code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import os, sys
import numpy as np
here = os.path.abspath(os.path.dirname(__file__))
CODE_SUB_DIR = os.path.abspath(os.path.join(here, "..", ".."))
print(CODE_SUB_DIR)
sys.path.append(CODE_SUB_DIR)
from at_speech import SLLRLiblinear, SLLRSag, ThinResnet34Classifier
from at_speech.data_space.raw_data_space import RawDataNpDb
from at_toolkit.at_sampler import AutoSamplerBasic, AutoSpSamplerNew, AutoValidSplitor, minisamples_edaer, sample_y_edaer
from at_speech.data_space.feats_data_space import FeatsDataDb
from at_speech.policy_space.decision_making import DecisionMaker
from at_toolkit.at_tfds_convertor import TfdsConvertor
from at_toolkit import AdlClassifier, AdlSpeechDMetadata
from at_toolkit.at_evalator import ATEvaluator
from at_speech.at_speech_cons import *
from at_speech.at_speech_config import TFDS2NP_TAKESIZE_RATION_LIST, TR34_TRAINPIP_WARMUP, IF_VAL_ON, Tr34SamplerHpParams
CLS_REG_TABLE = {
CLS_LR_LIBLINEAER: SLLRLiblinear,
CLS_LR_SAG: SLLRSag,
CLS_TR34: ThinResnet34Classifier,
}
CLS_2_FEATNAME_REG_TABLE = {
CLS_LR_LIBLINEAER: FEAT_KAPRE_MELSPECGRAM,
CLS_LR_SAG: FEAT_KAPRE_MELSPECGRAM,
CLS_TR34: FEAT_LBS_TR34,
}
class MetaClsHPParams:
lr_sag_cls_init_params = {"max_iter": 50}
class ModelExecutor:
def __init__(self, ds_metadata):
self.class_num = ds_metadata.get("class_num")
self.train_num = ds_metadata.get("train_num")
self.test_num = ds_metadata.get("test_num")
self.aspeech_metadata = AdlSpeechDMetadata(ds_metadata)
self.cls_tpye_libs = [CLS_LR_LIBLINEAER, CLS_LR_SAG, CLS_TR34]
self.lr_libl_cls = None
self.lr_sag_cls = None
self.tr34_cls = None
self.tr34_cls_train_pip_run = 0
self.tfds_convertor = TfdsConvertor()
self.feats_data_db = FeatsDataDb(self.train_num, self.test_num)
self.init_pipeline()
self.train_pip_id = 0
self.test_pip_id = 0
self.token_train_size = 0
self.cur_cls_ins_table = {
CLS_LR_LIBLINEAER: self.lr_libl_cls,
CLS_LR_SAG: self.lr_sag_cls,
CLS_TR34: self.tr34_cls,
}
self.decision_maker = DecisionMaker(self.aspeech_metadata)
self.cur_cls = None
self.cur_sampler = None
self.val_sample_idxs = list()
self.cur_val_examples_y = None
self.cur_val_nauc = None
self.cur_train_his_report = dict()
self.minis_eda_report = None
self.is_multilabel = False
self.lr_sampler = AutoSamplerBasic(self.class_num)
self.tr34_sampler = AutoSpSamplerNew(None)
self.val_splitor = AutoValidSplitor(self.class_num)
self.cur_sampler_table = {
CLS_LR_LIBLINEAER: self.lr_sampler,
CLS_LR_SAG: self.lr_sampler,
CLS_TR34: self.tr34_sampler,
}
self.tfds2np_take_size_array = TFDS2NP_TAKESIZE_RATION_LIST
self.tfds2np_takesize_flag = False
self.decision_maker.infer_model_select_def()
self.tr34_trainpip_warmup = self.decision_maker.infer_tr34_trainpip_warmup()
self.tr34_hps_epochs_dict = self.decision_maker.infer_tr34_hps_epoch()
self.tr34_hps_sample_dict = self.decision_maker.infer_tr34_hps_samplenum()
def init_pipeline(self):
self.lr_libl_cls = SLLRLiblinear()
self.lr_libl_cls.init(self.class_num)
self.lr_sag_cls = SLLRSag()
self.lr_sag_cls.init(self.class_num, MetaClsHPParams.lr_sag_cls_init_params)
self.tr34_cls = ThinResnet34Classifier()
self.tr34_cls.init(self.class_num)
def train_pipeline(self, train_tfds, update_train_data=True):
if self.train_pip_id < len(self.tfds2np_take_size_array):
if self.train_pip_id == 1:
take_train_size = max(200, int(self.tfds2np_take_size_array[self.train_pip_id] * self.train_num))
else:
take_train_size = int(self.tfds2np_take_size_array[self.train_pip_id] * self.train_num)
else:
take_train_size = 200
self.token_train_size += take_train_size
self.cur_train_his_report = dict()
self.tfds_convertor.init_train_tfds(train_tfds, self.train_num)
if update_train_data is True and self.feats_data_db.raw_data_db.raw_train_np_filled_num < self.train_num:
accm_raw_train_np_dict = self.tfds_convertor.get_train_np_accm(take_train_size)
self.minis_eda_report = minisamples_edaer(accm_raw_train_np_dict["x"], accm_raw_train_np_dict["y"])
if self.minis_eda_report.get("y_cover_rate") <= 0.5:
self.tfds_convertor.init_train_tfds(train_tfds, self.train_num, force_shuffle=True)
accm_raw_train_np_dict = self.tfds_convertor.get_train_np_accm(take_train_size)
self.minis_eda_report = minisamples_edaer(accm_raw_train_np_dict["x"], accm_raw_train_np_dict["y"])
self.is_multilabel = self.minis_eda_report.get("is_multilabel")
self.tr34_cls.renew_if_multilabel(self.is_multilabel)
if self.tfds2np_takesize_flag is False:
self.decision_maker.learn_train_minisamples_report(self.minis_eda_report)
self.tfds2np_take_size_array = self.decision_maker.decide_tfds2np_array()
self.tfds2np_takesize_flag = True
self.feats_data_db.raw_data_db.put_raw_train_np(accm_raw_train_np_dict["x"], accm_raw_train_np_dict["y"])
if_split_val = self.decision_maker.decide_if_split_val(self.token_train_size)
if IF_VAL_ON and if_split_val and len(self.val_sample_idxs) == 0:
val_mode = "bal"
val_num = self.decision_maker.decide_g_valid_num()
self.val_sample_idxs = self.val_splitor.get_valid_sample_idxs(
np.stack(self.feats_data_db.raw_data_db.raw_train_y_np_table_filled), val_num=val_num, mode=val_mode
)
self.feats_data_db.raw_data_db.put_split_valid_np(self.val_sample_idxs)
self.cur_val_examples_y = self.feats_data_db.get_raw_train_y(self.val_sample_idxs)
self.cur_cls_name = self.decision_maker.decide_model_select(self.train_pip_id)
self.cur_cls = self.cur_cls_ins_table.get(self.cur_cls_name)
self.cur_sampler = self.cur_sampler_table.get(self.cur_cls_name)
if self.cur_cls_name in [CLS_LR_LIBLINEAER, CLS_LR_SAG]:
if self.is_multilabel is False:
self.lr_sampler.init_train_y(self.feats_data_db.raw_data_db.raw_train_y_np_table_filled)
class_inverted_index_array = self.lr_sampler.init_each_class_index_by_y(self.lr_sampler.train_y)
cur_train_sample_idxs = self.lr_sampler.init_even_class_index_by_each(class_inverted_index_array)
cur_train_sample_idxs = [item for sublist in cur_train_sample_idxs for item in sublist]
cur_train_sample_idxs = [i for i in cur_train_sample_idxs if i not in self.val_sample_idxs]
else:
cur_train_sample_idxs = range(len(self.feats_data_db.raw_data_db.raw_train_y_np_table_filled))
self.cur_feat_name = CLS_2_FEATNAME_REG_TABLE.get(self.cur_cls_name)
self.use_feat_params = {"len_sample": 5, "sr": 16000}
cur_train_examples_x = self.feats_data_db.get_raw_train_feats(
self.cur_feat_name, cur_train_sample_idxs, self.use_feat_params
)
cur_train_examples_y = self.feats_data_db.get_raw_train_y(cur_train_sample_idxs)
train_eda_report = sample_y_edaer(cur_train_examples_y)
if self.cur_cls_name == CLS_LR_LIBLINEAER:
assert isinstance(self.cur_cls, SLLRLiblinear), "Error cur_cls is not {}".format(SLLRLiblinear.__name__)
self.cur_cls.offline_fit(cur_train_examples_x, cur_train_examples_y, fit_params={"if_multilabel": self.is_multilabel})
elif self.cur_cls_name == CLS_LR_SAG:
assert isinstance(self.cur_cls, SLLRSag), "Error cur_cls is not {}".format(SLLRSag.__name__)
self.cur_cls.offline_fit(cur_train_examples_x, cur_train_examples_y, fit_params={"if_multilabel": self.is_multilabel})
elif self.cur_cls_name in [CLS_TR34]:
assert isinstance(self.cur_cls, ThinResnet34Classifier), "Error, cls select is {}".format(
type(self.cur_cls)
)
train_use_y_labels = np.stack(self.feats_data_db.raw_data_db.raw_train_y_np_table_filled)
self.tr34_sampler = AutoSpSamplerNew(y_train_labels=train_use_y_labels)
if self.is_multilabel is False:
self.tr34_sampler.set_up()
cur_train_sample_idxs = self.tr34_sampler.get_downsample_index_list_by_class(
per_class_num=Tr34SamplerHpParams.SAMPL_PA_F_PERC_NUM,
max_sample_num=self.tr34_hps_sample_dict.get("SAMP_MAX_NUM"),
min_sample_num=self.tr34_hps_sample_dict.get("SAMP_MIN_NUM"),
)
else:
cur_train_sample_idxs = self.tr34_sampler.get_downsample_index_list_by_random(
max_sample_num=self.tr34_hps_sample_dict.get("SAMP_MAX_NUM"),
min_sample_num=self.tr34_hps_sample_dict.get("SAMP_MIN_NUM"))
cur_train_sample_idxs = [i for i in cur_train_sample_idxs if i not in self.val_sample_idxs]
self.cur_feat_name = CLS_2_FEATNAME_REG_TABLE.get(self.cur_cls_name)
if_train_feats_force = self.cur_cls.decide_if_renew_trainfeats()
self.use_feat_params = self.cur_cls.imp_feat_args
cur_train_examples_x = self.feats_data_db.get_raw_train_feats(
self.cur_feat_name, cur_train_sample_idxs, self.use_feat_params, if_train_feats_force
)
cur_train_examples_y = self.feats_data_db.get_raw_train_y(cur_train_sample_idxs)
train_eda_report = sample_y_edaer(cur_train_examples_y)
self.tr34_cls_train_pip_run += 1
self.cur_train_his_report = self.cur_cls.online_fit(cur_train_examples_x, cur_train_examples_y, fit_params=self.tr34_hps_epochs_dict)
if len(self.val_sample_idxs) > 0:
if self.cur_cls_name == CLS_TR34:
assert isinstance(self.cur_cls, ThinResnet34Classifier)
if_force_val_feats = self.cur_cls.decide_if_renew_valfeats()
use_feat_params = self.cur_cls.imp_feat_args
cur_val_examples_x = self.feats_data_db.get_split_val_feats(
self.cur_feat_name, self.val_sample_idxs, use_feat_params, if_force_val_feats
)
cur_val_examples_x = np.array(cur_val_examples_x)
cur_val_examples_x = cur_val_examples_x[:, :, :, np.newaxis]
cur_val_preds = self.cur_cls.predict_val_proba(cur_val_examples_x)
else:
cur_val_examples_x = self.feats_data_db.get_split_val_feats(self.cur_feat_name, self.val_sample_idxs, self.use_feat_params)
cur_val_preds = self.cur_cls.predict_proba(cur_val_examples_x, predict_prob_params={"if_multilabel": self.is_multilabel})
self.cur_val_nauc = ATEvaluator.autodl_auc(solution=self.cur_val_examples_y, prediction=cur_val_preds)
else:
self.cur_val_nauc = -1
self.train_pip_id += 1
self.cur_train_his_report["val_nauc"] = self.cur_val_nauc
self.cur_train_his_report["cls_name"] = self.cur_cls_name
return self.cur_train_his_report.copy()
def test_pipeline(self, test_tfds):
self.tfds_convertor.init_test_tfds(test_tfds)
if not self.feats_data_db.raw_data_db.if_raw_test_2_np_done:
raw_test_np = self.tfds_convertor.get_test_np()
assert isinstance(raw_test_np, list), "raw_test_np is not list"
self.feats_data_db.raw_data_db.put_raw_test_np(raw_test_np)
if self.cur_cls_name in [CLS_LR_LIBLINEAER, CLS_LR_SAG]:
use_feat_params = {"len_sample": 5, "sr": 16000}
cur_test_examples_x = self.feats_data_db.get_raw_test_feats(self.cur_feat_name, use_feat_params)
assert isinstance(self.cur_cls, AdlClassifier)
cur_test_preds = self.cur_cls.predict_proba(cur_test_examples_x, predict_prob_params={"if_multilabel": self.is_multilabel})
self.test_pip_id += 1
return np.array(cur_test_preds)
if self.cur_cls_name in [CLS_TR34]:
while self.tr34_cls_train_pip_run < self.tr34_trainpip_warmup:
self.train_pipeline(train_tfds=None, update_train_data=False)
assert isinstance(self.cur_cls, ThinResnet34Classifier), "Error, cur_cls type error."
if_force_test_feats = self.cur_cls.decide_if_renew_testfeats()
use_feat_params = self.cur_cls.imp_feat_args
cur_test_examples_x = self.feats_data_db.get_raw_test_feats(
self.cur_feat_name, use_feat_params, if_force_test_feats
)
cur_test_examples_x = np.asarray(cur_test_examples_x)
cur_test_examples_x = cur_test_examples_x[:, :, :, np.newaxis]
assert isinstance(self.cur_cls, AdlClassifier)
cur_test_preds = self.cur_cls.predict_proba(cur_test_examples_x)
del cur_test_examples_x
self.test_pip_id += 1
return cur_test_preds | AutoDL_sample_code_submission/at_speech/policy_space/model_executor.py | import os, sys
import numpy as np
here = os.path.abspath(os.path.dirname(__file__))
CODE_SUB_DIR = os.path.abspath(os.path.join(here, "..", ".."))
print(CODE_SUB_DIR)
sys.path.append(CODE_SUB_DIR)
from at_speech import SLLRLiblinear, SLLRSag, ThinResnet34Classifier
from at_speech.data_space.raw_data_space import RawDataNpDb
from at_toolkit.at_sampler import AutoSamplerBasic, AutoSpSamplerNew, AutoValidSplitor, minisamples_edaer, sample_y_edaer
from at_speech.data_space.feats_data_space import FeatsDataDb
from at_speech.policy_space.decision_making import DecisionMaker
from at_toolkit.at_tfds_convertor import TfdsConvertor
from at_toolkit import AdlClassifier, AdlSpeechDMetadata
from at_toolkit.at_evalator import ATEvaluator
from at_speech.at_speech_cons import *
from at_speech.at_speech_config import TFDS2NP_TAKESIZE_RATION_LIST, TR34_TRAINPIP_WARMUP, IF_VAL_ON, Tr34SamplerHpParams
CLS_REG_TABLE = {
CLS_LR_LIBLINEAER: SLLRLiblinear,
CLS_LR_SAG: SLLRSag,
CLS_TR34: ThinResnet34Classifier,
}
CLS_2_FEATNAME_REG_TABLE = {
CLS_LR_LIBLINEAER: FEAT_KAPRE_MELSPECGRAM,
CLS_LR_SAG: FEAT_KAPRE_MELSPECGRAM,
CLS_TR34: FEAT_LBS_TR34,
}
class MetaClsHPParams:
lr_sag_cls_init_params = {"max_iter": 50}
class ModelExecutor:
def __init__(self, ds_metadata):
self.class_num = ds_metadata.get("class_num")
self.train_num = ds_metadata.get("train_num")
self.test_num = ds_metadata.get("test_num")
self.aspeech_metadata = AdlSpeechDMetadata(ds_metadata)
self.cls_tpye_libs = [CLS_LR_LIBLINEAER, CLS_LR_SAG, CLS_TR34]
self.lr_libl_cls = None
self.lr_sag_cls = None
self.tr34_cls = None
self.tr34_cls_train_pip_run = 0
self.tfds_convertor = TfdsConvertor()
self.feats_data_db = FeatsDataDb(self.train_num, self.test_num)
self.init_pipeline()
self.train_pip_id = 0
self.test_pip_id = 0
self.token_train_size = 0
self.cur_cls_ins_table = {
CLS_LR_LIBLINEAER: self.lr_libl_cls,
CLS_LR_SAG: self.lr_sag_cls,
CLS_TR34: self.tr34_cls,
}
self.decision_maker = DecisionMaker(self.aspeech_metadata)
self.cur_cls = None
self.cur_sampler = None
self.val_sample_idxs = list()
self.cur_val_examples_y = None
self.cur_val_nauc = None
self.cur_train_his_report = dict()
self.minis_eda_report = None
self.is_multilabel = False
self.lr_sampler = AutoSamplerBasic(self.class_num)
self.tr34_sampler = AutoSpSamplerNew(None)
self.val_splitor = AutoValidSplitor(self.class_num)
self.cur_sampler_table = {
CLS_LR_LIBLINEAER: self.lr_sampler,
CLS_LR_SAG: self.lr_sampler,
CLS_TR34: self.tr34_sampler,
}
self.tfds2np_take_size_array = TFDS2NP_TAKESIZE_RATION_LIST
self.tfds2np_takesize_flag = False
self.decision_maker.infer_model_select_def()
self.tr34_trainpip_warmup = self.decision_maker.infer_tr34_trainpip_warmup()
self.tr34_hps_epochs_dict = self.decision_maker.infer_tr34_hps_epoch()
self.tr34_hps_sample_dict = self.decision_maker.infer_tr34_hps_samplenum()
def init_pipeline(self):
self.lr_libl_cls = SLLRLiblinear()
self.lr_libl_cls.init(self.class_num)
self.lr_sag_cls = SLLRSag()
self.lr_sag_cls.init(self.class_num, MetaClsHPParams.lr_sag_cls_init_params)
self.tr34_cls = ThinResnet34Classifier()
self.tr34_cls.init(self.class_num)
def train_pipeline(self, train_tfds, update_train_data=True):
if self.train_pip_id < len(self.tfds2np_take_size_array):
if self.train_pip_id == 1:
take_train_size = max(200, int(self.tfds2np_take_size_array[self.train_pip_id] * self.train_num))
else:
take_train_size = int(self.tfds2np_take_size_array[self.train_pip_id] * self.train_num)
else:
take_train_size = 200
self.token_train_size += take_train_size
self.cur_train_his_report = dict()
self.tfds_convertor.init_train_tfds(train_tfds, self.train_num)
if update_train_data is True and self.feats_data_db.raw_data_db.raw_train_np_filled_num < self.train_num:
accm_raw_train_np_dict = self.tfds_convertor.get_train_np_accm(take_train_size)
self.minis_eda_report = minisamples_edaer(accm_raw_train_np_dict["x"], accm_raw_train_np_dict["y"])
if self.minis_eda_report.get("y_cover_rate") <= 0.5:
self.tfds_convertor.init_train_tfds(train_tfds, self.train_num, force_shuffle=True)
accm_raw_train_np_dict = self.tfds_convertor.get_train_np_accm(take_train_size)
self.minis_eda_report = minisamples_edaer(accm_raw_train_np_dict["x"], accm_raw_train_np_dict["y"])
self.is_multilabel = self.minis_eda_report.get("is_multilabel")
self.tr34_cls.renew_if_multilabel(self.is_multilabel)
if self.tfds2np_takesize_flag is False:
self.decision_maker.learn_train_minisamples_report(self.minis_eda_report)
self.tfds2np_take_size_array = self.decision_maker.decide_tfds2np_array()
self.tfds2np_takesize_flag = True
self.feats_data_db.raw_data_db.put_raw_train_np(accm_raw_train_np_dict["x"], accm_raw_train_np_dict["y"])
if_split_val = self.decision_maker.decide_if_split_val(self.token_train_size)
if IF_VAL_ON and if_split_val and len(self.val_sample_idxs) == 0:
val_mode = "bal"
val_num = self.decision_maker.decide_g_valid_num()
self.val_sample_idxs = self.val_splitor.get_valid_sample_idxs(
np.stack(self.feats_data_db.raw_data_db.raw_train_y_np_table_filled), val_num=val_num, mode=val_mode
)
self.feats_data_db.raw_data_db.put_split_valid_np(self.val_sample_idxs)
self.cur_val_examples_y = self.feats_data_db.get_raw_train_y(self.val_sample_idxs)
self.cur_cls_name = self.decision_maker.decide_model_select(self.train_pip_id)
self.cur_cls = self.cur_cls_ins_table.get(self.cur_cls_name)
self.cur_sampler = self.cur_sampler_table.get(self.cur_cls_name)
if self.cur_cls_name in [CLS_LR_LIBLINEAER, CLS_LR_SAG]:
if self.is_multilabel is False:
self.lr_sampler.init_train_y(self.feats_data_db.raw_data_db.raw_train_y_np_table_filled)
class_inverted_index_array = self.lr_sampler.init_each_class_index_by_y(self.lr_sampler.train_y)
cur_train_sample_idxs = self.lr_sampler.init_even_class_index_by_each(class_inverted_index_array)
cur_train_sample_idxs = [item for sublist in cur_train_sample_idxs for item in sublist]
cur_train_sample_idxs = [i for i in cur_train_sample_idxs if i not in self.val_sample_idxs]
else:
cur_train_sample_idxs = range(len(self.feats_data_db.raw_data_db.raw_train_y_np_table_filled))
self.cur_feat_name = CLS_2_FEATNAME_REG_TABLE.get(self.cur_cls_name)
self.use_feat_params = {"len_sample": 5, "sr": 16000}
cur_train_examples_x = self.feats_data_db.get_raw_train_feats(
self.cur_feat_name, cur_train_sample_idxs, self.use_feat_params
)
cur_train_examples_y = self.feats_data_db.get_raw_train_y(cur_train_sample_idxs)
train_eda_report = sample_y_edaer(cur_train_examples_y)
if self.cur_cls_name == CLS_LR_LIBLINEAER:
assert isinstance(self.cur_cls, SLLRLiblinear), "Error cur_cls is not {}".format(SLLRLiblinear.__name__)
self.cur_cls.offline_fit(cur_train_examples_x, cur_train_examples_y, fit_params={"if_multilabel": self.is_multilabel})
elif self.cur_cls_name == CLS_LR_SAG:
assert isinstance(self.cur_cls, SLLRSag), "Error cur_cls is not {}".format(SLLRSag.__name__)
self.cur_cls.offline_fit(cur_train_examples_x, cur_train_examples_y, fit_params={"if_multilabel": self.is_multilabel})
elif self.cur_cls_name in [CLS_TR34]:
assert isinstance(self.cur_cls, ThinResnet34Classifier), "Error, cls select is {}".format(
type(self.cur_cls)
)
train_use_y_labels = np.stack(self.feats_data_db.raw_data_db.raw_train_y_np_table_filled)
self.tr34_sampler = AutoSpSamplerNew(y_train_labels=train_use_y_labels)
if self.is_multilabel is False:
self.tr34_sampler.set_up()
cur_train_sample_idxs = self.tr34_sampler.get_downsample_index_list_by_class(
per_class_num=Tr34SamplerHpParams.SAMPL_PA_F_PERC_NUM,
max_sample_num=self.tr34_hps_sample_dict.get("SAMP_MAX_NUM"),
min_sample_num=self.tr34_hps_sample_dict.get("SAMP_MIN_NUM"),
)
else:
cur_train_sample_idxs = self.tr34_sampler.get_downsample_index_list_by_random(
max_sample_num=self.tr34_hps_sample_dict.get("SAMP_MAX_NUM"),
min_sample_num=self.tr34_hps_sample_dict.get("SAMP_MIN_NUM"))
cur_train_sample_idxs = [i for i in cur_train_sample_idxs if i not in self.val_sample_idxs]
self.cur_feat_name = CLS_2_FEATNAME_REG_TABLE.get(self.cur_cls_name)
if_train_feats_force = self.cur_cls.decide_if_renew_trainfeats()
self.use_feat_params = self.cur_cls.imp_feat_args
cur_train_examples_x = self.feats_data_db.get_raw_train_feats(
self.cur_feat_name, cur_train_sample_idxs, self.use_feat_params, if_train_feats_force
)
cur_train_examples_y = self.feats_data_db.get_raw_train_y(cur_train_sample_idxs)
train_eda_report = sample_y_edaer(cur_train_examples_y)
self.tr34_cls_train_pip_run += 1
self.cur_train_his_report = self.cur_cls.online_fit(cur_train_examples_x, cur_train_examples_y, fit_params=self.tr34_hps_epochs_dict)
if len(self.val_sample_idxs) > 0:
if self.cur_cls_name == CLS_TR34:
assert isinstance(self.cur_cls, ThinResnet34Classifier)
if_force_val_feats = self.cur_cls.decide_if_renew_valfeats()
use_feat_params = self.cur_cls.imp_feat_args
cur_val_examples_x = self.feats_data_db.get_split_val_feats(
self.cur_feat_name, self.val_sample_idxs, use_feat_params, if_force_val_feats
)
cur_val_examples_x = np.array(cur_val_examples_x)
cur_val_examples_x = cur_val_examples_x[:, :, :, np.newaxis]
cur_val_preds = self.cur_cls.predict_val_proba(cur_val_examples_x)
else:
cur_val_examples_x = self.feats_data_db.get_split_val_feats(self.cur_feat_name, self.val_sample_idxs, self.use_feat_params)
cur_val_preds = self.cur_cls.predict_proba(cur_val_examples_x, predict_prob_params={"if_multilabel": self.is_multilabel})
self.cur_val_nauc = ATEvaluator.autodl_auc(solution=self.cur_val_examples_y, prediction=cur_val_preds)
else:
self.cur_val_nauc = -1
self.train_pip_id += 1
self.cur_train_his_report["val_nauc"] = self.cur_val_nauc
self.cur_train_his_report["cls_name"] = self.cur_cls_name
return self.cur_train_his_report.copy()
def test_pipeline(self, test_tfds):
self.tfds_convertor.init_test_tfds(test_tfds)
if not self.feats_data_db.raw_data_db.if_raw_test_2_np_done:
raw_test_np = self.tfds_convertor.get_test_np()
assert isinstance(raw_test_np, list), "raw_test_np is not list"
self.feats_data_db.raw_data_db.put_raw_test_np(raw_test_np)
if self.cur_cls_name in [CLS_LR_LIBLINEAER, CLS_LR_SAG]:
use_feat_params = {"len_sample": 5, "sr": 16000}
cur_test_examples_x = self.feats_data_db.get_raw_test_feats(self.cur_feat_name, use_feat_params)
assert isinstance(self.cur_cls, AdlClassifier)
cur_test_preds = self.cur_cls.predict_proba(cur_test_examples_x, predict_prob_params={"if_multilabel": self.is_multilabel})
self.test_pip_id += 1
return np.array(cur_test_preds)
if self.cur_cls_name in [CLS_TR34]:
while self.tr34_cls_train_pip_run < self.tr34_trainpip_warmup:
self.train_pipeline(train_tfds=None, update_train_data=False)
assert isinstance(self.cur_cls, ThinResnet34Classifier), "Error, cur_cls type error."
if_force_test_feats = self.cur_cls.decide_if_renew_testfeats()
use_feat_params = self.cur_cls.imp_feat_args
cur_test_examples_x = self.feats_data_db.get_raw_test_feats(
self.cur_feat_name, use_feat_params, if_force_test_feats
)
cur_test_examples_x = np.asarray(cur_test_examples_x)
cur_test_examples_x = cur_test_examples_x[:, :, :, np.newaxis]
assert isinstance(self.cur_cls, AdlClassifier)
cur_test_preds = self.cur_cls.predict_proba(cur_test_examples_x)
del cur_test_examples_x
self.test_pip_id += 1
return cur_test_preds | 0.217338 | 0.127029 |
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..configuration import Configuration
from ..api_client import ApiClient
class V3utilsApi(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not config.api_client:
config.api_client = ApiClient()
self.api_client = config.api_client
def check_client_version_v3(self, version, **kwargs):
"""
checks the client version
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.check_client_version_v3(version, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str version: (required)
:return: VersionCheckResult
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.check_client_version_v3_with_http_info(version, **kwargs)
else:
(data) = self.check_client_version_v3_with_http_info(version, **kwargs)
return data
def check_client_version_v3_with_http_info(self, version, **kwargs):
"""
checks the client version
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.check_client_version_v3_with_http_info(version, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str version: (required)
:return: VersionCheckResult
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['version']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
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 check_client_version_v3" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'version' is set
if ('version' not in params) or (params['version'] is None):
raise ValueError("Missing the required parameter `version` when calling `check_client_version_v3`")
collection_formats = {}
path_params = {}
if 'version' in params:
path_params['version'] = params['version']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/v3/utils/client/{version}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VersionCheckResult',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_rds_database_util_v3(self, **kwargs):
"""
create a database for the service in the RDS if the connection could be created
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_rds_database_util_v3(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param RDSBuildRequest body:
:param list[str] target:
:return: RdsBuildResult
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.create_rds_database_util_v3_with_http_info(**kwargs)
else:
(data) = self.create_rds_database_util_v3_with_http_info(**kwargs)
return data
def create_rds_database_util_v3_with_http_info(self, **kwargs):
"""
create a database for the service in the RDS if the connection could be created
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_rds_database_util_v3_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param RDSBuildRequest body:
:param list[str] target:
:return: RdsBuildResult
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'target']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
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_rds_database_util_v3" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'target' in params:
query_params.append(('target', params['target']))
collection_formats['target'] = 'multi'
header_params = {}
form_params = []
local_var_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'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/v3/utils/rds-database', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='RdsBuildResult',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_cloud_storage_matrix_v3(self, **kwargs):
"""
returns supported cloud storage for stack version
Define stack version at least at patch level eg. 2.6.0
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.get_cloud_storage_matrix_v3(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str stack_version:
:return: list[CloudStorageSupportedResponse]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_cloud_storage_matrix_v3_with_http_info(**kwargs)
else:
(data) = self.get_cloud_storage_matrix_v3_with_http_info(**kwargs)
return data
def get_cloud_storage_matrix_v3_with_http_info(self, **kwargs):
"""
returns supported cloud storage for stack version
Define stack version at least at patch level eg. 2.6.0
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.get_cloud_storage_matrix_v3_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str stack_version:
:return: list[CloudStorageSupportedResponse]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['stack_version']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
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 get_cloud_storage_matrix_v3" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'stack_version' in params:
query_params.append(('stackVersion', params['stack_version']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/v3/utils/cloudstoragematrix', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[CloudStorageSupportedResponse]',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_stack_matrix_util_v3(self, **kwargs):
"""
returns default ambari details for distinct HDP and HDF
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.get_stack_matrix_util_v3(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: StackMatrix
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_stack_matrix_util_v3_with_http_info(**kwargs)
else:
(data) = self.get_stack_matrix_util_v3_with_http_info(**kwargs)
return data
def get_stack_matrix_util_v3_with_http_info(self, **kwargs):
"""
returns default ambari details for distinct HDP and HDF
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.get_stack_matrix_util_v3_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: StackMatrix
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
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 get_stack_matrix_util_v3" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/v3/utils/stackmatrix', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='StackMatrix',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats) | whoville/cloudbreak/apis/v3utils_api.py | from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..configuration import Configuration
from ..api_client import ApiClient
class V3utilsApi(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not config.api_client:
config.api_client = ApiClient()
self.api_client = config.api_client
def check_client_version_v3(self, version, **kwargs):
"""
checks the client version
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.check_client_version_v3(version, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str version: (required)
:return: VersionCheckResult
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.check_client_version_v3_with_http_info(version, **kwargs)
else:
(data) = self.check_client_version_v3_with_http_info(version, **kwargs)
return data
def check_client_version_v3_with_http_info(self, version, **kwargs):
"""
checks the client version
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.check_client_version_v3_with_http_info(version, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str version: (required)
:return: VersionCheckResult
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['version']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
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 check_client_version_v3" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'version' is set
if ('version' not in params) or (params['version'] is None):
raise ValueError("Missing the required parameter `version` when calling `check_client_version_v3`")
collection_formats = {}
path_params = {}
if 'version' in params:
path_params['version'] = params['version']
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/v3/utils/client/{version}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VersionCheckResult',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_rds_database_util_v3(self, **kwargs):
"""
create a database for the service in the RDS if the connection could be created
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_rds_database_util_v3(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param RDSBuildRequest body:
:param list[str] target:
:return: RdsBuildResult
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.create_rds_database_util_v3_with_http_info(**kwargs)
else:
(data) = self.create_rds_database_util_v3_with_http_info(**kwargs)
return data
def create_rds_database_util_v3_with_http_info(self, **kwargs):
"""
create a database for the service in the RDS if the connection could be created
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_rds_database_util_v3_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param RDSBuildRequest body:
:param list[str] target:
:return: RdsBuildResult
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'target']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
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_rds_database_util_v3" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'target' in params:
query_params.append(('target', params['target']))
collection_formats['target'] = 'multi'
header_params = {}
form_params = []
local_var_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'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/v3/utils/rds-database', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='RdsBuildResult',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_cloud_storage_matrix_v3(self, **kwargs):
"""
returns supported cloud storage for stack version
Define stack version at least at patch level eg. 2.6.0
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.get_cloud_storage_matrix_v3(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str stack_version:
:return: list[CloudStorageSupportedResponse]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_cloud_storage_matrix_v3_with_http_info(**kwargs)
else:
(data) = self.get_cloud_storage_matrix_v3_with_http_info(**kwargs)
return data
def get_cloud_storage_matrix_v3_with_http_info(self, **kwargs):
"""
returns supported cloud storage for stack version
Define stack version at least at patch level eg. 2.6.0
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.get_cloud_storage_matrix_v3_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str stack_version:
:return: list[CloudStorageSupportedResponse]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['stack_version']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
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 get_cloud_storage_matrix_v3" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'stack_version' in params:
query_params.append(('stackVersion', params['stack_version']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/v3/utils/cloudstoragematrix', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[CloudStorageSupportedResponse]',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_stack_matrix_util_v3(self, **kwargs):
"""
returns default ambari details for distinct HDP and HDF
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.get_stack_matrix_util_v3(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: StackMatrix
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_stack_matrix_util_v3_with_http_info(**kwargs)
else:
(data) = self.get_stack_matrix_util_v3_with_http_info(**kwargs)
return data
def get_stack_matrix_util_v3_with_http_info(self, **kwargs):
"""
returns default ambari details for distinct HDP and HDF
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.get_stack_matrix_util_v3_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: StackMatrix
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
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 get_stack_matrix_util_v3" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/v3/utils/stackmatrix', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='StackMatrix',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats) | 0.601711 | 0.07221 |
# Step1: preprocess_data.py
import os
file_input_data = '../../umap_dataset/data/whole_annotation_data_336_modified_taxonomy.json'
content_features = 1
structural_features = 1
sentiment_features = 1
conversational_features = 1
feature_normalization = 0
model_name = 'cnn_base'
max_sequence_length = 50
max_num_vocabulary = 20000
embedding_selection = 'glove' # embed
embedding_dimension = [50, 100, 200] # embed_dim
convolutional_units = [128, 256, 512,1024] # conv_units
conv_stride_size = [2,3] # stride
conv_pooling_size = [2,3] # pool
conv_dropout_rate = [0.0, 0.2, 0.4, 0.6] # dropout
dense_units = [128,256] # dense_units
cross_validation = 3
script = 'python Main.py '
script += '--file_input_data %s ' % file_input_data
script += '--content_features %s ' % content_features
script += '--structural_features %s ' % structural_features
script += '--sentiment_features %s ' % sentiment_features
script += '--conversational_features %s ' % conversational_features
script += '--feature_normalization %s ' % feature_normalization
script += '--model_name %s ' % model_name
script += '--cross_validation %s ' % cross_validation
# model configuration
model_config = '--max_sequence_length %d --max_num_vocabulary %d --embedding_selection %s ' % \
(max_sequence_length,max_num_vocabulary, embedding_selection)
for embed_dim in embedding_dimension:
model_config_embed_dim = '--embedding_dimension %d ' % embed_dim
model_para_conv_unit = ''
model_para_stride_pool = ''
model_para_dropout = ''
model_para_dense = ''
for conv_units in convolutional_units:
model_para_conv_unit = '--convolutional_units %d ' % conv_units
for stride_size in conv_stride_size:
model_para_stride_pool = '--conv_stride_size %d --conv_pooling_size %d ' % (stride_size, stride_size)
for dropout_rate in conv_dropout_rate:
model_para_dropout = '--conv_dropout_rate %f ' % dropout_rate
for den_units in dense_units:
model_para_dense = '--dense_units %d ' % den_units
result_script = '> result/%s_content_%d_structural_%d_sentiment_%d_conversational_%d_feat_normalization_%d_embed_%s_embed_dim_%d_conv_units_%d_stride_%d_pool_%d_dropout_%.1f_dense_units_%d.txt' \
% (model_name, content_features,structural_features, sentiment_features,conversational_features, feature_normalization,embedding_selection,embed_dim, conv_units,stride_size, stride_size,dropout_rate, den_units)
result_script = '> result/%s_%d_%d_%d_%d_%d_embed_%s_%d_conv_units_%d_%d_%d_%.1f_dense_units_%d.txt' \
% (model_name, content_features,structural_features, sentiment_features,conversational_features, feature_normalization,embedding_selection,embed_dim, conv_units,stride_size, stride_size,dropout_rate, den_units)
s = script + model_config + model_config_embed_dim + model_para_conv_unit + model_para_stride_pool + model_para_dropout+ model_para_dense + result_script
print(s)
# os.system(s) | user_intent_prediction/model_cnn_base/script_cnn_base.py |
# Step1: preprocess_data.py
import os
file_input_data = '../../umap_dataset/data/whole_annotation_data_336_modified_taxonomy.json'
content_features = 1
structural_features = 1
sentiment_features = 1
conversational_features = 1
feature_normalization = 0
model_name = 'cnn_base'
max_sequence_length = 50
max_num_vocabulary = 20000
embedding_selection = 'glove' # embed
embedding_dimension = [50, 100, 200] # embed_dim
convolutional_units = [128, 256, 512,1024] # conv_units
conv_stride_size = [2,3] # stride
conv_pooling_size = [2,3] # pool
conv_dropout_rate = [0.0, 0.2, 0.4, 0.6] # dropout
dense_units = [128,256] # dense_units
cross_validation = 3
script = 'python Main.py '
script += '--file_input_data %s ' % file_input_data
script += '--content_features %s ' % content_features
script += '--structural_features %s ' % structural_features
script += '--sentiment_features %s ' % sentiment_features
script += '--conversational_features %s ' % conversational_features
script += '--feature_normalization %s ' % feature_normalization
script += '--model_name %s ' % model_name
script += '--cross_validation %s ' % cross_validation
# model configuration
model_config = '--max_sequence_length %d --max_num_vocabulary %d --embedding_selection %s ' % \
(max_sequence_length,max_num_vocabulary, embedding_selection)
for embed_dim in embedding_dimension:
model_config_embed_dim = '--embedding_dimension %d ' % embed_dim
model_para_conv_unit = ''
model_para_stride_pool = ''
model_para_dropout = ''
model_para_dense = ''
for conv_units in convolutional_units:
model_para_conv_unit = '--convolutional_units %d ' % conv_units
for stride_size in conv_stride_size:
model_para_stride_pool = '--conv_stride_size %d --conv_pooling_size %d ' % (stride_size, stride_size)
for dropout_rate in conv_dropout_rate:
model_para_dropout = '--conv_dropout_rate %f ' % dropout_rate
for den_units in dense_units:
model_para_dense = '--dense_units %d ' % den_units
result_script = '> result/%s_content_%d_structural_%d_sentiment_%d_conversational_%d_feat_normalization_%d_embed_%s_embed_dim_%d_conv_units_%d_stride_%d_pool_%d_dropout_%.1f_dense_units_%d.txt' \
% (model_name, content_features,structural_features, sentiment_features,conversational_features, feature_normalization,embedding_selection,embed_dim, conv_units,stride_size, stride_size,dropout_rate, den_units)
result_script = '> result/%s_%d_%d_%d_%d_%d_embed_%s_%d_conv_units_%d_%d_%d_%.1f_dense_units_%d.txt' \
% (model_name, content_features,structural_features, sentiment_features,conversational_features, feature_normalization,embedding_selection,embed_dim, conv_units,stride_size, stride_size,dropout_rate, den_units)
s = script + model_config + model_config_embed_dim + model_para_conv_unit + model_para_stride_pool + model_para_dropout+ model_para_dense + result_script
print(s)
# os.system(s) | 0.5794 | 0.299086 |
import subprocess
import os
from spotdl.encode import EncoderBase
from spotdl.encode.exceptions import EncoderNotFoundError
from spotdl.encode.exceptions import FFmpegNotFoundError
import logging
logger = logging.getLogger(__name__)
# Key: from format
# Subkey: to format
RULES = {
"m4a": {
"mp3": "-codec:v copy -codec:a libmp3lame -ar 48000",
"opus": "-codec:a libopus -vbr on",
"m4a": "-acodec copy",
"flac": "-codec:a flac -ar 48000",
"ogg": "-codec:a libvorbis -ar 48000",
"opus": "-codec:a libopus -ar 48000",
},
"opus": {
"mp3": "-codec:a libmp3lame -ar 48000",
"m4a": "-cutoff 20000 -codec:a aac -ar 48000",
"flac": "-codec:a flac -ar 48000",
"ogg": "-codec:a libvorbis -ar 48000",
"opus": "-acodec copy",
},
}
class EncoderFFmpeg(EncoderBase):
def __init__(self, encoder_path="ffmpeg", must_exist=True):
_loglevel = "-hide_banner -nostats -v warning"
_additional_arguments = ["-b:a", "192k", "-vn"]
try:
super().__init__(encoder_path, must_exist, _loglevel, _additional_arguments)
except EncoderNotFoundError as e:
raise FFmpegNotFoundError(e.args[0])
self._rules = RULES
def set_trim_silence(self):
self.set_argument("-af silenceremove=start_periods=1")
def get_encoding(self, path):
return super().get_encoding(path)
def _generate_encoding_arguments(self, input_encoding, target_encoding):
initial_arguments = self._rules.get(input_encoding)
if initial_arguments is None:
raise TypeError(
'The input format ("{}") is not supported.'.format(
input_encoding,
))
arguments = initial_arguments.get(target_encoding)
if arguments is None:
raise TypeError(
'The output format ("{}") is not supported.'.format(
target_encoding,
))
return arguments
def set_debuglog(self):
self._loglevel = "-loglevel debug"
def _generate_encode_command(self, input_path, target_file,
input_encoding=None, target_encoding=None):
if input_encoding is None:
input_encoding = self.get_encoding(input_path)
if target_encoding is None:
target_encoding = self.get_encoding(target_file)
arguments = self._generate_encoding_arguments(
input_encoding,
target_encoding
)
command = [self.encoder_path] \
+ ["-y", "-nostdin"] \
+ self._loglevel.split() \
+ ["-i", input_path] \
+ arguments.split() \
+ self._additional_arguments \
+ ["-f", self.target_format_from_encoding(target_encoding)] \
+ [target_file]
return command
def re_encode(self, input_path, target_file, target_encoding=None, delete_original=False):
encode_command = self._generate_encode_command(
input_path,
target_file,
target_encoding=target_encoding
)
logger.debug("Calling FFmpeg with:\n{command}".format(
command=encode_command,
))
process = subprocess.Popen(encode_command)
process.wait()
encode_successful = process.returncode == 0
if encode_successful and delete_original:
os.remove(input_path)
return process
def re_encode_from_stdin(self, input_encoding, target_file, target_encoding=None):
encode_command = self._generate_encode_command(
"-",
target_file,
input_encoding=input_encoding,
target_encoding=target_encoding,
)
logger.debug("Calling FFmpeg with:\n{command}".format(
command=encode_command,
))
process = subprocess.Popen(encode_command, stdin=subprocess.PIPE)
return process | spotdl/encode/encoders/ffmpeg.py | import subprocess
import os
from spotdl.encode import EncoderBase
from spotdl.encode.exceptions import EncoderNotFoundError
from spotdl.encode.exceptions import FFmpegNotFoundError
import logging
logger = logging.getLogger(__name__)
# Key: from format
# Subkey: to format
RULES = {
"m4a": {
"mp3": "-codec:v copy -codec:a libmp3lame -ar 48000",
"opus": "-codec:a libopus -vbr on",
"m4a": "-acodec copy",
"flac": "-codec:a flac -ar 48000",
"ogg": "-codec:a libvorbis -ar 48000",
"opus": "-codec:a libopus -ar 48000",
},
"opus": {
"mp3": "-codec:a libmp3lame -ar 48000",
"m4a": "-cutoff 20000 -codec:a aac -ar 48000",
"flac": "-codec:a flac -ar 48000",
"ogg": "-codec:a libvorbis -ar 48000",
"opus": "-acodec copy",
},
}
class EncoderFFmpeg(EncoderBase):
def __init__(self, encoder_path="ffmpeg", must_exist=True):
_loglevel = "-hide_banner -nostats -v warning"
_additional_arguments = ["-b:a", "192k", "-vn"]
try:
super().__init__(encoder_path, must_exist, _loglevel, _additional_arguments)
except EncoderNotFoundError as e:
raise FFmpegNotFoundError(e.args[0])
self._rules = RULES
def set_trim_silence(self):
self.set_argument("-af silenceremove=start_periods=1")
def get_encoding(self, path):
return super().get_encoding(path)
def _generate_encoding_arguments(self, input_encoding, target_encoding):
initial_arguments = self._rules.get(input_encoding)
if initial_arguments is None:
raise TypeError(
'The input format ("{}") is not supported.'.format(
input_encoding,
))
arguments = initial_arguments.get(target_encoding)
if arguments is None:
raise TypeError(
'The output format ("{}") is not supported.'.format(
target_encoding,
))
return arguments
def set_debuglog(self):
self._loglevel = "-loglevel debug"
def _generate_encode_command(self, input_path, target_file,
input_encoding=None, target_encoding=None):
if input_encoding is None:
input_encoding = self.get_encoding(input_path)
if target_encoding is None:
target_encoding = self.get_encoding(target_file)
arguments = self._generate_encoding_arguments(
input_encoding,
target_encoding
)
command = [self.encoder_path] \
+ ["-y", "-nostdin"] \
+ self._loglevel.split() \
+ ["-i", input_path] \
+ arguments.split() \
+ self._additional_arguments \
+ ["-f", self.target_format_from_encoding(target_encoding)] \
+ [target_file]
return command
def re_encode(self, input_path, target_file, target_encoding=None, delete_original=False):
encode_command = self._generate_encode_command(
input_path,
target_file,
target_encoding=target_encoding
)
logger.debug("Calling FFmpeg with:\n{command}".format(
command=encode_command,
))
process = subprocess.Popen(encode_command)
process.wait()
encode_successful = process.returncode == 0
if encode_successful and delete_original:
os.remove(input_path)
return process
def re_encode_from_stdin(self, input_encoding, target_file, target_encoding=None):
encode_command = self._generate_encode_command(
"-",
target_file,
input_encoding=input_encoding,
target_encoding=target_encoding,
)
logger.debug("Calling FFmpeg with:\n{command}".format(
command=encode_command,
))
process = subprocess.Popen(encode_command, stdin=subprocess.PIPE)
return process | 0.428831 | 0.12787 |
from django.db.models import Q, F
from rest_framework import viewsets, serializers
from rest_framework.filters import SearchFilter
from rest_framework.response import Response
from rest_framework.views import APIView
from models import Recipe, Ingredient
def search_by_time_ingredients(ingredients, time, queryset):
# Time intervals for the search
TIME_CHOICES = [(-1, 30), (30, 60), (60, 120), (120, 240), (-1, 999999)]
'''
Helper function to search by available ingredients and time
'''
recipes = queryset
# Add valid substitutes to the ingredient list
subs = []
for i in ingredients:
for s in Ingredient.objects.get(pk=i).substitutes.all():
subs.append(s.pk)
ingredients = ingredients + subs
# Filter by ingredients
recipes = recipes.filter(ingredients__ingredient__in=ingredients)
if time:
time = int(time)
lower_time = TIME_CHOICES[time][0]
upper_time = TIME_CHOICES[time][1]
recipes = recipes.filter(
(Q(cook_time__gt=lower_time - F('prep_time')) &
Q(cook_time__lte=upper_time - F('prep_time'))) |
(Q(cook_time__isnull=True) & Q(prep_time__isnull=True))
)
# Weed out the recipes that require at least one
# ingredient not in the list that is not a substitute
for r in recipes:
for i in r.ingredients.all():
if i.ingredient.pk not in ingredients:
recipes = recipes.exclude(pk=r.pk)
break
return recipes
class IngredientSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField()
def get_name(self, obj):
return obj.name.strip().title()
class Meta:
model = Ingredient
depth = 1
exclude = ['description', 'substitutes']
class IngredientViewSet(viewsets.ModelViewSet):
"""
Default endpoints to view/search/create/modify/delete ingredients
"""
queryset = Ingredient.objects.all().order_by('name')
serializer_class = IngredientSerializer
paginate_by = None
filter_backends = (SearchFilter,)
search_fields = ('name', 'description', 'substitutes__name')
class RecipeSerializer(serializers.ModelSerializer):
image = serializers.SerializerMethodField()
def get_image(self, obj):
if obj.image:
from sorl.thumbnail import get_thumbnail
thumbnail_url = get_thumbnail(
obj.image, '500x500', crop='center', format='PNG'
).url
return self.context['request'].build_absolute_uri(thumbnail_url)
class Meta:
model = Recipe
depth = 2
class RecipeSearchSerializer(serializers.ModelSerializer):
thumbnail = serializers.SerializerMethodField()
def get_thumbnail(self, obj):
if obj.image:
from sorl.thumbnail import get_thumbnail
thumbnail_url = get_thumbnail(
obj.image, '200x200', crop='center', format='PNG'
).url
return self.context['request'].build_absolute_uri(thumbnail_url)
class Meta:
model = Recipe
depth = 2
exclude = ['description', 'ingredients', 'instructions', 'notes']
class RecipeViewSet(viewsets.ModelViewSet):
"""
Default endpoints to view/search/create/modify/delete recipes
"""
queryset = Recipe.objects.all()
serializer_class = RecipeSerializer
filter_backends = (SearchFilter,)
search_fields = ('name', 'description', 'time',
'categories__name',
'ingredients__ingredient__name',
)
class RecipeSearchIngTimeViewSet(APIView):
"""
Search by ingredients endpoint
"""
queryset = Recipe.objects.all()
serializer_class = RecipeSearchSerializer
def get(self, request, format=None):
# Get parameters
params = request.query_params
ingredients = [int(i) for i in params.getlist('ings')]
time = params.get('time')
recipes = search_by_time_ingredients(ingredients, time,
self.queryset)
return Response(self.serializer_class(
recipes, many=True, context={'request': request}
).data)
class RecipeRandomIngTimeViewSet(APIView):
"""
Search by ingredients endpoint
"""
queryset = Recipe.objects.all()
serializer_class = RecipeSearchSerializer
def get(self, request, format=None):
# Get parameters
params = request.query_params
ingredients = [int(i) for i in params.getlist('ings')]
time = params.get('time')
recipes = search_by_time_ingredients(ingredients, time,
self.queryset)
recipe = recipes.order_by('?').first()
return Response(self.serializer_class(
recipe, context={'request': request}
).data) | recipe-search/recipe/serializers.py | from django.db.models import Q, F
from rest_framework import viewsets, serializers
from rest_framework.filters import SearchFilter
from rest_framework.response import Response
from rest_framework.views import APIView
from models import Recipe, Ingredient
def search_by_time_ingredients(ingredients, time, queryset):
# Time intervals for the search
TIME_CHOICES = [(-1, 30), (30, 60), (60, 120), (120, 240), (-1, 999999)]
'''
Helper function to search by available ingredients and time
'''
recipes = queryset
# Add valid substitutes to the ingredient list
subs = []
for i in ingredients:
for s in Ingredient.objects.get(pk=i).substitutes.all():
subs.append(s.pk)
ingredients = ingredients + subs
# Filter by ingredients
recipes = recipes.filter(ingredients__ingredient__in=ingredients)
if time:
time = int(time)
lower_time = TIME_CHOICES[time][0]
upper_time = TIME_CHOICES[time][1]
recipes = recipes.filter(
(Q(cook_time__gt=lower_time - F('prep_time')) &
Q(cook_time__lte=upper_time - F('prep_time'))) |
(Q(cook_time__isnull=True) & Q(prep_time__isnull=True))
)
# Weed out the recipes that require at least one
# ingredient not in the list that is not a substitute
for r in recipes:
for i in r.ingredients.all():
if i.ingredient.pk not in ingredients:
recipes = recipes.exclude(pk=r.pk)
break
return recipes
class IngredientSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField()
def get_name(self, obj):
return obj.name.strip().title()
class Meta:
model = Ingredient
depth = 1
exclude = ['description', 'substitutes']
class IngredientViewSet(viewsets.ModelViewSet):
"""
Default endpoints to view/search/create/modify/delete ingredients
"""
queryset = Ingredient.objects.all().order_by('name')
serializer_class = IngredientSerializer
paginate_by = None
filter_backends = (SearchFilter,)
search_fields = ('name', 'description', 'substitutes__name')
class RecipeSerializer(serializers.ModelSerializer):
image = serializers.SerializerMethodField()
def get_image(self, obj):
if obj.image:
from sorl.thumbnail import get_thumbnail
thumbnail_url = get_thumbnail(
obj.image, '500x500', crop='center', format='PNG'
).url
return self.context['request'].build_absolute_uri(thumbnail_url)
class Meta:
model = Recipe
depth = 2
class RecipeSearchSerializer(serializers.ModelSerializer):
thumbnail = serializers.SerializerMethodField()
def get_thumbnail(self, obj):
if obj.image:
from sorl.thumbnail import get_thumbnail
thumbnail_url = get_thumbnail(
obj.image, '200x200', crop='center', format='PNG'
).url
return self.context['request'].build_absolute_uri(thumbnail_url)
class Meta:
model = Recipe
depth = 2
exclude = ['description', 'ingredients', 'instructions', 'notes']
class RecipeViewSet(viewsets.ModelViewSet):
"""
Default endpoints to view/search/create/modify/delete recipes
"""
queryset = Recipe.objects.all()
serializer_class = RecipeSerializer
filter_backends = (SearchFilter,)
search_fields = ('name', 'description', 'time',
'categories__name',
'ingredients__ingredient__name',
)
class RecipeSearchIngTimeViewSet(APIView):
"""
Search by ingredients endpoint
"""
queryset = Recipe.objects.all()
serializer_class = RecipeSearchSerializer
def get(self, request, format=None):
# Get parameters
params = request.query_params
ingredients = [int(i) for i in params.getlist('ings')]
time = params.get('time')
recipes = search_by_time_ingredients(ingredients, time,
self.queryset)
return Response(self.serializer_class(
recipes, many=True, context={'request': request}
).data)
class RecipeRandomIngTimeViewSet(APIView):
"""
Search by ingredients endpoint
"""
queryset = Recipe.objects.all()
serializer_class = RecipeSearchSerializer
def get(self, request, format=None):
# Get parameters
params = request.query_params
ingredients = [int(i) for i in params.getlist('ings')]
time = params.get('time')
recipes = search_by_time_ingredients(ingredients, time,
self.queryset)
recipe = recipes.order_by('?').first()
return Response(self.serializer_class(
recipe, context={'request': request}
).data) | 0.749821 | 0.199016 |
__author__ = 'buec'
import xml.etree.ElementTree as et
from pyspeechgrammar import model
class SRGSXMLSerializer:
def create_grammar_element(self, grammar):
grammar_element = et.Element('grammar')
for rule in grammar.rules:
rule_element = self.create_rule_element(rule)
grammar_element.append(rule_element)
grammar_element.set('version', '1.0')
grammar_element.set('xmlns', 'http://www.w3.org/2001/06/grammar')
if grammar.language is not None:
grammar_element.set('xml:lang', grammar.language)
else:
grammar_element.set('xml:lang', 'en-US')
if grammar.root_rule is not None:
grammar_element.set('root', grammar.root_rule.name)
elif len(grammar.rules) > 0:
grammar_element.set('root', grammar.rules[0].name)
return grammar_element
def create_rule_element(self, rule):
rule_element = et.Element("rule")
rule_element.set('id', rule.name)
if rule.scope == model.Rule.SCOPE_PUBLIC:
rule_element.set('scope', 'public')
self.add_model_element_to_xml_element(rule_element, rule.value)
return rule_element
def add_model_element_to_xml_element(self, xml_element, model_element):
the_element = None
if isinstance(model_element, model.Token):
the_element = self.add_token_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.RuleReference):
the_element = self.add_rule_reference_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.Group):
the_element = self.add_group_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.OptionalGroup):
the_element = self.add_optional_group_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.Sequence):
the_element = self.add_sequence_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.Alternatives):
the_element = self.add_alternatives_to_xml_element(xml_element, model_element)
self.set_repetitions_on_xml_element(the_element, model_element)
self.add_tags_to_element(the_element, model_element)
def add_token_to_xml_element(self, xml_element, token):
xml_element.text = token.value
return xml_element
def add_rule_reference_to_xml_element(self, xml_element, rule_reference):
ref_element = et.SubElement(xml_element, 'ruleref')
ref_element.set('uri', '#' + rule_reference.rule_name)
return ref_element
def add_group_to_xml_element(self, xml_element, group):
group_element = et.SubElement(xml_element, 'item')
self.add_model_element_to_xml_element(group_element, group.value)
return group_element
def add_optional_group_to_xml_element(self, xml_element, optional_group):
group_element = et.SubElement(xml_element, 'item')
group_element.set('repeat', '0-1')
self.add_model_element_to_xml_element(group_element, optional_group.value)
return group_element
def add_sequence_to_xml_element(self, xml_element, sequence):
seq_element = et.SubElement(xml_element,'item')
for element in sequence.elements:
item_element = et.SubElement(seq_element, 'item')
self.add_model_element_to_xml_element(item_element, element)
return seq_element
def add_alternatives_to_xml_element(self, xml_element, alternatives):
alt_element = et.SubElement(xml_element,'one-of')
for element in alternatives.elements:
item_element = et.SubElement(alt_element, 'item')
if element.weight != 1:
item_element.set('weight', str(element.weight))
self.add_model_element_to_xml_element(item_element, element)
return alt_element
def set_repetitions_on_xml_element(self, xml_element, model_element):
if model_element.min_repeat == 1 and model_element.max_repeat == 1:
return
if model_element.max_repeat == model.Element.INFINITY_REPEAT:
xml_element.set('repeat', '{}-'.format(model_element.min_repeat))
else:
xml_element.set('repeat', '{}-{}'.format(model_element.min_repeat, model_element.max_repeat))
def add_tags_to_element(self, xml_element, model_element):
for tag in model_element.tags:
tag_element = et.SubElement(xml_element, 'tag')
tag_element.text = tag.name | pyspeechgrammar/srgs_xml/serialize.py | __author__ = 'buec'
import xml.etree.ElementTree as et
from pyspeechgrammar import model
class SRGSXMLSerializer:
def create_grammar_element(self, grammar):
grammar_element = et.Element('grammar')
for rule in grammar.rules:
rule_element = self.create_rule_element(rule)
grammar_element.append(rule_element)
grammar_element.set('version', '1.0')
grammar_element.set('xmlns', 'http://www.w3.org/2001/06/grammar')
if grammar.language is not None:
grammar_element.set('xml:lang', grammar.language)
else:
grammar_element.set('xml:lang', 'en-US')
if grammar.root_rule is not None:
grammar_element.set('root', grammar.root_rule.name)
elif len(grammar.rules) > 0:
grammar_element.set('root', grammar.rules[0].name)
return grammar_element
def create_rule_element(self, rule):
rule_element = et.Element("rule")
rule_element.set('id', rule.name)
if rule.scope == model.Rule.SCOPE_PUBLIC:
rule_element.set('scope', 'public')
self.add_model_element_to_xml_element(rule_element, rule.value)
return rule_element
def add_model_element_to_xml_element(self, xml_element, model_element):
the_element = None
if isinstance(model_element, model.Token):
the_element = self.add_token_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.RuleReference):
the_element = self.add_rule_reference_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.Group):
the_element = self.add_group_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.OptionalGroup):
the_element = self.add_optional_group_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.Sequence):
the_element = self.add_sequence_to_xml_element(xml_element, model_element)
elif isinstance(model_element, model.Alternatives):
the_element = self.add_alternatives_to_xml_element(xml_element, model_element)
self.set_repetitions_on_xml_element(the_element, model_element)
self.add_tags_to_element(the_element, model_element)
def add_token_to_xml_element(self, xml_element, token):
xml_element.text = token.value
return xml_element
def add_rule_reference_to_xml_element(self, xml_element, rule_reference):
ref_element = et.SubElement(xml_element, 'ruleref')
ref_element.set('uri', '#' + rule_reference.rule_name)
return ref_element
def add_group_to_xml_element(self, xml_element, group):
group_element = et.SubElement(xml_element, 'item')
self.add_model_element_to_xml_element(group_element, group.value)
return group_element
def add_optional_group_to_xml_element(self, xml_element, optional_group):
group_element = et.SubElement(xml_element, 'item')
group_element.set('repeat', '0-1')
self.add_model_element_to_xml_element(group_element, optional_group.value)
return group_element
def add_sequence_to_xml_element(self, xml_element, sequence):
seq_element = et.SubElement(xml_element,'item')
for element in sequence.elements:
item_element = et.SubElement(seq_element, 'item')
self.add_model_element_to_xml_element(item_element, element)
return seq_element
def add_alternatives_to_xml_element(self, xml_element, alternatives):
alt_element = et.SubElement(xml_element,'one-of')
for element in alternatives.elements:
item_element = et.SubElement(alt_element, 'item')
if element.weight != 1:
item_element.set('weight', str(element.weight))
self.add_model_element_to_xml_element(item_element, element)
return alt_element
def set_repetitions_on_xml_element(self, xml_element, model_element):
if model_element.min_repeat == 1 and model_element.max_repeat == 1:
return
if model_element.max_repeat == model.Element.INFINITY_REPEAT:
xml_element.set('repeat', '{}-'.format(model_element.min_repeat))
else:
xml_element.set('repeat', '{}-{}'.format(model_element.min_repeat, model_element.max_repeat))
def add_tags_to_element(self, xml_element, model_element):
for tag in model_element.tags:
tag_element = et.SubElement(xml_element, 'tag')
tag_element.text = tag.name | 0.483892 | 0.197696 |
from typing import Iterator, List, Union, Optional
import numpy as np
import logging
from syne_tune.optimizer.schedulers.searchers.bayesopt.tuning_algorithms.base_classes \
import CandidateGenerator
from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.common \
import Configuration, ConfigurationFilter
from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.hp_ranges \
import HyperparameterRanges
from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.tuning_job_state \
import TuningJobState
from syne_tune.config_space import config_space_size
logger = logging.getLogger(__name__)
MAX_RETRIES_CANDIDATES_EN_BULK = 20
class RandomStatefulCandidateGenerator(CandidateGenerator):
"""
This generator maintains a random state, so if generate_candidates is
called several times, different sequences are returned.
"""
def __init__(self, hp_ranges: HyperparameterRanges,
random_state: np.random.RandomState):
self.hp_ranges = hp_ranges
self.random_state = random_state
def generate_candidates(self) -> Iterator[Configuration]:
while True:
yield self.hp_ranges.random_config(self.random_state)
def generate_candidates_en_bulk(
self, num_cands: int, exclusion_list=None) -> List[Configuration]:
if exclusion_list is None:
return self.hp_ranges.random_configs(self.random_state, num_cands)
else:
assert isinstance(exclusion_list, ExclusionList), \
"exclusion_list must be of type ExclusionList"
configs = []
num_done = 0
for i in range(MAX_RETRIES_CANDIDATES_EN_BULK):
# From iteration 1, we request more than what is still
# needed, because the config space seems to not have
# enough configs left
num_requested = min(
num_cands, (num_cands - num_done) * (i + 1))
new_configs = [
config for config in self.hp_ranges.random_configs(
self.random_state, num_requested)
if not exclusion_list.contains(config)]
num_new = min(num_cands - num_done, len(new_configs))
configs += new_configs[:num_new]
num_done += num_new
if num_done == num_cands:
break
if num_done < num_cands:
logger.warning(
f"Could only sample {num_done} candidates where "
f"{num_cands} were requested. len(exclusion_list) = "
f"{len(exclusion_list)}")
return configs
class ExclusionList(object):
"""
Maintains exclusion list of configs, to avoid choosing configs several
times.
The exclusion list contains non-extended configs, but it can be fed with
and queried with extended configs. In that case, the resource attribute
is removed from the config.
"""
def __init__(
self, state: Union[TuningJobState, dict],
filter_observed_data: Optional[ConfigurationFilter] = None):
is_new = isinstance(state, TuningJobState)
if is_new:
self.hp_ranges = state.hp_ranges
keys = self.hp_ranges.internal_keys
# Remove resource attribute from `self.keys` if present
resource_attr = self.hp_ranges.name_last_pos
if resource_attr is None:
self.keys = keys
else:
pos = keys.index(resource_attr)
self.keys = keys[:pos] + keys[(pos + 1):]
_elist = [x.trial_id for x in state.pending_evaluations] +\
state.failed_trials
observed_trial_ids = [x.trial_id for x in state.trials_evaluations]
if filter_observed_data is not None:
observed_trial_ids = [
trial_id for trial_id in observed_trial_ids
if filter_observed_data(state.config_for_trial[trial_id])]
_elist = set(_elist + observed_trial_ids)
self.excl_set = set(
self._to_matchstr(state.config_for_trial[trial_id])
for trial_id in _elist)
else:
self.hp_ranges = state['hp_ranges']
self.excl_set = state['excl_set']
self.keys = state['keys']
self.configspace_size = config_space_size(self.hp_ranges.config_space)
def _to_matchstr(self, config) -> str:
return self.hp_ranges.config_to_match_string(config, keys=self.keys)
def contains(self, config: Configuration) -> bool:
return self._to_matchstr(config) in self.excl_set
def add(self, config: Configuration):
self.excl_set.add(self._to_matchstr(config))
def copy(self) -> 'ExclusionList':
return ExclusionList(
{'hp_ranges': self.hp_ranges,
'excl_set': set(self.excl_set),
'keys': self.keys})
@staticmethod
def empty_list(hp_ranges: HyperparameterRanges) -> 'ExclusionList':
return ExclusionList(TuningJobState.empty_state(hp_ranges))
def __len__(self) -> int:
return len(self.excl_set)
def config_space_exhausted(self) -> bool:
return (self.configspace_size is not None) and \
len(self.excl_set) >= self.configspace_size
MAX_RETRIES_ON_DUPLICATES = 10000
def generate_unique_candidates(
candidates_generator: CandidateGenerator, num_candidates: int,
exclusion_candidates: ExclusionList) -> List[Configuration]:
exclusion_candidates = exclusion_candidates.copy() # Copy
result = []
num_results = 0
retries = 0
just_added = True
for i, cand in enumerate(candidates_generator.generate_candidates()):
if just_added:
if exclusion_candidates.config_space_exhausted():
logger.warning(
"All entries of finite config space (size " +
f"{exclusion_candidates.configspace_size}) have been selected. Returning " +
f"{len(result)} configs instead of {num_candidates}")
break
just_added = False
if not exclusion_candidates.contains(cand):
result.append(cand)
num_results += 1
exclusion_candidates.add(cand)
retries = 0
just_added = True
else:
# found a duplicate; retry
retries += 1
# End loop if enough candidates where generated, or after too many retries
# (this latter can happen when most of them are duplicates, and must be done
# to avoid infinite loops in the purely discrete case)
if num_results == num_candidates or retries > MAX_RETRIES_ON_DUPLICATES:
if retries > MAX_RETRIES_ON_DUPLICATES:
logger.warning(
f"Reached limit of {MAX_RETRIES_ON_DUPLICATES} retries "
f"with i={i}. Returning {len(result)} candidates instead "
f"of the requested {num_candidates}")
break
return result | syne_tune/optimizer/schedulers/searchers/bayesopt/tuning_algorithms/common.py | from typing import Iterator, List, Union, Optional
import numpy as np
import logging
from syne_tune.optimizer.schedulers.searchers.bayesopt.tuning_algorithms.base_classes \
import CandidateGenerator
from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.common \
import Configuration, ConfigurationFilter
from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.hp_ranges \
import HyperparameterRanges
from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.tuning_job_state \
import TuningJobState
from syne_tune.config_space import config_space_size
logger = logging.getLogger(__name__)
MAX_RETRIES_CANDIDATES_EN_BULK = 20
class RandomStatefulCandidateGenerator(CandidateGenerator):
"""
This generator maintains a random state, so if generate_candidates is
called several times, different sequences are returned.
"""
def __init__(self, hp_ranges: HyperparameterRanges,
random_state: np.random.RandomState):
self.hp_ranges = hp_ranges
self.random_state = random_state
def generate_candidates(self) -> Iterator[Configuration]:
while True:
yield self.hp_ranges.random_config(self.random_state)
def generate_candidates_en_bulk(
self, num_cands: int, exclusion_list=None) -> List[Configuration]:
if exclusion_list is None:
return self.hp_ranges.random_configs(self.random_state, num_cands)
else:
assert isinstance(exclusion_list, ExclusionList), \
"exclusion_list must be of type ExclusionList"
configs = []
num_done = 0
for i in range(MAX_RETRIES_CANDIDATES_EN_BULK):
# From iteration 1, we request more than what is still
# needed, because the config space seems to not have
# enough configs left
num_requested = min(
num_cands, (num_cands - num_done) * (i + 1))
new_configs = [
config for config in self.hp_ranges.random_configs(
self.random_state, num_requested)
if not exclusion_list.contains(config)]
num_new = min(num_cands - num_done, len(new_configs))
configs += new_configs[:num_new]
num_done += num_new
if num_done == num_cands:
break
if num_done < num_cands:
logger.warning(
f"Could only sample {num_done} candidates where "
f"{num_cands} were requested. len(exclusion_list) = "
f"{len(exclusion_list)}")
return configs
class ExclusionList(object):
"""
Maintains exclusion list of configs, to avoid choosing configs several
times.
The exclusion list contains non-extended configs, but it can be fed with
and queried with extended configs. In that case, the resource attribute
is removed from the config.
"""
def __init__(
self, state: Union[TuningJobState, dict],
filter_observed_data: Optional[ConfigurationFilter] = None):
is_new = isinstance(state, TuningJobState)
if is_new:
self.hp_ranges = state.hp_ranges
keys = self.hp_ranges.internal_keys
# Remove resource attribute from `self.keys` if present
resource_attr = self.hp_ranges.name_last_pos
if resource_attr is None:
self.keys = keys
else:
pos = keys.index(resource_attr)
self.keys = keys[:pos] + keys[(pos + 1):]
_elist = [x.trial_id for x in state.pending_evaluations] +\
state.failed_trials
observed_trial_ids = [x.trial_id for x in state.trials_evaluations]
if filter_observed_data is not None:
observed_trial_ids = [
trial_id for trial_id in observed_trial_ids
if filter_observed_data(state.config_for_trial[trial_id])]
_elist = set(_elist + observed_trial_ids)
self.excl_set = set(
self._to_matchstr(state.config_for_trial[trial_id])
for trial_id in _elist)
else:
self.hp_ranges = state['hp_ranges']
self.excl_set = state['excl_set']
self.keys = state['keys']
self.configspace_size = config_space_size(self.hp_ranges.config_space)
def _to_matchstr(self, config) -> str:
return self.hp_ranges.config_to_match_string(config, keys=self.keys)
def contains(self, config: Configuration) -> bool:
return self._to_matchstr(config) in self.excl_set
def add(self, config: Configuration):
self.excl_set.add(self._to_matchstr(config))
def copy(self) -> 'ExclusionList':
return ExclusionList(
{'hp_ranges': self.hp_ranges,
'excl_set': set(self.excl_set),
'keys': self.keys})
@staticmethod
def empty_list(hp_ranges: HyperparameterRanges) -> 'ExclusionList':
return ExclusionList(TuningJobState.empty_state(hp_ranges))
def __len__(self) -> int:
return len(self.excl_set)
def config_space_exhausted(self) -> bool:
return (self.configspace_size is not None) and \
len(self.excl_set) >= self.configspace_size
MAX_RETRIES_ON_DUPLICATES = 10000
def generate_unique_candidates(
candidates_generator: CandidateGenerator, num_candidates: int,
exclusion_candidates: ExclusionList) -> List[Configuration]:
exclusion_candidates = exclusion_candidates.copy() # Copy
result = []
num_results = 0
retries = 0
just_added = True
for i, cand in enumerate(candidates_generator.generate_candidates()):
if just_added:
if exclusion_candidates.config_space_exhausted():
logger.warning(
"All entries of finite config space (size " +
f"{exclusion_candidates.configspace_size}) have been selected. Returning " +
f"{len(result)} configs instead of {num_candidates}")
break
just_added = False
if not exclusion_candidates.contains(cand):
result.append(cand)
num_results += 1
exclusion_candidates.add(cand)
retries = 0
just_added = True
else:
# found a duplicate; retry
retries += 1
# End loop if enough candidates where generated, or after too many retries
# (this latter can happen when most of them are duplicates, and must be done
# to avoid infinite loops in the purely discrete case)
if num_results == num_candidates or retries > MAX_RETRIES_ON_DUPLICATES:
if retries > MAX_RETRIES_ON_DUPLICATES:
logger.warning(
f"Reached limit of {MAX_RETRIES_ON_DUPLICATES} retries "
f"with i={i}. Returning {len(result)} candidates instead "
f"of the requested {num_candidates}")
break
return result | 0.864153 | 0.342599 |
import re
import requests
import time
import sys
from random import randint
from urlparse import urlparse
headers = {"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch, br",
"Accept-Language": "en-US,en;q=0.8"}
startingURLs = ["http://weheartit.com/inspirations/fashion",
"http://www.imdb.com/",
"http://www.espn.com/",
"http://abcnews.go.com",
"http://www.eonline.com/",
"http://fandom.wikia.com/",
"http://www.breitbart.com/",
"http://www.motherjones.com/",
"http://talkingcomicbooks.com/",
"http://www.independent.co.uk/us",
"http://www.wikihow.com/Main-Page",
"https://www.google.com/search?q=beyonce"]
def getNextURL(session, url):
responseText = requests.get(url, headers=headers, timeout=5).text
allHrefs = re.findall(r'(href="(\w|:|\/|\.|\?|\=|\&|\;)+")',responseText)
hrefText = str(allHrefs[randint(0,len(allHrefs))][0])
if 'http' not in hrefText:
if '//' not in hrefText:
# 'href="/questions/tagged/angularjs"'
parsed_uri = urlparse(url)
domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
return session, domain + hrefText[7:len(hrefText)-1]
else:
# 'href="//philosophy.stackexchange.com"'
return session, "http://" + hrefText[8:len(hrefText)-1]
else:
# 'href="http://www.espn.com/"'
return session, hrefText[6:(len(hrefText)-1)]
def main(startIndex):
urlIndex = int(startIndex)
browsingSession = requests.Session()
try:
while (True):
lastGoodUrl = startingURLs[urlIndex]
url = lastGoodUrl
urlIndex = randint(0, len(startingURLs)-1)
for x in xrange(randint(0, 50)):
try:
print(time.strftime("%c") + ": Going to: " + url)
browsingSession, url = getNextURL(browsingSession, url)
lastGoodUrl = url
waitTime = randint(2,60)
print("Waiting " + str(waitTime) + " seconds")
time.sleep(waitTime)
except:
browsingSession, url = getNextURL(browsingSession, lastGoodUrl)
except:
print("-------------Starting Again----------------")
main(randint(0, len(startingURLs)-1))
if __name__ == '__main__':
print("-------------Starting FogOfWeb----------------")
main(sys.argv[1]) | FogOfWar/fogofweb.py | import re
import requests
import time
import sys
from random import randint
from urlparse import urlparse
headers = {"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch, br",
"Accept-Language": "en-US,en;q=0.8"}
startingURLs = ["http://weheartit.com/inspirations/fashion",
"http://www.imdb.com/",
"http://www.espn.com/",
"http://abcnews.go.com",
"http://www.eonline.com/",
"http://fandom.wikia.com/",
"http://www.breitbart.com/",
"http://www.motherjones.com/",
"http://talkingcomicbooks.com/",
"http://www.independent.co.uk/us",
"http://www.wikihow.com/Main-Page",
"https://www.google.com/search?q=beyonce"]
def getNextURL(session, url):
responseText = requests.get(url, headers=headers, timeout=5).text
allHrefs = re.findall(r'(href="(\w|:|\/|\.|\?|\=|\&|\;)+")',responseText)
hrefText = str(allHrefs[randint(0,len(allHrefs))][0])
if 'http' not in hrefText:
if '//' not in hrefText:
# 'href="/questions/tagged/angularjs"'
parsed_uri = urlparse(url)
domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
return session, domain + hrefText[7:len(hrefText)-1]
else:
# 'href="//philosophy.stackexchange.com"'
return session, "http://" + hrefText[8:len(hrefText)-1]
else:
# 'href="http://www.espn.com/"'
return session, hrefText[6:(len(hrefText)-1)]
def main(startIndex):
urlIndex = int(startIndex)
browsingSession = requests.Session()
try:
while (True):
lastGoodUrl = startingURLs[urlIndex]
url = lastGoodUrl
urlIndex = randint(0, len(startingURLs)-1)
for x in xrange(randint(0, 50)):
try:
print(time.strftime("%c") + ": Going to: " + url)
browsingSession, url = getNextURL(browsingSession, url)
lastGoodUrl = url
waitTime = randint(2,60)
print("Waiting " + str(waitTime) + " seconds")
time.sleep(waitTime)
except:
browsingSession, url = getNextURL(browsingSession, lastGoodUrl)
except:
print("-------------Starting Again----------------")
main(randint(0, len(startingURLs)-1))
if __name__ == '__main__':
print("-------------Starting FogOfWeb----------------")
main(sys.argv[1]) | 0.097005 | 0.085251 |
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('diabetes.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 8].values
#taking care of missing data
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values=0, strategy='mean', axis = 0)
imputer = imputer.fit(X[:, 2:6])
X[:, 2:6] = imputer.transform(X[:, 2:6])
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
#Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Fitting classifier to the Training set
# Create your classifier here
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
from sklearn.metrics import accuracy_score
accuracy_score(y_test,y_pred)
#Applying k-Fold Cross Validation
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)
accuracies.mean()
accuracies.std()
#Applying Grid Search to find the best model and the best parameters
from sklearn.model_selection import GridSearchCV
parameters = [{ 'criterion':['gini'], 'min_samples_split':[2,3,4,5,6,7,8,9]},
{ 'criterion':['entropy'], 'min_samples_split':[2,3,4,5,6,7,8,9]},
]
grid_search = GridSearchCV(estimator = classifier,
param_grid = parameters,
scoring = 'accuracy',
cv = 10)
grid_search = grid_search.fit(X_train, y_train)
best_accuracy = grid_search.best_score_
best_parameters = grid_search.best_params_ | decision_tree.py |
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('diabetes.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 8].values
#taking care of missing data
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values=0, strategy='mean', axis = 0)
imputer = imputer.fit(X[:, 2:6])
X[:, 2:6] = imputer.transform(X[:, 2:6])
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
#Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Fitting classifier to the Training set
# Create your classifier here
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
from sklearn.metrics import accuracy_score
accuracy_score(y_test,y_pred)
#Applying k-Fold Cross Validation
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)
accuracies.mean()
accuracies.std()
#Applying Grid Search to find the best model and the best parameters
from sklearn.model_selection import GridSearchCV
parameters = [{ 'criterion':['gini'], 'min_samples_split':[2,3,4,5,6,7,8,9]},
{ 'criterion':['entropy'], 'min_samples_split':[2,3,4,5,6,7,8,9]},
]
grid_search = GridSearchCV(estimator = classifier,
param_grid = parameters,
scoring = 'accuracy',
cv = 10)
grid_search = grid_search.fit(X_train, y_train)
best_accuracy = grid_search.best_score_
best_parameters = grid_search.best_params_ | 0.764276 | 0.67698 |
from .____init___6 import *
import typing
import System.IO
import System.Collections.Generic
import System
import QuantConnect.Indicators
import QuantConnect.Data.Market
import QuantConnect.Data
import QuantConnect
import Python.Runtime
import datetime
class IndicatorExtensions(System.object):
""" Provides extension methods for Indicator """
@staticmethod
@typing.overload
def EMA(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], period: int, smoothingFactor: typing.Optional[float], waitForFirstToReady: bool) -> QuantConnect.Indicators.ExponentialMovingAverage:
pass
@staticmethod
@typing.overload
def EMA(left: Python.Runtime.PyObject, period: int, smoothingFactor: typing.Optional[float], waitForFirstToReady: bool) -> QuantConnect.Indicators.ExponentialMovingAverage:
pass
def EMA(self, *args) -> QuantConnect.Indicators.ExponentialMovingAverage:
pass
@staticmethod
@typing.overload
def MAX(left: QuantConnect.Indicators.IIndicator, period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.Maximum:
pass
@staticmethod
@typing.overload
def MAX(left: Python.Runtime.PyObject, period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.Maximum:
pass
def MAX(self, *args) -> QuantConnect.Indicators.Maximum:
pass
@staticmethod
@typing.overload
def MIN(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.Minimum:
pass
@staticmethod
@typing.overload
def MIN(left: Python.Runtime.PyObject, period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.Minimum:
pass
def MIN(self, *args) -> QuantConnect.Indicators.Minimum:
pass
@staticmethod
@typing.overload
def Minus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], constant: float) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Minus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T]) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Minus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], name: str) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Minus(left: Python.Runtime.PyObject, constant: float) -> object:
pass
@staticmethod
@typing.overload
def Minus(left: Python.Runtime.PyObject, right: Python.Runtime.PyObject, name: str) -> object:
pass
def Minus(self, *args) -> object:
pass
@staticmethod
@typing.overload
def Of(second: QuantConnect.Indicators.T, first: QuantConnect.Indicators.IIndicator, waitForFirstToReady: bool) -> QuantConnect.Indicators.T:
pass
@staticmethod
@typing.overload
def Of(second: Python.Runtime.PyObject, first: Python.Runtime.PyObject, waitForFirstToReady: bool) -> object:
pass
def Of(self, *args) -> object:
pass
@staticmethod
@typing.overload
def Over(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], constant: float) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Over(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T]) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Over(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], name: str) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Over(left: Python.Runtime.PyObject, constant: float) -> object:
pass
@staticmethod
@typing.overload
def Over(left: Python.Runtime.PyObject, right: Python.Runtime.PyObject, name: str) -> object:
pass
def Over(self, *args) -> object:
pass
@staticmethod
@typing.overload
def Plus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], constant: float) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Plus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T]) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Plus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], name: str) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Plus(left: Python.Runtime.PyObject, constant: float) -> object:
pass
@staticmethod
@typing.overload
def Plus(left: Python.Runtime.PyObject, right: Python.Runtime.PyObject, name: str) -> object:
pass
def Plus(self, *args) -> object:
pass
@staticmethod
@typing.overload
def SMA(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.SimpleMovingAverage:
pass
@staticmethod
@typing.overload
def SMA(left: Python.Runtime.PyObject, period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.SimpleMovingAverage:
pass
def SMA(self, *args) -> QuantConnect.Indicators.SimpleMovingAverage:
pass
@staticmethod
@typing.overload
def Times(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], constant: float) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Times(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T]) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Times(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], name: str) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Times(left: Python.Runtime.PyObject, constant: float) -> object:
pass
@staticmethod
@typing.overload
def Times(left: Python.Runtime.PyObject, right: Python.Runtime.PyObject, name: str) -> object:
pass
def Times(self, *args) -> object:
pass
@staticmethod
def Update(indicator: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.IndicatorDataPoint], time: datetime.datetime, value: float) -> bool:
pass
@staticmethod
@typing.overload
def WeightedBy(value: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], weight: QuantConnect.Indicators.TWeight, period: int) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.IndicatorDataPoint]:
pass
@staticmethod
@typing.overload
def WeightedBy(value: Python.Runtime.PyObject, weight: Python.Runtime.PyObject, period: int) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.IndicatorDataPoint]:
pass
def WeightedBy(self, *args) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.IndicatorDataPoint]:
pass
__all__: list
class IndicatorResult(System.object):
"""
Represents the result of an indicator's calculations
IndicatorResult(value: Decimal, status: IndicatorStatus)
"""
def __init__(self, value: float, status: QuantConnect.Indicators.IndicatorStatus) -> QuantConnect.Indicators.IndicatorResult:
pass
Status: QuantConnect.Indicators.IndicatorStatus
Value: float
class IndicatorStatus(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
"""
The possible states returned by QuantConnect.Indicators.IndicatorBase
enum IndicatorStatus, values: InvalidInput (1), MathError (2), Success (0), ValueNotReady (3)
"""
value__: int
InvalidInput: 'IndicatorStatus'
MathError: 'IndicatorStatus'
Success: 'IndicatorStatus'
ValueNotReady: 'IndicatorStatus'
class IndicatorUpdatedHandler(System.MulticastDelegate, System.Runtime.Serialization.ISerializable, System.ICloneable):
"""
Event handler type for the IndicatorBase.Updated event
IndicatorUpdatedHandler(object: object, method: IntPtr)
"""
def BeginInvoke(self, sender: object, updated: QuantConnect.Indicators.IndicatorDataPoint, callback: System.AsyncCallback, object: object) -> System.IAsyncResult:
pass
def EndInvoke(self, result: System.IAsyncResult) -> None:
pass
def Invoke(self, sender: object, updated: QuantConnect.Indicators.IndicatorDataPoint) -> None:
pass
def __init__(self, object: object, method: System.IntPtr) -> QuantConnect.Indicators.IndicatorUpdatedHandler:
pass
class IntradayVwap(QuantConnect.Indicators.IndicatorBase[BaseData], System.IComparable, QuantConnect.Indicators.IIndicator[BaseData], QuantConnect.Indicators.IIndicator, System.IComparable[IIndicator[BaseData]]):
"""
Defines the canonical intraday VWAP indicator
IntradayVwap(name: str)
"""
def __init__(self, name: str) -> QuantConnect.Indicators.IntradayVwap:
pass
IsReady: bool
class IReadOnlyWindow(System.Collections.IEnumerable, System.Collections.Generic.IEnumerable[T]):
# no doc
Count: int
IsReady: bool
MostRecentlyRemoved: QuantConnect.Indicators.T
Samples: float
Size: int
Item: indexer# | Algorithm.Python/stubs/QuantConnect/Indicators/____init___5.py | from .____init___6 import *
import typing
import System.IO
import System.Collections.Generic
import System
import QuantConnect.Indicators
import QuantConnect.Data.Market
import QuantConnect.Data
import QuantConnect
import Python.Runtime
import datetime
class IndicatorExtensions(System.object):
""" Provides extension methods for Indicator """
@staticmethod
@typing.overload
def EMA(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], period: int, smoothingFactor: typing.Optional[float], waitForFirstToReady: bool) -> QuantConnect.Indicators.ExponentialMovingAverage:
pass
@staticmethod
@typing.overload
def EMA(left: Python.Runtime.PyObject, period: int, smoothingFactor: typing.Optional[float], waitForFirstToReady: bool) -> QuantConnect.Indicators.ExponentialMovingAverage:
pass
def EMA(self, *args) -> QuantConnect.Indicators.ExponentialMovingAverage:
pass
@staticmethod
@typing.overload
def MAX(left: QuantConnect.Indicators.IIndicator, period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.Maximum:
pass
@staticmethod
@typing.overload
def MAX(left: Python.Runtime.PyObject, period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.Maximum:
pass
def MAX(self, *args) -> QuantConnect.Indicators.Maximum:
pass
@staticmethod
@typing.overload
def MIN(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.Minimum:
pass
@staticmethod
@typing.overload
def MIN(left: Python.Runtime.PyObject, period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.Minimum:
pass
def MIN(self, *args) -> QuantConnect.Indicators.Minimum:
pass
@staticmethod
@typing.overload
def Minus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], constant: float) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Minus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T]) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Minus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], name: str) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Minus(left: Python.Runtime.PyObject, constant: float) -> object:
pass
@staticmethod
@typing.overload
def Minus(left: Python.Runtime.PyObject, right: Python.Runtime.PyObject, name: str) -> object:
pass
def Minus(self, *args) -> object:
pass
@staticmethod
@typing.overload
def Of(second: QuantConnect.Indicators.T, first: QuantConnect.Indicators.IIndicator, waitForFirstToReady: bool) -> QuantConnect.Indicators.T:
pass
@staticmethod
@typing.overload
def Of(second: Python.Runtime.PyObject, first: Python.Runtime.PyObject, waitForFirstToReady: bool) -> object:
pass
def Of(self, *args) -> object:
pass
@staticmethod
@typing.overload
def Over(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], constant: float) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Over(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T]) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Over(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], name: str) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Over(left: Python.Runtime.PyObject, constant: float) -> object:
pass
@staticmethod
@typing.overload
def Over(left: Python.Runtime.PyObject, right: Python.Runtime.PyObject, name: str) -> object:
pass
def Over(self, *args) -> object:
pass
@staticmethod
@typing.overload
def Plus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], constant: float) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Plus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T]) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Plus(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], name: str) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Plus(left: Python.Runtime.PyObject, constant: float) -> object:
pass
@staticmethod
@typing.overload
def Plus(left: Python.Runtime.PyObject, right: Python.Runtime.PyObject, name: str) -> object:
pass
def Plus(self, *args) -> object:
pass
@staticmethod
@typing.overload
def SMA(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.SimpleMovingAverage:
pass
@staticmethod
@typing.overload
def SMA(left: Python.Runtime.PyObject, period: int, waitForFirstToReady: bool) -> QuantConnect.Indicators.SimpleMovingAverage:
pass
def SMA(self, *args) -> QuantConnect.Indicators.SimpleMovingAverage:
pass
@staticmethod
@typing.overload
def Times(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], constant: float) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Times(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T]) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Times(left: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], right: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], name: str) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.T]:
pass
@staticmethod
@typing.overload
def Times(left: Python.Runtime.PyObject, constant: float) -> object:
pass
@staticmethod
@typing.overload
def Times(left: Python.Runtime.PyObject, right: Python.Runtime.PyObject, name: str) -> object:
pass
def Times(self, *args) -> object:
pass
@staticmethod
def Update(indicator: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.IndicatorDataPoint], time: datetime.datetime, value: float) -> bool:
pass
@staticmethod
@typing.overload
def WeightedBy(value: QuantConnect.Indicators.IndicatorBase[QuantConnect.Indicators.T], weight: QuantConnect.Indicators.TWeight, period: int) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.IndicatorDataPoint]:
pass
@staticmethod
@typing.overload
def WeightedBy(value: Python.Runtime.PyObject, weight: Python.Runtime.PyObject, period: int) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.IndicatorDataPoint]:
pass
def WeightedBy(self, *args) -> QuantConnect.Indicators.CompositeIndicator[QuantConnect.Indicators.IndicatorDataPoint]:
pass
__all__: list
class IndicatorResult(System.object):
"""
Represents the result of an indicator's calculations
IndicatorResult(value: Decimal, status: IndicatorStatus)
"""
def __init__(self, value: float, status: QuantConnect.Indicators.IndicatorStatus) -> QuantConnect.Indicators.IndicatorResult:
pass
Status: QuantConnect.Indicators.IndicatorStatus
Value: float
class IndicatorStatus(System.Enum, System.IConvertible, System.IFormattable, System.IComparable):
"""
The possible states returned by QuantConnect.Indicators.IndicatorBase
enum IndicatorStatus, values: InvalidInput (1), MathError (2), Success (0), ValueNotReady (3)
"""
value__: int
InvalidInput: 'IndicatorStatus'
MathError: 'IndicatorStatus'
Success: 'IndicatorStatus'
ValueNotReady: 'IndicatorStatus'
class IndicatorUpdatedHandler(System.MulticastDelegate, System.Runtime.Serialization.ISerializable, System.ICloneable):
"""
Event handler type for the IndicatorBase.Updated event
IndicatorUpdatedHandler(object: object, method: IntPtr)
"""
def BeginInvoke(self, sender: object, updated: QuantConnect.Indicators.IndicatorDataPoint, callback: System.AsyncCallback, object: object) -> System.IAsyncResult:
pass
def EndInvoke(self, result: System.IAsyncResult) -> None:
pass
def Invoke(self, sender: object, updated: QuantConnect.Indicators.IndicatorDataPoint) -> None:
pass
def __init__(self, object: object, method: System.IntPtr) -> QuantConnect.Indicators.IndicatorUpdatedHandler:
pass
class IntradayVwap(QuantConnect.Indicators.IndicatorBase[BaseData], System.IComparable, QuantConnect.Indicators.IIndicator[BaseData], QuantConnect.Indicators.IIndicator, System.IComparable[IIndicator[BaseData]]):
"""
Defines the canonical intraday VWAP indicator
IntradayVwap(name: str)
"""
def __init__(self, name: str) -> QuantConnect.Indicators.IntradayVwap:
pass
IsReady: bool
class IReadOnlyWindow(System.Collections.IEnumerable, System.Collections.Generic.IEnumerable[T]):
# no doc
Count: int
IsReady: bool
MostRecentlyRemoved: QuantConnect.Indicators.T
Samples: float
Size: int
Item: indexer# | 0.853547 | 0.324329 |
class Solution:
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
# 维护一个数字到英语的转换字典
self.IntEng = {
"0": 'Zero',
"1": 'One',
"2": 'Two',
"3": 'Three',
"4": 'Four',
"5": 'Five',
"6": 'Six',
"7": 'Seven',
"8": 'Eight',
"9": 'Nine',
"10": 'Ten',
"11": 'Eleven',
"12": 'Twelve',
"13": 'Thirteen',
"14": 'Fourteen',
"15": 'Fifteen',
"16": 'Sixteen',
"17": 'Seventeen',
"18": 'Eighteen',
"19": 'Nineteen',
"20": 'Twenty',
"30": 'Thirty',
"40": 'Forty',
"50": 'Fifty',
"60": 'Sixty',
"70": 'Seventy',
"80": 'Eighty',
"90": 'Ninety',
"100": 'Hundred',
}
# 没三节为一个单位,2^31最大用到的单位为Billion
units = ['', 'Thousand', 'Million', 'Billion']
res = ''
# 将数字转换成为字符串
_str = str(num)
# count:字符串中字符个数,i:数字三个为一节,当前数字所在节
count, i = len(_str), 0
while count - (i + 1) * 3 >= 0:
# 取出三个数字
_num = _str[count - (i + 1) * 3:count - i * 3]
# 三个数字都不为0进行计算
if not _num == "000":
s = self.__readthree(_num)
res = s + " " + units[i] + " " + res
# 进入下一节
i += 1
# 如果最后一节不足三个数,处理剩下的数
if count - (i * 3):
s = self.__readthree(_str[0:count - (i * 3)])
res = s + " " + units[i] + " " + res
# 返回结果,去掉最后的空格
return res.strip()
# 私有函数,读一节(三个数字)数
def __readthree(self, _str):
_str = str(int(_str))
if len(_str) == 1:
return self.IntEng[_str]
if len(_str) == 2:
return self.__readtwo(_str)
if len(_str) == 3:
res = self.IntEng[_str[0]] + " " + "Hundred"
if int(_str) % 100:
return res + " " + self.__readtwo(_str[1:])
else:
return res
# 私有函数,读两位数,辅助读一节数字
def __readtwo(self, _str):
_str = str(int(_str))
if int(_str) <= 20 or _str[1] == "0":
return self.IntEng[_str]
else:
return self.IntEng[_str[0] + '0'] + " " + self.IntEng[_str[1]] | LeetCode/2019-02-04-273-Integer-to-English-Words.py |
class Solution:
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
# 维护一个数字到英语的转换字典
self.IntEng = {
"0": 'Zero',
"1": 'One',
"2": 'Two',
"3": 'Three',
"4": 'Four',
"5": 'Five',
"6": 'Six',
"7": 'Seven',
"8": 'Eight',
"9": 'Nine',
"10": 'Ten',
"11": 'Eleven',
"12": 'Twelve',
"13": 'Thirteen',
"14": 'Fourteen',
"15": 'Fifteen',
"16": 'Sixteen',
"17": 'Seventeen',
"18": 'Eighteen',
"19": 'Nineteen',
"20": 'Twenty',
"30": 'Thirty',
"40": 'Forty',
"50": 'Fifty',
"60": 'Sixty',
"70": 'Seventy',
"80": 'Eighty',
"90": 'Ninety',
"100": 'Hundred',
}
# 没三节为一个单位,2^31最大用到的单位为Billion
units = ['', 'Thousand', 'Million', 'Billion']
res = ''
# 将数字转换成为字符串
_str = str(num)
# count:字符串中字符个数,i:数字三个为一节,当前数字所在节
count, i = len(_str), 0
while count - (i + 1) * 3 >= 0:
# 取出三个数字
_num = _str[count - (i + 1) * 3:count - i * 3]
# 三个数字都不为0进行计算
if not _num == "000":
s = self.__readthree(_num)
res = s + " " + units[i] + " " + res
# 进入下一节
i += 1
# 如果最后一节不足三个数,处理剩下的数
if count - (i * 3):
s = self.__readthree(_str[0:count - (i * 3)])
res = s + " " + units[i] + " " + res
# 返回结果,去掉最后的空格
return res.strip()
# 私有函数,读一节(三个数字)数
def __readthree(self, _str):
_str = str(int(_str))
if len(_str) == 1:
return self.IntEng[_str]
if len(_str) == 2:
return self.__readtwo(_str)
if len(_str) == 3:
res = self.IntEng[_str[0]] + " " + "Hundred"
if int(_str) % 100:
return res + " " + self.__readtwo(_str[1:])
else:
return res
# 私有函数,读两位数,辅助读一节数字
def __readtwo(self, _str):
_str = str(int(_str))
if int(_str) <= 20 or _str[1] == "0":
return self.IntEng[_str]
else:
return self.IntEng[_str[0] + '0'] + " " + self.IntEng[_str[1]] | 0.487551 | 0.548794 |
# IMPORTOWANIE
from pylab import *
import ephem as ep
# OBSERVATEUR
obs = ep.Observer()
# TUNIS
obs.lon, obs.lat, obs.elev = '10.08', '36.4', 100.0
obs.name= "SAT-TUNIS"
# NOUS CRÉONS UN OBJET
# on vérifie si c'est sous l'horizon
soleil = ep.Sun()
lune = ep.Moon()
venus = ep.Venus()
mars = ep.Mars()
jupiter = ep.Jupiter()
# pas de temps - heure
dt = ep.hour
# temps initial
ts = ep.now()
# heure actuelle
tm = ts
# BOUCLE PRINCIPAL DU PROGRAMME
for i in range (365*24*2):
# nous fixons l'heure actuelle
obs.date = tm
# nous calculons des coordonnées
soleil.compute(obs)
lune.compute(obs)
venus.compute(obs)
mars.compute(obs)
jupiter.compute(obs)
# on calcule la séparation
s1 = ep.separation(venus , lune)
s2 = ep.separation(mars , lune)
s3 = ep.separation(jupiter , lune)
# la séparation doit être inférieure à 5 degrés
if degrees(s1) < 5:
# nous vérifions si la lune sera au-dessus de l'horizon
# et si le soleil est au-dessous de l'horizon
if degrees(lune.alt) > 5.0 and degrees(soleil.alt) < -5.0:
print("-------------------------------------------------------------")
print(u"précédente nouvelle lune , UT :", ep.previous_new_moon(ep.Date(tm)))
print(u"Vénus - Lune , UT :", ep.Date(tm) ,"séparation :", s1)
print(u"pos. Lune :", lune.az ,"El :", lune.alt)
if degrees(s2) < 5:
if degrees(lune.alt) > 5.0 and degrees(soleil.alt) < -5.0:
print("------------------------------------------------------------------")
print(u"précédente nouvelle lune , UT :", ep.previous_new_moon(ep.Date(tm)))
print(u"Mars - Lune , UT :", ep.Date(tm) ,"séparation :", s2)
print(u"Pos. Lune, Az :", lune.az ,"El :", lune.alt)
if degrees(s3) < 5:
if degrees(lune.alt) > 5.0 and degrees(soleil.alt) < -5.0:
print("--------------------------------------------------------------")
print(u"précédente nouvelle lune , UT :", ep.previous_new_moon(ep.Date(tm)))
print(u"Jupiter - Lune , UT :", ep.Date(tm) ,"séparation :", s3)
print(u"Pos. Lune, Az :", lune.az ,"El :", lune.alt)
# on augmente le temps d'une heure
tm += dt | docs/.src/programs/planet_conj.py | # IMPORTOWANIE
from pylab import *
import ephem as ep
# OBSERVATEUR
obs = ep.Observer()
# TUNIS
obs.lon, obs.lat, obs.elev = '10.08', '36.4', 100.0
obs.name= "SAT-TUNIS"
# NOUS CRÉONS UN OBJET
# on vérifie si c'est sous l'horizon
soleil = ep.Sun()
lune = ep.Moon()
venus = ep.Venus()
mars = ep.Mars()
jupiter = ep.Jupiter()
# pas de temps - heure
dt = ep.hour
# temps initial
ts = ep.now()
# heure actuelle
tm = ts
# BOUCLE PRINCIPAL DU PROGRAMME
for i in range (365*24*2):
# nous fixons l'heure actuelle
obs.date = tm
# nous calculons des coordonnées
soleil.compute(obs)
lune.compute(obs)
venus.compute(obs)
mars.compute(obs)
jupiter.compute(obs)
# on calcule la séparation
s1 = ep.separation(venus , lune)
s2 = ep.separation(mars , lune)
s3 = ep.separation(jupiter , lune)
# la séparation doit être inférieure à 5 degrés
if degrees(s1) < 5:
# nous vérifions si la lune sera au-dessus de l'horizon
# et si le soleil est au-dessous de l'horizon
if degrees(lune.alt) > 5.0 and degrees(soleil.alt) < -5.0:
print("-------------------------------------------------------------")
print(u"précédente nouvelle lune , UT :", ep.previous_new_moon(ep.Date(tm)))
print(u"Vénus - Lune , UT :", ep.Date(tm) ,"séparation :", s1)
print(u"pos. Lune :", lune.az ,"El :", lune.alt)
if degrees(s2) < 5:
if degrees(lune.alt) > 5.0 and degrees(soleil.alt) < -5.0:
print("------------------------------------------------------------------")
print(u"précédente nouvelle lune , UT :", ep.previous_new_moon(ep.Date(tm)))
print(u"Mars - Lune , UT :", ep.Date(tm) ,"séparation :", s2)
print(u"Pos. Lune, Az :", lune.az ,"El :", lune.alt)
if degrees(s3) < 5:
if degrees(lune.alt) > 5.0 and degrees(soleil.alt) < -5.0:
print("--------------------------------------------------------------")
print(u"précédente nouvelle lune , UT :", ep.previous_new_moon(ep.Date(tm)))
print(u"Jupiter - Lune , UT :", ep.Date(tm) ,"séparation :", s3)
print(u"Pos. Lune, Az :", lune.az ,"El :", lune.alt)
# on augmente le temps d'une heure
tm += dt | 0.127544 | 0.242183 |
import ctypes
import os
from typing import List, Dict, Union
import numpy as np
from jinja2 import Template
from deep500.lv0.operators.cmake_wrapper import cmake, try_mkdirs
from deep500.lv0.operators.op_compiler import CompilableOp
from deep500.utils.tensor_desc import TensorDescriptor
from deep500.lv0.operators.operator_interface import CustomOp, CustomCPPOp
_CTYPES = {
np.int8: 'int8_t',
np.int16: 'int16_t',
np.int32: 'int32_t',
np.int64: 'int64_t',
np.uint8: 'uint8_t',
np.uint16: 'uint16_t',
np.uint32: 'uint32_t',
np.uint64: 'uint64_t',
np.float32: 'float',
np.float64: 'double'
}
class NumpyCPPOp(CustomCPPOp):
def convert_input(self, input: np.ndarray):
return ctypes.c_void_p(input.__array_interface__['data'][0])
def _ctup(lst: List[TensorDescriptor], prefix: str):
return [(_CTYPES[t.dtype], prefix+"_t"+str(i))
for i, t in enumerate(lst)]
def desc_from_tensor(tensor: np.ndarray) -> TensorDescriptor:
""" Converts a NumPy array to a Deep500 TensorDescriptor. """
return TensorDescriptor(tensor.dtype.type, list(tensor.shape))
def _tendesc(lst: List[np.ndarray]):
return [desc_from_tensor(tensor) for tensor in lst]
class OpCompiler(object):
# Creates a wrapper file and returns its path
def create_wrapper(self, opname: str, dirname: str,
input_tensors: List[TensorDescriptor],
output_tensors: List[TensorDescriptor],
is_cuda: bool, files: List[str]):
curpath = os.path.abspath(os.path.dirname(__file__))
ext = ('.cpp' if not is_cuda else '.cu')
# Read wrapper template
template_file = os.path.join(curpath, 'base.tmpl.cpp')
with open(template_file, 'r') as f:
tmpl = Template(f.read())
# Render template with tensor types
pfile = tmpl.render(input_tensors=_ctup(input_tensors, 'inp'),
output_tensors=_ctup(output_tensors, 'out'),
nextop_grads=_ctup(output_tensors, 'nxtgrad'),
input_grads=_ctup(input_tensors, 'inpgrad'),
opfile='"' + os.path.abspath(files[0]) + '"',
opname=opname)
# Try to create a directory for the wrapper file
try_mkdirs(dirname)
wrapper_filename = os.path.join(dirname, 'base' + ext)
with open(wrapper_filename, 'w') as fp:
fp.write(pfile)
return [os.path.abspath(wrapper_filename)]
def compile_op(self, name: str, files: List[str],
input_tensors: List[TensorDescriptor],
output_tensors: List[TensorDescriptor],
is_cuda: bool,
live_output: bool,
additional_cmake_options: List[str],
additional_definitions: Dict[str, str]):
cmakelists_path = os.path.dirname(os.path.abspath(__file__))
# Create output folder
dirname = '%s_%s_build' % (name, 'base')
# Create wrapper template
wrapper_files = self.create_wrapper(name, dirname, input_tensors,
output_tensors,
is_cuda, files)
# Compile dynamic library (and ignore main file, which is part of the wrapper)
return cmake(name, files[1:] + wrapper_files, cmakelists_path, dirname,
live_output=live_output,
additional_cmake_options=additional_cmake_options,
additional_definitions=additional_definitions)
def custom_op(op_or_compilable_op: Union[CustomOp, CompilableOp]) -> CustomOp:
""" Converts a custom operator or a compilable operator into
an operator that can be run within the reference framework. """
if isinstance(op_or_compilable_op, CompilableOp):
op = op_or_compilable_op
# Compile operator
so_file = OpCompiler().compile_op(
op.name, op.files, op.inputs, op.outputs,
any([f.endswith('.cu') for f in op.files]), op.live_output,
op.cmake_options,
additional_definitions=op.defs)
return NumpyCPPOp(so_file, op.inputs,
op.outputs)
elif isinstance(op_or_compilable_op, CustomOp):
# Already a custom operator, return it as-is
return op_or_compilable_op
else:
raise TypeError | deep500/frameworks/reference/custom_operators/base.py | import ctypes
import os
from typing import List, Dict, Union
import numpy as np
from jinja2 import Template
from deep500.lv0.operators.cmake_wrapper import cmake, try_mkdirs
from deep500.lv0.operators.op_compiler import CompilableOp
from deep500.utils.tensor_desc import TensorDescriptor
from deep500.lv0.operators.operator_interface import CustomOp, CustomCPPOp
_CTYPES = {
np.int8: 'int8_t',
np.int16: 'int16_t',
np.int32: 'int32_t',
np.int64: 'int64_t',
np.uint8: 'uint8_t',
np.uint16: 'uint16_t',
np.uint32: 'uint32_t',
np.uint64: 'uint64_t',
np.float32: 'float',
np.float64: 'double'
}
class NumpyCPPOp(CustomCPPOp):
def convert_input(self, input: np.ndarray):
return ctypes.c_void_p(input.__array_interface__['data'][0])
def _ctup(lst: List[TensorDescriptor], prefix: str):
return [(_CTYPES[t.dtype], prefix+"_t"+str(i))
for i, t in enumerate(lst)]
def desc_from_tensor(tensor: np.ndarray) -> TensorDescriptor:
""" Converts a NumPy array to a Deep500 TensorDescriptor. """
return TensorDescriptor(tensor.dtype.type, list(tensor.shape))
def _tendesc(lst: List[np.ndarray]):
return [desc_from_tensor(tensor) for tensor in lst]
class OpCompiler(object):
# Creates a wrapper file and returns its path
def create_wrapper(self, opname: str, dirname: str,
input_tensors: List[TensorDescriptor],
output_tensors: List[TensorDescriptor],
is_cuda: bool, files: List[str]):
curpath = os.path.abspath(os.path.dirname(__file__))
ext = ('.cpp' if not is_cuda else '.cu')
# Read wrapper template
template_file = os.path.join(curpath, 'base.tmpl.cpp')
with open(template_file, 'r') as f:
tmpl = Template(f.read())
# Render template with tensor types
pfile = tmpl.render(input_tensors=_ctup(input_tensors, 'inp'),
output_tensors=_ctup(output_tensors, 'out'),
nextop_grads=_ctup(output_tensors, 'nxtgrad'),
input_grads=_ctup(input_tensors, 'inpgrad'),
opfile='"' + os.path.abspath(files[0]) + '"',
opname=opname)
# Try to create a directory for the wrapper file
try_mkdirs(dirname)
wrapper_filename = os.path.join(dirname, 'base' + ext)
with open(wrapper_filename, 'w') as fp:
fp.write(pfile)
return [os.path.abspath(wrapper_filename)]
def compile_op(self, name: str, files: List[str],
input_tensors: List[TensorDescriptor],
output_tensors: List[TensorDescriptor],
is_cuda: bool,
live_output: bool,
additional_cmake_options: List[str],
additional_definitions: Dict[str, str]):
cmakelists_path = os.path.dirname(os.path.abspath(__file__))
# Create output folder
dirname = '%s_%s_build' % (name, 'base')
# Create wrapper template
wrapper_files = self.create_wrapper(name, dirname, input_tensors,
output_tensors,
is_cuda, files)
# Compile dynamic library (and ignore main file, which is part of the wrapper)
return cmake(name, files[1:] + wrapper_files, cmakelists_path, dirname,
live_output=live_output,
additional_cmake_options=additional_cmake_options,
additional_definitions=additional_definitions)
def custom_op(op_or_compilable_op: Union[CustomOp, CompilableOp]) -> CustomOp:
""" Converts a custom operator or a compilable operator into
an operator that can be run within the reference framework. """
if isinstance(op_or_compilable_op, CompilableOp):
op = op_or_compilable_op
# Compile operator
so_file = OpCompiler().compile_op(
op.name, op.files, op.inputs, op.outputs,
any([f.endswith('.cu') for f in op.files]), op.live_output,
op.cmake_options,
additional_definitions=op.defs)
return NumpyCPPOp(so_file, op.inputs,
op.outputs)
elif isinstance(op_or_compilable_op, CustomOp):
# Already a custom operator, return it as-is
return op_or_compilable_op
else:
raise TypeError | 0.569134 | 0.447219 |
import os
from pathlib import Path
import cloudinary
import cloudinary.api
import cloudinary.uploader
import sentry_sdk
from dotenv import load_dotenv
from sentry_sdk.integrations.django import DjangoIntegration
load_dotenv() # take environment variables from .env.
BASE_DIR = Path(__file__).resolve().parent.parent
# cloudinary configration
cloudinary.config(cloud_name=os.getenv('CLOUD_NAME'), api_key=os.getenv('API_KEY'),
api_secret=os.getenv('API_SECRET'))
SECRET_KEY = os.getenv('SECRET_KEY')
STRIPE_PUB_KEY = os.getenv('STRIPE_PUB_KEY')
STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY')
sentry_sdk.init(
dsn=os.getenv('DNS'),
integrations=[DjangoIntegration()],
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for performance monitoring.
# We recommend adjusting this value in production.
# traces_sample_rate=1.0,
# If you wish to associate users to errors (assuming you are using
# django.contrib.auth) you may enable sending PII data.
send_default_pii=False
)
DEBUG = os.getenv('DEBUG')
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', os.getenv('PIP')]
DEFAULT_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.humanize',
]
LOCAL_APPS = [
'core.apps.CoreConfig',
'cart.apps.CartConfig',
'order.apps.OrderConfig',
'review.apps.ReviewConfig',
'product.apps.ProductConfig',
'vendor.apps.VendorConfig',
'blog.apps.BlogConfig',
'customers.apps.CustomersConfig',
'wishlist.apps.WishlistConfig',
'newsletter.apps.NewsletterConfig',
]
THIRD_PARTY_APPS = [
'cloudinary',
'django_countries',
'crispy_forms',
'crispy_tailwind',
'taggit',
'captcha',
'debug_toolbar',
'django_celery_results',
]
INSTALLED_APPS = DEFAULT_APPS + LOCAL_APPS + THIRD_PARTY_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ROOT_URLCONF = 'Project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'cart.context_processors.cart',
],
},
},
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'lomofy_cache',
}
}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
}
# CACHES = {
# "default": {
# "BACKEND": "django_redis.cache.RedisCache",
# "LOCATION": "redis://127.0.0.1:6379/1",
# "OPTIONS": {
# "CLIENT_CLASS": "django_redis.client.DefaultClient"
# },
# "KEY_PREFIX": "example"
# }
# }
# INTERNAL_IPS = [
# '127.0.0.1',
# ]
SITE_ID = 1
WSGI_APPLICATION = 'Project.wsgi.application'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Custom user model
AUTH_USER_MODEL = "customers.User"
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = os.getenv('TIME_ZONE')
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files configuration
STATIC_URL = '/static/'
CRISPY_TEMPLATE_PACK = "bootstrap4"
CRISPY_ALLOWED_TEMPLATE_PACKS = "tailwind"
CRISPY_TEMPLATE_PACK = "tailwind"
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [BASE_DIR / 'static']
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Mail configrations
EMAIL_HOST = os.getenv('EMAIL_HOST')
EMAIL_PORT = os.getenv('EMAIL_PORT')
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD')
EMAIL_USE_SSL = os.getenv('EMAIL_USE_SSL')
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
# Google reCAPTCHA
RECAPTCHA_PUBLIC_KEY = os.getenv('RECAPTCHA_PUBLIC_KEY')
RECAPTCHA_PRIVATE_KEY = os.getenv('RECAPTCHA_PRIVATE_KEY')
# Session configuration
CART_SESSION_ID = 'cart'
SESSION_COOKIE_AGE = 86400 # 24 hours in seconds
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# Celery Configurations
CELERY_BROKER_URL = 'redis://127.0.0.1:6379'
# CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379'
CELERY_RESULT_BACKEND = 'django-db'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = os.getenv('TIME_ZONE')
LOGIN_URL = 'customer_sign_in'
LOGIN_REDIRECT_URL = '/'
LOGOUT_URL = 'customer_sign_out'
LOGOUT_REDIRECT_URL = 'customer_sign_in'
# Security Principles
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True
CSRF_COOKIE_SECURE = True
# Activate Django-Heroku.
if 'HEROKU' in os.environ:
import django_heroku
django_heroku.settings(locals()) | Project/settings.py | import os
from pathlib import Path
import cloudinary
import cloudinary.api
import cloudinary.uploader
import sentry_sdk
from dotenv import load_dotenv
from sentry_sdk.integrations.django import DjangoIntegration
load_dotenv() # take environment variables from .env.
BASE_DIR = Path(__file__).resolve().parent.parent
# cloudinary configration
cloudinary.config(cloud_name=os.getenv('CLOUD_NAME'), api_key=os.getenv('API_KEY'),
api_secret=os.getenv('API_SECRET'))
SECRET_KEY = os.getenv('SECRET_KEY')
STRIPE_PUB_KEY = os.getenv('STRIPE_PUB_KEY')
STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY')
sentry_sdk.init(
dsn=os.getenv('DNS'),
integrations=[DjangoIntegration()],
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for performance monitoring.
# We recommend adjusting this value in production.
# traces_sample_rate=1.0,
# If you wish to associate users to errors (assuming you are using
# django.contrib.auth) you may enable sending PII data.
send_default_pii=False
)
DEBUG = os.getenv('DEBUG')
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', os.getenv('PIP')]
DEFAULT_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.sitemaps',
'django.contrib.humanize',
]
LOCAL_APPS = [
'core.apps.CoreConfig',
'cart.apps.CartConfig',
'order.apps.OrderConfig',
'review.apps.ReviewConfig',
'product.apps.ProductConfig',
'vendor.apps.VendorConfig',
'blog.apps.BlogConfig',
'customers.apps.CustomersConfig',
'wishlist.apps.WishlistConfig',
'newsletter.apps.NewsletterConfig',
]
THIRD_PARTY_APPS = [
'cloudinary',
'django_countries',
'crispy_forms',
'crispy_tailwind',
'taggit',
'captcha',
'debug_toolbar',
'django_celery_results',
]
INSTALLED_APPS = DEFAULT_APPS + LOCAL_APPS + THIRD_PARTY_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ROOT_URLCONF = 'Project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'cart.context_processors.cart',
],
},
},
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'lomofy_cache',
}
}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
}
# CACHES = {
# "default": {
# "BACKEND": "django_redis.cache.RedisCache",
# "LOCATION": "redis://127.0.0.1:6379/1",
# "OPTIONS": {
# "CLIENT_CLASS": "django_redis.client.DefaultClient"
# },
# "KEY_PREFIX": "example"
# }
# }
# INTERNAL_IPS = [
# '127.0.0.1',
# ]
SITE_ID = 1
WSGI_APPLICATION = 'Project.wsgi.application'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Custom user model
AUTH_USER_MODEL = "customers.User"
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = os.getenv('TIME_ZONE')
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files configuration
STATIC_URL = '/static/'
CRISPY_TEMPLATE_PACK = "bootstrap4"
CRISPY_ALLOWED_TEMPLATE_PACKS = "tailwind"
CRISPY_TEMPLATE_PACK = "tailwind"
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [BASE_DIR / 'static']
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Mail configrations
EMAIL_HOST = os.getenv('EMAIL_HOST')
EMAIL_PORT = os.getenv('EMAIL_PORT')
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD')
EMAIL_USE_SSL = os.getenv('EMAIL_USE_SSL')
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
# Google reCAPTCHA
RECAPTCHA_PUBLIC_KEY = os.getenv('RECAPTCHA_PUBLIC_KEY')
RECAPTCHA_PRIVATE_KEY = os.getenv('RECAPTCHA_PRIVATE_KEY')
# Session configuration
CART_SESSION_ID = 'cart'
SESSION_COOKIE_AGE = 86400 # 24 hours in seconds
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# Celery Configurations
CELERY_BROKER_URL = 'redis://127.0.0.1:6379'
# CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379'
CELERY_RESULT_BACKEND = 'django-db'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = os.getenv('TIME_ZONE')
LOGIN_URL = 'customer_sign_in'
LOGIN_REDIRECT_URL = '/'
LOGOUT_URL = 'customer_sign_out'
LOGOUT_REDIRECT_URL = 'customer_sign_in'
# Security Principles
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True
CSRF_COOKIE_SECURE = True
# Activate Django-Heroku.
if 'HEROKU' in os.environ:
import django_heroku
django_heroku.settings(locals()) | 0.186169 | 0.053576 |
import pprint
import re # noqa: F401
import six
from swagger_client.configuration import Configuration
class CellSiteChannel(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 = {
'channel': 'int',
'latitude': 'float',
'longitude': 'float',
'qos': 'int'
}
attribute_map = {
'channel': 'channel',
'latitude': 'latitude',
'longitude': 'longitude',
'qos': 'qos'
}
def __init__(self, channel=None, latitude=None, longitude=None, qos=None, _configuration=None): # noqa: E501
"""CellSiteChannel - a model defined in Swagger""" # noqa: E501
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._channel = None
self._latitude = None
self._longitude = None
self._qos = None
self.discriminator = None
if channel is not None:
self.channel = channel
if latitude is not None:
self.latitude = latitude
if longitude is not None:
self.longitude = longitude
if qos is not None:
self.qos = qos
@property
def channel(self):
"""Gets the channel of this CellSiteChannel. # noqa: E501
:return: The channel of this CellSiteChannel. # noqa: E501
:rtype: int
"""
return self._channel
@channel.setter
def channel(self, channel):
"""Sets the channel of this CellSiteChannel.
:param channel: The channel of this CellSiteChannel. # noqa: E501
:type: int
"""
self._channel = channel
@property
def latitude(self):
"""Gets the latitude of this CellSiteChannel. # noqa: E501
:return: The latitude of this CellSiteChannel. # noqa: E501
:rtype: float
"""
return self._latitude
@latitude.setter
def latitude(self, latitude):
"""Sets the latitude of this CellSiteChannel.
:param latitude: The latitude of this CellSiteChannel. # noqa: E501
:type: float
"""
self._latitude = latitude
@property
def longitude(self):
"""Gets the longitude of this CellSiteChannel. # noqa: E501
:return: The longitude of this CellSiteChannel. # noqa: E501
:rtype: float
"""
return self._longitude
@longitude.setter
def longitude(self, longitude):
"""Sets the longitude of this CellSiteChannel.
:param longitude: The longitude of this CellSiteChannel. # noqa: E501
:type: float
"""
self._longitude = longitude
@property
def qos(self):
"""Gets the qos of this CellSiteChannel. # noqa: E501
:return: The qos of this CellSiteChannel. # noqa: E501
:rtype: int
"""
return self._qos
@qos.setter
def qos(self, qos):
"""Sets the qos of this CellSiteChannel.
:param qos: The qos of this CellSiteChannel. # noqa: E501
:type: int
"""
self._qos = qos
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(CellSiteChannel, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CellSiteChannel):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, CellSiteChannel):
return True
return self.to_dict() != other.to_dict() | Wigle/python-client/swagger_client/models/cell_site_channel.py | import pprint
import re # noqa: F401
import six
from swagger_client.configuration import Configuration
class CellSiteChannel(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 = {
'channel': 'int',
'latitude': 'float',
'longitude': 'float',
'qos': 'int'
}
attribute_map = {
'channel': 'channel',
'latitude': 'latitude',
'longitude': 'longitude',
'qos': 'qos'
}
def __init__(self, channel=None, latitude=None, longitude=None, qos=None, _configuration=None): # noqa: E501
"""CellSiteChannel - a model defined in Swagger""" # noqa: E501
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._channel = None
self._latitude = None
self._longitude = None
self._qos = None
self.discriminator = None
if channel is not None:
self.channel = channel
if latitude is not None:
self.latitude = latitude
if longitude is not None:
self.longitude = longitude
if qos is not None:
self.qos = qos
@property
def channel(self):
"""Gets the channel of this CellSiteChannel. # noqa: E501
:return: The channel of this CellSiteChannel. # noqa: E501
:rtype: int
"""
return self._channel
@channel.setter
def channel(self, channel):
"""Sets the channel of this CellSiteChannel.
:param channel: The channel of this CellSiteChannel. # noqa: E501
:type: int
"""
self._channel = channel
@property
def latitude(self):
"""Gets the latitude of this CellSiteChannel. # noqa: E501
:return: The latitude of this CellSiteChannel. # noqa: E501
:rtype: float
"""
return self._latitude
@latitude.setter
def latitude(self, latitude):
"""Sets the latitude of this CellSiteChannel.
:param latitude: The latitude of this CellSiteChannel. # noqa: E501
:type: float
"""
self._latitude = latitude
@property
def longitude(self):
"""Gets the longitude of this CellSiteChannel. # noqa: E501
:return: The longitude of this CellSiteChannel. # noqa: E501
:rtype: float
"""
return self._longitude
@longitude.setter
def longitude(self, longitude):
"""Sets the longitude of this CellSiteChannel.
:param longitude: The longitude of this CellSiteChannel. # noqa: E501
:type: float
"""
self._longitude = longitude
@property
def qos(self):
"""Gets the qos of this CellSiteChannel. # noqa: E501
:return: The qos of this CellSiteChannel. # noqa: E501
:rtype: int
"""
return self._qos
@qos.setter
def qos(self, qos):
"""Sets the qos of this CellSiteChannel.
:param qos: The qos of this CellSiteChannel. # noqa: E501
:type: int
"""
self._qos = qos
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(CellSiteChannel, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CellSiteChannel):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, CellSiteChannel):
return True
return self.to_dict() != other.to_dict() | 0.772616 | 0.192862 |
import math
import os
import digitalio
import board
import time
from adafruit_rgb_display.rgb import color565
import adafruit_rgb_display.st7789 as st7789
from PIL import Image, ImageDraw, ImageFont
from fonts.ttf import RobotoMedium
import busio
import adafruit_vl53l0x
i2c = busio.I2C(board.SCL, board.SDA)
vl53 = adafruit_vl53l0x.VL53L0X(i2c)
# Configuration for CS and DC pins for Raspberry Pi
cs_pin = digitalio.DigitalInOut(board.CE0)
dc_pin = digitalio.DigitalInOut(board.D25)
reset_pin = None
BAUDRATE = 64000000 # The pi can be very fast!
# Create the ST7789 display:
display = st7789.ST7789(
board.SPI(),
cs=cs_pin,
dc=dc_pin,
rst=reset_pin,
baudrate=BAUDRATE,
width=135,
height=240,
x_offset=53,
y_offset=40,
)
FLIP = os.environ.get('FLIP', False)
WIDTH = display.height
HEIGHT = display.width
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
COLORS = [
(255, 0, 0),
(255, 128, 0),
(255, 255, 0),
(128, 255, 0),
(0, 255, 0),
(0, 255, 128),
(0, 255, 255),
(0, 128, 255),
(0, 0, 255),
(255, 0, 255),
(255, 0, 128),
]
COLORS_LENGTH = len(COLORS)
index = 0
font_ui = ImageFont.truetype(RobotoMedium, 64)
font = ImageFont.truetype(RobotoMedium, 32)
font_small = ImageFont.truetype(RobotoMedium, 32)
font_smiley = ImageFont.truetype('./CODE2000.TTF', 32)
img = Image.new("RGB", (WIDTH, HEIGHT), 0)
draw = ImageDraw.Draw(img)
index = 0
paused = False
threshold = -1
distances = []
DISTANCES_MAX_LEN = (WIDTH/4) if (WIDTH % 2 == 0) else ((WIDTH - 1)/4)
def format(distance):
if (distance > 1000):
return str(distance)[0:1] + ' m' + str(distance)[1:3]
if (distance > 100 and distance < 999):
return str(distance)[0:2] + 'cm' + str(distance)[2:3]
if (distance > 0 and distance < 99):
return str(distance)[0:2] + 'mm'
def get_ratio(distance, threshold):
return round((distance / threshold) * 100) / 100
def show_range(distance, ratio):
percent = str(round(ratio * 100)) + '%'
text = format(distance)
pw, ph = draw.textsize(percent, font=font_small)
draw.text((WIDTH - pw, HEIGHT - 64), percent, font=font_small, fill=WHITE)
draw.text((int(WIDTH * 0.6), HEIGHT - 32), text, font=font_small, fill=WHITE)
def show_credits():
global index
emoji = "¯\_(ツ)_/¯"
lw, lh = draw.textsize(emoji, font=font_smiley)
draw.text(((WIDTH/2) - (lw/2), int(HEIGHT*0.15)), emoji, font=font_smiley, fill=COLORS[index])
draw.text((0, int(HEIGHT*0.4)), "promethee", font=font, fill=COLORS[index])
draw.text((0, int(HEIGHT*0.7)), "@github", font=font, fill=COLORS[index])
backlight = digitalio.DigitalInOut(board.D22)
backlight.switch_to_output()
backlight.value = True
buttonA = digitalio.DigitalInOut(board.D23)
buttonB = digitalio.DigitalInOut(board.D24)
buttonA.switch_to_input()
buttonB.switch_to_input()
while True:
distance = vl53.range
if (distance > threshold):
threshold = distance
draw.rectangle((0, 0, WIDTH, HEIGHT), fill=BLACK)
if not buttonB.value:
FLIP = not FLIP
time.sleep(0.3)
if not buttonA.value:
paused = not paused
time.sleep(0.3)
if not paused:
index = index + 1 if index < len(COLORS) - 1 else 0
ratio = get_ratio(distance, threshold)
show_range(distance, ratio)
show_credits()
ROTATION = 270 if FLIP else 90
display.image(img, ROTATION) | main.py |
import math
import os
import digitalio
import board
import time
from adafruit_rgb_display.rgb import color565
import adafruit_rgb_display.st7789 as st7789
from PIL import Image, ImageDraw, ImageFont
from fonts.ttf import RobotoMedium
import busio
import adafruit_vl53l0x
i2c = busio.I2C(board.SCL, board.SDA)
vl53 = adafruit_vl53l0x.VL53L0X(i2c)
# Configuration for CS and DC pins for Raspberry Pi
cs_pin = digitalio.DigitalInOut(board.CE0)
dc_pin = digitalio.DigitalInOut(board.D25)
reset_pin = None
BAUDRATE = 64000000 # The pi can be very fast!
# Create the ST7789 display:
display = st7789.ST7789(
board.SPI(),
cs=cs_pin,
dc=dc_pin,
rst=reset_pin,
baudrate=BAUDRATE,
width=135,
height=240,
x_offset=53,
y_offset=40,
)
FLIP = os.environ.get('FLIP', False)
WIDTH = display.height
HEIGHT = display.width
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
COLORS = [
(255, 0, 0),
(255, 128, 0),
(255, 255, 0),
(128, 255, 0),
(0, 255, 0),
(0, 255, 128),
(0, 255, 255),
(0, 128, 255),
(0, 0, 255),
(255, 0, 255),
(255, 0, 128),
]
COLORS_LENGTH = len(COLORS)
index = 0
font_ui = ImageFont.truetype(RobotoMedium, 64)
font = ImageFont.truetype(RobotoMedium, 32)
font_small = ImageFont.truetype(RobotoMedium, 32)
font_smiley = ImageFont.truetype('./CODE2000.TTF', 32)
img = Image.new("RGB", (WIDTH, HEIGHT), 0)
draw = ImageDraw.Draw(img)
index = 0
paused = False
threshold = -1
distances = []
DISTANCES_MAX_LEN = (WIDTH/4) if (WIDTH % 2 == 0) else ((WIDTH - 1)/4)
def format(distance):
if (distance > 1000):
return str(distance)[0:1] + ' m' + str(distance)[1:3]
if (distance > 100 and distance < 999):
return str(distance)[0:2] + 'cm' + str(distance)[2:3]
if (distance > 0 and distance < 99):
return str(distance)[0:2] + 'mm'
def get_ratio(distance, threshold):
return round((distance / threshold) * 100) / 100
def show_range(distance, ratio):
percent = str(round(ratio * 100)) + '%'
text = format(distance)
pw, ph = draw.textsize(percent, font=font_small)
draw.text((WIDTH - pw, HEIGHT - 64), percent, font=font_small, fill=WHITE)
draw.text((int(WIDTH * 0.6), HEIGHT - 32), text, font=font_small, fill=WHITE)
def show_credits():
global index
emoji = "¯\_(ツ)_/¯"
lw, lh = draw.textsize(emoji, font=font_smiley)
draw.text(((WIDTH/2) - (lw/2), int(HEIGHT*0.15)), emoji, font=font_smiley, fill=COLORS[index])
draw.text((0, int(HEIGHT*0.4)), "promethee", font=font, fill=COLORS[index])
draw.text((0, int(HEIGHT*0.7)), "@github", font=font, fill=COLORS[index])
backlight = digitalio.DigitalInOut(board.D22)
backlight.switch_to_output()
backlight.value = True
buttonA = digitalio.DigitalInOut(board.D23)
buttonB = digitalio.DigitalInOut(board.D24)
buttonA.switch_to_input()
buttonB.switch_to_input()
while True:
distance = vl53.range
if (distance > threshold):
threshold = distance
draw.rectangle((0, 0, WIDTH, HEIGHT), fill=BLACK)
if not buttonB.value:
FLIP = not FLIP
time.sleep(0.3)
if not buttonA.value:
paused = not paused
time.sleep(0.3)
if not paused:
index = index + 1 if index < len(COLORS) - 1 else 0
ratio = get_ratio(distance, threshold)
show_range(distance, ratio)
show_credits()
ROTATION = 270 if FLIP else 90
display.image(img, ROTATION) | 0.419291 | 0.199347 |
import random
import numpy as np
from scipy.stats import norm
import time
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.gridspec as gridspec
# From Theano tutorial - MNIST dataset
from logistic_sgd import load_data
import theano
import theano.tensor as T
start_time = time.time()
n_latent = 10
n_hidden = 500
n_input = 28*28
# Right now the code only works with one expectation (like the article), but this can be easily fixed
n_expectations = 1
batch_size = 100
n_epochs = 25000
random.seed(0)
np.random.seed(1)
# The functions below were adapted from the amazing Theano tutorial by Newmu
# https://github.com/Newmu/Theano-Tutorials
def floatX(X):
return np.asarray(X, dtype=theano.config.floatX)
def init_weights(shape):
return theano.shared(floatX(np.random.randn(*shape) * 0.01))
def sgd(cost, params, lr=0.05, momentum = 0.9):
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
acc = theano.shared(p.get_value() * 0.)
acc_new = acc*momentum + (1.0-momentum)*g
updates.append([acc, acc_new])
updates.append([p, p - acc_new * lr])
return updates
def adagrad(cost, params, lr=0.001, epsilon=1e-6):
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
acc = theano.shared(p.get_value() * 0.)
acc_new = acc + g ** 2
gradient_scaling = T.sqrt(acc_new + epsilon)
g = g / gradient_scaling
updates.append((acc, acc_new))
updates.append((p, p - lr * g))
return updates
def RMSprop(cost, params, lr=0.001, rho=0.9, epsilon=1e-6):
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
acc = theano.shared(p.get_value() * 0.)
acc_new = rho * acc + (1 - rho) * g ** 2
gradient_scaling = T.sqrt(acc_new + epsilon)
g = g / gradient_scaling
updates.append((acc, acc_new))
updates.append((p, p - lr * g))
return updates
# Parameters
# Gaussian MLP weights and biases (encoder)
gaussian_bh = init_weights((n_hidden, ))
mu_bo = init_weights((n_latent, ))
sigma_bo = init_weights((n_latent, ))
gaussian_Wh = init_weights((n_input, n_hidden))
mu_Wo = init_weights((n_hidden, n_latent))
sigma_Wo = init_weights((n_hidden, n_latent))
# Bernoulli MLP weights and biases (decoder)
bernoulli_bh = init_weights((n_hidden, ))
bernoulli_bo = init_weights((n_input, ))
bernoulli_Wh = init_weights((n_latent, n_hidden))
bernoulli_Wo = init_weights((n_hidden, n_input))
# Only the weight matrices W will be regularized (weight decay)
W = [gaussian_Wh, mu_Wo, sigma_Wo, bernoulli_Wh, bernoulli_Wo]
b = [gaussian_bh, mu_bo, sigma_bo, bernoulli_bh, bernoulli_bo]
params = W + b
# Gaussian Encoder
x = T.matrix("x")
h_encoder = T.tanh(T.dot(x, gaussian_Wh) + gaussian_bh)
mu = T.dot(h_encoder, mu_Wo) + mu_bo
log_sigma = 0.5*(T.dot(h_encoder, sigma_Wo) + sigma_bo)
# This expression is simple (not an expectation) because we're using normal priors and posteriors
DKL = (1.0 + 2.0*log_sigma - mu**2 - T.exp(2.0*log_sigma)).sum(axis = 1)/2.0
# Bernoulli Decoder
std_normal = T.matrix("std_normal")
z = mu + T.exp(log_sigma)*std_normal
h_decoder = T.tanh(T.dot(z, bernoulli_Wh) + bernoulli_bh)
y = T.nnet.sigmoid(T.dot(h_decoder, bernoulli_Wo) + bernoulli_bo)
log_likelihood = -T.nnet.binary_crossentropy(y, x).sum(axis = 1)
# Lower bound
lower_bound = -(DKL + log_likelihood).mean()
# Weight decay
L2 = sum([(w**2).sum() for w in W])
cost = lower_bound + batch_size/50000.0/2.0*L2
#updates = sgd(lower_bound, params, lr = 0.001)
updates = RMSprop(cost, params, lr=0.001)
#updates = adagrad(lower_bound, params, lr=0.02)
train_model = theano.function(inputs=[x, std_normal],
outputs=cost,
updates=updates,
mode='FAST_RUN',
allow_input_downcast=True)
eval_model = theano.function(inputs=[x, std_normal], outputs=lower_bound,
mode='FAST_RUN',
allow_input_downcast=True)
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
# Load MNIST and binarize it
datasets = load_data('mnist.pkl.gz')
train_x, _ = datasets[0]
train_x = 1.0*(train_x > 0.5)
val_x, _ = datasets[1]
val_x = 1.0*(val_x > 0.5)
tx = theano.function([], T.concatenate([train_x, val_x]))()
# Using the test set as validation
tst_x, _ = datasets[2]
tst_x = 1.0*(tst_x > 0.5)
vx = theano.function([], tst_x)()
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
training = []
validation = []
for i in range(n_epochs):
minibatch_train = [ tx[j] for j in random.sample(xrange(len(tx)), batch_size) ]
val_cost = eval_model(vx, np.random.normal(size = (len(vx), n_latent)))
train_cost = train_model(minibatch_train, np.random.normal(size = (batch_size, n_latent)))
print "epoch", i, "train", train_cost, "val", val_cost
training.append(train_cost)
validation.append(val_cost)
plt.subplot(211)
plt.ylabel("-Lower bound")
plt.xlabel("Minibatch (" + str(batch_size) + " samples)")
plt.plot(training, label = "Train")
plt.legend()
plt.subplot(212)
plt.ylabel("-Lower bound")
plt.xlabel("Minibatch (" + str(batch_size) + " samples)")
plt.plot(validation, 'r', label = "Validation")
plt.legend()
plt.show()
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
# Now let's test the auto-encoder on some visual problems
# "Deterministic" decoder (uses only the mean of the Gaussian encoder)
t = T.vector()
h_mu = T.tanh(T.dot(t, gaussian_Wh) + gaussian_bh)
h_bern = T.tanh(T.dot(T.dot(h_mu, mu_Wo) + mu_bo, bernoulli_Wh) + bernoulli_bh)
yt = T.nnet.sigmoid(T.dot(h_bern, bernoulli_Wo) + bernoulli_bo)
test_input = theano.function([t], yt,
mode='FAST_RUN',
allow_input_downcast=True)
# Reconstruct some random images (with optional salt and peper noise)
salt_pepper = 0.2
plt.figure()#figsize = (5, 2))
gs1 = gridspec.GridSpec(5, 2)
gs1.update(wspace=0.0, hspace=0.0) # set the spacing between axes.
for i in range(5):
test = vx[random.randint(0, len(vx))]
test = np.array([test[j] if u > salt_pepper else np.random.choice([0, 1]) for u, j in zip(np.random.uniform(size = n_input), range(n_input))])
plt.subplot(gs1[2*i])
plt.axis('off')
plt.imshow(test.reshape((28, 28)), cmap = cm.Greys_r)
plt.subplot(gs1[2*i + 1])
plt.axis('off')
plt.imshow(test_input(test).reshape((28, 28)), cmap = cm.Greys_r)
plt.show()
# Now let's visualize the learned manifold
# We only need the decoder for this (and some way to generate latent variables)
t = T.vector()
h = T.tanh(T.dot(t, bernoulli_Wh) + bernoulli_bh)
yt = T.nnet.sigmoid(T.dot(h, bernoulli_Wo) + bernoulli_bo)
visualize = theano.function([t], yt,
mode='FAST_RUN',
allow_input_downcast=True)
# Size of visualizations
size = 10
# For 2 latent variables the manifold can be fully explored on a grid
plt.figure(figsize = (size, size))
gs1 = gridspec.GridSpec(size, size)
gs1.update(wspace=0.0, hspace=0.0) # set the spacing between axes.
ppf = np.linspace(1E-3, 1.0 - 1E-3, size)
if n_latent == 2:
for i in range(size):
for j in range(size):
plt.subplot(gs1[size*i + j])
plt.axis('off')
image = 1.0 - visualize([norm.ppf(ppf[i]), norm.ppf(ppf[j])])
plt.imshow(image.reshape((28, 28)), cmap = cm.Greys_r)
plt.show()
# For any number of latent variables you can sample them and generate fake data
plt.figure(figsize = (size, size))
gs1 = gridspec.GridSpec(size, size)
gs1.update(wspace=0.0, hspace=0.0) # set the spacing between axes.
for i in range(size):
for j in range(size):
plt.subplot(gs1[size*i + j])
plt.axis('off')
image = 1.0 - visualize(np.random.normal(0, 1.0, size = n_latent))
plt.imshow(image.reshape((28, 28)), cmap = cm.Greys_r)
plt.show()
print("--- %s seconds ---" % (time.time() - start_time)) | hard-gists/651afb13d45e4c587f63/snippet.py | import random
import numpy as np
from scipy.stats import norm
import time
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.gridspec as gridspec
# From Theano tutorial - MNIST dataset
from logistic_sgd import load_data
import theano
import theano.tensor as T
start_time = time.time()
n_latent = 10
n_hidden = 500
n_input = 28*28
# Right now the code only works with one expectation (like the article), but this can be easily fixed
n_expectations = 1
batch_size = 100
n_epochs = 25000
random.seed(0)
np.random.seed(1)
# The functions below were adapted from the amazing Theano tutorial by Newmu
# https://github.com/Newmu/Theano-Tutorials
def floatX(X):
return np.asarray(X, dtype=theano.config.floatX)
def init_weights(shape):
return theano.shared(floatX(np.random.randn(*shape) * 0.01))
def sgd(cost, params, lr=0.05, momentum = 0.9):
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
acc = theano.shared(p.get_value() * 0.)
acc_new = acc*momentum + (1.0-momentum)*g
updates.append([acc, acc_new])
updates.append([p, p - acc_new * lr])
return updates
def adagrad(cost, params, lr=0.001, epsilon=1e-6):
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
acc = theano.shared(p.get_value() * 0.)
acc_new = acc + g ** 2
gradient_scaling = T.sqrt(acc_new + epsilon)
g = g / gradient_scaling
updates.append((acc, acc_new))
updates.append((p, p - lr * g))
return updates
def RMSprop(cost, params, lr=0.001, rho=0.9, epsilon=1e-6):
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
acc = theano.shared(p.get_value() * 0.)
acc_new = rho * acc + (1 - rho) * g ** 2
gradient_scaling = T.sqrt(acc_new + epsilon)
g = g / gradient_scaling
updates.append((acc, acc_new))
updates.append((p, p - lr * g))
return updates
# Parameters
# Gaussian MLP weights and biases (encoder)
gaussian_bh = init_weights((n_hidden, ))
mu_bo = init_weights((n_latent, ))
sigma_bo = init_weights((n_latent, ))
gaussian_Wh = init_weights((n_input, n_hidden))
mu_Wo = init_weights((n_hidden, n_latent))
sigma_Wo = init_weights((n_hidden, n_latent))
# Bernoulli MLP weights and biases (decoder)
bernoulli_bh = init_weights((n_hidden, ))
bernoulli_bo = init_weights((n_input, ))
bernoulli_Wh = init_weights((n_latent, n_hidden))
bernoulli_Wo = init_weights((n_hidden, n_input))
# Only the weight matrices W will be regularized (weight decay)
W = [gaussian_Wh, mu_Wo, sigma_Wo, bernoulli_Wh, bernoulli_Wo]
b = [gaussian_bh, mu_bo, sigma_bo, bernoulli_bh, bernoulli_bo]
params = W + b
# Gaussian Encoder
x = T.matrix("x")
h_encoder = T.tanh(T.dot(x, gaussian_Wh) + gaussian_bh)
mu = T.dot(h_encoder, mu_Wo) + mu_bo
log_sigma = 0.5*(T.dot(h_encoder, sigma_Wo) + sigma_bo)
# This expression is simple (not an expectation) because we're using normal priors and posteriors
DKL = (1.0 + 2.0*log_sigma - mu**2 - T.exp(2.0*log_sigma)).sum(axis = 1)/2.0
# Bernoulli Decoder
std_normal = T.matrix("std_normal")
z = mu + T.exp(log_sigma)*std_normal
h_decoder = T.tanh(T.dot(z, bernoulli_Wh) + bernoulli_bh)
y = T.nnet.sigmoid(T.dot(h_decoder, bernoulli_Wo) + bernoulli_bo)
log_likelihood = -T.nnet.binary_crossentropy(y, x).sum(axis = 1)
# Lower bound
lower_bound = -(DKL + log_likelihood).mean()
# Weight decay
L2 = sum([(w**2).sum() for w in W])
cost = lower_bound + batch_size/50000.0/2.0*L2
#updates = sgd(lower_bound, params, lr = 0.001)
updates = RMSprop(cost, params, lr=0.001)
#updates = adagrad(lower_bound, params, lr=0.02)
train_model = theano.function(inputs=[x, std_normal],
outputs=cost,
updates=updates,
mode='FAST_RUN',
allow_input_downcast=True)
eval_model = theano.function(inputs=[x, std_normal], outputs=lower_bound,
mode='FAST_RUN',
allow_input_downcast=True)
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
# Load MNIST and binarize it
datasets = load_data('mnist.pkl.gz')
train_x, _ = datasets[0]
train_x = 1.0*(train_x > 0.5)
val_x, _ = datasets[1]
val_x = 1.0*(val_x > 0.5)
tx = theano.function([], T.concatenate([train_x, val_x]))()
# Using the test set as validation
tst_x, _ = datasets[2]
tst_x = 1.0*(tst_x > 0.5)
vx = theano.function([], tst_x)()
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
training = []
validation = []
for i in range(n_epochs):
minibatch_train = [ tx[j] for j in random.sample(xrange(len(tx)), batch_size) ]
val_cost = eval_model(vx, np.random.normal(size = (len(vx), n_latent)))
train_cost = train_model(minibatch_train, np.random.normal(size = (batch_size, n_latent)))
print "epoch", i, "train", train_cost, "val", val_cost
training.append(train_cost)
validation.append(val_cost)
plt.subplot(211)
plt.ylabel("-Lower bound")
plt.xlabel("Minibatch (" + str(batch_size) + " samples)")
plt.plot(training, label = "Train")
plt.legend()
plt.subplot(212)
plt.ylabel("-Lower bound")
plt.xlabel("Minibatch (" + str(batch_size) + " samples)")
plt.plot(validation, 'r', label = "Validation")
plt.legend()
plt.show()
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
# Now let's test the auto-encoder on some visual problems
# "Deterministic" decoder (uses only the mean of the Gaussian encoder)
t = T.vector()
h_mu = T.tanh(T.dot(t, gaussian_Wh) + gaussian_bh)
h_bern = T.tanh(T.dot(T.dot(h_mu, mu_Wo) + mu_bo, bernoulli_Wh) + bernoulli_bh)
yt = T.nnet.sigmoid(T.dot(h_bern, bernoulli_Wo) + bernoulli_bo)
test_input = theano.function([t], yt,
mode='FAST_RUN',
allow_input_downcast=True)
# Reconstruct some random images (with optional salt and peper noise)
salt_pepper = 0.2
plt.figure()#figsize = (5, 2))
gs1 = gridspec.GridSpec(5, 2)
gs1.update(wspace=0.0, hspace=0.0) # set the spacing between axes.
for i in range(5):
test = vx[random.randint(0, len(vx))]
test = np.array([test[j] if u > salt_pepper else np.random.choice([0, 1]) for u, j in zip(np.random.uniform(size = n_input), range(n_input))])
plt.subplot(gs1[2*i])
plt.axis('off')
plt.imshow(test.reshape((28, 28)), cmap = cm.Greys_r)
plt.subplot(gs1[2*i + 1])
plt.axis('off')
plt.imshow(test_input(test).reshape((28, 28)), cmap = cm.Greys_r)
plt.show()
# Now let's visualize the learned manifold
# We only need the decoder for this (and some way to generate latent variables)
t = T.vector()
h = T.tanh(T.dot(t, bernoulli_Wh) + bernoulli_bh)
yt = T.nnet.sigmoid(T.dot(h, bernoulli_Wo) + bernoulli_bo)
visualize = theano.function([t], yt,
mode='FAST_RUN',
allow_input_downcast=True)
# Size of visualizations
size = 10
# For 2 latent variables the manifold can be fully explored on a grid
plt.figure(figsize = (size, size))
gs1 = gridspec.GridSpec(size, size)
gs1.update(wspace=0.0, hspace=0.0) # set the spacing between axes.
ppf = np.linspace(1E-3, 1.0 - 1E-3, size)
if n_latent == 2:
for i in range(size):
for j in range(size):
plt.subplot(gs1[size*i + j])
plt.axis('off')
image = 1.0 - visualize([norm.ppf(ppf[i]), norm.ppf(ppf[j])])
plt.imshow(image.reshape((28, 28)), cmap = cm.Greys_r)
plt.show()
# For any number of latent variables you can sample them and generate fake data
plt.figure(figsize = (size, size))
gs1 = gridspec.GridSpec(size, size)
gs1.update(wspace=0.0, hspace=0.0) # set the spacing between axes.
for i in range(size):
for j in range(size):
plt.subplot(gs1[size*i + j])
plt.axis('off')
image = 1.0 - visualize(np.random.normal(0, 1.0, size = n_latent))
plt.imshow(image.reshape((28, 28)), cmap = cm.Greys_r)
plt.show()
print("--- %s seconds ---" % (time.time() - start_time)) | 0.734691 | 0.479321 |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import os
import json
from bs4 import BeautifulSoup
import requests
import re
import datetime
from mp.models import Config
def get_one(request):
myconfig = Config.objects.all().first()
if myconfig.apichange:
res = requests.get(url=myconfig.otherapi+"/one")
return HttpResponse(json.dumps(json.loads(res.text), ensure_ascii=False),
content_type="application/json,charset=utf-8")
with open('one.txt', mode='r', encoding='utf-8') as f:
if os.path.exists('one.txt'):
lines = f.readlines()
last_line = lines[-1]
# print(last_line)
if datetime.datetime.now().strftime('%Y-%m-%d') in last_line:
# print('读取模式')
content = last_line[12:]
return HttpResponse(json.dumps({'msg':'success','content':content}, ensure_ascii=False),
content_type="application/json,charset=utf-8")
elif int(datetime.datetime.now().strftime('%H')) < 8:
content = last_line[12:]
return HttpResponse(json.dumps({'msg':'success','content':content}, ensure_ascii=False),
content_type="application/json,charset=utf-8")
else:
with open('one.txt', mode='a', encoding='utf-8') as n:
# print('第一个访问了one!')
url = "http://wufazhuce.com/"
r = requests.get(url)
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text, 'html.parser')
oneall = soup.find('div', class_=re.compile('fp-one-cita'))
one = oneall.a.string
if int(datetime.datetime.now().strftime('%H')) > 8: # 每天九点后one肯定更新了
n.write('\n【%s】%s' % (datetime.datetime.now().strftime('%Y-%m-%d'), one))
return HttpResponse(json.dumps({'msg':'success','content':one}, ensure_ascii=False),
content_type="application/json,charset=utf-8")
else:
return HttpResponse(json.dumps({'msg':'error','content':"提醒管理员配置每日一言"}, ensure_ascii=False),
content_type="application/json,charset=utf-8") | zfnweb/one/views.py | from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import os
import json
from bs4 import BeautifulSoup
import requests
import re
import datetime
from mp.models import Config
def get_one(request):
myconfig = Config.objects.all().first()
if myconfig.apichange:
res = requests.get(url=myconfig.otherapi+"/one")
return HttpResponse(json.dumps(json.loads(res.text), ensure_ascii=False),
content_type="application/json,charset=utf-8")
with open('one.txt', mode='r', encoding='utf-8') as f:
if os.path.exists('one.txt'):
lines = f.readlines()
last_line = lines[-1]
# print(last_line)
if datetime.datetime.now().strftime('%Y-%m-%d') in last_line:
# print('读取模式')
content = last_line[12:]
return HttpResponse(json.dumps({'msg':'success','content':content}, ensure_ascii=False),
content_type="application/json,charset=utf-8")
elif int(datetime.datetime.now().strftime('%H')) < 8:
content = last_line[12:]
return HttpResponse(json.dumps({'msg':'success','content':content}, ensure_ascii=False),
content_type="application/json,charset=utf-8")
else:
with open('one.txt', mode='a', encoding='utf-8') as n:
# print('第一个访问了one!')
url = "http://wufazhuce.com/"
r = requests.get(url)
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text, 'html.parser')
oneall = soup.find('div', class_=re.compile('fp-one-cita'))
one = oneall.a.string
if int(datetime.datetime.now().strftime('%H')) > 8: # 每天九点后one肯定更新了
n.write('\n【%s】%s' % (datetime.datetime.now().strftime('%Y-%m-%d'), one))
return HttpResponse(json.dumps({'msg':'success','content':one}, ensure_ascii=False),
content_type="application/json,charset=utf-8")
else:
return HttpResponse(json.dumps({'msg':'error','content':"提醒管理员配置每日一言"}, ensure_ascii=False),
content_type="application/json,charset=utf-8") | 0.099361 | 0.034521 |
import uuid
import django.db.models
from django.core.exceptions import ValidationError
from django.forms import CharField
from django.utils.translation import gettext_lazy as _
import shortuuid
def short_uuid4():
return shortuuid.encode(uuid.uuid4())
def decode(value):
"""Decode the value from ShortUUID to UUID.
Raises ValueError when the value is not valid.
"""
if not isinstance(value, str) or len(value) != 22:
raise ValueError('badly formed ShortUUID')
return shortuuid.decode(value)
class NativeShortUUIDFormField(CharField):
default_error_messages = {
'invalid': _('Enter a valid ShortUUID.'),
}
def to_python(self, value):
value = super().to_python(value)
if value in self.empty_values:
return None
try:
decode(value)
except ValueError:
raise ValidationError(self.error_messages['invalid'], code='invalid')
return value
class NativeShortUUIDField(django.db.models.UUIDField):
default_error_messages = {
'invalid': _('“%(value)s” is not a valid ShortUUID.'),
}
def __init__(self, verbose_name=None, **kwargs):
self.default_value = kwargs.get('default', None)
if self.default_value is uuid.uuid4:
kwargs['default'] = short_uuid4
super().__init__(verbose_name, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if self.default_value is uuid.uuid4:
kwargs['default'] = uuid.uuid4
return name, path, args, kwargs
def from_db_value(self, value, expression, connection):
if value is None:
return value
return shortuuid.encode(value)
def to_python(self, value):
if value is not None and not isinstance(value, uuid.UUID):
try:
return decode(value)
except ValueError:
raise ValidationError(
self.error_messages['invalid'],
code='invalid',
params={'value': value},
)
return value
def formfield(self, **kwargs):
return super().formfield(**{
'form_class': NativeShortUUIDFormField,
**kwargs,
}) | native_shortuuid/fields.py | import uuid
import django.db.models
from django.core.exceptions import ValidationError
from django.forms import CharField
from django.utils.translation import gettext_lazy as _
import shortuuid
def short_uuid4():
return shortuuid.encode(uuid.uuid4())
def decode(value):
"""Decode the value from ShortUUID to UUID.
Raises ValueError when the value is not valid.
"""
if not isinstance(value, str) or len(value) != 22:
raise ValueError('badly formed ShortUUID')
return shortuuid.decode(value)
class NativeShortUUIDFormField(CharField):
default_error_messages = {
'invalid': _('Enter a valid ShortUUID.'),
}
def to_python(self, value):
value = super().to_python(value)
if value in self.empty_values:
return None
try:
decode(value)
except ValueError:
raise ValidationError(self.error_messages['invalid'], code='invalid')
return value
class NativeShortUUIDField(django.db.models.UUIDField):
default_error_messages = {
'invalid': _('“%(value)s” is not a valid ShortUUID.'),
}
def __init__(self, verbose_name=None, **kwargs):
self.default_value = kwargs.get('default', None)
if self.default_value is uuid.uuid4:
kwargs['default'] = short_uuid4
super().__init__(verbose_name, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if self.default_value is uuid.uuid4:
kwargs['default'] = uuid.uuid4
return name, path, args, kwargs
def from_db_value(self, value, expression, connection):
if value is None:
return value
return shortuuid.encode(value)
def to_python(self, value):
if value is not None and not isinstance(value, uuid.UUID):
try:
return decode(value)
except ValueError:
raise ValidationError(
self.error_messages['invalid'],
code='invalid',
params={'value': value},
)
return value
def formfield(self, **kwargs):
return super().formfield(**{
'form_class': NativeShortUUIDFormField,
**kwargs,
}) | 0.542379 | 0.135032 |
import os
from functools import lru_cache
from aws_cdk.aws_efs import IAccessPoint
from aws_cdk.aws_lambda import Code, Runtime, FileSystem as LambdaFileSystem, Function
from aws_cdk.aws_s3 import Bucket
from aws_cdk.core import Stack, Duration
from aws_cdk.lambda_layer_awscli import AwsCliLayer
from b_cfn_s3_large_deployment.deployment_props import DeploymentProps
class S3LargeDeploymentFunction(Function):
from . import source
SOURCE_PATH = os.path.dirname(source.__file__)
def __init__(
self,
scope: Stack,
name: str,
destination_bucket: Bucket,
deployment_props: DeploymentProps,
mount_path: str = None,
access_point: IAccessPoint = None
) -> None:
if deployment_props.use_efs and (mount_path is None or access_point is None):
raise ValueError('While using EFS its access point and mount path must be set.')
self.__name = name
super().__init__(
scope=scope,
id=name,
function_name=name,
code=self.__code(),
timeout=Duration.minutes(15),
handler='main.index.handler',
runtime=Runtime.PYTHON_3_7,
layers=[
AwsCliLayer(scope, f'{name}AwsCliLayer')
],
environment=None if not deployment_props.use_efs else {
'MOUNT_PATH': mount_path
},
role=deployment_props.role,
memory_size=deployment_props.memory_limit,
vpc=deployment_props.vpc,
vpc_subnets=deployment_props.vpc_subnets,
filesystem=(
LambdaFileSystem.from_efs_access_point(access_point, mount_path)
if deployment_props.use_efs
else None
)
)
if deployment_props.vpc:
self.node.add_dependency(deployment_props.vpc)
if access_point:
self.node.add_dependency(access_point)
destination_bucket.grant_read_write(self)
@lru_cache
def __code(self) -> Code:
return Code.from_asset(self.SOURCE_PATH)
@property
def function_name(self):
return self.__name | b_cfn_s3_large_deployment/function.py | import os
from functools import lru_cache
from aws_cdk.aws_efs import IAccessPoint
from aws_cdk.aws_lambda import Code, Runtime, FileSystem as LambdaFileSystem, Function
from aws_cdk.aws_s3 import Bucket
from aws_cdk.core import Stack, Duration
from aws_cdk.lambda_layer_awscli import AwsCliLayer
from b_cfn_s3_large_deployment.deployment_props import DeploymentProps
class S3LargeDeploymentFunction(Function):
from . import source
SOURCE_PATH = os.path.dirname(source.__file__)
def __init__(
self,
scope: Stack,
name: str,
destination_bucket: Bucket,
deployment_props: DeploymentProps,
mount_path: str = None,
access_point: IAccessPoint = None
) -> None:
if deployment_props.use_efs and (mount_path is None or access_point is None):
raise ValueError('While using EFS its access point and mount path must be set.')
self.__name = name
super().__init__(
scope=scope,
id=name,
function_name=name,
code=self.__code(),
timeout=Duration.minutes(15),
handler='main.index.handler',
runtime=Runtime.PYTHON_3_7,
layers=[
AwsCliLayer(scope, f'{name}AwsCliLayer')
],
environment=None if not deployment_props.use_efs else {
'MOUNT_PATH': mount_path
},
role=deployment_props.role,
memory_size=deployment_props.memory_limit,
vpc=deployment_props.vpc,
vpc_subnets=deployment_props.vpc_subnets,
filesystem=(
LambdaFileSystem.from_efs_access_point(access_point, mount_path)
if deployment_props.use_efs
else None
)
)
if deployment_props.vpc:
self.node.add_dependency(deployment_props.vpc)
if access_point:
self.node.add_dependency(access_point)
destination_bucket.grant_read_write(self)
@lru_cache
def __code(self) -> Code:
return Code.from_asset(self.SOURCE_PATH)
@property
def function_name(self):
return self.__name | 0.417628 | 0.048812 |
from torch.nn import functional as F
from dassl.engine import TRAINER_REGISTRY, TrainerX
from dassl.metrics import compute_accuracy
from torch.cuda.amp import autocast
from dassl.utils import count_num_param
from dassl.optim import build_optimizer, build_lr_scheduler
from dassl.modeling import build_backbone
@TRAINER_REGISTRY.register()
class RSC(TrainerX):
"""RSC implementation from official repo."""
def check_cfg(self, cfg):
assert '_rsc' in cfg.MODEL.BACKBONE.NAME, 'please use model special for RSC'
def build_model(self):
cfg = self.cfg
print('Building model')
self.model = build_backbone(
cfg.MODEL.BACKBONE.NAME,
verbose=cfg.VERBOSE,
pretrained=cfg.MODEL.BACKBONE.PRETRAINED,
classes=self.num_classes
)
self.model.to(self.device)
print('# params: {:,}'.format(count_num_param(self.model)))
self.optim = build_optimizer(self.model, cfg.OPTIM)
self.sched = build_lr_scheduler(self.optim, cfg.OPTIM)
self.register_model('model', self.model, self.optim, self.sched)
def forward_backward(self, batch):
input, label = self.parse_batch_train(batch)
if self.use_amp:
with autocast():
output = self.model(input, label, flag=True, epoch=self.epoch)
loss = F.cross_entropy(output, label)
else:
output = self.model(input, label, flag=True, epoch=self.epoch)
loss = F.cross_entropy(output, label)
self.model_backward_and_update(loss)
loss_summary = {
'loss': loss.item(),
'acc': compute_accuracy(output, label)[0].item()
}
if (self.batch_idx + 1) == self.num_batches:
self.update_lr()
return loss_summary
def parse_batch_train(self, batch):
input = batch['img']
label = batch['label']
input = input.to(self.device)
label = label.to(self.device)
return input, label | dassl/engine/dg/rsc.py | from torch.nn import functional as F
from dassl.engine import TRAINER_REGISTRY, TrainerX
from dassl.metrics import compute_accuracy
from torch.cuda.amp import autocast
from dassl.utils import count_num_param
from dassl.optim import build_optimizer, build_lr_scheduler
from dassl.modeling import build_backbone
@TRAINER_REGISTRY.register()
class RSC(TrainerX):
"""RSC implementation from official repo."""
def check_cfg(self, cfg):
assert '_rsc' in cfg.MODEL.BACKBONE.NAME, 'please use model special for RSC'
def build_model(self):
cfg = self.cfg
print('Building model')
self.model = build_backbone(
cfg.MODEL.BACKBONE.NAME,
verbose=cfg.VERBOSE,
pretrained=cfg.MODEL.BACKBONE.PRETRAINED,
classes=self.num_classes
)
self.model.to(self.device)
print('# params: {:,}'.format(count_num_param(self.model)))
self.optim = build_optimizer(self.model, cfg.OPTIM)
self.sched = build_lr_scheduler(self.optim, cfg.OPTIM)
self.register_model('model', self.model, self.optim, self.sched)
def forward_backward(self, batch):
input, label = self.parse_batch_train(batch)
if self.use_amp:
with autocast():
output = self.model(input, label, flag=True, epoch=self.epoch)
loss = F.cross_entropy(output, label)
else:
output = self.model(input, label, flag=True, epoch=self.epoch)
loss = F.cross_entropy(output, label)
self.model_backward_and_update(loss)
loss_summary = {
'loss': loss.item(),
'acc': compute_accuracy(output, label)[0].item()
}
if (self.batch_idx + 1) == self.num_batches:
self.update_lr()
return loss_summary
def parse_batch_train(self, batch):
input = batch['img']
label = batch['label']
input = input.to(self.device)
label = label.to(self.device)
return input, label | 0.809803 | 0.308333 |
from discord.ext.commands import group
import math
import discord
class Math:
def __init__(self, bot):
self.bot = bot
@group(invoke_without_command=True, aliases=["maths"])
async def math(self, ctx):
"""Various mathematical functions, collected for your enjoyment."""
if ctx.invoked_subcommand is None:
pass
@math.group(name="circumference", aliases=["circ"])
async def _circumference(self, ctx):
"""Calculate the circumference of a circle given its radius or diameter."""
if ctx.invoked_subcommand is None:
pass
@_circumference.command(name="radius")
async def _radius(self, ctx, number: int):
"""Calculate the circumference of a circle given its radius."""
answer = (math.pi * 2) * number
await ctx.send(answer)
@_circumference.command(name="diameter")
async def _diameter(self, ctx, number: int):
"""Calculate the circumference of a circle given its diameter."""
answer = math.pi * number
await ctx.send(answer)
@math.command(name="power")
async def _power(self, ctx, number: int, power: int):
"""Calculate x raised to the power y."""
answer = math.pow(number, power)
await ctx.send(answer)
@math.command(name="root")
async def _root(self, ctx, number: int, degree: int=2):
"""Calculate the principal root of a number.
If no degree is given, calculates the square root."""
if degree == 2:
answer = math.sqrt(number)
else:
answer = math.pow(number, 1.0/degree)
await ctx.send(answer)
@group()
async def temp(self, ctx):
"""Commands to convert between different units of temperature."""
pass
@temp.command()
async def f(self, ctx, temperature: int):
"""Converts Fahrenheit Temperatures to Celsius Temperatures."""
ans = (temperature-32) * 5/9
await ctx.send(embed=discord.Embed(
title="Conversion",
description=f"{ans} °C",
color=discord.Color.dark_orange()
))
@temp.command()
async def c(self, ctx, temperature: int):
"""Converts Celsius Temperatures to Fahrenheit Temperatures."""
ans = (temperature*1.8)+32
await ctx.send(embed=discord.Embed(
title="Conversion",
description=f"{ans} °F",
color=discord.Color.dark_orange()
))
def setup(bot):
bot.add_cog(Math(bot)) | cogs/math.py | from discord.ext.commands import group
import math
import discord
class Math:
def __init__(self, bot):
self.bot = bot
@group(invoke_without_command=True, aliases=["maths"])
async def math(self, ctx):
"""Various mathematical functions, collected for your enjoyment."""
if ctx.invoked_subcommand is None:
pass
@math.group(name="circumference", aliases=["circ"])
async def _circumference(self, ctx):
"""Calculate the circumference of a circle given its radius or diameter."""
if ctx.invoked_subcommand is None:
pass
@_circumference.command(name="radius")
async def _radius(self, ctx, number: int):
"""Calculate the circumference of a circle given its radius."""
answer = (math.pi * 2) * number
await ctx.send(answer)
@_circumference.command(name="diameter")
async def _diameter(self, ctx, number: int):
"""Calculate the circumference of a circle given its diameter."""
answer = math.pi * number
await ctx.send(answer)
@math.command(name="power")
async def _power(self, ctx, number: int, power: int):
"""Calculate x raised to the power y."""
answer = math.pow(number, power)
await ctx.send(answer)
@math.command(name="root")
async def _root(self, ctx, number: int, degree: int=2):
"""Calculate the principal root of a number.
If no degree is given, calculates the square root."""
if degree == 2:
answer = math.sqrt(number)
else:
answer = math.pow(number, 1.0/degree)
await ctx.send(answer)
@group()
async def temp(self, ctx):
"""Commands to convert between different units of temperature."""
pass
@temp.command()
async def f(self, ctx, temperature: int):
"""Converts Fahrenheit Temperatures to Celsius Temperatures."""
ans = (temperature-32) * 5/9
await ctx.send(embed=discord.Embed(
title="Conversion",
description=f"{ans} °C",
color=discord.Color.dark_orange()
))
@temp.command()
async def c(self, ctx, temperature: int):
"""Converts Celsius Temperatures to Fahrenheit Temperatures."""
ans = (temperature*1.8)+32
await ctx.send(embed=discord.Embed(
title="Conversion",
description=f"{ans} °F",
color=discord.Color.dark_orange()
))
def setup(bot):
bot.add_cog(Math(bot)) | 0.718002 | 0.286609 |
from PySide2 import QtCore
qt_resource_data = b"\
\x00\x00\x08\xd9\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:22-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:22-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:1ad09ad6-ad8c\
-a841-85e1-6979b\
8143a60\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:8de390c5-9065-6\
344-9f4d-c5b1dfd\
386d1\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:1bf1db4\
3-1ff6-8446-bcef\
-7c036a4ca7fd\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:1bf1db43-1ff6\
-8446-bcef-7c036\
a4ca7fd\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:1a\
d09ad6-ad8c-a841\
-85e1-6979b8143a\
60\x22 stEvt:when=\x22\
2020-05-02T17:52\
:22-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>/\x0a\
T[\x00\x00\x02\x8eIDATH\xc7\x95\xd6K\xa8\
Uu\x18\x05\xf0\xdf>w\x1f\x8f\xf7X)W\xad \
*\xb4\x818\x08|\x5c\xc5A\xea@\x22%\xb8\x08b\
\x04A8\xd3\x89\x08!84q\x22\xa8H\x93P\x88\
\xa6\x91\xa3\x10tbc%\xd1FW-(\x92\x1e\xb7\
\xa2\xe8\xe2\xdb\xfb8\x1d'k\xc3F\xe4\xdc}\xfe\xa3\
\xbd\xf7\xff\xf1}k}k}\xff]LMMm\xc7\
~t\xd1\xc1#\xdc\xc5R\x8c\xe2\x7f\x83G+\xeb\x9f\
`9\xday\xfe\x07\xc7K\xbc\x81\xf7\xb08\x933\xb8\
\x8f\x17\xb1\x08\xfd\x05\x02\x14x\x80Y,K\xc0y\xfc\
\x8b\xcf\xcaD\x1d\xc3\x17\xb8\x85-\xf8\x00\xdf\xe0:^\
\x18\x80\xa2:\xfcC\xbc\x8d\xd3\xf8\x0b;\xb1\x03\x9d\xb2\
\x96\xe1'\xc9|\x1d\xf6$\xe0E\xcd\xc6\xcbx\x05\x87\
\xf3\xfeK\x02\xf4\xca\xf0\x05_\xe166`$t5\
\x1d3a\xe1<\xfe\xc0;\xa1\xac_\xa2\x97E\xdb\xb1\
5\xbc\xab!+\x06\xd4\xa1\x9a\xeb\xa1\xc4\xae<wS\
\x87\xa2\x85%Y\xbc6\xca\xd9\x95M\xa3C \x18\x8b\
jV\xa6\xd0\xfb\xab\xfdu\x04\xef\xe3&\xb6%\xb3\xf9\
!\x02\xccF\x0c\x13\xf8\x13\x9b\xaa\x89\x12\x8f\xf3|\x16\
\x0fk\x88\xe6\x1aPT\x8d{\xc9\xf8\xeb\xf8\xa8\x9b\xda\
\xf6[\xd1?\x1cJ\x06\xc7#\xcb\xea\xd0AF\xab\xd6\
\x8cF\xae\x1fcw\x92]\x84\xa2\x0c\x0a\xb8\x1c\x15\x8d\
dc\x85d!\x1f<\xcc\x9a\xc7\xb8\x10W\xbf\x19\xc3\
)\x03\x09\xae\xd4\x0a5\x82\xcfq\x22\x08\x07Q\xf4\x04\
+\x92\xd0\xcf\x98\xc6k\x15Ee\x15\x09\x93\xf8\x1b\xaf\
c3~\xc2o\x81:\x08\xc1,\xd6\xa7\xe5\xdc\x88Y\
{X]Q4ZS\xd1\xbd8\xf9{\x1c\xc5\xa5\x86\
*:\x83\x8f\xd2\xd3`oL\xa7\xee\xe4s\xe9#k\
\xf2\xde\x19BE\xbdx\xe8\xcb$\xb9\xb1\x92\x7fY\xd3\
\xfbD\xad\x06E\x836]\x0f>\x13*\xf7\xa4\xc8\xaf\
F\xe6\xfdV\x8d\xa2\x1dX\x85}9\xbc3\xa4\x93\xa7\
S\x8bU8\x12q\x14\xad\x1a\xfc\xb1\xdc\x01/5\xa4\
\xe5Y\x8a\x8a\xb4\xfe\xa59\xa7\xff\xac\x93/>\xc7\xfe\
M\xc7tz\xd0\xb5\xda\xb7G\x95L+*\x8e\xe1\xf7\
\xb4\xeb\x03\xc9\xc8\x02H\xaa\xb9n\x0e\xfc4\xc1\xdeM\
=\x8a\xb2\xd6\xf7\xcf\xa4@\xe3\x09P\x0e\x81\xa0\x9bV\
q2\xef\x0fr+\xaa\x1b\xedj.\x8b\xb7\x92\xfd)\
\x1c\x0c\xc2\xfe\x02\x97\xcdx\x9c|#\x08\xd6e\xae]\
\xe2\x07|\x9b\xaaw\xf1+~\x8c\xba\xda\x0d\xdav\x1b\
\xdfE\x96K\xb2o2~\xf8\xaf\xc4\x9d\x5c\xf0\xed\xf4\
\xa0\xb9d\xd5\xc9\xb7&\xbf-3Idq\xce\x98O\
\x13\xbc\xfb\x14\xda\xda\xae\xefmH\xe4\x14\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x07\xfc\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:07-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:07-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:ef0702ba-b962\
-ba4e-8545-0f067\
83ad6c7\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:59ab4f91-fae9-1\
648-a49a-8446708\
70d24\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:fe4bdc4\
2-6783-0e4e-b924\
-6fd37ef01f3c\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:fe4bdc42-6783\
-0e4e-b924-6fd37\
ef01f3c\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:ef\
0702ba-b962-ba4e\
-8545-0f06783ad6\
c7\x22 stEvt:when=\x22\
2020-05-02T17:52\
:07-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>j!\
`\x9b\x00\x00\x01\xb1IDATH\xc7\xd5\xd6=k\
TA\x14\x06\xe0'\x9b\x0d\xaeh\xac\x22)\x0cV\x22\
\xb2\x8d\x1fi\x82`TH%\xf1\x07h\xef?\xb0\xf2\
\x0f(6b/\x82\x85\x8d\x85\x8a\x88\x8d\x88h$Q\
D\xc4Bp\xc14\x82,\xa2\x85\x82\x9f\x89\x9bks\
\x06\xc6\xcb\xde\xb8{a\x0b\xdf\xe6\xce\xcc\x19\xe6=\xf3\
\x9e\x8f\xb9cEQ\x18%\x1aF\x8c\x91\x134\xbb\xdd\
n\x13'1\x83\x1e\xca\x9aM\xe03n\xe0\xe7\xd0\x04\
X\xc4\xcd\x01\xf6\xee\xc3\xb9:\x04{b|\x0a\xaf\xb0\
5\xb3\x17X\xc3E\x9c\xc5e|\x18\x96`=\xc6K\
x_\xb1\xef<N\xe0\x01\xde\xa2\x95\xd9\xc6C\xc2\xeb\
\xb8\xdd\x8f i>\xb5\x09\xc13\x5c\xc1\x1cv\x97l\
kX\xc0\xde*\x82A\xb0\x8e3\x9b\xd8\x1fcW\x95\
D\xfd\xb0\x0dm\xfc\xcen\xf8+\xe6c\xd9\xbe\x8d\x98\
Ob\x0b\x0e\xc4z\x0b\xab\xf8XEp\xe9\x1f\x1eW\
\xe1e6~\x82\xc5~\x04;q\x1a\x8f\x22k&\xfb\
\xd4F\x19\xbd,\xe0_#\x9d\xdb\x98\xc8\x09\xd2\xd5\xf7\
\x87D\xd7p\xabf\x01_\xc0S|j\x94\xf4\x84c\
\xf1]\x19\xf2\xd0\xe4\xe0\xc1\xc8\xa8\x87\xe5^\x94\xea\xe1\
p\xa4k\xa7\xa6\xf7\xc7C\xd2\x952\xc1\xb7\xf0b\x16\
w\x07\xd0\xbd\x8c\xb4\x7f\x01_R\xc0s\x82\x1f\xd1o\
v\xa4\xeb\xd5\x90\xa7\x85Cq\xf8\xf72A\x13G#\
\x16\xcfk\xca\xd3\x8e\x8ep?=\x079\xc1\xf6 \xe8\
\xe0]My\xe6\x22U\x97\xd3z#n\xb1\x81\xe9\xd0\
\xef^Tl\x1d\x1c\x89\x8aO\x0a\x14\xcd\xd0\xaf\x11\x0f\
\xcaT\xb4\xed\xd9xh\x06E*\xb4y\xdcI\xfa'\
\xdd\xdf\xe0E\xf4\x92N\x04y\xa6F\x90{x\x8d\xab\
\x7f\x19\xfe\xfb\xbf\x8a?\xb4\xdaaG\xaae\x1f\xa5\x00\
\x00\x00\x00IEND\xaeB`\x82\
\x00\x00\x07\xd2\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:16-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:16-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:3476f972-cae4\
-6d48-ab9f-9a222\
8765b33\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:448a63e8-7143-7\
946-9c7f-101d056\
7c61b\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:a1e841e\
e-d491-564b-9dfb\
-d9d4b815d32a\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:a1e841ee-d491\
-564b-9dfb-d9d4b\
815d32a\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:34\
76f972-cae4-6d48\
-ab9f-9a2228765b\
33\x22 stEvt:when=\x22\
2020-05-02T17:52\
:16-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>\xf0\xa7\
\x86\xec\x00\x00\x01\x87IDATH\xc7\xad\xd6\xcf+\
\x04a\x1c\xc7\xf1\xd9\xe4@)?j3\xfc\x03n\x0e\
\x948H\xcaA\xe1H\x9cD\x09)\x22\xbf)\xcaE\
)[\x946?\x8b3\x0erp\x92-\x8a\x838q\
\x90\x83\xc3\xc4\x81\x94D\xd1x?\xf9NMS\xa6\xf5\
\xcc\xf3\xd4\xabmvg\x9e\xcf<\xdfy\x9eg6\xe6\
\xba\xae\xe55\xc7q\xac@\x8b\xc1\xb54\x9am\xdb\xbf\
\x1d\x04\x02\xbc\x0es\xf0\x8eoK\xb3\xfd\x15\xa0>\xda\
\x90\xc4>\xfa\xf1\xac3\x9a\xb0\x00\xd5y\x97|\xf5\x84\
!\xec\xfc7$,`\x1b\xb5h\xc1\x02*p\x81>\
\x9c\x9b\x18\x81\xba\xdb\x06\x14\xc83\xe8\xc4\xbc\x1c\xab\xf0\
a<F\x0dhD\x1c\x9f\xf2\x93z\xe8\x09t\xe0K\
F\x93\x0c+[:#(\xc4G\xe0\xba2,\xa1\x12\
\x972\x09R\xba%\x0a\x06\xf8\xef\xb4\x15\xeb\xc8\xc2\x1e\
\xbaeBD\x1e\x81\xbf\xe5a\x0e\xbdr\xde\x18\x96\xbd\
\xb5c\x22\xc0k%XA\x0d\xae\xe5\xf9\xa4L\x05\xf8\
\xcb\xd6\x84]d\xa0\x8a\x80\xb3\xa8\x01\xfe\xces1\x8d\
A\xdc\xa3\x9e\x80[\x13#\xc8\xc4\x04f\xe4X-\xcc\
Y\xbc\x99(\x91\x7f\x01\x1e`\x00w\xba\xb3\xc8_\x8e\
R\xac\xa1\x1c\x0f2E\x0fM\xac\x83\x22,\xa2\x19/\
\x18\xc5\xaa\x89\xad\x22\x1bS\x18\x97\xd3\x12R\xf3W\xdd\
\xadBmhu(\x96\x91l \x1f\xc7\xe8\xc1M\xd4\
\xddt\x13\xed8A5\xae0\x82#So4\xb5\xfc\
'\xa5\xfe\xea\x8e\xb7t\xde\xd1a\x01q)\xd1\xa9,\
\x1a\xe3\xefd#-\xdd\x80\xc8\x7f[~\x00\xd5\xa3\xf5\
\xd1@\x7f+\x07\x00\x00\x00\x00IEND\xaeB`\
\x82\
\x00\x00\x08>\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:35-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:35-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:2421bcd1-daf2\
-e64b-a315-1fa31\
f4792db\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:e9017898-4533-a\
842-bed9-eee21b5\
72acd\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:698e21f\
5-b155-424d-9968\
-c165d7dfe6fc\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:698e21f5-b155\
-424d-9968-c165d\
7dfe6fc\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:24\
21bcd1-daf2-e64b\
-a315-1fa31f4792\
db\x22 stEvt:when=\x22\
2020-05-02T17:52\
:35-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>A\xdc\
-\xd9\x00\x00\x01\xf3IDATH\xc7\xd5\xd6=\x8f\
LQ\x18\x07\xf0\xdf\x9d\x1d\xbb\x98]/\xeb%\x22\x13\
\x0d\x8dF\xa1 \xaa\xad\xb4dE\xa1R\xd0\x13\xadN\
%\x1a\x14Z!\x11\xad\x0f\xb0\xf1\x0d\xd4\x0a\x11\x09\x09\
3\x11\x14\x8c\xec\xcc\xd8\x99\xb9\x0a\xcfM\xce\xde\x9c\x9d\
]\x89-\x9c\xe4\xe6\xe6>\xaf\xff\xe79\xff\xe7\x9c[\
\x94ei;W\xc36\xaff\xb7\xdb]D;I\x98\
\x964\x89g\x06E\xcd\xb7\x0c]\x91\x01Zb\x8cw\
M\x5c\xc2#\xccm\x00b8E7\xc0\xce\x0dt\xdf\
\xb1\xd4\x0c\x839\xdc\xc5\xc7\x04\xcd\x18\xd7q\x1a\xb70\
\xaa!<\x8a\xdbx\x81\x97Qe\xe5w\x1e\xcb(\x9a\
\x89\xe2>\xbe\xd6P\x9c\xc2q<\xcc <\x98$x\
\x9eA\xbf\x8c2\xedy;\x13dO\xf48mCQ\
\xb3\xdf\x9f\xf1;\x94cQ\x8e\xaf\xd38\xbc%]#\
\x83\xcc&\xb2\xbf\xd2\xa5\x09\xfa\x19\xc3_a<\xcc\xa0\
\xeb'\x9b\x9ac\xde\x9f9H\x84\xf3\xf1\xde\x1d\xfc\x1e\
`G\x04\x5c\x08\xa7j\x1e\xfah\x85\xfdl\xbc[a\
\xbb\x8a]i\x82\x0a\xc9\x0az\xb1\xa1e$8\x12\x01\
\xde\x84\xac\xaax-\x82\x94\xb8\x83\x1bI\xc2~l\xf2\
\x00e3qz\x8d/\x11p\x1c\xcfY\x1c\xc6\xab\xf8\
\xae*X\xc3\x22\x96\xf0\x01o\x93J\xd6p\x12'\xaa\
9\xa8(x\x15\xefk\xbd|\x1c\x93~!\xd3\xe7c\
\x11\xfc\x01\x9e\xd6t\xd7\xc2w\xdd\xd9\xb3\x90\x092\x1b\
\x88sG\xc5\xbe\xda\xde\xa5\xab\x95cQc\x0a\xdd\x8a\
Md[\xa2\xe9\xb6\xdf\x07\xa3\x8c~\x9c\xd1\x955\xd9\
d\x8a\xdf\xba\x04\xdf2\x86\xfd\x08\x90K^\xd9\xf72\
\xba\x1f\x15\x98\x94\xa6O\x82\x15\xf3\x81\xe0'.\xc6a\
\xf6\xacv\xf1\xac\xc6q\x0d7q&9\xf4z8W\
\xcdY\xd1\xe9t.\xe3\x1e\xf6\x06k\xaa[j\x06\x9f\
\xa3\x8av\xc8\xaa\xf6\xcc\xc4 uq |GIW\
\x06\xf8\x84+E\xa7\xd3i\xc4T\x8e\xff\xd1\xbe\x96\x01\
`\x82a\xf1\xdf\xffU\xfc\x067=\x80~\x96\x98\xdb\
\xa8\x00\x00\x00\x00IEND\xaeB`\x82\
\x00\x00\x07\xa9\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:24-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:24-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:a62f63b9-7cfb\
-5b4f-bcde-8a607\
3625898\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:36a8b9a8-0618-2\
f40-aeab-d2ed41f\
3b180\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:0c81113\
4-3b4d-a448-935b\
-30a106666da2\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:0c811134-3b4d\
-a448-935b-30a10\
6666da2\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:a6\
2f63b9-7cfb-5b4f\
-bcde-8a60736258\
98\x22 stEvt:when=\x22\
2020-05-02T17:52\
:24-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>f\xe8\
\xce\x8f\x00\x00\x01^IDATH\xc7\xed\xd5\xcd+\
DQ\x18\xc7\xf1\xb9\xe3N$/Y(/\xb1aV\
(;J\x14R,d\xa9\xfc\x03\xac\x0c\x16deG\
YY\x10\x1bS\x92\x8d\xb2\xa0\xb0\xb7\xb3\xf2\x1eM6\
\x94{\x97\xde\xf2R\xd2\xf5=\xf5\x1b\x9dd\x145+\
\xf7\xd4g\xce=\xf7\xbc<\xe7<\xf7\xde\xc6\x09\x82 \
\x92\xcd\x12\x8dd\xb9\x84\x01\xfeA\x00\xd7\xf7\xfd\xbf\xce\
u\x10\xfc\xe6\x04\xc5hDy\x86\xb19\xa8G\x5c\xed\
\xef\x16\x8fkLz]'}\xd1\x8aC\x1c\xe0\x06\x83\
_&\x96b\x1b'Ha\x0e1\xab?\xa6{)\x8d\
\xd9A\x85\xd9\x84\xcbO\x196q\x8b1\xf4`\x09&\
w[\xc8\xc5\x8661\xae\x89#\xb8\xc7\x94\x02L#\
\x81\x05\x5ca\x06k\xe8v<\xcf\x1b\xe2bQ\xe99\
\xd2\x043y\x0f\xbdh\xc01&0\xab\xfe]\xb4\xa0\
H\xed;\x5c\xa0Y\xedI\x05\xad\x8b\xaa\xd3\x94\x1a\xd5\
\xb5(\xd0\x89LyQ]i\xa5\xa4\xc4\xea7\xe5\x11\
\x85V\xbbZ\xf5\x93\xab\xdc\x9e)\x0d\xab\xe8\xc2\x83\xb5\
\xdbK\x9dp\x18Uz\x09\x9a\xd0o-hR\xb5\x8c\
}\xa5\xb6\x0f\xf3\xb8\x8e*z;V4\xe9\x1c\x1d8\
\xb5\x16Hh\x91N=\xf0\x01\xac[\xfdI\xdd3'\
k\xd3\xd8Q\xf3\x90\xcd3\xb0\xdf\x96|<\xff\xf0Z\
\xe7\xe1\x1do\x99\xbe+y\xfd\xfcX\xc2\xff\x830@\
\x18 \xf2\x01%aQY Xt\x07\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x07\x19\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:37:\
55-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:18-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:18-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:80fec745-a70d\
-8449-a60e-a7c5e\
379bc07\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:c18f4afb-caeb-5\
c46-9c44-4a51e1d\
4bddb\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:36def88\
3-a73c-1047-b02e\
-2ef8a062d027\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:36def883-a73c\
-1047-b02e-2ef8a\
062d027\x22 stEvt:w\
hen=\x222020-05-02T\
17:37:55-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:80\
fec745-a70d-8449\
-a60e-a7c5e379bc\
07\x22 stEvt:when=\x22\
2020-05-02T17:52\
:18-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>L\xa9\
\x8a\xc7\x00\x00\x00\xceIDATH\xc7c\xfc\xff\xff\
?\x03-\x01\xe3\xa8\x05$Y\xf0\xfc\xf9s\x17 \x95\
\x0b\xc4\x9f@r$\x9a\xc5\x02\xc4\xbf\x81\xb8NRR\
\xf2>.\x0b\x12\x81\xd4< \xfe\x0c\xc4\xffH0\x1c\
d\x08\x17\x10\x7f\x05b\x07\xa0\x05\x97pY\xc0\x04\xa4\
\xd8(\x08\x11\x90a?\x81\x16\xe0\x0c\x22\xaa\x84\xfb\xf0\
\xb6\x80\x19H\xb1\x93\x9b\x22\xa1q\xf0\x03h\xc1?\x5c\
\x16D\x01\xa99\xd0T\xf4\x9f\xc4\xc8e\x87&o/\
\xa0\x05\xd7pY\xe0\x0a\xa4*\xa1\xc9\x8dT\x0b8\xa0\
\xfa\x0a\x81\x16<\x1c\xde\xa9\x88\x91\xc2\x8c6\xb0>\x10\
\x01R\xf2@\xfc\x87\x82dz\x0bh\xc1w\x5c\x16\xe4\
\x00\xa9\xc9\x14z\xc0\x02h\xc1I\x5c\x16h\x01)O\
\xfeEF2e\x83\xea[\x01\xb4\xe0\xedh\x959\
x,\x00\x00\xa0\xd9\x9f\xd1\xbe\xc1\x7f\xfe\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x08\xd9\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:22-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:22-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:1ad09ad6-ad8c\
-a841-85e1-6979b\
8143a60\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:8de390c5-9065-6\
344-9f4d-c5b1dfd\
386d1\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:1bf1db4\
3-1ff6-8446-bcef\
-7c036a4ca7fd\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:1bf1db43-1ff6\
-8446-bcef-7c036\
a4ca7fd\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:1a\
d09ad6-ad8c-a841\
-85e1-6979b8143a\
60\x22 stEvt:when=\x22\
2020-05-02T17:52\
:22-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>/\x0a\
T[\x00\x00\x02\x8eIDATH\xc7\x95\xd6K\xa8\
Uu\x18\x05\xf0\xdf>w\x1f\x8f\xf7X)W\xad \
*\xb4\x818\x08|\x5c\xc5A\xea@\x22%\xb8\x08b\
\x04A8\xd3\x89\x08!84q\x22\xa8H\x93P\x88\
\xa6\x91\xa3\x10tbc%\xd1FW-(\x92\x1e\xb7\
\xa2\xe8\xe2\xdb\xfb8\x1d'k\xc3F\xe4\xdc}\xfe\xa3\
\xbd\xf7\xff\xf1}k}k}\xff]LMMm\xc7\
~t\xd1\xc1#\xdc\xc5R\x8c\xe2\x7f\x83G+\xeb\x9f\
`9\xday\xfe\x07\xc7K\xbc\x81\xf7\xb08\x933\xb8\
\x8f\x17\xb1\x08\xfd\x05\x02\x14x\x80Y,K\xc0y\xfc\
\x8b\xcf\xcaD\x1d\xc3\x17\xb8\x85-\xf8\x00\xdf\xe0:^\
\x18\x80\xa2:\xfcC\xbc\x8d\xd3\xf8\x0b;\xb1\x03\x9d\xb2\
\x96\xe1'\xc9|\x1d\xf6$\xe0E\xcd\xc6\xcbx\x05\x87\
\xf3\xfeK\x02\xf4\xca\xf0\x05_\xe166`$t5\
\x1d3a\xe1<\xfe\xc0;\xa1\xac_\xa2\x97E\xdb\xb1\
5\xbc\xab!+\x06\xd4\xa1\x9a\xeb\xa1\xc4\xae<wS\
\x87\xa2\x85%Y\xbc6\xca\xd9\x95M\xa3C \x18\x8b\
jV\xa6\xd0\xfb\xab\xfdu\x04\xef\xe3&\xb6%\xb3\xf9\
!\x02\xccF\x0c\x13\xf8\x13\x9b\xaa\x89\x12\x8f\xf3|\x16\
\x0fk\x88\xe6\x1aPT\x8d{\xc9\xf8\xeb\xf8\xa8\x9b\xda\
\xf6[\xd1?\x1cJ\x06\xc7#\xcb\xea\xd0AF\xab\xd6\
\x8cF\xae\x1fcw\x92]\x84\xa2\x0c\x0a\xb8\x1c\x15\x8d\
dc\x85d!\x1f<\xcc\x9a\xc7\xb8\x10W\xbf\x19\xc3\
)\x03\x09\xae\xd4\x0a5\x82\xcfq\x22\x08\x07Q\xf4\x04\
+\x92\xd0\xcf\x98\xc6k\x15Ee\x15\x09\x93\xf8\x1b\xaf\
c3~\xc2o\x81:\x08\xc1,\xd6\xa7\xe5\xdc\x88Y\
{X]Q4ZS\xd1\xbd8\xf9{\x1c\xc5\xa5\x86\
*:\x83\x8f\xd2\xd3`oL\xa7\xee\xe4s\xe9#k\
\xf2\xde\x19BE\xbdx\xe8\xcb$\xb9\xb1\x92\x7fY\xd3\
\xfbD\xad\x06E\x836]\x0f>\x13*\xf7\xa4\xc8\xaf\
F\xe6\xfdV\x8d\xa2\x1dX\x85}9\xbc3\xa4\x93\xa7\
S\x8bU8\x12q\x14\xad\x1a\xfc\xb1\xdc\x01/5\xa4\
\xe5Y\x8a\x8a\xb4\xfe\xa59\xa7\xff\xac\x93/>\xc7\xfe\
M\xc7tz\xd0\xb5\xda\xb7G\x95L+*\x8e\xe1\xf7\
\xb4\xeb\x03\xc9\xc8\x02H\xaa\xb9n\x0e\xfc4\xc1\xdeM\
=\x8a\xb2\xd6\xf7\xcf\xa4@\xe3\x09P\x0e\x81\xa0\x9bV\
q2\xef\x0fr+\xaa\x1b\xedj.\x8b\xb7\x92\xfd)\
\x1c\x0c\xc2\xfe\x02\x97\xcdx\x9c|#\x08\xd6e\xae]\
\xe2\x07|\x9b\xaaw\xf1+~\x8c\xba\xda\x0d\xdav\x1b\
\xdfE\x96K\xb2o2~\xf8\xaf\xc4\x9d\x5c\xf0\xed\xf4\
\xa0\xb9d\xd5\xc9\xb7&\xbf-3Idq\xce\x98O\
\x13\xbc\xfb\x14\xda\xda\xae\xefmH\xe4\x14\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x07\x1d\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:17-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:17-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:91863354-1e11\
-2f44-9e2d-63d80\
ce7293a\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:3541d632-ee53-4\
b41-a6a1-5c1af1b\
0147f\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:bf7fd51\
a-fc98-884e-9110\
-2052b5782117\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:bf7fd51a-fc98\
-884e-9110-2052b\
5782117\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:91\
863354-1e11-2f44\
-9e2d-63d80ce729\
3a\x22 stEvt:when=\x22\
2020-05-02T17:52\
:17-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>\xc1@\
\x10\xfe\x00\x00\x00\xd2IDATH\xc7c\xfc\xff\xff\
?\x03-\x01\x13\x03\x8d\x01\xcd-`A\xe6<\x7f\xfe\
\x9c\x19H\xf9\x00\xb1\x1c\x10\xff\x05bb\xc3\x8f\x11J\
\x9f\x07\xe2\xe30AIIIT\x0b\x80\xc0\x0b\x887\
P\xe0\xe0\xaf@\xac\x0d\xc4\x0f\xb1\xfa\x00\x08\xd4\xa1t\
$\x10_\x04bN\x22]\xff\x0d\x88\x93\x80\xb8\x04\x88\
E\xf1Y\xf0\x1bJ\x1f\x06\xe2\xa7$\xba\xfe*\x9a\x19\
X#\x19\x16\xe6\x22d\x04\x0f\xdf\xf0L\xa6\xa3\x16\x8c\
Z0\x04-\x80\xf1\xdf\x90a\xd6G\xb4\x92\x15kY\
\x04\xe3\xa7\x03\xf1m \xe6!\xd2\xf0O@\xec\x8d\xcd\
Lt\x0b\x8e\x00\xf1K \xae%3DN\x03\xf1}\
$\x9f\xfcG\xb7\xe0\x04\x10[C\x8b\xdc\xdf$V8\
\xacP_\xbfE.8Y\xb0(\xbe\x0b\xc5\xe4\x02F\
d\x871\x0e\xf9V\x05\x00\xc8\xe2+\xc5\xc6x\xe0\xcd\
\x00\x00\x00\x00IEND\xaeB`\x82\
\x00\x00\x02Y\
\x00\
\x00D>x\x9c\xed\xd7\xdfKSa\x18\x07\xf0W\xa2\
\x22\x8c\xd5E\xe5\x9d\x08v!]\x04\x11\xd4eIa\
\xb7Z\x17\x12\xd1]\xffA\x17eKg\x06R\x11\x16\
\x16a\x82Y\x86 \xb9Ms:e\x9c\x9c?\x0al\
\x9asZ\xe9\xdc\xd8\xf4l\xee\xdfxz\xcf36\x8f\
aw\xf9\xbeu\xf6}\xe53\xf1\x1c\x06\xcf\xf3\xf59\
\xe7\xbcG\x882\xf9S{Q\xc8\xcf*QsY\x88\
\x13B\x88\x1a\xa9Vj\x15\xf9\xe3\xbc\xe4\x81YW^\
a}\xb8+\x08\x00\x00\x00\x00\x00\x00\x00\x00\xe0\x9f\xd1\
T\xa6\xbf\x06\xd0b\xa8\xed\x18\x85{\xaf\xd2H{\xa5\
\xf6Zt\xf9\xfa\xf1\x0e\xe5r9\xcaf\xd24\xdd\xd7\
\xb8\xf3|\x89\x5c\x1bQ\xe3\x19g\xb0:\xef\xe7\xdf\x89\
e\x83B\xaf.h\xafK\xa5\xa5\xc9\x17\xb4\x91\x8c\xd1\
\xe0\xbd}dt_!3\xf53\x9fI\xc4K\x81\xc7\
'\xb5\xd7\xa7B,\xfc\x92\xcc\x8d8\x0d\xba\x0f\xf0\xdf\
\xde\xfb\x87(2\xd2\xc49X\x16\x82\x0f\xc8\xefqm\
\x7f\xc7\x81\xd7\x07g\x90^#\xaf\xfb\xe0\x8e\xe3\xc3\x0f\
+(6\xd5\xc59\x98\xe9U\x9ay\x7fC{\xadJ\
3\xb0\xfd\xaf\xc7\x9e\x9e\xa2\xf5\xe88g\x91^_ \
\xa3\xeb\x92\xf6\x9aU\xcd\xc1\xef\xa6\xfb\xae\xcb{\xc5\x0f\
\xce\xe2\xfb\x97w\x14xT\xa5\xbdv\xd5\x19X\xbc\xee\
\xfd47t\xbbx\xaf\x88\x8c6\x93\xaf\xb9\x5c{\x0f\
\xca2\xb0]\x1f\xbe\x16\x17\xcd\x8fy8\x87\xd4\xda\x9c\
|~Tk\xefC\xd5\x1c\xd8s0^\xd7\xd1V6\
\xc39\x8c??\xab\xbd\x0fe\x19H\xd6\x9e\xc1\xda;\
X\xbd'W>\xd1D\xe7y\xed=\xa8\xca\xc0\xef9\
B\xdf&\xda\x8b\xfb\xea\xcf\x03\xb7x_\xa5\xbb\xfe=\
\xcd\xc06\xf7\xe17\xf5\x945S\xdc\xff\xcal\x0f\xbf\
g\xe9\xae[\xd5\x1c\x04;NS|1\x90\x7f\x8f\x88\
\x85\x1c1\xf7\x7f\xcc\xc0\xb6W\xb6\xf8Z\x0e\xcbw\xa9\
\x0e\xee}+k\xd2L\xff\xcd]\xe7\xc3)\x0asP\
\xb8\xb6\xed{\xa1\xa5\xc9N\x1an;\xae\xbd\xc6\xbd\xc6\
\xef\x8d\x89\xa8\x9c\xf3sr\xeeG\xb9\xf7x4(\x9f\
wg\xb4\xd7\xa6\xcab\xe8Iq\xdf\xb7\x99\x5c\xa6\xa9\
\xb7\xd7\xb6\xcf;p\xeew\x13\xeem\xa0\xccf\x82\xe7\
\xc1\xdfz\xb4\xe4\xfa/\xf4i\xdd\x03\x9d\xf2\xac\xff[\
\x99\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfc\xef\x04\x16\
V\x09\xaf_\x22N f\
\x00\x00\x07\xfc\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:07-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:07-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:ef0702ba-b962\
-ba4e-8545-0f067\
83ad6c7\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:59ab4f91-fae9-1\
648-a49a-8446708\
70d24\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:fe4bdc4\
2-6783-0e4e-b924\
-6fd37ef01f3c\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:fe4bdc42-6783\
-0e4e-b924-6fd37\
ef01f3c\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:ef\
0702ba-b962-ba4e\
-8545-0f06783ad6\
c7\x22 stEvt:when=\x22\
2020-05-02T17:52\
:07-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>j!\
`\x9b\x00\x00\x01\xb1IDATH\xc7\xd5\xd6=k\
TA\x14\x06\xe0'\x9b\x0d\xaeh\xac\x22)\x0cV\x22\
\xb2\x8d\x1fi\x82`TH%\xf1\x07h\xef?\xb0\xf2\
\x0f(6b/\x82\x85\x8d\x85\x8a\x88\x8d\x88h$Q\
D\xc4Bp\xc14\x82,\xa2\x85\x82\x9f\x89\x9bks\
\x06\xc6\xcb\xde\xb8{a\x0b\xdf\xe6\xce\xcc\x19\xe6=\xf3\
\x9e\x8f\xb9cEQ\x18%\x1aF\x8c\x91\x134\xbb\xdd\
n\x13'1\x83\x1e\xca\x9aM\xe03n\xe0\xe7\xd0\x04\
X\xc4\xcd\x01\xf6\xee\xc3\xb9:\x04{b|\x0a\xaf\xb0\
5\xb3\x17X\xc3E\x9c\xc5e|\x18\x96`=\xc6K\
x_\xb1\xef<N\xe0\x01\xde\xa2\x95\xd9\xc6C\xc2\xeb\
\xb8\xdd\x8f i>\xb5\x09\xc13\x5c\xc1\x1cv\x97l\
kX\xc0\xde*\x82A\xb0\x8e3\x9b\xd8\x1fcW\x95\
D\xfd\xb0\x0dm\xfc\xcen\xf8+\xe6c\xd9\xbe\x8d\x98\
Ob\x0b\x0e\xc4z\x0b\xab\xf8XEp\xe9\x1f\x1eW\
\xe1e6~\x82\xc5~\x04;q\x1a\x8f\x22k&\xfb\
\xd4F\x19\xbd,\xe0_#\x9d\xdb\x98\xc8\x09\xd2\xd5\xf7\
\x87D\xd7p\xabf\x01_\xc0S|j\x94\xf4\x84c\
\xf1]\x19\xf2\xd0\xe4\xe0\xc1\xc8\xa8\x87\xe5^\x94\xea\xe1\
p\xa4k\xa7\xa6\xf7\xc7C\xd2\x952\xc1\xb7\xf0b\x16\
w\x07\xd0\xbd\x8c\xb4\x7f\x01_R\xc0s\x82\x1f\xd1o\
v\xa4\xeb\xd5\x90\xa7\x85Cq\xf8\xf72A\x13G#\
\x16\xcfk\xca\xd3\x8e\x8ep?=\x079\xc1\xf6 \xe8\
\xe0]My\xe6\x22U\x97\xd3z#n\xb1\x81\xe9\xd0\
\xef^Tl\x1d\x1c\x89\x8aO\x0a\x14\xcd\xd0\xaf\x11\x0f\
\xcaT\xb4\xed\xd9xh\x06E*\xb4y\xdcI\xfa'\
\xdd\xdf\xe0E\xf4\x92N\x04y\xa6F\x90{x\x8d\xab\
\x7f\x19\xfe\xfb\xbf\x8a?\xb4\xdaaG\xaae\x1f\xa5\x00\
\x00\x00\x00IEND\xaeB`\x82\
"
qt_resource_name = b"\
\x00\x0b\
\x05:\xf2B\
\x00o\
\x00p\x00e\x00n\x00_\x00f\x00o\x00l\x00d\x00e\x00r\
\x00\x08\
\x08\x02\xf4>\
\x00M\
\x00a\x00i\x00n\x00I\x00c\x00o\x00n\
\x00\x0b\
\x07\x15<\x00\
\x00b\
\x00u\x00t\x00t\x00o\x00n\x00_\x00s\x00t\x00o\x00p\
\x00\x12\
\x0b\x84T\xe5\
\x00b\
\x00u\x00t\x00t\x00o\x00n\x00_\x00s\x00e\x00a\x00r\x00c\x00h\x00_\x00f\x00i\x00l\
\x00e\
\x00\x08\
\x0cY\xf4>\
\x00M\
\x00e\x00n\x00u\x00I\x00c\x00o\x00n\
\x00\x0d\
\x0b1\xac\x83\
\x00M\
\x00e\x00n\x00u\x00_\x00S\x00e\x00t\x00t\x00i\x00n\x00g\x00s\
\x00\x06\
\x07<[3\
\x00m\
\x00e\x00n\x00u\x00_\x00C\
\x00\x0c\
\x01S\xdet\
\x00b\
\x00u\x00t\x00t\x00o\x00n\x00_\x00s\x00t\x00a\x00r\x00t\
\x00\x12\
\x0f\xda\xb7\x05\
\x00b\
\x00u\x00t\x00t\x00o\x00n\x00_\x00o\x00u\x00t\x00p\x00u\x00t\x00_\x00f\x00i\x00l\
\x00e\
\x00\x07\
\x03\xc5\xb3\x93\
\x00m\
\x00e\x00n\x00u\x00_\x00C\x00C\
\x00\x03\
\x00\x00p7\
\x00i\
\x00m\x00g\
\x00\x0d\
\x0f\x0a\xde'\
\x00c\
\x00i\x00l\x00-\x00m\x00o\x00v\x00i\x00e\x00.\x00p\x00n\x00g\
\x00\x13\
\x04%\x01G\
\x00c\
\x00i\x00l\x00-\x00f\x00o\x00l\x00d\x00e\x00r\x00-\x00o\x00p\x00e\x00n\x00.\x00p\
\x00n\x00g\
\x00\x12\
\x0f\xad\x8fg\
\x00c\
\x00i\x00l\x00-\x00m\x00e\x00d\x00i\x00a\x00-\x00p\x00l\x00a\x00y\x00.\x00p\x00n\
\x00g\
\x00\x13\
\x07\x1d\xec\x87\
\x00c\
\x00i\x00l\x00-\x00v\x00i\x00e\x00w\x00-\x00m\x00o\x00d\x00u\x00l\x00e\x00.\x00p\
\x00n\x00g\
\x00\x1a\
\x08k\xa0\xa7\
\x00c\
\x00i\x00l\x00-\x00o\x00p\x00t\x00i\x00o\x00n\x00s\x00-\x00h\x00o\x00r\x00i\x00z\
\x00o\x00n\x00t\x00a\x00l\x00.\x00p\x00n\x00g\
\x00\x0c\
\x09k\xbf'\
\x00c\
\x00i\x00l\x00-\x00m\x00e\x00n\x00u\x00.\x00p\x00n\x00g\
\x00\x12\
\x06B\x8e\xc7\
\x00c\
\x00i\x00l\x00-\x00m\x00e\x00d\x00i\x00a\x00-\x00s\x00t\x00o\x00p\x00.\x00p\x00n\
\x00g\
\x00\x0e\
\x06P\xeb\xbf\
\x00m\
\x00a\x00i\x00n\x00_\x00i\x00c\x00o\x00n\x00e\x00.\x00i\x00c\x00o\
"
qt_resource_struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x0a\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\xc0\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1d\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01\x08\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1b\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x19\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x002\x00\x02\x00\x00\x00\x01\x00\x00\x00\x17\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\xae\x00\x02\x00\x00\x00\x01\x00\x00\x00\x15\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x13\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x8e\x00\x02\x00\x00\x00\x01\x00\x00\x00\x11\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00N\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0f\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00x\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0d\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\xde\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0b\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0c\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01H\x00\x00\x00\x00\x00\x01\x00\x00\x08\xdd\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0e\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x02\x04\x00\x00\x00\x00\x00\x01\x00\x00(\xa2\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x10\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01(\x00\x00\x00\x00\x00\x01\x00\x00/\xbf\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x12\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01\xca\x00\x00\x00\x00\x00\x01\x00\x00 \xf5\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x14\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x02L\x00\x01\x00\x00\x00\x01\x00\x00?\xbd\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x16\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x18\xb3\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x18\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x02\x22\x00\x00\x00\x00\x00\x01\x00\x008\x9c\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1a\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01H\x00\x00\x00\x00\x00\x01\x00\x00B\x1a\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1c\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01(\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1e\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01t\x00\x00\x00\x00\x00\x01\x00\x00\x10\xdd\
\x00\x00\x01vT\xbc\x95?\
"
def qInitResources():
QtCore.qRegisterResourceData(
0x03, qt_resource_struct, qt_resource_name, qt_resource_data
)
def qCleanupResources():
QtCore.qUnregisterResourceData(
0x03, qt_resource_struct, qt_resource_name, qt_resource_data
)
qInitResources() | conversor_divisor/resources_cd_rc.py |
from PySide2 import QtCore
qt_resource_data = b"\
\x00\x00\x08\xd9\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:22-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:22-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:1ad09ad6-ad8c\
-a841-85e1-6979b\
8143a60\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:8de390c5-9065-6\
344-9f4d-c5b1dfd\
386d1\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:1bf1db4\
3-1ff6-8446-bcef\
-7c036a4ca7fd\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:1bf1db43-1ff6\
-8446-bcef-7c036\
a4ca7fd\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:1a\
d09ad6-ad8c-a841\
-85e1-6979b8143a\
60\x22 stEvt:when=\x22\
2020-05-02T17:52\
:22-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>/\x0a\
T[\x00\x00\x02\x8eIDATH\xc7\x95\xd6K\xa8\
Uu\x18\x05\xf0\xdf>w\x1f\x8f\xf7X)W\xad \
*\xb4\x818\x08|\x5c\xc5A\xea@\x22%\xb8\x08b\
\x04A8\xd3\x89\x08!84q\x22\xa8H\x93P\x88\
\xa6\x91\xa3\x10tbc%\xd1FW-(\x92\x1e\xb7\
\xa2\xe8\xe2\xdb\xfb8\x1d'k\xc3F\xe4\xdc}\xfe\xa3\
\xbd\xf7\xff\xf1}k}k}\xff]LMMm\xc7\
~t\xd1\xc1#\xdc\xc5R\x8c\xe2\x7f\x83G+\xeb\x9f\
`9\xday\xfe\x07\xc7K\xbc\x81\xf7\xb08\x933\xb8\
\x8f\x17\xb1\x08\xfd\x05\x02\x14x\x80Y,K\xc0y\xfc\
\x8b\xcf\xcaD\x1d\xc3\x17\xb8\x85-\xf8\x00\xdf\xe0:^\
\x18\x80\xa2:\xfcC\xbc\x8d\xd3\xf8\x0b;\xb1\x03\x9d\xb2\
\x96\xe1'\xc9|\x1d\xf6$\xe0E\xcd\xc6\xcbx\x05\x87\
\xf3\xfeK\x02\xf4\xca\xf0\x05_\xe166`$t5\
\x1d3a\xe1<\xfe\xc0;\xa1\xac_\xa2\x97E\xdb\xb1\
5\xbc\xab!+\x06\xd4\xa1\x9a\xeb\xa1\xc4\xae<wS\
\x87\xa2\x85%Y\xbc6\xca\xd9\x95M\xa3C \x18\x8b\
jV\xa6\xd0\xfb\xab\xfdu\x04\xef\xe3&\xb6%\xb3\xf9\
!\x02\xccF\x0c\x13\xf8\x13\x9b\xaa\x89\x12\x8f\xf3|\x16\
\x0fk\x88\xe6\x1aPT\x8d{\xc9\xf8\xeb\xf8\xa8\x9b\xda\
\xf6[\xd1?\x1cJ\x06\xc7#\xcb\xea\xd0AF\xab\xd6\
\x8cF\xae\x1fcw\x92]\x84\xa2\x0c\x0a\xb8\x1c\x15\x8d\
dc\x85d!\x1f<\xcc\x9a\xc7\xb8\x10W\xbf\x19\xc3\
)\x03\x09\xae\xd4\x0a5\x82\xcfq\x22\x08\x07Q\xf4\x04\
+\x92\xd0\xcf\x98\xc6k\x15Ee\x15\x09\x93\xf8\x1b\xaf\
c3~\xc2o\x81:\x08\xc1,\xd6\xa7\xe5\xdc\x88Y\
{X]Q4ZS\xd1\xbd8\xf9{\x1c\xc5\xa5\x86\
*:\x83\x8f\xd2\xd3`oL\xa7\xee\xe4s\xe9#k\
\xf2\xde\x19BE\xbdx\xe8\xcb$\xb9\xb1\x92\x7fY\xd3\
\xfbD\xad\x06E\x836]\x0f>\x13*\xf7\xa4\xc8\xaf\
F\xe6\xfdV\x8d\xa2\x1dX\x85}9\xbc3\xa4\x93\xa7\
S\x8bU8\x12q\x14\xad\x1a\xfc\xb1\xdc\x01/5\xa4\
\xe5Y\x8a\x8a\xb4\xfe\xa59\xa7\xff\xac\x93/>\xc7\xfe\
M\xc7tz\xd0\xb5\xda\xb7G\x95L+*\x8e\xe1\xf7\
\xb4\xeb\x03\xc9\xc8\x02H\xaa\xb9n\x0e\xfc4\xc1\xdeM\
=\x8a\xb2\xd6\xf7\xcf\xa4@\xe3\x09P\x0e\x81\xa0\x9bV\
q2\xef\x0fr+\xaa\x1b\xedj.\x8b\xb7\x92\xfd)\
\x1c\x0c\xc2\xfe\x02\x97\xcdx\x9c|#\x08\xd6e\xae]\
\xe2\x07|\x9b\xaaw\xf1+~\x8c\xba\xda\x0d\xdav\x1b\
\xdfE\x96K\xb2o2~\xf8\xaf\xc4\x9d\x5c\xf0\xed\xf4\
\xa0\xb9d\xd5\xc9\xb7&\xbf-3Idq\xce\x98O\
\x13\xbc\xfb\x14\xda\xda\xae\xefmH\xe4\x14\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x07\xfc\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:07-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:07-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:ef0702ba-b962\
-ba4e-8545-0f067\
83ad6c7\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:59ab4f91-fae9-1\
648-a49a-8446708\
70d24\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:fe4bdc4\
2-6783-0e4e-b924\
-6fd37ef01f3c\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:fe4bdc42-6783\
-0e4e-b924-6fd37\
ef01f3c\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:ef\
0702ba-b962-ba4e\
-8545-0f06783ad6\
c7\x22 stEvt:when=\x22\
2020-05-02T17:52\
:07-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>j!\
`\x9b\x00\x00\x01\xb1IDATH\xc7\xd5\xd6=k\
TA\x14\x06\xe0'\x9b\x0d\xaeh\xac\x22)\x0cV\x22\
\xb2\x8d\x1fi\x82`TH%\xf1\x07h\xef?\xb0\xf2\
\x0f(6b/\x82\x85\x8d\x85\x8a\x88\x8d\x88h$Q\
D\xc4Bp\xc14\x82,\xa2\x85\x82\x9f\x89\x9bks\
\x06\xc6\xcb\xde\xb8{a\x0b\xdf\xe6\xce\xcc\x19\xe6=\xf3\
\x9e\x8f\xb9cEQ\x18%\x1aF\x8c\x91\x134\xbb\xdd\
n\x13'1\x83\x1e\xca\x9aM\xe03n\xe0\xe7\xd0\x04\
X\xc4\xcd\x01\xf6\xee\xc3\xb9:\x04{b|\x0a\xaf\xb0\
5\xb3\x17X\xc3E\x9c\xc5e|\x18\x96`=\xc6K\
x_\xb1\xef<N\xe0\x01\xde\xa2\x95\xd9\xc6C\xc2\xeb\
\xb8\xdd\x8f i>\xb5\x09\xc13\x5c\xc1\x1cv\x97l\
kX\xc0\xde*\x82A\xb0\x8e3\x9b\xd8\x1fcW\x95\
D\xfd\xb0\x0dm\xfc\xcen\xf8+\xe6c\xd9\xbe\x8d\x98\
Ob\x0b\x0e\xc4z\x0b\xab\xf8XEp\xe9\x1f\x1eW\
\xe1e6~\x82\xc5~\x04;q\x1a\x8f\x22k&\xfb\
\xd4F\x19\xbd,\xe0_#\x9d\xdb\x98\xc8\x09\xd2\xd5\xf7\
\x87D\xd7p\xabf\x01_\xc0S|j\x94\xf4\x84c\
\xf1]\x19\xf2\xd0\xe4\xe0\xc1\xc8\xa8\x87\xe5^\x94\xea\xe1\
p\xa4k\xa7\xa6\xf7\xc7C\xd2\x952\xc1\xb7\xf0b\x16\
w\x07\xd0\xbd\x8c\xb4\x7f\x01_R\xc0s\x82\x1f\xd1o\
v\xa4\xeb\xd5\x90\xa7\x85Cq\xf8\xf72A\x13G#\
\x16\xcfk\xca\xd3\x8e\x8ep?=\x079\xc1\xf6 \xe8\
\xe0]My\xe6\x22U\x97\xd3z#n\xb1\x81\xe9\xd0\
\xef^Tl\x1d\x1c\x89\x8aO\x0a\x14\xcd\xd0\xaf\x11\x0f\
\xcaT\xb4\xed\xd9xh\x06E*\xb4y\xdcI\xfa'\
\xdd\xdf\xe0E\xf4\x92N\x04y\xa6F\x90{x\x8d\xab\
\x7f\x19\xfe\xfb\xbf\x8a?\xb4\xdaaG\xaae\x1f\xa5\x00\
\x00\x00\x00IEND\xaeB`\x82\
\x00\x00\x07\xd2\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:16-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:16-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:3476f972-cae4\
-6d48-ab9f-9a222\
8765b33\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:448a63e8-7143-7\
946-9c7f-101d056\
7c61b\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:a1e841e\
e-d491-564b-9dfb\
-d9d4b815d32a\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:a1e841ee-d491\
-564b-9dfb-d9d4b\
815d32a\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:34\
76f972-cae4-6d48\
-ab9f-9a2228765b\
33\x22 stEvt:when=\x22\
2020-05-02T17:52\
:16-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>\xf0\xa7\
\x86\xec\x00\x00\x01\x87IDATH\xc7\xad\xd6\xcf+\
\x04a\x1c\xc7\xf1\xd9\xe4@)?j3\xfc\x03n\x0e\
\x948H\xcaA\xe1H\x9cD\x09)\x22\xbf)\xcaE\
)[\x946?\x8b3\x0erp\x92-\x8a\x838q\
\x90\x83\xc3\xc4\x81\x94D\xd1x?\xf9NMS\xa6\xf5\
\xcc\xf3\xd4\xabmvg\x9e\xcf<\xdfy\x9eg6\xe6\
\xba\xae\xe55\xc7q\xac@\x8b\xc1\xb54\x9am\xdb\xbf\
\x1d\x04\x02\xbc\x0es\xf0\x8eoK\xb3\xfd\x15\xa0>\xda\
\x90\xc4>\xfa\xf1\xac3\x9a\xb0\x00\xd5y\x97|\xf5\x84\
!\xec\xfc7$,`\x1b\xb5h\xc1\x02*p\x81>\
\x9c\x9b\x18\x81\xba\xdb\x06\x14\xc83\xe8\xc4\xbc\x1c\xab\xf0\
a<F\x0dhD\x1c\x9f\xf2\x93z\xe8\x09t\xe0K\
F\x93\x0c+[:#(\xc4G\xe0\xba2,\xa1\x12\
\x972\x09R\xba%\x0a\x06\xf8\xef\xb4\x15\xeb\xc8\xc2\x1e\
\xbaeBD\x1e\x81\xbf\xe5a\x0e\xbdr\xde\x18\x96\xbd\
\xb5c\x22\xc0k%XA\x0d\xae\xe5\xf9\xa4L\x05\xf8\
\xcb\xd6\x84]d\xa0\x8a\x80\xb3\xa8\x01\xfe\xces1\x8d\
A\xdc\xa3\x9e\x80[\x13#\xc8\xc4\x04f\xe4X-\xcc\
Y\xbc\x99(\x91\x7f\x01\x1e`\x00w\xba\xb3\xc8_\x8e\
R\xac\xa1\x1c\x0f2E\x0fM\xac\x83\x22,\xa2\x19/\
\x18\xc5\xaa\x89\xad\x22\x1bS\x18\x97\xd3\x12R\xf3W\xdd\
\xadBmhu(\x96\x91l \x1f\xc7\xe8\xc1M\xd4\
\xddt\x13\xed8A5\xae0\x82#So4\xb5\xfc\
'\xa5\xfe\xea\x8e\xb7t\xde\xd1a\x01q)\xd1\xa9,\
\x1a\xe3\xefd#-\xdd\x80\xc8\x7f[~\x00\xd5\xa3\xf5\
\xd1@\x7f+\x07\x00\x00\x00\x00IEND\xaeB`\
\x82\
\x00\x00\x08>\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:35-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:35-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:2421bcd1-daf2\
-e64b-a315-1fa31\
f4792db\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:e9017898-4533-a\
842-bed9-eee21b5\
72acd\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:698e21f\
5-b155-424d-9968\
-c165d7dfe6fc\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:698e21f5-b155\
-424d-9968-c165d\
7dfe6fc\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:24\
21bcd1-daf2-e64b\
-a315-1fa31f4792\
db\x22 stEvt:when=\x22\
2020-05-02T17:52\
:35-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>A\xdc\
-\xd9\x00\x00\x01\xf3IDATH\xc7\xd5\xd6=\x8f\
LQ\x18\x07\xf0\xdf\x9d\x1d\xbb\x98]/\xeb%\x22\x13\
\x0d\x8dF\xa1 \xaa\xad\xb4dE\xa1R\xd0\x13\xadN\
%\x1a\x14Z!\x11\xad\x0f\xb0\xf1\x0d\xd4\x0a\x11\x09\x09\
3\x11\x14\x8c\xec\xcc\xd8\x99\xb9\x0a\xcfM\xce\xde\x9c\x9d\
]\x89-\x9c\xe4\xe6\xe6>\xaf\xff\xe79\xff\xe7\x9c[\
\x94ei;W\xc36\xaff\xb7\xdb]D;I\x98\
\x964\x89g\x06E\xcd\xb7\x0c]\x91\x01Zb\x8cw\
M\x5c\xc2#\xccm\x00b8E7\xc0\xce\x0dt\xdf\
\xb1\xd4\x0c\x839\xdc\xc5\xc7\x04\xcd\x18\xd7q\x1a\xb70\
\xaa!<\x8a\xdbx\x81\x97Qe\xe5w\x1e\xcb(\x9a\
\x89\xe2>\xbe\xd6P\x9c\xc2q<\xcc <\x98$x\
\x9eA\xbf\x8c2\xedy;\x13dO\xf48mCQ\
\xb3\xdf\x9f\xf1;\x94cQ\x8e\xaf\xd38\xbc%]#\
\x83\xcc&\xb2\xbf\xd2\xa5\x09\xfa\x19\xc3_a<\xcc\xa0\
\xeb'\x9b\x9ac\xde\x9f9H\x84\xf3\xf1\xde\x1d\xfc\x1e\
`G\x04\x5c\x08\xa7j\x1e\xfah\x85\xfdl\xbc[a\
\xbb\x8a]i\x82\x0a\xc9\x0az\xb1\xa1e$8\x12\x01\
\xde\x84\xac\xaax-\x82\x94\xb8\x83\x1bI\xc2~l\xf2\
\x00e3qz\x8d/\x11p\x1c\xcfY\x1c\xc6\xab\xf8\
\xae*X\xc3\x22\x96\xf0\x01o\x93J\xd6p\x12'\xaa\
9\xa8(x\x15\xefk\xbd|\x1c\x93~!\xd3\xe7c\
\x11\xfc\x01\x9e\xd6t\xd7\xc2w\xdd\xd9\xb3\x90\x092\x1b\
\x88sG\xc5\xbe\xda\xde\xa5\xab\x95cQc\x0a\xdd\x8a\
Md[\xa2\xe9\xb6\xdf\x07\xa3\x8c~\x9c\xd1\x955\xd9\
d\x8a\xdf\xba\x04\xdf2\x86\xfd\x08\x90K^\xd9\xf72\
\xba\x1f\x15\x98\x94\xa6O\x82\x15\xf3\x81\xe0'.\xc6a\
\xf6\xacv\xf1\xac\xc6q\x0d7q&9\xf4z8W\
\xcdY\xd1\xe9t.\xe3\x1e\xf6\x06k\xaa[j\x06\x9f\
\xa3\x8av\xc8\xaa\xf6\xcc\xc4 uq |GIW\
\x06\xf8\x84+E\xa7\xd3i\xc4T\x8e\xff\xd1\xbe\x96\x01\
`\x82a\xf1\xdf\xffU\xfc\x067=\x80~\x96\x98\xdb\
\xa8\x00\x00\x00\x00IEND\xaeB`\x82\
\x00\x00\x07\xa9\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:24-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:24-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:a62f63b9-7cfb\
-5b4f-bcde-8a607\
3625898\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:36a8b9a8-0618-2\
f40-aeab-d2ed41f\
3b180\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:0c81113\
4-3b4d-a448-935b\
-30a106666da2\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:0c811134-3b4d\
-a448-935b-30a10\
6666da2\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:a6\
2f63b9-7cfb-5b4f\
-bcde-8a60736258\
98\x22 stEvt:when=\x22\
2020-05-02T17:52\
:24-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>f\xe8\
\xce\x8f\x00\x00\x01^IDATH\xc7\xed\xd5\xcd+\
DQ\x18\xc7\xf1\xb9\xe3N$/Y(/\xb1aV\
(;J\x14R,d\xa9\xfc\x03\xac\x0c\x16deG\
YY\x10\x1bS\x92\x8d\xb2\xa0\xb0\xb7\xb3\xf2\x1eM6\
\x94{\x97\xde\xf2R\xd2\xf5=\xf5\x1b\x9dd\x145+\
\xf7\xd4g\xce=\xf7\xbc<\xe7<\xf7\xde\xc6\x09\x82 \
\x92\xcd\x12\x8dd\xb9\x84\x01\xfeA\x00\xd7\xf7\xfd\xbf\xce\
u\x10\xfc\xe6\x04\xc5hDy\x86\xb19\xa8G\x5c\xed\
\xef\x16\x8fkLz]'}\xd1\x8aC\x1c\xe0\x06\x83\
_&\x96b\x1b'Ha\x0e1\xab?\xa6{)\x8d\
\xd9A\x85\xd9\x84\xcbO\x196q\x8b1\xf4`\x09&\
w[\xc8\xc5\x8661\xae\x89#\xb8\xc7\x94\x02L#\
\x81\x05\x5ca\x06k\xe8v<\xcf\x1b\xe2bQ\xe99\
\xd2\x043y\x0f\xbdh\xc01&0\xab\xfe]\xb4\xa0\
H\xed;\x5c\xa0Y\xedI\x05\xad\x8b\xaa\xd3\x94\x1a\xd5\
\xb5(\xd0\x89LyQ]i\xa5\xa4\xc4\xea7\xe5\x11\
\x85V\xbbZ\xf5\x93\xab\xdc\x9e)\x0d\xab\xe8\xc2\x83\xb5\
\xdbK\x9dp\x18Uz\x09\x9a\xd0o-hR\xb5\x8c\
}\xa5\xb6\x0f\xf3\xb8\x8e*z;V4\xe9\x1c\x1d8\
\xb5\x16Hh\x91N=\xf0\x01\xac[\xfdI\xdd3'\
k\xd3\xd8Q\xf3\x90\xcd3\xb0\xdf\x96|<\xff\xf0Z\
\xe7\xe1\x1do\x99\xbe+y\xfd\xfcX\xc2\xff\x830@\
\x18 \xf2\x01%aQY Xt\x07\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x07\x19\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:37:\
55-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:18-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:18-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:80fec745-a70d\
-8449-a60e-a7c5e\
379bc07\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:c18f4afb-caeb-5\
c46-9c44-4a51e1d\
4bddb\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:36def88\
3-a73c-1047-b02e\
-2ef8a062d027\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:36def883-a73c\
-1047-b02e-2ef8a\
062d027\x22 stEvt:w\
hen=\x222020-05-02T\
17:37:55-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:80\
fec745-a70d-8449\
-a60e-a7c5e379bc\
07\x22 stEvt:when=\x22\
2020-05-02T17:52\
:18-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>L\xa9\
\x8a\xc7\x00\x00\x00\xceIDATH\xc7c\xfc\xff\xff\
?\x03-\x01\xe3\xa8\x05$Y\xf0\xfc\xf9s\x17 \x95\
\x0b\xc4\x9f@r$\x9a\xc5\x02\xc4\xbf\x81\xb8NRR\
\xf2>.\x0b\x12\x81\xd4< \xfe\x0c\xc4\xffH0\x1c\
d\x08\x17\x10\x7f\x05b\x07\xa0\x05\x97pY\xc0\x04\xa4\
\xd8(\x08\x11\x90a?\x81\x16\xe0\x0c\x22\xaa\x84\xfb\xf0\
\xb6\x80\x19H\xb1\x93\x9b\x22\xa1q\xf0\x03h\xc1?\x5c\
\x16D\x01\xa99\xd0T\xf4\x9f\xc4\xc8e\x87&o/\
\xa0\x05\xd7pY\xe0\x0a\xa4*\xa1\xc9\x8dT\x0b8\xa0\
\xfa\x0a\x81\x16<\x1c\xde\xa9\x88\x91\xc2\x8c6\xb0>\x10\
\x01R\xf2@\xfc\x87\x82dz\x0bh\xc1w\x5c\x16\xe4\
\x00\xa9\xc9\x14z\xc0\x02h\xc1I\x5c\x16h\x01)O\
\xfeEF2e\x83\xea[\x01\xb4\xe0\xedh\x959\
x,\x00\x00\xa0\xd9\x9f\xd1\xbe\xc1\x7f\xfe\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x08\xd9\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:22-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:22-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:1ad09ad6-ad8c\
-a841-85e1-6979b\
8143a60\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:8de390c5-9065-6\
344-9f4d-c5b1dfd\
386d1\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:1bf1db4\
3-1ff6-8446-bcef\
-7c036a4ca7fd\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:1bf1db43-1ff6\
-8446-bcef-7c036\
a4ca7fd\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:1a\
d09ad6-ad8c-a841\
-85e1-6979b8143a\
60\x22 stEvt:when=\x22\
2020-05-02T17:52\
:22-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>/\x0a\
T[\x00\x00\x02\x8eIDATH\xc7\x95\xd6K\xa8\
Uu\x18\x05\xf0\xdf>w\x1f\x8f\xf7X)W\xad \
*\xb4\x818\x08|\x5c\xc5A\xea@\x22%\xb8\x08b\
\x04A8\xd3\x89\x08!84q\x22\xa8H\x93P\x88\
\xa6\x91\xa3\x10tbc%\xd1FW-(\x92\x1e\xb7\
\xa2\xe8\xe2\xdb\xfb8\x1d'k\xc3F\xe4\xdc}\xfe\xa3\
\xbd\xf7\xff\xf1}k}k}\xff]LMMm\xc7\
~t\xd1\xc1#\xdc\xc5R\x8c\xe2\x7f\x83G+\xeb\x9f\
`9\xday\xfe\x07\xc7K\xbc\x81\xf7\xb08\x933\xb8\
\x8f\x17\xb1\x08\xfd\x05\x02\x14x\x80Y,K\xc0y\xfc\
\x8b\xcf\xcaD\x1d\xc3\x17\xb8\x85-\xf8\x00\xdf\xe0:^\
\x18\x80\xa2:\xfcC\xbc\x8d\xd3\xf8\x0b;\xb1\x03\x9d\xb2\
\x96\xe1'\xc9|\x1d\xf6$\xe0E\xcd\xc6\xcbx\x05\x87\
\xf3\xfeK\x02\xf4\xca\xf0\x05_\xe166`$t5\
\x1d3a\xe1<\xfe\xc0;\xa1\xac_\xa2\x97E\xdb\xb1\
5\xbc\xab!+\x06\xd4\xa1\x9a\xeb\xa1\xc4\xae<wS\
\x87\xa2\x85%Y\xbc6\xca\xd9\x95M\xa3C \x18\x8b\
jV\xa6\xd0\xfb\xab\xfdu\x04\xef\xe3&\xb6%\xb3\xf9\
!\x02\xccF\x0c\x13\xf8\x13\x9b\xaa\x89\x12\x8f\xf3|\x16\
\x0fk\x88\xe6\x1aPT\x8d{\xc9\xf8\xeb\xf8\xa8\x9b\xda\
\xf6[\xd1?\x1cJ\x06\xc7#\xcb\xea\xd0AF\xab\xd6\
\x8cF\xae\x1fcw\x92]\x84\xa2\x0c\x0a\xb8\x1c\x15\x8d\
dc\x85d!\x1f<\xcc\x9a\xc7\xb8\x10W\xbf\x19\xc3\
)\x03\x09\xae\xd4\x0a5\x82\xcfq\x22\x08\x07Q\xf4\x04\
+\x92\xd0\xcf\x98\xc6k\x15Ee\x15\x09\x93\xf8\x1b\xaf\
c3~\xc2o\x81:\x08\xc1,\xd6\xa7\xe5\xdc\x88Y\
{X]Q4ZS\xd1\xbd8\xf9{\x1c\xc5\xa5\x86\
*:\x83\x8f\xd2\xd3`oL\xa7\xee\xe4s\xe9#k\
\xf2\xde\x19BE\xbdx\xe8\xcb$\xb9\xb1\x92\x7fY\xd3\
\xfbD\xad\x06E\x836]\x0f>\x13*\xf7\xa4\xc8\xaf\
F\xe6\xfdV\x8d\xa2\x1dX\x85}9\xbc3\xa4\x93\xa7\
S\x8bU8\x12q\x14\xad\x1a\xfc\xb1\xdc\x01/5\xa4\
\xe5Y\x8a\x8a\xb4\xfe\xa59\xa7\xff\xac\x93/>\xc7\xfe\
M\xc7tz\xd0\xb5\xda\xb7G\x95L+*\x8e\xe1\xf7\
\xb4\xeb\x03\xc9\xc8\x02H\xaa\xb9n\x0e\xfc4\xc1\xdeM\
=\x8a\xb2\xd6\xf7\xcf\xa4@\xe3\x09P\x0e\x81\xa0\x9bV\
q2\xef\x0fr+\xaa\x1b\xedj.\x8b\xb7\x92\xfd)\
\x1c\x0c\xc2\xfe\x02\x97\xcdx\x9c|#\x08\xd6e\xae]\
\xe2\x07|\x9b\xaaw\xf1+~\x8c\xba\xda\x0d\xdav\x1b\
\xdfE\x96K\xb2o2~\xf8\xaf\xc4\x9d\x5c\xf0\xed\xf4\
\xa0\xb9d\xd5\xc9\xb7&\xbf-3Idq\xce\x98O\
\x13\xbc\xfb\x14\xda\xda\xae\xefmH\xe4\x14\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x07\x1d\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:17-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:17-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:91863354-1e11\
-2f44-9e2d-63d80\
ce7293a\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:3541d632-ee53-4\
b41-a6a1-5c1af1b\
0147f\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:bf7fd51\
a-fc98-884e-9110\
-2052b5782117\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:bf7fd51a-fc98\
-884e-9110-2052b\
5782117\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:91\
863354-1e11-2f44\
-9e2d-63d80ce729\
3a\x22 stEvt:when=\x22\
2020-05-02T17:52\
:17-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>\xc1@\
\x10\xfe\x00\x00\x00\xd2IDATH\xc7c\xfc\xff\xff\
?\x03-\x01\x13\x03\x8d\x01\xcd-`A\xe6<\x7f\xfe\
\x9c\x19H\xf9\x00\xb1\x1c\x10\xff\x05bb\xc3\x8f\x11J\
\x9f\x07\xe2\xe30AIIIT\x0b\x80\xc0\x0b\x887\
P\xe0\xe0\xaf@\xac\x0d\xc4\x0f\xb1\xfa\x00\x08\xd4\xa1t\
$\x10_\x04bN\x22]\xff\x0d\x88\x93\x80\xb8\x04\x88\
E\xf1Y\xf0\x1bJ\x1f\x06\xe2\xa7$\xba\xfe*\x9a\x19\
X#\x19\x16\xe6\x22d\x04\x0f\xdf\xf0L\xa6\xa3\x16\x8c\
Z0\x04-\x80\xf1\xdf\x90a\xd6G\xb4\x92\x15kY\
\x04\xe3\xa7\x03\xf1m \xe6!\xd2\xf0O@\xec\x8d\xcd\
Lt\x0b\x8e\x00\xf1K \xae%3DN\x03\xf1}\
$\x9f\xfcG\xb7\xe0\x04\x10[C\x8b\xdc\xdf$V8\
\xacP_\xbfE.8Y\xb0(\xbe\x0b\xc5\xe4\x02F\
d\x871\x0e\xf9V\x05\x00\xc8\xe2+\xc5\xc6x\xe0\xcd\
\x00\x00\x00\x00IEND\xaeB`\x82\
\x00\x00\x02Y\
\x00\
\x00D>x\x9c\xed\xd7\xdfKSa\x18\x07\xf0W\xa2\
\x22\x8c\xd5E\xe5\x9d\x08v!]\x04\x11\xd4eIa\
\xb7Z\x17\x12\xd1]\xffA\x17eKg\x06R\x11\x16\
\x16a\x82Y\x86 \xb9Ms:e\x9c\x9c?\x0al\
\x9asZ\xe9\xdc\xd8\xf4l\xee\xdfxz\xcf36\x8f\
aw\xf9\xbeu\xf6}\xe53\xf1\x1c\x06\xcf\xf3\xf59\
\xe7\xbcG\x882\xf9S{Q\xc8\xcf*QsY\x88\
\x13B\x88\x1a\xa9Vj\x15\xf9\xe3\xbc\xe4\x81YW^\
a}\xb8+\x08\x00\x00\x00\x00\x00\x00\x00\x00\xe0\x9f\xd1\
T\xa6\xbf\x06\xd0b\xa8\xed\x18\x85{\xaf\xd2H{\xa5\
\xf6Zt\xf9\xfa\xf1\x0e\xe5r9\xcaf\xd24\xdd\xd7\
\xb8\xf3|\x89\x5c\x1bQ\xe3\x19g\xb0:\xef\xe7\xdf\x89\
e\x83B\xaf.h\xafK\xa5\xa5\xc9\x17\xb4\x91\x8c\xd1\
\xe0\xbd}dt_!3\xf53\x9fI\xc4K\x81\xc7\
'\xb5\xd7\xa7B,\xfc\x92\xcc\x8d8\x0d\xba\x0f\xf0\xdf\
\xde\xfb\x87(2\xd2\xc49X\x16\x82\x0f\xc8\xefqm\
\x7f\xc7\x81\xd7\x07g\x90^#\xaf\xfb\xe0\x8e\xe3\xc3\x0f\
+(6\xd5\xc59\x98\xe9U\x9ay\x7fC{\xadJ\
3\xb0\xfd\xaf\xc7\x9e\x9e\xa2\xf5\xe88g\x91^_ \
\xa3\xeb\x92\xf6\x9aU\xcd\xc1\xef\xa6\xfb\xae\xcb{\xc5\x0f\
\xce\xe2\xfb\x97w\x14xT\xa5\xbdv\xd5\x19X\xbc\xee\
\xfd47t\xbbx\xaf\x88\x8c6\x93\xaf\xb9\x5c{\x0f\
\xca2\xb0]\x1f\xbe\x16\x17\xcd\x8fy8\x87\xd4\xda\x9c\
|~Tk\xefC\xd5\x1c\xd8s0^\xd7\xd1V6\
\xc39\x8c??\xab\xbd\x0fe\x19H\xd6\x9e\xc1\xda;\
X\xbd'W>\xd1D\xe7y\xed=\xa8\xca\xc0\xef9\
B\xdf&\xda\x8b\xfb\xea\xcf\x03\xb7x_\xa5\xbb\xfe=\
\xcd\xc06\xf7\xe17\xf5\x945S\xdc\xff\xcal\x0f\xbf\
g\xe9\xae[\xd5\x1c\x04;NS|1\x90\x7f\x8f\x88\
\x85\x1c1\xf7\x7f\xcc\xc0\xb6W\xb6\xf8Z\x0e\xcbw\xa9\
\x0e\xee}+k\xd2L\xff\xcd]\xe7\xc3)\x0asP\
\xb8\xb6\xed{\xa1\xa5\xc9N\x1an;\xae\xbd\xc6\xbd\xc6\
\xef\x8d\x89\xa8\x9c\xf3sr\xeeG\xb9\xf7x4(\x9f\
wg\xb4\xd7\xa6\xcab\xe8Iq\xdf\xb7\x99\x5c\xa6\xa9\
\xb7\xd7\xb6\xcf;p\xeew\x13\xeem\xa0\xccf\x82\xe7\
\xc1\xdfz\xb4\xe4\xfa/\xf4i\xdd\x03\x9d\xf2\xac\xff[\
\x99\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfc\xef\x04\x16\
V\x09\xaf_\x22N f\
\x00\x00\x07\xfc\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\
\x00\x00\x00\x09pHYs\x00\x00\x16%\x00\x00\x16%\
\x01IR$\xf0\x00\x00\x05\xf1iTXtXML\
:com.adobe.xmp\x00\x00\
\x00\x00\x00<?xpacket beg\
in=\x22\xef\xbb\xbf\x22 id=\x22W5M\
0MpCehiHzreSzNTc\
zkc9d\x22?> <x:xmpm\
eta xmlns:x=\x22ado\
be:ns:meta/\x22 x:x\
mptk=\x22Adobe XMP \
Core 5.6-c148 79\
.164036, 2019/08\
/13-01:06:57 \
\x22> <rdf:RDF \
xmlns:rdf=\x22http:\
//www.w3.org/199\
9/02/22-rdf-synt\
ax-ns#\x22> <rdf:De\
scription rdf:ab\
out=\x22\x22 xmlns:xmp\
=\x22http://ns.adob\
e.com/xap/1.0/\x22 \
xmlns:dc=\x22http:/\
/purl.org/dc/ele\
ments/1.1/\x22 xmln\
s:photoshop=\x22htt\
p://ns.adobe.com\
/photoshop/1.0/\x22\
xmlns:xmpMM=\x22ht\
tp://ns.adobe.co\
m/xap/1.0/mm/\x22 x\
mlns:stEvt=\x22http\
://ns.adobe.com/\
xap/1.0/sType/Re\
sourceEvent#\x22 xm\
p:CreatorTool=\x22A\
dobe Photoshop 2\
1.0 (Windows)\x22 x\
mp:CreateDate=\x222\
020-05-02T17:48:\
24-03:00\x22 xmp:Mo\
difyDate=\x222020-0\
5-02T17:52:07-03\
:00\x22 xmp:Metadat\
aDate=\x222020-05-0\
2T17:52:07-03:00\
\x22 dc:format=\x22ima\
ge/png\x22 photosho\
p:ColorMode=\x223\x22 \
photoshop:ICCPro\
file=\x22sRGB IEC61\
966-2.1\x22 xmpMM:I\
nstanceID=\x22xmp.i\
id:ef0702ba-b962\
-ba4e-8545-0f067\
83ad6c7\x22 xmpMM:D\
ocumentID=\x22adobe\
:docid:photoshop\
:59ab4f91-fae9-1\
648-a49a-8446708\
70d24\x22 xmpMM:Ori\
ginalDocumentID=\
\x22xmp.did:fe4bdc4\
2-6783-0e4e-b924\
-6fd37ef01f3c\x22> \
<xmpMM:History> \
<rdf:Seq> <rdf:l\
i stEvt:action=\x22\
created\x22 stEvt:i\
nstanceID=\x22xmp.i\
id:fe4bdc42-6783\
-0e4e-b924-6fd37\
ef01f3c\x22 stEvt:w\
hen=\x222020-05-02T\
17:48:24-03:00\x22 \
stEvt:softwareAg\
ent=\x22Adobe Photo\
shop 21.0 (Windo\
ws)\x22/> <rdf:li s\
tEvt:action=\x22sav\
ed\x22 stEvt:instan\
ceID=\x22xmp.iid:ef\
0702ba-b962-ba4e\
-8545-0f06783ad6\
c7\x22 stEvt:when=\x22\
2020-05-02T17:52\
:07-03:00\x22 stEvt\
:softwareAgent=\x22\
Adobe Photoshop \
21.0 (Windows)\x22 \
stEvt:changed=\x22/\
\x22/> </rdf:Seq> <\
/xmpMM:History> \
</rdf:Descriptio\
n> </rdf:RDF> </\
x:xmpmeta> <?xpa\
cket end=\x22r\x22?>j!\
`\x9b\x00\x00\x01\xb1IDATH\xc7\xd5\xd6=k\
TA\x14\x06\xe0'\x9b\x0d\xaeh\xac\x22)\x0cV\x22\
\xb2\x8d\x1fi\x82`TH%\xf1\x07h\xef?\xb0\xf2\
\x0f(6b/\x82\x85\x8d\x85\x8a\x88\x8d\x88h$Q\
D\xc4Bp\xc14\x82,\xa2\x85\x82\x9f\x89\x9bks\
\x06\xc6\xcb\xde\xb8{a\x0b\xdf\xe6\xce\xcc\x19\xe6=\xf3\
\x9e\x8f\xb9cEQ\x18%\x1aF\x8c\x91\x134\xbb\xdd\
n\x13'1\x83\x1e\xca\x9aM\xe03n\xe0\xe7\xd0\x04\
X\xc4\xcd\x01\xf6\xee\xc3\xb9:\x04{b|\x0a\xaf\xb0\
5\xb3\x17X\xc3E\x9c\xc5e|\x18\x96`=\xc6K\
x_\xb1\xef<N\xe0\x01\xde\xa2\x95\xd9\xc6C\xc2\xeb\
\xb8\xdd\x8f i>\xb5\x09\xc13\x5c\xc1\x1cv\x97l\
kX\xc0\xde*\x82A\xb0\x8e3\x9b\xd8\x1fcW\x95\
D\xfd\xb0\x0dm\xfc\xcen\xf8+\xe6c\xd9\xbe\x8d\x98\
Ob\x0b\x0e\xc4z\x0b\xab\xf8XEp\xe9\x1f\x1eW\
\xe1e6~\x82\xc5~\x04;q\x1a\x8f\x22k&\xfb\
\xd4F\x19\xbd,\xe0_#\x9d\xdb\x98\xc8\x09\xd2\xd5\xf7\
\x87D\xd7p\xabf\x01_\xc0S|j\x94\xf4\x84c\
\xf1]\x19\xf2\xd0\xe4\xe0\xc1\xc8\xa8\x87\xe5^\x94\xea\xe1\
p\xa4k\xa7\xa6\xf7\xc7C\xd2\x952\xc1\xb7\xf0b\x16\
w\x07\xd0\xbd\x8c\xb4\x7f\x01_R\xc0s\x82\x1f\xd1o\
v\xa4\xeb\xd5\x90\xa7\x85Cq\xf8\xf72A\x13G#\
\x16\xcfk\xca\xd3\x8e\x8ep?=\x079\xc1\xf6 \xe8\
\xe0]My\xe6\x22U\x97\xd3z#n\xb1\x81\xe9\xd0\
\xef^Tl\x1d\x1c\x89\x8aO\x0a\x14\xcd\xd0\xaf\x11\x0f\
\xcaT\xb4\xed\xd9xh\x06E*\xb4y\xdcI\xfa'\
\xdd\xdf\xe0E\xf4\x92N\x04y\xa6F\x90{x\x8d\xab\
\x7f\x19\xfe\xfb\xbf\x8a?\xb4\xdaaG\xaae\x1f\xa5\x00\
\x00\x00\x00IEND\xaeB`\x82\
"
qt_resource_name = b"\
\x00\x0b\
\x05:\xf2B\
\x00o\
\x00p\x00e\x00n\x00_\x00f\x00o\x00l\x00d\x00e\x00r\
\x00\x08\
\x08\x02\xf4>\
\x00M\
\x00a\x00i\x00n\x00I\x00c\x00o\x00n\
\x00\x0b\
\x07\x15<\x00\
\x00b\
\x00u\x00t\x00t\x00o\x00n\x00_\x00s\x00t\x00o\x00p\
\x00\x12\
\x0b\x84T\xe5\
\x00b\
\x00u\x00t\x00t\x00o\x00n\x00_\x00s\x00e\x00a\x00r\x00c\x00h\x00_\x00f\x00i\x00l\
\x00e\
\x00\x08\
\x0cY\xf4>\
\x00M\
\x00e\x00n\x00u\x00I\x00c\x00o\x00n\
\x00\x0d\
\x0b1\xac\x83\
\x00M\
\x00e\x00n\x00u\x00_\x00S\x00e\x00t\x00t\x00i\x00n\x00g\x00s\
\x00\x06\
\x07<[3\
\x00m\
\x00e\x00n\x00u\x00_\x00C\
\x00\x0c\
\x01S\xdet\
\x00b\
\x00u\x00t\x00t\x00o\x00n\x00_\x00s\x00t\x00a\x00r\x00t\
\x00\x12\
\x0f\xda\xb7\x05\
\x00b\
\x00u\x00t\x00t\x00o\x00n\x00_\x00o\x00u\x00t\x00p\x00u\x00t\x00_\x00f\x00i\x00l\
\x00e\
\x00\x07\
\x03\xc5\xb3\x93\
\x00m\
\x00e\x00n\x00u\x00_\x00C\x00C\
\x00\x03\
\x00\x00p7\
\x00i\
\x00m\x00g\
\x00\x0d\
\x0f\x0a\xde'\
\x00c\
\x00i\x00l\x00-\x00m\x00o\x00v\x00i\x00e\x00.\x00p\x00n\x00g\
\x00\x13\
\x04%\x01G\
\x00c\
\x00i\x00l\x00-\x00f\x00o\x00l\x00d\x00e\x00r\x00-\x00o\x00p\x00e\x00n\x00.\x00p\
\x00n\x00g\
\x00\x12\
\x0f\xad\x8fg\
\x00c\
\x00i\x00l\x00-\x00m\x00e\x00d\x00i\x00a\x00-\x00p\x00l\x00a\x00y\x00.\x00p\x00n\
\x00g\
\x00\x13\
\x07\x1d\xec\x87\
\x00c\
\x00i\x00l\x00-\x00v\x00i\x00e\x00w\x00-\x00m\x00o\x00d\x00u\x00l\x00e\x00.\x00p\
\x00n\x00g\
\x00\x1a\
\x08k\xa0\xa7\
\x00c\
\x00i\x00l\x00-\x00o\x00p\x00t\x00i\x00o\x00n\x00s\x00-\x00h\x00o\x00r\x00i\x00z\
\x00o\x00n\x00t\x00a\x00l\x00.\x00p\x00n\x00g\
\x00\x0c\
\x09k\xbf'\
\x00c\
\x00i\x00l\x00-\x00m\x00e\x00n\x00u\x00.\x00p\x00n\x00g\
\x00\x12\
\x06B\x8e\xc7\
\x00c\
\x00i\x00l\x00-\x00m\x00e\x00d\x00i\x00a\x00-\x00s\x00t\x00o\x00p\x00.\x00p\x00n\
\x00g\
\x00\x0e\
\x06P\xeb\xbf\
\x00m\
\x00a\x00i\x00n\x00_\x00i\x00c\x00o\x00n\x00e\x00.\x00i\x00c\x00o\
"
qt_resource_struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x0a\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\xc0\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1d\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01\x08\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1b\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x19\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x002\x00\x02\x00\x00\x00\x01\x00\x00\x00\x17\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\xae\x00\x02\x00\x00\x00\x01\x00\x00\x00\x15\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x13\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x8e\x00\x02\x00\x00\x00\x01\x00\x00\x00\x11\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00N\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0f\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00x\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0d\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\xde\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0b\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0c\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01H\x00\x00\x00\x00\x00\x01\x00\x00\x08\xdd\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x0e\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x02\x04\x00\x00\x00\x00\x00\x01\x00\x00(\xa2\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x10\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01(\x00\x00\x00\x00\x00\x01\x00\x00/\xbf\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x12\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01\xca\x00\x00\x00\x00\x00\x01\x00\x00 \xf5\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x14\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x02L\x00\x01\x00\x00\x00\x01\x00\x00?\xbd\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x16\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x18\xb3\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x18\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x02\x22\x00\x00\x00\x00\x00\x01\x00\x008\x9c\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1a\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01H\x00\x00\x00\x00\x00\x01\x00\x00B\x1a\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1c\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01(\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
\x00\x00\x01vT\xbc\x95?\
\x00\x00\x01\x1c\x00\x02\x00\x00\x00\x01\x00\x00\x00\x1e\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x01t\x00\x00\x00\x00\x00\x01\x00\x00\x10\xdd\
\x00\x00\x01vT\xbc\x95?\
"
def qInitResources():
QtCore.qRegisterResourceData(
0x03, qt_resource_struct, qt_resource_name, qt_resource_data
)
def qCleanupResources():
QtCore.qUnregisterResourceData(
0x03, qt_resource_struct, qt_resource_name, qt_resource_data
)
qInitResources() | 0.270288 | 0.279853 |
import benchmarkstt.docblock as docblock
from textwrap import dedent
import pytest
def test_text():
txt = " \t \t\n\n\t "
assert docblock.process_rst(txt, 'text') == ''
txt = '''
.. code-block:: text
Some block
In samem block
Still included
Not anymore
'''
print(docblock.process_rst(txt, 'text'))
assert docblock.process_rst(txt, 'text') == """Some block
In samem block
Still included
Not anymore"""
expected = '<blockquote>\n<pre class="code text literal-block"><code>Some block\n' \
'In samem block\n\nStill included</code></pre>\n<p>Not anymore</p>\n' \
'</blockquote>'
assert docblock.process_rst(txt, 'html') == expected
with pytest.raises(ValueError) as exc:
docblock.process_rst(txt, 'someunknownwriter')
assert 'Unknown writer' in str(exc)
def test_parse():
def dummy_func(config):
"""
The normalization rules are applied top-to-bottom and follow this format:
.. code-block:: text
Normalizer1 arg1 "arg 2"
# This is a comment
Normalizer2
# (Normalizer2 has no arguments)
Normalizer3 "This is argument 1
Spanning multiple lines
" "argument 2"
Normalizer4 "argument with double quote ("")"
:param config: configuration text
:example text: "He bravely turned his tail and fled"
:example config:
.. code-block:: text
# using a simple config file
Lowercase
# it even supports comments
# If there is a space in the argument,
# make sure you quote it though!
regex "y t" "Y T"
# extraneous whitespaces are ignored
replace e a
:example return: "ha bravalY Turnad his tail and flad"
"""
expected = docblock.Docblock(
docs=dedent('''
The normalization rules are applied top-to-bottom and follow this format:
.. code-block:: text
Normalizer1 arg1 "arg 2"
# This is a comment
Normalizer2
# (Normalizer2 has no arguments)
Normalizer3 "This is argument 1
Spanning multiple lines
" "argument 2"
Normalizer4 "argument with double quote ("")"
''').strip(),
params=[
docblock.Param(name='config', type=None, type_doc='str',
is_required=True, description='configuration text',
examples=[
{'text': docblock.DocblockParam(name='text', type=None,
value='He bravely turned his tail and fled'),
'config': docblock.DocblockParam(name='config', type=None, value=dedent('''
# using a simple config file
Lowercase
# it even supports comments
# If there is a space in the argument,
# make sure you quote it though!
regex "y t" "Y T"
# extraneous whitespaces are ignored
replace e a''').strip()),
'return': docblock.DocblockParam(name='return', type=None,
value='ha bravalY Turnad his tail and flad')
}
]
)
],
result=None,
result_type=None)
parsed = docblock.parse(dummy_func)
assert parsed.docs == expected.docs
def test_parse2():
def dummy_func(self):
"""
:return: Returns something
"""
parsed = docblock.parse(dummy_func)
assert parsed == docblock.Docblock(docs=':return: Returns something', params=[],
result='Returns something', result_type=None)
# todo: test the other Docblock properties as well
def test_decode_literal():
assert docblock.decode_literal(None) == ''
assert docblock.decode_literal('"hi!"') == 'hi!'
assert docblock.decode_literal('58') is 58
assert docblock.decode_literal('5.3') == 5.3
assert docblock.decode_literal('"') == '"' | tests/benchmarkstt/test_docblock.py | import benchmarkstt.docblock as docblock
from textwrap import dedent
import pytest
def test_text():
txt = " \t \t\n\n\t "
assert docblock.process_rst(txt, 'text') == ''
txt = '''
.. code-block:: text
Some block
In samem block
Still included
Not anymore
'''
print(docblock.process_rst(txt, 'text'))
assert docblock.process_rst(txt, 'text') == """Some block
In samem block
Still included
Not anymore"""
expected = '<blockquote>\n<pre class="code text literal-block"><code>Some block\n' \
'In samem block\n\nStill included</code></pre>\n<p>Not anymore</p>\n' \
'</blockquote>'
assert docblock.process_rst(txt, 'html') == expected
with pytest.raises(ValueError) as exc:
docblock.process_rst(txt, 'someunknownwriter')
assert 'Unknown writer' in str(exc)
def test_parse():
def dummy_func(config):
"""
The normalization rules are applied top-to-bottom and follow this format:
.. code-block:: text
Normalizer1 arg1 "arg 2"
# This is a comment
Normalizer2
# (Normalizer2 has no arguments)
Normalizer3 "This is argument 1
Spanning multiple lines
" "argument 2"
Normalizer4 "argument with double quote ("")"
:param config: configuration text
:example text: "He bravely turned his tail and fled"
:example config:
.. code-block:: text
# using a simple config file
Lowercase
# it even supports comments
# If there is a space in the argument,
# make sure you quote it though!
regex "y t" "Y T"
# extraneous whitespaces are ignored
replace e a
:example return: "ha bravalY Turnad his tail and flad"
"""
expected = docblock.Docblock(
docs=dedent('''
The normalization rules are applied top-to-bottom and follow this format:
.. code-block:: text
Normalizer1 arg1 "arg 2"
# This is a comment
Normalizer2
# (Normalizer2 has no arguments)
Normalizer3 "This is argument 1
Spanning multiple lines
" "argument 2"
Normalizer4 "argument with double quote ("")"
''').strip(),
params=[
docblock.Param(name='config', type=None, type_doc='str',
is_required=True, description='configuration text',
examples=[
{'text': docblock.DocblockParam(name='text', type=None,
value='He bravely turned his tail and fled'),
'config': docblock.DocblockParam(name='config', type=None, value=dedent('''
# using a simple config file
Lowercase
# it even supports comments
# If there is a space in the argument,
# make sure you quote it though!
regex "y t" "Y T"
# extraneous whitespaces are ignored
replace e a''').strip()),
'return': docblock.DocblockParam(name='return', type=None,
value='ha bravalY Turnad his tail and flad')
}
]
)
],
result=None,
result_type=None)
parsed = docblock.parse(dummy_func)
assert parsed.docs == expected.docs
def test_parse2():
def dummy_func(self):
"""
:return: Returns something
"""
parsed = docblock.parse(dummy_func)
assert parsed == docblock.Docblock(docs=':return: Returns something', params=[],
result='Returns something', result_type=None)
# todo: test the other Docblock properties as well
def test_decode_literal():
assert docblock.decode_literal(None) == ''
assert docblock.decode_literal('"hi!"') == 'hi!'
assert docblock.decode_literal('58') is 58
assert docblock.decode_literal('5.3') == 5.3
assert docblock.decode_literal('"') == '"' | 0.372277 | 0.486758 |
import numpy as np
import pandas as pd
import sys
import matplotlib
matplotlib.use("pgf")
import time
from matplotlib import pyplot as plt
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.externals import joblib
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.wrappers.scikit_learn import KerasRegressor
from keras.callbacks import EarlyStopping
from math import sqrt
from datetime import datetime
from keras import backend as kk
matplotlib.rcParams['text.latex.unicode']=True
matplotlib.rcParams['text.usetex']=True
matplotlib.rcParams['pgf.texsystem'] = 'pdflatex'
if kk.tensorflow_backend._get_available_gpus():
from keras.layers import CuDNNLSTM
print("Using GPU for training")
else:
from keras.layers import LSTM as CuDNNLSTM
print("Using CPU for training")
class Pollution:
def __init__(self):
self.loss = []
self.history = []
self.scalers = [MinMaxScaler(feature_range=(0, 1)), MinMaxScaler(feature_range=(0, 1))]
self.y = np.ndarray
self.times = []
self.predictions = []
self.split = 0
def parse_all(self, file):
print(file)
raw_data = pd.read_csv("Data/" + file + ".csv")
return raw_data
def model_compile_double(self, optimizer='adam', neurons1=50, neurons2=50, dropout1=0.2, dropout2=0.2):
model = Sequential()
model.add(CuDNNLSTM(neurons1, input_shape=(1, 16), return_sequences=True))
model.add(Dropout(dropout1))
model.add(CuDNNLSTM(neurons2))
model.add(Dropout(dropout2))
model.add(Dense(1))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mse'])
return model
def model_compile_triple(self, optimizer='adam', neurons1=50, neurons2=50, neurons3=50, dropout1=0.2, dropout2=0.2):
model = Sequential()
model.add(CuDNNLSTM(neurons1, input_shape=(1, 16), return_sequences=True))
model.add(Dropout(dropout1))
model.add(CuDNNLSTM(neurons2, return_sequences=True))
model.add(Dropout(dropout2))
model.add(CuDNNLSTM(neurons3))
model.add(Dense(1))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mse'])
return model
def model_fit(self, layers, train_X, train_y, label, test_X=0, epochs=50000, optim='adam', batch=10, save=False):
test_X = self.X_test if type(test_X) is int else test_X
test_y = self.y_test
start = datetime.now()
model = Sequential(layers)
model.compile(loss='mean_squared_error', optimizer=optim)
hist = model.fit(train_X, train_y, batch_size=batch, epochs=epochs, verbose=self.verbosity, shuffle=False, validation_data=(test_X, test_y))
model.summary()
if save:
model.save("models/lstm.h5")
joblib.dump(self.scalers[1], "models/x_scaler.save")
joblib.dump(self.scalers[0], "models/y_scaler.save")
all_X = np.concatenate((train_X, test_X))
yhat = model.predict(all_X)
inv_yhat = self.scalers[0].inverse_transform(yhat)
# Himua na ang predictions kayma pasa nalang sa dictionry para ma chuy, pero nag groupings must be in a special way
self.predictor_magtanggol(inv_yhat, label)
self.create_loss(hist, label)
self.times.append(datetime.now() - start)
def manual(self, X, y):
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dropout(0.2),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, optim='rmsprop', batch=50, label="basic_rmsprop2")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dropout(0.2),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, optim='adam', batch=50, label="basic_adam2")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dropout(0.2),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=20, label="Lower_batch2")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dropout(0.2),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, label="Lowest_batch2")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=50, label="basic3")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=5, label="lower_batch3")
self.model_fit([CuDNNLSTM(150, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(250, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(200),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, label="high_neuron3")
self.model_fit([CuDNNLSTM(150, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(300, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(200, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(450),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=20, label="basic4")
self.model_fit([CuDNNLSTM(150, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(300, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(200, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(450),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=5, label="lower_batch4")
self.model_fit([CuDNNLSTM(250, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(200, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(300),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=5, label="Grid Searched")
# self.graph_flush("optimizer.pdf", [1, 2])
# self.graph_flush("batch_size.pdf", [1, 3, 4])
# self.graph_flush("layer_3.pdf", [3, 6, 7])
# self.graph_flush("grid_search.pdf", [6, 10])
# self.graph_flush("ffdnn.pdf", [0, 10])
def graph_flush(self, fn, models):
plt.gcf().clear()
fig = plt.figure()
a = np.array(self.history)
for i in a[models]:
sub1 = fig.add_subplot(2, 1, 1)
sub1.plot(i['loss'], label=i['label'])
sub1.set_title('Train Loss')
sub2 = fig.add_subplot(2, 1, 2)
sub2.plot(i['val_loss'], label=i['label'])
sub2.set_title('Test Loss')
sub1.legend(loc=2)
sub2.legend(loc=2)
plt.savefig("Data/"+fn, bbox_inches='tight')
plt.gcf().clear()
plt.plot(self.y, label="real")
for vals in [self.predictions[i] for i in models]:
plt.plot(vals[0], label=vals[1])
plt.legend(loc=2)
plt.savefig("Data/predictions_" + fn, bbox_inches='tight')
plt.gcf().clear()
def predictor_magtanggol(self, inv_yhat, label):
yforms = [self.y, inv_yhat,
self.y[self.split:], inv_yhat[self.split:],
self.y[:self.split], inv_yhat[:self.split]]
self.predictions.append((yforms[1], label))
self.loss.append((sqrt(mean_squared_error(yforms[0], yforms[1])), mean_absolute_error(yforms[0], yforms[1]),
sqrt(mean_squared_error(yforms[2], yforms[3])), mean_absolute_error(yforms[2], yforms[3]),
sqrt(mean_squared_error(yforms[4], yforms[5])), mean_absolute_error(yforms[4], yforms[5])))
def create_loss(self, hist, label):
self.history.append({'loss': hist.history['loss'], 'val_loss': hist.history['val_loss'], 'label': label})
plt.subplot(2, 1, 1)
plt.plot(hist.history['loss'], label=label)
plt.ylabel('Train Loss')
plt.subplot(2, 1, 2)
plt.plot(hist.history['val_loss'], label=label)
plt.ylabel('Test Loss')
def main(self, verbosity, auto, graphing):
self.verbosity = verbosity
holder = {}
X = pd.DataFrame()
for year in range(15, 18):
for station in [2, 7, 11, 14]:
file = str(station).zfill(2) + '_' + str(year)
y = self.parse_all(file)
if year in holder:
holder[year] = pd.merge(holder[year], y, how="outer", on="date", sort=False)
else:
holder[year] = y
for key in holder:
X = X.append(other=holder[key], ignore_index=True)
X.to_csv("Data/Features.csv")
X.dropna(thresh=6, inplace=True)
X.fillna(-1, inplace=True)
target_raw = pd.read_csv("Data/MonthlyTarget.csv")
weeks = [0 for _ in range(len(target_raw))]
for date in X['date'].get_values():
which = (int(date[2:-3]) - 1) + (int(date[-2:]) - 15) * 12
weeks[which] = weeks[which] + 1
print(weeks)
print("Shape of features {}".format(X.shape))
targets = target_raw['target'].get_values()
y = []
for ind, people in enumerate(targets):
amp = [people // weeks[ind] for _ in range(weeks[ind])]
y.extend(amp)
print(y)
pd.Series(y).to_csv("Data/Targets.csv")
printable = X
printable['target'] = pd.Series(y, index=X.index)
printable.to_csv("Data/ProcessedData.csv")
self.y = pd.Series(y).values.astype('float32').reshape(-1, 1)
print("Average value of targets {}".format(self.y.mean()))
self.split = (self.y.shape[0] // 3) * 2
y = self.scalers[0].fit_transform(self.y)
#y.to_csv("Data/TargetsScaled.csv")
self.y_test = y[self.split:, :]
y = y[:self.split, :]
# X = pd.read_csv("KNN.csv")
X = X.drop("date", axis=1)
print(X[:5])
X = X.values.astype('float32')
svm_X=X
X = self.scalers[1].fit_transform(X)
all_X = X.reshape((X.shape[0], 1, X.shape[1]))
self.X_test = X[self.split:]
self.X_test = self.X_test.reshape((self.X_test.shape[0], 1, self.X_test.shape[1]))
X = X[:self.split]
X = X.reshape((X.shape[0], 1, X.shape[1]))
print("{} {}".format(X.shape, y.shape))
startTime = datetime.now()
# Basic feed forward neural network
mlp_train_X = self.scalers[1].transform(svm_X[:self.split])
mlp_test_X = self.scalers[1].transform(svm_X[self.split:])
self.model_fit([Dense(12, input_dim=svm_X.shape[1], activation='relu'),
Dense(8, activation='relu'),
Dense(1)],
train_X=mlp_train_X, train_y=y, test_X=mlp_test_X, optim='adam', epochs=500, batch=2, label="FFDNN")
if auto == 0:
self.manual(X, y)
for ind, x in enumerate(self.times):
print("Time for {}:{}".format(self.history[ind]['label'], x))
print("\nTraining time of All Models {}\n".format(datetime.now() - startTime))
split = (self.split / self.y.shape[0]) * 100
print("Train-Test split: {:.2f} {:.2f}".format(split, 100 - split))
for index, error in enumerate(self.loss):
print(
'Model {}:\nTotal RMSE: {:.2f}\nTotal MAE: {:.2f}\nTrain RMSE: {:.2f}\nTrain MAE: {:.2f}'.format(self.history[index]['label'], error[0], error[1], error[2], error[3]))
print('\nTest RMSE: {:.2f}\nTest MAE: {:.2f}\n'.format(error[4], error[5]))
print('{:.2f}\n{:.2f}'.format(error[4], error[5]), file=open("Data/Loss_vals.txt", "a"))
else:
print("Starting GridSearch in 5")
time.sleep(5)
param_grid = {'neurons1': list(range(100, 325, 75)),
'neurons2': list(range(200, 500, 100)),
# 'neurons3': list(range(200, 500, 150)),
'dropout1': [0.2],
'dropout2': [0.2],
'optimizer': ['adam', 'rmsprop'],
'batch_size': [5, 20, 50]}
# model = KerasRegressor(build_fn=self.model_compile_triple, epochs=500, batch_size=10, verbose=verbosity)
model = KerasRegressor(build_fn=self.model_compile_double, epochs=500, batch_size=10, verbose=verbosity)
my_cv = TimeSeriesSplit(n_splits=2).split(X)
grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=my_cv)
grid.fit(X, y)
print("\nTraining time of All Models {}\n".format(datetime.now() - startTime))
print("Best: {:.2f} using {}".format(grid.best_score_, grid.best_params_))
yhat = grid.best_estimator_.predict(all_X)
yhat = pd.Series(yhat).values.astype('float32').reshape(-1, 1)
inv_yhat = self.scalers[0].inverse_transform(yhat)
self.predictor_magtanggol(inv_yhat, "Best")
plt.legend(loc=2)
if graphing < 1:
plt.show()
plt.gcf().clear()
# self.graph_flush("all_models.pdf", [i for i in range(0, 11)])
if __name__ == "__main__":
if len(sys.argv) > 1:
x = int(sys.argv[1]) % 2
z = int(sys.argv[1])//2
if len(sys.argv) > 2:
y = int(sys.argv[2])
else:
y = 0
else:
x = 0
y = 0
z = 0
Pollution().main(x, y, z) | src/health_lstm.py | import numpy as np
import pandas as pd
import sys
import matplotlib
matplotlib.use("pgf")
import time
from matplotlib import pyplot as plt
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.externals import joblib
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.wrappers.scikit_learn import KerasRegressor
from keras.callbacks import EarlyStopping
from math import sqrt
from datetime import datetime
from keras import backend as kk
matplotlib.rcParams['text.latex.unicode']=True
matplotlib.rcParams['text.usetex']=True
matplotlib.rcParams['pgf.texsystem'] = 'pdflatex'
if kk.tensorflow_backend._get_available_gpus():
from keras.layers import CuDNNLSTM
print("Using GPU for training")
else:
from keras.layers import LSTM as CuDNNLSTM
print("Using CPU for training")
class Pollution:
def __init__(self):
self.loss = []
self.history = []
self.scalers = [MinMaxScaler(feature_range=(0, 1)), MinMaxScaler(feature_range=(0, 1))]
self.y = np.ndarray
self.times = []
self.predictions = []
self.split = 0
def parse_all(self, file):
print(file)
raw_data = pd.read_csv("Data/" + file + ".csv")
return raw_data
def model_compile_double(self, optimizer='adam', neurons1=50, neurons2=50, dropout1=0.2, dropout2=0.2):
model = Sequential()
model.add(CuDNNLSTM(neurons1, input_shape=(1, 16), return_sequences=True))
model.add(Dropout(dropout1))
model.add(CuDNNLSTM(neurons2))
model.add(Dropout(dropout2))
model.add(Dense(1))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mse'])
return model
def model_compile_triple(self, optimizer='adam', neurons1=50, neurons2=50, neurons3=50, dropout1=0.2, dropout2=0.2):
model = Sequential()
model.add(CuDNNLSTM(neurons1, input_shape=(1, 16), return_sequences=True))
model.add(Dropout(dropout1))
model.add(CuDNNLSTM(neurons2, return_sequences=True))
model.add(Dropout(dropout2))
model.add(CuDNNLSTM(neurons3))
model.add(Dense(1))
model.add(Activation('linear'))
model.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mse'])
return model
def model_fit(self, layers, train_X, train_y, label, test_X=0, epochs=50000, optim='adam', batch=10, save=False):
test_X = self.X_test if type(test_X) is int else test_X
test_y = self.y_test
start = datetime.now()
model = Sequential(layers)
model.compile(loss='mean_squared_error', optimizer=optim)
hist = model.fit(train_X, train_y, batch_size=batch, epochs=epochs, verbose=self.verbosity, shuffle=False, validation_data=(test_X, test_y))
model.summary()
if save:
model.save("models/lstm.h5")
joblib.dump(self.scalers[1], "models/x_scaler.save")
joblib.dump(self.scalers[0], "models/y_scaler.save")
all_X = np.concatenate((train_X, test_X))
yhat = model.predict(all_X)
inv_yhat = self.scalers[0].inverse_transform(yhat)
# Himua na ang predictions kayma pasa nalang sa dictionry para ma chuy, pero nag groupings must be in a special way
self.predictor_magtanggol(inv_yhat, label)
self.create_loss(hist, label)
self.times.append(datetime.now() - start)
def manual(self, X, y):
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dropout(0.2),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, optim='rmsprop', batch=50, label="basic_rmsprop2")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dropout(0.2),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, optim='adam', batch=50, label="basic_adam2")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dropout(0.2),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=20, label="Lower_batch2")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dropout(0.2),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, label="Lowest_batch2")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=50, label="basic3")
self.model_fit([CuDNNLSTM(50, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(100),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=5, label="lower_batch3")
self.model_fit([CuDNNLSTM(150, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(250, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(200),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, label="high_neuron3")
self.model_fit([CuDNNLSTM(150, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(300, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(200, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(450),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=20, label="basic4")
self.model_fit([CuDNNLSTM(150, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(300, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(200, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(450),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=5, label="lower_batch4")
self.model_fit([CuDNNLSTM(250, input_shape=(X.shape[1], X.shape[2]), return_sequences=True),
Dropout(0.2),
CuDNNLSTM(200, return_sequences=True),
Dropout(0.2),
CuDNNLSTM(300),
Dense(1),
Activation('linear')],
train_X=X, train_y=y, batch=5, label="Grid Searched")
# self.graph_flush("optimizer.pdf", [1, 2])
# self.graph_flush("batch_size.pdf", [1, 3, 4])
# self.graph_flush("layer_3.pdf", [3, 6, 7])
# self.graph_flush("grid_search.pdf", [6, 10])
# self.graph_flush("ffdnn.pdf", [0, 10])
def graph_flush(self, fn, models):
plt.gcf().clear()
fig = plt.figure()
a = np.array(self.history)
for i in a[models]:
sub1 = fig.add_subplot(2, 1, 1)
sub1.plot(i['loss'], label=i['label'])
sub1.set_title('Train Loss')
sub2 = fig.add_subplot(2, 1, 2)
sub2.plot(i['val_loss'], label=i['label'])
sub2.set_title('Test Loss')
sub1.legend(loc=2)
sub2.legend(loc=2)
plt.savefig("Data/"+fn, bbox_inches='tight')
plt.gcf().clear()
plt.plot(self.y, label="real")
for vals in [self.predictions[i] for i in models]:
plt.plot(vals[0], label=vals[1])
plt.legend(loc=2)
plt.savefig("Data/predictions_" + fn, bbox_inches='tight')
plt.gcf().clear()
def predictor_magtanggol(self, inv_yhat, label):
yforms = [self.y, inv_yhat,
self.y[self.split:], inv_yhat[self.split:],
self.y[:self.split], inv_yhat[:self.split]]
self.predictions.append((yforms[1], label))
self.loss.append((sqrt(mean_squared_error(yforms[0], yforms[1])), mean_absolute_error(yforms[0], yforms[1]),
sqrt(mean_squared_error(yforms[2], yforms[3])), mean_absolute_error(yforms[2], yforms[3]),
sqrt(mean_squared_error(yforms[4], yforms[5])), mean_absolute_error(yforms[4], yforms[5])))
def create_loss(self, hist, label):
self.history.append({'loss': hist.history['loss'], 'val_loss': hist.history['val_loss'], 'label': label})
plt.subplot(2, 1, 1)
plt.plot(hist.history['loss'], label=label)
plt.ylabel('Train Loss')
plt.subplot(2, 1, 2)
plt.plot(hist.history['val_loss'], label=label)
plt.ylabel('Test Loss')
def main(self, verbosity, auto, graphing):
self.verbosity = verbosity
holder = {}
X = pd.DataFrame()
for year in range(15, 18):
for station in [2, 7, 11, 14]:
file = str(station).zfill(2) + '_' + str(year)
y = self.parse_all(file)
if year in holder:
holder[year] = pd.merge(holder[year], y, how="outer", on="date", sort=False)
else:
holder[year] = y
for key in holder:
X = X.append(other=holder[key], ignore_index=True)
X.to_csv("Data/Features.csv")
X.dropna(thresh=6, inplace=True)
X.fillna(-1, inplace=True)
target_raw = pd.read_csv("Data/MonthlyTarget.csv")
weeks = [0 for _ in range(len(target_raw))]
for date in X['date'].get_values():
which = (int(date[2:-3]) - 1) + (int(date[-2:]) - 15) * 12
weeks[which] = weeks[which] + 1
print(weeks)
print("Shape of features {}".format(X.shape))
targets = target_raw['target'].get_values()
y = []
for ind, people in enumerate(targets):
amp = [people // weeks[ind] for _ in range(weeks[ind])]
y.extend(amp)
print(y)
pd.Series(y).to_csv("Data/Targets.csv")
printable = X
printable['target'] = pd.Series(y, index=X.index)
printable.to_csv("Data/ProcessedData.csv")
self.y = pd.Series(y).values.astype('float32').reshape(-1, 1)
print("Average value of targets {}".format(self.y.mean()))
self.split = (self.y.shape[0] // 3) * 2
y = self.scalers[0].fit_transform(self.y)
#y.to_csv("Data/TargetsScaled.csv")
self.y_test = y[self.split:, :]
y = y[:self.split, :]
# X = pd.read_csv("KNN.csv")
X = X.drop("date", axis=1)
print(X[:5])
X = X.values.astype('float32')
svm_X=X
X = self.scalers[1].fit_transform(X)
all_X = X.reshape((X.shape[0], 1, X.shape[1]))
self.X_test = X[self.split:]
self.X_test = self.X_test.reshape((self.X_test.shape[0], 1, self.X_test.shape[1]))
X = X[:self.split]
X = X.reshape((X.shape[0], 1, X.shape[1]))
print("{} {}".format(X.shape, y.shape))
startTime = datetime.now()
# Basic feed forward neural network
mlp_train_X = self.scalers[1].transform(svm_X[:self.split])
mlp_test_X = self.scalers[1].transform(svm_X[self.split:])
self.model_fit([Dense(12, input_dim=svm_X.shape[1], activation='relu'),
Dense(8, activation='relu'),
Dense(1)],
train_X=mlp_train_X, train_y=y, test_X=mlp_test_X, optim='adam', epochs=500, batch=2, label="FFDNN")
if auto == 0:
self.manual(X, y)
for ind, x in enumerate(self.times):
print("Time for {}:{}".format(self.history[ind]['label'], x))
print("\nTraining time of All Models {}\n".format(datetime.now() - startTime))
split = (self.split / self.y.shape[0]) * 100
print("Train-Test split: {:.2f} {:.2f}".format(split, 100 - split))
for index, error in enumerate(self.loss):
print(
'Model {}:\nTotal RMSE: {:.2f}\nTotal MAE: {:.2f}\nTrain RMSE: {:.2f}\nTrain MAE: {:.2f}'.format(self.history[index]['label'], error[0], error[1], error[2], error[3]))
print('\nTest RMSE: {:.2f}\nTest MAE: {:.2f}\n'.format(error[4], error[5]))
print('{:.2f}\n{:.2f}'.format(error[4], error[5]), file=open("Data/Loss_vals.txt", "a"))
else:
print("Starting GridSearch in 5")
time.sleep(5)
param_grid = {'neurons1': list(range(100, 325, 75)),
'neurons2': list(range(200, 500, 100)),
# 'neurons3': list(range(200, 500, 150)),
'dropout1': [0.2],
'dropout2': [0.2],
'optimizer': ['adam', 'rmsprop'],
'batch_size': [5, 20, 50]}
# model = KerasRegressor(build_fn=self.model_compile_triple, epochs=500, batch_size=10, verbose=verbosity)
model = KerasRegressor(build_fn=self.model_compile_double, epochs=500, batch_size=10, verbose=verbosity)
my_cv = TimeSeriesSplit(n_splits=2).split(X)
grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=my_cv)
grid.fit(X, y)
print("\nTraining time of All Models {}\n".format(datetime.now() - startTime))
print("Best: {:.2f} using {}".format(grid.best_score_, grid.best_params_))
yhat = grid.best_estimator_.predict(all_X)
yhat = pd.Series(yhat).values.astype('float32').reshape(-1, 1)
inv_yhat = self.scalers[0].inverse_transform(yhat)
self.predictor_magtanggol(inv_yhat, "Best")
plt.legend(loc=2)
if graphing < 1:
plt.show()
plt.gcf().clear()
# self.graph_flush("all_models.pdf", [i for i in range(0, 11)])
if __name__ == "__main__":
if len(sys.argv) > 1:
x = int(sys.argv[1]) % 2
z = int(sys.argv[1])//2
if len(sys.argv) > 2:
y = int(sys.argv[2])
else:
y = 0
else:
x = 0
y = 0
z = 0
Pollution().main(x, y, z) | 0.70912 | 0.322033 |
import configargparse
from pathlib import Path
from icalendar import Calendar, Event
import datetime
import os
import requests
parser = configargparse.ArgParser(default_config_files=['~/.config/calreader.ini'],description="""
Downloads a webcal file and schedules an external file to run at
the beginning of each event. This can be used to play a sound or
show an alert with an external script.""")
parser.add("-c","--config", help="""
Specify configration file to use. Command line options override
the config file. Defaults to ~/.config/calreader.ini""",is_config_file=True)
#ArgumentParser(description="Downloads a webcal file and schedules an external file to run at the beginning of each event. This can be used to play a sound or show an alert with an exteranl script.")
parser.add_argument("--url",help="URL of a webcal or ICS file to parse",default="",required=True)
parser.add_argument("-p","--prefix", help="Prefix or path to executable script. Defaults to ~/",default="~/")
parser.add_argument("-s","--suffix", help="Suffix of path to executable script. Defaults to .sh",default=".sh")
parser.add_argument("-d","--dryrun", "--debug", help="Dry run mode. Shows commands to be executed, but does not schedule them",action="store_true",default=False)
parser.add_argument("-q","--queue", help="Queue to use for the at command. Limited to a single letter. Defaults to s (as in schedule or sound)",default="s")
parser.add_argument("-v","--verbose", help="Show details about the process.",action="store_true",default=False)
parser.add_argument("-e","--everything", help="Process all events in the file. Defaults to today only",action="store_true",default=False)
options = parser.parse_args()
resp = requests.get(options.url)
if resp.status_code != 200:
print (f'Unable to download calendar from URL:\n{options.url}\nPlease check your schedule elsewhere!')
exit(-1)
cal = Calendar.from_ical(resp.content)
today = datetime.datetime.now()
if options.everything == False:
print (f'Loading events for {today.date()}.')
else:
print (f'Loading all events in calendar.')
for c in cal.walk():
if c.name == 'VEVENT':
dtstart = c.decoded('DTSTART')
dtend = c.decoded('DTEND')
if options.everything or dtstart.date() == today.date():
if options.verbose:
print (f"{c['DESCRIPTION']} begins at {dtstart.astimezone()} and ends at {dtend.astimezone()}.")
exefile = c['DESCRIPTION'].replace(' ','-').lower()
timestr = dtstart.astimezone().strftime('%Y%m%d%H%M')
if options.dryrun:
print ('Command not executed: ',end='')
atcmd = f"at -q {options.queue} -f {options.prefix}{exefile}{options.suffix} -t {timestr}"
if options.dryrun or options.verbose:
print(atcmd)
if not options.dryrun:
os.system(atcmd) | calreader2.py | import configargparse
from pathlib import Path
from icalendar import Calendar, Event
import datetime
import os
import requests
parser = configargparse.ArgParser(default_config_files=['~/.config/calreader.ini'],description="""
Downloads a webcal file and schedules an external file to run at
the beginning of each event. This can be used to play a sound or
show an alert with an external script.""")
parser.add("-c","--config", help="""
Specify configration file to use. Command line options override
the config file. Defaults to ~/.config/calreader.ini""",is_config_file=True)
#ArgumentParser(description="Downloads a webcal file and schedules an external file to run at the beginning of each event. This can be used to play a sound or show an alert with an exteranl script.")
parser.add_argument("--url",help="URL of a webcal or ICS file to parse",default="",required=True)
parser.add_argument("-p","--prefix", help="Prefix or path to executable script. Defaults to ~/",default="~/")
parser.add_argument("-s","--suffix", help="Suffix of path to executable script. Defaults to .sh",default=".sh")
parser.add_argument("-d","--dryrun", "--debug", help="Dry run mode. Shows commands to be executed, but does not schedule them",action="store_true",default=False)
parser.add_argument("-q","--queue", help="Queue to use for the at command. Limited to a single letter. Defaults to s (as in schedule or sound)",default="s")
parser.add_argument("-v","--verbose", help="Show details about the process.",action="store_true",default=False)
parser.add_argument("-e","--everything", help="Process all events in the file. Defaults to today only",action="store_true",default=False)
options = parser.parse_args()
resp = requests.get(options.url)
if resp.status_code != 200:
print (f'Unable to download calendar from URL:\n{options.url}\nPlease check your schedule elsewhere!')
exit(-1)
cal = Calendar.from_ical(resp.content)
today = datetime.datetime.now()
if options.everything == False:
print (f'Loading events for {today.date()}.')
else:
print (f'Loading all events in calendar.')
for c in cal.walk():
if c.name == 'VEVENT':
dtstart = c.decoded('DTSTART')
dtend = c.decoded('DTEND')
if options.everything or dtstart.date() == today.date():
if options.verbose:
print (f"{c['DESCRIPTION']} begins at {dtstart.astimezone()} and ends at {dtend.astimezone()}.")
exefile = c['DESCRIPTION'].replace(' ','-').lower()
timestr = dtstart.astimezone().strftime('%Y%m%d%H%M')
if options.dryrun:
print ('Command not executed: ',end='')
atcmd = f"at -q {options.queue} -f {options.prefix}{exefile}{options.suffix} -t {timestr}"
if options.dryrun or options.verbose:
print(atcmd)
if not options.dryrun:
os.system(atcmd) | 0.255251 | 0.159512 |
import pprint
import re # noqa: F401
import six
from swagger_client.configuration import Configuration
class TpdmStaffTeacherPreparationProviderAssociation(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 = {
'id': 'str',
'school_year_type_reference': 'EdFiSchoolYearTypeReference',
'staff_reference': 'EdFiStaffReference',
'teacher_preparation_provider_reference': 'TpdmTeacherPreparationProviderReference',
'academic_subjects': 'list[TpdmStaffTeacherPreparationProviderAssociationAcademicSubject]',
'grade_levels': 'list[TpdmStaffTeacherPreparationProviderAssociationGradeLevel]',
'program_assignment_descriptor': 'str',
'etag': 'str'
}
attribute_map = {
'id': 'id',
'school_year_type_reference': 'schoolYearTypeReference',
'staff_reference': 'staffReference',
'teacher_preparation_provider_reference': 'teacherPreparationProviderReference',
'academic_subjects': 'academicSubjects',
'grade_levels': 'gradeLevels',
'program_assignment_descriptor': 'programAssignmentDescriptor',
'etag': '_etag'
}
def __init__(self, id=None, school_year_type_reference=None, staff_reference=None, teacher_preparation_provider_reference=None, academic_subjects=None, grade_levels=None, program_assignment_descriptor=None, etag=None, _configuration=None): # noqa: E501
"""TpdmStaffTeacherPreparationProviderAssociation - a model defined in Swagger""" # noqa: E501
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._id = None
self._school_year_type_reference = None
self._staff_reference = None
self._teacher_preparation_provider_reference = None
self._academic_subjects = None
self._grade_levels = None
self._program_assignment_descriptor = None
self._etag = None
self.discriminator = None
if id is not None:
self.id = id
self.school_year_type_reference = school_year_type_reference
self.staff_reference = staff_reference
self.teacher_preparation_provider_reference = teacher_preparation_provider_reference
if academic_subjects is not None:
self.academic_subjects = academic_subjects
if grade_levels is not None:
self.grade_levels = grade_levels
self.program_assignment_descriptor = program_assignment_descriptor
if etag is not None:
self.etag = etag
@property
def id(self):
"""Gets the id of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
# noqa: E501
:return: The id of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this TpdmStaffTeacherPreparationProviderAssociation.
# noqa: E501
:param id: The id of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: str
"""
self._id = id
@property
def school_year_type_reference(self):
"""Gets the school_year_type_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:return: The school_year_type_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: EdFiSchoolYearTypeReference
"""
return self._school_year_type_reference
@school_year_type_reference.setter
def school_year_type_reference(self, school_year_type_reference):
"""Sets the school_year_type_reference of this TpdmStaffTeacherPreparationProviderAssociation.
:param school_year_type_reference: The school_year_type_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: EdFiSchoolYearTypeReference
"""
if self._configuration.client_side_validation and school_year_type_reference is None:
raise ValueError("Invalid value for `school_year_type_reference`, must not be `None`") # noqa: E501
self._school_year_type_reference = school_year_type_reference
@property
def staff_reference(self):
"""Gets the staff_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:return: The staff_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: EdFiStaffReference
"""
return self._staff_reference
@staff_reference.setter
def staff_reference(self, staff_reference):
"""Sets the staff_reference of this TpdmStaffTeacherPreparationProviderAssociation.
:param staff_reference: The staff_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: EdFiStaffReference
"""
if self._configuration.client_side_validation and staff_reference is None:
raise ValueError("Invalid value for `staff_reference`, must not be `None`") # noqa: E501
self._staff_reference = staff_reference
@property
def teacher_preparation_provider_reference(self):
"""Gets the teacher_preparation_provider_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:return: The teacher_preparation_provider_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: TpdmTeacherPreparationProviderReference
"""
return self._teacher_preparation_provider_reference
@teacher_preparation_provider_reference.setter
def teacher_preparation_provider_reference(self, teacher_preparation_provider_reference):
"""Sets the teacher_preparation_provider_reference of this TpdmStaffTeacherPreparationProviderAssociation.
:param teacher_preparation_provider_reference: The teacher_preparation_provider_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: TpdmTeacherPreparationProviderReference
"""
if self._configuration.client_side_validation and teacher_preparation_provider_reference is None:
raise ValueError("Invalid value for `teacher_preparation_provider_reference`, must not be `None`") # noqa: E501
self._teacher_preparation_provider_reference = teacher_preparation_provider_reference
@property
def academic_subjects(self):
"""Gets the academic_subjects of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
An unordered collection of staffTeacherPreparationProviderAssociationAcademicSubjects. The description of the content or subject area (e.g., arts, mathematics, reading, stenography, or a foreign language) of a degree. # noqa: E501
:return: The academic_subjects of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: list[TpdmStaffTeacherPreparationProviderAssociationAcademicSubject]
"""
return self._academic_subjects
@academic_subjects.setter
def academic_subjects(self, academic_subjects):
"""Sets the academic_subjects of this TpdmStaffTeacherPreparationProviderAssociation.
An unordered collection of staffTeacherPreparationProviderAssociationAcademicSubjects. The description of the content or subject area (e.g., arts, mathematics, reading, stenography, or a foreign language) of a degree. # noqa: E501
:param academic_subjects: The academic_subjects of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: list[TpdmStaffTeacherPreparationProviderAssociationAcademicSubject]
"""
self._academic_subjects = academic_subjects
@property
def grade_levels(self):
"""Gets the grade_levels of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
An unordered collection of staffTeacherPreparationProviderAssociationGradeLevels. The grade levels for the association. # noqa: E501
:return: The grade_levels of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: list[TpdmStaffTeacherPreparationProviderAssociationGradeLevel]
"""
return self._grade_levels
@grade_levels.setter
def grade_levels(self, grade_levels):
"""Sets the grade_levels of this TpdmStaffTeacherPreparationProviderAssociation.
An unordered collection of staffTeacherPreparationProviderAssociationGradeLevels. The grade levels for the association. # noqa: E501
:param grade_levels: The grade_levels of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: list[TpdmStaffTeacherPreparationProviderAssociationGradeLevel]
"""
self._grade_levels = grade_levels
@property
def program_assignment_descriptor(self):
"""Gets the program_assignment_descriptor of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
Program Assignment for the association # noqa: E501
:return: The program_assignment_descriptor of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: str
"""
return self._program_assignment_descriptor
@program_assignment_descriptor.setter
def program_assignment_descriptor(self, program_assignment_descriptor):
"""Sets the program_assignment_descriptor of this TpdmStaffTeacherPreparationProviderAssociation.
Program Assignment for the association # noqa: E501
:param program_assignment_descriptor: The program_assignment_descriptor of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: str
"""
if self._configuration.client_side_validation and program_assignment_descriptor is None:
raise ValueError("Invalid value for `program_assignment_descriptor`, must not be `None`") # noqa: E501
if (self._configuration.client_side_validation and
program_assignment_descriptor is not None and len(program_assignment_descriptor) > 306):
raise ValueError("Invalid value for `program_assignment_descriptor`, length must be less than or equal to `306`") # noqa: E501
self._program_assignment_descriptor = program_assignment_descriptor
@property
def etag(self):
"""Gets the etag of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
A unique system-generated value that identifies the version of the resource. # noqa: E501
:return: The etag of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: str
"""
return self._etag
@etag.setter
def etag(self, etag):
"""Sets the etag of this TpdmStaffTeacherPreparationProviderAssociation.
A unique system-generated value that identifies the version of the resource. # noqa: E501
:param etag: The etag of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: str
"""
self._etag = etag
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(TpdmStaffTeacherPreparationProviderAssociation, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, TpdmStaffTeacherPreparationProviderAssociation):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, TpdmStaffTeacherPreparationProviderAssociation):
return True
return self.to_dict() != other.to_dict() | src/v5.1/resources/swagger_client/models/tpdm_staff_teacher_preparation_provider_association.py | import pprint
import re # noqa: F401
import six
from swagger_client.configuration import Configuration
class TpdmStaffTeacherPreparationProviderAssociation(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 = {
'id': 'str',
'school_year_type_reference': 'EdFiSchoolYearTypeReference',
'staff_reference': 'EdFiStaffReference',
'teacher_preparation_provider_reference': 'TpdmTeacherPreparationProviderReference',
'academic_subjects': 'list[TpdmStaffTeacherPreparationProviderAssociationAcademicSubject]',
'grade_levels': 'list[TpdmStaffTeacherPreparationProviderAssociationGradeLevel]',
'program_assignment_descriptor': 'str',
'etag': 'str'
}
attribute_map = {
'id': 'id',
'school_year_type_reference': 'schoolYearTypeReference',
'staff_reference': 'staffReference',
'teacher_preparation_provider_reference': 'teacherPreparationProviderReference',
'academic_subjects': 'academicSubjects',
'grade_levels': 'gradeLevels',
'program_assignment_descriptor': 'programAssignmentDescriptor',
'etag': '_etag'
}
def __init__(self, id=None, school_year_type_reference=None, staff_reference=None, teacher_preparation_provider_reference=None, academic_subjects=None, grade_levels=None, program_assignment_descriptor=None, etag=None, _configuration=None): # noqa: E501
"""TpdmStaffTeacherPreparationProviderAssociation - a model defined in Swagger""" # noqa: E501
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._id = None
self._school_year_type_reference = None
self._staff_reference = None
self._teacher_preparation_provider_reference = None
self._academic_subjects = None
self._grade_levels = None
self._program_assignment_descriptor = None
self._etag = None
self.discriminator = None
if id is not None:
self.id = id
self.school_year_type_reference = school_year_type_reference
self.staff_reference = staff_reference
self.teacher_preparation_provider_reference = teacher_preparation_provider_reference
if academic_subjects is not None:
self.academic_subjects = academic_subjects
if grade_levels is not None:
self.grade_levels = grade_levels
self.program_assignment_descriptor = program_assignment_descriptor
if etag is not None:
self.etag = etag
@property
def id(self):
"""Gets the id of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
# noqa: E501
:return: The id of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this TpdmStaffTeacherPreparationProviderAssociation.
# noqa: E501
:param id: The id of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: str
"""
self._id = id
@property
def school_year_type_reference(self):
"""Gets the school_year_type_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:return: The school_year_type_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: EdFiSchoolYearTypeReference
"""
return self._school_year_type_reference
@school_year_type_reference.setter
def school_year_type_reference(self, school_year_type_reference):
"""Sets the school_year_type_reference of this TpdmStaffTeacherPreparationProviderAssociation.
:param school_year_type_reference: The school_year_type_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: EdFiSchoolYearTypeReference
"""
if self._configuration.client_side_validation and school_year_type_reference is None:
raise ValueError("Invalid value for `school_year_type_reference`, must not be `None`") # noqa: E501
self._school_year_type_reference = school_year_type_reference
@property
def staff_reference(self):
"""Gets the staff_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:return: The staff_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: EdFiStaffReference
"""
return self._staff_reference
@staff_reference.setter
def staff_reference(self, staff_reference):
"""Sets the staff_reference of this TpdmStaffTeacherPreparationProviderAssociation.
:param staff_reference: The staff_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: EdFiStaffReference
"""
if self._configuration.client_side_validation and staff_reference is None:
raise ValueError("Invalid value for `staff_reference`, must not be `None`") # noqa: E501
self._staff_reference = staff_reference
@property
def teacher_preparation_provider_reference(self):
"""Gets the teacher_preparation_provider_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:return: The teacher_preparation_provider_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: TpdmTeacherPreparationProviderReference
"""
return self._teacher_preparation_provider_reference
@teacher_preparation_provider_reference.setter
def teacher_preparation_provider_reference(self, teacher_preparation_provider_reference):
"""Sets the teacher_preparation_provider_reference of this TpdmStaffTeacherPreparationProviderAssociation.
:param teacher_preparation_provider_reference: The teacher_preparation_provider_reference of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: TpdmTeacherPreparationProviderReference
"""
if self._configuration.client_side_validation and teacher_preparation_provider_reference is None:
raise ValueError("Invalid value for `teacher_preparation_provider_reference`, must not be `None`") # noqa: E501
self._teacher_preparation_provider_reference = teacher_preparation_provider_reference
@property
def academic_subjects(self):
"""Gets the academic_subjects of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
An unordered collection of staffTeacherPreparationProviderAssociationAcademicSubjects. The description of the content or subject area (e.g., arts, mathematics, reading, stenography, or a foreign language) of a degree. # noqa: E501
:return: The academic_subjects of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: list[TpdmStaffTeacherPreparationProviderAssociationAcademicSubject]
"""
return self._academic_subjects
@academic_subjects.setter
def academic_subjects(self, academic_subjects):
"""Sets the academic_subjects of this TpdmStaffTeacherPreparationProviderAssociation.
An unordered collection of staffTeacherPreparationProviderAssociationAcademicSubjects. The description of the content or subject area (e.g., arts, mathematics, reading, stenography, or a foreign language) of a degree. # noqa: E501
:param academic_subjects: The academic_subjects of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: list[TpdmStaffTeacherPreparationProviderAssociationAcademicSubject]
"""
self._academic_subjects = academic_subjects
@property
def grade_levels(self):
"""Gets the grade_levels of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
An unordered collection of staffTeacherPreparationProviderAssociationGradeLevels. The grade levels for the association. # noqa: E501
:return: The grade_levels of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: list[TpdmStaffTeacherPreparationProviderAssociationGradeLevel]
"""
return self._grade_levels
@grade_levels.setter
def grade_levels(self, grade_levels):
"""Sets the grade_levels of this TpdmStaffTeacherPreparationProviderAssociation.
An unordered collection of staffTeacherPreparationProviderAssociationGradeLevels. The grade levels for the association. # noqa: E501
:param grade_levels: The grade_levels of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: list[TpdmStaffTeacherPreparationProviderAssociationGradeLevel]
"""
self._grade_levels = grade_levels
@property
def program_assignment_descriptor(self):
"""Gets the program_assignment_descriptor of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
Program Assignment for the association # noqa: E501
:return: The program_assignment_descriptor of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: str
"""
return self._program_assignment_descriptor
@program_assignment_descriptor.setter
def program_assignment_descriptor(self, program_assignment_descriptor):
"""Sets the program_assignment_descriptor of this TpdmStaffTeacherPreparationProviderAssociation.
Program Assignment for the association # noqa: E501
:param program_assignment_descriptor: The program_assignment_descriptor of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: str
"""
if self._configuration.client_side_validation and program_assignment_descriptor is None:
raise ValueError("Invalid value for `program_assignment_descriptor`, must not be `None`") # noqa: E501
if (self._configuration.client_side_validation and
program_assignment_descriptor is not None and len(program_assignment_descriptor) > 306):
raise ValueError("Invalid value for `program_assignment_descriptor`, length must be less than or equal to `306`") # noqa: E501
self._program_assignment_descriptor = program_assignment_descriptor
@property
def etag(self):
"""Gets the etag of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
A unique system-generated value that identifies the version of the resource. # noqa: E501
:return: The etag of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:rtype: str
"""
return self._etag
@etag.setter
def etag(self, etag):
"""Sets the etag of this TpdmStaffTeacherPreparationProviderAssociation.
A unique system-generated value that identifies the version of the resource. # noqa: E501
:param etag: The etag of this TpdmStaffTeacherPreparationProviderAssociation. # noqa: E501
:type: str
"""
self._etag = etag
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(TpdmStaffTeacherPreparationProviderAssociation, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, TpdmStaffTeacherPreparationProviderAssociation):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, TpdmStaffTeacherPreparationProviderAssociation):
return True
return self.to_dict() != other.to_dict() | 0.64791 | 0.102125 |
import io
import typing as t
from django_docker_helpers.config.backends.base import BaseParser
from django_docker_helpers.config.exceptions import KVStorageValueIsEmpty
from .yaml_parser import YamlParser
class RedisParser(BaseParser):
"""
Reads a whole config bundle from a redis key and provides the unified interface to access config options.
It assumes that config in your storage can be parsed with any simple parser, like
:class:`~django_docker_helpers.config.backends.YamlParser`.
Compared to, e.g. :class:`~django_docker_helpers.config.backends.environment_parser.EnvironmentParser`
it does not have scope support by design, since ``endpoint`` is a good enough scope by itself.
Example:
::
parser = RedisParser('my/server/config.yml', host=REDIS_HOST, port=REDIS_PORT)
parser.get('nested.a.b', coerce_type=int)
"""
def __init__(self,
endpoint: str = 'service',
host: str = '127.0.0.1',
port: int = 6379,
db: int = 0,
path_separator: str = '.',
inner_parser_class: t.Optional[t.Type[BaseParser]] = YamlParser,
**redis_options):
"""
:param endpoint: specifies a redis key with serialized config, e.g. ``'services/mailer/config.yml'``
:param host: redis host, default is ``'127.0.0.1'``
:param port: redis port, default id ``6379``
:param db: redis database, default is ``0``
:param path_separator: specifies which character separates nested variables, default is ``'.'``
:param inner_parser_class: use the specified parser to read config from ``endpoint`` key
:param redis_options: additional options for ``redis.Redis`` client
"""
super().__init__(path_separator=path_separator)
self.inner_parser_class = inner_parser_class
self.endpoint = endpoint
self.client_options = {
'host': host,
'port': port,
'db': db,
}
self.client_options.update(**redis_options)
self._inner_parser = None
def __str__(self):
return '<{0} {1[host]}:{1[port]} db={1[db]} scope={2}>'.format(
self.__class__.__name__,
self.client_options,
self.scope,
)
def get_client(self):
# type: () -> redis.Redis
import redis
self._client = redis.Redis(**self.client_options)
return self._client
@property
def inner_parser(self) -> BaseParser:
"""
Prepares inner config parser for config stored at ``endpoint``.
:return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser`
:raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain a config
"""
if self._inner_parser is not None:
return self._inner_parser
config = self.client.get(self.endpoint)
if not config:
raise KVStorageValueIsEmpty('Key `{0}` does not exist or value is empty'.format(self.endpoint))
config = config.decode()
self._inner_parser = self.inner_parser_class(
config=io.StringIO(config),
path_separator=self.path_separator,
scope=None
)
return self._inner_parser
def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
Reads a value of ``variable_path`` from redis storage.
:param variable_path: a delimiter-separated path to a nested value
:param default: default value if there's no object by specified path
:param coerce_type: cast a type of a value to a specified one
:param coercer: perform a type casting with specified callback
:param kwargs: additional arguments inherited parser may need
:return: value or default
:raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain a config
"""
return self.inner_parser.get(
variable_path,
default=default,
coerce_type=coerce_type,
coercer=coercer,
**kwargs,
) | django_docker_helpers/config/backends/redis_parser.py | import io
import typing as t
from django_docker_helpers.config.backends.base import BaseParser
from django_docker_helpers.config.exceptions import KVStorageValueIsEmpty
from .yaml_parser import YamlParser
class RedisParser(BaseParser):
"""
Reads a whole config bundle from a redis key and provides the unified interface to access config options.
It assumes that config in your storage can be parsed with any simple parser, like
:class:`~django_docker_helpers.config.backends.YamlParser`.
Compared to, e.g. :class:`~django_docker_helpers.config.backends.environment_parser.EnvironmentParser`
it does not have scope support by design, since ``endpoint`` is a good enough scope by itself.
Example:
::
parser = RedisParser('my/server/config.yml', host=REDIS_HOST, port=REDIS_PORT)
parser.get('nested.a.b', coerce_type=int)
"""
def __init__(self,
endpoint: str = 'service',
host: str = '127.0.0.1',
port: int = 6379,
db: int = 0,
path_separator: str = '.',
inner_parser_class: t.Optional[t.Type[BaseParser]] = YamlParser,
**redis_options):
"""
:param endpoint: specifies a redis key with serialized config, e.g. ``'services/mailer/config.yml'``
:param host: redis host, default is ``'127.0.0.1'``
:param port: redis port, default id ``6379``
:param db: redis database, default is ``0``
:param path_separator: specifies which character separates nested variables, default is ``'.'``
:param inner_parser_class: use the specified parser to read config from ``endpoint`` key
:param redis_options: additional options for ``redis.Redis`` client
"""
super().__init__(path_separator=path_separator)
self.inner_parser_class = inner_parser_class
self.endpoint = endpoint
self.client_options = {
'host': host,
'port': port,
'db': db,
}
self.client_options.update(**redis_options)
self._inner_parser = None
def __str__(self):
return '<{0} {1[host]}:{1[port]} db={1[db]} scope={2}>'.format(
self.__class__.__name__,
self.client_options,
self.scope,
)
def get_client(self):
# type: () -> redis.Redis
import redis
self._client = redis.Redis(**self.client_options)
return self._client
@property
def inner_parser(self) -> BaseParser:
"""
Prepares inner config parser for config stored at ``endpoint``.
:return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser`
:raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain a config
"""
if self._inner_parser is not None:
return self._inner_parser
config = self.client.get(self.endpoint)
if not config:
raise KVStorageValueIsEmpty('Key `{0}` does not exist or value is empty'.format(self.endpoint))
config = config.decode()
self._inner_parser = self.inner_parser_class(
config=io.StringIO(config),
path_separator=self.path_separator,
scope=None
)
return self._inner_parser
def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
Reads a value of ``variable_path`` from redis storage.
:param variable_path: a delimiter-separated path to a nested value
:param default: default value if there's no object by specified path
:param coerce_type: cast a type of a value to a specified one
:param coercer: perform a type casting with specified callback
:param kwargs: additional arguments inherited parser may need
:return: value or default
:raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain a config
"""
return self.inner_parser.get(
variable_path,
default=default,
coerce_type=coerce_type,
coercer=coercer,
**kwargs,
) | 0.817975 | 0.123102 |
import numpy as np
from time import time
from math import sqrt, ceil, floor, log
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import scipy.integrate as integrate
# find the primes up to and including limit
def sieve_of_eratosthenes(limit):
limit = floor(limit)
possible_primes = np.ones(limit, dtype=bool)
possible_primes[0:2:1] = False
for i in range(2, ceil(sqrt(limit))):
possible_primes[i*i:limit:i] = False
return np.flatnonzero(possible_primes)
def prime_counting_function_estimation(N):
return N/log(N)
@np.vectorize
def exponential_integral(x, minfloat=1e-7, maxfloat=10000):
"""Ei integral function."""
minfloat = min(np.abs(x), minfloat)
maxfloat = max(np.abs(x), maxfloat)
def f(t):
return np.exp(t) / t
if x > 0:
return (integrate.quad(f, -maxfloat, -minfloat)[0] + integrate.quad(f, minfloat, x)[0])
else:
return integrate.quad(f, -maxfloat, x)[0]
def logarithmic_integral(N):
return exponential_integral(log(N))
def prime_power_function(N):
sum_ = 0
for r in range(1, floor(log(N, 2))+1):
sum_ += sieve_of_eratosthenes(N**(1/r)).size
return sum_
def animate(i, x_vals, y_vals_pcf, y_vals_x_logx, y_vals_li, y_vals_ppf, LIMIT):
if i > 2:
x_vals.append(i)
y_vals_pcf.append(sieve_of_eratosthenes(i).size)
y_vals_x_logx.append(prime_counting_function_estimation(i))
y_vals_li.append(logarithmic_integral(i))
y_vals_ppf.append(prime_power_function(i))
plt.cla()
plt.scatter(x_vals, y_vals_pcf, label='Prime Counting Function')
plt.plot(x_vals, y_vals_x_logx, label='x / log(x)', color='yellow')
plt.plot(x_vals, y_vals_li, label='Logarithmic Integral', color='green')
plt.plot(x_vals, y_vals_ppf, label='Prime Power Function', color='blue')
plt.legend(loc='upper left')
plt.xlabel('')
plt.ylabel('')
plt.tight_layout()
def plot():
LIMIT = 1*10**6
plt.style.use('dark_background')
x_vals = []
y_vals_pcf = []
y_vals_x_logx= []
y_vals_li = []
y_vals_ppf = []
animation = FuncAnimation(plt.gcf(), animate, fargs=(x_vals, y_vals_pcf, y_vals_x_logx, y_vals_li, y_vals_ppf, LIMIT), interval=10)
plt.xlabel('')
plt.ylabel('')
plt.tight_layout()
plt.show()
if __name__ == "__main__":
start = time()
plot()
print(f'--- {start-time()} seconds ---') | Prototypes/Graph Plots/prime_counting_function_plot.py |
import numpy as np
from time import time
from math import sqrt, ceil, floor, log
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import scipy.integrate as integrate
# find the primes up to and including limit
def sieve_of_eratosthenes(limit):
limit = floor(limit)
possible_primes = np.ones(limit, dtype=bool)
possible_primes[0:2:1] = False
for i in range(2, ceil(sqrt(limit))):
possible_primes[i*i:limit:i] = False
return np.flatnonzero(possible_primes)
def prime_counting_function_estimation(N):
return N/log(N)
@np.vectorize
def exponential_integral(x, minfloat=1e-7, maxfloat=10000):
"""Ei integral function."""
minfloat = min(np.abs(x), minfloat)
maxfloat = max(np.abs(x), maxfloat)
def f(t):
return np.exp(t) / t
if x > 0:
return (integrate.quad(f, -maxfloat, -minfloat)[0] + integrate.quad(f, minfloat, x)[0])
else:
return integrate.quad(f, -maxfloat, x)[0]
def logarithmic_integral(N):
return exponential_integral(log(N))
def prime_power_function(N):
sum_ = 0
for r in range(1, floor(log(N, 2))+1):
sum_ += sieve_of_eratosthenes(N**(1/r)).size
return sum_
def animate(i, x_vals, y_vals_pcf, y_vals_x_logx, y_vals_li, y_vals_ppf, LIMIT):
if i > 2:
x_vals.append(i)
y_vals_pcf.append(sieve_of_eratosthenes(i).size)
y_vals_x_logx.append(prime_counting_function_estimation(i))
y_vals_li.append(logarithmic_integral(i))
y_vals_ppf.append(prime_power_function(i))
plt.cla()
plt.scatter(x_vals, y_vals_pcf, label='Prime Counting Function')
plt.plot(x_vals, y_vals_x_logx, label='x / log(x)', color='yellow')
plt.plot(x_vals, y_vals_li, label='Logarithmic Integral', color='green')
plt.plot(x_vals, y_vals_ppf, label='Prime Power Function', color='blue')
plt.legend(loc='upper left')
plt.xlabel('')
plt.ylabel('')
plt.tight_layout()
def plot():
LIMIT = 1*10**6
plt.style.use('dark_background')
x_vals = []
y_vals_pcf = []
y_vals_x_logx= []
y_vals_li = []
y_vals_ppf = []
animation = FuncAnimation(plt.gcf(), animate, fargs=(x_vals, y_vals_pcf, y_vals_x_logx, y_vals_li, y_vals_ppf, LIMIT), interval=10)
plt.xlabel('')
plt.ylabel('')
plt.tight_layout()
plt.show()
if __name__ == "__main__":
start = time()
plot()
print(f'--- {start-time()} seconds ---') | 0.806472 | 0.49585 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = [
'GetVantagePointsResult',
'AwaitableGetVantagePointsResult',
'get_vantage_points',
]
@pulumi.output_type
class GetVantagePointsResult:
"""
A collection of values returned by getVantagePoints.
"""
def __init__(__self__, display_name=None, filters=None, health_checks_vantage_points=None, id=None, name=None):
if display_name and not isinstance(display_name, str):
raise TypeError("Expected argument 'display_name' to be a str")
pulumi.set(__self__, "display_name", display_name)
if filters and not isinstance(filters, list):
raise TypeError("Expected argument 'filters' to be a list")
pulumi.set(__self__, "filters", filters)
if health_checks_vantage_points and not isinstance(health_checks_vantage_points, list):
raise TypeError("Expected argument 'health_checks_vantage_points' to be a list")
pulumi.set(__self__, "health_checks_vantage_points", health_checks_vantage_points)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
@property
@pulumi.getter(name="displayName")
def display_name(self) -> Optional[str]:
"""
The display name for the vantage point. Display names are determined by the best information available and may change over time.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter
def filters(self) -> Optional[Sequence['outputs.GetVantagePointsFilterResult']]:
return pulumi.get(self, "filters")
@property
@pulumi.getter(name="healthChecksVantagePoints")
def health_checks_vantage_points(self) -> Sequence['outputs.GetVantagePointsHealthChecksVantagePointResult']:
"""
The list of health_checks_vantage_points.
"""
return pulumi.get(self, "health_checks_vantage_points")
@property
@pulumi.getter
def id(self) -> str:
"""
The provider-assigned unique ID for this managed resource.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def name(self) -> Optional[str]:
"""
The unique, permanent name for the vantage point.
"""
return pulumi.get(self, "name")
class AwaitableGetVantagePointsResult(GetVantagePointsResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetVantagePointsResult(
display_name=self.display_name,
filters=self.filters,
health_checks_vantage_points=self.health_checks_vantage_points,
id=self.id,
name=self.name)
def get_vantage_points(display_name: Optional[str] = None,
filters: Optional[Sequence[pulumi.InputType['GetVantagePointsFilterArgs']]] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVantagePointsResult:
"""
This data source provides the list of Vantage Points in Oracle Cloud Infrastructure Health Checks service.
Gets information about all vantage points available to the user.
## Example Usage
```python
import pulumi
import pulumi_oci as oci
test_vantage_points = oci.healthchecks.get_vantage_points(display_name=var["vantage_point_display_name"],
name=var["vantage_point_name"])
```
:param str display_name: Filters results that exactly match the `displayName` field.
:param str name: Filters results that exactly match the `name` field.
"""
__args__ = dict()
__args__['displayName'] = display_name
__args__['filters'] = filters
__args__['name'] = name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('oci:healthchecks/getVantagePoints:getVantagePoints', __args__, opts=opts, typ=GetVantagePointsResult).value
return AwaitableGetVantagePointsResult(
display_name=__ret__.display_name,
filters=__ret__.filters,
health_checks_vantage_points=__ret__.health_checks_vantage_points,
id=__ret__.id,
name=__ret__.name) | sdk/python/pulumi_oci/healthchecks/get_vantage_points.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = [
'GetVantagePointsResult',
'AwaitableGetVantagePointsResult',
'get_vantage_points',
]
@pulumi.output_type
class GetVantagePointsResult:
"""
A collection of values returned by getVantagePoints.
"""
def __init__(__self__, display_name=None, filters=None, health_checks_vantage_points=None, id=None, name=None):
if display_name and not isinstance(display_name, str):
raise TypeError("Expected argument 'display_name' to be a str")
pulumi.set(__self__, "display_name", display_name)
if filters and not isinstance(filters, list):
raise TypeError("Expected argument 'filters' to be a list")
pulumi.set(__self__, "filters", filters)
if health_checks_vantage_points and not isinstance(health_checks_vantage_points, list):
raise TypeError("Expected argument 'health_checks_vantage_points' to be a list")
pulumi.set(__self__, "health_checks_vantage_points", health_checks_vantage_points)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
@property
@pulumi.getter(name="displayName")
def display_name(self) -> Optional[str]:
"""
The display name for the vantage point. Display names are determined by the best information available and may change over time.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter
def filters(self) -> Optional[Sequence['outputs.GetVantagePointsFilterResult']]:
return pulumi.get(self, "filters")
@property
@pulumi.getter(name="healthChecksVantagePoints")
def health_checks_vantage_points(self) -> Sequence['outputs.GetVantagePointsHealthChecksVantagePointResult']:
"""
The list of health_checks_vantage_points.
"""
return pulumi.get(self, "health_checks_vantage_points")
@property
@pulumi.getter
def id(self) -> str:
"""
The provider-assigned unique ID for this managed resource.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def name(self) -> Optional[str]:
"""
The unique, permanent name for the vantage point.
"""
return pulumi.get(self, "name")
class AwaitableGetVantagePointsResult(GetVantagePointsResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetVantagePointsResult(
display_name=self.display_name,
filters=self.filters,
health_checks_vantage_points=self.health_checks_vantage_points,
id=self.id,
name=self.name)
def get_vantage_points(display_name: Optional[str] = None,
filters: Optional[Sequence[pulumi.InputType['GetVantagePointsFilterArgs']]] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVantagePointsResult:
"""
This data source provides the list of Vantage Points in Oracle Cloud Infrastructure Health Checks service.
Gets information about all vantage points available to the user.
## Example Usage
```python
import pulumi
import pulumi_oci as oci
test_vantage_points = oci.healthchecks.get_vantage_points(display_name=var["vantage_point_display_name"],
name=var["vantage_point_name"])
```
:param str display_name: Filters results that exactly match the `displayName` field.
:param str name: Filters results that exactly match the `name` field.
"""
__args__ = dict()
__args__['displayName'] = display_name
__args__['filters'] = filters
__args__['name'] = name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('oci:healthchecks/getVantagePoints:getVantagePoints', __args__, opts=opts, typ=GetVantagePointsResult).value
return AwaitableGetVantagePointsResult(
display_name=__ret__.display_name,
filters=__ret__.filters,
health_checks_vantage_points=__ret__.health_checks_vantage_points,
id=__ret__.id,
name=__ret__.name) | 0.778607 | 0.17522 |
import arcpy
import os.path
import os
import sys
from pprint import pprint
import pdb
records = [108814,109019,116056,116097,123383,167,191,203,210,290,306,310,321,406,414,422,432,440,514,518,56995,56997,57000,57002,57004,57172,57174,57177,57178,57181,57182,57186,57241,57242,57440,57694,57695,57699,57702,58041,58042,58162,58164,58165,58175,58233,58513,58549,58551,58554,58560,58716,58719,58781,58804,59648,59765,59783,59784,604,928,92939,92941,936,973,98055]
ROOT = ""
install_dir = arcpy.GetInstallInfo("desktop")["InstallDir"]
translator = os.path.join(install_dir, "Metadata\Translator\ARCGIS2FGDC.xml")
for i in records:
unknowns = []
srs = {}
#ws = os.path.join(ROOT,str(i),"converted","GISfiles")
ws = os.path.join(ROOT,str(i))
xml_path = os.path.join(ROOT,str(i),"final_XMLs")
walk = arcpy.da.Walk(ws,datatype=["FeatureClass","RasterDataset"])
if not os.path.exists(os.path.join(ws,"converted","GISfiles")):
for dirpath,dirname,files in walk:
for f in files:
d = os.path.join(dirpath,f)
desc = arcpy.Describe(d)
if desc.datatype.startswith('ShapeFile'):
if desc.spatialreference:
sr = desc.spatialreference.PCSCode
if sr == 0:
unknowns.append(d)
if srs.has_key(sr):
srs[sr] = srs[sr] + 1
else:
srs[sr] = 1
else:
print f,'has no spatial ref'
#see https://wiki.python.org/moin/HowTo/Sorting for more on sorting iterables
most_popular_srs = sorted(srs.iteritems(), reverse=True, key=lambda item: item[1])[0][0]
#create spatial reference object using the code
new_srs = arcpy.SpatialReference(most_popular_srs)
print new_srs.name,'is the most popular SRS for', i
else:
print 'skipped %s because it has e00s' % (str(i))
for d in unknowns:
arcpy.DefineProjection_management(d, new_srs)
print 'defined projection for' ,d
path_to_xml = os.path.join(xml_path, os.path.split(d)[1]+".xml")
if os.path.exists(path_to_xml):
os.remove(path_to_xml)
print 'removed existing XML to make room for a new one'
arcpy.ExportMetadata_conversion(d, translator,
path_to_xml)
print 'exported new XML for', d
print '\n' | defineProjections.py |
import arcpy
import os.path
import os
import sys
from pprint import pprint
import pdb
records = [108814,109019,116056,116097,123383,167,191,203,210,290,306,310,321,406,414,422,432,440,514,518,56995,56997,57000,57002,57004,57172,57174,57177,57178,57181,57182,57186,57241,57242,57440,57694,57695,57699,57702,58041,58042,58162,58164,58165,58175,58233,58513,58549,58551,58554,58560,58716,58719,58781,58804,59648,59765,59783,59784,604,928,92939,92941,936,973,98055]
ROOT = ""
install_dir = arcpy.GetInstallInfo("desktop")["InstallDir"]
translator = os.path.join(install_dir, "Metadata\Translator\ARCGIS2FGDC.xml")
for i in records:
unknowns = []
srs = {}
#ws = os.path.join(ROOT,str(i),"converted","GISfiles")
ws = os.path.join(ROOT,str(i))
xml_path = os.path.join(ROOT,str(i),"final_XMLs")
walk = arcpy.da.Walk(ws,datatype=["FeatureClass","RasterDataset"])
if not os.path.exists(os.path.join(ws,"converted","GISfiles")):
for dirpath,dirname,files in walk:
for f in files:
d = os.path.join(dirpath,f)
desc = arcpy.Describe(d)
if desc.datatype.startswith('ShapeFile'):
if desc.spatialreference:
sr = desc.spatialreference.PCSCode
if sr == 0:
unknowns.append(d)
if srs.has_key(sr):
srs[sr] = srs[sr] + 1
else:
srs[sr] = 1
else:
print f,'has no spatial ref'
#see https://wiki.python.org/moin/HowTo/Sorting for more on sorting iterables
most_popular_srs = sorted(srs.iteritems(), reverse=True, key=lambda item: item[1])[0][0]
#create spatial reference object using the code
new_srs = arcpy.SpatialReference(most_popular_srs)
print new_srs.name,'is the most popular SRS for', i
else:
print 'skipped %s because it has e00s' % (str(i))
for d in unknowns:
arcpy.DefineProjection_management(d, new_srs)
print 'defined projection for' ,d
path_to_xml = os.path.join(xml_path, os.path.split(d)[1]+".xml")
if os.path.exists(path_to_xml):
os.remove(path_to_xml)
print 'removed existing XML to make room for a new one'
arcpy.ExportMetadata_conversion(d, translator,
path_to_xml)
print 'exported new XML for', d
print '\n' | 0.221098 | 0.064594 |
from digitalsky_provider.models import DigitalSkyLog
from gcs_operations.models import CloudFile, FlightPlan, FlightOperation, Transaction, FlightPermission, FlightLog
from pki_framework.models import AerobridgeCredential
from registry.models import Person, Address, Activity, Authorization, Operator, Contact, Test, TypeCertificate, \
Manufacturer, Firmware, Pilot, TestValidity, Aircraft
from .test_setup import TestModels
class TestModelsDelete(TestModels):
fixtures = ['Activity', 'Address', 'Authorization', 'Manufacturer', 'Operator', 'Person', 'Test',
'TypeCertificate', 'Pilot', 'CloudFile', 'FlightPlan', 'FlightOperation', 'Aircraft', 'Transaction',
'Contact', 'DigitalSkyLog', 'Firmware', 'FlightLog', 'FlightPermission',
'TestValidity', 'AerobridgeCredential']
def test_digitalsky_provider_digitalsky_log_delete(self):
digitalsky_log = DigitalSkyLog.objects.first()
self.assertIsNotNone(digitalsky_log)
digitalsky_log.delete()
self.assertNotIn(digitalsky_log, DigitalSkyLog.objects.all())
def test_gcs_operations_cloud_file_delete(self):
cloud_file = CloudFile.objects.first()
self.assertIsNotNone(cloud_file)
cloud_file.delete()
self.assertNotIn(cloud_file, CloudFile.objects.all())
def test_gcs_operations_flight_plan_delete(self):
flight_plan = FlightPlan.objects.first()
self.assertIsNotNone(flight_plan)
flight_plan.delete()
self.assertNotIn(flight_plan, FlightPlan.objects.all())
def test_gcs_operations_flight_operation_delete(self):
flight_operation = FlightOperation.objects.first()
self.assertIsNotNone(flight_operation)
flight_operation.delete()
self.assertNotIn(flight_operation, FlightOperation.objects.all())
def test_gcs_operations_transaction_delete(self):
transaction = Transaction.objects.first()
self.assertIsNotNone(transaction)
transaction.delete()
self.assertNotIn(transaction, Transaction.objects.all())
def test_gcs_operations_flight_permission_delete(self):
flight_permission = FlightPermission.objects.first()
self.assertIsNotNone(flight_permission)
flight_permission.delete()
self.assertNotIn(flight_permission, FlightPermission.objects.all())
def test_gcs_operations_flight_log_delete(self):
flight_log = FlightLog.objects.first()
self.assertIsNotNone(flight_log)
flight_log.delete()
self.assertNotIn(flight_log, FlightLog.objects.all())
def test_registry_person_delete(self):
person = Person.objects.first()
self.assertIsNotNone(person)
person.delete()
self.assertNotIn(person, Person.objects.all())
def test_registry_address_delete(self):
address = Address.objects.first()
self.assertIsNotNone(address)
address.delete()
self.assertNotIn(address, Address.objects.all())
def test_registry_activity_delete(self):
activity = Activity.objects.first()
self.assertIsNotNone(activity)
activity.delete()
self.assertNotIn(activity, Activity.objects.all())
def test_registry_authorization_delete(self):
authorization = Authorization.objects.first()
self.assertIsNotNone(authorization)
authorization.delete()
self.assertNotIn(authorization, Authorization.objects.all())
def test_registry_operator_delete(self):
operator = Operator.objects.first()
self.assertIsNotNone(operator)
operator.delete()
self.assertNotIn(operator, Operator.objects.all())
def test_registry_contact_delete(self):
contact = Contact.objects.first()
self.assertIsNotNone(contact)
contact.delete()
self.assertNotIn(contact, Contact.objects.all())
def test_registry_test_delete(self):
test = Test.objects.first()
self.assertIsNotNone(test)
test.delete()
self.assertNotIn(test, Test.objects.all())
def test_registry_pilot_delete(self):
pilot = Pilot.objects.first()
self.assertIsNotNone(pilot)
pilot.delete()
self.assertNotIn(pilot, Pilot.objects.all())
def test_registry_testValidity_delete(self):
test_validity = TestValidity.objects.first()
self.assertIsNotNone(test_validity)
test_validity.delete()
self.assertNotIn(test_validity, TestValidity.objects.all())
def test_registry_typeCertificate_delete(self):
type_certificate = TypeCertificate.objects.first()
self.assertIsNotNone(type_certificate)
type_certificate.delete()
self.assertNotIn(type_certificate, TypeCertificate.objects.all())
def test_registry_manufacturer_delete(self):
manufacturer = Manufacturer.objects.first()
self.assertIsNotNone(manufacturer)
manufacturer.delete()
self.assertNotIn(manufacturer, Manufacturer.objects.all())
def test_registry_firmware_delete(self):
firmware = Firmware.objects.first()
self.assertIsNotNone(firmware)
firmware.delete()
self.assertNotIn(firmware, Firmware.objects.all())
def test_registry_aircraft_delete(self):
aircraft = Aircraft.objects.first()
self.assertIsNotNone(aircraft)
aircraft.delete()
self.assertNotIn(aircraft, Aircraft.objects.all())
def test_pki_framework_aerobridge_credentials_delete(self):
aerobridge_credentials = AerobridgeCredential.objects.first()
self.assertIsNotNone(aerobridge_credentials)
aerobridge_credentials.delete()
self.assertNotIn(aerobridge_credentials, Aircraft.objects.all()) | tests/test_models/test_models_delete.py | from digitalsky_provider.models import DigitalSkyLog
from gcs_operations.models import CloudFile, FlightPlan, FlightOperation, Transaction, FlightPermission, FlightLog
from pki_framework.models import AerobridgeCredential
from registry.models import Person, Address, Activity, Authorization, Operator, Contact, Test, TypeCertificate, \
Manufacturer, Firmware, Pilot, TestValidity, Aircraft
from .test_setup import TestModels
class TestModelsDelete(TestModels):
fixtures = ['Activity', 'Address', 'Authorization', 'Manufacturer', 'Operator', 'Person', 'Test',
'TypeCertificate', 'Pilot', 'CloudFile', 'FlightPlan', 'FlightOperation', 'Aircraft', 'Transaction',
'Contact', 'DigitalSkyLog', 'Firmware', 'FlightLog', 'FlightPermission',
'TestValidity', 'AerobridgeCredential']
def test_digitalsky_provider_digitalsky_log_delete(self):
digitalsky_log = DigitalSkyLog.objects.first()
self.assertIsNotNone(digitalsky_log)
digitalsky_log.delete()
self.assertNotIn(digitalsky_log, DigitalSkyLog.objects.all())
def test_gcs_operations_cloud_file_delete(self):
cloud_file = CloudFile.objects.first()
self.assertIsNotNone(cloud_file)
cloud_file.delete()
self.assertNotIn(cloud_file, CloudFile.objects.all())
def test_gcs_operations_flight_plan_delete(self):
flight_plan = FlightPlan.objects.first()
self.assertIsNotNone(flight_plan)
flight_plan.delete()
self.assertNotIn(flight_plan, FlightPlan.objects.all())
def test_gcs_operations_flight_operation_delete(self):
flight_operation = FlightOperation.objects.first()
self.assertIsNotNone(flight_operation)
flight_operation.delete()
self.assertNotIn(flight_operation, FlightOperation.objects.all())
def test_gcs_operations_transaction_delete(self):
transaction = Transaction.objects.first()
self.assertIsNotNone(transaction)
transaction.delete()
self.assertNotIn(transaction, Transaction.objects.all())
def test_gcs_operations_flight_permission_delete(self):
flight_permission = FlightPermission.objects.first()
self.assertIsNotNone(flight_permission)
flight_permission.delete()
self.assertNotIn(flight_permission, FlightPermission.objects.all())
def test_gcs_operations_flight_log_delete(self):
flight_log = FlightLog.objects.first()
self.assertIsNotNone(flight_log)
flight_log.delete()
self.assertNotIn(flight_log, FlightLog.objects.all())
def test_registry_person_delete(self):
person = Person.objects.first()
self.assertIsNotNone(person)
person.delete()
self.assertNotIn(person, Person.objects.all())
def test_registry_address_delete(self):
address = Address.objects.first()
self.assertIsNotNone(address)
address.delete()
self.assertNotIn(address, Address.objects.all())
def test_registry_activity_delete(self):
activity = Activity.objects.first()
self.assertIsNotNone(activity)
activity.delete()
self.assertNotIn(activity, Activity.objects.all())
def test_registry_authorization_delete(self):
authorization = Authorization.objects.first()
self.assertIsNotNone(authorization)
authorization.delete()
self.assertNotIn(authorization, Authorization.objects.all())
def test_registry_operator_delete(self):
operator = Operator.objects.first()
self.assertIsNotNone(operator)
operator.delete()
self.assertNotIn(operator, Operator.objects.all())
def test_registry_contact_delete(self):
contact = Contact.objects.first()
self.assertIsNotNone(contact)
contact.delete()
self.assertNotIn(contact, Contact.objects.all())
def test_registry_test_delete(self):
test = Test.objects.first()
self.assertIsNotNone(test)
test.delete()
self.assertNotIn(test, Test.objects.all())
def test_registry_pilot_delete(self):
pilot = Pilot.objects.first()
self.assertIsNotNone(pilot)
pilot.delete()
self.assertNotIn(pilot, Pilot.objects.all())
def test_registry_testValidity_delete(self):
test_validity = TestValidity.objects.first()
self.assertIsNotNone(test_validity)
test_validity.delete()
self.assertNotIn(test_validity, TestValidity.objects.all())
def test_registry_typeCertificate_delete(self):
type_certificate = TypeCertificate.objects.first()
self.assertIsNotNone(type_certificate)
type_certificate.delete()
self.assertNotIn(type_certificate, TypeCertificate.objects.all())
def test_registry_manufacturer_delete(self):
manufacturer = Manufacturer.objects.first()
self.assertIsNotNone(manufacturer)
manufacturer.delete()
self.assertNotIn(manufacturer, Manufacturer.objects.all())
def test_registry_firmware_delete(self):
firmware = Firmware.objects.first()
self.assertIsNotNone(firmware)
firmware.delete()
self.assertNotIn(firmware, Firmware.objects.all())
def test_registry_aircraft_delete(self):
aircraft = Aircraft.objects.first()
self.assertIsNotNone(aircraft)
aircraft.delete()
self.assertNotIn(aircraft, Aircraft.objects.all())
def test_pki_framework_aerobridge_credentials_delete(self):
aerobridge_credentials = AerobridgeCredential.objects.first()
self.assertIsNotNone(aerobridge_credentials)
aerobridge_credentials.delete()
self.assertNotIn(aerobridge_credentials, Aircraft.objects.all()) | 0.606848 | 0.507141 |
from constants import EOS_TOKEN, MAX_LENGTH, DEVICE
import numpy as np
import torch
class Lang:
def __init__(self, name):
self.name = name
self.word2index = {}
self.word2count = {}
self.index2word = {0: "SOS", 1: "EOS"}
self.n_words = 2 # Count SOS and EOS
def addSentence(self, sentence):
for word in sentence:
self.addWord(word)
def addWord(self, word):
if word not in self.word2index:
self.word2index[word] = self.n_words
self.word2count[word] = 1
self.index2word[self.n_words] = word
self.n_words += 1
else:
self.word2count[word] += 1
class TensorBuilder:
def __init__(self, input_lang, output_lang):
self.input_lang = input_lang
self.output_lang = output_lang
def indexesFromSentence(self, lang, sentence):
return [lang.word2index[word] for word in sentence]
def tensorFromSentence(self, lang, sentence):
indexes = self.indexesFromSentence(lang, sentence)
indexes.append(EOS_TOKEN)
return torch.tensor(indexes, dtype=torch.long, device=DEVICE).view(-1, 1)
def tensorsFromPair(self, pair):
input_tensor = self.tensorFromSentence(self.input_lang, pair[0])
target_tensor = self.tensorFromSentence(self.output_lang, pair[1])
return (input_tensor, target_tensor)
def read_langs(lang1, lang2, corpora):
input_lang = Lang(lang1)
output_lang = Lang(lang2)
input_sentences = []
target_sentences = []
for i, row in corpora.iterrows():
input_sent = row[lang1]
target_sent = row[lang2]
input_tokenized = str(input_sent).split()
target_tokenized = str(target_sent).split()
if len(input_tokenized) > MAX_LENGTH and len(input_tokenized) > 0 and len(target_tokenized) > 0:
continue
input_sentences.append(input_tokenized)
target_sentences.append(target_tokenized)
output_lang.addSentence(target_tokenized)
input_lang.addSentence(input_tokenized)
return input_lang, output_lang, list(zip(input_sentences, target_sentences))
def train_validation_test_split(data, train_proportion, validation_proportion, test_proportion):
if train_proportion + validation_proportion + test_proportion != 1.0:
raise ValueError("Train, test, and validation proportions don't sum up to 1.")
test_size = int(test_proportion * len(data))
valid_size = int(validation_proportion * len(data))
train_size = int(train_proportion * len(data))
indices = np.random.permutation(len(data))
train_idx = indices[:train_size]
valid_idx = indices[train_size:(train_size + valid_size)]
test_idx = indices[-test_size:]
data = np.array(data)
train_set = data[train_idx]
valid_set = data[valid_idx]
test_set = data[test_idx]
return train_set, valid_set, test_set | src/Learning/preprocessing.py | from constants import EOS_TOKEN, MAX_LENGTH, DEVICE
import numpy as np
import torch
class Lang:
def __init__(self, name):
self.name = name
self.word2index = {}
self.word2count = {}
self.index2word = {0: "SOS", 1: "EOS"}
self.n_words = 2 # Count SOS and EOS
def addSentence(self, sentence):
for word in sentence:
self.addWord(word)
def addWord(self, word):
if word not in self.word2index:
self.word2index[word] = self.n_words
self.word2count[word] = 1
self.index2word[self.n_words] = word
self.n_words += 1
else:
self.word2count[word] += 1
class TensorBuilder:
def __init__(self, input_lang, output_lang):
self.input_lang = input_lang
self.output_lang = output_lang
def indexesFromSentence(self, lang, sentence):
return [lang.word2index[word] for word in sentence]
def tensorFromSentence(self, lang, sentence):
indexes = self.indexesFromSentence(lang, sentence)
indexes.append(EOS_TOKEN)
return torch.tensor(indexes, dtype=torch.long, device=DEVICE).view(-1, 1)
def tensorsFromPair(self, pair):
input_tensor = self.tensorFromSentence(self.input_lang, pair[0])
target_tensor = self.tensorFromSentence(self.output_lang, pair[1])
return (input_tensor, target_tensor)
def read_langs(lang1, lang2, corpora):
input_lang = Lang(lang1)
output_lang = Lang(lang2)
input_sentences = []
target_sentences = []
for i, row in corpora.iterrows():
input_sent = row[lang1]
target_sent = row[lang2]
input_tokenized = str(input_sent).split()
target_tokenized = str(target_sent).split()
if len(input_tokenized) > MAX_LENGTH and len(input_tokenized) > 0 and len(target_tokenized) > 0:
continue
input_sentences.append(input_tokenized)
target_sentences.append(target_tokenized)
output_lang.addSentence(target_tokenized)
input_lang.addSentence(input_tokenized)
return input_lang, output_lang, list(zip(input_sentences, target_sentences))
def train_validation_test_split(data, train_proportion, validation_proportion, test_proportion):
if train_proportion + validation_proportion + test_proportion != 1.0:
raise ValueError("Train, test, and validation proportions don't sum up to 1.")
test_size = int(test_proportion * len(data))
valid_size = int(validation_proportion * len(data))
train_size = int(train_proportion * len(data))
indices = np.random.permutation(len(data))
train_idx = indices[:train_size]
valid_idx = indices[train_size:(train_size + valid_size)]
test_idx = indices[-test_size:]
data = np.array(data)
train_set = data[train_idx]
valid_set = data[valid_idx]
test_set = data[test_idx]
return train_set, valid_set, test_set | 0.516352 | 0.322206 |
import sys
from config import *
INT_MIN = -sys.maxsize - 1
def reversed_kronecker(cell_1: int, cell_2: int):
"""
This function determines the interaction between cell_1 and cell_2. Here were are going to implement a reversed
Kronecker Delta function ie. if the two cells are the same, they will not interact (because we arent looking at
intracellular interaction) and if they are different, then they will interact with an interaction strength of J that
is defined in the config file
---
:param cell_1: Type of cell in the lattice for which interaction is to be measured
:param cell_2: Type of cell in the lattice for which the a cell interacts with
:return: interaction_strength: The interaction strength if they were to interact
"""
if cell_1 != cell_2:
interaction_strength = j
return interaction_strength
return 0
class Point:
"""Defines a point
"""
def __init__(self, x, y, parent=[[]]):
"""Creates a point instance on a parent
Args:
x (int): X coordinate of the point on a matrix
y (int): Y coordinate of the point on a matrix
parent (2D Array, optional): Parent matrix. Defaults to a blank matrix.
"""
self.x = x
self.y = y
self.parent = parent
@property
def top(self, ):
"""Top point to the original
Returns:
Any: Point on the top
"""
if self.x == 0:
return INT_MIN
return self.parent[self.x - 1][self.y]
@property
def bottom(self, ):
"""Bottom point to the original
Returns:
Any: Point on the bottom
"""
if self.x == len(self.parent) - 1:
return INT_MIN
return self.parent[self.x + 1][self.y]
@property
def left(self, ):
"""Left point to the original
Returns:
Any: Point on the left
"""
if self.y == 0:
return INT_MIN
return self.parent[self.x][self.y - 1]
@property
def right(self, ):
"""Right point to the original
Returns:
Any: Point on the right
"""
if self.y == len(self.parent[0]) - 1:
return INT_MIN
return self.parent[self.x][self.y + 1]
def __str__(self, ):
"""Returns the point as string representation
Returns:
String
"""
return f"Point({self.x}, {self.y})"
@property
def type(self, ):
"""Returns the type of the cess
Returns:
Any: Type/Value of the cell
"""
return self.parent[self.x][self.y]
def get_1D_neighbour(mat, point):
"""Gets the 1D neighbour in respect to the specified point on the matrix
Args:
mat (2D Array): The base matrix
point (int, int): x, y point
Returns:
Tuple: Returns 4 neighbouring points
"""
point = Point(*point, mat)
return (point.left, point.right, point.top, point.bottom)
def get_neighbour_mapping(mat):
"""Gets all the points from the 2D Matrix as point lists
Usage:
[x for x in get_neighbour_mapping(mat)]
Args:
mat (2D List): 2D Matrix
Yields:
Point: Point representing the points in the matrix
"""
for x in range(len(mat)):
for y in range(len(mat[0])):
yield Point(x, y, mat)
def get_interaction(mat):
R = len(mat)
C = len(mat[0])
arr = [0, R, C]
total_interaction = 0
neighbour_mapping = get_neighbour_mapping(mat)
for neighbour in neighbour_mapping:
unique_neighbour = set([neighbour.left, neighbour.right, neighbour.top, neighbour.bottom, neighbour.type])
for f_neighbour in unique_neighbour:
total_interaction += reversed_kronecker(f_neighbour, neighbour.type)
total_interaction = total_interaction - (R+C) # Subtracting the box sides
return (total_interaction / 2 ) | research/cpm-vqe/interaction_helper.py | import sys
from config import *
INT_MIN = -sys.maxsize - 1
def reversed_kronecker(cell_1: int, cell_2: int):
"""
This function determines the interaction between cell_1 and cell_2. Here were are going to implement a reversed
Kronecker Delta function ie. if the two cells are the same, they will not interact (because we arent looking at
intracellular interaction) and if they are different, then they will interact with an interaction strength of J that
is defined in the config file
---
:param cell_1: Type of cell in the lattice for which interaction is to be measured
:param cell_2: Type of cell in the lattice for which the a cell interacts with
:return: interaction_strength: The interaction strength if they were to interact
"""
if cell_1 != cell_2:
interaction_strength = j
return interaction_strength
return 0
class Point:
"""Defines a point
"""
def __init__(self, x, y, parent=[[]]):
"""Creates a point instance on a parent
Args:
x (int): X coordinate of the point on a matrix
y (int): Y coordinate of the point on a matrix
parent (2D Array, optional): Parent matrix. Defaults to a blank matrix.
"""
self.x = x
self.y = y
self.parent = parent
@property
def top(self, ):
"""Top point to the original
Returns:
Any: Point on the top
"""
if self.x == 0:
return INT_MIN
return self.parent[self.x - 1][self.y]
@property
def bottom(self, ):
"""Bottom point to the original
Returns:
Any: Point on the bottom
"""
if self.x == len(self.parent) - 1:
return INT_MIN
return self.parent[self.x + 1][self.y]
@property
def left(self, ):
"""Left point to the original
Returns:
Any: Point on the left
"""
if self.y == 0:
return INT_MIN
return self.parent[self.x][self.y - 1]
@property
def right(self, ):
"""Right point to the original
Returns:
Any: Point on the right
"""
if self.y == len(self.parent[0]) - 1:
return INT_MIN
return self.parent[self.x][self.y + 1]
def __str__(self, ):
"""Returns the point as string representation
Returns:
String
"""
return f"Point({self.x}, {self.y})"
@property
def type(self, ):
"""Returns the type of the cess
Returns:
Any: Type/Value of the cell
"""
return self.parent[self.x][self.y]
def get_1D_neighbour(mat, point):
"""Gets the 1D neighbour in respect to the specified point on the matrix
Args:
mat (2D Array): The base matrix
point (int, int): x, y point
Returns:
Tuple: Returns 4 neighbouring points
"""
point = Point(*point, mat)
return (point.left, point.right, point.top, point.bottom)
def get_neighbour_mapping(mat):
"""Gets all the points from the 2D Matrix as point lists
Usage:
[x for x in get_neighbour_mapping(mat)]
Args:
mat (2D List): 2D Matrix
Yields:
Point: Point representing the points in the matrix
"""
for x in range(len(mat)):
for y in range(len(mat[0])):
yield Point(x, y, mat)
def get_interaction(mat):
R = len(mat)
C = len(mat[0])
arr = [0, R, C]
total_interaction = 0
neighbour_mapping = get_neighbour_mapping(mat)
for neighbour in neighbour_mapping:
unique_neighbour = set([neighbour.left, neighbour.right, neighbour.top, neighbour.bottom, neighbour.type])
for f_neighbour in unique_neighbour:
total_interaction += reversed_kronecker(f_neighbour, neighbour.type)
total_interaction = total_interaction - (R+C) # Subtracting the box sides
return (total_interaction / 2 ) | 0.804675 | 0.866923 |
import re
from calendar import monthrange
from datetime import datetime
from bs4 import BeautifulSoup
from requests import get
from .console import console
from .logger import logger
from .sanitize import sanitize_metar, sanitize_taf
TODAY = datetime.now()
OGIMET_LIMIT_MESAGE = "#Sorry, Your quota limit for slow queries rate has been reached"
class OgimetQuotaLimitError(Exception):
"""
#Sorry, Your quota limit for slow queries rate has been reached
The anterior message is raised by Ogimet.com when you get a request
one after another. So, you must to wait at less five minutes to ensure
succesful request of METAR data.
This exception is raised when that message is detected.
"""
def __init__(self, message=OGIMET_LIMIT_MESAGE):
super().__init__(message + ". Wait a few minutes to execute a new request. :)")
def _join_line_separated_metars(metar_list: list, icao_code: str):
"""Joins the metar when it is separated in several lines
Args:
metar_list (list): The Metar list from file lines without fromating
Returns:
list: The correct Metar list, one Metar by item
"""
metar = ""
correct_metar_list = []
for line in metar_list:
metar += re.sub(r"^\s{2,}", " ", line)
if "=" in line:
sanitized = sanitize_metar(metar, icao_code)
correct_metar_list.append(sanitized)
# correct_metar_list.append(metar)
metar = ""
return correct_metar_list
def download_data_from_ogimet(icao_code: str, month: int, year=TODAY.year):
metars = []
tafs = []
month_range = monthrange(year=year, month=month)
if month >= 10:
month = f"{month}"
else:
month = f"0{month}"
url = f"https://www.ogimet.com/display_metars2.php?lugar={icao_code.lower()}&tipo=ALL&ord=DIR&nil=SI&fmt=txt&ano={year}&mes={month}&day=01&hora=00&anof={year}&mesf={month}&dayf={month_range[1]}&horaf=23&minf=59&enviar=Ver"
try:
res = get(url)
html_soup = BeautifulSoup(res.text, "html.parser")
data = html_soup.text.split("\n")
# print(data)
# print(f'DATA: {data[:50]}')
# print(f'DATA: {data[-50:-1]}')
if OGIMET_LIMIT_MESAGE in data:
raise OgimetQuotaLimitError()
elif "Fallo de consulta" in data[-1]:
raise OgimetQuotaLimitError(message=data[-1])
else:
# Extract the METAR's from data
for line in data[32:]:
if line == "":
break
metars.append(line)
# Extract the TAF's from data
for line in data[32 + len(metars) + 6 :]:
line = sanitize_taf(line, icao_code)
tafs.append(line.strip())
# Rensemble METAR's separated in several lines
metars = _join_line_separated_metars(metars, icao_code)
return metars, tafs
except Exception as error:
logger.error("Some error ocurred: {}".format(error))
exit()
if __name__ == "__main__":
download_data_from_ogimet("mroc", 1) | tafver_metars/download.py |
import re
from calendar import monthrange
from datetime import datetime
from bs4 import BeautifulSoup
from requests import get
from .console import console
from .logger import logger
from .sanitize import sanitize_metar, sanitize_taf
TODAY = datetime.now()
OGIMET_LIMIT_MESAGE = "#Sorry, Your quota limit for slow queries rate has been reached"
class OgimetQuotaLimitError(Exception):
"""
#Sorry, Your quota limit for slow queries rate has been reached
The anterior message is raised by Ogimet.com when you get a request
one after another. So, you must to wait at less five minutes to ensure
succesful request of METAR data.
This exception is raised when that message is detected.
"""
def __init__(self, message=OGIMET_LIMIT_MESAGE):
super().__init__(message + ". Wait a few minutes to execute a new request. :)")
def _join_line_separated_metars(metar_list: list, icao_code: str):
"""Joins the metar when it is separated in several lines
Args:
metar_list (list): The Metar list from file lines without fromating
Returns:
list: The correct Metar list, one Metar by item
"""
metar = ""
correct_metar_list = []
for line in metar_list:
metar += re.sub(r"^\s{2,}", " ", line)
if "=" in line:
sanitized = sanitize_metar(metar, icao_code)
correct_metar_list.append(sanitized)
# correct_metar_list.append(metar)
metar = ""
return correct_metar_list
def download_data_from_ogimet(icao_code: str, month: int, year=TODAY.year):
metars = []
tafs = []
month_range = monthrange(year=year, month=month)
if month >= 10:
month = f"{month}"
else:
month = f"0{month}"
url = f"https://www.ogimet.com/display_metars2.php?lugar={icao_code.lower()}&tipo=ALL&ord=DIR&nil=SI&fmt=txt&ano={year}&mes={month}&day=01&hora=00&anof={year}&mesf={month}&dayf={month_range[1]}&horaf=23&minf=59&enviar=Ver"
try:
res = get(url)
html_soup = BeautifulSoup(res.text, "html.parser")
data = html_soup.text.split("\n")
# print(data)
# print(f'DATA: {data[:50]}')
# print(f'DATA: {data[-50:-1]}')
if OGIMET_LIMIT_MESAGE in data:
raise OgimetQuotaLimitError()
elif "Fallo de consulta" in data[-1]:
raise OgimetQuotaLimitError(message=data[-1])
else:
# Extract the METAR's from data
for line in data[32:]:
if line == "":
break
metars.append(line)
# Extract the TAF's from data
for line in data[32 + len(metars) + 6 :]:
line = sanitize_taf(line, icao_code)
tafs.append(line.strip())
# Rensemble METAR's separated in several lines
metars = _join_line_separated_metars(metars, icao_code)
return metars, tafs
except Exception as error:
logger.error("Some error ocurred: {}".format(error))
exit()
if __name__ == "__main__":
download_data_from_ogimet("mroc", 1) | 0.347094 | 0.177882 |
from operator import itemgetter
# 3rd party
import numpy
from domdf_python_tools.paths import PathPlus
# ==========================
print("Part One")
# ==========================
lines = PathPlus("input.txt").read_lines()
earliest = int(lines[0])
buses = sorted(map(int, filter(str.isdigit, lines[1].split(','))))
print(earliest)
print(buses)
possible_times = []
for bus in buses:
possible_times.append((bus, int(earliest / bus) * bus))
possible_times.append((bus, (int(earliest / bus) + 1) * bus))
possible_times = sorted(filter(lambda t: t[1] >= earliest, possible_times), key=itemgetter(1))
next_bus = possible_times[0]
print(next_bus)
print(f"Have to wait {next_bus[1] - earliest} to catch bus {next_bus[0]}")
print("The answer is:", (next_bus[1] - earliest) * next_bus[0]) # 370
# ==========================
print("\nPart Two")
# ==========================
"""
The shuttle company is running a contest: one gold coin for anyone that can find the earliest timestamp
such that the first bus ID departs at that time and each subsequent listed bus ID departs at that subsequent minute.
(The first line in your input is no longer relevant.)
For example, suppose you have the same list of bus IDs as above::
7,13,x,x,59,x,31,19
An x in the schedule means there are no constraints on what bus IDs must depart at that time.
This means you are looking for the earliest timestamp (called t) such that:
- Bus ID ``7`` departs at timestamp ``t``.
- Bus ID ``13`` departs one minute after timestamp ``t``.
- There are no requirements or restrictions on departures at two or three minutes after timestamp ``t``.
- Bus ID ``59`` departs four minutes after timestamp ``t``.
- There are no requirements or restrictions on departures at five minutes after timestamp ``t``.
- Bus ID ``31`` departs six minutes after timestamp ``t``.
- Bus ID ``19`` departs seven minutes after timestamp ``t``.
The only bus departures that matter are the listed bus IDs at their specific offsets from ``t``.
Those bus IDs can depart at other times, and other bus IDs can depart at those times.
For example, in the list above, because bus ID ``19`` must depart seven minutes after the timestamp
at which bus ID ``7`` departs, bus ID 7 will always also be departing with bus ID ``19`` at
seven minutes after timestamp t.
In this example, the earliest timestamp at which this occurs is 1068781:
time bus 7 bus 13 bus 59 bus 31 bus 19
1068773 . . . . .
1068774 D . . . .
1068775 . . . . .
1068776 . . . . .
1068777 . . . . .
1068778 . . . . .
1068779 . . . . .
1068780 . . . . .
1068781 D . . . .
1068782 . D . . .
1068783 . . . . .
1068784 . . . . .
1068785 . . D . .
1068786 . . . . .
1068787 . . . D .
1068788 D . . . D
1068789 . . . . .
1068790 . . . . .
1068791 . . . . .
1068792 . . . . .
1068793 . . . . .
1068794 . . . . .
1068795 D D . . .
1068796 . . . . .
1068797 . . . . .
In the above example, bus ID ``7`` departs at timestamp ``1068788`` (seven minutes after ``t``).
This is fine; the only requirement on that minute is that bus ID ``19`` departs then, and it does.
Here are some other examples:
- The earliest timestamp that matches the list ``17,x,13,19`` is ``3417``.
- ``67,7,59,61`` first occurs at timestamp ``754018``.
- ``67,x,7,59,61`` first occurs at timestamp ``779210``.
- ``67,7,x,59,61`` first occurs at timestamp ``1261476``.
- ``1789,37,47,1889`` first occurs at timestamp ``1202161486``.
However, with so many bus IDs in your list,
surely the actual earliest timestamp will be larger than ``100000000000000``!
What is the earliest timestamp such that all of the listed bus IDs depart at
offsets matching their positions in the list?
"""
buses = [int(x) if x.isdigit() else x for x in lines[1].split(',')]
# From https://www.reddit.com/r/adventofcode/comments/kc4njx/2020_day_13_solutions/gfs4g0k
# Start time and increment are equal to the first bus
t = step = buses[0]
for bus in buses[1:]:
if not isinstance(bus, int):
continue
while True:
# The index value of the number is how far it is from the first number
if (t + buses.index(bus)) % bus == 0:
break
t += step # incrementing time with LCM of current number in the loop and the previous number
# print(t)
# Take the LCM in case some number in the input is not a prime number
step = numpy.lcm(step, bus)
print("The answer is:", t) # 894954360381385 | 13/code.py | from operator import itemgetter
# 3rd party
import numpy
from domdf_python_tools.paths import PathPlus
# ==========================
print("Part One")
# ==========================
lines = PathPlus("input.txt").read_lines()
earliest = int(lines[0])
buses = sorted(map(int, filter(str.isdigit, lines[1].split(','))))
print(earliest)
print(buses)
possible_times = []
for bus in buses:
possible_times.append((bus, int(earliest / bus) * bus))
possible_times.append((bus, (int(earliest / bus) + 1) * bus))
possible_times = sorted(filter(lambda t: t[1] >= earliest, possible_times), key=itemgetter(1))
next_bus = possible_times[0]
print(next_bus)
print(f"Have to wait {next_bus[1] - earliest} to catch bus {next_bus[0]}")
print("The answer is:", (next_bus[1] - earliest) * next_bus[0]) # 370
# ==========================
print("\nPart Two")
# ==========================
"""
The shuttle company is running a contest: one gold coin for anyone that can find the earliest timestamp
such that the first bus ID departs at that time and each subsequent listed bus ID departs at that subsequent minute.
(The first line in your input is no longer relevant.)
For example, suppose you have the same list of bus IDs as above::
7,13,x,x,59,x,31,19
An x in the schedule means there are no constraints on what bus IDs must depart at that time.
This means you are looking for the earliest timestamp (called t) such that:
- Bus ID ``7`` departs at timestamp ``t``.
- Bus ID ``13`` departs one minute after timestamp ``t``.
- There are no requirements or restrictions on departures at two or three minutes after timestamp ``t``.
- Bus ID ``59`` departs four minutes after timestamp ``t``.
- There are no requirements or restrictions on departures at five minutes after timestamp ``t``.
- Bus ID ``31`` departs six minutes after timestamp ``t``.
- Bus ID ``19`` departs seven minutes after timestamp ``t``.
The only bus departures that matter are the listed bus IDs at their specific offsets from ``t``.
Those bus IDs can depart at other times, and other bus IDs can depart at those times.
For example, in the list above, because bus ID ``19`` must depart seven minutes after the timestamp
at which bus ID ``7`` departs, bus ID 7 will always also be departing with bus ID ``19`` at
seven minutes after timestamp t.
In this example, the earliest timestamp at which this occurs is 1068781:
time bus 7 bus 13 bus 59 bus 31 bus 19
1068773 . . . . .
1068774 D . . . .
1068775 . . . . .
1068776 . . . . .
1068777 . . . . .
1068778 . . . . .
1068779 . . . . .
1068780 . . . . .
1068781 D . . . .
1068782 . D . . .
1068783 . . . . .
1068784 . . . . .
1068785 . . D . .
1068786 . . . . .
1068787 . . . D .
1068788 D . . . D
1068789 . . . . .
1068790 . . . . .
1068791 . . . . .
1068792 . . . . .
1068793 . . . . .
1068794 . . . . .
1068795 D D . . .
1068796 . . . . .
1068797 . . . . .
In the above example, bus ID ``7`` departs at timestamp ``1068788`` (seven minutes after ``t``).
This is fine; the only requirement on that minute is that bus ID ``19`` departs then, and it does.
Here are some other examples:
- The earliest timestamp that matches the list ``17,x,13,19`` is ``3417``.
- ``67,7,59,61`` first occurs at timestamp ``754018``.
- ``67,x,7,59,61`` first occurs at timestamp ``779210``.
- ``67,7,x,59,61`` first occurs at timestamp ``1261476``.
- ``1789,37,47,1889`` first occurs at timestamp ``1202161486``.
However, with so many bus IDs in your list,
surely the actual earliest timestamp will be larger than ``100000000000000``!
What is the earliest timestamp such that all of the listed bus IDs depart at
offsets matching their positions in the list?
"""
buses = [int(x) if x.isdigit() else x for x in lines[1].split(',')]
# From https://www.reddit.com/r/adventofcode/comments/kc4njx/2020_day_13_solutions/gfs4g0k
# Start time and increment are equal to the first bus
t = step = buses[0]
for bus in buses[1:]:
if not isinstance(bus, int):
continue
while True:
# The index value of the number is how far it is from the first number
if (t + buses.index(bus)) % bus == 0:
break
t += step # incrementing time with LCM of current number in the loop and the previous number
# print(t)
# Take the LCM in case some number in the input is not a prime number
step = numpy.lcm(step, bus)
print("The answer is:", t) # 894954360381385 | 0.544801 | 0.344251 |
def autoencoder (epoch, batch, latent, encoder_o, encoder_i, \
decoder_i, decoder_o, train_percent, lam, norm_order, loss_plot):
"""
This module is autoencoder neural network which gets input data and
reduces the dimension and returns similar data to the input. Data
compression is useful for future data manipulation.
Parameters
----------
epoch : int
Epoch gets the epoch number of the neural network passed through
the neural network in each iteration
batch : int
Batch number of the neural network determines how many times all
the data will be passed through the neural network
latent : int
Latent vector dimension shows the size of buttleneck (compressed data)
encoder_o : int
Size of outer encoder hidden layer of the neural network close to the
input
encoder_i : int
size of inner encoder hidden layer of the neural network close to the
buttleneck
decore_i : int
size of inner decoder hidden layer of the neural network close to the
buttleneck
decore_o : int
size of outer decoder hidden layer of the neural network close to the
output
train_percent : float
(The value will be between 0 and 100) shows what fraction of the dataset
will be used for training and the rest for testing
lam : float
The coefficient of regularization for the autoencoder model
norm_order: int
keras data normalization parameter
loss_plot : Boolean
If True plots the loss function and if False, does not plot that
Returns
-------
input : list
gives all the inputs used for training
latent vector : list
Latent vector, the compressed representation of the input
reconstructed: list
Gives the reconstructed data from the input
cell_types: list
Gives a list of integers represent cell types for the given input data
auto_runtime : float
Training runtime in seconds
auto_err: float
The autoencoder average error (%)
"""
# Import required libraries
from keras import callbacks
from keras.layers import Input, Dense
from keras.models import Model
from keras.utils import normalize
from keras import regularizers
import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.pyplot import draw, show
import pickle
import time
# starting time is measured to compare performance"""
time_start = time.time()
# Importing the database parsed from the input file
dataset = np.load('temp/dataset_binary.npy')
# PErforme log transform and normalization before analysis
input_data =np.log(dataset[:,:-1]) / np.log(2)
input_data = normalize(input_data, axis=0, order=norm_order)
input_size = len(input_data[0, :])
# Split cell types list from the raw data and keep it
labels = dataset[:,-1]
# Split training and testing data from the input dataset
percent_training = int(len(input_data[:, 0]) * (train_percent/100))
X_train = input_data[:percent_training,:input_size]
L_train = dataset[:percent_training, -1]
X_test = input_data [percent_training:,:input_size]
L_test = dataset[percent_training:, -1]
# Define network parameters
epoch_size = epoch
batch_size = batch
latent_dim = latent
# Lambda coefficnet of l2 regulizor of the keras
lam = lam
### Building the neural network layers
encoder_o = encoder_o
encoder_i = encoder_i
decoder_i = decoder_i
decoder_o = decoder_o
# building the input layer
input_gene_expression = Input(shape=(input_size,))
"""#### Encoder layer
The encoder layer will connet input layer to the latent vector.
In order to avoid ovefitting, l2 regularization methos is used which
changes loss function for larger weights.
"""
encoded = Dense(encoder_o, kernel_regularizer=regularizers.l2(lam), \
activation=tf.nn.relu)(input_gene_expression)
encoded = Dense(encoder_i, kernel_regularizer=regularizers.l2(lam), \
activation=tf.nn.relu)(encoded)
encoded = Dense(latent_dim, kernel_regularizer=regularizers.l2(lam), \
activation=tf.nn.relu)(encoded)
"""#### Decoder layer
Decoder layer is defined same as encoder layer but, it connects latent space
to the output layer.
"""
decoded = Dense(decoder_i, kernel_regularizer=regularizers.l2(lam), \
activation =tf.nn.relu)(encoded)
decoded = Dense(decoder_o, kernel_regularizer=regularizers.l2(lam), \
activation =tf.nn.relu)(decoded)
decoded = Dense(input_size, kernel_regularizer=regularizers.l2(lam), \
activation =tf.nn.sigmoid)(decoded)
"""
The autoencoder model is created mapping input data to reconstructed data
similar to the input.
"""
autoencoder = Model(input_gene_expression, decoded)
"""
Encoder model is created to show the latent vectors
"""
encoder = Model(input_gene_expression, encoded)
"""
Loss function of variational autoencoder is defined as the distance between
input and output using mean squared error (MSE). The optimizer "adam" is
then used to minimize the MSE function
"""
autoencoder.compile(optimizer='adam', loss='mean_squared_error',metrics=\
['accuracy'])
"""
Training the autoencoder model: Network dimensions, batch and epoch sizes
and training and testing datasets are used to train the model
"""
# This section defins the plot and callback functions to track training
class PlotLosses(callbacks.Callback):
def on_train_begin(self, logs={}):
self.i = 0
self.x = []
self.losses = []
self.val_losses = []
self.fig = plt.figure()
self.logs = []
def on_epoch_end(self, epoch, logs={}):
self.logs.append(logs)
self.x.append(self.i)
self.losses.append(logs.get('loss'))
self.val_losses.append(logs.get('val_loss'))
self.i += 1
if loss_plot:
plt.plot(self.x, self.losses, label="Training loss", c = 'b', \
linestyle = '-')
plt.plot(self.x, self.val_losses, label="Validation loss",\
c = 'b', linestyle = '-.')
plt.pause(0.01)
plt.title('Training loss: ---, Validation loss: -.-.')
plt.xlabel('Epoch number')
plt.ylabel('MSE value')
else:
pass
time_start = time.time()
autoencoder.fit(X_train, X_train, epochs=epoch_size, batch_size=batch_size,\
shuffle=True, callbacks=[PlotLosses()], validation_data=\
(X_test, X_test), verbose=1)
# Build reconstructed testing layer to measure the autoencoder's error
reconstructed_test = autoencoder.predict(X_test)
# Autoencoder training runtime is calculated
time_end = time.time()
auto_runtime = time_end - time_start
# Autoencoder error is defined
diff = abs(X_test - reconstructed_test)
diff_mean = np.mean(diff)
mean = np.mean(abs(X_test))
auto_err = diff_mean / mean
# show() function, keeps the plot open until the computation is finished
if loss_plot:
plt.show()
else:
pass
# Build latent and reconstruction tensors
latent = encoder.predict(input_data)
reconstructed = autoencoder.predict(input_data)
# exporting latent file and labels for classifier
pickle.dump(latent, open('temp/latent', 'wb'))
pickle.dump(labels, open('temp/labels', 'wb'))
plt.close()
return input_data, latent, reconstructed, labels, auto_runtime, auto_err | autoencoder.py | def autoencoder (epoch, batch, latent, encoder_o, encoder_i, \
decoder_i, decoder_o, train_percent, lam, norm_order, loss_plot):
"""
This module is autoencoder neural network which gets input data and
reduces the dimension and returns similar data to the input. Data
compression is useful for future data manipulation.
Parameters
----------
epoch : int
Epoch gets the epoch number of the neural network passed through
the neural network in each iteration
batch : int
Batch number of the neural network determines how many times all
the data will be passed through the neural network
latent : int
Latent vector dimension shows the size of buttleneck (compressed data)
encoder_o : int
Size of outer encoder hidden layer of the neural network close to the
input
encoder_i : int
size of inner encoder hidden layer of the neural network close to the
buttleneck
decore_i : int
size of inner decoder hidden layer of the neural network close to the
buttleneck
decore_o : int
size of outer decoder hidden layer of the neural network close to the
output
train_percent : float
(The value will be between 0 and 100) shows what fraction of the dataset
will be used for training and the rest for testing
lam : float
The coefficient of regularization for the autoencoder model
norm_order: int
keras data normalization parameter
loss_plot : Boolean
If True plots the loss function and if False, does not plot that
Returns
-------
input : list
gives all the inputs used for training
latent vector : list
Latent vector, the compressed representation of the input
reconstructed: list
Gives the reconstructed data from the input
cell_types: list
Gives a list of integers represent cell types for the given input data
auto_runtime : float
Training runtime in seconds
auto_err: float
The autoencoder average error (%)
"""
# Import required libraries
from keras import callbacks
from keras.layers import Input, Dense
from keras.models import Model
from keras.utils import normalize
from keras import regularizers
import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.pyplot import draw, show
import pickle
import time
# starting time is measured to compare performance"""
time_start = time.time()
# Importing the database parsed from the input file
dataset = np.load('temp/dataset_binary.npy')
# PErforme log transform and normalization before analysis
input_data =np.log(dataset[:,:-1]) / np.log(2)
input_data = normalize(input_data, axis=0, order=norm_order)
input_size = len(input_data[0, :])
# Split cell types list from the raw data and keep it
labels = dataset[:,-1]
# Split training and testing data from the input dataset
percent_training = int(len(input_data[:, 0]) * (train_percent/100))
X_train = input_data[:percent_training,:input_size]
L_train = dataset[:percent_training, -1]
X_test = input_data [percent_training:,:input_size]
L_test = dataset[percent_training:, -1]
# Define network parameters
epoch_size = epoch
batch_size = batch
latent_dim = latent
# Lambda coefficnet of l2 regulizor of the keras
lam = lam
### Building the neural network layers
encoder_o = encoder_o
encoder_i = encoder_i
decoder_i = decoder_i
decoder_o = decoder_o
# building the input layer
input_gene_expression = Input(shape=(input_size,))
"""#### Encoder layer
The encoder layer will connet input layer to the latent vector.
In order to avoid ovefitting, l2 regularization methos is used which
changes loss function for larger weights.
"""
encoded = Dense(encoder_o, kernel_regularizer=regularizers.l2(lam), \
activation=tf.nn.relu)(input_gene_expression)
encoded = Dense(encoder_i, kernel_regularizer=regularizers.l2(lam), \
activation=tf.nn.relu)(encoded)
encoded = Dense(latent_dim, kernel_regularizer=regularizers.l2(lam), \
activation=tf.nn.relu)(encoded)
"""#### Decoder layer
Decoder layer is defined same as encoder layer but, it connects latent space
to the output layer.
"""
decoded = Dense(decoder_i, kernel_regularizer=regularizers.l2(lam), \
activation =tf.nn.relu)(encoded)
decoded = Dense(decoder_o, kernel_regularizer=regularizers.l2(lam), \
activation =tf.nn.relu)(decoded)
decoded = Dense(input_size, kernel_regularizer=regularizers.l2(lam), \
activation =tf.nn.sigmoid)(decoded)
"""
The autoencoder model is created mapping input data to reconstructed data
similar to the input.
"""
autoencoder = Model(input_gene_expression, decoded)
"""
Encoder model is created to show the latent vectors
"""
encoder = Model(input_gene_expression, encoded)
"""
Loss function of variational autoencoder is defined as the distance between
input and output using mean squared error (MSE). The optimizer "adam" is
then used to minimize the MSE function
"""
autoencoder.compile(optimizer='adam', loss='mean_squared_error',metrics=\
['accuracy'])
"""
Training the autoencoder model: Network dimensions, batch and epoch sizes
and training and testing datasets are used to train the model
"""
# This section defins the plot and callback functions to track training
class PlotLosses(callbacks.Callback):
def on_train_begin(self, logs={}):
self.i = 0
self.x = []
self.losses = []
self.val_losses = []
self.fig = plt.figure()
self.logs = []
def on_epoch_end(self, epoch, logs={}):
self.logs.append(logs)
self.x.append(self.i)
self.losses.append(logs.get('loss'))
self.val_losses.append(logs.get('val_loss'))
self.i += 1
if loss_plot:
plt.plot(self.x, self.losses, label="Training loss", c = 'b', \
linestyle = '-')
plt.plot(self.x, self.val_losses, label="Validation loss",\
c = 'b', linestyle = '-.')
plt.pause(0.01)
plt.title('Training loss: ---, Validation loss: -.-.')
plt.xlabel('Epoch number')
plt.ylabel('MSE value')
else:
pass
time_start = time.time()
autoencoder.fit(X_train, X_train, epochs=epoch_size, batch_size=batch_size,\
shuffle=True, callbacks=[PlotLosses()], validation_data=\
(X_test, X_test), verbose=1)
# Build reconstructed testing layer to measure the autoencoder's error
reconstructed_test = autoencoder.predict(X_test)
# Autoencoder training runtime is calculated
time_end = time.time()
auto_runtime = time_end - time_start
# Autoencoder error is defined
diff = abs(X_test - reconstructed_test)
diff_mean = np.mean(diff)
mean = np.mean(abs(X_test))
auto_err = diff_mean / mean
# show() function, keeps the plot open until the computation is finished
if loss_plot:
plt.show()
else:
pass
# Build latent and reconstruction tensors
latent = encoder.predict(input_data)
reconstructed = autoencoder.predict(input_data)
# exporting latent file and labels for classifier
pickle.dump(latent, open('temp/latent', 'wb'))
pickle.dump(labels, open('temp/labels', 'wb'))
plt.close()
return input_data, latent, reconstructed, labels, auto_runtime, auto_err | 0.919995 | 0.908374 |
# 利用华为ups检测机房是否停电
# 停电后发送企业微信告警并对主要服务器关机
import sys
import os
import time
import ssl
import json
import http.cookiejar
import paramiko
from urllib import parse, request
# ----------------------企业微信配置开始------------------------------------
corpid = '你自己的pid'
corpsecret = '你自己的key'
wx_url = 'https://qyapi.weixin.qq.com'
log_file = r'D:\脚本\web_loing.log'
# ----------------------取token---------------------------------------------
def get_token(wx_url, corpid, corpsecret):
token_url = '{}/cgi-bin/gettoken?corpid={}&corpsecret={}'.format(
wx_url, corpid, corpsecret)
token = json.loads(request.urlopen(token_url).read().decode())[
'access_token']
print(token)
return token
# -----------------------构建告警信息json----------------------------------------
def messages(msg):
values = {"touser": 'lijingfeng', "msgtype": 'text',
"agentid": 1000002, "text": {'content': msg}, "safe": 0}
msges = (bytes(json.dumps(values), 'utf-8'))
print(msges)
return msges
# ------------------发送告警信息--------------
def send_message(wx_url, token, data):
send_url = '{}/cgi-bin/message/send?access_token={}'.format(wx_url, token)
respone = request.urlopen(request.Request(url=send_url, data=data)).read()
x = json.loads(respone.decode())['errcode']
print(x)
if x == 0:
print('Succesfully')
else:
print('Failed')
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' 微信发送失败!.\n'
file_zj.writelines(file_nr)
# ----------------------企业微信配置结束------------------------------------
# ------------------连接linux主 机开始--------------
def run(ssh_num):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ssh_num[0], 22, ssh_num[2], ssh_num[1])
stdin, stdout, stderr = ssh.exec_command('shutdown -h 5')
ssh_end = stdout.read().decode('utf-8') # 回显
print(ssh_end)
print("check status %s OK\n" % ssh_num[0])
ssh.close()
# 关机后调用企业微信发送,并关本机
msg = '报警主机: {}\n 报警时间: {} \n 报警信息:检测到电源有故障,请检查是否误报,服务器将于5分钟后关机 \n 当前状态:等待关机'.format(
ssh_num[0], time.strftime("%Y-%m-%d %X", time.localtime(time.time())))
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
except Exception as ex:
print("\tError %s\n" % ex)
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime("%Y-%m-%d %X", time.localtime(time.time())) + \
"\tError %s" % ex + ' to ' + ssh_num[0] + '\n'
file_zj.writelines(file_nr)
# 抛异常时调用企业微信发送,并退出
msg = ssh_num[0] + '尝试关机失败'
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
# ------------------连接linux主 机结束--------------
ssl._create_default_https_context = ssl._create_unverified_context # 忽略ssl错误
post_time = str(int(time.time())) + "000" # 提交时间
textmod = {"userName": "admin5", "password": "<PASSWORD>",
"dateTime": post_time} # 提交数据
textmod = parse.urlencode(textmod).encode(encoding='utf-8') # 转码
url = 'https://localhost:8443/security!login.action'
req = request.Request(url=url, data=textmod)
try:
# 保存cookie
cj = http.cookiejar.CookieJar()
opener = request.build_opener(request.HTTPCookieProcessor(cj))
r = opener.open(req).read().decode('utf-8') # 返回登陆结果
except:
# 抛异常时调用企业微信发送,并退出
msg = 'ups_web不能正常连接.请检查'
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' ups_web不能正常连接.请检查.\n'
file_zj.writelines(file_nr)
sys.exit()
login_zc = '{"retMsg":"op.successfully"}'
print(r)
if login_zc != r: # 登陆失败发送消息,并退出
msg = 'ups_web登陆出错了.请检查'
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' ups_web登陆出错了.请检查.\n'
file_zj.writelines(file_nr)
sys.exit()
print(cj)
try:
req = request.Request(
'https://localhost:8443/alarmCurrent!initAlarmBoard.action')
opener = request.build_opener(
request.HTTPCookieProcessor(cj)) # 调用cookie访问
r = opener.open(req).read().decode('utf-8') # 返回状态结果
print(r)
except:
# 抛异常时调用企业微信发送,并退出
msg = 'ups_web不能正常连接.请检查'
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' ups_web获取电源状态时出错.请检查.\n'
file_zj.writelines(file_nr)
sys.exit()
end_zc = '{"alarmCountMap":{"alarm1":0,"alarm2":0,"alarm3":0,"alarm4":0}}'
req = request.Request(
'https://localhost:8443/securitys!loginOut.action') # 退出登陆
opener = request.build_opener(request.HTTPCookieProcessor(cj)) # 调用cookie访问
opener.open(req).read().decode('utf-8') # 返回状态结果
if end_zc != r:
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' 检测到电源有故障,请检查是否误报\n'
file_zj.writelines(file_nr)
ssh_all = (
('192.168.1.31', 'Mzj@Server31', 'root'), ('192.168.1.11', 'Mzj@Server11', 'root'), ('192.168.1.12', 'Mzj@Server12', 'root'), ('192.168.1.20', 'Mzj@Server20', 'root'))
for ssh_num in ssh_all:
print(ssh_num)
run(ssh_num)
os.system('shutdown -s -t 100') # 关机,shutdown -a 取消关机
# TODO 需要增加数据可视化
# set CL=/FI"%VCINSTALLDIR%\\INCLUDE\\stdint.h" %CL% | web_login.py |
# 利用华为ups检测机房是否停电
# 停电后发送企业微信告警并对主要服务器关机
import sys
import os
import time
import ssl
import json
import http.cookiejar
import paramiko
from urllib import parse, request
# ----------------------企业微信配置开始------------------------------------
corpid = '你自己的pid'
corpsecret = '你自己的key'
wx_url = 'https://qyapi.weixin.qq.com'
log_file = r'D:\脚本\web_loing.log'
# ----------------------取token---------------------------------------------
def get_token(wx_url, corpid, corpsecret):
token_url = '{}/cgi-bin/gettoken?corpid={}&corpsecret={}'.format(
wx_url, corpid, corpsecret)
token = json.loads(request.urlopen(token_url).read().decode())[
'access_token']
print(token)
return token
# -----------------------构建告警信息json----------------------------------------
def messages(msg):
values = {"touser": 'lijingfeng', "msgtype": 'text',
"agentid": 1000002, "text": {'content': msg}, "safe": 0}
msges = (bytes(json.dumps(values), 'utf-8'))
print(msges)
return msges
# ------------------发送告警信息--------------
def send_message(wx_url, token, data):
send_url = '{}/cgi-bin/message/send?access_token={}'.format(wx_url, token)
respone = request.urlopen(request.Request(url=send_url, data=data)).read()
x = json.loads(respone.decode())['errcode']
print(x)
if x == 0:
print('Succesfully')
else:
print('Failed')
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' 微信发送失败!.\n'
file_zj.writelines(file_nr)
# ----------------------企业微信配置结束------------------------------------
# ------------------连接linux主 机开始--------------
def run(ssh_num):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ssh_num[0], 22, ssh_num[2], ssh_num[1])
stdin, stdout, stderr = ssh.exec_command('shutdown -h 5')
ssh_end = stdout.read().decode('utf-8') # 回显
print(ssh_end)
print("check status %s OK\n" % ssh_num[0])
ssh.close()
# 关机后调用企业微信发送,并关本机
msg = '报警主机: {}\n 报警时间: {} \n 报警信息:检测到电源有故障,请检查是否误报,服务器将于5分钟后关机 \n 当前状态:等待关机'.format(
ssh_num[0], time.strftime("%Y-%m-%d %X", time.localtime(time.time())))
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
except Exception as ex:
print("\tError %s\n" % ex)
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime("%Y-%m-%d %X", time.localtime(time.time())) + \
"\tError %s" % ex + ' to ' + ssh_num[0] + '\n'
file_zj.writelines(file_nr)
# 抛异常时调用企业微信发送,并退出
msg = ssh_num[0] + '尝试关机失败'
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
# ------------------连接linux主 机结束--------------
ssl._create_default_https_context = ssl._create_unverified_context # 忽略ssl错误
post_time = str(int(time.time())) + "000" # 提交时间
textmod = {"userName": "admin5", "password": "<PASSWORD>",
"dateTime": post_time} # 提交数据
textmod = parse.urlencode(textmod).encode(encoding='utf-8') # 转码
url = 'https://localhost:8443/security!login.action'
req = request.Request(url=url, data=textmod)
try:
# 保存cookie
cj = http.cookiejar.CookieJar()
opener = request.build_opener(request.HTTPCookieProcessor(cj))
r = opener.open(req).read().decode('utf-8') # 返回登陆结果
except:
# 抛异常时调用企业微信发送,并退出
msg = 'ups_web不能正常连接.请检查'
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' ups_web不能正常连接.请检查.\n'
file_zj.writelines(file_nr)
sys.exit()
login_zc = '{"retMsg":"op.successfully"}'
print(r)
if login_zc != r: # 登陆失败发送消息,并退出
msg = 'ups_web登陆出错了.请检查'
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' ups_web登陆出错了.请检查.\n'
file_zj.writelines(file_nr)
sys.exit()
print(cj)
try:
req = request.Request(
'https://localhost:8443/alarmCurrent!initAlarmBoard.action')
opener = request.build_opener(
request.HTTPCookieProcessor(cj)) # 调用cookie访问
r = opener.open(req).read().decode('utf-8') # 返回状态结果
print(r)
except:
# 抛异常时调用企业微信发送,并退出
msg = 'ups_web不能正常连接.请检查'
test_token = get_token(wx_url, corpid, corpsecret)
msg_data = messages(msg)
send_message(wx_url, test_token, msg_data)
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' ups_web获取电源状态时出错.请检查.\n'
file_zj.writelines(file_nr)
sys.exit()
end_zc = '{"alarmCountMap":{"alarm1":0,"alarm2":0,"alarm3":0,"alarm4":0}}'
req = request.Request(
'https://localhost:8443/securitys!loginOut.action') # 退出登陆
opener = request.build_opener(request.HTTPCookieProcessor(cj)) # 调用cookie访问
opener.open(req).read().decode('utf-8') # 返回状态结果
if end_zc != r:
with open(log_file, 'a', encoding='utf-8') as file_zj:
file_nr = time.strftime(
"%Y-%m-%d %X", time.localtime(time.time())) + ' 检测到电源有故障,请检查是否误报\n'
file_zj.writelines(file_nr)
ssh_all = (
('192.168.1.31', 'Mzj@Server31', 'root'), ('192.168.1.11', 'Mzj@Server11', 'root'), ('192.168.1.12', 'Mzj@Server12', 'root'), ('192.168.1.20', 'Mzj@Server20', 'root'))
for ssh_num in ssh_all:
print(ssh_num)
run(ssh_num)
os.system('shutdown -s -t 100') # 关机,shutdown -a 取消关机
# TODO 需要增加数据可视化
# set CL=/FI"%VCINSTALLDIR%\\INCLUDE\\stdint.h" %CL% | 0.164852 | 0.110136 |
import numpy as np
import pandas as pd
from math import floor
import sys
from .erorrs import NotBinaryData, NoSuchColumn
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
class ICOTE
def __init__(self, binary_columns : list = None, seed : 'int > 0' = 42) -> None:
'''
The constructor of ICOTE.
:param binary_columns: list, default = None
The list of columns that should have binary values after balancing.
:param seed: int > 0, default = 42
The seed for random number generator.
'''
if binary_columns is None:
self.__binarize = False
else:
self.__binarize = True
self.__binary_columns = binary_columns
self.__seed = seed
np.random.seed(self.__seed)
def __to_binary(self) -> None:
'''
If the :param binary_columns: is set to True then the intermediate values in binary columns will be rounded.
'''
for column_name in self.__binary_columns:
serie = self.synthetic_df[column_name].values
threshold = (self.df[column_name].max() + self.df[column_name].min()) / 2
for i in range(len(serie)):
if serie[i] >= threshold:
serie[i] = self.df[column_name].max()
else:
serie[i] = self.df[column_name].min()
self.synthetic_df[column_name] = serie
def __infinity_check(self, matrix : 'np.array') -> 'np.array':
'''
This function replaces the infinity and -infinity values with the minimal and maximal float python values.
:param matrix: 'np.array'
The numpy array that was generated my the algorithm.
:return: 'np.array'
The numpy array with the infinity replaced values.
'''
matrix[matrix == -np.inf] = sys.float_info.min
matrix[matrix == np.inf] = sys.float_info.max
return matrix
def balance(self, df : 'pd.DataFrame', target : str):
'''
The balance function.
:param df: pd.DataFrame
The pandas Data Frame to apply the balancer.
:param target: str
The name of the target column.
:return: pd.DataFrame
A pandas Data Frame
'''
# Creating an internal copy of the data frame.
self.df = df.copy()
self.target = target
# Checking if the target string based t algorithm is present in the data frame.
if target not in self.df.columns:
raise NoSuchColumn(f"{target} isn't a column of passed data frame")
# Checking if the target column is a binary one.
if len(self.df[target].unique()) != 2:
raise NotBinaryData(f"{target} column isn't a binary column")
# Getting the column names that are not the target one.
self.X_columns = [column for column in self.df.columns if column != target]
# Getting the class frequencies.
classes_frequency = dict(self.df[target].value_counts())
# Searching for the class with the biggest frequency.
max_freq = 0
for cls in classes_frequency:
if classes_frequency[cls] > max_freq:
majority_class = cls
max_freq = classes_frequency[cls]
# Getting the name of the minority class.
minority_class = [cls for cls in classes_frequency if cls != majority_class][0]
# Splitting the data in features and target arrays.
X, y = self.df[self.X_columns].values, self.df[self.target].values
# Getting the min and max arrays of the features.
X_min = X.min(axis=0)
X_max = X.max(axis=0)
# Normalising the data.
norm_X = (X - X_min) / (X_max - X_min)
# Getting the indexes of the minority and majority classes.
minority_index = np.where(y == minority_class)
majority_index = np.where(y == majority_class)
# Getting the number of samples of minority class.
minority_samples: int = len(minority_index)
# Defining the empty list with synthetic data.
self.synthetic_data = []
while minority_samples <= len(majority_index):
# Creating clones for every minority sample.
for i in minority_index[0]:
clones = [].copy()
dist = [].copy()
for j in majority_index[0]:
dist.append(np.linalg.norm(norm_X[i] - norm_X[j], ord=2))
for dist_index in range(len(dist)):
if dist[dist_index] == 0:
continue
for _ in range(floor(dist[dist_index])):
clones.append([norm_X[i], dist_index])
for clone_index in range(len(clones)):
alpha = 1 / dist[clones[clone_index][1]]
if alpha < 0.05:
continue
# Creating mutations in clones.
clones[clone_index][0] = clones[clone_index][0] + alpha * (clones[clone_index][0] - norm_X[clones[clone_index][1]])
# Adding the clones to the synthetic data list.
self.synthetic_data.extend([clone[0] for clone in clones])
minority_samples += len(clones)
# Selecting majority - minority samples.
selected_data = np.random.randint(len(self.synthetic_data), size=(len(majority_index[0]) - len(minority_index[0]), 1))
self.synthetic_data = np.array(self.synthetic_data)[selected_data.reshape(1, -1)[0], :]
# Taking the data to the original dimensions.
for i in range(len(self.synthetic_data)):
self.synthetic_data[i] = X_min + (X_max - X_min) * self.synthetic_data[i]
# Replacing infinity values with minimal and maximal float python values.
self.synthetic_data = self.__infinity_check(np.array(self.synthetic_data).astype(float))
# Creating the synthetic data frame.
self.synthetic_df = pd.DataFrame(np.array(self.synthetic_data), columns=self.X_columns)
# Rounding binary columns if needed.
if self.__binarize:
self.__to_binary()
# Adding the target column.
self.synthetic_df.loc[:, self.target] = minority_class
new_df = pd.concat([self.df, self.synthetic_df], axis=0)
return new_df | crucio/ICOTE.py | import numpy as np
import pandas as pd
from math import floor
import sys
from .erorrs import NotBinaryData, NoSuchColumn
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
class ICOTE
def __init__(self, binary_columns : list = None, seed : 'int > 0' = 42) -> None:
'''
The constructor of ICOTE.
:param binary_columns: list, default = None
The list of columns that should have binary values after balancing.
:param seed: int > 0, default = 42
The seed for random number generator.
'''
if binary_columns is None:
self.__binarize = False
else:
self.__binarize = True
self.__binary_columns = binary_columns
self.__seed = seed
np.random.seed(self.__seed)
def __to_binary(self) -> None:
'''
If the :param binary_columns: is set to True then the intermediate values in binary columns will be rounded.
'''
for column_name in self.__binary_columns:
serie = self.synthetic_df[column_name].values
threshold = (self.df[column_name].max() + self.df[column_name].min()) / 2
for i in range(len(serie)):
if serie[i] >= threshold:
serie[i] = self.df[column_name].max()
else:
serie[i] = self.df[column_name].min()
self.synthetic_df[column_name] = serie
def __infinity_check(self, matrix : 'np.array') -> 'np.array':
'''
This function replaces the infinity and -infinity values with the minimal and maximal float python values.
:param matrix: 'np.array'
The numpy array that was generated my the algorithm.
:return: 'np.array'
The numpy array with the infinity replaced values.
'''
matrix[matrix == -np.inf] = sys.float_info.min
matrix[matrix == np.inf] = sys.float_info.max
return matrix
def balance(self, df : 'pd.DataFrame', target : str):
'''
The balance function.
:param df: pd.DataFrame
The pandas Data Frame to apply the balancer.
:param target: str
The name of the target column.
:return: pd.DataFrame
A pandas Data Frame
'''
# Creating an internal copy of the data frame.
self.df = df.copy()
self.target = target
# Checking if the target string based t algorithm is present in the data frame.
if target not in self.df.columns:
raise NoSuchColumn(f"{target} isn't a column of passed data frame")
# Checking if the target column is a binary one.
if len(self.df[target].unique()) != 2:
raise NotBinaryData(f"{target} column isn't a binary column")
# Getting the column names that are not the target one.
self.X_columns = [column for column in self.df.columns if column != target]
# Getting the class frequencies.
classes_frequency = dict(self.df[target].value_counts())
# Searching for the class with the biggest frequency.
max_freq = 0
for cls in classes_frequency:
if classes_frequency[cls] > max_freq:
majority_class = cls
max_freq = classes_frequency[cls]
# Getting the name of the minority class.
minority_class = [cls for cls in classes_frequency if cls != majority_class][0]
# Splitting the data in features and target arrays.
X, y = self.df[self.X_columns].values, self.df[self.target].values
# Getting the min and max arrays of the features.
X_min = X.min(axis=0)
X_max = X.max(axis=0)
# Normalising the data.
norm_X = (X - X_min) / (X_max - X_min)
# Getting the indexes of the minority and majority classes.
minority_index = np.where(y == minority_class)
majority_index = np.where(y == majority_class)
# Getting the number of samples of minority class.
minority_samples: int = len(minority_index)
# Defining the empty list with synthetic data.
self.synthetic_data = []
while minority_samples <= len(majority_index):
# Creating clones for every minority sample.
for i in minority_index[0]:
clones = [].copy()
dist = [].copy()
for j in majority_index[0]:
dist.append(np.linalg.norm(norm_X[i] - norm_X[j], ord=2))
for dist_index in range(len(dist)):
if dist[dist_index] == 0:
continue
for _ in range(floor(dist[dist_index])):
clones.append([norm_X[i], dist_index])
for clone_index in range(len(clones)):
alpha = 1 / dist[clones[clone_index][1]]
if alpha < 0.05:
continue
# Creating mutations in clones.
clones[clone_index][0] = clones[clone_index][0] + alpha * (clones[clone_index][0] - norm_X[clones[clone_index][1]])
# Adding the clones to the synthetic data list.
self.synthetic_data.extend([clone[0] for clone in clones])
minority_samples += len(clones)
# Selecting majority - minority samples.
selected_data = np.random.randint(len(self.synthetic_data), size=(len(majority_index[0]) - len(minority_index[0]), 1))
self.synthetic_data = np.array(self.synthetic_data)[selected_data.reshape(1, -1)[0], :]
# Taking the data to the original dimensions.
for i in range(len(self.synthetic_data)):
self.synthetic_data[i] = X_min + (X_max - X_min) * self.synthetic_data[i]
# Replacing infinity values with minimal and maximal float python values.
self.synthetic_data = self.__infinity_check(np.array(self.synthetic_data).astype(float))
# Creating the synthetic data frame.
self.synthetic_df = pd.DataFrame(np.array(self.synthetic_data), columns=self.X_columns)
# Rounding binary columns if needed.
if self.__binarize:
self.__to_binary()
# Adding the target column.
self.synthetic_df.loc[:, self.target] = minority_class
new_df = pd.concat([self.df, self.synthetic_df], axis=0)
return new_df | 0.457621 | 0.403802 |
import numpy as np
import pandas as pd
from netfile.ipeds_file import IpedsFile
from database.ipeds_grad_rates import IpedsGraduationRate
from database.date_dimension import DateRow
from database.ipeds_demographic_dimension import IpedsDemographicDimension
class GraduationRateFile(IpedsFile):
def __init__(self, year):
super().__init__(year)
self.populate_rows()
def populate_rows(self):
# get appropriate url for year
url = self.get_url(f'gr{self.year}.zip')
print(f'Reading data from {url}')
df = self.read(url,
{
'UNITID': np.int32,
'GRTYPE': np.int32,
'CHRTSTAT': np.int32,
'SECTION': np.int32,
'COHORT': np.int32,
'LINE' : np.str,
'GRRACE01' : np.float32,
'GRRACE02' : np.float32,
'GRRACE03' : np.float32,
'GRRACE04' : np.float32,
'GRRACE05' : np.float32,
'GRRACE06' : np.float32,
'GRRACE07' : np.float32,
'GRRACE08' : np.float32,
'GRRACE09' : np.float32,
'GRRACE10' : np.float32,
'GRRACE11' : np.float32,
'GRRACE12' : np.float32,
'GRRACE13' : np.float32,
'GRRACE14' : np.float32,
'DVGRHSM' : np.float32,
'DVGRHSW' : np.float32,
'DVGRAIM' : np.float32,
'DVGRAIW' : np.float32,
'DVGRBKM' : np.float32,
'DVGRBKW' : np.float32,
'DVGRWHM' : np.float32,
'DVGRWHW' : np.float32,
'GRNRALM': np.float32,
'GRNRALW': np.float32,
'GRUNKNM': np.float32,
'GRUNKNW': np.float32,
'GRHISPM': np.float32,
'GRHISPW': np.float32,
'GRAIANM': np.float32,
'GRAIAMW': np.float32,
'GRASIAM': np.float32,
'GRASIAW': np.float32,
'GRBKAAM': np.float32,
'GRBKAAW': np.float32,
'GRNHPIM': np.float32,
'GRNHPIW': np.float32,
'GRWHITM': np.float32,
'GRWHITW': np.float32,
'GR2MORM': np.float32,
'GR2MORW': np.float32,
})
# add date key
df['date_key'] = self.date_key
# year-specific columns
if (self.year < 2008):
if (self.year > 1999 and self.year <= 2001):
df['efalevel'] = self.item_recode(
df.line, {
1 : 24,
3 : 25,
7 : 31,
11 : 32,
9 : 36,
15 : 44,
17 : 45,
21: 45,
25 : 52,
23 : 56,
},
99
)
elif (self.year < 2000):
df['efalevel'] = self.item_recode(
df.line, {
1 : 24,
3 : 40,
4 : 40,
5 : 40,
6 : 40,
2 : 39,
7 : 31,
11 : 32,
12 : 32,
13 : 32,
9 : 36,
10 : 36,
15 : 44,
16 : 59,
17 : 60,
18 : 60,
19 : 60,
20 : 60,
21 : 51,
25 : 52,
26 : 52,
23 : 56,
24 : 56,
},
99
)
levels = (24, 25, 31, 32, 36, 44, 45, 51, 52, 56)
df['efnralm'] = df['efrace01']
df['efnralw'] = df['efrace02']
df['efunknm'] = df['efrace13']
df['efunknw'] = df['efrace14']
df['efhispm'] = df['efrace09']
df['efhispw'] = df['efrace10']
df['efaianm'] = df['efrace05']
df['efaianw'] = df['efrace06']
df['efasiam'] = df['efrace07']
df['efasiaw'] = df['efrace08']
df['efbkaam'] = df['efrace03']
df['efbkaaw'] = df['efrace04']
df['efnhpim'] = 0
df['efnhpiw'] = 0
df['efwhitm'] = df['efrace11']
df['efwhitw'] = df['efrace12']
df['ef2morm'] = 0
df['ef2morw'] = 0
elif (self.year == 2008):
levels = (24, 25, 31, 32, 36, 44, 45, 51, 52, 56)
df['efhispm'] = df['dvefhsm']
df['efhispw'] = df['dvefhsw']
df['efaianm'] = df['dvefaim']
df['efaianw'] = df['dvefaiw']
df['efasiam'] = df['dvefapm']
df['efasiaw'] = df['dvefapw']
df['efbkaam'] = df['dvefbkm']
df['efbkaaw'] = df['dvefbkw']
df['efnhpim'] = 0
df['efnhpiw'] = 0
df['efwhitm'] = df['dvefwhm']
df['efwhitw'] = df['dvefwhw']
elif (self.year == 2009):
levels = (24, 31, 32, 39, 40, 44, 51, 52, 59, 60)
df['efhispm'] = df['dvefhsm']
df['efhispw'] = df['dvefhsw']
df['efaianm'] = df['dvefaim']
df['efaianw'] = df['dvefaiw']
df['efasiam'] = df['dvefapm']
df['efasiaw'] = df['dvefapw']
df['efbkaam'] = df['dvefbkm']
df['efbkaaw'] = df['dvefbkw']
df['efnhpim'] = 0
df['efnhpiw'] = 0
df['efwhitm'] = df['dvefwhm']
df['efwhitw'] = df['dvefwhw']
else:
levels = (24, 31, 32, 39, 40, 44, 51, 52, 59, 60)
keepers = [
'unitid', 'date_key', 'efalevel',
'efnralm', 'efnralw', 'efunknm', 'efunknw', 'efhispm', 'efhispw',
'efaianm', 'efaianw', 'efasiam', 'efasiaw', 'efbkaam', 'efbkaaw',
'efnhpim', 'efnhpiw', 'efwhitm', 'efwhitw', 'ef2morm', 'ef2morw',
]
# add back missing variables
for col in keepers:
if col not in list(df.columns):
df[col] = None
# reduce file
df = df[keepers].fillna(0)
# filter out unused rows
df = df[df.efalevel.isin(levels)]
# assign time status
df['time_status'] = self.item_recode(
df.efalevel, {
24: 'Full-time',
25: 'Full-time',
31: 'Full-time',
32: 'Full-time',
36: 'Full-time',
39: 'Full-time',
40: 'Full-time',
},
'Part-time'
)
# assign career level
df['career_level'] = self.item_recode(
df.efalevel, {
32: 'Graduate',
36: 'Graduate',
52: 'Graduate',
56: 'Graduate',
},
'Undergraduate')
# assign degree seeking status
df['degree_seeking'] = self.item_recode(
df.efalevel, {
24: 'Degree-seeking',
25: 'Degree-seeking',
31: 'Non-degree-seeking',
39: 'Degree-seeking',
40: 'Degree-seeking',
44: 'Degree-seeking',
45: 'Degree-seeking',
51: 'Non-degree-seeking',
59: 'Degree-seeking',
60: 'Degree-seeking',
},
'Unknown')
# assign continuation type
df['continuation_type'] = self.item_recode(df.efalevel, {
24: 'First-time',
39: 'Transfer',
40: 'Continuing',
44: 'First-time',
59: 'Transfer',
60: 'Continuing',
},
'Unknown')
# id columns
id_columns = ['unitid','date_key','time_status','career_level','degree_seeking','continuation_type']
# reshape from wide to long format
df = pd.melt(
df,
id_vars = id_columns,
value_vars = [
'efnralm', 'efnralw', 'efunknm', 'efunknw', 'efhispm',
'efhispw', 'efaianm', 'efaianw', 'efasiam', 'efasiaw',
'efbkaam', 'efbkaaw', 'efnhpim', 'efnhpiw', 'efwhitm',
'efwhitw', 'ef2morm', 'ef2morw'
],
value_name = 'headcount')
# demographic dimension
df['demographic_key'] = df.variable.str.slice(2, 7).str.lower()
id_columns.append('demographic_key')
# drop variable field
df = df.drop(columns = ['variable'])
# remove institutions with no data
df.headcount = df.headcount.fillna(0)
# collapse sums
df = df.groupby(id_columns).sum().reset_index()
# keep only rows with non-zero headcount
df = df.query('headcount > 0')
# unitid = Column(Integer, nullable = False)
# date_key = Column(Date, ForeignKey('date_dimension.date_key'), nullable = False)
# cohort_date_key = Column(Date, ForeignKey('date_dimension.date_key'), nullable = False)
# demographic_key = Column(String(5), ForeignKey('ipeds_demographic_dimension.demographic_key'), nullable = False)
# entering_cohort = Column(Integer, nullable = False, default = 0)
# exclusions = Column(Integer, nullable = False, default = 0)
# adjusted_cohort = Column(Integer, nullable = False, default = 0)
# completers_4_years = Column(Integer, nullable = False, default = 0)
# completers_5_years = Column(Integer, nullable = False, default = 0)
# completers_6_years = Column(Integer, nullable = False, default = 0)
# enrolled= Column(Integer, nullable = False, default = 0)
# transfers = Column(Integer, nullable = False, default = 0)
# no_longer_enrolled = Column(Integer, nullable = False, default = 0)
for row in df.itertuples(index=False):
self.rows.append(
IpedsGraduationRate(
unitid = row.unitid,
date_key = row.date_key,
time_status = row.time_status,
career_level = row.career_level,
degree_seeking = row.degree_seeking,
continuation_type = row.continuation_type,
demographic_key = row.demographic_key,
headcount = row.headcount))
def __repr__(self):
return('{self.__class__.__name__}={})'.format(self.year))
def write(self):
print(f'Writing {len(self.rows):,} rows to {IpedsGraduationRate.__tablename__} table in database.')
super().write()
if __name__ == '__main__':
adm = GraduationRateFile(2018)
print(adm.year)
print(adm.url)
print(adm.rows[0]) | netfile/graduation_rate_file.py |
import numpy as np
import pandas as pd
from netfile.ipeds_file import IpedsFile
from database.ipeds_grad_rates import IpedsGraduationRate
from database.date_dimension import DateRow
from database.ipeds_demographic_dimension import IpedsDemographicDimension
class GraduationRateFile(IpedsFile):
def __init__(self, year):
super().__init__(year)
self.populate_rows()
def populate_rows(self):
# get appropriate url for year
url = self.get_url(f'gr{self.year}.zip')
print(f'Reading data from {url}')
df = self.read(url,
{
'UNITID': np.int32,
'GRTYPE': np.int32,
'CHRTSTAT': np.int32,
'SECTION': np.int32,
'COHORT': np.int32,
'LINE' : np.str,
'GRRACE01' : np.float32,
'GRRACE02' : np.float32,
'GRRACE03' : np.float32,
'GRRACE04' : np.float32,
'GRRACE05' : np.float32,
'GRRACE06' : np.float32,
'GRRACE07' : np.float32,
'GRRACE08' : np.float32,
'GRRACE09' : np.float32,
'GRRACE10' : np.float32,
'GRRACE11' : np.float32,
'GRRACE12' : np.float32,
'GRRACE13' : np.float32,
'GRRACE14' : np.float32,
'DVGRHSM' : np.float32,
'DVGRHSW' : np.float32,
'DVGRAIM' : np.float32,
'DVGRAIW' : np.float32,
'DVGRBKM' : np.float32,
'DVGRBKW' : np.float32,
'DVGRWHM' : np.float32,
'DVGRWHW' : np.float32,
'GRNRALM': np.float32,
'GRNRALW': np.float32,
'GRUNKNM': np.float32,
'GRUNKNW': np.float32,
'GRHISPM': np.float32,
'GRHISPW': np.float32,
'GRAIANM': np.float32,
'GRAIAMW': np.float32,
'GRASIAM': np.float32,
'GRASIAW': np.float32,
'GRBKAAM': np.float32,
'GRBKAAW': np.float32,
'GRNHPIM': np.float32,
'GRNHPIW': np.float32,
'GRWHITM': np.float32,
'GRWHITW': np.float32,
'GR2MORM': np.float32,
'GR2MORW': np.float32,
})
# add date key
df['date_key'] = self.date_key
# year-specific columns
if (self.year < 2008):
if (self.year > 1999 and self.year <= 2001):
df['efalevel'] = self.item_recode(
df.line, {
1 : 24,
3 : 25,
7 : 31,
11 : 32,
9 : 36,
15 : 44,
17 : 45,
21: 45,
25 : 52,
23 : 56,
},
99
)
elif (self.year < 2000):
df['efalevel'] = self.item_recode(
df.line, {
1 : 24,
3 : 40,
4 : 40,
5 : 40,
6 : 40,
2 : 39,
7 : 31,
11 : 32,
12 : 32,
13 : 32,
9 : 36,
10 : 36,
15 : 44,
16 : 59,
17 : 60,
18 : 60,
19 : 60,
20 : 60,
21 : 51,
25 : 52,
26 : 52,
23 : 56,
24 : 56,
},
99
)
levels = (24, 25, 31, 32, 36, 44, 45, 51, 52, 56)
df['efnralm'] = df['efrace01']
df['efnralw'] = df['efrace02']
df['efunknm'] = df['efrace13']
df['efunknw'] = df['efrace14']
df['efhispm'] = df['efrace09']
df['efhispw'] = df['efrace10']
df['efaianm'] = df['efrace05']
df['efaianw'] = df['efrace06']
df['efasiam'] = df['efrace07']
df['efasiaw'] = df['efrace08']
df['efbkaam'] = df['efrace03']
df['efbkaaw'] = df['efrace04']
df['efnhpim'] = 0
df['efnhpiw'] = 0
df['efwhitm'] = df['efrace11']
df['efwhitw'] = df['efrace12']
df['ef2morm'] = 0
df['ef2morw'] = 0
elif (self.year == 2008):
levels = (24, 25, 31, 32, 36, 44, 45, 51, 52, 56)
df['efhispm'] = df['dvefhsm']
df['efhispw'] = df['dvefhsw']
df['efaianm'] = df['dvefaim']
df['efaianw'] = df['dvefaiw']
df['efasiam'] = df['dvefapm']
df['efasiaw'] = df['dvefapw']
df['efbkaam'] = df['dvefbkm']
df['efbkaaw'] = df['dvefbkw']
df['efnhpim'] = 0
df['efnhpiw'] = 0
df['efwhitm'] = df['dvefwhm']
df['efwhitw'] = df['dvefwhw']
elif (self.year == 2009):
levels = (24, 31, 32, 39, 40, 44, 51, 52, 59, 60)
df['efhispm'] = df['dvefhsm']
df['efhispw'] = df['dvefhsw']
df['efaianm'] = df['dvefaim']
df['efaianw'] = df['dvefaiw']
df['efasiam'] = df['dvefapm']
df['efasiaw'] = df['dvefapw']
df['efbkaam'] = df['dvefbkm']
df['efbkaaw'] = df['dvefbkw']
df['efnhpim'] = 0
df['efnhpiw'] = 0
df['efwhitm'] = df['dvefwhm']
df['efwhitw'] = df['dvefwhw']
else:
levels = (24, 31, 32, 39, 40, 44, 51, 52, 59, 60)
keepers = [
'unitid', 'date_key', 'efalevel',
'efnralm', 'efnralw', 'efunknm', 'efunknw', 'efhispm', 'efhispw',
'efaianm', 'efaianw', 'efasiam', 'efasiaw', 'efbkaam', 'efbkaaw',
'efnhpim', 'efnhpiw', 'efwhitm', 'efwhitw', 'ef2morm', 'ef2morw',
]
# add back missing variables
for col in keepers:
if col not in list(df.columns):
df[col] = None
# reduce file
df = df[keepers].fillna(0)
# filter out unused rows
df = df[df.efalevel.isin(levels)]
# assign time status
df['time_status'] = self.item_recode(
df.efalevel, {
24: 'Full-time',
25: 'Full-time',
31: 'Full-time',
32: 'Full-time',
36: 'Full-time',
39: 'Full-time',
40: 'Full-time',
},
'Part-time'
)
# assign career level
df['career_level'] = self.item_recode(
df.efalevel, {
32: 'Graduate',
36: 'Graduate',
52: 'Graduate',
56: 'Graduate',
},
'Undergraduate')
# assign degree seeking status
df['degree_seeking'] = self.item_recode(
df.efalevel, {
24: 'Degree-seeking',
25: 'Degree-seeking',
31: 'Non-degree-seeking',
39: 'Degree-seeking',
40: 'Degree-seeking',
44: 'Degree-seeking',
45: 'Degree-seeking',
51: 'Non-degree-seeking',
59: 'Degree-seeking',
60: 'Degree-seeking',
},
'Unknown')
# assign continuation type
df['continuation_type'] = self.item_recode(df.efalevel, {
24: 'First-time',
39: 'Transfer',
40: 'Continuing',
44: 'First-time',
59: 'Transfer',
60: 'Continuing',
},
'Unknown')
# id columns
id_columns = ['unitid','date_key','time_status','career_level','degree_seeking','continuation_type']
# reshape from wide to long format
df = pd.melt(
df,
id_vars = id_columns,
value_vars = [
'efnralm', 'efnralw', 'efunknm', 'efunknw', 'efhispm',
'efhispw', 'efaianm', 'efaianw', 'efasiam', 'efasiaw',
'efbkaam', 'efbkaaw', 'efnhpim', 'efnhpiw', 'efwhitm',
'efwhitw', 'ef2morm', 'ef2morw'
],
value_name = 'headcount')
# demographic dimension
df['demographic_key'] = df.variable.str.slice(2, 7).str.lower()
id_columns.append('demographic_key')
# drop variable field
df = df.drop(columns = ['variable'])
# remove institutions with no data
df.headcount = df.headcount.fillna(0)
# collapse sums
df = df.groupby(id_columns).sum().reset_index()
# keep only rows with non-zero headcount
df = df.query('headcount > 0')
# unitid = Column(Integer, nullable = False)
# date_key = Column(Date, ForeignKey('date_dimension.date_key'), nullable = False)
# cohort_date_key = Column(Date, ForeignKey('date_dimension.date_key'), nullable = False)
# demographic_key = Column(String(5), ForeignKey('ipeds_demographic_dimension.demographic_key'), nullable = False)
# entering_cohort = Column(Integer, nullable = False, default = 0)
# exclusions = Column(Integer, nullable = False, default = 0)
# adjusted_cohort = Column(Integer, nullable = False, default = 0)
# completers_4_years = Column(Integer, nullable = False, default = 0)
# completers_5_years = Column(Integer, nullable = False, default = 0)
# completers_6_years = Column(Integer, nullable = False, default = 0)
# enrolled= Column(Integer, nullable = False, default = 0)
# transfers = Column(Integer, nullable = False, default = 0)
# no_longer_enrolled = Column(Integer, nullable = False, default = 0)
for row in df.itertuples(index=False):
self.rows.append(
IpedsGraduationRate(
unitid = row.unitid,
date_key = row.date_key,
time_status = row.time_status,
career_level = row.career_level,
degree_seeking = row.degree_seeking,
continuation_type = row.continuation_type,
demographic_key = row.demographic_key,
headcount = row.headcount))
def __repr__(self):
return('{self.__class__.__name__}={})'.format(self.year))
def write(self):
print(f'Writing {len(self.rows):,} rows to {IpedsGraduationRate.__tablename__} table in database.')
super().write()
if __name__ == '__main__':
adm = GraduationRateFile(2018)
print(adm.year)
print(adm.url)
print(adm.rows[0]) | 0.219505 | 0.128689 |
import getpass
import pyaes
import sqlite3
import hashlib
import string
import random
conn = None
_name_lock = None
class Key:
_k = None
@staticmethod
def set(key: bytes):
if key is None:
Key._k = None
return
Key._k = list(key)
for i in range(len(Key._k)):
Key._k[i] ^= hash('salt')
@staticmethod
def get():
return bytes([Key._k[i] ^ hash('salt') for i in range(len(Key._k))])
@staticmethod
def setted():
if Key._k:
return True
return False
def init_db(path=None):
global conn, _name_lock
if path is None:
for i in range(len(__file__)-1, -1, -1):
if __file__[i] in ('/', '\\'):
path = ''.join([__file__[:i+1], 'secure.db'])
break
conn = sqlite3.connect(path)
c = conn.cursor()
try:
c.execute('create table verify(id primary key not null'
', verify_key text not null, name_lock text not null)')
c.execute('create table content(id integer primary key autoincrement'
' not null, name text not null, account text not null, pass'
'word text not null, extra text, random_key text not null)')
print('create new sqlite3 database file (%s) success.' % path)
except sqlite3.OperationalError:
pass
c.close()
_name_lock = None
def new_random_key(length=32):
return ''.join(random.sample(
string.ascii_letters + string.digits, length))
def aes_encrypts(s: str, key, no_padding=False):
if isinstance(s, str):
s = s.encode('utf-8')
if isinstance(key, str):
key = key.encode('utf-8')
aes_ = pyaes.AESModeOfOperationCBC(key)
if no_padding and len(s)/16-int(len(s)/16) == 0:
s_ = s
else:
s_ = pyaes.util.append_PKCS7_padding(s)
r = list()
for i in range(int(len(s_)/16)):
r.append(aes_.encrypt(s_[i*16:(i+1)*16]))
return b''.join(r)
def aes_decrypts(b: bytes, key, no_padding=False):
if isinstance(key, str):
key = key.encode('utf-8')
aes_ = pyaes.AESModeOfOperationCBC(key)
r = list()
for i in range(int(len(b)/16)):
r.append(aes_.decrypt(b[i*16:(i+1)*16]))
if no_padding:
return b''.join(r).decode('utf-8')
return pyaes.util.strip_PKCS7_padding(b''.join(r)).decode('utf-8')
def add_sign(s: str):
s_ = list(s)
for i in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31):
s_[i] = '\x7f'
return ''.join(s_)
def veri_sign(s: str):
for i in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31):
if s[i] != '\x7f':
return False
return True
def get_password(prompt):
_pw = getpass.getpass(prompt)
if len(_pw) not in range(4, 19):
print('incorrect password length (must 4-18).')
return None
for ch in _pw:
if 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' or '0' <= ch <= '9':
continue
if ch in ('!', '@', '#', '$', '-', '_'):
continue
print('incorrect password spell (must by 0-9 a-Z !@#$-_ ).')
return None
return _pw
def require_key():
if Key.setted():
return True
if conn is None:
init_db()
c = conn.cursor()
c.execute('select verify_key from verify where id=0')
v = c.fetchone()
if v is None:
c.execute('select count(*) from content')
if c.fetchone()[0] != 0:
return False
print('creating new password to your database:')
passwd = get_password('Password:')
passwd2 = get_password('Password Again:')
if passwd is None or passwd != passwd2:
print('inconsistent password.')
return False
Key.set(hashlib.sha256(passwd.encode('utf-8')).digest())
rs = new_random_key()
nk = new_random_key()
signed = add_sign(rs)
enc = aes_encrypts(signed, Key.get(), True)
enc2 = aes_encrypts(nk, Key.get(), True)
c.execute('insert into verify values (0, ?, ?)', (enc, enc2))
conn.commit()
c.close()
else:
print('verifying your password of database:')
passwd = get_password('Password:')
if passwd is None:
return False
Key.set(hashlib.sha256(passwd.encode('utf-8')).digest())
try:
dec = aes_decrypts(v[0], Key.get(), True)
verified = veri_sign(dec)
except UnicodeDecodeError:
verified = False
if not verified:
print('incorrect password.')
Key.set(None)
return False
return True
def get_name_lock_key():
global _name_lock
if _name_lock is None:
c = conn.cursor()
c.execute('select name_lock from verify where id=0')
_name_lock = c.fetchone()[0]
c.close()
_name_lock_de = aes_decrypts(_name_lock, Key.get(), True)
return add_sign(_name_lock_de)
def add_mode():
while True:
a = input('(ADD)>> ')
if len(a) > 5 and a[:5] == 'name ':
name = a[5:]
print('Name:', name)
account = input('Account: ')
if len(account) == 0:
continue
passwd = getpass.getpass('Password: ')
if len(passwd) == 0:
continue
passwd2 = getpass.getpass('Password Again: ')
if passwd != passwd2:
print('inconsistent password.')
continue
extra = input('Add Extra: ')
random_key = new_random_key()
name_en = aes_encrypts(name, get_name_lock_key())
account_en = aes_encrypts(account, random_key)
passwd_en = aes_encrypts(passwd, random_key)
extra_en = aes_encrypts(extra, random_key)
random_key_en = aes_encrypts(random_key, Key.get(), True)
c = conn.cursor()
c.execute('insert into content values (NULL, ?, ?, ?, ?, ?)', (
name_en, account_en, passwd_en, extra_en, random_key_en))
conn.commit()
c.close()
elif a in ('exit', 'quit'):
break
def command_list():
c = conn.cursor()
c.execute('select name from content')
datas = list(set(i[0] for i in c.fetchall()))
row_pos = 0
min_col = 5
for data in datas:
name = aes_decrypts(data, get_name_lock_key())
if row_pos < min_col-1:
print(name, end='\t')
row_pos += 1
else:
print(name)
row_pos = 0
if len(datas) % min_col > 0:
print('')
c.close()
def view_mode():
while True:
a = input('(VIEW)>> ')
if len(a) > 5 and a[:5] in ('name ', 'info '):
name = a[5:]
name_en = aes_encrypts(name, get_name_lock_key())
c = conn.cursor()
c.execute('select random_key, account, password, extra'
' from content where name=?', (name_en,))
datas = c.fetchall()
print('find %d account(s).' % len(datas))
random_key_cache = []
for i in range(len(datas)):
random_key = aes_decrypts(datas[i][0], Key.get(), True)
account = aes_decrypts(datas[i][1], random_key)
print('[%d] %s' % (i+1, account))
random_key_cache.append(random_key)
if len(datas) > 0:
if a[:5] == 'name ':
a1 = input('Choose to view password: ')
for n in a1.split(' '):
if n.isdecimal() and 0 < int(n) <= len(datas):
idx = int(n)-1
passwd = aes_decrypts(
datas[idx][2], random_key_cache[idx])
print('[%s] |%s|' % (n, passwd))
else:
break
else:
a1 = input('Choose to view extra: ')
for n in a1.split(' '):
if n.isdecimal() and 0 < int(n) <= len(datas):
idx = int(n)-1
extra = aes_decrypts(
datas[idx][3], random_key_cache[idx])
print('[%s]:\n%s' % (n, extra))
else:
break
c.close()
elif a == 'list':
command_list()
elif a in ('exit', 'quit'):
break
def remove_mode():
while True:
a = input('(REMOVE)>> ')
if len(a) > 5 and a[:5] == 'name ':
name = a[5:]
name_en = aes_encrypts(name, get_name_lock_key())
c = conn.cursor()
c.execute('select random_key, account, id'
' from content where name=?', (name_en,))
datas = c.fetchall()
print('find %d account(s).' % len(datas))
for i in range(len(datas)):
random_key = aes_decrypts(datas[i][0], Key.get(), True)
account = aes_decrypts(datas[i][1], random_key)
print('[%d] %s' % (i+1, account))
if len(datas) > 0:
a1 = input('Choose to delete: ')
for n in a1.split(' '):
if n.isdecimal() and 0 < int(n) <= len(datas):
c.execute('delete from content where id=?',
(datas[int(n)-1][2],))
else:
break
conn.commit()
c.close()
elif a in ('exit', 'quit'):
break
def change_mode():
while True:
a = input('(CHANGE)>> ')
if len(a) > 5 and a[:5] == 'name ':
name = a[5:]
name_en = aes_encrypts(name, get_name_lock_key())
c = conn.cursor()
c.execute('select random_key, account, extra, id'
' from content where name=?', (name_en,))
datas = c.fetchall()
print('find %d account(s).' % len(datas))
random_key_cache = []
for i in range(len(datas)):
random_key = aes_decrypts(datas[i][0], Key.get(), True)
account = aes_decrypts(datas[i][1], random_key)
print('[%d] %s' % (i+1, account))
random_key_cache.append(random_key)
if len(datas) > 0:
a1 = input('Choose to change password/extra: ')
for n in a1.split(' '):
if n.isdecimal() and 0 < int(n) <= len(datas):
passwd = getpass.getpass('[%s]New Password: ' % n)
if len(passwd) == 0:
continue
passwd2 = getpass.getpass(
'[%s]New Password Again: ' % n)
if passwd != passwd2:
print('inconsistent password.')
continue
extra = input('[%s]Add Extra: ' % n)
idx = int(n)-1
passwd_ch_en = aes_encrypts(
passwd, random_key_cache[idx])
if len(extra) > 0:
extra_de = aes_decrypts(
datas[idx][2], random_key_cache[idx])
if len(extra_de) > 0:
extra_ch = extra_de + '\n' + extra
else:
extra_ch = extra
extra_ch_en = aes_encrypts(
extra_ch, random_key_cache[idx])
c.execute(
'update content set password=?,'
' extra=? where id=?',
(passwd_ch_en, extra_ch_en, datas[idx][3]))
else:
c.execute(
'update content set password=? where id=?',
(passwd_ch_en, datas[idx][3]))
else:
break
conn.commit()
c.close()
if a in ('exit', 'quit'):
break
def change_password():
if conn is None:
init_db()
old_passwd = get_password('Old Password: ')
c = conn.cursor()
c.execute('select verify_key, name_lock from verify where id=0')
v = c.fetchone()
if v:
old_key = hashlib.sha256(old_passwd.encode('utf-8')).digest()
dec = aes_decrypts(v[0], old_key, True)
if not veri_sign(dec):
print('incorrect password.')
return
new_passwd = get_password('New Password: ')
new_passwd2 = get_password('New Password Again: ')
if len(new_passwd) == 0 or new_passwd != new_passwd2:
print('inconsistent password.')
return
new_key = hashlib.sha256(new_passwd.encode('utf-8')).digest()
enc = aes_encrypts(dec, new_key, True)
enc2 = aes_encrypts(aes_decrypts(v[1], old_key, True),
new_key, True)
c.execute('select id, random_key from content')
rows = c.fetchall()
rencs = []
for row in rows:
random_key_de = aes_decrypts(row[1], old_key, True)
rencs.append((aes_encrypts(random_key_de, new_key, True),
row[0]))
c.execute('update verify set verify_key=?, name_lock=? where id=0',
(enc, enc2))
c.executemany('update content set random_key=? where id=?', rencs)
conn.commit()
else:
print('database error.')
c.close()
def main():
while True:
try:
a = input('>> ')
except KeyboardInterrupt:
print('\nBye.')
break
if len(a) == 0:
continue
try:
if a == 'add':
if require_key():
add_mode()
Key.set(None)
elif a == 'view':
if require_key():
view_mode()
Key.set(None)
elif a == 'remove':
if require_key():
remove_mode()
Key.set(None)
elif a == 'change':
if require_key():
change_mode()
Key.set(None)
elif a == 'passwd':
change_password()
elif a == 'help':
print('Usage:\tadd | view | remove |'
' change | passwd')
print('Then:\tlist | name | info')
elif a in ('quit', 'exit'):
raise SystemExit
except SystemExit:
print('Bye.')
break
except KeyboardInterrupt:
Key.set(None)
print('')
if __name__ == '__main__':
print('Welcome to MySecure !')
main() | mysecure.py | import getpass
import pyaes
import sqlite3
import hashlib
import string
import random
conn = None
_name_lock = None
class Key:
_k = None
@staticmethod
def set(key: bytes):
if key is None:
Key._k = None
return
Key._k = list(key)
for i in range(len(Key._k)):
Key._k[i] ^= hash('salt')
@staticmethod
def get():
return bytes([Key._k[i] ^ hash('salt') for i in range(len(Key._k))])
@staticmethod
def setted():
if Key._k:
return True
return False
def init_db(path=None):
global conn, _name_lock
if path is None:
for i in range(len(__file__)-1, -1, -1):
if __file__[i] in ('/', '\\'):
path = ''.join([__file__[:i+1], 'secure.db'])
break
conn = sqlite3.connect(path)
c = conn.cursor()
try:
c.execute('create table verify(id primary key not null'
', verify_key text not null, name_lock text not null)')
c.execute('create table content(id integer primary key autoincrement'
' not null, name text not null, account text not null, pass'
'word text not null, extra text, random_key text not null)')
print('create new sqlite3 database file (%s) success.' % path)
except sqlite3.OperationalError:
pass
c.close()
_name_lock = None
def new_random_key(length=32):
return ''.join(random.sample(
string.ascii_letters + string.digits, length))
def aes_encrypts(s: str, key, no_padding=False):
if isinstance(s, str):
s = s.encode('utf-8')
if isinstance(key, str):
key = key.encode('utf-8')
aes_ = pyaes.AESModeOfOperationCBC(key)
if no_padding and len(s)/16-int(len(s)/16) == 0:
s_ = s
else:
s_ = pyaes.util.append_PKCS7_padding(s)
r = list()
for i in range(int(len(s_)/16)):
r.append(aes_.encrypt(s_[i*16:(i+1)*16]))
return b''.join(r)
def aes_decrypts(b: bytes, key, no_padding=False):
if isinstance(key, str):
key = key.encode('utf-8')
aes_ = pyaes.AESModeOfOperationCBC(key)
r = list()
for i in range(int(len(b)/16)):
r.append(aes_.decrypt(b[i*16:(i+1)*16]))
if no_padding:
return b''.join(r).decode('utf-8')
return pyaes.util.strip_PKCS7_padding(b''.join(r)).decode('utf-8')
def add_sign(s: str):
s_ = list(s)
for i in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31):
s_[i] = '\x7f'
return ''.join(s_)
def veri_sign(s: str):
for i in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31):
if s[i] != '\x7f':
return False
return True
def get_password(prompt):
_pw = getpass.getpass(prompt)
if len(_pw) not in range(4, 19):
print('incorrect password length (must 4-18).')
return None
for ch in _pw:
if 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' or '0' <= ch <= '9':
continue
if ch in ('!', '@', '#', '$', '-', '_'):
continue
print('incorrect password spell (must by 0-9 a-Z !@#$-_ ).')
return None
return _pw
def require_key():
if Key.setted():
return True
if conn is None:
init_db()
c = conn.cursor()
c.execute('select verify_key from verify where id=0')
v = c.fetchone()
if v is None:
c.execute('select count(*) from content')
if c.fetchone()[0] != 0:
return False
print('creating new password to your database:')
passwd = get_password('Password:')
passwd2 = get_password('Password Again:')
if passwd is None or passwd != passwd2:
print('inconsistent password.')
return False
Key.set(hashlib.sha256(passwd.encode('utf-8')).digest())
rs = new_random_key()
nk = new_random_key()
signed = add_sign(rs)
enc = aes_encrypts(signed, Key.get(), True)
enc2 = aes_encrypts(nk, Key.get(), True)
c.execute('insert into verify values (0, ?, ?)', (enc, enc2))
conn.commit()
c.close()
else:
print('verifying your password of database:')
passwd = get_password('Password:')
if passwd is None:
return False
Key.set(hashlib.sha256(passwd.encode('utf-8')).digest())
try:
dec = aes_decrypts(v[0], Key.get(), True)
verified = veri_sign(dec)
except UnicodeDecodeError:
verified = False
if not verified:
print('incorrect password.')
Key.set(None)
return False
return True
def get_name_lock_key():
global _name_lock
if _name_lock is None:
c = conn.cursor()
c.execute('select name_lock from verify where id=0')
_name_lock = c.fetchone()[0]
c.close()
_name_lock_de = aes_decrypts(_name_lock, Key.get(), True)
return add_sign(_name_lock_de)
def add_mode():
while True:
a = input('(ADD)>> ')
if len(a) > 5 and a[:5] == 'name ':
name = a[5:]
print('Name:', name)
account = input('Account: ')
if len(account) == 0:
continue
passwd = getpass.getpass('Password: ')
if len(passwd) == 0:
continue
passwd2 = getpass.getpass('Password Again: ')
if passwd != passwd2:
print('inconsistent password.')
continue
extra = input('Add Extra: ')
random_key = new_random_key()
name_en = aes_encrypts(name, get_name_lock_key())
account_en = aes_encrypts(account, random_key)
passwd_en = aes_encrypts(passwd, random_key)
extra_en = aes_encrypts(extra, random_key)
random_key_en = aes_encrypts(random_key, Key.get(), True)
c = conn.cursor()
c.execute('insert into content values (NULL, ?, ?, ?, ?, ?)', (
name_en, account_en, passwd_en, extra_en, random_key_en))
conn.commit()
c.close()
elif a in ('exit', 'quit'):
break
def command_list():
c = conn.cursor()
c.execute('select name from content')
datas = list(set(i[0] for i in c.fetchall()))
row_pos = 0
min_col = 5
for data in datas:
name = aes_decrypts(data, get_name_lock_key())
if row_pos < min_col-1:
print(name, end='\t')
row_pos += 1
else:
print(name)
row_pos = 0
if len(datas) % min_col > 0:
print('')
c.close()
def view_mode():
while True:
a = input('(VIEW)>> ')
if len(a) > 5 and a[:5] in ('name ', 'info '):
name = a[5:]
name_en = aes_encrypts(name, get_name_lock_key())
c = conn.cursor()
c.execute('select random_key, account, password, extra'
' from content where name=?', (name_en,))
datas = c.fetchall()
print('find %d account(s).' % len(datas))
random_key_cache = []
for i in range(len(datas)):
random_key = aes_decrypts(datas[i][0], Key.get(), True)
account = aes_decrypts(datas[i][1], random_key)
print('[%d] %s' % (i+1, account))
random_key_cache.append(random_key)
if len(datas) > 0:
if a[:5] == 'name ':
a1 = input('Choose to view password: ')
for n in a1.split(' '):
if n.isdecimal() and 0 < int(n) <= len(datas):
idx = int(n)-1
passwd = aes_decrypts(
datas[idx][2], random_key_cache[idx])
print('[%s] |%s|' % (n, passwd))
else:
break
else:
a1 = input('Choose to view extra: ')
for n in a1.split(' '):
if n.isdecimal() and 0 < int(n) <= len(datas):
idx = int(n)-1
extra = aes_decrypts(
datas[idx][3], random_key_cache[idx])
print('[%s]:\n%s' % (n, extra))
else:
break
c.close()
elif a == 'list':
command_list()
elif a in ('exit', 'quit'):
break
def remove_mode():
while True:
a = input('(REMOVE)>> ')
if len(a) > 5 and a[:5] == 'name ':
name = a[5:]
name_en = aes_encrypts(name, get_name_lock_key())
c = conn.cursor()
c.execute('select random_key, account, id'
' from content where name=?', (name_en,))
datas = c.fetchall()
print('find %d account(s).' % len(datas))
for i in range(len(datas)):
random_key = aes_decrypts(datas[i][0], Key.get(), True)
account = aes_decrypts(datas[i][1], random_key)
print('[%d] %s' % (i+1, account))
if len(datas) > 0:
a1 = input('Choose to delete: ')
for n in a1.split(' '):
if n.isdecimal() and 0 < int(n) <= len(datas):
c.execute('delete from content where id=?',
(datas[int(n)-1][2],))
else:
break
conn.commit()
c.close()
elif a in ('exit', 'quit'):
break
def change_mode():
while True:
a = input('(CHANGE)>> ')
if len(a) > 5 and a[:5] == 'name ':
name = a[5:]
name_en = aes_encrypts(name, get_name_lock_key())
c = conn.cursor()
c.execute('select random_key, account, extra, id'
' from content where name=?', (name_en,))
datas = c.fetchall()
print('find %d account(s).' % len(datas))
random_key_cache = []
for i in range(len(datas)):
random_key = aes_decrypts(datas[i][0], Key.get(), True)
account = aes_decrypts(datas[i][1], random_key)
print('[%d] %s' % (i+1, account))
random_key_cache.append(random_key)
if len(datas) > 0:
a1 = input('Choose to change password/extra: ')
for n in a1.split(' '):
if n.isdecimal() and 0 < int(n) <= len(datas):
passwd = getpass.getpass('[%s]New Password: ' % n)
if len(passwd) == 0:
continue
passwd2 = getpass.getpass(
'[%s]New Password Again: ' % n)
if passwd != passwd2:
print('inconsistent password.')
continue
extra = input('[%s]Add Extra: ' % n)
idx = int(n)-1
passwd_ch_en = aes_encrypts(
passwd, random_key_cache[idx])
if len(extra) > 0:
extra_de = aes_decrypts(
datas[idx][2], random_key_cache[idx])
if len(extra_de) > 0:
extra_ch = extra_de + '\n' + extra
else:
extra_ch = extra
extra_ch_en = aes_encrypts(
extra_ch, random_key_cache[idx])
c.execute(
'update content set password=?,'
' extra=? where id=?',
(passwd_ch_en, extra_ch_en, datas[idx][3]))
else:
c.execute(
'update content set password=? where id=?',
(passwd_ch_en, datas[idx][3]))
else:
break
conn.commit()
c.close()
if a in ('exit', 'quit'):
break
def change_password():
if conn is None:
init_db()
old_passwd = get_password('Old Password: ')
c = conn.cursor()
c.execute('select verify_key, name_lock from verify where id=0')
v = c.fetchone()
if v:
old_key = hashlib.sha256(old_passwd.encode('utf-8')).digest()
dec = aes_decrypts(v[0], old_key, True)
if not veri_sign(dec):
print('incorrect password.')
return
new_passwd = get_password('New Password: ')
new_passwd2 = get_password('New Password Again: ')
if len(new_passwd) == 0 or new_passwd != new_passwd2:
print('inconsistent password.')
return
new_key = hashlib.sha256(new_passwd.encode('utf-8')).digest()
enc = aes_encrypts(dec, new_key, True)
enc2 = aes_encrypts(aes_decrypts(v[1], old_key, True),
new_key, True)
c.execute('select id, random_key from content')
rows = c.fetchall()
rencs = []
for row in rows:
random_key_de = aes_decrypts(row[1], old_key, True)
rencs.append((aes_encrypts(random_key_de, new_key, True),
row[0]))
c.execute('update verify set verify_key=?, name_lock=? where id=0',
(enc, enc2))
c.executemany('update content set random_key=? where id=?', rencs)
conn.commit()
else:
print('database error.')
c.close()
def main():
while True:
try:
a = input('>> ')
except KeyboardInterrupt:
print('\nBye.')
break
if len(a) == 0:
continue
try:
if a == 'add':
if require_key():
add_mode()
Key.set(None)
elif a == 'view':
if require_key():
view_mode()
Key.set(None)
elif a == 'remove':
if require_key():
remove_mode()
Key.set(None)
elif a == 'change':
if require_key():
change_mode()
Key.set(None)
elif a == 'passwd':
change_password()
elif a == 'help':
print('Usage:\tadd | view | remove |'
' change | passwd')
print('Then:\tlist | name | info')
elif a in ('quit', 'exit'):
raise SystemExit
except SystemExit:
print('Bye.')
break
except KeyboardInterrupt:
Key.set(None)
print('')
if __name__ == '__main__':
print('Welcome to MySecure !')
main() | 0.241042 | 0.056159 |
from typing import Dict, List, Optional, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = [
"build_act",
"ConvLayer",
"LinearLayer",
"SELayer",
"DsConvLayer",
"InvertedBlock",
"SeInvertedBlock",
"ResidualBlock",
"OpSequential",
]
def build_norm(name: Optional[str], num_features: int) -> Optional[nn.Module]:
if name is None:
return None
elif name == "bn_2d":
return nn.BatchNorm2d(num_features)
else:
raise NotImplementedError
def build_act(name: Union[str, nn.Module, None]) -> Optional[nn.Module]:
if name is None:
return None
elif isinstance(name, nn.Module):
return name
elif name == "relu":
return nn.ReLU(inplace=True)
elif name == "relu6":
return nn.ReLU6(inplace=True)
elif name == "h_swish":
return nn.Hardswish(inplace=True)
elif name == "h_sigmoid":
return nn.Hardsigmoid(inplace=True)
else:
raise NotImplementedError
class ConvLayer(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size=3,
stride=1,
dilation=1,
groups=1,
use_bias=False,
norm="bn_2d",
act_func="relu",
):
super(ConvLayer, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.dilation = dilation
self.groups = groups
padding = kernel_size // 2
padding *= dilation
self.conv = nn.Conv2d(
in_channels,
out_channels,
kernel_size=(kernel_size, kernel_size),
stride=(stride, stride),
padding=padding,
dilation=(dilation, dilation),
groups=groups,
bias=use_bias,
)
self.norm = build_norm(norm, num_features=out_channels)
self.act = build_act(act_func)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv(x)
if self.norm:
x = self.norm(x)
if self.act:
x = self.act(x)
return x
class LinearLayer(nn.Module):
def __init__(
self,
in_features: int,
out_features: int,
use_bias=True,
dropout_rate=0,
norm=None,
act_func=None,
):
super(LinearLayer, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.dropout = (
nn.Dropout(dropout_rate, inplace=False) if dropout_rate > 0 else None
)
self.linear = nn.Linear(in_features, out_features, use_bias)
self.norm = build_norm(norm, num_features=out_features)
self.act = build_act(act_func)
def _try_squeeze(self, x: torch.Tensor) -> torch.Tensor:
if x.dim() > 2:
for i in range(x.dim() - 1, 1, -1):
x = torch.squeeze(x, dim=i)
return x
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self._try_squeeze(x)
if self.dropout:
x = self.dropout(x)
x = self.linear(x)
if self.norm:
x = self.norm(x)
if self.act:
x = self.act(x)
return x
class SELayer(nn.Module):
def __init__(
self,
in_channels: int,
mid_channels=None,
reduction=4,
min_dim=16,
act_func="relu",
):
super(SELayer, self).__init__()
self.in_channels = in_channels
self.mid_channels = mid_channels or max(round(in_channels / reduction), min_dim)
self.reduction = self.in_channels / self.mid_channels + 1e-10
self.min_dim = min_dim
self.pooling = nn.AdaptiveAvgPool2d(1)
self.reduce_conv = nn.Conv2d(
in_channels, self.mid_channels, kernel_size=(1, 1), bias=True
)
self.act = build_act(act_func)
self.expand_conv = nn.Conv2d(
self.mid_channels, in_channels, kernel_size=(1, 1), bias=True
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
channel_attention = self.pooling(x)
channel_attention = self.reduce_conv(channel_attention)
channel_attention = self.act(channel_attention)
channel_attention = self.expand_conv(channel_attention)
channel_attention = F.hardsigmoid(channel_attention, inplace=True)
return x * channel_attention
class DsConvLayer(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size=3,
stride=1,
act_func=("relu6", None),
norm=("bn_2d", "bn_2d"),
):
super(DsConvLayer, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.depth_conv = ConvLayer(
in_channels,
in_channels,
kernel_size,
stride,
groups=in_channels,
norm=norm[0],
act_func=act_func[0],
)
self.point_conv = ConvLayer(
in_channels,
out_channels,
1,
norm=norm[1],
act_func=act_func[1],
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.depth_conv(x)
x = self.point_conv(x)
return x
class InvertedBlock(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size=3,
stride=1,
mid_channels=None,
expand_ratio=6,
act_func=("relu6", "relu6", None),
norm=("bn_2d", "bn_2d", "bn_2d"),
):
super(InvertedBlock, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.mid_channels = mid_channels or round(in_channels * expand_ratio)
self.expand_ratio = self.mid_channels / self.in_channels + 1e-10
self.inverted_conv = ConvLayer(
in_channels,
self.mid_channels,
1,
norm=norm[0],
act_func=act_func[0],
)
self.depth_conv = ConvLayer(
self.mid_channels,
self.mid_channels,
kernel_size,
stride,
groups=self.mid_channels,
norm=norm[1],
act_func=act_func[1],
)
self.point_conv = ConvLayer(
self.mid_channels,
out_channels,
1,
norm=norm[2],
act_func=act_func[2],
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.inverted_conv(x)
x = self.depth_conv(x)
x = self.point_conv(x)
return x
class SeInvertedBlock(InvertedBlock):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size=3,
stride=1,
mid_channels=None,
expand_ratio=6,
act_func=("relu6", "relu6", None),
norm=("bn_2d", "bn_2d", "bn_2d"),
se_config: Optional[Dict] = None,
):
super(SeInvertedBlock, self).__init__(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
mid_channels=mid_channels,
expand_ratio=expand_ratio,
act_func=act_func,
norm=norm,
)
se_config = se_config or {
"reduction": 4,
"min_dim": 16,
"act_func": "relu",
}
self.se_layer = SELayer(self.depth_conv.out_channels, **se_config)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.inverted_conv(x)
x = self.depth_conv(x)
x = self.se_layer(x)
x = self.point_conv(x)
return x
class ResidualBlock(nn.Module):
def __init__(self, conv: Optional[nn.Module], shortcut: Optional[nn.Module]):
super(ResidualBlock, self).__init__()
self.conv = conv
self.shortcut = shortcut
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.conv is None:
return x
elif self.shortcut is None:
return self.conv(x)
else:
return self.conv(x) + self.shortcut(x)
class OpSequential(nn.Module):
def __init__(self, op_list: List[Optional[nn.Module]]):
super(OpSequential, self).__init__()
valid_op_list = []
for op in op_list:
if op is not None:
valid_op_list.append(op)
self.op_list = nn.ModuleList(valid_op_list)
def forward(self, x: torch.Tensor) -> torch.Tensor:
for op in self.op_list:
x = op(x)
return x | netaug/models/base/layers.py | from typing import Dict, List, Optional, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = [
"build_act",
"ConvLayer",
"LinearLayer",
"SELayer",
"DsConvLayer",
"InvertedBlock",
"SeInvertedBlock",
"ResidualBlock",
"OpSequential",
]
def build_norm(name: Optional[str], num_features: int) -> Optional[nn.Module]:
if name is None:
return None
elif name == "bn_2d":
return nn.BatchNorm2d(num_features)
else:
raise NotImplementedError
def build_act(name: Union[str, nn.Module, None]) -> Optional[nn.Module]:
if name is None:
return None
elif isinstance(name, nn.Module):
return name
elif name == "relu":
return nn.ReLU(inplace=True)
elif name == "relu6":
return nn.ReLU6(inplace=True)
elif name == "h_swish":
return nn.Hardswish(inplace=True)
elif name == "h_sigmoid":
return nn.Hardsigmoid(inplace=True)
else:
raise NotImplementedError
class ConvLayer(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size=3,
stride=1,
dilation=1,
groups=1,
use_bias=False,
norm="bn_2d",
act_func="relu",
):
super(ConvLayer, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.dilation = dilation
self.groups = groups
padding = kernel_size // 2
padding *= dilation
self.conv = nn.Conv2d(
in_channels,
out_channels,
kernel_size=(kernel_size, kernel_size),
stride=(stride, stride),
padding=padding,
dilation=(dilation, dilation),
groups=groups,
bias=use_bias,
)
self.norm = build_norm(norm, num_features=out_channels)
self.act = build_act(act_func)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv(x)
if self.norm:
x = self.norm(x)
if self.act:
x = self.act(x)
return x
class LinearLayer(nn.Module):
def __init__(
self,
in_features: int,
out_features: int,
use_bias=True,
dropout_rate=0,
norm=None,
act_func=None,
):
super(LinearLayer, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.dropout = (
nn.Dropout(dropout_rate, inplace=False) if dropout_rate > 0 else None
)
self.linear = nn.Linear(in_features, out_features, use_bias)
self.norm = build_norm(norm, num_features=out_features)
self.act = build_act(act_func)
def _try_squeeze(self, x: torch.Tensor) -> torch.Tensor:
if x.dim() > 2:
for i in range(x.dim() - 1, 1, -1):
x = torch.squeeze(x, dim=i)
return x
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self._try_squeeze(x)
if self.dropout:
x = self.dropout(x)
x = self.linear(x)
if self.norm:
x = self.norm(x)
if self.act:
x = self.act(x)
return x
class SELayer(nn.Module):
def __init__(
self,
in_channels: int,
mid_channels=None,
reduction=4,
min_dim=16,
act_func="relu",
):
super(SELayer, self).__init__()
self.in_channels = in_channels
self.mid_channels = mid_channels or max(round(in_channels / reduction), min_dim)
self.reduction = self.in_channels / self.mid_channels + 1e-10
self.min_dim = min_dim
self.pooling = nn.AdaptiveAvgPool2d(1)
self.reduce_conv = nn.Conv2d(
in_channels, self.mid_channels, kernel_size=(1, 1), bias=True
)
self.act = build_act(act_func)
self.expand_conv = nn.Conv2d(
self.mid_channels, in_channels, kernel_size=(1, 1), bias=True
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
channel_attention = self.pooling(x)
channel_attention = self.reduce_conv(channel_attention)
channel_attention = self.act(channel_attention)
channel_attention = self.expand_conv(channel_attention)
channel_attention = F.hardsigmoid(channel_attention, inplace=True)
return x * channel_attention
class DsConvLayer(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size=3,
stride=1,
act_func=("relu6", None),
norm=("bn_2d", "bn_2d"),
):
super(DsConvLayer, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.depth_conv = ConvLayer(
in_channels,
in_channels,
kernel_size,
stride,
groups=in_channels,
norm=norm[0],
act_func=act_func[0],
)
self.point_conv = ConvLayer(
in_channels,
out_channels,
1,
norm=norm[1],
act_func=act_func[1],
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.depth_conv(x)
x = self.point_conv(x)
return x
class InvertedBlock(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size=3,
stride=1,
mid_channels=None,
expand_ratio=6,
act_func=("relu6", "relu6", None),
norm=("bn_2d", "bn_2d", "bn_2d"),
):
super(InvertedBlock, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.mid_channels = mid_channels or round(in_channels * expand_ratio)
self.expand_ratio = self.mid_channels / self.in_channels + 1e-10
self.inverted_conv = ConvLayer(
in_channels,
self.mid_channels,
1,
norm=norm[0],
act_func=act_func[0],
)
self.depth_conv = ConvLayer(
self.mid_channels,
self.mid_channels,
kernel_size,
stride,
groups=self.mid_channels,
norm=norm[1],
act_func=act_func[1],
)
self.point_conv = ConvLayer(
self.mid_channels,
out_channels,
1,
norm=norm[2],
act_func=act_func[2],
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.inverted_conv(x)
x = self.depth_conv(x)
x = self.point_conv(x)
return x
class SeInvertedBlock(InvertedBlock):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size=3,
stride=1,
mid_channels=None,
expand_ratio=6,
act_func=("relu6", "relu6", None),
norm=("bn_2d", "bn_2d", "bn_2d"),
se_config: Optional[Dict] = None,
):
super(SeInvertedBlock, self).__init__(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=stride,
mid_channels=mid_channels,
expand_ratio=expand_ratio,
act_func=act_func,
norm=norm,
)
se_config = se_config or {
"reduction": 4,
"min_dim": 16,
"act_func": "relu",
}
self.se_layer = SELayer(self.depth_conv.out_channels, **se_config)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.inverted_conv(x)
x = self.depth_conv(x)
x = self.se_layer(x)
x = self.point_conv(x)
return x
class ResidualBlock(nn.Module):
def __init__(self, conv: Optional[nn.Module], shortcut: Optional[nn.Module]):
super(ResidualBlock, self).__init__()
self.conv = conv
self.shortcut = shortcut
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.conv is None:
return x
elif self.shortcut is None:
return self.conv(x)
else:
return self.conv(x) + self.shortcut(x)
class OpSequential(nn.Module):
def __init__(self, op_list: List[Optional[nn.Module]]):
super(OpSequential, self).__init__()
valid_op_list = []
for op in op_list:
if op is not None:
valid_op_list.append(op)
self.op_list = nn.ModuleList(valid_op_list)
def forward(self, x: torch.Tensor) -> torch.Tensor:
for op in self.op_list:
x = op(x)
return x | 0.967271 | 0.409044 |
import os
import sys
import csv
import re
from math import ceil
from typing import Union
import pandas as pd
import dask.dataframe as dd
import argparse
from timeit import default_timer as timer
from enum import Enum
from PIL import Image
from pathlib import Path
from collections import namedtuple
from misc import resize_keep_aspect, decode_int_or_tuple
MIN_PYTHON = (3, 6)
if sys.version_info < MIN_PYTHON:
sys.exit("Python %s.%s or later is required.\n" % MIN_PYTHON)
class Df(Enum):
PANDAS = 1
DASK = 2
def save_list(filepath, save_lst):
"""
Save a list to file
:param filepath: File to as as
:param save_lst: List to save
:return:
"""
print(f"Saving '{filepath}'")
with open(filepath, mode='w') as fh:
fh.writelines(f"{entry}\n" for entry in save_lst)
def load_list(filepath):
"""
Load a list from file
:param filepath: File to load list from
:return:
"""
print(f"Loading '{filepath}'")
with open(filepath, 'r') as fh:
lst = [current_line.rstrip() for current_line in fh.readlines()]
return lst
def check_parent(parent, alias, parent_aliases, exclude_lst):
"""
Check if alias is equal to parent or a sub-alias
:param parent: parent alias to check for
:param alias: alias
:param parent_aliases: parent aliases
:param exclude_lst:
:return: True or False
"""
candidate = (alias == parent or parent in parent_aliases)
if candidate:
candidate = (alias not in exclude_lst)
return candidate
def verify_path(path, typ='file', create_dir=False):
exists = os.path.exists(path)
if typ == 'folder':
if not exists and create_dir:
Path(path).mkdir(parents=True, exist_ok=True)
exists = True
valid = os.path.isdir(path)
elif typ == 'file':
valid = os.path.isfile(path)
else:
raise ValueError(f"Unrecognised 'typ' argument: {typ}")
if not exists:
error(f"'{path}' does not exist")
if not valid:
error(f"'{path}' is not a {typ}")
return exists and valid
def get_categories(category_path, parent_category, exclude_str, save_cats_path, verbose):
"""
Process the categories file to get a list of all sub-categories of the specified parent
:param category_path: Path to categories json file
:param parent_category: Parent category
:param exclude_str: Comma separated string of categories to exclude
:param save_cats_path: File to save category list to
:param verbose: Verbose mode flag
:return: List of categories
"""
print(f"Retrieving sub-categories of '{parent_category}' from '{category_path}'")
# read business categories
# e.g. {
# "alias": "burgers",
# "title": "Burgers",
# "parent_aliases": [
# "restaurants"
# ],
# "country_whitelist": [],
# "country_blacklist": []
# },
cat_df = pd.read_json(category_path)
excludes = []
if exclude_str is not None:
if len(exclude_str) > 0:
excludes = exclude_str.split(',')
# set 'req' column; true for aliases with parent_category as parent
cat_df['req'] = cat_df['categories'].apply(
lambda lst: check_parent(parent_category, lst['alias'], lst['parent_aliases'], excludes))
# get just the alias
req_cats_df = cat_df[cat_df['req']]['categories'].apply(lambda lst: lst['title'])
req_cats_lst = req_cats_df.to_list()
print(f"{len(req_cats_lst)} sub-categories identified")
if len(req_cats_lst) == 0:
print(f"Please verify '{parent_category}' is a valid alias")
elif verbose:
print(f"{req_cats_lst}")
if save_cats_path is not None:
save_list(save_cats_path, req_cats_lst)
return req_cats_lst
def check_categories(categories_str, category_list):
"""
Check if at least one entry in category_list is in the category string
:param categories_str: Comma-separated list of categories
:param category_list: List of categories to match
:return:
"""
req = False
if isinstance(categories_str, str):
categories = categories_str.split(',')
for category in categories:
req = category.strip() in category_list
if req:
break
return req
def duration(start, verbose):
if verbose:
print(f"Duration: {timer() - start:.1f}s")
def save_csv(df, out_path, index=False):
"""
Save a Dataframe to csv
:param df: Dataframe to save
:param out_path: Path to save to
:param index: Write row names (index)
:return:
"""
if out_path is not None:
print(f"Saving {len(df)} rows to '{out_path}'")
df.to_csv(out_path, index=index)
def binary_search(arr, low, high, x):
"""
Find index of x in arr if present, else -1
Thanks to https://www.geeksforgeeks.org/python-program-for-binary-search/
:param arr: Ascending order sorted array to search
:param low: Start index (inclusive)
:param high: End index (inclusive)
:param x: Element to find
:return: index of x in arr if present, else -1
"""
# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid + 1, high, x)
else:
# Element is not present in the array
return -1
def load_csv(entity_name, csv_path, dtype=None, converters=None, out_path=None,
filter_id_column=None, filter_id_lst=None,
filter_lambda_column=None, filter_lambda=None,
entity_id_column=None,
arg_dict=None, csv_id=None):
"""
Get the entities for the specified list of business ids
:param entity_name: Name of entity being processed
:param csv_path: Path to entity csv file
:param dtype: dtypes for read_csv
:param converters: converters for read_csv
:param out_path: Path to save filtered entities to
:param filter_id_column: Name of id column to filter by
:param filter_id_lst: List of ids to filter by
:param filter_lambda_column: Name of column to apply lambda filter to
:param filter_lambda: lambda filter function
:param entity_id_column: Name of id column of the entity
:param arg_dict: keyword arguments
- 'verbose': verbose mode flag; True/False
- 'dataframe': dataframe type; Df.PANDAS/Df.DASK, default Df.PANDAS
- 'col': name of column to filter on
- 'regex': regex to filter column 'col'
- 'drop_regex': regex for columns to drop
- 'nrows': number of rows to read, (Df.PANDAS only)
- 'show_duration': display duration flag in verbose mode; True/False
:param csv_id: cvs_id of arg_dict['regex'] to use for column matching
:return:
"""
start = timer()
if arg_dict is None:
arg_dict = {}
verbose = False if 'verbose' not in arg_dict else arg_dict['verbose']
df = Df.PANDAS if 'dataframe' not in arg_dict else arg_dict['dataframe']
drop_regex = None if 'drop_regex' not in arg_dict else arg_dict['drop_regex']
limit_id = None if 'limit_id' not in arg_dict else arg_dict['limit_id']
# exclude id list flag; default False. False: accept all ids in list, True: accept all ids not in list
ex_id = False if 'ex_id' not in arg_dict else arg_dict['ex_id']
show_duration = True if 'show_duration' not in arg_dict else arg_dict['show_duration']
parse_engine = 'python' if 'parse_engine' not in arg_dict else arg_dict['parse_engine']
col = None
regex = None
if 'regex' in arg_dict and csv_id is not None:
if csv_id in arg_dict['regex']:
col = arg_dict['regex'][csv_id][0]
regex = arg_dict['regex'][csv_id][1]
do_filter_col = (col is not None and regex is not None) # do col/regex filter
do_filter_lambda = (filter_lambda_column is not None and filter_lambda is not None) # do lambda filter?
# hash ids for faster comparison
hash_id_list = None
do_filter_by_id = (filter_id_lst is not None and filter_id_column is not None) # do filter id?
if do_filter_by_id:
hash_id_list = []
for bid in filter_id_lst:
hash_id_list.append(hash(bid))
hash_id_list = sorted(hash_id_list)
if limit_id is not None:
max_count = limit_id
else:
max_count = sys.maxsize
print(f"Reading '{csv_path}'")
if verbose:
print(f"Using {df}")
parse_args = {
'dtype': dtype,
'converters': converters,
'encoding': 'utf-8',
'engine': parse_engine,
'quoting': csv.QUOTE_MINIMAL
}
try:
if df == Df.PANDAS:
if 'nrows' in arg_dict:
parse_args['nrows'] = arg_dict['nrows']
rev_df = pd.read_csv(csv_path, **parse_args)
elif df == Df.DASK:
if 'nrows' in arg_dict:
warning("-nr/--nrows not supported for Dask dataframe")
rev_df = dd.read_csv(csv_path, **parse_args)
else:
raise NotImplemented(f'Unrecognised dataframe type: {df}')
except pd.errors.ParserError:
error(f"The current max csv field size of {hex(csv.field_size_limit() // 0x1000)[2:]}kB is too small. "
f"Use the '-cs/--csv_size' option to increase the max csv field size")
rev_df = None
print(f"{len(rev_df)} {entity_name} loaded")
if do_filter_col or do_filter_lambda or do_filter_by_id or (limit_id is not None):
# filter by column value
cmts = []
if do_filter_col:
if col not in rev_df.columns:
error(f"Column '{col}' not in dataframe")
cmts.append(f"'{col}' column")
def col_val_fxn(mcol):
return True if re.search(regex, mcol) else False
else:
def col_val_fxn(mcol):
return True
if filter_lambda is not None:
cmts.append(f"'{filter_lambda_column}' column")
if do_filter_by_id is not False:
cmts.append(f"'{filter_id_column}' column, {len(hash_id_list)} possible values")
count = 0
total = len(rev_df)
if df != Df.DASK:
def inc_progress():
nonlocal count
count = progress("Row", total, count)
else:
def inc_progress():
nonlocal count
count += 1
def filter_by_id_and_col(filter_props):
if do_filter_lambda:
# filter on lambda function
ok = filter_lambda(filter_props[filter_lambda_column])
else:
ok = True
if ok:
# filter on column value
ok = col_val_fxn(None if col is None else filter_props[col])
if ok:
if do_filter_by_id:
# filter on ids
ok = (binary_search(hash_id_list, 0, len(hash_id_list) - 1,
hash(filter_props[filter_id_column])) >= 0)
if ex_id:
ok = not ok # exclude id
nonlocal max_count
if ok and max_count > 0:
max_count -= 1
else:
ok = False
inc_progress()
return ok
cmt = f"Filtering for required {entity_name}"
for cnd in cmts:
cmt += f"\n- matching {cnd}"
if max_count < sys.maxsize:
cmt += f"\n- max count {max_count}"
print(cmt)
# filter by ids
filter_col_list = [filter_id_column, col] if col is not None else [filter_id_column]
if filter_lambda_column is not None and filter_lambda is not None:
filter_col_list.append(filter_lambda_column)
if df == Df.PANDAS:
rev_df['req'] = rev_df[filter_col_list].apply(filter_by_id_and_col, axis=1)
elif df == Df.DASK:
rev_df['req'] = rev_df[filter_col_list].apply(filter_by_id_and_col, axis=1, meta=('req', 'bool'))
if df != Df.DASK:
progress("Row", total, total)
# drop columns matching the drop column regex
if drop_regex is not None:
cols_to_drop = set()
for dcol in rev_df.columns.values:
if re.search(drop_regex, dcol):
cols_to_drop.add(dcol)
if len(cols_to_drop) > 0:
print(f'Dropping {len(cols_to_drop)} unnecessary columns')
print(f'{cols_to_drop}')
rev_df = rev_df.drop(list(cols_to_drop), axis=1)
# get just the required rows
if 'req' in rev_df.columns.values:
req_rev_df = rev_df[rev_df['req']]
# drop work column
req_rev_df = req_rev_df.drop(['req'], axis=1)
else:
req_rev_df = rev_df
if entity_id_column is not None:
entity_id_lst = req_rev_df[entity_id_column].to_list()
else:
entity_id_lst = None
print(f"{len(req_rev_df)} {entity_name} identified")
save_csv(req_rev_df, out_path, index=False)
if show_duration:
duration(start, verbose)
return req_rev_df, entity_id_lst, start
def get_business(csv_path, category_list=None, out_path=None, save_ids_path=None, id_list=None, arg_dict=None,
csv_id='biz'):
"""
Process the businesses csv file to get a list of businesses with the specified categories
:param csv_path: Path to business csv file
:param category_list: List of categories to match
:param out_path: File to save filtered businesses to
:param save_ids_path: File to save business id list to
:param id_list: List of business ids
:param arg_dict: See load_csv::arg_dict
:param csv_id: cvs_id of arg_dict['regex'] to use for column matching
:return: Business id list
"""
arg_dict['show_duration'] = False
verbose = False if 'verbose' not in arg_dict else arg_dict['verbose']
# read business details
# - DtypeWarning: Columns (36,37,41,43,46,56,67,72,76,80,99) have mixed types
# most of the columns have bool mixed with missing values so use a converter to preserve the missing value
# for the moment
def bool_or_none(x):
return bool(x) if x else None
if category_list is not None:
def filter_lambda_fxn(lst):
return check_categories(lst, category_list)
filter_lambda = filter_lambda_fxn
else:
filter_lambda = None
biz_df, req_biz_id_lst, start = load_csv("businesses", csv_path, dtype={
"attributes.AgesAllowed": str, # 36
"attributes.DietaryRestrictions": str, # 41
}, converters={
"attributes.DietaryRestrictions.gluten-free": bool_or_none, # 37
"attributes.DietaryRestrictions.vegan": bool_or_none, # 43
"attributes.DietaryRestrictions.dairy-free": bool_or_none, # 46
"attributes.DietaryRestrictions.halal": bool_or_none, # 56
"attributes.DietaryRestrictions.soy-free": bool_or_none, # 67
"attributes.DietaryRestrictions.vegetarian": bool_or_none, # 72
"attributes.RestaurantsCounterService": bool_or_none, # 76
"attributes.DietaryRestrictions.kosher": bool_or_none, # 80
"attributes.Open24Hours": bool_or_none, # 99
}, filter_id_column='business_id', filter_id_lst=id_list,
filter_lambda_column='categories',
filter_lambda=filter_lambda,
entity_id_column='business_id', arg_dict=arg_dict, csv_id=csv_id)
# find root columns which are not required as values have been expanded into their own columns
# e.g. 'hours' is not required as info is in 'hours.Friday' etc.
col_to_drop = set()
for col in biz_df.columns.values:
if "." in col:
dot_splits = col.split(".")
col_name = dot_splits[0]
col_to_drop.add(col_name)
for col_idx in range(1, len(dot_splits) - 1):
col_name = col_name + '.' + dot_splits[col_idx]
col_to_drop.add(col_name)
if len(col_to_drop) > 0:
print(f'Dropping {len(col_to_drop)} unnecessary columns')
print(f'{col_to_drop}')
biz_df = biz_df.drop(list(col_to_drop), axis=1)
biz_df = biz_df.fillna('')
duration(start, verbose)
save_csv(biz_df, out_path, index=False)
if save_ids_path is not None:
save_list(save_ids_path, req_biz_id_lst)
return biz_df, req_biz_id_lst
def get_reviews(csv_path, id_lst, out_path, prefilter_path=None, arg_dict=None):
"""
Get the reviews for the specified list of business ids
:param csv_path: Path to review csv file
:param id_lst: List of business ids
:param out_path: Path to save filtered reviews to
:param prefilter_path: Path to save pre-filtered reviews to
:param arg_dict: keyword arguments
:return:
"""
load_path = csv_path
filter_id_lst = id_lst
if prefilter_path is not None:
load_path = prefilter_path # give pre-filtered input to load_csv()
filter_id_lst = None # no need to filter ids in load_csv()
biz_iz_idx = -1
# hash ids for faster comparison
hash_id_list = None
if id_lst is not None:
hash_id_list = []
for bid in id_lst:
hash_id_list.append(hash(bid))
print(f"Pre-filter {csv_path} to {prefilter_path}")
count = 0
total = 0
with open(csv_path, "r") as fhin:
with open(prefilter_path, "w") as fhout:
for line in fhin:
columns = line.strip(' \n').split(",")
if count == 0:
if "business_id" in columns:
biz_iz_idx = columns.index("business_id")
if biz_iz_idx < 0:
error("'business_id' index not found")
ok = True
else:
ok = hash(columns[biz_iz_idx]) in hash_id_list
count = progress("Row", total, count)
if ok:
fhout.write(line)
return load_csv('reviews', load_path, dtype={
"cool": object,
"funny": object,
"useful": object,
"stars": object,
}, out_path=out_path, filter_id_column='business_id', filter_id_lst=filter_id_lst,
arg_dict=arg_dict, csv_id='review')
def get_tips(csv_path, id_lst, out_path, arg_dict=None):
"""
Get the tips for the specified list of business ids
:param csv_path: Path to tip csv file
:param id_lst: List of business ids
:param out_path: Path to save filtered reviews to
:param arg_dict: keyword arguments
:return:
"""
return load_csv('tips', csv_path, dtype={
"compliment_count": object,
}, out_path=out_path, filter_id_column='business_id', filter_id_lst=id_lst, arg_dict=arg_dict, csv_id='tips')
def get_checkin(csv_path, id_lst, out_path, arg_dict=None):
"""
Get the checkin for the specified list of business ids
:param csv_path: Path to checkin csv file
:param id_lst: List of business ids
:param out_path: Path to save filtered reviews to
:param arg_dict: keyword arguments
:return:
"""
return load_csv('checkins', csv_path, out_path=out_path, filter_id_column='business_id', filter_id_lst=id_lst,
arg_dict=arg_dict)
def get_photos(csv_path, id_lst, out_path, arg_dict=None):
"""
Get the photos for the specified list of business ids
:param csv_path: Path to checkin csv file
:param id_lst: List of business ids
:param out_path: Path to save filtered photos to
:param arg_dict: keyword arguments
:return:
"""
return load_csv('photos', csv_path, out_path=out_path, filter_id_column='business_id', filter_id_lst=id_lst,
arg_dict=arg_dict, csv_id='pin')
def progress(cmt, total, current, step=100):
current += 1
if current % step == 0 or total == current:
percent = "" if total == 0 else f"({current * 100 / total:.1f}%)"
print(f"{cmt}: {current} {percent}", flush=True, end='\r' if total > current or total == 0 else '\n')
return current
def img_process(photo, extensions, photo_folder, count, total,
get_attrib=False, resize=False, size=None, resize_folder=None):
"""
Process photos
:param photo: Image name
:param extensions: List of possible extensions
:param photo_folder: Folder containing image files
:param count: Current processed count
:param total: Total number to process
:param get_attrib: Get attributes flag
:param resize: Resize image flag
:param size: Size to resize to
:param resize_folder: Folder to save resized images
:return:
"""
attrib = None
for ext in extensions:
filename = f"{photo}{ext}"
filepath = os.path.join(photo_folder, filename)
if os.path.isfile(filepath):
if get_attrib:
im = Image.open(filepath)
attrib = f"{filename},{im.format},{im.size[0]},{im.size[1]},{im.mode}"
im.close()
else:
attrib = None
if resize:
resize_keep_aspect(filepath, size, resize_folder)
count = progress("Photo", total, count)
break
if get_attrib and attrib is None:
raise ValueError(f"Unmatched photo id {photo}")
return count, attrib
def generate_photo_set(biz_path, photo_csv_path, id_lst, photo_folder, out_path, save_ids_path=None, arg_dict=None):
"""
Generate a csv for the photo dataset
:param biz_path: Path to business csv file
:param photo_csv_path: Path to photo csv file
:param id_lst: List of business ids
:param photo_folder: Path to folder containing photos
:param out_path: Path to save dataset to
:param save_ids_path: File to save business id list to
:param arg_dict: keyword arguments
:return:
"""
biz_df, _ = get_business(biz_path, id_list=id_lst, arg_dict=arg_dict, csv_id='biz_photo')
photo_df, _, _ = get_photos(photo_csv_path, id_lst, None, arg_dict=arg_dict)
# categorical representation; e.g. '1_0' represents 1.0 stars
biz_df['stars_cat'] = biz_df['stars'].apply(lambda x: str(x).replace(".", "_"))
# ordinal representation;
# e.g. [0,0,0,0,0,0,0,0,0] represents 1.0 star, [1,0,0,0,0,0,0,0,0] represents 1.5 stars etc.
star_min = biz_df['stars'].min()
max_len = ceil(((biz_df['stars'].max() - star_min) * 2)) + 1 # stars range * num of 0.5 + 1
def fill_array(x):
one_cnt = ceil((x - star_min) * 2)
return ([1] * one_cnt) + ([0] * (max_len - one_cnt))
biz_df['stars_ord'] = biz_df['stars'].apply(fill_array)
# numerical representation; e.g. 0.5 = 1, 1.0 = 2 etc.
biz_df['stars_num'] = biz_df['stars'].apply(lambda x: ceil(x * 2))
# many-to-one join, i.e many photos to one business id
biz_photo_df = pd.merge(photo_df, biz_df, on='business_id', how='outer')
# drop rows with no photo id, no photo no prediction
total = len(biz_photo_df)
biz_photo_df = biz_photo_df[~biz_photo_df['photo_id'].isna()]
if total > len(biz_photo_df):
print(f"Dropped {total - len(biz_photo_df)} businesses with no photos")
if 'random_select' in arg_dict:
sample_ctrl = {
'n': int(arg_dict['random_select']) if arg_dict['random_select'] >= 1.0 else None,
'frac': arg_dict['random_select'] if arg_dict['random_select'] < 1.0 else None
}
pre_sample_len = len(biz_photo_df)
if arg_dict['select_on'].lower() == 'all':
# do sample on all photos available
biz_photo_df = biz_photo_df.sample(**sample_ctrl, random_state=1)
print(f"Sampled {len(biz_photo_df)} from {pre_sample_len} possible photos")
else:
# do sample on unique values of specified column
# make sorted list of hashed unique samples
unique_biz_ids = pd.Series(biz_photo_df[arg_dict['select_on']].unique())
vals_to_match = sorted(unique_biz_ids.
sample(**sample_ctrl, random_state=1).apply(hash).to_list())
def is_req(row):
return binary_search(vals_to_match, 0, len(vals_to_match) - 1, hash(row)) >= 0
biz_photo_df = biz_photo_df[biz_photo_df[arg_dict['select_on']].apply(is_req)]
print(f"Sampled {len(vals_to_match)} from {len(unique_biz_ids)} "
f"possible {arg_dict['select_on']}, giving {len(biz_photo_df)} photos")
# process photos
extensions = Image.registered_extensions().keys()
count = 0
total = len(biz_photo_df)
# process photos details
print(f"Processing photo details")
resize = ('photo_folder_resize' in arg_dict and 'photo_size' in arg_dict)
if resize:
print(f" Including resizing photos to {photo_size_str(arg_dict['photo_size'])} in "
f"{arg_dict['photo_folder_resize']}")
Path(arg_dict['photo_folder_resize']).mkdir(parents=True, exist_ok=True)
def img_attrib(photo):
nonlocal count
count, attrib = img_process(photo, extensions, photo_folder, count, total, get_attrib=True, resize=True,
size=arg_dict['photo_size'], resize_folder=arg_dict['photo_folder_resize'])
return attrib
else:
def img_attrib(photo):
nonlocal count
count, attrib = img_process(photo, extensions, photo_folder, count, total, get_attrib=True)
return attrib
biz_photo_df['photo_attrib'] = biz_photo_df['photo_id'].apply(img_attrib)
biz_photo_df[['photo_file', 'format', 'width', 'height', 'mode']] = \
biz_photo_df.apply(lambda row: pd.Series(row['photo_attrib'].split(',')), axis=1, result_type='expand')
biz_photo_df['width'] = biz_photo_df['width'].astype('int32')
biz_photo_df['height'] = biz_photo_df['height'].astype('int32')
progress("Photo", len(biz_photo_df), len(biz_photo_df))
# just keep required columns
photo_set_df = biz_photo_df[['business_id', 'stars', 'stars_cat', 'stars_ord', 'stars_num', 'photo_id',
'photo_file', 'format', 'width', 'height', 'mode']]
def wh_anal(column):
lwr = column.lower()
print(f"{column}: min - {photo_set_df[lwr].min()}px, max - {photo_set_df[lwr].max()}px")
print(f"{column}: value counts - {photo_set_df[lwr].value_counts()}")
unique_vals = photo_set_df['format'].unique()
print(f"Format: {len(unique_vals)} format{'' if len(unique_vals) == 1 else 's'} - {unique_vals}")
wh_anal("Width")
wh_anal("Height")
unique_vals = photo_set_df['mode'].unique()
print(f"Mode: {len(unique_vals)} mode{'' if len(unique_vals) == 1 else 's'} - {unique_vals}")
unique_vals = photo_set_df['stars'].unique()
unique_cat_vals = photo_set_df['stars_cat'].unique()
unique_num_vals = photo_set_df['stars_num'].unique()
unique_ord_vals = set()
photo_set_df['stars_ord'].apply(lambda x: unique_ord_vals.add(tuple(x)))
print(f"Stars: {len(unique_vals)} class{'' if len(unique_vals) == 1 else 'es'} - {unique_vals}\n"
f"\t{unique_cat_vals}\n\t{unique_num_vals}\n\t{unique_ord_vals}")
if save_ids_path is not None:
save_list(save_ids_path, biz_photo_df['business_id'].unique().tolist())
save_csv(photo_set_df, out_path, index=False)
def photo_size_str(p_size: Union[int, tuple]):
if isinstance(p_size, int):
width = p_size
height = width
else:
width = p_size[0]
height = p_size[1]
return f"{width}x{height}px"
def resize_photo_set(dataset_csv_path, photo_folder, arg_dict=None):
"""
Generate a csv for the photo dataset
:param dataset_csv_path: Path to dataset csv file
:param photo_folder: Path to folder containing photos
:param arg_dict: keyword arguments
:return:
"""
photo_set_df, _, start = load_csv('photos', dataset_csv_path, arg_dict=arg_dict)
print(f"Resizing photos to {photo_size_str(arg_dict['photo_size'])} in {arg_dict['photo_folder_resize']}")
Path(arg_dict['photo_folder_resize']).mkdir(parents=True, exist_ok=True)
# process photos
extensions = Image.registered_extensions().keys()
count = 0
total = len(photo_set_df)
def img_proc(photo):
nonlocal count
count, _ = img_process(photo, extensions, photo_folder, count, total, resize=True,
size=arg_dict['photo_size'], resize_folder=arg_dict['photo_folder_resize'])
photo_set_df['photo_id'].apply(img_proc)
duration(start, verbose=False if 'verbose' not in arg_dict else arg_dict['verbose'])
def file_arg_help(descrip, target='file', action=None):
if action is None:
tail = ';'
else:
tail = f' {action};'
return f"Path to {descrip} {target}{tail} absolute or relative to 'root directory' if argument supplied"
def warning(msg):
print(f"Warning: {msg}")
def error(msg):
sys.exit(f"Error: {msg}")
def ignore_arg_warning(args_namespace, arg_lst):
for arg in arg_lst:
if arg in args_namespace:
warning(f"Ignoring '{arg}' argument")
def arg_error(arg_parser, msg):
arg_parser.print_usage()
sys.exit(msg)
def required_arg_error(arg_parser, req_arg):
arg_error(arg_parser, f"{os.path.split(sys.argv[0])[1]}: error one of the arguments {req_arg} is required")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Perform ETL on the Yelp Dataset CSV data to extract the subset of businesses/reviews etc. '
'based on a parent category',
)
parser.add_argument(
'-d', '--dir',
type=str,
help='Root directory',
default='',
)
# business csv file or business ids file
biz_group = parser.add_mutually_exclusive_group(required=False)
biz_group.add_argument('-b', '--biz', type=str, help=file_arg_help("business csv"), default='')
biz_group.add_argument('-bi', '--biz_ids', type=str, help=file_arg_help("business ids"), default='')
# review, tips, checkin & photo input csv files
for arg_tuple in [('-r', '--review', 'review'),
('-t', '--tips', 'tips'),
('-ci', '--chkin', 'checkin'),
('-pi', '--pin', 'photo'),
('-psi', '--photo_set_in', 'photo dataset')]:
parser.add_argument(
arg_tuple[0], arg_tuple[1], type=str, help=file_arg_help(f"{arg_tuple[2]} csv"), default='', required=False
)
# categories json file or categories file
cat_group = parser.add_mutually_exclusive_group(required=False)
cat_group.add_argument('-c', '--cat', type=str, help=file_arg_help("categories json"), default='')
cat_group.add_argument('-cl', '--cat_list', type=str, help=file_arg_help("category list"), default='')
# category selection
parser.add_argument('-p', '--parent', type=str, help='Parent category', default='', required=False)
parser.add_argument(
'-e', '--exclude', type=str, help='Exclude categories; a comma separated list of categories to exclude',
default='', required=False)
# output files
for arg_tuple in [('-ob', '--out_biz', 'business'),
('-opr', '--out_prefilter_review', 'review pre-filter'),
('-or', '--out_review', 'review'),
('-ot', '--out_tips', 'tips'),
('-oci', '--out_chkin', 'checkin'),
('-op', '--out_photo', 'photo'),
('-ops', '--out_photo_set', 'photo set')]:
parser.add_argument(
arg_tuple[0], arg_tuple[1], type=str, help=file_arg_help(f"{arg_tuple[2]} csv", action="to create"),
default=argparse.SUPPRESS, required=False
)
parser.add_argument('-bp', '--biz_photo', type=str, help=file_arg_help("business csv for photo dataset"),
default='') # just so as not to conflict with mutually exclusive --biz/--biz_ids arguments
for arg_tuple in [('-oc', '--out_cat', 'category list'),
('-obi', '--out_biz_id', 'business ids')]:
parser.add_argument(
arg_tuple[0], arg_tuple[1], type=str, help=file_arg_help(f"{arg_tuple[2]}", action="to create"),
default=argparse.SUPPRESS, required=False
)
# input folders
parser.add_argument('-pf', '--photo_folder', type=str, help=file_arg_help("photo", target='folder'),
default='')
# output folders
parser.add_argument('-pfr', '--photo_folder_resize', type=str,
help=file_arg_help("resized photos", target='folder'),
default='')
# miscellaneous
parser.add_argument('-dx', '--drop_regex', help='Regex for business csv columns to drop', type=str, default=None)
parser.add_argument('-mx', '--match_regex', help="Regex for csv columns to match; 'csv_id:column_name=regex'. "
"Valid 'csv_id' are; 'biz'=business csv file, "
"'pin'=photo csv file, 'tip'=tip csv file and "
"'review'=review csv file",
type=str, default=argparse.SUPPRESS, nargs='+')
parser.add_argument('-df', '--dataframe', help="Dataframe to use; 'pandas' or 'dask'",
choices=['pandas', 'dask'], required=False)
parser.add_argument('-pe', '--parse_engine', help="Parser engine to use; 'c' or 'python'}",
choices=['c', 'python'], required=False)
parser.add_argument('-nr', '--nrows', help="Number of rows to read, (Note: ignored with '-df=dask' option)",
type=int, default=argparse.SUPPRESS)
parser.add_argument('-li', '--limit_id', help="Limit number of business ids to read",
type=int, default=argparse.SUPPRESS)
parser.add_argument('-rs', '--random_select', help="Make random selection; 'value' < 1.0 = percent of total "
"available, or 'value' > 1 = number to select",
type=float, default=argparse.SUPPRESS)
parser.add_argument('-so', '--select_on', help="Column to make selection on or 'all' to select from total "
"available; e.g. 'business_id'",
type=str, default=argparse.SUPPRESS)
parser.add_argument('-cs', '--csv_size',
help=f"max csv field size in kB; default {hex(csv.field_size_limit() // 0x1000)[2:]}kB",
type=int, default=argparse.SUPPRESS)
parser.add_argument('-ps', '--photo_size',
help=f"required photo size in pixels or 'width,height'; e.g. '299' or '150,100'",
type=str, default=argparse.SUPPRESS)
parser.add_argument('-v', '--verbose', help='Verbose mode', action='store_true')
args = parser.parse_args()
if len(sys.argv) == 1:
# display help message when no args are passed.
parser.print_help()
sys.exit(1)
if args.verbose:
print(f"Arguments: {args}")
if 'csv_size' in args:
csv.field_size_limit(int(str(args.csv_size), 16) * 0x1000) # convert kB to bytes
paths = {'biz': None, 'biz_ids': None, 'biz_photo': None, 'photo_folder': None, 'photo_folder_resize': None,
'cat': None, 'cat_list': None,
'review': None, 'tips': None, 'chkin': None, 'pin': None, 'photo_set_in': None,
'out_biz': None, 'out_review': None, 'out_prefilter_review': None,
'out_tips': None, 'out_chkin': None, 'out_photo': None,
'out_photo_set': None,
'out_cat': None, 'out_biz_id': None}
IpArgDetail = namedtuple('IpArgDetail', ['name', 'value', 'typ', 'create_dir'])
ip_arg_tuples = [IpArgDetail('biz', args.biz, 'file', False), IpArgDetail('biz_ids', args.biz_ids, 'file', False),
IpArgDetail('biz_photo', args.biz_photo, 'file', False),
IpArgDetail('photo_folder', args.photo_folder, 'folder', False),
IpArgDetail('photo_folder_resize', args.photo_folder_resize, 'folder', True),
IpArgDetail('cat', args.cat, 'file', False), IpArgDetail('cat_list', args.cat_list, 'file', False)]
for arg_tuple in ip_arg_tuples:
if arg_tuple.name in args:
paths[arg_tuple.name] = arg_tuple.value
for arg_tuple in [('review', args.review),
('tips', args.tips),
('chkin', args.chkin),
('pin', args.pin),
('photo_set_in', args.photo_set_in)]:
if arg_tuple[0] in args and len(arg_tuple[1]):
paths[arg_tuple[0]] = arg_tuple[1]
for arg_tuple in [('out_biz', None if 'out_biz' not in args else args.out_biz),
('out_prefilter_review',
None if 'out_prefilter_review' not in args else args.out_prefilter_review),
('out_review', None if 'out_review' not in args else args.out_review),
('out_tips', None if 'out_tips' not in args else args.out_tips),
('out_chkin', None if 'out_chkin' not in args else args.out_chkin),
('out_photo', None if 'out_photo' not in args else args.out_photo),
('out_photo_set', None if 'out_photo_set' not in args else args.out_photo_set),
('out_cat', None if 'out_cat' not in args else args.out_cat),
('out_biz_id', None if 'out_biz_id' not in args else args.out_biz_id)]:
if arg_tuple[0] in args:
paths[arg_tuple[0]] = arg_tuple[1]
if len(args.dir) > 0:
for key, val in paths.items():
if val is not None and not os.path.isabs(val):
paths[key] = os.path.join(args.dir, val)
for arg_tuple in ip_arg_tuples:
if len(arg_tuple.value) > 0:
verify_path(paths[arg_tuple.name], typ=arg_tuple.typ, create_dir=arg_tuple.create_dir)
kwarg_dict = {'verbose': args.verbose, 'drop_regex': args.drop_regex}
if args.dataframe is not None:
kwarg_dict['dataframe'] = Df.PANDAS if args.dataframe == 'pandas' else Df.DASK
if args.parse_engine is not None:
kwarg_dict['parse_engine'] = 'c' if args.parse_engine == 'c' else 'python'
for arg_tuple in [('limit_id', None if 'limit_id' not in args else args.limit_id),
('nrows', None if 'nrows' not in args else args.nrows)]:
if arg_tuple[0] in args:
kwarg_dict[arg_tuple[0]] = arg_tuple[1]
if 'match_regex' in args:
for regex_cmd in args.match_regex:
split_file_regex = regex_cmd.split(':')
if len(split_file_regex) != 2:
arg_error(parser, f"Invalid format for -mx/--match_regex, expected 'csv_id:column_name=regex'")
splits_col_regex = split_file_regex[1].split('=')
if len(splits_col_regex) != 2:
arg_error(parser, f"Invalid format for -mx/--match_regex, expected 'csv_id:column_name=regex'")
if 'regex' not in kwarg_dict:
kwarg_dict['regex'] = {}
# csv_id [column_name, regex]
kwarg_dict['regex'][split_file_regex[0]] = splits_col_regex
if 'photo_folder_resize' in args or 'photo_size' in args:
if ('photo_size' in args and len(args.photo_folder_resize) == 0) or \
('photo_size' not in args and len(args.photo_folder_resize)):
arg_error(parser, f"Options -pfr/--photo_folder_resize and -ps/--photo_size are both required")
if 'photo_size' in args and len(args.photo_folder_resize):
photo_size = decode_int_or_tuple(args.photo_size)
if photo_size is None:
arg_error(parser, f"Invalid -ps/--photo_size option")
kwarg_dict['photo_size'] = photo_size
kwarg_dict['photo_folder_resize'] = paths['photo_folder_resize']
if 'random_select' in args or 'select_on' in args:
if (('random_select' in args and 'select_on' not in args) or
('random_select' not in args and 'select_on' in args)):
arg_error(parser, f"Options -rs/--random_select and -so/--select_on are both required")
kwarg_dict['random_select'] = args.random_select
kwarg_dict['select_on'] = args.select_on
# load categories
if len(args.cat_list) > 0:
ignore_arg_warning(args, ['out_cat', 'parent', 'exclude'])
categories_lst = load_list(paths['cat_list'])
elif len(args.cat) > 0:
categories_lst = get_categories(paths['cat'], args.parent, args.exclude, paths['out_cat'], args.verbose)
else:
categories_lst = None
# load business ids
if len(args.biz_ids) > 0:
ignore_arg_warning(args, ['out_biz', 'out_biz_id'])
biz_id_lst = load_list(paths['biz_ids'])
elif len(args.biz) > 0:
if categories_lst is None:
required_arg_error(parser, ['-c/--cat', '-cl/--cat_list'])
_, biz_id_lst = get_business(paths['biz'], category_list=categories_lst, out_path=paths['out_biz'],
save_ids_path=paths['out_biz_id'], arg_dict=kwarg_dict)
else:
biz_id_lst = None
# check have required info for filtering ops
for out_arg in ['out_review', 'out_tips', 'out_chkin', 'out_photo']:
if paths[out_arg] is not None:
if biz_id_lst is None:
required_arg_error(parser, ['-b/--biz', '-bi/--biz_ids'])
else:
break
# filter reviews
if paths['out_review'] is not None:
if 'dataframe' not in kwarg_dict:
kwarg_dict['dataframe'] = Df.DASK
get_reviews(paths['review'], biz_id_lst, paths['out_review'], paths['out_prefilter_review'],
arg_dict=kwarg_dict)
# filter tips
if paths['out_tips'] is not None:
get_tips(paths['tips'], biz_id_lst, paths['out_tips'], arg_dict=kwarg_dict)
# filter checkin
if paths['out_chkin'] is not None:
get_checkin(paths['chkin'], biz_id_lst, paths['out_chkin'], arg_dict=kwarg_dict)
# filter photo
if paths['out_photo'] is not None:
get_photos(paths['pin'], biz_id_lst, paths['out_photo'], arg_dict=kwarg_dict)
# photo dataset
if paths['out_photo_set'] is not None:
generate_photo_set(paths['biz_photo'], paths['pin'], biz_id_lst, paths['photo_folder'], paths['out_photo_set'],
save_ids_path=paths['out_biz_id'], arg_dict=kwarg_dict)
# resize photos
if paths['photo_set_in'] is not None:
resize_photo_set(paths['photo_set_in'], paths['photo_folder'], arg_dict=kwarg_dict) | etl.py | import os
import sys
import csv
import re
from math import ceil
from typing import Union
import pandas as pd
import dask.dataframe as dd
import argparse
from timeit import default_timer as timer
from enum import Enum
from PIL import Image
from pathlib import Path
from collections import namedtuple
from misc import resize_keep_aspect, decode_int_or_tuple
MIN_PYTHON = (3, 6)
if sys.version_info < MIN_PYTHON:
sys.exit("Python %s.%s or later is required.\n" % MIN_PYTHON)
class Df(Enum):
PANDAS = 1
DASK = 2
def save_list(filepath, save_lst):
"""
Save a list to file
:param filepath: File to as as
:param save_lst: List to save
:return:
"""
print(f"Saving '{filepath}'")
with open(filepath, mode='w') as fh:
fh.writelines(f"{entry}\n" for entry in save_lst)
def load_list(filepath):
"""
Load a list from file
:param filepath: File to load list from
:return:
"""
print(f"Loading '{filepath}'")
with open(filepath, 'r') as fh:
lst = [current_line.rstrip() for current_line in fh.readlines()]
return lst
def check_parent(parent, alias, parent_aliases, exclude_lst):
"""
Check if alias is equal to parent or a sub-alias
:param parent: parent alias to check for
:param alias: alias
:param parent_aliases: parent aliases
:param exclude_lst:
:return: True or False
"""
candidate = (alias == parent or parent in parent_aliases)
if candidate:
candidate = (alias not in exclude_lst)
return candidate
def verify_path(path, typ='file', create_dir=False):
exists = os.path.exists(path)
if typ == 'folder':
if not exists and create_dir:
Path(path).mkdir(parents=True, exist_ok=True)
exists = True
valid = os.path.isdir(path)
elif typ == 'file':
valid = os.path.isfile(path)
else:
raise ValueError(f"Unrecognised 'typ' argument: {typ}")
if not exists:
error(f"'{path}' does not exist")
if not valid:
error(f"'{path}' is not a {typ}")
return exists and valid
def get_categories(category_path, parent_category, exclude_str, save_cats_path, verbose):
"""
Process the categories file to get a list of all sub-categories of the specified parent
:param category_path: Path to categories json file
:param parent_category: Parent category
:param exclude_str: Comma separated string of categories to exclude
:param save_cats_path: File to save category list to
:param verbose: Verbose mode flag
:return: List of categories
"""
print(f"Retrieving sub-categories of '{parent_category}' from '{category_path}'")
# read business categories
# e.g. {
# "alias": "burgers",
# "title": "Burgers",
# "parent_aliases": [
# "restaurants"
# ],
# "country_whitelist": [],
# "country_blacklist": []
# },
cat_df = pd.read_json(category_path)
excludes = []
if exclude_str is not None:
if len(exclude_str) > 0:
excludes = exclude_str.split(',')
# set 'req' column; true for aliases with parent_category as parent
cat_df['req'] = cat_df['categories'].apply(
lambda lst: check_parent(parent_category, lst['alias'], lst['parent_aliases'], excludes))
# get just the alias
req_cats_df = cat_df[cat_df['req']]['categories'].apply(lambda lst: lst['title'])
req_cats_lst = req_cats_df.to_list()
print(f"{len(req_cats_lst)} sub-categories identified")
if len(req_cats_lst) == 0:
print(f"Please verify '{parent_category}' is a valid alias")
elif verbose:
print(f"{req_cats_lst}")
if save_cats_path is not None:
save_list(save_cats_path, req_cats_lst)
return req_cats_lst
def check_categories(categories_str, category_list):
"""
Check if at least one entry in category_list is in the category string
:param categories_str: Comma-separated list of categories
:param category_list: List of categories to match
:return:
"""
req = False
if isinstance(categories_str, str):
categories = categories_str.split(',')
for category in categories:
req = category.strip() in category_list
if req:
break
return req
def duration(start, verbose):
if verbose:
print(f"Duration: {timer() - start:.1f}s")
def save_csv(df, out_path, index=False):
"""
Save a Dataframe to csv
:param df: Dataframe to save
:param out_path: Path to save to
:param index: Write row names (index)
:return:
"""
if out_path is not None:
print(f"Saving {len(df)} rows to '{out_path}'")
df.to_csv(out_path, index=index)
def binary_search(arr, low, high, x):
"""
Find index of x in arr if present, else -1
Thanks to https://www.geeksforgeeks.org/python-program-for-binary-search/
:param arr: Ascending order sorted array to search
:param low: Start index (inclusive)
:param high: End index (inclusive)
:param x: Element to find
:return: index of x in arr if present, else -1
"""
# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it can only be present in left subarray
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
# Else the element can only be present in right subarray
else:
return binary_search(arr, mid + 1, high, x)
else:
# Element is not present in the array
return -1
def load_csv(entity_name, csv_path, dtype=None, converters=None, out_path=None,
filter_id_column=None, filter_id_lst=None,
filter_lambda_column=None, filter_lambda=None,
entity_id_column=None,
arg_dict=None, csv_id=None):
"""
Get the entities for the specified list of business ids
:param entity_name: Name of entity being processed
:param csv_path: Path to entity csv file
:param dtype: dtypes for read_csv
:param converters: converters for read_csv
:param out_path: Path to save filtered entities to
:param filter_id_column: Name of id column to filter by
:param filter_id_lst: List of ids to filter by
:param filter_lambda_column: Name of column to apply lambda filter to
:param filter_lambda: lambda filter function
:param entity_id_column: Name of id column of the entity
:param arg_dict: keyword arguments
- 'verbose': verbose mode flag; True/False
- 'dataframe': dataframe type; Df.PANDAS/Df.DASK, default Df.PANDAS
- 'col': name of column to filter on
- 'regex': regex to filter column 'col'
- 'drop_regex': regex for columns to drop
- 'nrows': number of rows to read, (Df.PANDAS only)
- 'show_duration': display duration flag in verbose mode; True/False
:param csv_id: cvs_id of arg_dict['regex'] to use for column matching
:return:
"""
start = timer()
if arg_dict is None:
arg_dict = {}
verbose = False if 'verbose' not in arg_dict else arg_dict['verbose']
df = Df.PANDAS if 'dataframe' not in arg_dict else arg_dict['dataframe']
drop_regex = None if 'drop_regex' not in arg_dict else arg_dict['drop_regex']
limit_id = None if 'limit_id' not in arg_dict else arg_dict['limit_id']
# exclude id list flag; default False. False: accept all ids in list, True: accept all ids not in list
ex_id = False if 'ex_id' not in arg_dict else arg_dict['ex_id']
show_duration = True if 'show_duration' not in arg_dict else arg_dict['show_duration']
parse_engine = 'python' if 'parse_engine' not in arg_dict else arg_dict['parse_engine']
col = None
regex = None
if 'regex' in arg_dict and csv_id is not None:
if csv_id in arg_dict['regex']:
col = arg_dict['regex'][csv_id][0]
regex = arg_dict['regex'][csv_id][1]
do_filter_col = (col is not None and regex is not None) # do col/regex filter
do_filter_lambda = (filter_lambda_column is not None and filter_lambda is not None) # do lambda filter?
# hash ids for faster comparison
hash_id_list = None
do_filter_by_id = (filter_id_lst is not None and filter_id_column is not None) # do filter id?
if do_filter_by_id:
hash_id_list = []
for bid in filter_id_lst:
hash_id_list.append(hash(bid))
hash_id_list = sorted(hash_id_list)
if limit_id is not None:
max_count = limit_id
else:
max_count = sys.maxsize
print(f"Reading '{csv_path}'")
if verbose:
print(f"Using {df}")
parse_args = {
'dtype': dtype,
'converters': converters,
'encoding': 'utf-8',
'engine': parse_engine,
'quoting': csv.QUOTE_MINIMAL
}
try:
if df == Df.PANDAS:
if 'nrows' in arg_dict:
parse_args['nrows'] = arg_dict['nrows']
rev_df = pd.read_csv(csv_path, **parse_args)
elif df == Df.DASK:
if 'nrows' in arg_dict:
warning("-nr/--nrows not supported for Dask dataframe")
rev_df = dd.read_csv(csv_path, **parse_args)
else:
raise NotImplemented(f'Unrecognised dataframe type: {df}')
except pd.errors.ParserError:
error(f"The current max csv field size of {hex(csv.field_size_limit() // 0x1000)[2:]}kB is too small. "
f"Use the '-cs/--csv_size' option to increase the max csv field size")
rev_df = None
print(f"{len(rev_df)} {entity_name} loaded")
if do_filter_col or do_filter_lambda or do_filter_by_id or (limit_id is not None):
# filter by column value
cmts = []
if do_filter_col:
if col not in rev_df.columns:
error(f"Column '{col}' not in dataframe")
cmts.append(f"'{col}' column")
def col_val_fxn(mcol):
return True if re.search(regex, mcol) else False
else:
def col_val_fxn(mcol):
return True
if filter_lambda is not None:
cmts.append(f"'{filter_lambda_column}' column")
if do_filter_by_id is not False:
cmts.append(f"'{filter_id_column}' column, {len(hash_id_list)} possible values")
count = 0
total = len(rev_df)
if df != Df.DASK:
def inc_progress():
nonlocal count
count = progress("Row", total, count)
else:
def inc_progress():
nonlocal count
count += 1
def filter_by_id_and_col(filter_props):
if do_filter_lambda:
# filter on lambda function
ok = filter_lambda(filter_props[filter_lambda_column])
else:
ok = True
if ok:
# filter on column value
ok = col_val_fxn(None if col is None else filter_props[col])
if ok:
if do_filter_by_id:
# filter on ids
ok = (binary_search(hash_id_list, 0, len(hash_id_list) - 1,
hash(filter_props[filter_id_column])) >= 0)
if ex_id:
ok = not ok # exclude id
nonlocal max_count
if ok and max_count > 0:
max_count -= 1
else:
ok = False
inc_progress()
return ok
cmt = f"Filtering for required {entity_name}"
for cnd in cmts:
cmt += f"\n- matching {cnd}"
if max_count < sys.maxsize:
cmt += f"\n- max count {max_count}"
print(cmt)
# filter by ids
filter_col_list = [filter_id_column, col] if col is not None else [filter_id_column]
if filter_lambda_column is not None and filter_lambda is not None:
filter_col_list.append(filter_lambda_column)
if df == Df.PANDAS:
rev_df['req'] = rev_df[filter_col_list].apply(filter_by_id_and_col, axis=1)
elif df == Df.DASK:
rev_df['req'] = rev_df[filter_col_list].apply(filter_by_id_and_col, axis=1, meta=('req', 'bool'))
if df != Df.DASK:
progress("Row", total, total)
# drop columns matching the drop column regex
if drop_regex is not None:
cols_to_drop = set()
for dcol in rev_df.columns.values:
if re.search(drop_regex, dcol):
cols_to_drop.add(dcol)
if len(cols_to_drop) > 0:
print(f'Dropping {len(cols_to_drop)} unnecessary columns')
print(f'{cols_to_drop}')
rev_df = rev_df.drop(list(cols_to_drop), axis=1)
# get just the required rows
if 'req' in rev_df.columns.values:
req_rev_df = rev_df[rev_df['req']]
# drop work column
req_rev_df = req_rev_df.drop(['req'], axis=1)
else:
req_rev_df = rev_df
if entity_id_column is not None:
entity_id_lst = req_rev_df[entity_id_column].to_list()
else:
entity_id_lst = None
print(f"{len(req_rev_df)} {entity_name} identified")
save_csv(req_rev_df, out_path, index=False)
if show_duration:
duration(start, verbose)
return req_rev_df, entity_id_lst, start
def get_business(csv_path, category_list=None, out_path=None, save_ids_path=None, id_list=None, arg_dict=None,
csv_id='biz'):
"""
Process the businesses csv file to get a list of businesses with the specified categories
:param csv_path: Path to business csv file
:param category_list: List of categories to match
:param out_path: File to save filtered businesses to
:param save_ids_path: File to save business id list to
:param id_list: List of business ids
:param arg_dict: See load_csv::arg_dict
:param csv_id: cvs_id of arg_dict['regex'] to use for column matching
:return: Business id list
"""
arg_dict['show_duration'] = False
verbose = False if 'verbose' not in arg_dict else arg_dict['verbose']
# read business details
# - DtypeWarning: Columns (36,37,41,43,46,56,67,72,76,80,99) have mixed types
# most of the columns have bool mixed with missing values so use a converter to preserve the missing value
# for the moment
def bool_or_none(x):
return bool(x) if x else None
if category_list is not None:
def filter_lambda_fxn(lst):
return check_categories(lst, category_list)
filter_lambda = filter_lambda_fxn
else:
filter_lambda = None
biz_df, req_biz_id_lst, start = load_csv("businesses", csv_path, dtype={
"attributes.AgesAllowed": str, # 36
"attributes.DietaryRestrictions": str, # 41
}, converters={
"attributes.DietaryRestrictions.gluten-free": bool_or_none, # 37
"attributes.DietaryRestrictions.vegan": bool_or_none, # 43
"attributes.DietaryRestrictions.dairy-free": bool_or_none, # 46
"attributes.DietaryRestrictions.halal": bool_or_none, # 56
"attributes.DietaryRestrictions.soy-free": bool_or_none, # 67
"attributes.DietaryRestrictions.vegetarian": bool_or_none, # 72
"attributes.RestaurantsCounterService": bool_or_none, # 76
"attributes.DietaryRestrictions.kosher": bool_or_none, # 80
"attributes.Open24Hours": bool_or_none, # 99
}, filter_id_column='business_id', filter_id_lst=id_list,
filter_lambda_column='categories',
filter_lambda=filter_lambda,
entity_id_column='business_id', arg_dict=arg_dict, csv_id=csv_id)
# find root columns which are not required as values have been expanded into their own columns
# e.g. 'hours' is not required as info is in 'hours.Friday' etc.
col_to_drop = set()
for col in biz_df.columns.values:
if "." in col:
dot_splits = col.split(".")
col_name = dot_splits[0]
col_to_drop.add(col_name)
for col_idx in range(1, len(dot_splits) - 1):
col_name = col_name + '.' + dot_splits[col_idx]
col_to_drop.add(col_name)
if len(col_to_drop) > 0:
print(f'Dropping {len(col_to_drop)} unnecessary columns')
print(f'{col_to_drop}')
biz_df = biz_df.drop(list(col_to_drop), axis=1)
biz_df = biz_df.fillna('')
duration(start, verbose)
save_csv(biz_df, out_path, index=False)
if save_ids_path is not None:
save_list(save_ids_path, req_biz_id_lst)
return biz_df, req_biz_id_lst
def get_reviews(csv_path, id_lst, out_path, prefilter_path=None, arg_dict=None):
"""
Get the reviews for the specified list of business ids
:param csv_path: Path to review csv file
:param id_lst: List of business ids
:param out_path: Path to save filtered reviews to
:param prefilter_path: Path to save pre-filtered reviews to
:param arg_dict: keyword arguments
:return:
"""
load_path = csv_path
filter_id_lst = id_lst
if prefilter_path is not None:
load_path = prefilter_path # give pre-filtered input to load_csv()
filter_id_lst = None # no need to filter ids in load_csv()
biz_iz_idx = -1
# hash ids for faster comparison
hash_id_list = None
if id_lst is not None:
hash_id_list = []
for bid in id_lst:
hash_id_list.append(hash(bid))
print(f"Pre-filter {csv_path} to {prefilter_path}")
count = 0
total = 0
with open(csv_path, "r") as fhin:
with open(prefilter_path, "w") as fhout:
for line in fhin:
columns = line.strip(' \n').split(",")
if count == 0:
if "business_id" in columns:
biz_iz_idx = columns.index("business_id")
if biz_iz_idx < 0:
error("'business_id' index not found")
ok = True
else:
ok = hash(columns[biz_iz_idx]) in hash_id_list
count = progress("Row", total, count)
if ok:
fhout.write(line)
return load_csv('reviews', load_path, dtype={
"cool": object,
"funny": object,
"useful": object,
"stars": object,
}, out_path=out_path, filter_id_column='business_id', filter_id_lst=filter_id_lst,
arg_dict=arg_dict, csv_id='review')
def get_tips(csv_path, id_lst, out_path, arg_dict=None):
"""
Get the tips for the specified list of business ids
:param csv_path: Path to tip csv file
:param id_lst: List of business ids
:param out_path: Path to save filtered reviews to
:param arg_dict: keyword arguments
:return:
"""
return load_csv('tips', csv_path, dtype={
"compliment_count": object,
}, out_path=out_path, filter_id_column='business_id', filter_id_lst=id_lst, arg_dict=arg_dict, csv_id='tips')
def get_checkin(csv_path, id_lst, out_path, arg_dict=None):
"""
Get the checkin for the specified list of business ids
:param csv_path: Path to checkin csv file
:param id_lst: List of business ids
:param out_path: Path to save filtered reviews to
:param arg_dict: keyword arguments
:return:
"""
return load_csv('checkins', csv_path, out_path=out_path, filter_id_column='business_id', filter_id_lst=id_lst,
arg_dict=arg_dict)
def get_photos(csv_path, id_lst, out_path, arg_dict=None):
"""
Get the photos for the specified list of business ids
:param csv_path: Path to checkin csv file
:param id_lst: List of business ids
:param out_path: Path to save filtered photos to
:param arg_dict: keyword arguments
:return:
"""
return load_csv('photos', csv_path, out_path=out_path, filter_id_column='business_id', filter_id_lst=id_lst,
arg_dict=arg_dict, csv_id='pin')
def progress(cmt, total, current, step=100):
current += 1
if current % step == 0 or total == current:
percent = "" if total == 0 else f"({current * 100 / total:.1f}%)"
print(f"{cmt}: {current} {percent}", flush=True, end='\r' if total > current or total == 0 else '\n')
return current
def img_process(photo, extensions, photo_folder, count, total,
get_attrib=False, resize=False, size=None, resize_folder=None):
"""
Process photos
:param photo: Image name
:param extensions: List of possible extensions
:param photo_folder: Folder containing image files
:param count: Current processed count
:param total: Total number to process
:param get_attrib: Get attributes flag
:param resize: Resize image flag
:param size: Size to resize to
:param resize_folder: Folder to save resized images
:return:
"""
attrib = None
for ext in extensions:
filename = f"{photo}{ext}"
filepath = os.path.join(photo_folder, filename)
if os.path.isfile(filepath):
if get_attrib:
im = Image.open(filepath)
attrib = f"{filename},{im.format},{im.size[0]},{im.size[1]},{im.mode}"
im.close()
else:
attrib = None
if resize:
resize_keep_aspect(filepath, size, resize_folder)
count = progress("Photo", total, count)
break
if get_attrib and attrib is None:
raise ValueError(f"Unmatched photo id {photo}")
return count, attrib
def generate_photo_set(biz_path, photo_csv_path, id_lst, photo_folder, out_path, save_ids_path=None, arg_dict=None):
"""
Generate a csv for the photo dataset
:param biz_path: Path to business csv file
:param photo_csv_path: Path to photo csv file
:param id_lst: List of business ids
:param photo_folder: Path to folder containing photos
:param out_path: Path to save dataset to
:param save_ids_path: File to save business id list to
:param arg_dict: keyword arguments
:return:
"""
biz_df, _ = get_business(biz_path, id_list=id_lst, arg_dict=arg_dict, csv_id='biz_photo')
photo_df, _, _ = get_photos(photo_csv_path, id_lst, None, arg_dict=arg_dict)
# categorical representation; e.g. '1_0' represents 1.0 stars
biz_df['stars_cat'] = biz_df['stars'].apply(lambda x: str(x).replace(".", "_"))
# ordinal representation;
# e.g. [0,0,0,0,0,0,0,0,0] represents 1.0 star, [1,0,0,0,0,0,0,0,0] represents 1.5 stars etc.
star_min = biz_df['stars'].min()
max_len = ceil(((biz_df['stars'].max() - star_min) * 2)) + 1 # stars range * num of 0.5 + 1
def fill_array(x):
one_cnt = ceil((x - star_min) * 2)
return ([1] * one_cnt) + ([0] * (max_len - one_cnt))
biz_df['stars_ord'] = biz_df['stars'].apply(fill_array)
# numerical representation; e.g. 0.5 = 1, 1.0 = 2 etc.
biz_df['stars_num'] = biz_df['stars'].apply(lambda x: ceil(x * 2))
# many-to-one join, i.e many photos to one business id
biz_photo_df = pd.merge(photo_df, biz_df, on='business_id', how='outer')
# drop rows with no photo id, no photo no prediction
total = len(biz_photo_df)
biz_photo_df = biz_photo_df[~biz_photo_df['photo_id'].isna()]
if total > len(biz_photo_df):
print(f"Dropped {total - len(biz_photo_df)} businesses with no photos")
if 'random_select' in arg_dict:
sample_ctrl = {
'n': int(arg_dict['random_select']) if arg_dict['random_select'] >= 1.0 else None,
'frac': arg_dict['random_select'] if arg_dict['random_select'] < 1.0 else None
}
pre_sample_len = len(biz_photo_df)
if arg_dict['select_on'].lower() == 'all':
# do sample on all photos available
biz_photo_df = biz_photo_df.sample(**sample_ctrl, random_state=1)
print(f"Sampled {len(biz_photo_df)} from {pre_sample_len} possible photos")
else:
# do sample on unique values of specified column
# make sorted list of hashed unique samples
unique_biz_ids = pd.Series(biz_photo_df[arg_dict['select_on']].unique())
vals_to_match = sorted(unique_biz_ids.
sample(**sample_ctrl, random_state=1).apply(hash).to_list())
def is_req(row):
return binary_search(vals_to_match, 0, len(vals_to_match) - 1, hash(row)) >= 0
biz_photo_df = biz_photo_df[biz_photo_df[arg_dict['select_on']].apply(is_req)]
print(f"Sampled {len(vals_to_match)} from {len(unique_biz_ids)} "
f"possible {arg_dict['select_on']}, giving {len(biz_photo_df)} photos")
# process photos
extensions = Image.registered_extensions().keys()
count = 0
total = len(biz_photo_df)
# process photos details
print(f"Processing photo details")
resize = ('photo_folder_resize' in arg_dict and 'photo_size' in arg_dict)
if resize:
print(f" Including resizing photos to {photo_size_str(arg_dict['photo_size'])} in "
f"{arg_dict['photo_folder_resize']}")
Path(arg_dict['photo_folder_resize']).mkdir(parents=True, exist_ok=True)
def img_attrib(photo):
nonlocal count
count, attrib = img_process(photo, extensions, photo_folder, count, total, get_attrib=True, resize=True,
size=arg_dict['photo_size'], resize_folder=arg_dict['photo_folder_resize'])
return attrib
else:
def img_attrib(photo):
nonlocal count
count, attrib = img_process(photo, extensions, photo_folder, count, total, get_attrib=True)
return attrib
biz_photo_df['photo_attrib'] = biz_photo_df['photo_id'].apply(img_attrib)
biz_photo_df[['photo_file', 'format', 'width', 'height', 'mode']] = \
biz_photo_df.apply(lambda row: pd.Series(row['photo_attrib'].split(',')), axis=1, result_type='expand')
biz_photo_df['width'] = biz_photo_df['width'].astype('int32')
biz_photo_df['height'] = biz_photo_df['height'].astype('int32')
progress("Photo", len(biz_photo_df), len(biz_photo_df))
# just keep required columns
photo_set_df = biz_photo_df[['business_id', 'stars', 'stars_cat', 'stars_ord', 'stars_num', 'photo_id',
'photo_file', 'format', 'width', 'height', 'mode']]
def wh_anal(column):
lwr = column.lower()
print(f"{column}: min - {photo_set_df[lwr].min()}px, max - {photo_set_df[lwr].max()}px")
print(f"{column}: value counts - {photo_set_df[lwr].value_counts()}")
unique_vals = photo_set_df['format'].unique()
print(f"Format: {len(unique_vals)} format{'' if len(unique_vals) == 1 else 's'} - {unique_vals}")
wh_anal("Width")
wh_anal("Height")
unique_vals = photo_set_df['mode'].unique()
print(f"Mode: {len(unique_vals)} mode{'' if len(unique_vals) == 1 else 's'} - {unique_vals}")
unique_vals = photo_set_df['stars'].unique()
unique_cat_vals = photo_set_df['stars_cat'].unique()
unique_num_vals = photo_set_df['stars_num'].unique()
unique_ord_vals = set()
photo_set_df['stars_ord'].apply(lambda x: unique_ord_vals.add(tuple(x)))
print(f"Stars: {len(unique_vals)} class{'' if len(unique_vals) == 1 else 'es'} - {unique_vals}\n"
f"\t{unique_cat_vals}\n\t{unique_num_vals}\n\t{unique_ord_vals}")
if save_ids_path is not None:
save_list(save_ids_path, biz_photo_df['business_id'].unique().tolist())
save_csv(photo_set_df, out_path, index=False)
def photo_size_str(p_size: Union[int, tuple]):
if isinstance(p_size, int):
width = p_size
height = width
else:
width = p_size[0]
height = p_size[1]
return f"{width}x{height}px"
def resize_photo_set(dataset_csv_path, photo_folder, arg_dict=None):
"""
Generate a csv for the photo dataset
:param dataset_csv_path: Path to dataset csv file
:param photo_folder: Path to folder containing photos
:param arg_dict: keyword arguments
:return:
"""
photo_set_df, _, start = load_csv('photos', dataset_csv_path, arg_dict=arg_dict)
print(f"Resizing photos to {photo_size_str(arg_dict['photo_size'])} in {arg_dict['photo_folder_resize']}")
Path(arg_dict['photo_folder_resize']).mkdir(parents=True, exist_ok=True)
# process photos
extensions = Image.registered_extensions().keys()
count = 0
total = len(photo_set_df)
def img_proc(photo):
nonlocal count
count, _ = img_process(photo, extensions, photo_folder, count, total, resize=True,
size=arg_dict['photo_size'], resize_folder=arg_dict['photo_folder_resize'])
photo_set_df['photo_id'].apply(img_proc)
duration(start, verbose=False if 'verbose' not in arg_dict else arg_dict['verbose'])
def file_arg_help(descrip, target='file', action=None):
if action is None:
tail = ';'
else:
tail = f' {action};'
return f"Path to {descrip} {target}{tail} absolute or relative to 'root directory' if argument supplied"
def warning(msg):
print(f"Warning: {msg}")
def error(msg):
sys.exit(f"Error: {msg}")
def ignore_arg_warning(args_namespace, arg_lst):
for arg in arg_lst:
if arg in args_namespace:
warning(f"Ignoring '{arg}' argument")
def arg_error(arg_parser, msg):
arg_parser.print_usage()
sys.exit(msg)
def required_arg_error(arg_parser, req_arg):
arg_error(arg_parser, f"{os.path.split(sys.argv[0])[1]}: error one of the arguments {req_arg} is required")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Perform ETL on the Yelp Dataset CSV data to extract the subset of businesses/reviews etc. '
'based on a parent category',
)
parser.add_argument(
'-d', '--dir',
type=str,
help='Root directory',
default='',
)
# business csv file or business ids file
biz_group = parser.add_mutually_exclusive_group(required=False)
biz_group.add_argument('-b', '--biz', type=str, help=file_arg_help("business csv"), default='')
biz_group.add_argument('-bi', '--biz_ids', type=str, help=file_arg_help("business ids"), default='')
# review, tips, checkin & photo input csv files
for arg_tuple in [('-r', '--review', 'review'),
('-t', '--tips', 'tips'),
('-ci', '--chkin', 'checkin'),
('-pi', '--pin', 'photo'),
('-psi', '--photo_set_in', 'photo dataset')]:
parser.add_argument(
arg_tuple[0], arg_tuple[1], type=str, help=file_arg_help(f"{arg_tuple[2]} csv"), default='', required=False
)
# categories json file or categories file
cat_group = parser.add_mutually_exclusive_group(required=False)
cat_group.add_argument('-c', '--cat', type=str, help=file_arg_help("categories json"), default='')
cat_group.add_argument('-cl', '--cat_list', type=str, help=file_arg_help("category list"), default='')
# category selection
parser.add_argument('-p', '--parent', type=str, help='Parent category', default='', required=False)
parser.add_argument(
'-e', '--exclude', type=str, help='Exclude categories; a comma separated list of categories to exclude',
default='', required=False)
# output files
for arg_tuple in [('-ob', '--out_biz', 'business'),
('-opr', '--out_prefilter_review', 'review pre-filter'),
('-or', '--out_review', 'review'),
('-ot', '--out_tips', 'tips'),
('-oci', '--out_chkin', 'checkin'),
('-op', '--out_photo', 'photo'),
('-ops', '--out_photo_set', 'photo set')]:
parser.add_argument(
arg_tuple[0], arg_tuple[1], type=str, help=file_arg_help(f"{arg_tuple[2]} csv", action="to create"),
default=argparse.SUPPRESS, required=False
)
parser.add_argument('-bp', '--biz_photo', type=str, help=file_arg_help("business csv for photo dataset"),
default='') # just so as not to conflict with mutually exclusive --biz/--biz_ids arguments
for arg_tuple in [('-oc', '--out_cat', 'category list'),
('-obi', '--out_biz_id', 'business ids')]:
parser.add_argument(
arg_tuple[0], arg_tuple[1], type=str, help=file_arg_help(f"{arg_tuple[2]}", action="to create"),
default=argparse.SUPPRESS, required=False
)
# input folders
parser.add_argument('-pf', '--photo_folder', type=str, help=file_arg_help("photo", target='folder'),
default='')
# output folders
parser.add_argument('-pfr', '--photo_folder_resize', type=str,
help=file_arg_help("resized photos", target='folder'),
default='')
# miscellaneous
parser.add_argument('-dx', '--drop_regex', help='Regex for business csv columns to drop', type=str, default=None)
parser.add_argument('-mx', '--match_regex', help="Regex for csv columns to match; 'csv_id:column_name=regex'. "
"Valid 'csv_id' are; 'biz'=business csv file, "
"'pin'=photo csv file, 'tip'=tip csv file and "
"'review'=review csv file",
type=str, default=argparse.SUPPRESS, nargs='+')
parser.add_argument('-df', '--dataframe', help="Dataframe to use; 'pandas' or 'dask'",
choices=['pandas', 'dask'], required=False)
parser.add_argument('-pe', '--parse_engine', help="Parser engine to use; 'c' or 'python'}",
choices=['c', 'python'], required=False)
parser.add_argument('-nr', '--nrows', help="Number of rows to read, (Note: ignored with '-df=dask' option)",
type=int, default=argparse.SUPPRESS)
parser.add_argument('-li', '--limit_id', help="Limit number of business ids to read",
type=int, default=argparse.SUPPRESS)
parser.add_argument('-rs', '--random_select', help="Make random selection; 'value' < 1.0 = percent of total "
"available, or 'value' > 1 = number to select",
type=float, default=argparse.SUPPRESS)
parser.add_argument('-so', '--select_on', help="Column to make selection on or 'all' to select from total "
"available; e.g. 'business_id'",
type=str, default=argparse.SUPPRESS)
parser.add_argument('-cs', '--csv_size',
help=f"max csv field size in kB; default {hex(csv.field_size_limit() // 0x1000)[2:]}kB",
type=int, default=argparse.SUPPRESS)
parser.add_argument('-ps', '--photo_size',
help=f"required photo size in pixels or 'width,height'; e.g. '299' or '150,100'",
type=str, default=argparse.SUPPRESS)
parser.add_argument('-v', '--verbose', help='Verbose mode', action='store_true')
args = parser.parse_args()
if len(sys.argv) == 1:
# display help message when no args are passed.
parser.print_help()
sys.exit(1)
if args.verbose:
print(f"Arguments: {args}")
if 'csv_size' in args:
csv.field_size_limit(int(str(args.csv_size), 16) * 0x1000) # convert kB to bytes
paths = {'biz': None, 'biz_ids': None, 'biz_photo': None, 'photo_folder': None, 'photo_folder_resize': None,
'cat': None, 'cat_list': None,
'review': None, 'tips': None, 'chkin': None, 'pin': None, 'photo_set_in': None,
'out_biz': None, 'out_review': None, 'out_prefilter_review': None,
'out_tips': None, 'out_chkin': None, 'out_photo': None,
'out_photo_set': None,
'out_cat': None, 'out_biz_id': None}
IpArgDetail = namedtuple('IpArgDetail', ['name', 'value', 'typ', 'create_dir'])
ip_arg_tuples = [IpArgDetail('biz', args.biz, 'file', False), IpArgDetail('biz_ids', args.biz_ids, 'file', False),
IpArgDetail('biz_photo', args.biz_photo, 'file', False),
IpArgDetail('photo_folder', args.photo_folder, 'folder', False),
IpArgDetail('photo_folder_resize', args.photo_folder_resize, 'folder', True),
IpArgDetail('cat', args.cat, 'file', False), IpArgDetail('cat_list', args.cat_list, 'file', False)]
for arg_tuple in ip_arg_tuples:
if arg_tuple.name in args:
paths[arg_tuple.name] = arg_tuple.value
for arg_tuple in [('review', args.review),
('tips', args.tips),
('chkin', args.chkin),
('pin', args.pin),
('photo_set_in', args.photo_set_in)]:
if arg_tuple[0] in args and len(arg_tuple[1]):
paths[arg_tuple[0]] = arg_tuple[1]
for arg_tuple in [('out_biz', None if 'out_biz' not in args else args.out_biz),
('out_prefilter_review',
None if 'out_prefilter_review' not in args else args.out_prefilter_review),
('out_review', None if 'out_review' not in args else args.out_review),
('out_tips', None if 'out_tips' not in args else args.out_tips),
('out_chkin', None if 'out_chkin' not in args else args.out_chkin),
('out_photo', None if 'out_photo' not in args else args.out_photo),
('out_photo_set', None if 'out_photo_set' not in args else args.out_photo_set),
('out_cat', None if 'out_cat' not in args else args.out_cat),
('out_biz_id', None if 'out_biz_id' not in args else args.out_biz_id)]:
if arg_tuple[0] in args:
paths[arg_tuple[0]] = arg_tuple[1]
if len(args.dir) > 0:
for key, val in paths.items():
if val is not None and not os.path.isabs(val):
paths[key] = os.path.join(args.dir, val)
for arg_tuple in ip_arg_tuples:
if len(arg_tuple.value) > 0:
verify_path(paths[arg_tuple.name], typ=arg_tuple.typ, create_dir=arg_tuple.create_dir)
kwarg_dict = {'verbose': args.verbose, 'drop_regex': args.drop_regex}
if args.dataframe is not None:
kwarg_dict['dataframe'] = Df.PANDAS if args.dataframe == 'pandas' else Df.DASK
if args.parse_engine is not None:
kwarg_dict['parse_engine'] = 'c' if args.parse_engine == 'c' else 'python'
for arg_tuple in [('limit_id', None if 'limit_id' not in args else args.limit_id),
('nrows', None if 'nrows' not in args else args.nrows)]:
if arg_tuple[0] in args:
kwarg_dict[arg_tuple[0]] = arg_tuple[1]
if 'match_regex' in args:
for regex_cmd in args.match_regex:
split_file_regex = regex_cmd.split(':')
if len(split_file_regex) != 2:
arg_error(parser, f"Invalid format for -mx/--match_regex, expected 'csv_id:column_name=regex'")
splits_col_regex = split_file_regex[1].split('=')
if len(splits_col_regex) != 2:
arg_error(parser, f"Invalid format for -mx/--match_regex, expected 'csv_id:column_name=regex'")
if 'regex' not in kwarg_dict:
kwarg_dict['regex'] = {}
# csv_id [column_name, regex]
kwarg_dict['regex'][split_file_regex[0]] = splits_col_regex
if 'photo_folder_resize' in args or 'photo_size' in args:
if ('photo_size' in args and len(args.photo_folder_resize) == 0) or \
('photo_size' not in args and len(args.photo_folder_resize)):
arg_error(parser, f"Options -pfr/--photo_folder_resize and -ps/--photo_size are both required")
if 'photo_size' in args and len(args.photo_folder_resize):
photo_size = decode_int_or_tuple(args.photo_size)
if photo_size is None:
arg_error(parser, f"Invalid -ps/--photo_size option")
kwarg_dict['photo_size'] = photo_size
kwarg_dict['photo_folder_resize'] = paths['photo_folder_resize']
if 'random_select' in args or 'select_on' in args:
if (('random_select' in args and 'select_on' not in args) or
('random_select' not in args and 'select_on' in args)):
arg_error(parser, f"Options -rs/--random_select and -so/--select_on are both required")
kwarg_dict['random_select'] = args.random_select
kwarg_dict['select_on'] = args.select_on
# load categories
if len(args.cat_list) > 0:
ignore_arg_warning(args, ['out_cat', 'parent', 'exclude'])
categories_lst = load_list(paths['cat_list'])
elif len(args.cat) > 0:
categories_lst = get_categories(paths['cat'], args.parent, args.exclude, paths['out_cat'], args.verbose)
else:
categories_lst = None
# load business ids
if len(args.biz_ids) > 0:
ignore_arg_warning(args, ['out_biz', 'out_biz_id'])
biz_id_lst = load_list(paths['biz_ids'])
elif len(args.biz) > 0:
if categories_lst is None:
required_arg_error(parser, ['-c/--cat', '-cl/--cat_list'])
_, biz_id_lst = get_business(paths['biz'], category_list=categories_lst, out_path=paths['out_biz'],
save_ids_path=paths['out_biz_id'], arg_dict=kwarg_dict)
else:
biz_id_lst = None
# check have required info for filtering ops
for out_arg in ['out_review', 'out_tips', 'out_chkin', 'out_photo']:
if paths[out_arg] is not None:
if biz_id_lst is None:
required_arg_error(parser, ['-b/--biz', '-bi/--biz_ids'])
else:
break
# filter reviews
if paths['out_review'] is not None:
if 'dataframe' not in kwarg_dict:
kwarg_dict['dataframe'] = Df.DASK
get_reviews(paths['review'], biz_id_lst, paths['out_review'], paths['out_prefilter_review'],
arg_dict=kwarg_dict)
# filter tips
if paths['out_tips'] is not None:
get_tips(paths['tips'], biz_id_lst, paths['out_tips'], arg_dict=kwarg_dict)
# filter checkin
if paths['out_chkin'] is not None:
get_checkin(paths['chkin'], biz_id_lst, paths['out_chkin'], arg_dict=kwarg_dict)
# filter photo
if paths['out_photo'] is not None:
get_photos(paths['pin'], biz_id_lst, paths['out_photo'], arg_dict=kwarg_dict)
# photo dataset
if paths['out_photo_set'] is not None:
generate_photo_set(paths['biz_photo'], paths['pin'], biz_id_lst, paths['photo_folder'], paths['out_photo_set'],
save_ids_path=paths['out_biz_id'], arg_dict=kwarg_dict)
# resize photos
if paths['photo_set_in'] is not None:
resize_photo_set(paths['photo_set_in'], paths['photo_folder'], arg_dict=kwarg_dict) | 0.536313 | 0.201931 |
import socket
from sshuttle.firewall import subnet_weight
from sshuttle.linux import nft, nft_get_handle, nonfatal
from sshuttle.methods import BaseMethod
class Method(BaseMethod):
# We name the chain based on the transproxy port number so that it's
# possible to run multiple copies of sshuttle at the same time. Of course,
# the multiple copies shouldn't have overlapping subnets, or only the most-
# recently-started one will win (because we use "-I OUTPUT 1" instead of
# "-A OUTPUT").
def setup_firewall(self, port, dnsport, nslist, family, subnets, udp,
user):
if udp:
raise Exception("UDP not supported by nft")
table = "nat"
def _nft(action, *args):
return nft(family, table, action, *args)
chain = 'sshuttle-%s' % port
# basic cleanup/setup of chains
_nft('add table', '')
_nft('add chain', 'prerouting',
'{ type nat hook prerouting priority -100; policy accept; }')
_nft('add chain', 'postrouting',
'{ type nat hook postrouting priority 100; policy accept; }')
_nft('add chain', 'output',
'{ type nat hook output priority -100; policy accept; }')
_nft('add chain', chain)
_nft('flush chain', chain)
_nft('add rule', 'output jump %s' % chain)
_nft('add rule', 'prerouting jump %s' % chain)
# create new subnet entries.
for _, swidth, sexclude, snet, fport, lport \
in sorted(subnets, key=subnet_weight, reverse=True):
tcp_ports = ('ip', 'protocol', 'tcp')
if fport and fport != lport:
tcp_ports = \
tcp_ports + \
('tcp', 'dport', '{ %d-%d }' % (fport, lport))
elif fport and fport == lport:
tcp_ports = tcp_ports + ('tcp', 'dport', '%d' % (fport))
if sexclude:
_nft('add rule', chain, *(tcp_ports + (
'ip daddr %s/%s' % (snet, swidth), 'return')))
else:
_nft('add rule', chain, *(tcp_ports + (
'ip daddr %s/%s' % (snet, swidth), 'ip ttl != 42',
('redirect to :' + str(port)))))
for _, ip in [i for i in nslist if i[0] == family]:
if family == socket.AF_INET:
_nft('add rule', chain, 'ip protocol udp ip daddr %s' % ip,
'udp dport { 53 }', 'ip ttl != 42',
('redirect to :' + str(dnsport)))
elif family == socket.AF_INET6:
_nft('add rule', chain, 'ip6 protocol udp ip6 daddr %s' % ip,
'udp dport { 53 }', 'ip ttl != 42',
('redirect to :' + str(dnsport)))
def restore_firewall(self, port, family, udp, user):
if udp:
raise Exception("UDP not supported by nft method_name")
table = "nat"
def _nft(action, *args):
return nft(family, table, action, *args)
chain = 'sshuttle-%s' % port
# basic cleanup/setup of chains
handle = nft_get_handle('chain ip nat output', chain)
nonfatal(_nft, 'delete rule', 'output', handle)
handle = nft_get_handle('chain ip nat prerouting', chain)
nonfatal(_nft, 'delete rule', 'prerouting', handle)
nonfatal(_nft, 'delete chain', chain) | lib/python/lib/python3.6/site-packages/sshuttle-0.78.5.dev35+gaaa6684-py3.6.egg/sshuttle/methods/nft.py | import socket
from sshuttle.firewall import subnet_weight
from sshuttle.linux import nft, nft_get_handle, nonfatal
from sshuttle.methods import BaseMethod
class Method(BaseMethod):
# We name the chain based on the transproxy port number so that it's
# possible to run multiple copies of sshuttle at the same time. Of course,
# the multiple copies shouldn't have overlapping subnets, or only the most-
# recently-started one will win (because we use "-I OUTPUT 1" instead of
# "-A OUTPUT").
def setup_firewall(self, port, dnsport, nslist, family, subnets, udp,
user):
if udp:
raise Exception("UDP not supported by nft")
table = "nat"
def _nft(action, *args):
return nft(family, table, action, *args)
chain = 'sshuttle-%s' % port
# basic cleanup/setup of chains
_nft('add table', '')
_nft('add chain', 'prerouting',
'{ type nat hook prerouting priority -100; policy accept; }')
_nft('add chain', 'postrouting',
'{ type nat hook postrouting priority 100; policy accept; }')
_nft('add chain', 'output',
'{ type nat hook output priority -100; policy accept; }')
_nft('add chain', chain)
_nft('flush chain', chain)
_nft('add rule', 'output jump %s' % chain)
_nft('add rule', 'prerouting jump %s' % chain)
# create new subnet entries.
for _, swidth, sexclude, snet, fport, lport \
in sorted(subnets, key=subnet_weight, reverse=True):
tcp_ports = ('ip', 'protocol', 'tcp')
if fport and fport != lport:
tcp_ports = \
tcp_ports + \
('tcp', 'dport', '{ %d-%d }' % (fport, lport))
elif fport and fport == lport:
tcp_ports = tcp_ports + ('tcp', 'dport', '%d' % (fport))
if sexclude:
_nft('add rule', chain, *(tcp_ports + (
'ip daddr %s/%s' % (snet, swidth), 'return')))
else:
_nft('add rule', chain, *(tcp_ports + (
'ip daddr %s/%s' % (snet, swidth), 'ip ttl != 42',
('redirect to :' + str(port)))))
for _, ip in [i for i in nslist if i[0] == family]:
if family == socket.AF_INET:
_nft('add rule', chain, 'ip protocol udp ip daddr %s' % ip,
'udp dport { 53 }', 'ip ttl != 42',
('redirect to :' + str(dnsport)))
elif family == socket.AF_INET6:
_nft('add rule', chain, 'ip6 protocol udp ip6 daddr %s' % ip,
'udp dport { 53 }', 'ip ttl != 42',
('redirect to :' + str(dnsport)))
def restore_firewall(self, port, family, udp, user):
if udp:
raise Exception("UDP not supported by nft method_name")
table = "nat"
def _nft(action, *args):
return nft(family, table, action, *args)
chain = 'sshuttle-%s' % port
# basic cleanup/setup of chains
handle = nft_get_handle('chain ip nat output', chain)
nonfatal(_nft, 'delete rule', 'output', handle)
handle = nft_get_handle('chain ip nat prerouting', chain)
nonfatal(_nft, 'delete rule', 'prerouting', handle)
nonfatal(_nft, 'delete chain', chain) | 0.379378 | 0.131034 |
import pandas
import scipy
import numpy
def identity(x):
return x
def rolling_apply(df, window_size, f, trim=True, **kargs):
''' A function that will apply a window wise operation to the rows of a
dataframe, df.
input:
df - a pandas dataframe
window_size - The size of windows to extract from each row series
f - A function mapping f(numpy.ndarray) -> scalar
trim - a boolean, if true, columns with null values will be trimmed
kargs - Other parameters to pass to the Series.rolling constructor
output:
a dataframe
'''
data = df.apply(lambda x: x.rolling(window_size, **kargs).apply(f), axis=1)
if(trim):
data = data.dropna(axis=1, how='any')
return data
def transform_standardized(cell_trap_frame, axis=1):
""" Transforms a dataframe into a feature representation of the data
standardizing each element by row. Use axis=0 to perform the
transformation by column as a form of time normalization.
ret = ( t(raw) - min(t_axis) ) / max(t_axis)
"""
mins = cell_trap_frame.min(axis=axis)
maxs = cell_trap_frame.max(axis=axis)
temp = cell_trap_frame.sub(mins, axis=abs(axis - 1))
return temp.div(maxs, axis=abs(axis - 1))
def resample(cell_trap_frame, resample_freq=60):
cell_trap = cell_trap_frame.transpose()
cell_trap.index = pandas.to_datetime(cell_trap.index, unit="s")
cell_trap_resamp = cell_trap.resample("{0}T".format(resample_freq)).mean()
data_plot = cell_trap_resamp.transpose()
data_plot.columns = data_plot.columns.values.astype(numpy.int64) // 10**9
return data_plot
def holt_winters_second_order_ewma(x, alpha, beta):
"""
A smoothing function that takes a weighted mean of a point in a time
series with respect to its history. alpha is the weight (ie, the relative
importance) with which the time series most recent behavior is valued.
Similarly, beta is the weight given to the most recent 1st derivative, w,
when averaging the trend.
input
:param x: array or array-like
Time series to be smoothed.
:param alpha: float, (0,1)
Weight given to most recent time point.
:param beta: float, (0, 1)
Weight given to most recent linear slope/trend.
:return: s: numpy.array
The smoothed time series.
"""
N = x.size
s = numpy.zeros((N, ))
b = numpy.zeros((N, ))
s[0] = x[0]
for i in range(1, N):
if(numpy.isnan(s[i-1])):
s[i] = x[i]
s[i] = alpha * x[i] + (1 - alpha) * (s[i - 1] + b[i - 1])
b[i] = beta * (s[i] - s[i - 1]) + (1 - beta) * b[i - 1]
return s
def smooth(cell_trap_frame, alpha=0.1, beta=0.001):
return cell_trap_frame.apply(
lambda x: holt_winters_second_order_ewma(x, alpha, beta),
axis=1,
raw=True)
def rolling_standardized_center(cell_trap_frame, window_size):
''' ret[a, b] = ( ctf[a,b] - min(ctf[a, b-ws/2:b+ws/2]) / max(ctf[a, b-ws/2:b+ws/2])
'''
return rolling_apply(
cell_trap_frame,
window_size,
lambda x: (x[window_size / 2] - x.min()) / x.max(),
center=True)
def rolling_standardized_right(cell_trap_frame, window_size):
''' let ctf = cell_trap_frame - min(cell_trap_frame) + 1
ret[a,b] = ( ctf[a,b] - min(ctf[a, b-ws:b]) ) / max(ctf[a,b-ws:b])
'''
cell_trap_frame = cell_trap_frame - cell_trap_frame.min().min() + 1
return rolling_apply(
cell_trap_frame,
window_size,
lambda x: (x[-1] - x.min()) / x.max() )
def transform_z_score(cell_trap_frame, axis=0):
''' z_score the columns (axis=0) or rows(axis=1) of a dataframe.
'''
return cell_trap_frame.apply(
scipy.stats.mstats.zscore,
raw=True,
axis=axis)
def rolling_z_score_center(cell_trap_frame, window_size):
''' ret[a,b] = zscore(ctf[a, b-ws/2:b+ws/2])[b]
'''
return rolling_apply(
cell_trap_frame,
window_size,
lambda x: scipy.stats.mstats.zscore(x)[window_size / 2],
center=True)
def rolling_z_score_right(cell_trap_frame, window_size):
''' ret[a.b] = zscore(ctf[a,b-ws:b])[b]
'''
return rolling_apply(
cell_trap_frame,
window_size,
lambda x: (x[-1] - x.mean()) / x.std())
def normalize_time(cell_trap_frame):
""" Transforms a dataframe by dividing each element by its column average.
Applying this transformation effectively means that each element is
now scaled in comparison to other elements observed at same time
ret = t(raw) / mean(t_column)
"""
means = cell_trap_frame.mean(axis=0)
return cell_trap_frame.div(means, axis=1)
def transform_delta(cell_trap_frame, shift=False):
''' Computes the delta across rows, delta(T, T-1). By default, the values
will associate with the t-1 label. Use shift=True to associate deltas
with the T label
ret = t(raw) - t-1(raw)
'''
deltas = cell_trap_frame.diff(axis=1)
if(shift):
deltas = deltas.shift(-1, axis=1)
return deltas.iloc[:, :-1]
else:
return deltas.iloc[:, 1:]
def transform_derivative(cell_trap_frame):
''' computes first derivative of the cell trap data
delta(signal)/delta(time)
'''
deltas = cell_trap_frame.diff(axis=1)
times = pandas.Series(cell_trap_frame.keys())
label_map = {k1: k2 for k1, k2 in zip(times.keys(), deltas.keys())}
times = times.rename(label_map)
delta_times = times.diff()
ret = deltas.apply(lambda c: c / delta_times, axis=1)
remap = {v: (i + v) / 2 for i,v in zip(ret.keys(), ret.keys()[1:])}
ret = ret.rename(columns=remap)
return ret
def transform_rof(cell_trap_frame):
middle_values = rolling_apply(
cell_trap_frame,
2,
lambda x: float(x[0] + x[1]) / 2)
deltas = transform_delta(cell_trap_frame)
return middle_values + deltas
#TODO: NH: make the interior print statement a warnings.waring(), instead of a print().
def drop_duplicates(df, subset=None, keep='first'):
""" Drops duplicates from a DataFrame df.
Params :
df : DataFrame
A dataFrame duplicates should be removed from
subset : [obj]
A list of column keys in df to care about when establishing
if two entries are duplicates. Defaults to all column keys
keep : 'first' or 'last' or False
A rule to determine which duplicate entries should be kept.
'first' means that the first entry of a duplicate should be
kept while 'last' means that the last entry of a duplicate
should be kept. If rule=False, then all duplicated entries
will be dropped.
Returns: DataFrame
"""
data = df.loc[numpy.invert(df.duplicated(subset=subset, keep=keep))]
if data.shape != df.shape:
print('Dropped duplicates : Original - {0!s} : New - {1!s}'.format(
df.shape, data.shape))
return data
def add_mean_and_std(df):
""" Return a copy of df with rows representing mean and standard
deviation added. Mean corrosponds to index 0 and stddev is -1
"""
mean_series = df.mean(axis=0)
std_series = df.std(axis=0)
ret = df.copy()
ret.loc[0] = mean_series
ret.loc[-1] = std_series
return ret.sort_index()
feature_types = {
'raw': lambda x: x,
'normalized': normalize_time,
'z_scored': lambda x: transform_z_score(x, axis=0),
'raw`': transform_derivative,
'raw`^2': lambda x: transform_derivative(x) ** 2,
'raw``': lambda x: transform_derivative(transform_derivative(x)),
'raw``^2': lambda x: transform_derivative(transform_derivative(x)) ** 2,
'formation_rate': transform_rof,
'standardized_10': lambda x: rolling_standardized_right(x, 10),
'standardized_20': lambda x: rolling_standardized_right(x, 20),
'standardized_30': lambda x: rolling_standardized_right(x, 30),
'rolling_z-score_10': lambda x: rolling_z_score_right(x, 10),
'rolling_z-score_20': lambda x: rolling_z_score_right(x, 20),
'rolling_z-score_30': lambda x: rolling_z_score_right(x, 30),
'smooth_rolling_z_score_30': lambda x: rolling_z_score_right(smooth(x),30),
'smooth': lambda x: smooth(x),
'smooth`': lambda x: transform_derivative(smooth(x)),
'smooth`^2': lambda x: transform_derivative(smooth(x)) ** 2,
'smooth``':
lambda x: transform_derivative(transform_derivative(smooth(x))),
'smooth``^2':
lambda x: transform_derivative(transform_derivative(smooth(x))) ** 2,
'smooth_resampled': lambda x: smooth(resample(x)),
'smooth_resampled``':
lambda x: smooth(resample(x)).diff(axis=1).diff(axis=1).dropna(axis=1, how='any'),
'smooth_resampled``^2':
lambda x: smooth(resample(x)).diff(axis=1).diff(axis=1).dropna(axis=1, how='any') ** 2,
'transform_derivative': lambda x: transform_derivative(x),
'sqrt': lambda x: numpy.sqrt(x),
'norm_mean': lambda x: x.divide(x.mean().mean()),
'abs': lambda x: x.abs(),
'square': lambda x: x.multiply(x),
} | transformations.py | import pandas
import scipy
import numpy
def identity(x):
return x
def rolling_apply(df, window_size, f, trim=True, **kargs):
''' A function that will apply a window wise operation to the rows of a
dataframe, df.
input:
df - a pandas dataframe
window_size - The size of windows to extract from each row series
f - A function mapping f(numpy.ndarray) -> scalar
trim - a boolean, if true, columns with null values will be trimmed
kargs - Other parameters to pass to the Series.rolling constructor
output:
a dataframe
'''
data = df.apply(lambda x: x.rolling(window_size, **kargs).apply(f), axis=1)
if(trim):
data = data.dropna(axis=1, how='any')
return data
def transform_standardized(cell_trap_frame, axis=1):
""" Transforms a dataframe into a feature representation of the data
standardizing each element by row. Use axis=0 to perform the
transformation by column as a form of time normalization.
ret = ( t(raw) - min(t_axis) ) / max(t_axis)
"""
mins = cell_trap_frame.min(axis=axis)
maxs = cell_trap_frame.max(axis=axis)
temp = cell_trap_frame.sub(mins, axis=abs(axis - 1))
return temp.div(maxs, axis=abs(axis - 1))
def resample(cell_trap_frame, resample_freq=60):
cell_trap = cell_trap_frame.transpose()
cell_trap.index = pandas.to_datetime(cell_trap.index, unit="s")
cell_trap_resamp = cell_trap.resample("{0}T".format(resample_freq)).mean()
data_plot = cell_trap_resamp.transpose()
data_plot.columns = data_plot.columns.values.astype(numpy.int64) // 10**9
return data_plot
def holt_winters_second_order_ewma(x, alpha, beta):
"""
A smoothing function that takes a weighted mean of a point in a time
series with respect to its history. alpha is the weight (ie, the relative
importance) with which the time series most recent behavior is valued.
Similarly, beta is the weight given to the most recent 1st derivative, w,
when averaging the trend.
input
:param x: array or array-like
Time series to be smoothed.
:param alpha: float, (0,1)
Weight given to most recent time point.
:param beta: float, (0, 1)
Weight given to most recent linear slope/trend.
:return: s: numpy.array
The smoothed time series.
"""
N = x.size
s = numpy.zeros((N, ))
b = numpy.zeros((N, ))
s[0] = x[0]
for i in range(1, N):
if(numpy.isnan(s[i-1])):
s[i] = x[i]
s[i] = alpha * x[i] + (1 - alpha) * (s[i - 1] + b[i - 1])
b[i] = beta * (s[i] - s[i - 1]) + (1 - beta) * b[i - 1]
return s
def smooth(cell_trap_frame, alpha=0.1, beta=0.001):
return cell_trap_frame.apply(
lambda x: holt_winters_second_order_ewma(x, alpha, beta),
axis=1,
raw=True)
def rolling_standardized_center(cell_trap_frame, window_size):
''' ret[a, b] = ( ctf[a,b] - min(ctf[a, b-ws/2:b+ws/2]) / max(ctf[a, b-ws/2:b+ws/2])
'''
return rolling_apply(
cell_trap_frame,
window_size,
lambda x: (x[window_size / 2] - x.min()) / x.max(),
center=True)
def rolling_standardized_right(cell_trap_frame, window_size):
''' let ctf = cell_trap_frame - min(cell_trap_frame) + 1
ret[a,b] = ( ctf[a,b] - min(ctf[a, b-ws:b]) ) / max(ctf[a,b-ws:b])
'''
cell_trap_frame = cell_trap_frame - cell_trap_frame.min().min() + 1
return rolling_apply(
cell_trap_frame,
window_size,
lambda x: (x[-1] - x.min()) / x.max() )
def transform_z_score(cell_trap_frame, axis=0):
''' z_score the columns (axis=0) or rows(axis=1) of a dataframe.
'''
return cell_trap_frame.apply(
scipy.stats.mstats.zscore,
raw=True,
axis=axis)
def rolling_z_score_center(cell_trap_frame, window_size):
''' ret[a,b] = zscore(ctf[a, b-ws/2:b+ws/2])[b]
'''
return rolling_apply(
cell_trap_frame,
window_size,
lambda x: scipy.stats.mstats.zscore(x)[window_size / 2],
center=True)
def rolling_z_score_right(cell_trap_frame, window_size):
''' ret[a.b] = zscore(ctf[a,b-ws:b])[b]
'''
return rolling_apply(
cell_trap_frame,
window_size,
lambda x: (x[-1] - x.mean()) / x.std())
def normalize_time(cell_trap_frame):
""" Transforms a dataframe by dividing each element by its column average.
Applying this transformation effectively means that each element is
now scaled in comparison to other elements observed at same time
ret = t(raw) / mean(t_column)
"""
means = cell_trap_frame.mean(axis=0)
return cell_trap_frame.div(means, axis=1)
def transform_delta(cell_trap_frame, shift=False):
''' Computes the delta across rows, delta(T, T-1). By default, the values
will associate with the t-1 label. Use shift=True to associate deltas
with the T label
ret = t(raw) - t-1(raw)
'''
deltas = cell_trap_frame.diff(axis=1)
if(shift):
deltas = deltas.shift(-1, axis=1)
return deltas.iloc[:, :-1]
else:
return deltas.iloc[:, 1:]
def transform_derivative(cell_trap_frame):
''' computes first derivative of the cell trap data
delta(signal)/delta(time)
'''
deltas = cell_trap_frame.diff(axis=1)
times = pandas.Series(cell_trap_frame.keys())
label_map = {k1: k2 for k1, k2 in zip(times.keys(), deltas.keys())}
times = times.rename(label_map)
delta_times = times.diff()
ret = deltas.apply(lambda c: c / delta_times, axis=1)
remap = {v: (i + v) / 2 for i,v in zip(ret.keys(), ret.keys()[1:])}
ret = ret.rename(columns=remap)
return ret
def transform_rof(cell_trap_frame):
middle_values = rolling_apply(
cell_trap_frame,
2,
lambda x: float(x[0] + x[1]) / 2)
deltas = transform_delta(cell_trap_frame)
return middle_values + deltas
#TODO: NH: make the interior print statement a warnings.waring(), instead of a print().
def drop_duplicates(df, subset=None, keep='first'):
""" Drops duplicates from a DataFrame df.
Params :
df : DataFrame
A dataFrame duplicates should be removed from
subset : [obj]
A list of column keys in df to care about when establishing
if two entries are duplicates. Defaults to all column keys
keep : 'first' or 'last' or False
A rule to determine which duplicate entries should be kept.
'first' means that the first entry of a duplicate should be
kept while 'last' means that the last entry of a duplicate
should be kept. If rule=False, then all duplicated entries
will be dropped.
Returns: DataFrame
"""
data = df.loc[numpy.invert(df.duplicated(subset=subset, keep=keep))]
if data.shape != df.shape:
print('Dropped duplicates : Original - {0!s} : New - {1!s}'.format(
df.shape, data.shape))
return data
def add_mean_and_std(df):
""" Return a copy of df with rows representing mean and standard
deviation added. Mean corrosponds to index 0 and stddev is -1
"""
mean_series = df.mean(axis=0)
std_series = df.std(axis=0)
ret = df.copy()
ret.loc[0] = mean_series
ret.loc[-1] = std_series
return ret.sort_index()
feature_types = {
'raw': lambda x: x,
'normalized': normalize_time,
'z_scored': lambda x: transform_z_score(x, axis=0),
'raw`': transform_derivative,
'raw`^2': lambda x: transform_derivative(x) ** 2,
'raw``': lambda x: transform_derivative(transform_derivative(x)),
'raw``^2': lambda x: transform_derivative(transform_derivative(x)) ** 2,
'formation_rate': transform_rof,
'standardized_10': lambda x: rolling_standardized_right(x, 10),
'standardized_20': lambda x: rolling_standardized_right(x, 20),
'standardized_30': lambda x: rolling_standardized_right(x, 30),
'rolling_z-score_10': lambda x: rolling_z_score_right(x, 10),
'rolling_z-score_20': lambda x: rolling_z_score_right(x, 20),
'rolling_z-score_30': lambda x: rolling_z_score_right(x, 30),
'smooth_rolling_z_score_30': lambda x: rolling_z_score_right(smooth(x),30),
'smooth': lambda x: smooth(x),
'smooth`': lambda x: transform_derivative(smooth(x)),
'smooth`^2': lambda x: transform_derivative(smooth(x)) ** 2,
'smooth``':
lambda x: transform_derivative(transform_derivative(smooth(x))),
'smooth``^2':
lambda x: transform_derivative(transform_derivative(smooth(x))) ** 2,
'smooth_resampled': lambda x: smooth(resample(x)),
'smooth_resampled``':
lambda x: smooth(resample(x)).diff(axis=1).diff(axis=1).dropna(axis=1, how='any'),
'smooth_resampled``^2':
lambda x: smooth(resample(x)).diff(axis=1).diff(axis=1).dropna(axis=1, how='any') ** 2,
'transform_derivative': lambda x: transform_derivative(x),
'sqrt': lambda x: numpy.sqrt(x),
'norm_mean': lambda x: x.divide(x.mean().mean()),
'abs': lambda x: x.abs(),
'square': lambda x: x.multiply(x),
} | 0.764496 | 0.723926 |
""" Turing machine internals testing module """
from __future__ import unicode_literals, print_function
from turing import (TMSyntaxError, TMLocked, tokenizer, raw_rule_generator,
sequence_cant_have, evaluate_symbol_query, TuringMachine)
from pytest import raises, mark
p = mark.parametrize
class TestTokenizer(object):
def test_simple_full_line_rule(self):
data = "q1 1 -> P0 R q2" # Newline token is always implicit
expected = ["q1", "1", "->", "P0", "R", "q2", "\n"]
assert list(tokenizer(data)) == expected
def test_three_full_line_rules(self):
data = (
"q1 1 -> P0 R q2\n"
"q2 0 -> P1 q2\n"
"q2 1 -> E L q1\n"
)
expected = [
"q1", "1", "->", "P0", "R", "q2", "\n",
"q2", "0", "->", "P1", "q2", "\n",
"q2", "1", "->", "E", "L", "q1", "\n",
]
assert list(tokenizer(data)) == expected
def test_simple_multiline_rule(self):
data = (
"q3 0 -> P1 R\n"
" P0 R q2\n"
)
expected = ["q3", "0", "->", "P1", "R", "P0", "R", "q2", "\n"]
assert list(tokenizer(data)) == expected
def test_no_token_at_all(self): # Empty files have a single token
assert list(tokenizer("\n\n\n")) == ["\n"] == \
list(tokenizer("")) == list(tokenizer("\n \n \n"))
def test_empty_lines(self):
data = (
"\n\nq312 0 -> P1 R\n\n\n"
" P0 L L q2\n\n"
)
expected = ["q312", "0", "->", "P1", "R", "P0", "L", "L", "q2", "\n"]
assert list(tokenizer(data)) == expected
def test_indent_arrow(self):
data = (
"q4 0 -> P1 R q3\n"
" 1 -> Px q4\n\n"
" x -> P0 L q3\n\n"
)
expected = [ # The space is an indent token
"q4", "0", "->", "P1", "R", "q3", "\n",
" ", "1", "->", "Px", "q4", "\n",
" ", "x", "->", "P0", "L", "q3", "\n",
]
assert list(tokenizer(data)) == expected
def test_single_mconf_in_first_line(self):
data = (
"A \n"
" b -> Pxx2 R E alpha\n"
)
expected = ["A", "b", "->", "Pxx2", "R", "E", "alpha", "\n",]
assert list(tokenizer(data)) == expected
def test_square_brackets_in_symbols(self):
data = (
"q1 \n"
" [0 4] -> Pinf R aba\n"
" [1 '2' 3] -> P-1 k\n"
" [xTj'c] -> P0\nç \n\n"
" - -> +"
)
expected = [ # The space is an indent token
"q1", "[", "0", "4", "]", "->", "Pinf", "R", "aba", "\n",
" ", "[", "1", "'2'", "3", "]", "->", "P-1", "k", "\n",
" ", "[", "xTj'c", "]", "->", "P0", "ç", "\n",
" ", "-", "->", "+", "\n",
]
assert list(tokenizer(data)) == expected
class TestRawRuleGenerator(object):
def test_no_rules(self):
assert list(raw_rule_generator("\n \n\n")) == [] == \
list(raw_rule_generator(""))
def test_one_rule(self):
rgen = raw_rule_generator("q1 1 -> P0 R q2")
assert next(rgen) == (["q1", "1"], ["P0", "R", "q2"])
with raises(StopIteration):
next(rgen)
def test_half_rule(self):
rgen = raw_rule_generator("q1 1")
with raises(TMSyntaxError):
next(rgen)
@p("rule", ["q1 1 ->", "-> q0"])
def test_one_and_a_half_rule_with_arrow(self, rule):
rgen = raw_rule_generator("q0 -> q1\n" + rule)
assert next(rgen) == (["q0"], ["q1"])
with raises(TMSyntaxError):
next(rgen)
@p("rule", [" ->", "->", "\n->", "->\n\n", "->\n\nq0 -> q1"])
def test_one_and_a_arrow_only_rule(self, rule):
rgen = raw_rule_generator("q1 1 -> E q0\n" + rule)
assert next(rgen) == (["q1", "1"], ["E", "q0"])
with raises(TMSyntaxError):
next(rgen)
def test_five_rules(self):
rgen = raw_rule_generator(
"q4 0 -> P1 R q3\n"
" 1 -> Px q4\n\n"
" x -> P0 L\n\n\n"
" P1 q3\n"
"q3 0 -> P1 q4\n"
" 1 -> P0 L q3"
)
assert next(rgen) == (["q4", "0"], ["P1", "R", "q3"])
assert next(rgen) == ([" ", "1"], ["Px", "q4"])
assert next(rgen) == ([" ", "x"], ["P0", "L", "P1", "q3"])
assert next(rgen) == (["q3", "0"], ["P1", "q4"])
assert next(rgen) == ([" ", "1"], ["P0", "L", "q3"])
with raises(StopIteration):
next(rgen)
class TestSequenceCantHave(object):
def test_empty_input(self):
func = sequence_cant_have()(lambda: [1, "2", sequence_cant_have])
assert func() == [1, "2", sequence_cant_have]
def test_empty_function_output(self):
func = sequence_cant_have("a", "Not")(lambda x: x)
assert func([]) == []
def test_empty_both_input_and_output(self):
assert sequence_cant_have()(lambda x: x)([]) == []
def test_occurrence(self):
data = ["a", "", self]
func = sequence_cant_have("Not", "Neither")(lambda: data)
assert func() == data
data.append("Neither")
with raises(TMSyntaxError):
func()
data.pop()
assert func() == data
data[1] = "Not"
with raises(TMSyntaxError):
func()
class TestEvaluateSymbolQuery(object):
@p("symb", ["a", "1", "noot", "_bad", "q1", "Ç", "That'sIt"])
def test_valid_one_symbol_scenarios(self, symb):
assert evaluate_symbol_query(symb) == ((symb,), True)
assert evaluate_symbol_query("Not", symb) == ((symb,), False)
def test_simple_multisymbol_without_repeat(self):
symbs = "abc defgh ijk lmnop qrs".split()
input_data = ["["] + symbs + ["]"]
expected = tuple(symbs)
assert evaluate_symbol_query(*input_data) == (expected, True)
assert evaluate_symbol_query("Not", *input_data) == (expected, False)
with raises(TMSyntaxError):
evaluate_symbol_query(*symbs)
with raises(TMSyntaxError):
evaluate_symbol_query("Not", *symbs)
@p("symbs", [("Not",), ("1", "Not"), ("ABC", "Not", "Neither")])
def test_not_twice_or_invalidly_alone(self, symbs):
with raises(TMSyntaxError):
evaluate_symbol_query(*symbs)
with raises(TMSyntaxError):
evaluate_symbol_query("Not", *symbs)
def test_empty_query(self):
assert evaluate_symbol_query() == (tuple(), False)
class TestTuringMachine(object):
def test_one_rule_no_tape(self):
tm = TuringMachine("q4 -> q3")
assert tm.mconf == "q4" # Default starting state is the first m-conf
tm.move()
assert tm.mconf == "q3"
with raises(TMLocked):
tm.move()
def test_two_rules_no_tape(self):
tm = TuringMachine("a -> b\nb None -> R c\n")
assert tm.mconf == "a"
tm.move()
assert tm.mconf == "b"
assert tm.scan() == "None"
tm.move()
assert tm.mconf == "c"
with raises(TMLocked):
tm.move()
def test_zero_one_zero_one(self):
tm = TuringMachine(
"a -> P0 R b\n"
"b -> P1 R a\n"
)
for unused in range(40):
assert tm.mconf == "a"
tm.move()
assert tm.mconf == "b"
tm.move()
tape = tm.tape
assert len(tape) == 80
for idx in range(80):
assert tape[idx] == str(idx % 2)
def test_turing_first_example(self):
tm1 = TuringMachine( # On p. 233 of his article
"b None -> P0 R c\n"
"c None -> R e\n"
"e None -> P1 R f\n"
"f None -> R b\n"
)
tm2 = TuringMachine( # On p. 234 of his article, the same idea
"b None -> P0 b\n"
" 0 -> R R P1 b\n"
" 1 -> R R P0 b\n"
)
assert tm1.mconf == tm2.mconf == "b"
assert tm1.index == tm2.index == 0
tm1.move() # Syncronizing them
tm2.move()
for idx in range(50):
assert tm2.mconf == "b"
assert tm1.index == 2 * idx + 1
tm1.move()
assert tm1.index == 2 * idx + 2
tm1.move()
assert tm1.index == 2 * idx + 3
assert tm2.index == 2 * idx
tm2.move()
assert tm2.index == 2 * idx + 2
assert tm1.tape == tm2.tape
tape = tm1.tape
tape_length = abs(max(tm1.tape) - min(tm1.tape))
assert tape_length == 100
for idx in range(100):
if idx % 2 == 0:
assert tape[idx] == str(idx // 2 % 2)
else:
assert idx not in tape # "None" | test_turing.py | """ Turing machine internals testing module """
from __future__ import unicode_literals, print_function
from turing import (TMSyntaxError, TMLocked, tokenizer, raw_rule_generator,
sequence_cant_have, evaluate_symbol_query, TuringMachine)
from pytest import raises, mark
p = mark.parametrize
class TestTokenizer(object):
def test_simple_full_line_rule(self):
data = "q1 1 -> P0 R q2" # Newline token is always implicit
expected = ["q1", "1", "->", "P0", "R", "q2", "\n"]
assert list(tokenizer(data)) == expected
def test_three_full_line_rules(self):
data = (
"q1 1 -> P0 R q2\n"
"q2 0 -> P1 q2\n"
"q2 1 -> E L q1\n"
)
expected = [
"q1", "1", "->", "P0", "R", "q2", "\n",
"q2", "0", "->", "P1", "q2", "\n",
"q2", "1", "->", "E", "L", "q1", "\n",
]
assert list(tokenizer(data)) == expected
def test_simple_multiline_rule(self):
data = (
"q3 0 -> P1 R\n"
" P0 R q2\n"
)
expected = ["q3", "0", "->", "P1", "R", "P0", "R", "q2", "\n"]
assert list(tokenizer(data)) == expected
def test_no_token_at_all(self): # Empty files have a single token
assert list(tokenizer("\n\n\n")) == ["\n"] == \
list(tokenizer("")) == list(tokenizer("\n \n \n"))
def test_empty_lines(self):
data = (
"\n\nq312 0 -> P1 R\n\n\n"
" P0 L L q2\n\n"
)
expected = ["q312", "0", "->", "P1", "R", "P0", "L", "L", "q2", "\n"]
assert list(tokenizer(data)) == expected
def test_indent_arrow(self):
data = (
"q4 0 -> P1 R q3\n"
" 1 -> Px q4\n\n"
" x -> P0 L q3\n\n"
)
expected = [ # The space is an indent token
"q4", "0", "->", "P1", "R", "q3", "\n",
" ", "1", "->", "Px", "q4", "\n",
" ", "x", "->", "P0", "L", "q3", "\n",
]
assert list(tokenizer(data)) == expected
def test_single_mconf_in_first_line(self):
data = (
"A \n"
" b -> Pxx2 R E alpha\n"
)
expected = ["A", "b", "->", "Pxx2", "R", "E", "alpha", "\n",]
assert list(tokenizer(data)) == expected
def test_square_brackets_in_symbols(self):
data = (
"q1 \n"
" [0 4] -> Pinf R aba\n"
" [1 '2' 3] -> P-1 k\n"
" [xTj'c] -> P0\nç \n\n"
" - -> +"
)
expected = [ # The space is an indent token
"q1", "[", "0", "4", "]", "->", "Pinf", "R", "aba", "\n",
" ", "[", "1", "'2'", "3", "]", "->", "P-1", "k", "\n",
" ", "[", "xTj'c", "]", "->", "P0", "ç", "\n",
" ", "-", "->", "+", "\n",
]
assert list(tokenizer(data)) == expected
class TestRawRuleGenerator(object):
def test_no_rules(self):
assert list(raw_rule_generator("\n \n\n")) == [] == \
list(raw_rule_generator(""))
def test_one_rule(self):
rgen = raw_rule_generator("q1 1 -> P0 R q2")
assert next(rgen) == (["q1", "1"], ["P0", "R", "q2"])
with raises(StopIteration):
next(rgen)
def test_half_rule(self):
rgen = raw_rule_generator("q1 1")
with raises(TMSyntaxError):
next(rgen)
@p("rule", ["q1 1 ->", "-> q0"])
def test_one_and_a_half_rule_with_arrow(self, rule):
rgen = raw_rule_generator("q0 -> q1\n" + rule)
assert next(rgen) == (["q0"], ["q1"])
with raises(TMSyntaxError):
next(rgen)
@p("rule", [" ->", "->", "\n->", "->\n\n", "->\n\nq0 -> q1"])
def test_one_and_a_arrow_only_rule(self, rule):
rgen = raw_rule_generator("q1 1 -> E q0\n" + rule)
assert next(rgen) == (["q1", "1"], ["E", "q0"])
with raises(TMSyntaxError):
next(rgen)
def test_five_rules(self):
rgen = raw_rule_generator(
"q4 0 -> P1 R q3\n"
" 1 -> Px q4\n\n"
" x -> P0 L\n\n\n"
" P1 q3\n"
"q3 0 -> P1 q4\n"
" 1 -> P0 L q3"
)
assert next(rgen) == (["q4", "0"], ["P1", "R", "q3"])
assert next(rgen) == ([" ", "1"], ["Px", "q4"])
assert next(rgen) == ([" ", "x"], ["P0", "L", "P1", "q3"])
assert next(rgen) == (["q3", "0"], ["P1", "q4"])
assert next(rgen) == ([" ", "1"], ["P0", "L", "q3"])
with raises(StopIteration):
next(rgen)
class TestSequenceCantHave(object):
def test_empty_input(self):
func = sequence_cant_have()(lambda: [1, "2", sequence_cant_have])
assert func() == [1, "2", sequence_cant_have]
def test_empty_function_output(self):
func = sequence_cant_have("a", "Not")(lambda x: x)
assert func([]) == []
def test_empty_both_input_and_output(self):
assert sequence_cant_have()(lambda x: x)([]) == []
def test_occurrence(self):
data = ["a", "", self]
func = sequence_cant_have("Not", "Neither")(lambda: data)
assert func() == data
data.append("Neither")
with raises(TMSyntaxError):
func()
data.pop()
assert func() == data
data[1] = "Not"
with raises(TMSyntaxError):
func()
class TestEvaluateSymbolQuery(object):
@p("symb", ["a", "1", "noot", "_bad", "q1", "Ç", "That'sIt"])
def test_valid_one_symbol_scenarios(self, symb):
assert evaluate_symbol_query(symb) == ((symb,), True)
assert evaluate_symbol_query("Not", symb) == ((symb,), False)
def test_simple_multisymbol_without_repeat(self):
symbs = "abc defgh ijk lmnop qrs".split()
input_data = ["["] + symbs + ["]"]
expected = tuple(symbs)
assert evaluate_symbol_query(*input_data) == (expected, True)
assert evaluate_symbol_query("Not", *input_data) == (expected, False)
with raises(TMSyntaxError):
evaluate_symbol_query(*symbs)
with raises(TMSyntaxError):
evaluate_symbol_query("Not", *symbs)
@p("symbs", [("Not",), ("1", "Not"), ("ABC", "Not", "Neither")])
def test_not_twice_or_invalidly_alone(self, symbs):
with raises(TMSyntaxError):
evaluate_symbol_query(*symbs)
with raises(TMSyntaxError):
evaluate_symbol_query("Not", *symbs)
def test_empty_query(self):
assert evaluate_symbol_query() == (tuple(), False)
class TestTuringMachine(object):
def test_one_rule_no_tape(self):
tm = TuringMachine("q4 -> q3")
assert tm.mconf == "q4" # Default starting state is the first m-conf
tm.move()
assert tm.mconf == "q3"
with raises(TMLocked):
tm.move()
def test_two_rules_no_tape(self):
tm = TuringMachine("a -> b\nb None -> R c\n")
assert tm.mconf == "a"
tm.move()
assert tm.mconf == "b"
assert tm.scan() == "None"
tm.move()
assert tm.mconf == "c"
with raises(TMLocked):
tm.move()
def test_zero_one_zero_one(self):
tm = TuringMachine(
"a -> P0 R b\n"
"b -> P1 R a\n"
)
for unused in range(40):
assert tm.mconf == "a"
tm.move()
assert tm.mconf == "b"
tm.move()
tape = tm.tape
assert len(tape) == 80
for idx in range(80):
assert tape[idx] == str(idx % 2)
def test_turing_first_example(self):
tm1 = TuringMachine( # On p. 233 of his article
"b None -> P0 R c\n"
"c None -> R e\n"
"e None -> P1 R f\n"
"f None -> R b\n"
)
tm2 = TuringMachine( # On p. 234 of his article, the same idea
"b None -> P0 b\n"
" 0 -> R R P1 b\n"
" 1 -> R R P0 b\n"
)
assert tm1.mconf == tm2.mconf == "b"
assert tm1.index == tm2.index == 0
tm1.move() # Syncronizing them
tm2.move()
for idx in range(50):
assert tm2.mconf == "b"
assert tm1.index == 2 * idx + 1
tm1.move()
assert tm1.index == 2 * idx + 2
tm1.move()
assert tm1.index == 2 * idx + 3
assert tm2.index == 2 * idx
tm2.move()
assert tm2.index == 2 * idx + 2
assert tm1.tape == tm2.tape
tape = tm1.tape
tape_length = abs(max(tm1.tape) - min(tm1.tape))
assert tape_length == 100
for idx in range(100):
if idx % 2 == 0:
assert tape[idx] == str(idx // 2 % 2)
else:
assert idx not in tape # "None" | 0.747063 | 0.645288 |
import glob
import threading
import subprocess
from pathlib import Path
from typing import *
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
from .utils import progress_save
EXTRACT_SCRIPT = (Path(__file__).parent / "extract.py").resolve()
assert EXTRACT_SCRIPT.exists()
def main():
with progress_save(visited=(set, list), failed_detail=(dict)) as (
visited,
failed_detail,
):
executor = None
p_bar = None
failed = set(failed_detail.keys())
processed = set()
try:
print("Counting files...")
files = set(glob.iglob("./**/truffle-config.js", recursive=True))
files -= failed
new_files = files - visited
print(f"We have {len(new_files)} new files")
write_lock = threading.Lock()
p_bar = tqdm(total=len(new_files))
TNPREFIX = "ilf"
DEFAULT_PORT = 8545
with ThreadPoolExecutor(max_workers=8, thread_name_prefix=TNPREFIX) as executor:
for _file in new_files:
def _closure(file):
t_name = threading.current_thread().name
t_id = int(t_name[len(TNPREFIX)+1:])
port = DEFAULT_PORT + t_id
truffle_file = Path(file).resolve()
root_dir = truffle_file.parent
cmd = subprocess.run(
f"python3 {EXTRACT_SCRIPT} --proj {root_dir} --port {port}".split(),
capture_output=True,
)
with write_lock:
p_bar.update(1)
if cmd.returncode != 0:
failed_detail[file] = cmd.stderr.decode("utf8")
failed.add(file)
p_bar.set_description(f"{root_dir.name} @ {t_id} FAILED", refresh=True)
else:
processed.add(file)
p_bar.set_description(f"{root_dir.name} @ {t_id} done", refresh=True)
executor.submit(_closure, _file)
except KeyboardInterrupt:
print()
print("Exiting gracefully... (let the threads finish)")
finally:
if executor:
executor.shutdown(cancel_futures=True)
if p_bar:
p_bar.close()
visited |= processed
if __name__ == "__main__":
main() | script/compile_all.py | import glob
import threading
import subprocess
from pathlib import Path
from typing import *
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
from .utils import progress_save
EXTRACT_SCRIPT = (Path(__file__).parent / "extract.py").resolve()
assert EXTRACT_SCRIPT.exists()
def main():
with progress_save(visited=(set, list), failed_detail=(dict)) as (
visited,
failed_detail,
):
executor = None
p_bar = None
failed = set(failed_detail.keys())
processed = set()
try:
print("Counting files...")
files = set(glob.iglob("./**/truffle-config.js", recursive=True))
files -= failed
new_files = files - visited
print(f"We have {len(new_files)} new files")
write_lock = threading.Lock()
p_bar = tqdm(total=len(new_files))
TNPREFIX = "ilf"
DEFAULT_PORT = 8545
with ThreadPoolExecutor(max_workers=8, thread_name_prefix=TNPREFIX) as executor:
for _file in new_files:
def _closure(file):
t_name = threading.current_thread().name
t_id = int(t_name[len(TNPREFIX)+1:])
port = DEFAULT_PORT + t_id
truffle_file = Path(file).resolve()
root_dir = truffle_file.parent
cmd = subprocess.run(
f"python3 {EXTRACT_SCRIPT} --proj {root_dir} --port {port}".split(),
capture_output=True,
)
with write_lock:
p_bar.update(1)
if cmd.returncode != 0:
failed_detail[file] = cmd.stderr.decode("utf8")
failed.add(file)
p_bar.set_description(f"{root_dir.name} @ {t_id} FAILED", refresh=True)
else:
processed.add(file)
p_bar.set_description(f"{root_dir.name} @ {t_id} done", refresh=True)
executor.submit(_closure, _file)
except KeyboardInterrupt:
print()
print("Exiting gracefully... (let the threads finish)")
finally:
if executor:
executor.shutdown(cancel_futures=True)
if p_bar:
p_bar.close()
visited |= processed
if __name__ == "__main__":
main() | 0.303938 | 0.163245 |
from smtplib import SMTP
from abc import ABCMeta, abstractmethod
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class EMailManager:
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
raise NotImplemented
@abstractmethod
def __enter__(self):
raise NotImplemented
@abstractmethod
def send(self, receiver_address: str, subject: str, message: str):
raise NotImplemented
@abstractmethod
def __exit__(self, exc_type, exc_val, exc_tb):
raise NotImplemented
class TLSEMailManager(EMailManager):
def __init__(self, server_uri, server_port, sender_address, sender_pass):
self.__server_uri = server_uri
self.__server_port = server_port
self.__sender_address = sender_address
self.__sender_pass = <PASSWORD>pass
def __enter__(self):
self.__session = SMTP(self.__server_uri, self.__server_port) # FIXME pull out
self.__session.starttls()
self.__session.login(self.__sender_address, self.__sender_pass)
def send(self, receiver_address: str, subject: str, content: str): # FIXME pull out
message = MIMEMultipart()
message['From'] = self.__sender_address
message['To'] = receiver_address
message['Subject'] = subject
message.attach(MIMEText(content, 'plain'))
mail = message.as_string()
self.__session.sendmail(self.__sender_address, receiver_address, mail)
def __exit__(self, exc_type, exc_val, exc_tb):
self.__session.quit()
class Notifier:
__metaclass__ = ABCMeta
@abstractmethod
def notify(self, title: str, message: str):
raise NotImplemented
class EMailNotifier(Notifier):
def __init__(self, email_manager: EMailManager) -> None:
self.__email_manager = email_manager
def notify(self, title: str, content: str):
subject = self.__build_subject()
content = self.__build_content()
with self.__email_manager as manager:
manager.send('', subject, content)
def __build_subject(self):
pass
def __build_content(self):
pass | notifier.py | from smtplib import SMTP
from abc import ABCMeta, abstractmethod
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class EMailManager:
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
raise NotImplemented
@abstractmethod
def __enter__(self):
raise NotImplemented
@abstractmethod
def send(self, receiver_address: str, subject: str, message: str):
raise NotImplemented
@abstractmethod
def __exit__(self, exc_type, exc_val, exc_tb):
raise NotImplemented
class TLSEMailManager(EMailManager):
def __init__(self, server_uri, server_port, sender_address, sender_pass):
self.__server_uri = server_uri
self.__server_port = server_port
self.__sender_address = sender_address
self.__sender_pass = <PASSWORD>pass
def __enter__(self):
self.__session = SMTP(self.__server_uri, self.__server_port) # FIXME pull out
self.__session.starttls()
self.__session.login(self.__sender_address, self.__sender_pass)
def send(self, receiver_address: str, subject: str, content: str): # FIXME pull out
message = MIMEMultipart()
message['From'] = self.__sender_address
message['To'] = receiver_address
message['Subject'] = subject
message.attach(MIMEText(content, 'plain'))
mail = message.as_string()
self.__session.sendmail(self.__sender_address, receiver_address, mail)
def __exit__(self, exc_type, exc_val, exc_tb):
self.__session.quit()
class Notifier:
__metaclass__ = ABCMeta
@abstractmethod
def notify(self, title: str, message: str):
raise NotImplemented
class EMailNotifier(Notifier):
def __init__(self, email_manager: EMailManager) -> None:
self.__email_manager = email_manager
def notify(self, title: str, content: str):
subject = self.__build_subject()
content = self.__build_content()
with self.__email_manager as manager:
manager.send('', subject, content)
def __build_subject(self):
pass
def __build_content(self):
pass | 0.474875 | 0.084568 |
import pygame
from pygame.locals import *
from snake_classes import *
from constantes import *
import time
global t0
t0 = time.time()
pygame.init()
fenetre = pygame.display.set_mode((window_side,window_side+50))
fenetre.fill(WHITE)
pygame.display.set_caption(titre_fenetre)
grid = Grid(fenetre)
grid.display()
snake = Snake(fenetre)
snake.draw_rect()
souris = Souris(fenetre,3)
souris.display_souris()
font = pygame.font.SysFont("comicsansms",12)
text = font.render("Your score : 0", True, BLACK)
fenetre.blit(text,(0,window_side))
pygame.display.flip()
#pygame.key.set_repeat(400,30)
continuer = 1
while continuer:
pygame.time.Clock().tick(30)
fenetre.fill(WHITE)
grid.display()
souris.update_mice()
souris.display_souris()
snake.draw_rect()
text = font.render("Your score : {}".format(snake.get_score()), True, BLACK)
fenetre.blit(text, (0, window_side))
pygame.display.flip()
if time.time()-t0 >= time_gap :
t0 = time.time()
snake.move(snake.get_direction())
for event in pygame.event.get():
if event.type == QUIT :
continuer = 0
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
continuer = 0
elif event.key == K_RIGHT:
snake.move('right')
t0 = time.time()
elif event.key == K_LEFT:
snake.move('left')
t0 = time.time()
elif event.key == K_UP:
snake.move('up')
t0 = time.time()
elif event.key == K_DOWN:
snake.move('down')
t0 = time.time()
break
if souris.is_mouse(snake.get_last_coordonnees()):
snake.increase_score()
souris.delete_mouse(snake.get_last_coordonnees())
snake.add_square()
souris.new_mouse(snake.get_coordonnees())
t0 = time.time()
if snake.eat_tail():
continuer = 2
while continuer == 2:
pygame.time.Clock().tick(30)
fenetre.fill(WHITE)
grid.display()
snake.draw_rect()
souris.display_souris()
text = font.render("Your dead !! Press space key to play again".format(snake.get_score()), True, BLACK)
fenetre.blit(text, (0, window_side))
pygame.display.flip()
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
continuer = 0
elif (event.type == KEYDOWN and event.key == K_SPACE):
snake.reboot()
continuer = 1 | Snake.py | import pygame
from pygame.locals import *
from snake_classes import *
from constantes import *
import time
global t0
t0 = time.time()
pygame.init()
fenetre = pygame.display.set_mode((window_side,window_side+50))
fenetre.fill(WHITE)
pygame.display.set_caption(titre_fenetre)
grid = Grid(fenetre)
grid.display()
snake = Snake(fenetre)
snake.draw_rect()
souris = Souris(fenetre,3)
souris.display_souris()
font = pygame.font.SysFont("comicsansms",12)
text = font.render("Your score : 0", True, BLACK)
fenetre.blit(text,(0,window_side))
pygame.display.flip()
#pygame.key.set_repeat(400,30)
continuer = 1
while continuer:
pygame.time.Clock().tick(30)
fenetre.fill(WHITE)
grid.display()
souris.update_mice()
souris.display_souris()
snake.draw_rect()
text = font.render("Your score : {}".format(snake.get_score()), True, BLACK)
fenetre.blit(text, (0, window_side))
pygame.display.flip()
if time.time()-t0 >= time_gap :
t0 = time.time()
snake.move(snake.get_direction())
for event in pygame.event.get():
if event.type == QUIT :
continuer = 0
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
continuer = 0
elif event.key == K_RIGHT:
snake.move('right')
t0 = time.time()
elif event.key == K_LEFT:
snake.move('left')
t0 = time.time()
elif event.key == K_UP:
snake.move('up')
t0 = time.time()
elif event.key == K_DOWN:
snake.move('down')
t0 = time.time()
break
if souris.is_mouse(snake.get_last_coordonnees()):
snake.increase_score()
souris.delete_mouse(snake.get_last_coordonnees())
snake.add_square()
souris.new_mouse(snake.get_coordonnees())
t0 = time.time()
if snake.eat_tail():
continuer = 2
while continuer == 2:
pygame.time.Clock().tick(30)
fenetre.fill(WHITE)
grid.display()
snake.draw_rect()
souris.display_souris()
text = font.render("Your dead !! Press space key to play again".format(snake.get_score()), True, BLACK)
fenetre.blit(text, (0, window_side))
pygame.display.flip()
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
continuer = 0
elif (event.type == KEYDOWN and event.key == K_SPACE):
snake.reboot()
continuer = 1 | 0.206334 | 0.169372 |
from ..constants import (
COLOR_CANVAS_DARK,
COLOR_CANVAS_LIGHT,
COLOR_GRID_LIGHT,
COLOR_GRID_DARK,
COLOR_PLOT_TEXT_LIGHT,
COLOR_PLOT_TEXT_DARK,
COLOR_SLIDER_BORDER_DARK,
COLOR_SLIDER_BORDER_LIGHT,
COLOR_SLIDER_TICK_DARK,
COLOR_SLIDER_TICK_LIGHT,
COLOR_ZERO_LINE_LIGHT,
COLOR_ZERO_LINE_DARK,
PLOT_HEIGHT,
PLOT_HEIGHT_NOTEBOOK,
PLOT_MARGIN,
PLOT_MARGIN_NOTEBOOK,
PLOT_SLIDER_PADDING,
PLOT_SLIDER_PADDING_NOTEBOOK,
PLOT_WIDTH,
PLOT_WIDTH_NOTEBOOK,
)
def fetch_plot_colors(dark_mode: bool):
"""Fetch correct colors scheme for plotly plots.
Parameters
----------
dark_mode : bool
Specifies whether dark mode should be implemented
"""
if dark_mode:
return COLOR_CANVAS_DARK, COLOR_PLOT_TEXT_DARK, COLOR_GRID_DARK, \
COLOR_ZERO_LINE_DARK
return COLOR_CANVAS_LIGHT, COLOR_PLOT_TEXT_LIGHT, COLOR_GRID_LIGHT, \
COLOR_ZERO_LINE_LIGHT
def fetch_slider_colors(dark_mode: bool):
"""Fetch correct colors scheme for plotly sliders.
Parameters
----------
dark_mode : bool
Specifies whether dark mode should be implemented
"""
if dark_mode:
return COLOR_PLOT_TEXT_DARK, COLOR_SLIDER_TICK_DARK, \
COLOR_SLIDER_BORDER_DARK,
return COLOR_PLOT_TEXT_LIGHT, COLOR_SLIDER_TICK_LIGHT, \
COLOR_SLIDER_BORDER_LIGHT
def fetch_plot_size(notebook_mode: bool):
"""Fetch correct plot size for plotly plots.
Parameters
----------
notebook_mode : bool
specifies whether plot size should be optimized for notebooks
"""
if notebook_mode:
return PLOT_HEIGHT_NOTEBOOK, PLOT_WIDTH_NOTEBOOK
return PLOT_HEIGHT, PLOT_WIDTH
def fetch_plot_margin(notebook_mode: bool):
"""Fetch correct margins for plotly plots.
Parameters
----------
notebook_mode : bool
Specifies whether plot margins should be optimized for notebooks
"""
if notebook_mode:
return PLOT_MARGIN_NOTEBOOK
return PLOT_MARGIN
def fetch_slider_padding(notebook_mode: bool):
"""Fetch correct slider margins for plot procedure.
Parameters
----------
notebook_mode : bool
Specifies whether the slider padding should be optimized for notebooks
"""
if notebook_mode:
return PLOT_SLIDER_PADDING_NOTEBOOK
return PLOT_SLIDER_PADDING | src/pyskindose/plotting/plot_settings.py | from ..constants import (
COLOR_CANVAS_DARK,
COLOR_CANVAS_LIGHT,
COLOR_GRID_LIGHT,
COLOR_GRID_DARK,
COLOR_PLOT_TEXT_LIGHT,
COLOR_PLOT_TEXT_DARK,
COLOR_SLIDER_BORDER_DARK,
COLOR_SLIDER_BORDER_LIGHT,
COLOR_SLIDER_TICK_DARK,
COLOR_SLIDER_TICK_LIGHT,
COLOR_ZERO_LINE_LIGHT,
COLOR_ZERO_LINE_DARK,
PLOT_HEIGHT,
PLOT_HEIGHT_NOTEBOOK,
PLOT_MARGIN,
PLOT_MARGIN_NOTEBOOK,
PLOT_SLIDER_PADDING,
PLOT_SLIDER_PADDING_NOTEBOOK,
PLOT_WIDTH,
PLOT_WIDTH_NOTEBOOK,
)
def fetch_plot_colors(dark_mode: bool):
"""Fetch correct colors scheme for plotly plots.
Parameters
----------
dark_mode : bool
Specifies whether dark mode should be implemented
"""
if dark_mode:
return COLOR_CANVAS_DARK, COLOR_PLOT_TEXT_DARK, COLOR_GRID_DARK, \
COLOR_ZERO_LINE_DARK
return COLOR_CANVAS_LIGHT, COLOR_PLOT_TEXT_LIGHT, COLOR_GRID_LIGHT, \
COLOR_ZERO_LINE_LIGHT
def fetch_slider_colors(dark_mode: bool):
"""Fetch correct colors scheme for plotly sliders.
Parameters
----------
dark_mode : bool
Specifies whether dark mode should be implemented
"""
if dark_mode:
return COLOR_PLOT_TEXT_DARK, COLOR_SLIDER_TICK_DARK, \
COLOR_SLIDER_BORDER_DARK,
return COLOR_PLOT_TEXT_LIGHT, COLOR_SLIDER_TICK_LIGHT, \
COLOR_SLIDER_BORDER_LIGHT
def fetch_plot_size(notebook_mode: bool):
"""Fetch correct plot size for plotly plots.
Parameters
----------
notebook_mode : bool
specifies whether plot size should be optimized for notebooks
"""
if notebook_mode:
return PLOT_HEIGHT_NOTEBOOK, PLOT_WIDTH_NOTEBOOK
return PLOT_HEIGHT, PLOT_WIDTH
def fetch_plot_margin(notebook_mode: bool):
"""Fetch correct margins for plotly plots.
Parameters
----------
notebook_mode : bool
Specifies whether plot margins should be optimized for notebooks
"""
if notebook_mode:
return PLOT_MARGIN_NOTEBOOK
return PLOT_MARGIN
def fetch_slider_padding(notebook_mode: bool):
"""Fetch correct slider margins for plot procedure.
Parameters
----------
notebook_mode : bool
Specifies whether the slider padding should be optimized for notebooks
"""
if notebook_mode:
return PLOT_SLIDER_PADDING_NOTEBOOK
return PLOT_SLIDER_PADDING | 0.778776 | 0.18866 |
from datetime import datetime, timedelta
from flask import Blueprint, current_app, abort, request, jsonify
from flask_jwt_extended import (
create_access_token, jwt_required, jwt_optional, get_jwt_identity)
from .. import db
from ..models import User
from ..providers import ProviderError
from ..utils import validation_required
module = Blueprint('auth', __name__, url_prefix='/auth')
@module.route('/providers', methods=['GET'])
def providers():
"""
Providers list
.. :quickref: auth; Retrieve providers list
**Request**:
.. sourcecode:: http
GET /auth/providers HTTP/1.1
**Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
[
"provider_one",
"provider_two"
]
:statuscode 200: OK
:statuscode 500: unexpected errors
"""
return jsonify([key for key in current_app.providers.keys()])
@module.route('/<provider_name>', methods=['GET'])
def redirect(provider_name):
"""
Returns URL for redirect user to provider's auth page
.. :quickref: auth; Retrieve redirect URL to provider's auth page
**Request**:
.. sourcecode:: http
GET /auth/<provider_name> HTTP/1.1
**Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"redirect": "http://<provider's_auth_page>"
}
:statuscode 200: OK
:statuscode 500: unexpected errors
:statuscode 503: provider errors
"""
provider = current_app.providers.get(provider_name.lower(), None)
if not provider:
return abort(404, 'Provider not found')
return jsonify(redirect=provider.redirect())
@module.route('/<provider_name>', methods=['POST'])
@jwt_optional
@validation_required({'code': {'type': 'string', 'required': True}})
def login(provider_name):
"""
Log-in user, returns JWT token for signing future requests
to protected routes.
.. :quickref: auth; Retrieve JWT token to access protected routes
**Request**:
.. sourcecode:: http
POST /auth/<provider_name> HTTP/1.1
Content-Type: application/json
{
"code": "qwerty"
}
**Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"token": "<PASSWORD>"
}
:reqjson string code: authorization code from callback
:statuscode 200: OK
:statuscode 400: invalid JSON in request's body
:statuscode 401: auth errors
:statuscode 500: unexpected errors
:statuscode 503: provider errors
"""
try:
provider = current_app.providers.get(provider_name.lower(), None)
if not provider:
current_app.logger.warning(f'Provider [{provider_name}] not found')
return abort(404, 'Provider not found')
code = request.get_json()['code']
ids = provider.tokenize(code, refresh=False)
identity = provider.identity(ids['access_token'])
user = User.query.filter_by(
uniq=identity, provider=provider.name).first()
if not user:
user = User(uniq=identity, provider=provider.name)
user.access = ids['access_token']
user.refresh = ids['refresh_token']
user.expires = datetime.utcnow() + timedelta(seconds=ids['expires_in'])
db.session.add(user)
db.session.commit()
except ProviderError as e:
current_app.logger.error(f'Login error: {e}')
return abort(503, 'Provider error')
else:
current_app.logger.info(f'Logged in: {user}')
return jsonify(token=create_access_token(user.id))
@module.route('/refresh', methods=['GET'])
@jwt_required
def refresh():
"""
Returns new JWT token with fresh expiration date
.. :quickref: auth; Refresh exists JWT token (reset TTL)
**Request**:
.. sourcecode:: http
GET /auth/refresh HTTP/1.1
Authorization: JWT <PASSWORD>
**Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"token": "<PASSWORD>"
}
:reqheader Authorization: valid JWT token
:statuscode 200: OK
:statuscode 401: auth errors
:statuscode 500: unexpected errors
"""
user_id = get_jwt_identity()
token = create_access_token(user_id)
return jsonify(token=token) | app/controllers/auth.py | from datetime import datetime, timedelta
from flask import Blueprint, current_app, abort, request, jsonify
from flask_jwt_extended import (
create_access_token, jwt_required, jwt_optional, get_jwt_identity)
from .. import db
from ..models import User
from ..providers import ProviderError
from ..utils import validation_required
module = Blueprint('auth', __name__, url_prefix='/auth')
@module.route('/providers', methods=['GET'])
def providers():
"""
Providers list
.. :quickref: auth; Retrieve providers list
**Request**:
.. sourcecode:: http
GET /auth/providers HTTP/1.1
**Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
[
"provider_one",
"provider_two"
]
:statuscode 200: OK
:statuscode 500: unexpected errors
"""
return jsonify([key for key in current_app.providers.keys()])
@module.route('/<provider_name>', methods=['GET'])
def redirect(provider_name):
"""
Returns URL for redirect user to provider's auth page
.. :quickref: auth; Retrieve redirect URL to provider's auth page
**Request**:
.. sourcecode:: http
GET /auth/<provider_name> HTTP/1.1
**Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"redirect": "http://<provider's_auth_page>"
}
:statuscode 200: OK
:statuscode 500: unexpected errors
:statuscode 503: provider errors
"""
provider = current_app.providers.get(provider_name.lower(), None)
if not provider:
return abort(404, 'Provider not found')
return jsonify(redirect=provider.redirect())
@module.route('/<provider_name>', methods=['POST'])
@jwt_optional
@validation_required({'code': {'type': 'string', 'required': True}})
def login(provider_name):
"""
Log-in user, returns JWT token for signing future requests
to protected routes.
.. :quickref: auth; Retrieve JWT token to access protected routes
**Request**:
.. sourcecode:: http
POST /auth/<provider_name> HTTP/1.1
Content-Type: application/json
{
"code": "qwerty"
}
**Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"token": "<PASSWORD>"
}
:reqjson string code: authorization code from callback
:statuscode 200: OK
:statuscode 400: invalid JSON in request's body
:statuscode 401: auth errors
:statuscode 500: unexpected errors
:statuscode 503: provider errors
"""
try:
provider = current_app.providers.get(provider_name.lower(), None)
if not provider:
current_app.logger.warning(f'Provider [{provider_name}] not found')
return abort(404, 'Provider not found')
code = request.get_json()['code']
ids = provider.tokenize(code, refresh=False)
identity = provider.identity(ids['access_token'])
user = User.query.filter_by(
uniq=identity, provider=provider.name).first()
if not user:
user = User(uniq=identity, provider=provider.name)
user.access = ids['access_token']
user.refresh = ids['refresh_token']
user.expires = datetime.utcnow() + timedelta(seconds=ids['expires_in'])
db.session.add(user)
db.session.commit()
except ProviderError as e:
current_app.logger.error(f'Login error: {e}')
return abort(503, 'Provider error')
else:
current_app.logger.info(f'Logged in: {user}')
return jsonify(token=create_access_token(user.id))
@module.route('/refresh', methods=['GET'])
@jwt_required
def refresh():
"""
Returns new JWT token with fresh expiration date
.. :quickref: auth; Refresh exists JWT token (reset TTL)
**Request**:
.. sourcecode:: http
GET /auth/refresh HTTP/1.1
Authorization: JWT <PASSWORD>
**Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"token": "<PASSWORD>"
}
:reqheader Authorization: valid JWT token
:statuscode 200: OK
:statuscode 401: auth errors
:statuscode 500: unexpected errors
"""
user_id = get_jwt_identity()
token = create_access_token(user_id)
return jsonify(token=token) | 0.652241 | 0.101278 |
from __future__ import unicode_literals
from django.db import migrations, models
import assets.asset_helpers
import django.core.files.storage
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Asset',
fields=[
('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
('name', models.CharField(null=True, max_length=100, blank=True)),
('delete_file_with_record',
models.BooleanField(default=True, help_text='This will delete the file if this asset is deleted')),
('file', models.FileField(upload_to=assets.asset_helpers.generate_asset_file_name)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='AssetType',
fields=[
('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
('type_of_asset', models.CharField(max_length=30)),
],
),
migrations.CreateModel(
name='SecureAsset',
fields=[
('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
('name', models.CharField(null=True, max_length=100, blank=True)),
('delete_file_with_record',
models.BooleanField(default=True, help_text='This will delete the file if this asset is deleted')),
('file', models.FileField(upload_to=assets.asset_helpers.generate_asset_file_name,
storage=django.core.files.storage.FileSystemStorage(
base_url='/secure_asset',
location='/home/geomemes/cedar_media_secure'))),
('asset_type', models.ForeignKey(to='assets.AssetType')),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='asset',
name='asset_type',
field=models.ForeignKey(to='assets.AssetType'),
),
] | assets/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
import assets.asset_helpers
import django.core.files.storage
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Asset',
fields=[
('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
('name', models.CharField(null=True, max_length=100, blank=True)),
('delete_file_with_record',
models.BooleanField(default=True, help_text='This will delete the file if this asset is deleted')),
('file', models.FileField(upload_to=assets.asset_helpers.generate_asset_file_name)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='AssetType',
fields=[
('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
('type_of_asset', models.CharField(max_length=30)),
],
),
migrations.CreateModel(
name='SecureAsset',
fields=[
('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),
('name', models.CharField(null=True, max_length=100, blank=True)),
('delete_file_with_record',
models.BooleanField(default=True, help_text='This will delete the file if this asset is deleted')),
('file', models.FileField(upload_to=assets.asset_helpers.generate_asset_file_name,
storage=django.core.files.storage.FileSystemStorage(
base_url='/secure_asset',
location='/home/geomemes/cedar_media_secure'))),
('asset_type', models.ForeignKey(to='assets.AssetType')),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='asset',
name='asset_type',
field=models.ForeignKey(to='assets.AssetType'),
),
] | 0.524151 | 0.121113 |
from aliyunsdkcore.request import RpcRequest
from aliyunsdkvpc.endpoint import endpoint_data
class ListVirtualPhysicalConnectionsRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Vpc', '2016-04-28', 'ListVirtualPhysicalConnections','vpc')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_VlanIdss(self):
return self.get_query_params().get('VlanIds')
def set_VlanIdss(self, VlanIdss):
for depth1 in range(len(VlanIdss)):
if VlanIdss[depth1] is not None:
self.add_query_param('VlanIds.' + str(depth1 + 1) , VlanIdss[depth1])
def get_VirtualPhysicalConnectionBusinessStatus(self):
return self.get_query_params().get('VirtualPhysicalConnectionBusinessStatus')
def set_VirtualPhysicalConnectionBusinessStatus(self,VirtualPhysicalConnectionBusinessStatus):
self.add_query_param('VirtualPhysicalConnectionBusinessStatus',VirtualPhysicalConnectionBusinessStatus)
def get_VirtualPhysicalConnectionAliUidss(self):
return self.get_query_params().get('VirtualPhysicalConnectionAliUids')
def set_VirtualPhysicalConnectionAliUidss(self, VirtualPhysicalConnectionAliUidss):
for depth1 in range(len(VirtualPhysicalConnectionAliUidss)):
if VirtualPhysicalConnectionAliUidss[depth1] is not None:
self.add_query_param('VirtualPhysicalConnectionAliUids.' + str(depth1 + 1) , VirtualPhysicalConnectionAliUidss[depth1])
def get_NextToken(self):
return self.get_query_params().get('NextToken')
def set_NextToken(self,NextToken):
self.add_query_param('NextToken',NextToken)
def get_VirtualPhysicalConnectionIdss(self):
return self.get_query_params().get('VirtualPhysicalConnectionIds')
def set_VirtualPhysicalConnectionIdss(self, VirtualPhysicalConnectionIdss):
for depth1 in range(len(VirtualPhysicalConnectionIdss)):
if VirtualPhysicalConnectionIdss[depth1] is not None:
self.add_query_param('VirtualPhysicalConnectionIds.' + str(depth1 + 1) , VirtualPhysicalConnectionIdss[depth1])
def get_IsConfirmed(self):
return self.get_query_params().get('IsConfirmed')
def set_IsConfirmed(self,IsConfirmed):
self.add_query_param('IsConfirmed',IsConfirmed)
def get_VirtualPhysicalConnectionStatusess(self):
return self.get_query_params().get('VirtualPhysicalConnectionStatuses')
def set_VirtualPhysicalConnectionStatusess(self, VirtualPhysicalConnectionStatusess):
for depth1 in range(len(VirtualPhysicalConnectionStatusess)):
if VirtualPhysicalConnectionStatusess[depth1] is not None:
self.add_query_param('VirtualPhysicalConnectionStatuses.' + str(depth1 + 1) , VirtualPhysicalConnectionStatusess[depth1])
def get_PhysicalConnectionId(self):
return self.get_query_params().get('PhysicalConnectionId')
def set_PhysicalConnectionId(self,PhysicalConnectionId):
self.add_query_param('PhysicalConnectionId',PhysicalConnectionId)
def get_MaxResults(self):
return self.get_query_params().get('MaxResults')
def set_MaxResults(self,MaxResults):
self.add_query_param('MaxResults',MaxResults) | aliyun-python-sdk-vpc/aliyunsdkvpc/request/v20160428/ListVirtualPhysicalConnectionsRequest.py |
from aliyunsdkcore.request import RpcRequest
from aliyunsdkvpc.endpoint import endpoint_data
class ListVirtualPhysicalConnectionsRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Vpc', '2016-04-28', 'ListVirtualPhysicalConnections','vpc')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_VlanIdss(self):
return self.get_query_params().get('VlanIds')
def set_VlanIdss(self, VlanIdss):
for depth1 in range(len(VlanIdss)):
if VlanIdss[depth1] is not None:
self.add_query_param('VlanIds.' + str(depth1 + 1) , VlanIdss[depth1])
def get_VirtualPhysicalConnectionBusinessStatus(self):
return self.get_query_params().get('VirtualPhysicalConnectionBusinessStatus')
def set_VirtualPhysicalConnectionBusinessStatus(self,VirtualPhysicalConnectionBusinessStatus):
self.add_query_param('VirtualPhysicalConnectionBusinessStatus',VirtualPhysicalConnectionBusinessStatus)
def get_VirtualPhysicalConnectionAliUidss(self):
return self.get_query_params().get('VirtualPhysicalConnectionAliUids')
def set_VirtualPhysicalConnectionAliUidss(self, VirtualPhysicalConnectionAliUidss):
for depth1 in range(len(VirtualPhysicalConnectionAliUidss)):
if VirtualPhysicalConnectionAliUidss[depth1] is not None:
self.add_query_param('VirtualPhysicalConnectionAliUids.' + str(depth1 + 1) , VirtualPhysicalConnectionAliUidss[depth1])
def get_NextToken(self):
return self.get_query_params().get('NextToken')
def set_NextToken(self,NextToken):
self.add_query_param('NextToken',NextToken)
def get_VirtualPhysicalConnectionIdss(self):
return self.get_query_params().get('VirtualPhysicalConnectionIds')
def set_VirtualPhysicalConnectionIdss(self, VirtualPhysicalConnectionIdss):
for depth1 in range(len(VirtualPhysicalConnectionIdss)):
if VirtualPhysicalConnectionIdss[depth1] is not None:
self.add_query_param('VirtualPhysicalConnectionIds.' + str(depth1 + 1) , VirtualPhysicalConnectionIdss[depth1])
def get_IsConfirmed(self):
return self.get_query_params().get('IsConfirmed')
def set_IsConfirmed(self,IsConfirmed):
self.add_query_param('IsConfirmed',IsConfirmed)
def get_VirtualPhysicalConnectionStatusess(self):
return self.get_query_params().get('VirtualPhysicalConnectionStatuses')
def set_VirtualPhysicalConnectionStatusess(self, VirtualPhysicalConnectionStatusess):
for depth1 in range(len(VirtualPhysicalConnectionStatusess)):
if VirtualPhysicalConnectionStatusess[depth1] is not None:
self.add_query_param('VirtualPhysicalConnectionStatuses.' + str(depth1 + 1) , VirtualPhysicalConnectionStatusess[depth1])
def get_PhysicalConnectionId(self):
return self.get_query_params().get('PhysicalConnectionId')
def set_PhysicalConnectionId(self,PhysicalConnectionId):
self.add_query_param('PhysicalConnectionId',PhysicalConnectionId)
def get_MaxResults(self):
return self.get_query_params().get('MaxResults')
def set_MaxResults(self,MaxResults):
self.add_query_param('MaxResults',MaxResults) | 0.387459 | 0.052887 |
import scrapy
import time
import psycopg2
import json
import requests
from scrapy_djangoitem import DjangoItem
from home.models import Publisher
from scrapy_djangoitem import DjangoItem
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
#Connect to the DB
conn = psycopg2.connect(database="d22i0kdtb07bvn", user = "sdibkoceylgpfh", \
password = "<PASSWORD>", \
host = "ec2-54-228-255-234.eu-west-1.compute.amazonaws.com", port = "5432")
cur = conn.cursor()
cur.execute("SELECT * FROM public.stoyo_data1")
rows = cur.fetchall()
#define header
headers = {'content-type' : 'application/json'}
#define the API endpoint
video = 'http://127.0.0.1:8000/home/publisher/'
dbLinkList = []
i = cur.rowcount
for i in range(0,i):
dbLinkList.append(rows[i][2])
listPage = []
listViews = []
listLinks = []
listTitle = []
listFinal = []
attempts = 0
def init_driver():
driver = webdriver.Firefox()
driver.wait = WebDriverWait(driver, 5)
return driver
#Look for the elements to enable the program to connect to Facebook
def lookup(driver, email, password):
driver.get("https://www.facebook.com")
try:
box1 = driver.wait.until(EC.presence_of_element_located(
(By.NAME, "email")))
box2 = driver.wait.until(EC.presence_of_element_located(
(By.NAME, "pass")))
button = driver.wait.until(EC.element_to_be_clickable(
(By.ID, "loginbutton")))
box1.send_keys(email)
box2.send_keys(password)
button.click()
except TimeoutException:
print("Box or Button not found in facebook.com")
#Define the items to crawl
class PublisherItem(DjangoItem):
django_model = Publisher
#Define the behavior of the spider
class ProductSpider(scrapy.Spider):
name = "dbcrawl"
allowed_domains = ['facebook.com']
f = open("pub.txt")
start_urls = [url.strip() for url in f.readlines()]
#Connect to Facebook
driver = init_driver()
lookup(driver, "<EMAIL>", "Bouffegratos12")
time.sleep(5)
def __init__(self):
self.driver
def parse(self, response):
self.driver.get(response.url)
pub = PublisherItem()
attemps = 0
#50 attempts is 600 videos back. 60 seems to be optimal
while attemps < 10:
self.driver.implicitly_wait(10)
try:
self.driver.implicitly_wait(10)
more = self.driver.find_element_by_xpath('//div[@class="_3v4j"]/div[@class="clearfix uiMorePager stat_elem _52jv"]')
more.click()
#print self.driver.find_element_by_xpath('//div[@class="_3v4h _50f3 _50f7"]/a/@href')
attemps += 1
#print attemps
except:
break
#myfile = open('links.txt', 'w')
page = self.driver.find_element_by_xpath('//title').text
views = self.driver.find_elements_by_xpath('//div[@class="_u3y"]/div[@class="_3v4i"]/div[@class="fsm fwn fcg"]')
elements = self.driver.find_elements_by_xpath('//div[@class="_u3y"]/div[@class="_3v4h _50f3 _50f7"]/a')
print('Length of elements: {}'.format(len(elements)))
for element in elements:
try:
listTitle.append((element.text).encode("utf-8"))
listLinks.append((element.get_attribute('href')).encode("utf-8"))
listPage.append((page).encode("utf-8"))
except:
print("Not conform")
#save the list in the DB
for i in range(0,len(listTitle)):
info = {
'title': listTitle[i],
'link': listLinks[i],
'page_name': listPage[i],
}
resp = requests.post(video,data=json.dumps(info), headers=headers)
print('Video imported: {}'.format(resp)) | facebbok/facebbok/spiders/FBCrawlerWithDBCheck.py |
import scrapy
import time
import psycopg2
import json
import requests
from scrapy_djangoitem import DjangoItem
from home.models import Publisher
from scrapy_djangoitem import DjangoItem
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
#Connect to the DB
conn = psycopg2.connect(database="d22i0kdtb07bvn", user = "sdibkoceylgpfh", \
password = "<PASSWORD>", \
host = "ec2-54-228-255-234.eu-west-1.compute.amazonaws.com", port = "5432")
cur = conn.cursor()
cur.execute("SELECT * FROM public.stoyo_data1")
rows = cur.fetchall()
#define header
headers = {'content-type' : 'application/json'}
#define the API endpoint
video = 'http://127.0.0.1:8000/home/publisher/'
dbLinkList = []
i = cur.rowcount
for i in range(0,i):
dbLinkList.append(rows[i][2])
listPage = []
listViews = []
listLinks = []
listTitle = []
listFinal = []
attempts = 0
def init_driver():
driver = webdriver.Firefox()
driver.wait = WebDriverWait(driver, 5)
return driver
#Look for the elements to enable the program to connect to Facebook
def lookup(driver, email, password):
driver.get("https://www.facebook.com")
try:
box1 = driver.wait.until(EC.presence_of_element_located(
(By.NAME, "email")))
box2 = driver.wait.until(EC.presence_of_element_located(
(By.NAME, "pass")))
button = driver.wait.until(EC.element_to_be_clickable(
(By.ID, "loginbutton")))
box1.send_keys(email)
box2.send_keys(password)
button.click()
except TimeoutException:
print("Box or Button not found in facebook.com")
#Define the items to crawl
class PublisherItem(DjangoItem):
django_model = Publisher
#Define the behavior of the spider
class ProductSpider(scrapy.Spider):
name = "dbcrawl"
allowed_domains = ['facebook.com']
f = open("pub.txt")
start_urls = [url.strip() for url in f.readlines()]
#Connect to Facebook
driver = init_driver()
lookup(driver, "<EMAIL>", "Bouffegratos12")
time.sleep(5)
def __init__(self):
self.driver
def parse(self, response):
self.driver.get(response.url)
pub = PublisherItem()
attemps = 0
#50 attempts is 600 videos back. 60 seems to be optimal
while attemps < 10:
self.driver.implicitly_wait(10)
try:
self.driver.implicitly_wait(10)
more = self.driver.find_element_by_xpath('//div[@class="_3v4j"]/div[@class="clearfix uiMorePager stat_elem _52jv"]')
more.click()
#print self.driver.find_element_by_xpath('//div[@class="_3v4h _50f3 _50f7"]/a/@href')
attemps += 1
#print attemps
except:
break
#myfile = open('links.txt', 'w')
page = self.driver.find_element_by_xpath('//title').text
views = self.driver.find_elements_by_xpath('//div[@class="_u3y"]/div[@class="_3v4i"]/div[@class="fsm fwn fcg"]')
elements = self.driver.find_elements_by_xpath('//div[@class="_u3y"]/div[@class="_3v4h _50f3 _50f7"]/a')
print('Length of elements: {}'.format(len(elements)))
for element in elements:
try:
listTitle.append((element.text).encode("utf-8"))
listLinks.append((element.get_attribute('href')).encode("utf-8"))
listPage.append((page).encode("utf-8"))
except:
print("Not conform")
#save the list in the DB
for i in range(0,len(listTitle)):
info = {
'title': listTitle[i],
'link': listLinks[i],
'page_name': listPage[i],
}
resp = requests.post(video,data=json.dumps(info), headers=headers)
print('Video imported: {}'.format(resp)) | 0.167355 | 0.050565 |
from __future__ import division
import numpy as np
from astropy.io import fits
from math import fsum
from warnings import warn
# TODO: Investigate using scipy.fftpack instead?
def pad_and_rfft_image(img, newshape):
"""
Pads the psf array to the size described by imgshape, then run rfft to put
it in Fourier space.
"""
# TODO: pad with white noise instead of zeros?
pad = np.asarray(newshape) - np.asarray(img.shape)
if np.any(pad < 0):
raise NotImplementedError('PSF images larger than observation images '
'are not yet supported')
img_pad = np.zeros(newshape, dtype=img.dtype)
img_pad[pad[0]//2:pad[0]//2 + img.shape[0],
pad[1]//2:pad[1]//2 + img.shape[1]] = img
return np.fft.rfft2(img_pad)
def convolve(img, fourier_kernel):
"""
FFT-based convolution, using the Convolution Theorem. This is about 100x
faster than using scipy.ndimage.convolve, due to FFT. But it effectively
forces the boundary mode to be wrap. The kernel is supplied with its fft
pre-computed. For improved speed, supply power-of-two arrays
"""
return np.fft.ifftshift(np.fft.irfft2(np.fft.rfft2(img) * fourier_kernel))
def array_coords(shape=(1, 1)):
"""
Returns prod(shape) x 2 array of x, y coordinates for each cell in array
with dimensions like shape
"""
indexes = np.arange(np.product(shape))
coords = [indexes % shape[1], indexes // shape[1]]
return np.transpose(coords).astype('float64')
def norm_psf(psf_data, psf_ivm):
"""
Returns normed psf and correspondingly scaled IVM.
Uses math.fsum for its stable summation algorithm
"""
psf_sum = fsum(psf_data.flat)
return psf_data / psf_sum, psf_ivm * psf_sum**2
def preprocess_obs(obs_data, obs_ivm, mask_file=None):
"""
Opens data and weight maps for both observations and PSF, masks out bad
pixels, and normalizes the PSF for convolution
"""
# Read in arrays, mask bad pixels
obs_hdr = fits.getheader(obs_data)
obs_data = fits.getdata(obs_data, ignore_missing_end=True)
obs_ivm = fits.getdata(obs_ivm, ignore_missing_end=True)
# Generate bad pixel mask. Bad pixels get 0 weight in weight map, and are
# excluded from fitting
badpx = ~np.isfinite(obs_data) | ~np.isfinite(obs_ivm) | (obs_ivm <= 0)
# Pre-compute variance map for observation. Bad pixels are given infinite
# variance, since, when making the weight map, 1 / inf = 0.0
obs_var = np.where(badpx, np.inf, 1 / obs_ivm)
# Add masking regions to bad pixel mask. We leave their variance alone, to
# facilitate photometry later
if mask_file is not None:
exclude_px = mask_from_file(mask_file, obs_hdr, obs_data.shape)
if exclude_px is not None:
badpx |= exclude_px
return obs_hdr, obs_data, obs_var, badpx
def mask_from_file(mask_file, obs_hdr, shape):
"""
Create bad pixel mask from a file. File can be supplied in fits format
(nonzero pixels denoting exclusion), or in ds9 region format.
"""
try:
return fits.getdata(mask_file).astype(bool)
except IOError:
pass # When not in fits format
try:
import pyregion
regfilt = pyregion.open(mask_file).as_imagecoord(obs_hdr).get_filter()
return ~regfilt.mask(shape)
except ImportError:
pyregion = None
warn('pyregion module could not be imported. ds9 region format masks '
'will be ignored.')
except UnicodeDecodeError:
pass # When not ds9 region format
return None
def preprocess_psf(psf_data, psf_ivm):
"""
Read in a PSF & IVM, mask bad pixels, normalize kernel
Return the normed data and a corresponding (non-inverse) variance map
"""
psf_data = fits.getdata(psf_data, ignore_missing_end=True)
psf_ivm = fits.getdata(psf_ivm, ignore_missing_end=True)
# We don't want zero-weight pixels in the PSF to contribute infinitely to
# the variance, so we simply set them to 0 in both data and weight map
badpx = ~np.isfinite(psf_data) | ~np.isfinite(psf_ivm) | (psf_ivm <= 0)
psf_data[badpx] = 0
psf_ivm[badpx] = 0
# Normalize the PSF kernel, then return data and variance map
psf_data, psf_ivm = norm_psf(psf_data, psf_ivm)
psf_var = np.where(psf_ivm <= 0, 0, 1 / psf_ivm)
return psf_data, psf_var
def pre_fft_psf(psf_data, psf_var, pad_to_shape=None):
"""
Pre-compute (real) Fourier transforms of input PSFs and their variance maps,
padding to the given size if needed
"""
f_psf = pad_and_rfft_image(psf_data, pad_to_shape)
f_psf_var = pad_and_rfft_image(psf_var, pad_to_shape)
return f_psf, f_psf_var
def calculate_psf_variability(psf_data, psf_vars, debug_psfs=False):
"""
Take a set of normalized PSFs and their corresponding variance maps, measure
the inter-PSF (i.e. PSF variability/mismatch) variance map, and propagate
its contribution into the individual variance maps.
"""
if len(psf_data) == 1:
return psf_data, psf_vars
mismatch_var = np.var(psf_data, axis=0)
if debug_psfs:
meanpsf = np.mean(psf_data, axis=0)
fits.writeto('xx_rms.fits', np.sqrt(mismatch_var))
fits.writeto('xx_mean.fits', meanpsf)
for num, (psf, var) in enumerate(zip(psf_data, psf_vars)):
fits.writeto('xx_psf{:d}.fits'.format(num), psf - meanpsf)
fits.writeto('xx_rms{:d}.fits'.format(num), np.sqrt(var))
exit(1)
# Add contribution of PSF mismatch to all individual variance maps
psf_vars = [var + mismatch_var for var in psf_vars]
return psf_data, psf_vars
def mag_to_flux(mag, mag_zp):
"""
Returns total flux of the integrated profile, units relative to mag_zp
"""
return 10 ** (-0.4 * (mag - mag_zp))
def print_progress(sample, max_samples, stage='Burning'):
next_pct = 100 * (sample + 1) // max_samples
curr_pct = 100 * sample // max_samples
if next_pct - curr_pct > 0:
print('{}: {:d}%'.format(stage, next_pct)) | psfMC/utils.py | from __future__ import division
import numpy as np
from astropy.io import fits
from math import fsum
from warnings import warn
# TODO: Investigate using scipy.fftpack instead?
def pad_and_rfft_image(img, newshape):
"""
Pads the psf array to the size described by imgshape, then run rfft to put
it in Fourier space.
"""
# TODO: pad with white noise instead of zeros?
pad = np.asarray(newshape) - np.asarray(img.shape)
if np.any(pad < 0):
raise NotImplementedError('PSF images larger than observation images '
'are not yet supported')
img_pad = np.zeros(newshape, dtype=img.dtype)
img_pad[pad[0]//2:pad[0]//2 + img.shape[0],
pad[1]//2:pad[1]//2 + img.shape[1]] = img
return np.fft.rfft2(img_pad)
def convolve(img, fourier_kernel):
"""
FFT-based convolution, using the Convolution Theorem. This is about 100x
faster than using scipy.ndimage.convolve, due to FFT. But it effectively
forces the boundary mode to be wrap. The kernel is supplied with its fft
pre-computed. For improved speed, supply power-of-two arrays
"""
return np.fft.ifftshift(np.fft.irfft2(np.fft.rfft2(img) * fourier_kernel))
def array_coords(shape=(1, 1)):
"""
Returns prod(shape) x 2 array of x, y coordinates for each cell in array
with dimensions like shape
"""
indexes = np.arange(np.product(shape))
coords = [indexes % shape[1], indexes // shape[1]]
return np.transpose(coords).astype('float64')
def norm_psf(psf_data, psf_ivm):
"""
Returns normed psf and correspondingly scaled IVM.
Uses math.fsum for its stable summation algorithm
"""
psf_sum = fsum(psf_data.flat)
return psf_data / psf_sum, psf_ivm * psf_sum**2
def preprocess_obs(obs_data, obs_ivm, mask_file=None):
"""
Opens data and weight maps for both observations and PSF, masks out bad
pixels, and normalizes the PSF for convolution
"""
# Read in arrays, mask bad pixels
obs_hdr = fits.getheader(obs_data)
obs_data = fits.getdata(obs_data, ignore_missing_end=True)
obs_ivm = fits.getdata(obs_ivm, ignore_missing_end=True)
# Generate bad pixel mask. Bad pixels get 0 weight in weight map, and are
# excluded from fitting
badpx = ~np.isfinite(obs_data) | ~np.isfinite(obs_ivm) | (obs_ivm <= 0)
# Pre-compute variance map for observation. Bad pixels are given infinite
# variance, since, when making the weight map, 1 / inf = 0.0
obs_var = np.where(badpx, np.inf, 1 / obs_ivm)
# Add masking regions to bad pixel mask. We leave their variance alone, to
# facilitate photometry later
if mask_file is not None:
exclude_px = mask_from_file(mask_file, obs_hdr, obs_data.shape)
if exclude_px is not None:
badpx |= exclude_px
return obs_hdr, obs_data, obs_var, badpx
def mask_from_file(mask_file, obs_hdr, shape):
"""
Create bad pixel mask from a file. File can be supplied in fits format
(nonzero pixels denoting exclusion), or in ds9 region format.
"""
try:
return fits.getdata(mask_file).astype(bool)
except IOError:
pass # When not in fits format
try:
import pyregion
regfilt = pyregion.open(mask_file).as_imagecoord(obs_hdr).get_filter()
return ~regfilt.mask(shape)
except ImportError:
pyregion = None
warn('pyregion module could not be imported. ds9 region format masks '
'will be ignored.')
except UnicodeDecodeError:
pass # When not ds9 region format
return None
def preprocess_psf(psf_data, psf_ivm):
"""
Read in a PSF & IVM, mask bad pixels, normalize kernel
Return the normed data and a corresponding (non-inverse) variance map
"""
psf_data = fits.getdata(psf_data, ignore_missing_end=True)
psf_ivm = fits.getdata(psf_ivm, ignore_missing_end=True)
# We don't want zero-weight pixels in the PSF to contribute infinitely to
# the variance, so we simply set them to 0 in both data and weight map
badpx = ~np.isfinite(psf_data) | ~np.isfinite(psf_ivm) | (psf_ivm <= 0)
psf_data[badpx] = 0
psf_ivm[badpx] = 0
# Normalize the PSF kernel, then return data and variance map
psf_data, psf_ivm = norm_psf(psf_data, psf_ivm)
psf_var = np.where(psf_ivm <= 0, 0, 1 / psf_ivm)
return psf_data, psf_var
def pre_fft_psf(psf_data, psf_var, pad_to_shape=None):
"""
Pre-compute (real) Fourier transforms of input PSFs and their variance maps,
padding to the given size if needed
"""
f_psf = pad_and_rfft_image(psf_data, pad_to_shape)
f_psf_var = pad_and_rfft_image(psf_var, pad_to_shape)
return f_psf, f_psf_var
def calculate_psf_variability(psf_data, psf_vars, debug_psfs=False):
"""
Take a set of normalized PSFs and their corresponding variance maps, measure
the inter-PSF (i.e. PSF variability/mismatch) variance map, and propagate
its contribution into the individual variance maps.
"""
if len(psf_data) == 1:
return psf_data, psf_vars
mismatch_var = np.var(psf_data, axis=0)
if debug_psfs:
meanpsf = np.mean(psf_data, axis=0)
fits.writeto('xx_rms.fits', np.sqrt(mismatch_var))
fits.writeto('xx_mean.fits', meanpsf)
for num, (psf, var) in enumerate(zip(psf_data, psf_vars)):
fits.writeto('xx_psf{:d}.fits'.format(num), psf - meanpsf)
fits.writeto('xx_rms{:d}.fits'.format(num), np.sqrt(var))
exit(1)
# Add contribution of PSF mismatch to all individual variance maps
psf_vars = [var + mismatch_var for var in psf_vars]
return psf_data, psf_vars
def mag_to_flux(mag, mag_zp):
"""
Returns total flux of the integrated profile, units relative to mag_zp
"""
return 10 ** (-0.4 * (mag - mag_zp))
def print_progress(sample, max_samples, stage='Burning'):
next_pct = 100 * (sample + 1) // max_samples
curr_pct = 100 * sample // max_samples
if next_pct - curr_pct > 0:
print('{}: {:d}%'.format(stage, next_pct)) | 0.611614 | 0.579757 |
import pandas as pd
from flask import Blueprint, request, jsonify
from src.extraction.data_management import Data
from src.metrics.cust_metric import get_auc_score
from src.predict import make_prediction, get_models_list
from src import __version__ as _version
from api.config import get_logger
from api.validation import validate_inputs
from api import __version__ as api_version
_logger = get_logger(logger_name=__name__)
application = Blueprint('prediction_app', __name__)
@application.route('/', methods=['GET'])
def home():
return "<h1 style='color:blue'>Hello There :) !</h1>"
@application.route('/health', methods=['GET'])
def health():
if request.method == 'GET':
_logger.info('health status OK')
return 'ok'
@application.route('/version', methods=['GET'])
def version():
if request.method == 'GET':
return jsonify({'model_version': _version,
'api_version': api_version})
@application.route('/predict/', methods=['POST'])
def predict():
"""Output of default model based on last timestamp"""
if request.method == 'POST':
# Step 1: Extract POST data from request body as JSON
json_data = request.get_json()
# _logger.debug(f'Inputs: {json_data}')
# Step 2: Validate the input using marshmallow schema
input_data, errors = validate_inputs(input_data=json_data)
# Step 3: Model prediction
result = make_prediction(input_data=input_data)
_logger.debug(f'Outputs: {result}')
# Step 4: Convert numpy ndarray to list
predictions = result.get('predictions').tolist()
version = result.get('version')
# Step 5: Return the response as JSON
return jsonify({'predictions': predictions,
'version': version,
'errors': errors})
@application.route('/models/', methods=['GET'])
def get_models():
models_list = get_models_list()
return jsonify({'models': models_list})
@application.route('/output/<model_id>', methods=['POST'])
def output_specific_model(model_id):
model_id = model_id
# lightgbm_output_v0.1-1588759220.335498
if request.method == 'POST':
# Step 1: Extract POST data from request body as JSON
data = request.get_json()
# Step 2: Validate the input using marshmallow schema
data, errors = validate_inputs(input_data=data)
# Step 3: Model prediction
result = make_prediction(input_data=data, id_model=model_id)
predictions = result.get('predictions').tolist()
version = result.get('version')
return jsonify({
'result': predictions,
'model': model_id,
'version': version,
'errors': errors
})
@application.route('/outputs/<model_id>', methods=['POST'])
def batch_output_specific_model(model_id):
"""Output of a specific model with test.csv data
parameters
---------------
model_id: str
returns
---------------
"""
model_id = model_id
auc_score = ''
# lightgbm_output_v0.1-1588759220.335498
if request.method == 'POST':
data_mngmnt = Data()
data_mngmnt.from_csv("test.csv", sep=',')
data = data_mngmnt.df
result = make_prediction(input_data=data, id_model=model_id)
predictions = result.get('predictions').tolist()
if 'default' in data.columns:
auc_score = get_auc_score(data['default'], result.get('predictions'))
return jsonify({
'result': predictions,
'model': model_id,
'auc_score': auc_score
})
@application.route('/outputs_upload/<model_id>', methods=['POST'])
def outputs_upload(model_id):
"""Upload a csv file and return prediction output
"""
if request.method == 'POST':
auc_score = ''
# Create variable for uploaded file
df = pd.read_csv(request.files.get('fileupload'))
result = make_prediction(input_data=df, id_model=model_id)
predictions = result.get('predictions').tolist()
if 'default' in df.columns:
auc_score = get_auc_score(df['default'], result.get('predictions'))
return jsonify({
'result': predictions,
'model': model_id,
'auc_score': auc_score
}) | api/controller.py | import pandas as pd
from flask import Blueprint, request, jsonify
from src.extraction.data_management import Data
from src.metrics.cust_metric import get_auc_score
from src.predict import make_prediction, get_models_list
from src import __version__ as _version
from api.config import get_logger
from api.validation import validate_inputs
from api import __version__ as api_version
_logger = get_logger(logger_name=__name__)
application = Blueprint('prediction_app', __name__)
@application.route('/', methods=['GET'])
def home():
return "<h1 style='color:blue'>Hello There :) !</h1>"
@application.route('/health', methods=['GET'])
def health():
if request.method == 'GET':
_logger.info('health status OK')
return 'ok'
@application.route('/version', methods=['GET'])
def version():
if request.method == 'GET':
return jsonify({'model_version': _version,
'api_version': api_version})
@application.route('/predict/', methods=['POST'])
def predict():
"""Output of default model based on last timestamp"""
if request.method == 'POST':
# Step 1: Extract POST data from request body as JSON
json_data = request.get_json()
# _logger.debug(f'Inputs: {json_data}')
# Step 2: Validate the input using marshmallow schema
input_data, errors = validate_inputs(input_data=json_data)
# Step 3: Model prediction
result = make_prediction(input_data=input_data)
_logger.debug(f'Outputs: {result}')
# Step 4: Convert numpy ndarray to list
predictions = result.get('predictions').tolist()
version = result.get('version')
# Step 5: Return the response as JSON
return jsonify({'predictions': predictions,
'version': version,
'errors': errors})
@application.route('/models/', methods=['GET'])
def get_models():
models_list = get_models_list()
return jsonify({'models': models_list})
@application.route('/output/<model_id>', methods=['POST'])
def output_specific_model(model_id):
model_id = model_id
# lightgbm_output_v0.1-1588759220.335498
if request.method == 'POST':
# Step 1: Extract POST data from request body as JSON
data = request.get_json()
# Step 2: Validate the input using marshmallow schema
data, errors = validate_inputs(input_data=data)
# Step 3: Model prediction
result = make_prediction(input_data=data, id_model=model_id)
predictions = result.get('predictions').tolist()
version = result.get('version')
return jsonify({
'result': predictions,
'model': model_id,
'version': version,
'errors': errors
})
@application.route('/outputs/<model_id>', methods=['POST'])
def batch_output_specific_model(model_id):
"""Output of a specific model with test.csv data
parameters
---------------
model_id: str
returns
---------------
"""
model_id = model_id
auc_score = ''
# lightgbm_output_v0.1-1588759220.335498
if request.method == 'POST':
data_mngmnt = Data()
data_mngmnt.from_csv("test.csv", sep=',')
data = data_mngmnt.df
result = make_prediction(input_data=data, id_model=model_id)
predictions = result.get('predictions').tolist()
if 'default' in data.columns:
auc_score = get_auc_score(data['default'], result.get('predictions'))
return jsonify({
'result': predictions,
'model': model_id,
'auc_score': auc_score
})
@application.route('/outputs_upload/<model_id>', methods=['POST'])
def outputs_upload(model_id):
"""Upload a csv file and return prediction output
"""
if request.method == 'POST':
auc_score = ''
# Create variable for uploaded file
df = pd.read_csv(request.files.get('fileupload'))
result = make_prediction(input_data=df, id_model=model_id)
predictions = result.get('predictions').tolist()
if 'default' in df.columns:
auc_score = get_auc_score(df['default'], result.get('predictions'))
return jsonify({
'result': predictions,
'model': model_id,
'auc_score': auc_score
}) | 0.69035 | 0.165998 |
import asyncio
import logging
import random
import re
import textwrap
from typing import Any, Dict
import aiohttp
import async_timeout
import discord
from discord.ext.commands import AutoShardedBot, Context, command, bot_has_permissions
from bot.converters import Snake
from bot.decorators import locked
from bot.utils import disambiguate
log = logging.getLogger(__name__)
URL = "https://en.wikipedia.org/w/api.php?"
class Snakes:
"""
Snake-related commands
"""
# I really hope this works
wiki_sects = re.compile(r'(?:=+ (.*?) =+)(.*?\n\n)', flags=re.DOTALL)
wiki_brief = re.compile(r'(.*?)(=+ (.*?) =+)', flags=re.DOTALL)
valid = ('gif', 'png', 'jpeg', 'jpg', 'webp')
def __init__(self, bot: AutoShardedBot):
self.bot = bot
async def fetch(self, session, url, params=None):
if params is None:
params = {}
async with async_timeout.timeout(10):
async with session.get(url, params=params) as response:
return await response.json()
async def get_snek(self, name: str) -> Dict[str, Any]:
"""
Go online and fetch information about a snake
The information includes the name of the snake, a picture of the snake, and various other pieces of info.
What information you get for the snake is up to you. Be creative!
If "python" is given as the snake name, you should return information about the programming language, but with
all the information you'd provide for a real snake. Try to have some fun with this!
:param name: The name of the snake to get information for - omit for a random snake
:return: A dict containing information on a snake
"""
snake_info = {}
async with aiohttp.ClientSession() as session:
params = {
'format': 'json',
'action': 'query',
'list': 'search',
'srsearch': name,
'utf8': '',
'srlimit': '1',
}
json = await self.fetch(session, URL, params=params)
# wikipedia does have a error page
try:
pageid = json["query"]["search"][0]["pageid"]
except KeyError:
# Wikipedia error page ID(?)
pageid = 41118
params = {
'format': 'json',
'action': 'query',
'prop': 'extracts|images|info',
'exlimit': 'max',
'explaintext': '',
'inprop': 'url',
'pageids': pageid
}
json = await self.fetch(session, URL, params=params)
# constructing dict - handle exceptions later
try:
snake_info["title"] = json["query"]["pages"][f"{pageid}"]["title"]
snake_info["extract"] = json["query"]["pages"][f"{pageid}"]["extract"]
snake_info["images"] = json["query"]["pages"][f"{pageid}"]["images"]
snake_info["fullurl"] = json["query"]["pages"][f"{pageid}"]["fullurl"]
snake_info["pageid"] = json["query"]["pages"][f"{pageid}"]["pageid"]
except KeyError:
snake_info["error"] = True
if snake_info["images"]:
i_url = 'https://commons.wikimedia.org/wiki/Special:FilePath/'
image_list = []
map_list = []
thumb_list = []
# Wikipedia has arbitrary images that are not snakes
banned = [
'Commons-logo.svg',
'Red%20Pencil%20Icon.png',
'distribution',
'The%20Death%20of%20Cleopatra%20arthur.jpg',
'Head%20of%20holotype',
'locator',
'Woma.png',
'-map.',
'.svg',
'ange.',
'Adder%20(PSF).png'
]
for image in snake_info["images"]:
# images come in the format of `File:filename.extension`
file, sep, filename = image["title"].partition(':')
filename = filename.replace(" ", "%20") # Wikipedia returns good data!
if not filename.startswith('Map'):
if any(ban in filename for ban in banned):
log.info("the image is banned")
else:
image_list.append(f"{i_url}{filename}")
thumb_list.append(f"{i_url}{filename}?width=100")
else:
map_list.append(f"{i_url}{filename}")
snake_info["image_list"] = image_list
snake_info["map_list"] = map_list
snake_info["thumb_list"] = thumb_list
return snake_info
@command(name="snakes.get()", aliases=["snakes.get"])
@bot_has_permissions(manage_messages=True)
@locked()
async def get(self, ctx: Context, name: Snake = None):
"""
Fetches information about a snake from Wikipedia.
:param ctx: Context object passed from discord.py
:param name: Optional, the name of the snake to get information for - omit for a random snake
"""
if name is None:
name = Snake.random()
data = await self.get_snek(name)
if data.get('error'):
return await ctx.send('Could not fetch data from Wikipedia.')
match = self.wiki_brief.match(data['extract'])
embed = discord.Embed(
title=data['title'],
description=match.group(1) if match else None,
url=data['fullurl'],
colour=0x59982F
)
fields = self.wiki_sects.findall(data['extract'])
excluded = ('see also', 'further reading', 'subspecies')
for title, body in fields:
if title.lower() in excluded:
continue
if not body.strip():
continue
# Only takes the first sentence
title, dot, _ = title.partition('.')
# There's probably a better way to do this
value = textwrap.shorten(body.strip(), width=200)
embed.add_field(name=title + dot, value=value + '\n\u200b', inline=False)
embed.set_footer(text='Powered by Wikipedia')
emoji = 'https://emojipedia-us.s3.amazonaws.com/thumbs/60/google/3/snake_1f40d.png'
image = next((url for url in data['image_list'] if url.endswith(self.valid)), emoji)
embed.set_thumbnail(url=image)
await ctx.send(embed=embed)
@command(hidden=True)
async def zen(self, ctx):
"""
>>> import this
Long time Pythoneer <NAME> succinctly channels the BDFL's guiding principles
for Python's design into 20 aphorisms, only 19 of which have been written down.
You must be connected to a voice channel in order to use this command.
"""
channel = ctx.author.voice.channel
if channel is None:
return
state = ctx.guild.voice_client
if state is not None:
# Already playing
return
voice = await channel.connect()
source = discord.FFmpegPCMAudio('zen.mp3')
voice.play(source, after=lambda *args: asyncio.run_coroutine_threadsafe(
voice.disconnect(), loop=ctx.bot.loop
))
@command(name="snakes.guess()", aliases=["snakes.guess", "identify"])
@locked()
async def guess(self, ctx):
"""
Snake identifying game!
"""
image = None
while image is None:
snakes = [Snake.random() for _ in range(5)]
answer = random.choice(snakes)
data = await self.get_snek(answer)
image = next((url for url in data['image_list'] if url.endswith(self.valid)), None)
embed = discord.Embed(
title='Which of the following is the snake in the image?',
colour=random.randint(1, 0xFFFFFF)
)
embed.set_image(url=image)
guess = await disambiguate(ctx, snakes, timeout=60, embed=embed)
if guess == answer:
return await ctx.send('You guessed correctly!')
await ctx.send(f'You guessed wrong. The correct answer was {answer}.')
def setup(bot):
bot.add_cog(Snakes(bot))
log.info("Cog loaded: Snakes") | bot/cogs/snakes.py | import asyncio
import logging
import random
import re
import textwrap
from typing import Any, Dict
import aiohttp
import async_timeout
import discord
from discord.ext.commands import AutoShardedBot, Context, command, bot_has_permissions
from bot.converters import Snake
from bot.decorators import locked
from bot.utils import disambiguate
log = logging.getLogger(__name__)
URL = "https://en.wikipedia.org/w/api.php?"
class Snakes:
"""
Snake-related commands
"""
# I really hope this works
wiki_sects = re.compile(r'(?:=+ (.*?) =+)(.*?\n\n)', flags=re.DOTALL)
wiki_brief = re.compile(r'(.*?)(=+ (.*?) =+)', flags=re.DOTALL)
valid = ('gif', 'png', 'jpeg', 'jpg', 'webp')
def __init__(self, bot: AutoShardedBot):
self.bot = bot
async def fetch(self, session, url, params=None):
if params is None:
params = {}
async with async_timeout.timeout(10):
async with session.get(url, params=params) as response:
return await response.json()
async def get_snek(self, name: str) -> Dict[str, Any]:
"""
Go online and fetch information about a snake
The information includes the name of the snake, a picture of the snake, and various other pieces of info.
What information you get for the snake is up to you. Be creative!
If "python" is given as the snake name, you should return information about the programming language, but with
all the information you'd provide for a real snake. Try to have some fun with this!
:param name: The name of the snake to get information for - omit for a random snake
:return: A dict containing information on a snake
"""
snake_info = {}
async with aiohttp.ClientSession() as session:
params = {
'format': 'json',
'action': 'query',
'list': 'search',
'srsearch': name,
'utf8': '',
'srlimit': '1',
}
json = await self.fetch(session, URL, params=params)
# wikipedia does have a error page
try:
pageid = json["query"]["search"][0]["pageid"]
except KeyError:
# Wikipedia error page ID(?)
pageid = 41118
params = {
'format': 'json',
'action': 'query',
'prop': 'extracts|images|info',
'exlimit': 'max',
'explaintext': '',
'inprop': 'url',
'pageids': pageid
}
json = await self.fetch(session, URL, params=params)
# constructing dict - handle exceptions later
try:
snake_info["title"] = json["query"]["pages"][f"{pageid}"]["title"]
snake_info["extract"] = json["query"]["pages"][f"{pageid}"]["extract"]
snake_info["images"] = json["query"]["pages"][f"{pageid}"]["images"]
snake_info["fullurl"] = json["query"]["pages"][f"{pageid}"]["fullurl"]
snake_info["pageid"] = json["query"]["pages"][f"{pageid}"]["pageid"]
except KeyError:
snake_info["error"] = True
if snake_info["images"]:
i_url = 'https://commons.wikimedia.org/wiki/Special:FilePath/'
image_list = []
map_list = []
thumb_list = []
# Wikipedia has arbitrary images that are not snakes
banned = [
'Commons-logo.svg',
'Red%20Pencil%20Icon.png',
'distribution',
'The%20Death%20of%20Cleopatra%20arthur.jpg',
'Head%20of%20holotype',
'locator',
'Woma.png',
'-map.',
'.svg',
'ange.',
'Adder%20(PSF).png'
]
for image in snake_info["images"]:
# images come in the format of `File:filename.extension`
file, sep, filename = image["title"].partition(':')
filename = filename.replace(" ", "%20") # Wikipedia returns good data!
if not filename.startswith('Map'):
if any(ban in filename for ban in banned):
log.info("the image is banned")
else:
image_list.append(f"{i_url}{filename}")
thumb_list.append(f"{i_url}{filename}?width=100")
else:
map_list.append(f"{i_url}{filename}")
snake_info["image_list"] = image_list
snake_info["map_list"] = map_list
snake_info["thumb_list"] = thumb_list
return snake_info
@command(name="snakes.get()", aliases=["snakes.get"])
@bot_has_permissions(manage_messages=True)
@locked()
async def get(self, ctx: Context, name: Snake = None):
"""
Fetches information about a snake from Wikipedia.
:param ctx: Context object passed from discord.py
:param name: Optional, the name of the snake to get information for - omit for a random snake
"""
if name is None:
name = Snake.random()
data = await self.get_snek(name)
if data.get('error'):
return await ctx.send('Could not fetch data from Wikipedia.')
match = self.wiki_brief.match(data['extract'])
embed = discord.Embed(
title=data['title'],
description=match.group(1) if match else None,
url=data['fullurl'],
colour=0x59982F
)
fields = self.wiki_sects.findall(data['extract'])
excluded = ('see also', 'further reading', 'subspecies')
for title, body in fields:
if title.lower() in excluded:
continue
if not body.strip():
continue
# Only takes the first sentence
title, dot, _ = title.partition('.')
# There's probably a better way to do this
value = textwrap.shorten(body.strip(), width=200)
embed.add_field(name=title + dot, value=value + '\n\u200b', inline=False)
embed.set_footer(text='Powered by Wikipedia')
emoji = 'https://emojipedia-us.s3.amazonaws.com/thumbs/60/google/3/snake_1f40d.png'
image = next((url for url in data['image_list'] if url.endswith(self.valid)), emoji)
embed.set_thumbnail(url=image)
await ctx.send(embed=embed)
@command(hidden=True)
async def zen(self, ctx):
"""
>>> import this
Long time Pythoneer <NAME> succinctly channels the BDFL's guiding principles
for Python's design into 20 aphorisms, only 19 of which have been written down.
You must be connected to a voice channel in order to use this command.
"""
channel = ctx.author.voice.channel
if channel is None:
return
state = ctx.guild.voice_client
if state is not None:
# Already playing
return
voice = await channel.connect()
source = discord.FFmpegPCMAudio('zen.mp3')
voice.play(source, after=lambda *args: asyncio.run_coroutine_threadsafe(
voice.disconnect(), loop=ctx.bot.loop
))
@command(name="snakes.guess()", aliases=["snakes.guess", "identify"])
@locked()
async def guess(self, ctx):
"""
Snake identifying game!
"""
image = None
while image is None:
snakes = [Snake.random() for _ in range(5)]
answer = random.choice(snakes)
data = await self.get_snek(answer)
image = next((url for url in data['image_list'] if url.endswith(self.valid)), None)
embed = discord.Embed(
title='Which of the following is the snake in the image?',
colour=random.randint(1, 0xFFFFFF)
)
embed.set_image(url=image)
guess = await disambiguate(ctx, snakes, timeout=60, embed=embed)
if guess == answer:
return await ctx.send('You guessed correctly!')
await ctx.send(f'You guessed wrong. The correct answer was {answer}.')
def setup(bot):
bot.add_cog(Snakes(bot))
log.info("Cog loaded: Snakes") | 0.67971 | 0.124372 |
from __future__ import print_function
from __future__ import division
import sys
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.model_selection import H2OModelSelectionEstimator as modelSelection
# test modelselection works with validation dataset
def test_modelselection_validation():
d = h2o.import_file(path=pyunit_utils.locate("smalldata/glm_test/gaussian_20cols_10000Rows.csv"))
my_y = "C21"
my_x = ["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10", "C11", "C12", "C13", "C14",
"C15", "C16", "C17", "C18", "C19", "C20"]
factor_x = ["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10"]
for x in factor_x:
d[x] = d[x].asfactor()
frames = d.split_frame(ratios=[0.8],seed=12345)
train = frames[0]
test = frames[1]
allsubsets_model = modelSelection(seed=12345, max_predictor_number=3, mode="allsubsets")
allsubsets_model.train(training_frame=train, x=my_x, y=my_y)
best_r2_allsubsets = allsubsets_model.get_best_R2_values()
best_predictor_allsubsets = allsubsets_model.get_best_model_predictors()
allsubsets_model_v = modelSelection(seed=12345, max_predictor_number=3, mode="allsubsets")
allsubsets_model_v.train(training_frame=train, validation_frame=test, x=my_x, y=my_y)
best_r2_allsubsets_v = allsubsets_model_v.get_best_R2_values()
best_predictor_allsubsets_v = allsubsets_model.get_best_model_predictors()
maxr_model_v = modelSelection(seed=12345, max_predictor_number=3, mode="maxr")
maxr_model_v.train(training_frame=train, validation_frame=test, x=my_x, y=my_y)
best_r2_maxr_v = maxr_model_v.get_best_R2_values()
best_predictor_maxr_v = maxr_model_v.get_best_model_predictors()
# R2 values are different between the two models
numSet = len(best_r2_allsubsets)
for index in range(numSet):
one_best_predictor_allsubsets = best_predictor_allsubsets[index]
one_best_predictor_v_allsubsets = best_predictor_allsubsets_v[index]
one_best_r2_allsubsets = best_r2_allsubsets[index]
one_best_r2_v_allsubsets = best_r2_allsubsets_v[index]
best_r2_v_maxr = best_r2_maxr_v[index]
if one_best_predictor_allsubsets == one_best_predictor_v_allsubsets:
assert not(one_best_r2_allsubsets == one_best_r2_v_allsubsets), "R2 values should not equal"
assert abs(one_best_r2_v_allsubsets-best_r2_v_maxr) < 1e-6, "allsubset best R2: {0}, maxr best R2: {1}. They " \
"are different.".format(one_best_r2_v_allsubsets,
best_r2_v_maxr)
if __name__ == "__main__":
pyunit_utils.standalone_test(test_modelselection_validation)
else:
test_modelselection_validation() | h2o-py/tests/testdir_algos/modelselection/pyunit_PUBDEV_8235_modelselection_gaussian_validation.py | from __future__ import print_function
from __future__ import division
import sys
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.model_selection import H2OModelSelectionEstimator as modelSelection
# test modelselection works with validation dataset
def test_modelselection_validation():
d = h2o.import_file(path=pyunit_utils.locate("smalldata/glm_test/gaussian_20cols_10000Rows.csv"))
my_y = "C21"
my_x = ["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10", "C11", "C12", "C13", "C14",
"C15", "C16", "C17", "C18", "C19", "C20"]
factor_x = ["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10"]
for x in factor_x:
d[x] = d[x].asfactor()
frames = d.split_frame(ratios=[0.8],seed=12345)
train = frames[0]
test = frames[1]
allsubsets_model = modelSelection(seed=12345, max_predictor_number=3, mode="allsubsets")
allsubsets_model.train(training_frame=train, x=my_x, y=my_y)
best_r2_allsubsets = allsubsets_model.get_best_R2_values()
best_predictor_allsubsets = allsubsets_model.get_best_model_predictors()
allsubsets_model_v = modelSelection(seed=12345, max_predictor_number=3, mode="allsubsets")
allsubsets_model_v.train(training_frame=train, validation_frame=test, x=my_x, y=my_y)
best_r2_allsubsets_v = allsubsets_model_v.get_best_R2_values()
best_predictor_allsubsets_v = allsubsets_model.get_best_model_predictors()
maxr_model_v = modelSelection(seed=12345, max_predictor_number=3, mode="maxr")
maxr_model_v.train(training_frame=train, validation_frame=test, x=my_x, y=my_y)
best_r2_maxr_v = maxr_model_v.get_best_R2_values()
best_predictor_maxr_v = maxr_model_v.get_best_model_predictors()
# R2 values are different between the two models
numSet = len(best_r2_allsubsets)
for index in range(numSet):
one_best_predictor_allsubsets = best_predictor_allsubsets[index]
one_best_predictor_v_allsubsets = best_predictor_allsubsets_v[index]
one_best_r2_allsubsets = best_r2_allsubsets[index]
one_best_r2_v_allsubsets = best_r2_allsubsets_v[index]
best_r2_v_maxr = best_r2_maxr_v[index]
if one_best_predictor_allsubsets == one_best_predictor_v_allsubsets:
assert not(one_best_r2_allsubsets == one_best_r2_v_allsubsets), "R2 values should not equal"
assert abs(one_best_r2_v_allsubsets-best_r2_v_maxr) < 1e-6, "allsubset best R2: {0}, maxr best R2: {1}. They " \
"are different.".format(one_best_r2_v_allsubsets,
best_r2_v_maxr)
if __name__ == "__main__":
pyunit_utils.standalone_test(test_modelselection_validation)
else:
test_modelselection_validation() | 0.419291 | 0.231973 |
from unittest import TestSuite
import mock
from requests import HTTPError
from contacthub.workspace import Workspace
from contacthub._api_manager._api_customer import _CustomerAPIManager
from tests.utility import FakeHTTPResponse
class TestCustomerAPIManager(TestSuite):
@classmethod
def setUp(cls):
w = Workspace(workspace_id=123, token=<PASSWORD>)
cls.node = w.get_node(123)
cls.customer_manager = _CustomerAPIManager(node=cls.node)
cls.headers_expected = {'Authorization': 'Bearer 456', 'Content-Type': 'application/json'}
cls.base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
@classmethod
def tearDown(cls):
pass
@mock.patch('requests.get', return_value=FakeHTTPResponse(status_code=200))
def test_get_all_custumers(self, mock_get):
params_expected = {'nodeId': '123'}
resp = self.customer_manager.get_all()
mock_get.assert_called_with(self.base_url, params=params_expected, headers=self.headers_expected)
assert type(resp) is dict, type(resp)
assert 'elements' in resp, resp
@mock.patch('requests.get', return_value=FakeHTTPResponse(status_code=401))
def test_get_customer_unathorized(self, mock_get):
params_expected = {'nodeId': '123'}
try:
self.customer_manager.get_all()
except HTTPError as e:
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, params=params_expected)
@mock.patch('requests.get', return_value=FakeHTTPResponse())
def test_get_customer_extra(self, mock_get):
params_expected = {'nodeId': '123'}
self.customer_manager.get(_id='01', urls_extra='extra')
mock_get.assert_called_with(self.base_url + '/01/extra', headers=self.headers_expected)
@mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response'))
def test_post_customer(self, mock_get):
body = {'base': {'contacts': {'email': '<EMAIL>'}}}
data_expected = {'base': {'contacts': {'email': '<EMAIL>'}}, 'nodeId': '123'}
self.customer_manager.post(body=body)
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, json =data_expected)
@mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response', status_code=401))
def test_post_customer_unathorized(self, mock_get):
try:
self.customer_manager.post(body={})
except HTTPError as e:
assert 'Message' in str(e), str(e)
@mock.patch('requests.patch',
return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response', status_code=401))
def test_patch_customer_unathorized(self, mock_get):
try:
self.customer_manager.patch(_id='id', body={})
except HTTPError as e:
assert 'Message' in str(e), str(e)
@mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response'))
def test_put_customer(self, mock_get):
body = {'base': {'contacts': {'email': '<EMAIL>'}}}
self.customer_manager.put(_id='01', body=body)
mock_get.assert_called_with(self.base_url + '/01', headers=self.headers_expected, json=body)
@mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response', status_code=400))
def test_put_customer_unauthorized(self, mock_get):
try:
self.customer_manager.put(_id='id', body={})
except HTTPError as e:
assert 'Message' in str(e), str(e)
@mock.patch('requests.delete',
return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response'))
def test_delete_extra_url(self, mock_delete):
self.customer_manager.delete(_id="01", urls_extra='likes/02')
mock_delete.assert_called_with(self.base_url + '/01/likes/02', headers=self.headers_expected)
@mock.patch('requests.put',
return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response'))
def test_put_extra_url(self, mock_delete):
self.customer_manager.put(_id="01", urls_extra='likes/02', body={})
mock_delete.assert_called_with(self.base_url + '/01/likes/02', headers=self.headers_expected, json={})
@mock.patch('requests.delete',
return_value=FakeHTTPResponse(resp_path=None))
def test_delete_null_response(self, mock_delete):
a = self.customer_manager.delete(_id="01", urls_extra='likes/02')
mock_delete.assert_called_with(self.base_url + '/01/likes/02', headers=self.headers_expected)
assert not a, a
@mock.patch('requests.get',
return_value=FakeHTTPResponse())
def test_get_all_external_id(self, mock_get):
a = self.customer_manager.get_all(externalId='01')
params_expected = {'nodeId': '123', 'externalId':'01'}
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, params=params_expected)
@mock.patch('requests.get',
return_value=FakeHTTPResponse())
def test_get_all_page_size(self, mock_get):
self.customer_manager.get_all(page=1, size=2)
params_expected = {'nodeId': '123', 'page': 1, 'size':2}
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, params=params_expected)
@mock.patch('requests.get',
return_value=FakeHTTPResponse(status_code=400))
def test_get_error(self, mock_get):
try:
self.customer_manager.get(_id='01')
except HTTPError as e:
assert 'Message' in str(e), str(e)
@mock.patch('requests.get',
return_value=FakeHTTPResponse())
def test_get_all_fields(self, mock_get):
self.customer_manager.get_all(fields=['a','b','c'])
params_expected = {'nodeId': '123', 'fields': 'a,b,c'}
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, params=params_expected) | tests/test_api_customer.py | from unittest import TestSuite
import mock
from requests import HTTPError
from contacthub.workspace import Workspace
from contacthub._api_manager._api_customer import _CustomerAPIManager
from tests.utility import FakeHTTPResponse
class TestCustomerAPIManager(TestSuite):
@classmethod
def setUp(cls):
w = Workspace(workspace_id=123, token=<PASSWORD>)
cls.node = w.get_node(123)
cls.customer_manager = _CustomerAPIManager(node=cls.node)
cls.headers_expected = {'Authorization': 'Bearer 456', 'Content-Type': 'application/json'}
cls.base_url = 'https://api.contactlab.it/hub/v1/workspaces/123/customers'
@classmethod
def tearDown(cls):
pass
@mock.patch('requests.get', return_value=FakeHTTPResponse(status_code=200))
def test_get_all_custumers(self, mock_get):
params_expected = {'nodeId': '123'}
resp = self.customer_manager.get_all()
mock_get.assert_called_with(self.base_url, params=params_expected, headers=self.headers_expected)
assert type(resp) is dict, type(resp)
assert 'elements' in resp, resp
@mock.patch('requests.get', return_value=FakeHTTPResponse(status_code=401))
def test_get_customer_unathorized(self, mock_get):
params_expected = {'nodeId': '123'}
try:
self.customer_manager.get_all()
except HTTPError as e:
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, params=params_expected)
@mock.patch('requests.get', return_value=FakeHTTPResponse())
def test_get_customer_extra(self, mock_get):
params_expected = {'nodeId': '123'}
self.customer_manager.get(_id='01', urls_extra='extra')
mock_get.assert_called_with(self.base_url + '/01/extra', headers=self.headers_expected)
@mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response'))
def test_post_customer(self, mock_get):
body = {'base': {'contacts': {'email': '<EMAIL>'}}}
data_expected = {'base': {'contacts': {'email': '<EMAIL>'}}, 'nodeId': '123'}
self.customer_manager.post(body=body)
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, json =data_expected)
@mock.patch('requests.post', return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response', status_code=401))
def test_post_customer_unathorized(self, mock_get):
try:
self.customer_manager.post(body={})
except HTTPError as e:
assert 'Message' in str(e), str(e)
@mock.patch('requests.patch',
return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response', status_code=401))
def test_patch_customer_unathorized(self, mock_get):
try:
self.customer_manager.patch(_id='id', body={})
except HTTPError as e:
assert 'Message' in str(e), str(e)
@mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response'))
def test_put_customer(self, mock_get):
body = {'base': {'contacts': {'email': '<EMAIL>'}}}
self.customer_manager.put(_id='01', body=body)
mock_get.assert_called_with(self.base_url + '/01', headers=self.headers_expected, json=body)
@mock.patch('requests.put', return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response', status_code=400))
def test_put_customer_unauthorized(self, mock_get):
try:
self.customer_manager.put(_id='id', body={})
except HTTPError as e:
assert 'Message' in str(e), str(e)
@mock.patch('requests.delete',
return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response'))
def test_delete_extra_url(self, mock_delete):
self.customer_manager.delete(_id="01", urls_extra='likes/02')
mock_delete.assert_called_with(self.base_url + '/01/likes/02', headers=self.headers_expected)
@mock.patch('requests.put',
return_value=FakeHTTPResponse(resp_path='tests/util/fake_query_response'))
def test_put_extra_url(self, mock_delete):
self.customer_manager.put(_id="01", urls_extra='likes/02', body={})
mock_delete.assert_called_with(self.base_url + '/01/likes/02', headers=self.headers_expected, json={})
@mock.patch('requests.delete',
return_value=FakeHTTPResponse(resp_path=None))
def test_delete_null_response(self, mock_delete):
a = self.customer_manager.delete(_id="01", urls_extra='likes/02')
mock_delete.assert_called_with(self.base_url + '/01/likes/02', headers=self.headers_expected)
assert not a, a
@mock.patch('requests.get',
return_value=FakeHTTPResponse())
def test_get_all_external_id(self, mock_get):
a = self.customer_manager.get_all(externalId='01')
params_expected = {'nodeId': '123', 'externalId':'01'}
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, params=params_expected)
@mock.patch('requests.get',
return_value=FakeHTTPResponse())
def test_get_all_page_size(self, mock_get):
self.customer_manager.get_all(page=1, size=2)
params_expected = {'nodeId': '123', 'page': 1, 'size':2}
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, params=params_expected)
@mock.patch('requests.get',
return_value=FakeHTTPResponse(status_code=400))
def test_get_error(self, mock_get):
try:
self.customer_manager.get(_id='01')
except HTTPError as e:
assert 'Message' in str(e), str(e)
@mock.patch('requests.get',
return_value=FakeHTTPResponse())
def test_get_all_fields(self, mock_get):
self.customer_manager.get_all(fields=['a','b','c'])
params_expected = {'nodeId': '123', 'fields': 'a,b,c'}
mock_get.assert_called_with(self.base_url, headers=self.headers_expected, params=params_expected) | 0.504394 | 0.218732 |
import tensorflow as tf
from typing import Optional, Tuple, Any
from utils.tfutils import get_activation, apply_noise
from .cell_utils import ugrnn
class UGRNNCell(tf.compat.v1.nn.rnn_cell.RNNCell):
def __init__(self, units: int, activation: str, name: str, recurrent_noise: tf.Tensor):
self._units = units
self._activation = get_activation(activation)
self._name = name
self._recurrent_noise = recurrent_noise
# Create the trainable parameters
self.W_transform = tf.compat.v1.get_variable(name='{0}-W-transform'.format(name),
initializer=tf.compat.v1.glorot_uniform_initializer(),
shape=[2 * units, 2 * units],
trainable=True)
self.b_transform = tf.compat.v1.get_variable(name='{0}-b-transform'.format(name),
initializer=tf.compat.v1.glorot_uniform_initializer(),
shape=[1, 2 * units],
trainable=True)
@property
def state_size(self) -> int:
return self._units
@property
def output_size(self) -> int:
return self._units
def get_initial_state(self, inputs: Optional[tf.Tensor], batch_size: Optional[int], dtype: Any) -> tf.Tensor:
initial_state = tf.compat.v1.get_variable(name='initial-state',
initializer=tf.compat.v1.zeros_initializer(),
shape=[1, self._units],
dtype=dtype,
trainable=False)
return tf.tile(initial_state, multiples=(batch_size, 1)) # [B, D]
def __call__(self, inputs: tf.Tensor, state: tf.Tensor, scope=None) -> Tuple[tf.Tensor, tf.Tensor]:
scope = scope if scope is not None else type(self).__name__
with tf.compat.v1.variable_scope(scope):
# Apply the standard UGRNN update, [B, D]
next_state = ugrnn(inputs=inputs,
state=state,
W_transform=self.W_transform,
b_transform=self.b_transform,
activation=self._activation)
# Apply regularization noise
next_state = apply_noise(next_state, scale=self._recurrent_noise)
return next_state, next_state | budget-rnn/src/layers/cells/standard_rnn_cells.py | import tensorflow as tf
from typing import Optional, Tuple, Any
from utils.tfutils import get_activation, apply_noise
from .cell_utils import ugrnn
class UGRNNCell(tf.compat.v1.nn.rnn_cell.RNNCell):
def __init__(self, units: int, activation: str, name: str, recurrent_noise: tf.Tensor):
self._units = units
self._activation = get_activation(activation)
self._name = name
self._recurrent_noise = recurrent_noise
# Create the trainable parameters
self.W_transform = tf.compat.v1.get_variable(name='{0}-W-transform'.format(name),
initializer=tf.compat.v1.glorot_uniform_initializer(),
shape=[2 * units, 2 * units],
trainable=True)
self.b_transform = tf.compat.v1.get_variable(name='{0}-b-transform'.format(name),
initializer=tf.compat.v1.glorot_uniform_initializer(),
shape=[1, 2 * units],
trainable=True)
@property
def state_size(self) -> int:
return self._units
@property
def output_size(self) -> int:
return self._units
def get_initial_state(self, inputs: Optional[tf.Tensor], batch_size: Optional[int], dtype: Any) -> tf.Tensor:
initial_state = tf.compat.v1.get_variable(name='initial-state',
initializer=tf.compat.v1.zeros_initializer(),
shape=[1, self._units],
dtype=dtype,
trainable=False)
return tf.tile(initial_state, multiples=(batch_size, 1)) # [B, D]
def __call__(self, inputs: tf.Tensor, state: tf.Tensor, scope=None) -> Tuple[tf.Tensor, tf.Tensor]:
scope = scope if scope is not None else type(self).__name__
with tf.compat.v1.variable_scope(scope):
# Apply the standard UGRNN update, [B, D]
next_state = ugrnn(inputs=inputs,
state=state,
W_transform=self.W_transform,
b_transform=self.b_transform,
activation=self._activation)
# Apply regularization noise
next_state = apply_noise(next_state, scale=self._recurrent_noise)
return next_state, next_state | 0.943387 | 0.298528 |
import numpy as np
import gym
from gym import spaces
from path_following.envs.envUtils import utils
from colorama import Fore, Style
class Tool5D(gym.Env):
metadata = {'render.modes': ['human', 'rgb_array']}
def __init__(self):
super(Tool5D, self).__init__()
"Initialize environment variables"
self.tlp = 100
self.blp = -100
self.tla = 180
self.bla = -180
self.timestepLimit = 1000
self.test = False
low_bound = np.array([self.blp, self.blp, self.blp, self.bla, self.bla])
high_bound = np.array([self.tlp, self.tlp, self.tlp, self.tla, self.tla])
low_bound = low_bound.reshape((5, 1))
high_bound = high_bound.reshape((5, 1))
self.observation_space = spaces.Box(low_bound, high_bound, dtype=np.float64)
# Action space tuple of 3 actions for each DoF
self.action_space = spaces.Box(-5.0, +5.0, (5,), dtype=np.float32)
self.episode = 0
self.viewer = None
def reset(self):
self.episode = 0
self.timestep = 0
self.cRew = 0.0
self.surf = utils.generate_surface()
self.traj, self.norms, self.curve = utils.get_norms(self.surf, self.timestepLimit)
if self.test:
offset = np.zeros((5,))
else:
offset = np.random.uniform(self.blp/2, self.tlp/2, (5,))
self.pos = np.array(self.traj[self.timestep]) + offset
self.pos = np.reshape(self.pos, (5, 1))
self.goal = np.array(self.traj[self.timestep])
self.goal = np.reshape(self.goal, (5, 1))
self.state = self.goal - self.pos
return self.state
def step(self, action):
action = action.reshape((5, 1))
self.pos += action
info = {"status": "ok"}
reward = 0.0
done = False
self.state = self.goal - self.pos
norm = np.linalg.norm(self.state)
r = np.float64(np.power(np.e, -0.1*norm))
if self.timestep > self.timestepLimit:
done = True
self.episode += 1
info["status"] = "Timestep limit"
# elif norm < 0.5:
# done = True
# info["status"] = "reached minimum norm"
reward += r
self.cRew += reward
self.timestep += 1
if self.timestep > self.timestepLimit-1:
self.goal = np.array(self.traj[self.timestepLimit-1])
else:
self.goal = np.array(self.traj[self.timestep])
self.goal = np.reshape(self.goal, (5, 1))
info["pos"] = self.pos
info["state"] = self.state
info["cRew"] = self.cRew
info["step"] = self.timestep
info["episode"] = self.episode
if done and norm < 5:
info['status'] = 'goal reached'
print(Fore.GREEN + "reward: {0:.2f}, timesteps: {1}, status: {2}\
".format(info["cRew"], info["step"], info["status"]) + Style.RESET_ALL)
return self.state, reward, done, info
def render(self, mode="human"):
pass
def close(self):
pass | path_following/envs/tcp_Tool5D.py | import numpy as np
import gym
from gym import spaces
from path_following.envs.envUtils import utils
from colorama import Fore, Style
class Tool5D(gym.Env):
metadata = {'render.modes': ['human', 'rgb_array']}
def __init__(self):
super(Tool5D, self).__init__()
"Initialize environment variables"
self.tlp = 100
self.blp = -100
self.tla = 180
self.bla = -180
self.timestepLimit = 1000
self.test = False
low_bound = np.array([self.blp, self.blp, self.blp, self.bla, self.bla])
high_bound = np.array([self.tlp, self.tlp, self.tlp, self.tla, self.tla])
low_bound = low_bound.reshape((5, 1))
high_bound = high_bound.reshape((5, 1))
self.observation_space = spaces.Box(low_bound, high_bound, dtype=np.float64)
# Action space tuple of 3 actions for each DoF
self.action_space = spaces.Box(-5.0, +5.0, (5,), dtype=np.float32)
self.episode = 0
self.viewer = None
def reset(self):
self.episode = 0
self.timestep = 0
self.cRew = 0.0
self.surf = utils.generate_surface()
self.traj, self.norms, self.curve = utils.get_norms(self.surf, self.timestepLimit)
if self.test:
offset = np.zeros((5,))
else:
offset = np.random.uniform(self.blp/2, self.tlp/2, (5,))
self.pos = np.array(self.traj[self.timestep]) + offset
self.pos = np.reshape(self.pos, (5, 1))
self.goal = np.array(self.traj[self.timestep])
self.goal = np.reshape(self.goal, (5, 1))
self.state = self.goal - self.pos
return self.state
def step(self, action):
action = action.reshape((5, 1))
self.pos += action
info = {"status": "ok"}
reward = 0.0
done = False
self.state = self.goal - self.pos
norm = np.linalg.norm(self.state)
r = np.float64(np.power(np.e, -0.1*norm))
if self.timestep > self.timestepLimit:
done = True
self.episode += 1
info["status"] = "Timestep limit"
# elif norm < 0.5:
# done = True
# info["status"] = "reached minimum norm"
reward += r
self.cRew += reward
self.timestep += 1
if self.timestep > self.timestepLimit-1:
self.goal = np.array(self.traj[self.timestepLimit-1])
else:
self.goal = np.array(self.traj[self.timestep])
self.goal = np.reshape(self.goal, (5, 1))
info["pos"] = self.pos
info["state"] = self.state
info["cRew"] = self.cRew
info["step"] = self.timestep
info["episode"] = self.episode
if done and norm < 5:
info['status'] = 'goal reached'
print(Fore.GREEN + "reward: {0:.2f}, timesteps: {1}, status: {2}\
".format(info["cRew"], info["step"], info["status"]) + Style.RESET_ALL)
return self.state, reward, done, info
def render(self, mode="human"):
pass
def close(self):
pass | 0.49707 | 0.374104 |
import os
import numpy as np
import tensorflow.keras.backend as K
from sklearn.base import BaseEstimator, TransformerMixin
from tensorflow.keras import regularizers
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model
class AutoencoderProjection(BaseEstimator, TransformerMixin):
def __init__(self, epochs=100, verbose=0):
self.epochs = epochs
self.autoencoder = None
self.encoder = None
self.decoder = None
self.verbose = verbose
self.is_fitted = False
K.clear_session()
def fit(self, X):
ae_input = Input(shape=(X.shape[1],))
encoded = Dense(512, activation='relu')(ae_input)
encoded = Dense(128, activation='relu')(encoded)
encoded = Dense(32, activation='relu')(encoded)
encoded = Dense(2, activation='linear')(encoded)
decoded = Dense(32, activation='relu', name='enc1')(encoded)
decoded = Dense(128, activation='relu', name='enc2')(decoded)
decoded = Dense(512, activation='relu', name='enc3')(decoded)
decoded = Dense(X.shape[1], activation='sigmoid', name='decoder_output')(decoded)
self.encoder = Model(inputs=ae_input, outputs=encoded)
self.autoencoder = Model(ae_input, decoded)
self.autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
self.autoencoder.fit( X,
X,
epochs=self.epochs,
batch_size=32,
shuffle=True,
verbose=self.verbose)
encoded_input = Input(shape=(2,))
l = self.autoencoder.get_layer('enc1')(encoded_input)
l = self.autoencoder.get_layer('enc2')(l)
l = self.autoencoder.get_layer('enc3')(l)
decoder_layer = self.autoencoder.get_layer('decoder_output')(l)
self.decoder = Model(encoded_input, decoder_layer)
self.is_fitted = True
def transform(self, X):
if self._is_fit():
return self.encoder.predict(X)
def inverse_transform(self, X_2d):
if self._is_fit():
return self.decoder.predict(X_2d)
def _is_fit(self):
if self.is_fitted:
return True
else:
raise Exception('Model not trained. Call fit() before calling transform()') | code/ae.py | import os
import numpy as np
import tensorflow.keras.backend as K
from sklearn.base import BaseEstimator, TransformerMixin
from tensorflow.keras import regularizers
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model
class AutoencoderProjection(BaseEstimator, TransformerMixin):
def __init__(self, epochs=100, verbose=0):
self.epochs = epochs
self.autoencoder = None
self.encoder = None
self.decoder = None
self.verbose = verbose
self.is_fitted = False
K.clear_session()
def fit(self, X):
ae_input = Input(shape=(X.shape[1],))
encoded = Dense(512, activation='relu')(ae_input)
encoded = Dense(128, activation='relu')(encoded)
encoded = Dense(32, activation='relu')(encoded)
encoded = Dense(2, activation='linear')(encoded)
decoded = Dense(32, activation='relu', name='enc1')(encoded)
decoded = Dense(128, activation='relu', name='enc2')(decoded)
decoded = Dense(512, activation='relu', name='enc3')(decoded)
decoded = Dense(X.shape[1], activation='sigmoid', name='decoder_output')(decoded)
self.encoder = Model(inputs=ae_input, outputs=encoded)
self.autoencoder = Model(ae_input, decoded)
self.autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
self.autoencoder.fit( X,
X,
epochs=self.epochs,
batch_size=32,
shuffle=True,
verbose=self.verbose)
encoded_input = Input(shape=(2,))
l = self.autoencoder.get_layer('enc1')(encoded_input)
l = self.autoencoder.get_layer('enc2')(l)
l = self.autoencoder.get_layer('enc3')(l)
decoder_layer = self.autoencoder.get_layer('decoder_output')(l)
self.decoder = Model(encoded_input, decoder_layer)
self.is_fitted = True
def transform(self, X):
if self._is_fit():
return self.encoder.predict(X)
def inverse_transform(self, X_2d):
if self._is_fit():
return self.decoder.predict(X_2d)
def _is_fit(self):
if self.is_fitted:
return True
else:
raise Exception('Model not trained. Call fit() before calling transform()') | 0.68056 | 0.208179 |
import re
import time
import string
import itertools as it
import numpy as np
import numba as nb
class ParserException (Exception):
""" Class to represent parser's exceptions """
@nb.vectorize(nopython = True, cache = True)
def np_bitwise_maj (x, y, z):
""" Bitwise MAJ function """
return (x & y) | (x & z) | (y & z)
maj_fmt = "({0} & {1}) | ({0} & {2}) | ({1} & {2})"
gates = {
"AND" : ( np.bitwise_and , 2 , "{} & {}" ),
"OR" : ( np.bitwise_or , 2 , "{} | {}" ),
"MAJ" : ( np_bitwise_maj , 3 , maj_fmt ),
"NOT" : ( np.bitwise_not , 1 , "~{}" ),
}
# Pre-compiled REGEXPs
remove_newline_comment = re.compile(r"//.*")
remove_two_not = re.compile(r"^(?:~~)+")
single_spaces = re.compile(r"\s+")
norm_spaces = re.compile(r"\s*([{},;()&|=])\s*")
binary_input = re.compile(r"^~?(?:1'b)?([01])$")
gates_split = re.compile(r"[&|]")
parse_file = re.compile(r"^module ([^\s]+) \((?:[^;]*)\) ; "
r"input ([^;]*) ; "
r"output ([^;]*) ; "
r"wire (?:[^;]*) ; "
r"((?:.* ; )*?)"
r"endmodule$")
def plain (gate):
""" Returns non-inverted gate name """
return gate.lstrip("~")
def invert (gate):
""" Inverts the gate name """
return plain(gate) if gate[0] == "~" else "~{}".format(gate)
def split_file (fname):
""" Splits file into pieces """
data = ""
with open(fname, "r") as f:
data = f.read()
info = parse_file.match(single_spaces.sub(r" ",
norm_spaces.sub(r" \1 ", remove_newline_comment.sub("", data))
).strip())
if info is None:
raise ParserException("Could not match file.")
# Break output into metadata
return (
info.group(1).strip(),
list(map(str.strip, info.group(2).split(","))),
list(map(str.strip, info.group(3).split(","))),
list(filter(bool, map(str.strip, info.group(4).split(";"))))
)
def sanitize_input (inp):
""" Sanitizes inputs' names by removing \
double inversors and finding fixed inputs (0 or 1) """
inp = remove_two_not.sub("", inp)
if binary_input.match(inp):
raise ParserException("Fixed inputs are not supported.")
return inp
def parse_args (rop, out):
""" Parse arguments """
args = []
unique = set()
strip = "();{}".format(string.whitespace)
for op in gates_split.split(rop):
op = sanitize_input(op.strip(strip))
if op == "" or op in unique:
continue
unique.add(op)
args.append(op)
return args
def parse_expression (expr):
""" Parse expression """
lop, rop = expr[ 7 : ].split("=", 1)
out = lop.strip()
# Count ands and ors
and_count = rop.count("&")
or_count = rop.count("|")
args = parse_args(rop, out)
# Tries to figure out the gate
if len(args) == 1:
gate = "I"
elif len(args) == 2:
if and_count == 1:
gate = "AND"
elif or_count == 1:
gate = "OR"
elif len(args) == 3:
if (and_count == 2 or and_count == 3) and or_count == 2:
gate = "MAJ"
if gate is None:
raise ParserException("Unknown operator at `{}`.".format(expr))
return out, gate, args
def topological_sort (inputs, parents, children):
""" Make a topological sort of the circuit """
# Start on the inputs
order = inputs.copy()
pos = 0
while pos < len(order):
node = order[pos]
# Iterate over children
for child in children.get(node, []):
parents[child] -= 1
if parents[child] == 0:
# Add to order if all parents were processed
order.append(child)
pos += 1
return order
def find_id (node, node_map, ids, circuit):
""" Find node id or insert it if inverted """
node = node_map.get(node, node)
if node not in ids:
# Create inversor if needed
if node[0] == "~":
ids[node] = len(ids)
circuit.append([ "NOT", ids[plain(node)] ])
# Could not find a valid argment
if node not in ids:
raise ParserException("Node `{}` undefined.".format(node))
return ids[node]
def build_circuit (order, inputs, gates, outputs):
""" Build circuit from pre-processed pieces """
# Assign IDs
ids = { inp : i for i, inp in enumerate(inputs) }
# Map to remove wires and indirect double inversors, e.g., a = ~b; c = ~a
node_map = {}
# Build circuit
circuit = []
# Iterate over topology, ignoring inputs
for pos in range(len(inputs), len(order)):
node = order[pos]
# Node does not have an expression
if node not in gates:
continue
gate, args = gates[node]
if gate == "I":
# Parse wires and inversors
arg = args[0]
iarg = invert(arg)
# Add node and its inverted value to map
node_map[node] = node_map.get(arg, arg)
node_map[invert(node)] = node_map.get(iarg, iarg)
continue
# Fetch arguments
arg_ids = [ find_id(arg, node_map, ids, circuit) for arg in args ]
ids[node] = len(ids)
circuit.append([ gate, *arg_ids ])
# Convert outputs to ids
outputs = [ find_id(out, node_map, ids, circuit) for out in outputs ]
return circuit, outputs
def convert (fname):
""" Convert verilog to a format closer to CGP's genotype """
# Split file data
module, inputs, outputs, exprs = split_file(fname)
parents = {}
children = {}
gates = {}
# Parse expressions
for out, gate, args in map(parse_expression, exprs):
parents[out] = len(args)
gates[out] = ( gate, args )
for arg in map(plain, args):
children.setdefault(arg, []).append(out)
order = topological_sort(inputs, parents, children)
circuit, outputs = build_circuit(order, inputs, gates, outputs)
return module, inputs, circuit, outputs | parser.py | import re
import time
import string
import itertools as it
import numpy as np
import numba as nb
class ParserException (Exception):
""" Class to represent parser's exceptions """
@nb.vectorize(nopython = True, cache = True)
def np_bitwise_maj (x, y, z):
""" Bitwise MAJ function """
return (x & y) | (x & z) | (y & z)
maj_fmt = "({0} & {1}) | ({0} & {2}) | ({1} & {2})"
gates = {
"AND" : ( np.bitwise_and , 2 , "{} & {}" ),
"OR" : ( np.bitwise_or , 2 , "{} | {}" ),
"MAJ" : ( np_bitwise_maj , 3 , maj_fmt ),
"NOT" : ( np.bitwise_not , 1 , "~{}" ),
}
# Pre-compiled REGEXPs
remove_newline_comment = re.compile(r"//.*")
remove_two_not = re.compile(r"^(?:~~)+")
single_spaces = re.compile(r"\s+")
norm_spaces = re.compile(r"\s*([{},;()&|=])\s*")
binary_input = re.compile(r"^~?(?:1'b)?([01])$")
gates_split = re.compile(r"[&|]")
parse_file = re.compile(r"^module ([^\s]+) \((?:[^;]*)\) ; "
r"input ([^;]*) ; "
r"output ([^;]*) ; "
r"wire (?:[^;]*) ; "
r"((?:.* ; )*?)"
r"endmodule$")
def plain (gate):
""" Returns non-inverted gate name """
return gate.lstrip("~")
def invert (gate):
""" Inverts the gate name """
return plain(gate) if gate[0] == "~" else "~{}".format(gate)
def split_file (fname):
""" Splits file into pieces """
data = ""
with open(fname, "r") as f:
data = f.read()
info = parse_file.match(single_spaces.sub(r" ",
norm_spaces.sub(r" \1 ", remove_newline_comment.sub("", data))
).strip())
if info is None:
raise ParserException("Could not match file.")
# Break output into metadata
return (
info.group(1).strip(),
list(map(str.strip, info.group(2).split(","))),
list(map(str.strip, info.group(3).split(","))),
list(filter(bool, map(str.strip, info.group(4).split(";"))))
)
def sanitize_input (inp):
""" Sanitizes inputs' names by removing \
double inversors and finding fixed inputs (0 or 1) """
inp = remove_two_not.sub("", inp)
if binary_input.match(inp):
raise ParserException("Fixed inputs are not supported.")
return inp
def parse_args (rop, out):
""" Parse arguments """
args = []
unique = set()
strip = "();{}".format(string.whitespace)
for op in gates_split.split(rop):
op = sanitize_input(op.strip(strip))
if op == "" or op in unique:
continue
unique.add(op)
args.append(op)
return args
def parse_expression (expr):
""" Parse expression """
lop, rop = expr[ 7 : ].split("=", 1)
out = lop.strip()
# Count ands and ors
and_count = rop.count("&")
or_count = rop.count("|")
args = parse_args(rop, out)
# Tries to figure out the gate
if len(args) == 1:
gate = "I"
elif len(args) == 2:
if and_count == 1:
gate = "AND"
elif or_count == 1:
gate = "OR"
elif len(args) == 3:
if (and_count == 2 or and_count == 3) and or_count == 2:
gate = "MAJ"
if gate is None:
raise ParserException("Unknown operator at `{}`.".format(expr))
return out, gate, args
def topological_sort (inputs, parents, children):
""" Make a topological sort of the circuit """
# Start on the inputs
order = inputs.copy()
pos = 0
while pos < len(order):
node = order[pos]
# Iterate over children
for child in children.get(node, []):
parents[child] -= 1
if parents[child] == 0:
# Add to order if all parents were processed
order.append(child)
pos += 1
return order
def find_id (node, node_map, ids, circuit):
""" Find node id or insert it if inverted """
node = node_map.get(node, node)
if node not in ids:
# Create inversor if needed
if node[0] == "~":
ids[node] = len(ids)
circuit.append([ "NOT", ids[plain(node)] ])
# Could not find a valid argment
if node not in ids:
raise ParserException("Node `{}` undefined.".format(node))
return ids[node]
def build_circuit (order, inputs, gates, outputs):
""" Build circuit from pre-processed pieces """
# Assign IDs
ids = { inp : i for i, inp in enumerate(inputs) }
# Map to remove wires and indirect double inversors, e.g., a = ~b; c = ~a
node_map = {}
# Build circuit
circuit = []
# Iterate over topology, ignoring inputs
for pos in range(len(inputs), len(order)):
node = order[pos]
# Node does not have an expression
if node not in gates:
continue
gate, args = gates[node]
if gate == "I":
# Parse wires and inversors
arg = args[0]
iarg = invert(arg)
# Add node and its inverted value to map
node_map[node] = node_map.get(arg, arg)
node_map[invert(node)] = node_map.get(iarg, iarg)
continue
# Fetch arguments
arg_ids = [ find_id(arg, node_map, ids, circuit) for arg in args ]
ids[node] = len(ids)
circuit.append([ gate, *arg_ids ])
# Convert outputs to ids
outputs = [ find_id(out, node_map, ids, circuit) for out in outputs ]
return circuit, outputs
def convert (fname):
""" Convert verilog to a format closer to CGP's genotype """
# Split file data
module, inputs, outputs, exprs = split_file(fname)
parents = {}
children = {}
gates = {}
# Parse expressions
for out, gate, args in map(parse_expression, exprs):
parents[out] = len(args)
gates[out] = ( gate, args )
for arg in map(plain, args):
children.setdefault(arg, []).append(out)
order = topological_sort(inputs, parents, children)
circuit, outputs = build_circuit(order, inputs, gates, outputs)
return module, inputs, circuit, outputs | 0.585338 | 0.413536 |
import ast
import operator
from peval.tools import Dispatcher, immutableadict, ast_equal, replace_fields
from peval.core.gensym import GenSym
from peval.core.reify import KnownValue, is_known_value, reify
from peval.wisdom import is_pure, get_signature
from peval.core.callable import inspect_callable
from peval.tools import immutabledict, fold_and, map_accum
from peval.tags import pure
UNARY_OPS = {
ast.UAdd: KnownValue(operator.pos),
ast.USub: KnownValue(operator.neg),
ast.Not: KnownValue(operator.not_),
ast.Invert: KnownValue(operator.invert),
}
BIN_OPS = {
ast.Add: KnownValue(operator.add),
ast.Sub: KnownValue(operator.sub),
ast.Mult: KnownValue(operator.mul),
ast.Div: KnownValue(operator.truediv),
ast.FloorDiv: KnownValue(operator.floordiv),
ast.Mod: KnownValue(operator.mod),
ast.Pow: KnownValue(operator.pow),
ast.LShift: KnownValue(operator.lshift),
ast.RShift: KnownValue(operator.rshift),
ast.BitOr: KnownValue(operator.or_),
ast.BitXor: KnownValue(operator.xor),
ast.BitAnd: KnownValue(operator.and_),
}
# Wrapping ``contains``, because its parameters
# do not follow the pattern (left operand, right operand).
@pure
def in_(x, y):
return operator.contains(y, x)
@pure
def not_in(x, y):
return not operator.contains(y, x)
COMPARE_OPS = {
ast.Eq: KnownValue(operator.eq),
ast.NotEq: KnownValue(operator.ne),
ast.Lt: KnownValue(operator.lt),
ast.LtE: KnownValue(operator.le),
ast.Gt: KnownValue(operator.gt),
ast.GtE: KnownValue(operator.ge),
ast.Is: KnownValue(operator.is_),
ast.IsNot: KnownValue(operator.is_not),
ast.In: KnownValue(in_),
ast.NotIn: KnownValue(not_in),
}
def _reify_func(acc, value, create_binding):
if is_known_value(value):
# For ``reify()`` we do not need to pass through
# the whole state, only ``gen_sym``.
gen_sym, bindings = acc
node, gen_sym, binding = reify(value, gen_sym, create_binding=create_binding)
return (gen_sym, bindings.update(binding)), node
else:
# Should be an AST node
return acc, value
def map_reify(state, container, create_binding=False):
acc = (state.gen_sym, immutabledict())
acc, new_container = map_accum(_reify_func, acc, container, create_binding)
gen_sym, bindings = acc
new_state = state.update(gen_sym=gen_sym, temp_bindings=state.temp_bindings.update(bindings))
return new_state, new_container
def map_peval_expression(state, container, ctx):
return map_accum(_peval_expression, state, container, ctx)
def map_get_value(container):
_, new_container = map_accum(lambda acc, kvalue: (acc, kvalue.value), None, container)
return new_container
def all_known_values(container):
return fold_and(is_known_value, container)
def all_known_values_or_none(container):
return fold_and(lambda val: (val is None or is_known_value(val)), container)
def try_call(obj, args=(), kwds={}):
# The only entry point for function calls.
callable_ = inspect_callable(obj)
if callable_.self_obj is not None:
args = (callable_.self_obj,) + args
obj = callable_.func_obj
if not is_pure(obj):
return False, None
try:
sig = get_signature(obj)
except ValueError:
return False, None
try:
sig.bind(*args, **kwds)
except TypeError:
# binding failed
return False, None
try:
value = obj(*args, **kwds)
except Exception:
return False, None
return True, value
def try_get_attribute(obj, name):
return try_call(getattr, args=(obj, name))
def try_call_method(obj, name, args=(), kwds={}):
success, attr = try_get_attribute(obj, name)
if not success:
return False, None
return try_call(attr, args=args, kwds=kwds)
def peval_call(state, ctx, func, args=[], keywords=[]):
assert all(type(arg) != ast.Starred for arg in args)
assert all(kw.arg is not None for kw in keywords)
keyword_expressions = [kw.value for kw in keywords]
state, results = map_peval_expression(
state, dict(func=func, args=args, keywords=keyword_expressions), ctx)
if all_known_values_or_none(results):
values = map_get_value(results)
kwds = {kw.arg: value for kw, value in zip(keywords, values['keywords'])}
success, value = try_eval_call(
values['func'], args=values['args'], keywords=kwds)
if success:
return state, KnownValue(value=value)
state, nodes = map_reify(state, results)
# restoring the keyword list
nodes['keywords'] = [
ast.keyword(arg=kw.arg, value=expr)
for kw, expr in zip(keywords, nodes['keywords'])]
return state, ast.Call(**nodes)
def try_eval_call(function, args=[], keywords=[]):
args = args
kwds = dict(keywords)
return try_call(function, args=args, kwds=kwds)
def peval_boolop(state, ctx, op, values):
assert type(op) in (ast.And, ast.Or)
new_values = []
for value in values:
state, new_value = _peval_expression(state, value, ctx)
# Short circuit
if is_known_value(new_value):
success, bool_value = try_call(bool, args=(new_value.value,))
short_circuit_applicable = (
success
and (
(type(op) == ast.And and not bool_value)
or (type(op) == ast.Or and bool_value)))
if short_circuit_applicable:
return state, new_value
# Just skip it, it won't change the BoolOp result.
else:
new_values.append(new_value)
if len(new_values) == 0:
return state, KnownValue(type(op) == ast.And)
elif len(new_values) == 1:
return state, new_values[0]
else:
return state, ast.BoolOp(op=op, values=new_values)
def peval_binop(state, ctx, op, left, right):
func = BIN_OPS[type(op)]
state, result = peval_call(state, ctx, func, args=[left, right])
if not is_known_value(result):
state = state.update(temp_bindings=state.temp_bindings.del_(result.func.id))
result = ast.BinOp(op=op, left=result.args[0], right=result.args[1])
return state, result
def peval_single_compare(state, ctx, op, left, right):
func = COMPARE_OPS[type(op)]
state, result = peval_call(state, ctx, func, args=[left, right])
if not is_known_value(result):
state = state.update(temp_bindings=state.temp_bindings.del_(result.func.id))
result = ast.Compare(left=result.args[0], ops=[op], comparators=[result.args[1]])
return state, result
def peval_compare(state, ctx, node):
if len(node.ops) == 1:
return peval_single_compare(state, ctx, node.ops[0], node.left, node.comparators[0])
values = []
for value_node in [node.left] + node.comparators:
state, value = _peval_expression(state, value_node, ctx)
values.append(value)
pair_values = []
lefts = [node.left] + node.comparators[:-1]
rights = node.comparators
for left, op, right in zip(lefts, node.ops, rights):
state, pair_value = peval_single_compare(state, ctx, op, left, right)
pair_values.append(pair_value)
state, result = peval_boolop(state, ctx, ast.And(), pair_values)
if is_known_value(result):
return state, result
if type(result) != ast.BoolOp:
return state, result
# Glueing non-evaluated comparisons back together.
nodes = [result.values[0]]
for value in result.values[1:]:
last_node = nodes[-1]
if (type(last_node) == ast.Compare
and type(value) == ast.Compare
and ast_equal(last_node.comparators[-1], value.left)):
nodes[-1] = ast.Compare(
left=last_node.left,
ops=last_node.ops + value.ops,
comparators=last_node.comparators + value.comparators)
else:
nodes.append(value)
if len(nodes) == 1:
return state, nodes[0]
else:
return state, ast.BoolOp(op=ast.And(), values=nodes)
class CannotEvaluateComprehension(Exception):
pass
class ListAccumulator:
def __init__(self):
self.accum = []
def add_elem(self, elem):
self.accum.append(elem)
def add_part(self, part):
self.accum.extend(part)
def get_accum(self):
return self.accum
class SetAccumulator:
def __init__(self):
self.accum = set()
def add_elem(self, elem):
self.accum.add(elem)
def add_part(self, part):
self.accum.update(part)
def get_accum(self):
return self.accum
class DictAccumulator:
def __init__(self):
self.accum = {}
def add_elem(self, elem):
self.accum[elem[0]] = elem[1]
def add_part(self, part):
self.accum.update(part)
def get_accum(self):
return self.accum
class GeneratorExpAccumulator:
"""
This is just a list that presents itself as a generator expression
(to preserve the type after partial evaluation).
Since we are evaluating each of its elements before returning it anyway,
it does not really matter.
"""
def __init__(self):
self.accum = []
def add_elem(self, elem):
self.accum.append(elem)
def add_part(self, part):
self.accum.extend(list(part))
def get_accum(self):
return (x for x in self.accum)
def peval_comprehension(state, node, ctx):
accum_cls = {
ast.ListComp: ListAccumulator,
ast.GeneratorExp: GeneratorExpAccumulator,
ast.SetComp: SetAccumulator,
ast.DictComp: DictAccumulator,
}
# variables from generators temporary mask bindings
target_names = set()
for generator in node.generators:
if type(generator.target) == ast.Name:
target_names.add(generator.target.id)
else:
target_names.update([elt.id for elt in generator.target.elts])
# pre-evaluate the expression
elt_bindings = dict(ctx.bindings)
for name in target_names:
if name in elt_bindings:
del elt_bindings[name]
elt_ctx = ctx.update(bindings=elt_bindings)
if type(node) == ast.DictComp:
elt = ast.Tuple(elts=[node.key, node.value])
else:
elt = node.elt
state, new_elt = _peval_expression(state, elt, elt_ctx)
try:
state, container = _peval_comprehension(
state, accum_cls[type(node)], new_elt, node.generators, ctx)
evaluated = True
except CannotEvaluateComprehension:
evaluated = False
if evaluated:
return state, KnownValue(value=container)
else:
state, new_elt = map_reify(state, new_elt)
state, new_generators = _peval_comprehension_generators(state, node.generators, ctx)
if type(node) == ast.DictComp:
key, value = new_elt.elts
return state, replace_fields(node, key=key, value=value, generators=new_generators)
else:
return state, replace_fields(node, elt=new_elt, generators=new_generators)
def _peval_comprehension_ifs(state, ifs, ctx):
if len(ifs) > 0:
joint_ifs = ast.BoolOp(op=ast.And(), values=ifs)
state, joint_ifs_result = _peval_expression(state, joint_ifs, ctx)
if is_known_value(joint_ifs_result):
return state, joint_ifs_result
else:
return state, joint_ifs_result.values
else:
return state, KnownValue(value=True)
def _get_masked_bindings(target, bindings):
if type(target) == ast.Name:
target_names = [target.id]
else:
target_names = [elt.id for elt in target.elts]
new_bindings = dict(bindings)
for name in target_names:
if name in new_bindings:
del new_bindings[name]
return new_bindings
def _peval_comprehension_generators(state, generators, ctx):
if len(generators) == 0:
return state, []
generator = generators[0]
next_generators = generators[1:]
state, iter_result = _peval_expression(state, generator.iter, ctx)
masked_bindings = _get_masked_bindings(generator.target, ctx.bindings)
masked_ctx = ctx.set('bindings', masked_bindings)
state, ifs_result = _peval_comprehension_ifs(state, generator.ifs, masked_ctx)
if is_known_value(ifs_result):
success, bool_value = try_call(bool, args=(ifs_result.value,))
if success and bool_value:
ifs_result = []
state, new_generator_kwds = map_reify(
state, dict(target=generator.target, iter=iter_result, ifs=ifs_result))
new_generator = ast.comprehension(**new_generator_kwds)
state, new_generators = _peval_comprehension_generators(state, next_generators, ctx)
return state, [new_generator] + new_generators
def _try_unpack_sequence(seq, node):
# node is either a Name, a Tuple of Names, or a List of Names
if type(node) == ast.Name:
return True, {node.id: seq}
elif type(node) in (ast.Tuple, ast.List):
if not all(type(elt) == ast.Name for elt in node.elts):
return False, None
bindings = {}
success, it = try_call(iter, args=(seq,))
if not success:
return False, None
if it is seq:
return False, None
for elt in node.elts:
try:
elem = next(it)
except StopIteration:
return False, None
bindings[elt.id] = elem
try:
elem = next(it)
except StopIteration:
return True, bindings
return False, None
else:
return False, None
def _peval_comprehension(state, accum_cls, elt, generators, ctx):
generator = generators[0]
next_generators = generators[1:]
state, iter_result = _peval_expression(state, generator.iter, ctx)
masked_bindings = _get_masked_bindings(generator.target, ctx.bindings)
masked_ctx = ctx.set('bindings', masked_bindings)
state, ifs_result = _peval_comprehension_ifs(state, generator.ifs, masked_ctx)
if is_known_value(iter_result):
iterable = iter_result.value
iterator_evaluated, iterator = try_call(iter, args=(iterable,))
else:
iterator_evaluated = False
if not iterator_evaluated or iterator is iterable:
raise CannotEvaluateComprehension
accum = accum_cls()
for targets in iterable:
unpacked, target_bindings = _try_unpack_sequence(targets, generator.target)
if not unpacked:
raise CannotEvaluateComprehension
iter_bindings = dict(ctx.bindings)
iter_bindings.update(target_bindings)
iter_ctx = ctx.set('bindings', iter_bindings)
state, ifs_value = _peval_expression(state, ifs_result, iter_ctx)
if not is_known_value(ifs_value):
raise CannotEvaluateComprehension
success, bool_value = try_call(bool, args=(ifs_value.value,))
if not success:
raise CannotEvaluateComprehension
if success and not bool_value:
continue
if len(next_generators) == 0:
state, elt_result = _peval_expression(state, elt, iter_ctx)
if not is_known_value(elt_result):
raise CannotEvaluateComprehension
accum.add_elem(elt_result.value)
else:
state, part = _peval_comprehension(state, accum_cls, elt, next_generators, iter_ctx)
accum.add_part(part)
return state, accum.get_accum()
@Dispatcher
class _peval_expression_dispatcher:
@staticmethod
def handle(state, node, _):
# Pass through in case of type(node) == KnownValue
return state, node
@staticmethod
def handle_Name(state, node, ctx):
name = node.id
if name in ctx.bindings:
return state, KnownValue(ctx.bindings[name], preferred_name=name)
else:
return state, node
@staticmethod
def handle_Num(state, node, _):
return state, KnownValue(node.n)
@staticmethod
def handle_Str(state, node, _):
return state, KnownValue(node.s)
@staticmethod
def handle_Bytes(state, node, _):
return state, KnownValue(node.s)
@staticmethod
def handle_NameConstant(state, node, _):
return state, KnownValue(node.value)
@staticmethod
def handle_Constant(state, node, _):
return state, KnownValue(node.value)
@staticmethod
def handle_BoolOp(state, node, ctx):
return peval_boolop(state, ctx, node.op, node.values)
@staticmethod
def handle_BinOp(state, node, ctx):
return peval_binop(state, ctx, node.op, node.left, node.right)
@staticmethod
def handle_UnaryOp(state, node, ctx):
state, result = peval_call(
state, ctx, UNARY_OPS[type(node.op)], args=[node.operand])
if not is_known_value(result):
state = state.update(temp_bindings=state.temp_bindings.del_(result.func.id))
result = ast.UnaryOp(op=node.op, operand=result.args[0])
return state, result
@staticmethod
def handle_Lambda(state, node, ctx):
raise NotImplementedError
@staticmethod
def handle_IfExp(state, node, ctx):
state, test_value = _peval_expression(state, node.test, ctx)
if is_known_value(test_value):
success, bool_value = try_call(bool, args=(test_value.value,))
if success:
taken_node = node.body if bool_value else node.orelse
return _peval_expression(state, taken_node, ctx)
state, new_body = _peval_expression(state, node.body, ctx)
state, new_orelse = _peval_expression(state, node.orelse, ctx)
state, new_body_node = map_reify(state, new_body)
state, new_orelse_node = map_reify(state, new_orelse)
return state, replace_fields(
node, test=test_value, body=new_body_node, orelse=new_orelse_node)
@staticmethod
def handle_Dict(state, node, ctx):
state, pairs = map_peval_expression(state, zip(node.keys, node.values), ctx)
can_eval = all_known_values(pairs)
if can_eval:
new_dict = dict((key.value, value.value) for key, value in pairs)
return state, KnownValue(value=new_dict)
else:
state, keys_values = map_reify(state, zip(*pairs))
new_node = replace_fields(node, keys=list(keys_values[0]), values=list(keys_values[1]))
return state, new_node
@staticmethod
def handle_List(state, node, ctx):
state, elts = map_peval_expression(state, node.elts, ctx)
can_eval = all_known_values(elts)
if can_eval:
new_list = [elt.value for elt in elts]
return state, KnownValue(value=new_list)
else:
state, new_elts = map_reify(state, elts)
return state, replace_fields(node, elts=new_elts)
@staticmethod
def handle_Tuple(state, node, ctx):
state, elts = map_peval_expression(state, node.elts, ctx)
can_eval = all_known_values(elts)
if can_eval:
new_list = tuple(elt.value for elt in elts)
return state, KnownValue(value=new_list)
else:
state, new_elts = map_reify(state, elts)
return state, replace_fields(node, elts=new_elts)
@staticmethod
def handle_Set(state, node, ctx):
state, elts = map_peval_expression(state, node.elts, ctx)
can_eval = all_known_values(elts)
if can_eval:
new_set = set(elt.value for elt in elts)
return state, KnownValue(value=new_set)
else:
state, new_elts = map_reify(state, elts)
return state, replace_fields(node, elts=new_elts)
@staticmethod
def handle_ListComp(state, node, ctx):
return peval_comprehension(state, node, ctx)
@staticmethod
def handle_SetComp(state, node, ctx):
return peval_comprehension(state, node, ctx)
@staticmethod
def handle_DictComp(state, node, ctx):
return peval_comprehension(state, node, ctx)
@staticmethod
def handle_GeneratorExp(state, node, ctx):
return peval_comprehension(state, node, ctx)
@staticmethod
def handle_Yield(state, node, ctx):
state, result = _peval_expression(state, node.value, ctx)
# We cannot evaluate a yield expression,
# so just wrap whatever we've got in a node and return.
state, new_value = map_reify(state, result)
return state, replace_fields(node, value=new_value)
@staticmethod
def handle_YieldFrom(state, node, ctx):
state, result = _peval_expression(state, node.value, ctx)
# We cannot evaluate a yield expression,
# so just wrap whatever we've got in a node and return.
state, new_value = map_reify(state, result)
return state, replace_fields(node, value=new_value)
@staticmethod
def handle_Compare(state, node, ctx):
return peval_compare(state, ctx, node)
@staticmethod
def handle_Call(state, node, ctx):
return peval_call(state, ctx, node.func, args=node.args, keywords=node.keywords)
@staticmethod
def handle_Attribute(state, node, ctx):
state, result = _peval_expression(state, node.value, ctx)
if is_known_value(result):
success, attr = try_get_attribute(result.value, node.attr)
if success:
return state, KnownValue(value=attr)
state, new_value = map_reify(state, result)
return state, replace_fields(node, value=new_value)
@staticmethod
def handle_Subscript(state, node, ctx):
state, value_result = _peval_expression(state, node.value, ctx)
state, slice_result = _peval_expression(state, node.slice, ctx)
if is_known_value(value_result) and is_known_value(slice_result):
success, elem = try_call_method(
value_result.value, '__getitem__', args=(slice_result.value,))
if success:
return state, KnownValue(value=elem)
state, new_value = map_reify(state, value_result)
state, new_slice = map_reify(state, slice_result)
if type(new_slice) not in (ast.Index, ast.Slice, ast.ExtSlice):
new_slice = ast.Index(value=new_slice)
return state, replace_fields(node, value=new_value, slice=new_slice)
@staticmethod
def handle_Index(state, node, ctx):
state, result = _peval_expression(state, node.value, ctx)
if is_known_value(result):
return state, KnownValue(value=result.value)
else:
return state, result
@staticmethod
def handle_Slice(state, node, ctx):
state, results = map_peval_expression(state, (node.lower, node.upper, node.step), ctx)
# how do we handle None values in nodes? Technically, they are known values
if all_known_values_or_none(results):
lower, upper, step = [result if result is None else result.value for result in results]
return state, KnownValue(value=slice(lower, upper, step))
state, new_nodes = map_reify(state, results)
new_node = replace_fields(node, lower=new_nodes[0], upper=new_nodes[1], step=new_nodes[2])
return state, new_node
@staticmethod
def handle_ExtSlice(state, node, ctx):
state, results = map_peval_expression(state, node.dims, ctx)
if all_known_values(results):
return state, KnownValue(value=tuple(result.value for result in results))
state, new_nodes = map_reify(state, results)
return state, replace_fields(node, dims=new_nodes)
class EvaluationResult:
def __init__(self, fully_evaluated, node, temp_bindings, value=None):
self.fully_evaluated = fully_evaluated
if fully_evaluated:
self.value = value
self.temp_bindings = temp_bindings
self.node = node
def _peval_expression(state, node, ctx):
return _peval_expression_dispatcher(node, state, node, ctx)
def peval_expression(node, gen_sym, bindings, create_binding=False):
ctx = immutableadict(bindings=bindings)
state = immutableadict(gen_sym=gen_sym, temp_bindings=immutableadict())
state, result = _peval_expression(state, node, ctx)
if is_known_value(result):
state, result_node = map_reify(state, result, create_binding)
eval_result = EvaluationResult(
fully_evaluated=True,
value=result.value,
node=result_node,
temp_bindings=state.temp_bindings)
else:
eval_result = EvaluationResult(
fully_evaluated=False,
node=result,
temp_bindings=state.temp_bindings)
return eval_result, state.gen_sym
def try_peval_expression(node, bindings):
"""
Try to partially evaluate the AST expression ``node`` using the dictionary ``bindings``.
Returns a pair ``(evaluated, result)``, where ``evaluated`` is a boolean
and ``result`` is the evaulation result if ``evaluated`` is ``True``,
and an AST expression otherwise.
"""
gen_sym = GenSym()
eval_result, gen_sym = peval_expression(node, gen_sym, bindings)
if eval_result.fully_evaluated:
return True, eval_result.value
else:
return False, node | peval/core/expression.py | import ast
import operator
from peval.tools import Dispatcher, immutableadict, ast_equal, replace_fields
from peval.core.gensym import GenSym
from peval.core.reify import KnownValue, is_known_value, reify
from peval.wisdom import is_pure, get_signature
from peval.core.callable import inspect_callable
from peval.tools import immutabledict, fold_and, map_accum
from peval.tags import pure
UNARY_OPS = {
ast.UAdd: KnownValue(operator.pos),
ast.USub: KnownValue(operator.neg),
ast.Not: KnownValue(operator.not_),
ast.Invert: KnownValue(operator.invert),
}
BIN_OPS = {
ast.Add: KnownValue(operator.add),
ast.Sub: KnownValue(operator.sub),
ast.Mult: KnownValue(operator.mul),
ast.Div: KnownValue(operator.truediv),
ast.FloorDiv: KnownValue(operator.floordiv),
ast.Mod: KnownValue(operator.mod),
ast.Pow: KnownValue(operator.pow),
ast.LShift: KnownValue(operator.lshift),
ast.RShift: KnownValue(operator.rshift),
ast.BitOr: KnownValue(operator.or_),
ast.BitXor: KnownValue(operator.xor),
ast.BitAnd: KnownValue(operator.and_),
}
# Wrapping ``contains``, because its parameters
# do not follow the pattern (left operand, right operand).
@pure
def in_(x, y):
return operator.contains(y, x)
@pure
def not_in(x, y):
return not operator.contains(y, x)
COMPARE_OPS = {
ast.Eq: KnownValue(operator.eq),
ast.NotEq: KnownValue(operator.ne),
ast.Lt: KnownValue(operator.lt),
ast.LtE: KnownValue(operator.le),
ast.Gt: KnownValue(operator.gt),
ast.GtE: KnownValue(operator.ge),
ast.Is: KnownValue(operator.is_),
ast.IsNot: KnownValue(operator.is_not),
ast.In: KnownValue(in_),
ast.NotIn: KnownValue(not_in),
}
def _reify_func(acc, value, create_binding):
if is_known_value(value):
# For ``reify()`` we do not need to pass through
# the whole state, only ``gen_sym``.
gen_sym, bindings = acc
node, gen_sym, binding = reify(value, gen_sym, create_binding=create_binding)
return (gen_sym, bindings.update(binding)), node
else:
# Should be an AST node
return acc, value
def map_reify(state, container, create_binding=False):
acc = (state.gen_sym, immutabledict())
acc, new_container = map_accum(_reify_func, acc, container, create_binding)
gen_sym, bindings = acc
new_state = state.update(gen_sym=gen_sym, temp_bindings=state.temp_bindings.update(bindings))
return new_state, new_container
def map_peval_expression(state, container, ctx):
return map_accum(_peval_expression, state, container, ctx)
def map_get_value(container):
_, new_container = map_accum(lambda acc, kvalue: (acc, kvalue.value), None, container)
return new_container
def all_known_values(container):
return fold_and(is_known_value, container)
def all_known_values_or_none(container):
return fold_and(lambda val: (val is None or is_known_value(val)), container)
def try_call(obj, args=(), kwds={}):
# The only entry point for function calls.
callable_ = inspect_callable(obj)
if callable_.self_obj is not None:
args = (callable_.self_obj,) + args
obj = callable_.func_obj
if not is_pure(obj):
return False, None
try:
sig = get_signature(obj)
except ValueError:
return False, None
try:
sig.bind(*args, **kwds)
except TypeError:
# binding failed
return False, None
try:
value = obj(*args, **kwds)
except Exception:
return False, None
return True, value
def try_get_attribute(obj, name):
return try_call(getattr, args=(obj, name))
def try_call_method(obj, name, args=(), kwds={}):
success, attr = try_get_attribute(obj, name)
if not success:
return False, None
return try_call(attr, args=args, kwds=kwds)
def peval_call(state, ctx, func, args=[], keywords=[]):
assert all(type(arg) != ast.Starred for arg in args)
assert all(kw.arg is not None for kw in keywords)
keyword_expressions = [kw.value for kw in keywords]
state, results = map_peval_expression(
state, dict(func=func, args=args, keywords=keyword_expressions), ctx)
if all_known_values_or_none(results):
values = map_get_value(results)
kwds = {kw.arg: value for kw, value in zip(keywords, values['keywords'])}
success, value = try_eval_call(
values['func'], args=values['args'], keywords=kwds)
if success:
return state, KnownValue(value=value)
state, nodes = map_reify(state, results)
# restoring the keyword list
nodes['keywords'] = [
ast.keyword(arg=kw.arg, value=expr)
for kw, expr in zip(keywords, nodes['keywords'])]
return state, ast.Call(**nodes)
def try_eval_call(function, args=[], keywords=[]):
args = args
kwds = dict(keywords)
return try_call(function, args=args, kwds=kwds)
def peval_boolop(state, ctx, op, values):
assert type(op) in (ast.And, ast.Or)
new_values = []
for value in values:
state, new_value = _peval_expression(state, value, ctx)
# Short circuit
if is_known_value(new_value):
success, bool_value = try_call(bool, args=(new_value.value,))
short_circuit_applicable = (
success
and (
(type(op) == ast.And and not bool_value)
or (type(op) == ast.Or and bool_value)))
if short_circuit_applicable:
return state, new_value
# Just skip it, it won't change the BoolOp result.
else:
new_values.append(new_value)
if len(new_values) == 0:
return state, KnownValue(type(op) == ast.And)
elif len(new_values) == 1:
return state, new_values[0]
else:
return state, ast.BoolOp(op=op, values=new_values)
def peval_binop(state, ctx, op, left, right):
func = BIN_OPS[type(op)]
state, result = peval_call(state, ctx, func, args=[left, right])
if not is_known_value(result):
state = state.update(temp_bindings=state.temp_bindings.del_(result.func.id))
result = ast.BinOp(op=op, left=result.args[0], right=result.args[1])
return state, result
def peval_single_compare(state, ctx, op, left, right):
func = COMPARE_OPS[type(op)]
state, result = peval_call(state, ctx, func, args=[left, right])
if not is_known_value(result):
state = state.update(temp_bindings=state.temp_bindings.del_(result.func.id))
result = ast.Compare(left=result.args[0], ops=[op], comparators=[result.args[1]])
return state, result
def peval_compare(state, ctx, node):
if len(node.ops) == 1:
return peval_single_compare(state, ctx, node.ops[0], node.left, node.comparators[0])
values = []
for value_node in [node.left] + node.comparators:
state, value = _peval_expression(state, value_node, ctx)
values.append(value)
pair_values = []
lefts = [node.left] + node.comparators[:-1]
rights = node.comparators
for left, op, right in zip(lefts, node.ops, rights):
state, pair_value = peval_single_compare(state, ctx, op, left, right)
pair_values.append(pair_value)
state, result = peval_boolop(state, ctx, ast.And(), pair_values)
if is_known_value(result):
return state, result
if type(result) != ast.BoolOp:
return state, result
# Glueing non-evaluated comparisons back together.
nodes = [result.values[0]]
for value in result.values[1:]:
last_node = nodes[-1]
if (type(last_node) == ast.Compare
and type(value) == ast.Compare
and ast_equal(last_node.comparators[-1], value.left)):
nodes[-1] = ast.Compare(
left=last_node.left,
ops=last_node.ops + value.ops,
comparators=last_node.comparators + value.comparators)
else:
nodes.append(value)
if len(nodes) == 1:
return state, nodes[0]
else:
return state, ast.BoolOp(op=ast.And(), values=nodes)
class CannotEvaluateComprehension(Exception):
pass
class ListAccumulator:
def __init__(self):
self.accum = []
def add_elem(self, elem):
self.accum.append(elem)
def add_part(self, part):
self.accum.extend(part)
def get_accum(self):
return self.accum
class SetAccumulator:
def __init__(self):
self.accum = set()
def add_elem(self, elem):
self.accum.add(elem)
def add_part(self, part):
self.accum.update(part)
def get_accum(self):
return self.accum
class DictAccumulator:
def __init__(self):
self.accum = {}
def add_elem(self, elem):
self.accum[elem[0]] = elem[1]
def add_part(self, part):
self.accum.update(part)
def get_accum(self):
return self.accum
class GeneratorExpAccumulator:
"""
This is just a list that presents itself as a generator expression
(to preserve the type after partial evaluation).
Since we are evaluating each of its elements before returning it anyway,
it does not really matter.
"""
def __init__(self):
self.accum = []
def add_elem(self, elem):
self.accum.append(elem)
def add_part(self, part):
self.accum.extend(list(part))
def get_accum(self):
return (x for x in self.accum)
def peval_comprehension(state, node, ctx):
accum_cls = {
ast.ListComp: ListAccumulator,
ast.GeneratorExp: GeneratorExpAccumulator,
ast.SetComp: SetAccumulator,
ast.DictComp: DictAccumulator,
}
# variables from generators temporary mask bindings
target_names = set()
for generator in node.generators:
if type(generator.target) == ast.Name:
target_names.add(generator.target.id)
else:
target_names.update([elt.id for elt in generator.target.elts])
# pre-evaluate the expression
elt_bindings = dict(ctx.bindings)
for name in target_names:
if name in elt_bindings:
del elt_bindings[name]
elt_ctx = ctx.update(bindings=elt_bindings)
if type(node) == ast.DictComp:
elt = ast.Tuple(elts=[node.key, node.value])
else:
elt = node.elt
state, new_elt = _peval_expression(state, elt, elt_ctx)
try:
state, container = _peval_comprehension(
state, accum_cls[type(node)], new_elt, node.generators, ctx)
evaluated = True
except CannotEvaluateComprehension:
evaluated = False
if evaluated:
return state, KnownValue(value=container)
else:
state, new_elt = map_reify(state, new_elt)
state, new_generators = _peval_comprehension_generators(state, node.generators, ctx)
if type(node) == ast.DictComp:
key, value = new_elt.elts
return state, replace_fields(node, key=key, value=value, generators=new_generators)
else:
return state, replace_fields(node, elt=new_elt, generators=new_generators)
def _peval_comprehension_ifs(state, ifs, ctx):
if len(ifs) > 0:
joint_ifs = ast.BoolOp(op=ast.And(), values=ifs)
state, joint_ifs_result = _peval_expression(state, joint_ifs, ctx)
if is_known_value(joint_ifs_result):
return state, joint_ifs_result
else:
return state, joint_ifs_result.values
else:
return state, KnownValue(value=True)
def _get_masked_bindings(target, bindings):
if type(target) == ast.Name:
target_names = [target.id]
else:
target_names = [elt.id for elt in target.elts]
new_bindings = dict(bindings)
for name in target_names:
if name in new_bindings:
del new_bindings[name]
return new_bindings
def _peval_comprehension_generators(state, generators, ctx):
if len(generators) == 0:
return state, []
generator = generators[0]
next_generators = generators[1:]
state, iter_result = _peval_expression(state, generator.iter, ctx)
masked_bindings = _get_masked_bindings(generator.target, ctx.bindings)
masked_ctx = ctx.set('bindings', masked_bindings)
state, ifs_result = _peval_comprehension_ifs(state, generator.ifs, masked_ctx)
if is_known_value(ifs_result):
success, bool_value = try_call(bool, args=(ifs_result.value,))
if success and bool_value:
ifs_result = []
state, new_generator_kwds = map_reify(
state, dict(target=generator.target, iter=iter_result, ifs=ifs_result))
new_generator = ast.comprehension(**new_generator_kwds)
state, new_generators = _peval_comprehension_generators(state, next_generators, ctx)
return state, [new_generator] + new_generators
def _try_unpack_sequence(seq, node):
# node is either a Name, a Tuple of Names, or a List of Names
if type(node) == ast.Name:
return True, {node.id: seq}
elif type(node) in (ast.Tuple, ast.List):
if not all(type(elt) == ast.Name for elt in node.elts):
return False, None
bindings = {}
success, it = try_call(iter, args=(seq,))
if not success:
return False, None
if it is seq:
return False, None
for elt in node.elts:
try:
elem = next(it)
except StopIteration:
return False, None
bindings[elt.id] = elem
try:
elem = next(it)
except StopIteration:
return True, bindings
return False, None
else:
return False, None
def _peval_comprehension(state, accum_cls, elt, generators, ctx):
generator = generators[0]
next_generators = generators[1:]
state, iter_result = _peval_expression(state, generator.iter, ctx)
masked_bindings = _get_masked_bindings(generator.target, ctx.bindings)
masked_ctx = ctx.set('bindings', masked_bindings)
state, ifs_result = _peval_comprehension_ifs(state, generator.ifs, masked_ctx)
if is_known_value(iter_result):
iterable = iter_result.value
iterator_evaluated, iterator = try_call(iter, args=(iterable,))
else:
iterator_evaluated = False
if not iterator_evaluated or iterator is iterable:
raise CannotEvaluateComprehension
accum = accum_cls()
for targets in iterable:
unpacked, target_bindings = _try_unpack_sequence(targets, generator.target)
if not unpacked:
raise CannotEvaluateComprehension
iter_bindings = dict(ctx.bindings)
iter_bindings.update(target_bindings)
iter_ctx = ctx.set('bindings', iter_bindings)
state, ifs_value = _peval_expression(state, ifs_result, iter_ctx)
if not is_known_value(ifs_value):
raise CannotEvaluateComprehension
success, bool_value = try_call(bool, args=(ifs_value.value,))
if not success:
raise CannotEvaluateComprehension
if success and not bool_value:
continue
if len(next_generators) == 0:
state, elt_result = _peval_expression(state, elt, iter_ctx)
if not is_known_value(elt_result):
raise CannotEvaluateComprehension
accum.add_elem(elt_result.value)
else:
state, part = _peval_comprehension(state, accum_cls, elt, next_generators, iter_ctx)
accum.add_part(part)
return state, accum.get_accum()
@Dispatcher
class _peval_expression_dispatcher:
@staticmethod
def handle(state, node, _):
# Pass through in case of type(node) == KnownValue
return state, node
@staticmethod
def handle_Name(state, node, ctx):
name = node.id
if name in ctx.bindings:
return state, KnownValue(ctx.bindings[name], preferred_name=name)
else:
return state, node
@staticmethod
def handle_Num(state, node, _):
return state, KnownValue(node.n)
@staticmethod
def handle_Str(state, node, _):
return state, KnownValue(node.s)
@staticmethod
def handle_Bytes(state, node, _):
return state, KnownValue(node.s)
@staticmethod
def handle_NameConstant(state, node, _):
return state, KnownValue(node.value)
@staticmethod
def handle_Constant(state, node, _):
return state, KnownValue(node.value)
@staticmethod
def handle_BoolOp(state, node, ctx):
return peval_boolop(state, ctx, node.op, node.values)
@staticmethod
def handle_BinOp(state, node, ctx):
return peval_binop(state, ctx, node.op, node.left, node.right)
@staticmethod
def handle_UnaryOp(state, node, ctx):
state, result = peval_call(
state, ctx, UNARY_OPS[type(node.op)], args=[node.operand])
if not is_known_value(result):
state = state.update(temp_bindings=state.temp_bindings.del_(result.func.id))
result = ast.UnaryOp(op=node.op, operand=result.args[0])
return state, result
@staticmethod
def handle_Lambda(state, node, ctx):
raise NotImplementedError
@staticmethod
def handle_IfExp(state, node, ctx):
state, test_value = _peval_expression(state, node.test, ctx)
if is_known_value(test_value):
success, bool_value = try_call(bool, args=(test_value.value,))
if success:
taken_node = node.body if bool_value else node.orelse
return _peval_expression(state, taken_node, ctx)
state, new_body = _peval_expression(state, node.body, ctx)
state, new_orelse = _peval_expression(state, node.orelse, ctx)
state, new_body_node = map_reify(state, new_body)
state, new_orelse_node = map_reify(state, new_orelse)
return state, replace_fields(
node, test=test_value, body=new_body_node, orelse=new_orelse_node)
@staticmethod
def handle_Dict(state, node, ctx):
state, pairs = map_peval_expression(state, zip(node.keys, node.values), ctx)
can_eval = all_known_values(pairs)
if can_eval:
new_dict = dict((key.value, value.value) for key, value in pairs)
return state, KnownValue(value=new_dict)
else:
state, keys_values = map_reify(state, zip(*pairs))
new_node = replace_fields(node, keys=list(keys_values[0]), values=list(keys_values[1]))
return state, new_node
@staticmethod
def handle_List(state, node, ctx):
state, elts = map_peval_expression(state, node.elts, ctx)
can_eval = all_known_values(elts)
if can_eval:
new_list = [elt.value for elt in elts]
return state, KnownValue(value=new_list)
else:
state, new_elts = map_reify(state, elts)
return state, replace_fields(node, elts=new_elts)
@staticmethod
def handle_Tuple(state, node, ctx):
state, elts = map_peval_expression(state, node.elts, ctx)
can_eval = all_known_values(elts)
if can_eval:
new_list = tuple(elt.value for elt in elts)
return state, KnownValue(value=new_list)
else:
state, new_elts = map_reify(state, elts)
return state, replace_fields(node, elts=new_elts)
@staticmethod
def handle_Set(state, node, ctx):
state, elts = map_peval_expression(state, node.elts, ctx)
can_eval = all_known_values(elts)
if can_eval:
new_set = set(elt.value for elt in elts)
return state, KnownValue(value=new_set)
else:
state, new_elts = map_reify(state, elts)
return state, replace_fields(node, elts=new_elts)
@staticmethod
def handle_ListComp(state, node, ctx):
return peval_comprehension(state, node, ctx)
@staticmethod
def handle_SetComp(state, node, ctx):
return peval_comprehension(state, node, ctx)
@staticmethod
def handle_DictComp(state, node, ctx):
return peval_comprehension(state, node, ctx)
@staticmethod
def handle_GeneratorExp(state, node, ctx):
return peval_comprehension(state, node, ctx)
@staticmethod
def handle_Yield(state, node, ctx):
state, result = _peval_expression(state, node.value, ctx)
# We cannot evaluate a yield expression,
# so just wrap whatever we've got in a node and return.
state, new_value = map_reify(state, result)
return state, replace_fields(node, value=new_value)
@staticmethod
def handle_YieldFrom(state, node, ctx):
state, result = _peval_expression(state, node.value, ctx)
# We cannot evaluate a yield expression,
# so just wrap whatever we've got in a node and return.
state, new_value = map_reify(state, result)
return state, replace_fields(node, value=new_value)
@staticmethod
def handle_Compare(state, node, ctx):
return peval_compare(state, ctx, node)
@staticmethod
def handle_Call(state, node, ctx):
return peval_call(state, ctx, node.func, args=node.args, keywords=node.keywords)
@staticmethod
def handle_Attribute(state, node, ctx):
state, result = _peval_expression(state, node.value, ctx)
if is_known_value(result):
success, attr = try_get_attribute(result.value, node.attr)
if success:
return state, KnownValue(value=attr)
state, new_value = map_reify(state, result)
return state, replace_fields(node, value=new_value)
@staticmethod
def handle_Subscript(state, node, ctx):
state, value_result = _peval_expression(state, node.value, ctx)
state, slice_result = _peval_expression(state, node.slice, ctx)
if is_known_value(value_result) and is_known_value(slice_result):
success, elem = try_call_method(
value_result.value, '__getitem__', args=(slice_result.value,))
if success:
return state, KnownValue(value=elem)
state, new_value = map_reify(state, value_result)
state, new_slice = map_reify(state, slice_result)
if type(new_slice) not in (ast.Index, ast.Slice, ast.ExtSlice):
new_slice = ast.Index(value=new_slice)
return state, replace_fields(node, value=new_value, slice=new_slice)
@staticmethod
def handle_Index(state, node, ctx):
state, result = _peval_expression(state, node.value, ctx)
if is_known_value(result):
return state, KnownValue(value=result.value)
else:
return state, result
@staticmethod
def handle_Slice(state, node, ctx):
state, results = map_peval_expression(state, (node.lower, node.upper, node.step), ctx)
# how do we handle None values in nodes? Technically, they are known values
if all_known_values_or_none(results):
lower, upper, step = [result if result is None else result.value for result in results]
return state, KnownValue(value=slice(lower, upper, step))
state, new_nodes = map_reify(state, results)
new_node = replace_fields(node, lower=new_nodes[0], upper=new_nodes[1], step=new_nodes[2])
return state, new_node
@staticmethod
def handle_ExtSlice(state, node, ctx):
state, results = map_peval_expression(state, node.dims, ctx)
if all_known_values(results):
return state, KnownValue(value=tuple(result.value for result in results))
state, new_nodes = map_reify(state, results)
return state, replace_fields(node, dims=new_nodes)
class EvaluationResult:
def __init__(self, fully_evaluated, node, temp_bindings, value=None):
self.fully_evaluated = fully_evaluated
if fully_evaluated:
self.value = value
self.temp_bindings = temp_bindings
self.node = node
def _peval_expression(state, node, ctx):
return _peval_expression_dispatcher(node, state, node, ctx)
def peval_expression(node, gen_sym, bindings, create_binding=False):
ctx = immutableadict(bindings=bindings)
state = immutableadict(gen_sym=gen_sym, temp_bindings=immutableadict())
state, result = _peval_expression(state, node, ctx)
if is_known_value(result):
state, result_node = map_reify(state, result, create_binding)
eval_result = EvaluationResult(
fully_evaluated=True,
value=result.value,
node=result_node,
temp_bindings=state.temp_bindings)
else:
eval_result = EvaluationResult(
fully_evaluated=False,
node=result,
temp_bindings=state.temp_bindings)
return eval_result, state.gen_sym
def try_peval_expression(node, bindings):
"""
Try to partially evaluate the AST expression ``node`` using the dictionary ``bindings``.
Returns a pair ``(evaluated, result)``, where ``evaluated`` is a boolean
and ``result`` is the evaulation result if ``evaluated`` is ``True``,
and an AST expression otherwise.
"""
gen_sym = GenSym()
eval_result, gen_sym = peval_expression(node, gen_sym, bindings)
if eval_result.fully_evaluated:
return True, eval_result.value
else:
return False, node | 0.63023 | 0.356615 |
from leapp.libraries.common import multipathutil
_regexes = ('vendor', 'product', 'revision', 'product_blacklist', 'devnode',
'wwid', 'property', 'protocol')
def _update_config(need_foreign, need_allow_usb, config):
if not (need_foreign or need_allow_usb or config.invalid_regexes_exist):
return None
contents = multipathutil.read_config(config.pathname)
if contents is None:
return None
lines = contents.split('\n')
section = None
in_subsection = False
updated_file = False
defaults_start = -1
for i, line in enumerate(lines):
try:
data = multipathutil.LineData(line, section, in_subsection)
except ValueError:
continue
if data.type == data.TYPE_SECTION_END:
if in_subsection:
in_subsection = False
elif section is not None:
section = None
elif data.type == data.TYPE_SECTION_START:
if section is None:
section = data.section
if section == 'defaults':
defaults_start = i + 1
elif not in_subsection:
in_subsection = True
elif data.type == data.TYPE_OPTION:
if section == 'defaults':
if data.option == 'enable_foreign':
need_foreign = False
elif data.option == 'allow_usb_devices':
need_allow_usb = False
if data.option in _regexes and data.value == '*':
lines[i] = line.replace('*', '.*', 1)
lines[i] += ' # line modified by Leapp'
updated_file = True
if need_foreign or need_allow_usb:
updated_file = True
if defaults_start < 0:
if in_subsection:
lines.append('\t} # line added by Leapp')
if section is not None:
lines.append('} # line added by Leapp')
lines.append('defaults { # section added by Leapp')
if need_foreign:
lines.append('\tenable_foreign ""')
if need_allow_usb:
lines.append('\tallow_usb_devices yes')
lines.append('}')
lines.append('')
else:
if need_allow_usb:
lines.insert(defaults_start, '\tallow_usb_devices yes # line added by Leapp')
if need_foreign:
lines.insert(defaults_start, '\tenable_foreign "" # line added by Leapp')
if not updated_file:
return None
contents = '\n'.join(lines)
return contents
def update_configs(facts):
need_foreign = not any(x for x in facts.configs if x.enable_foreign_exists)
need_allow_usb = not any(x for x in facts.configs if x.allow_usb_exists)
for config in facts.configs:
contents = _update_config(need_foreign, need_allow_usb, config)
need_foreign = False
need_allow_usb = False
"""
foreign_exists and allow_usb_exists only matter for the main
config file.
"""
if contents:
multipathutil.write_config(config.pathname, contents) | repos/system_upgrade/el8toel9/actors/multipathconfupdate/libraries/multipathconfupdate.py | from leapp.libraries.common import multipathutil
_regexes = ('vendor', 'product', 'revision', 'product_blacklist', 'devnode',
'wwid', 'property', 'protocol')
def _update_config(need_foreign, need_allow_usb, config):
if not (need_foreign or need_allow_usb or config.invalid_regexes_exist):
return None
contents = multipathutil.read_config(config.pathname)
if contents is None:
return None
lines = contents.split('\n')
section = None
in_subsection = False
updated_file = False
defaults_start = -1
for i, line in enumerate(lines):
try:
data = multipathutil.LineData(line, section, in_subsection)
except ValueError:
continue
if data.type == data.TYPE_SECTION_END:
if in_subsection:
in_subsection = False
elif section is not None:
section = None
elif data.type == data.TYPE_SECTION_START:
if section is None:
section = data.section
if section == 'defaults':
defaults_start = i + 1
elif not in_subsection:
in_subsection = True
elif data.type == data.TYPE_OPTION:
if section == 'defaults':
if data.option == 'enable_foreign':
need_foreign = False
elif data.option == 'allow_usb_devices':
need_allow_usb = False
if data.option in _regexes and data.value == '*':
lines[i] = line.replace('*', '.*', 1)
lines[i] += ' # line modified by Leapp'
updated_file = True
if need_foreign or need_allow_usb:
updated_file = True
if defaults_start < 0:
if in_subsection:
lines.append('\t} # line added by Leapp')
if section is not None:
lines.append('} # line added by Leapp')
lines.append('defaults { # section added by Leapp')
if need_foreign:
lines.append('\tenable_foreign ""')
if need_allow_usb:
lines.append('\tallow_usb_devices yes')
lines.append('}')
lines.append('')
else:
if need_allow_usb:
lines.insert(defaults_start, '\tallow_usb_devices yes # line added by Leapp')
if need_foreign:
lines.insert(defaults_start, '\tenable_foreign "" # line added by Leapp')
if not updated_file:
return None
contents = '\n'.join(lines)
return contents
def update_configs(facts):
need_foreign = not any(x for x in facts.configs if x.enable_foreign_exists)
need_allow_usb = not any(x for x in facts.configs if x.allow_usb_exists)
for config in facts.configs:
contents = _update_config(need_foreign, need_allow_usb, config)
need_foreign = False
need_allow_usb = False
"""
foreign_exists and allow_usb_exists only matter for the main
config file.
"""
if contents:
multipathutil.write_config(config.pathname, contents) | 0.206414 | 0.118717 |
from arrays import Array
import warnings
class Array2D(Array):
def __init__(self, r, c):
self.capacity = r
self.__arr = Array2D.__create_arr(r, c)
def __create_arr(r, c):
arr = []
for i in range(r):
arr.append(Array(c))
return arr
def __getitem__(self, key):
if key > self.capacity - 1:
raise IndexError
return self.__arr[key]
def __setitem__(self, key, item):
if key > self.capacity - 1:
raise IndexError
elif not isinstance(item, Array):
raise ValueError
self.__arr[key] = item
def get(self, r_index, c_index):
warnings.warn("get is deprecated, square bracket notation preferred", DeprecationWarning)
if r_index > self.capacity - 1 or c_index > self.__arr[0].capacity - 1:
raise IndexError
return (self.__arr[r_index])[c_index]
def set(self, r_index, c_index, item):
warnings.warn("set is deprecated, square bracket notation preferred", DeprecationWarning)
if r_index > self.capacity - 1 or c_index > self.__arr[0].capacity - 1:
raise IndexError
self.__arr[r_index].__setitem__(c_index, item)
def print(self):
if self.capacity == 0:
print('()')
return
for i in self.__arr:
i.print()
def contains(self, item):
for i in self._arr:
for j in i:
if j == item:
return True
return False
def __contains__(self, item):
for i in self._arr:
for j in i:
if j == item:
return True
return False
def index(self, item):
r_index = 0
c_index = 0
for i in self.__arr:
for j in i:
c_index = 0
if i == item:
return [r_index, c_index]
c_index += 1
r_index += 1
return [-1]
def __len__(self):
return len(self.__arr) | influence/array/multiarray.py | from arrays import Array
import warnings
class Array2D(Array):
def __init__(self, r, c):
self.capacity = r
self.__arr = Array2D.__create_arr(r, c)
def __create_arr(r, c):
arr = []
for i in range(r):
arr.append(Array(c))
return arr
def __getitem__(self, key):
if key > self.capacity - 1:
raise IndexError
return self.__arr[key]
def __setitem__(self, key, item):
if key > self.capacity - 1:
raise IndexError
elif not isinstance(item, Array):
raise ValueError
self.__arr[key] = item
def get(self, r_index, c_index):
warnings.warn("get is deprecated, square bracket notation preferred", DeprecationWarning)
if r_index > self.capacity - 1 or c_index > self.__arr[0].capacity - 1:
raise IndexError
return (self.__arr[r_index])[c_index]
def set(self, r_index, c_index, item):
warnings.warn("set is deprecated, square bracket notation preferred", DeprecationWarning)
if r_index > self.capacity - 1 or c_index > self.__arr[0].capacity - 1:
raise IndexError
self.__arr[r_index].__setitem__(c_index, item)
def print(self):
if self.capacity == 0:
print('()')
return
for i in self.__arr:
i.print()
def contains(self, item):
for i in self._arr:
for j in i:
if j == item:
return True
return False
def __contains__(self, item):
for i in self._arr:
for j in i:
if j == item:
return True
return False
def index(self, item):
r_index = 0
c_index = 0
for i in self.__arr:
for j in i:
c_index = 0
if i == item:
return [r_index, c_index]
c_index += 1
r_index += 1
return [-1]
def __len__(self):
return len(self.__arr) | 0.447943 | 0.190705 |
from .utils import serializable_dict
class Change(object):
def __init__(self, key, value, old_value=None, **kwargs):
self.key = key
self.value = value
self.old_value = old_value
self.metadata = kwargs or {}
def __repr__(self):
return serializable_dict(self.__dict__)
class Diff(object):
def __init__(self, field_name=None, diff=None, **kwargs):
self.field_name = field_name
self.added = diff.added if diff else []
self.deleted = diff.deleted if diff else []
self.updated = diff.updated if diff else []
self.metadata = kwargs or {}
@property
def empty(self):
return not any([self.added, self.deleted, self.updated])
class DiffHelper(object):
def _missing_items(self, existing_items, items):
return [k for k in items if k not in existing_items]
def value_is_dict_or_entity(self, value):
return hasattr(value, '__dict__') or isinstance(value, dict)
def _list_diff(self, field_name, new_value, old_value):
list_field_diff = Diff(field_name=field_name)
# If the list elements are dicts or entities, go for an
# entity diff instead of a diff of simple list of scalars
if self.value_is_dict_or_entity(new_value[0]):
new_dict = {e.get('id'): e for e in new_value}
old_dict = {e.get('id'): e for e in old_value}
new_ids = set(new_dict.keys())
old_ids = set(old_dict.keys())
if new_ids or old_ids:
added_ids = new_ids.difference(old_ids)
deleted_ids = old_ids.difference(new_ids)
common_ids = new_ids.intersection(old_ids)
for existing_id in common_ids:
elem_diff = self.diff(new_dict.get(existing_id), old_dict.get(existing_id))
if not elem_diff.empty:
list_field_diff.updated.append(elem_diff)
for new_id in added_ids:
list_field_diff.added.append(Change(
new_id, value=new_dict.get(new_id), old_value=None)
)
for deleted_id in deleted_ids:
list_field_diff.deleted.append(Change(
deleted_id, value=None, old_value=old_dict.get(deleted_id))
)
else:
# Simple list diff where there's only add/delete
for nv in new_value:
if nv not in old_value:
list_field_diff.added.append(
Change(None, value=nv, old_value=None)
)
for ov in old_value:
if ov not in new_value:
list_field_diff.deleted.append(
Change(None, value=None, old_value=ov)
)
return list_field_diff
def diff(self, entity_dict, old_entity_dict, **metadata):
"""
Calculates the diff between two entity's dicts. When dealing
with nested entities or fields that are list of entities, in order
to calculate the diff it assumes every entity dict has an `id` field,
otherwise calculates the diff as if it were a simple list of scalars
"""
new_keys = set(entity_dict.keys())
old_keys = set(old_entity_dict.keys())
existing_keys = old_keys.intersection(new_keys)
_diff = Diff(**metadata)
for new_field in self._missing_items(existing_keys, new_keys):
_diff.added.append(Change(new_field, entity_dict.get(new_field)))
for deleted_field in self._missing_items(existing_keys, old_keys):
_diff.deleted.append(Change(deleted_field, None, old_entity_dict.get(deleted_field)))
for k in existing_keys:
new_value, old_value = entity_dict.get(k), old_entity_dict.get(k)
if isinstance(new_value, (list, set, tuple)):
list_field_diff = self._list_diff(k, new_value, old_value)
if not list_field_diff.empty:
_diff.updated.append(list_field_diff)
elif self.value_is_dict_or_entity(new_value):
sub_entity_diff = self.diff(new_value, old_value)
if not sub_entity_diff.empty:
_diff.updated.append(Diff(
field_name=k,
diff=sub_entity_diff,
))
elif new_value != old_value:
_diff.updated.append(Change(k, value=new_value, old_value=old_value))
return _diff | kronos/diff.py | from .utils import serializable_dict
class Change(object):
def __init__(self, key, value, old_value=None, **kwargs):
self.key = key
self.value = value
self.old_value = old_value
self.metadata = kwargs or {}
def __repr__(self):
return serializable_dict(self.__dict__)
class Diff(object):
def __init__(self, field_name=None, diff=None, **kwargs):
self.field_name = field_name
self.added = diff.added if diff else []
self.deleted = diff.deleted if diff else []
self.updated = diff.updated if diff else []
self.metadata = kwargs or {}
@property
def empty(self):
return not any([self.added, self.deleted, self.updated])
class DiffHelper(object):
def _missing_items(self, existing_items, items):
return [k for k in items if k not in existing_items]
def value_is_dict_or_entity(self, value):
return hasattr(value, '__dict__') or isinstance(value, dict)
def _list_diff(self, field_name, new_value, old_value):
list_field_diff = Diff(field_name=field_name)
# If the list elements are dicts or entities, go for an
# entity diff instead of a diff of simple list of scalars
if self.value_is_dict_or_entity(new_value[0]):
new_dict = {e.get('id'): e for e in new_value}
old_dict = {e.get('id'): e for e in old_value}
new_ids = set(new_dict.keys())
old_ids = set(old_dict.keys())
if new_ids or old_ids:
added_ids = new_ids.difference(old_ids)
deleted_ids = old_ids.difference(new_ids)
common_ids = new_ids.intersection(old_ids)
for existing_id in common_ids:
elem_diff = self.diff(new_dict.get(existing_id), old_dict.get(existing_id))
if not elem_diff.empty:
list_field_diff.updated.append(elem_diff)
for new_id in added_ids:
list_field_diff.added.append(Change(
new_id, value=new_dict.get(new_id), old_value=None)
)
for deleted_id in deleted_ids:
list_field_diff.deleted.append(Change(
deleted_id, value=None, old_value=old_dict.get(deleted_id))
)
else:
# Simple list diff where there's only add/delete
for nv in new_value:
if nv not in old_value:
list_field_diff.added.append(
Change(None, value=nv, old_value=None)
)
for ov in old_value:
if ov not in new_value:
list_field_diff.deleted.append(
Change(None, value=None, old_value=ov)
)
return list_field_diff
def diff(self, entity_dict, old_entity_dict, **metadata):
"""
Calculates the diff between two entity's dicts. When dealing
with nested entities or fields that are list of entities, in order
to calculate the diff it assumes every entity dict has an `id` field,
otherwise calculates the diff as if it were a simple list of scalars
"""
new_keys = set(entity_dict.keys())
old_keys = set(old_entity_dict.keys())
existing_keys = old_keys.intersection(new_keys)
_diff = Diff(**metadata)
for new_field in self._missing_items(existing_keys, new_keys):
_diff.added.append(Change(new_field, entity_dict.get(new_field)))
for deleted_field in self._missing_items(existing_keys, old_keys):
_diff.deleted.append(Change(deleted_field, None, old_entity_dict.get(deleted_field)))
for k in existing_keys:
new_value, old_value = entity_dict.get(k), old_entity_dict.get(k)
if isinstance(new_value, (list, set, tuple)):
list_field_diff = self._list_diff(k, new_value, old_value)
if not list_field_diff.empty:
_diff.updated.append(list_field_diff)
elif self.value_is_dict_or_entity(new_value):
sub_entity_diff = self.diff(new_value, old_value)
if not sub_entity_diff.empty:
_diff.updated.append(Diff(
field_name=k,
diff=sub_entity_diff,
))
elif new_value != old_value:
_diff.updated.append(Change(k, value=new_value, old_value=old_value))
return _diff | 0.77552 | 0.169269 |
import ast
import astor
import sys
from x2paddle.project_convertor.pytorch.mapper import *
import copy
import os.path as osp
from .utils import get_dep_file_path
class DepInfo:
"""
依赖包信息。
PT_FROM代表pytorch from信息的字符串,例如:torch;
PD_FROM代表paddle from信息的字符串,例如:paddle;
PT_IMPORT代表pytorch import信息系的字符串,例如:nn.functional;
PD_IMPORT代表paddle import信息系的字符串,例如:nn.functional;
AS代表as信息的字符串,例如:F;
PT_DEPENDENCY代表由PT_FROM、PT_IMPORT、AS三者组成的字符串,例如:from torch import nn.functional as F。
PD_DEPENDENCY代表由PD_FROM、PD_IMPORT、AS三者组成的字符串,例如:from paddle import nn.functional as F。
"""
PT_FROM = None
PD_FROM = None
PT_IMPORT = None
PD_IMPORT = None
AS = None
PT_DEPENDENCY = None
PD_DEPENDENCY = None
class AstUpdater(ast.NodeVisitor):
""" 更新ast树,将ast树中PyTorch相关的节点转为Paddle相关的节点。
Args:
py_file_path (str): python文件的绝对值路径。
file_dependencies (dict): 当前已经统计的依赖信息,key为python文件的绝对值路径,
value为key文件所对应的依赖信息组成的list。
"""
def __init__(self, py_file_path, file_dependencies):
self.py_file_path = py_file_path
self.root = ast.parse(open(py_file_path, "rb").read())
self.file_dependencies = file_dependencies
self.scopes_and_dependencies = list() # 作用域和依赖组成的stack
self.nodes = list() # ast节点组成的stack
self.no_support_apis = list() # 不支持的API列表
self.is_import_torch2paddle = False # 是否添加import torch2paddle
self.is_import_paddle = True # 是否添加import padddle
self.is_import_x2paddle = False # 是否添加import x2paddle
def _get_scope_node(self):
""" 获取当前节点的作用域。
"""
scope_node = None
for i in range(len(self.scopes_and_dependencies)):
i = -(i + 1)
sd = self.scopes_and_dependencies[i]
if not isinstance(sd, DepInfo) and not isinstance(sd, ast.Assign):
scope_node = sd
break
return scope_node
def _get_current_index(self, scope_node, node):
""" 获取当前节点在其作用域中的索引序号。
"""
current_id = 0
for i, n in enumerate(scope_node.body):
if node == n:
current_id = i
break
return current_id
def _get_father_node(self):
""" 获取父节点。
"""
return self.nodes[-2]
def _get_complete_api(self, api_part_name):
""" 根据部分api名字获取PyTorch的api全名。
情况1:依赖是DepInfo,但其PD_IMPORT为None(非PyTorch的依赖),则pytorch_api为None。
情况2:依赖是DepInfo,且DepInfo的部分PyTorch属性以“torch”开头,则pytorch_api为完整api。
情况3:依赖是ast.Assign节点,则pytorch_api为None。
"""
pytorch_api = None
dep_info = None
if api_part_name is None:
return pytorch_api, dep_info
for i in range(len(self.scopes_and_dependencies)):
i = -(i + 1)
dep_info = self.scopes_and_dependencies[i]
if isinstance(dep_info, DepInfo):
if dep_info.PT_IMPORT is None:
continue
if (dep_info.PT_FROM is not None and "torch" in dep_info.PT_FROM) or \
(dep_info.PT_IMPORT is not None and "torch" in dep_info.PT_IMPORT):
replace_str = None
if dep_info.AS is not None and api_part_name.startswith(
dep_info.AS + "."):
replace_str = dep_info.AS
elif dep_info.AS is None and api_part_name.startswith(
dep_info.PT_IMPORT):
replace_str = dep_info.PT_IMPORT
if replace_str is not None:
pytorch_api = api_part_name.replace(
replace_str, dep_info.PT_DEPENDENCY, 1)
if "torch2paddle" in pytorch_api:
# 说明当前节点是插入的已经替换过的node
pytorch_api = None
break
elif isinstance(dep_info, ast.Assign):
is_customized = False
for s in astor.to_source(dep_info.targets[0]).split(","):
if api_part_name.split(".")[0] == s.strip():
is_customized = True
break
if is_customized:
break
return pytorch_api, dep_info
def _rename(self, name, dep_info, pytorch_api, paddle_api):
""" 对函数名进行重命名。
例如:将nn.Conv2d替换为nn.Conv2D。
"""
pytorch_api_seg = pytorch_api.split(dep_info.PT_IMPORT)
if ".models." in paddle_api:
self.is_import_x2paddle = True
if paddle_api.startswith(dep_info.PD_IMPORT + ".") or \
paddle_api.endswith("." + dep_info.PD_IMPORT) or \
"." + dep_info.PD_IMPORT + "." in paddle_api:
paddle_api_seg = paddle_api.split(dep_info.PD_IMPORT)
if dep_info.AS is None:
name = name.replace(dep_info.PT_IMPORT + pytorch_api_seg[-1],
dep_info.PD_IMPORT + paddle_api_seg[-1])
else:
name = name.replace(pytorch_api_seg[-1], paddle_api_seg[-1])
elif "torch2paddle." in paddle_api:
name = "torch2paddle." + paddle_api.split("torch2paddle.")[-1]
self.is_import_torch2paddle = True
else:
name = paddle_api
return name
def run(self):
self.scopes_and_dependencies.append(self.root)
self.visit(self.root)
for i, node in enumerate(self.root.body):
if isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom):
if self.is_import_torch2paddle:
self.root.body.insert(
i,
ast.parse("from x2paddle import torch2paddle").body[0])
if self.is_import_x2paddle:
self.root.body.insert(i,
ast.parse("import x2paddle").body[0])
if self.is_import_paddle:
self.root.body.insert(i, ast.parse("import paddle").body[0])
break
def visit(self, node):
self.nodes.append(node)
out = super(AstUpdater, self).visit(node)
self.nodes.pop()
if out is not None:
return out
else:
# 出现字符串或者if等节点需要返回字符串
try:
return astor.to_source(node)
except Exception:
return None
def visit_ImportFrom(self, node):
""" 1. 遍历子节点。
2. 将当前from依赖中的多个import拆分成多个import。
例如:from torch import nn, utils 这个node
拆分为:node1:from torch import nn
node2:from torch import utils
拆分原因:
在paddle中父依赖包可能不一致。
"""
scope_node = self._get_scope_node()
current_id = self._get_current_index(scope_node, node)
scope_node.body.pop(current_id)
son_nodes = node.names
for i, son_node in enumerate(son_nodes):
copy_node = copy.deepcopy(node)
copy_node.names = [son_node]
if i == 0:
is_remove = self.visit_alias(son_node, copy_node, node.module,
node.level)
if not is_remove:
scope_node.body.insert(current_id, copy_node)
else:
scope_node.body.insert(current_id + i, copy_node)
def visit_Import(self, node):
""" 遍历子节点。
"""
son_nodes = getattr(node, "names")
for son_node in son_nodes:
self.visit_alias(son_node, node)
def visit_alias(self,
node,
father_node=None,
from_name=None,
from_level=None):
""" 构建DepInfo并将其放入scopes_and_dependencies。
如果import字符串为“*”,获取依赖包所在文件的依赖信息并转换为DepInfo加入当前的scopes_and_dependencies;
反之,直接在scopes_and_dependencies中加入DepInfo。
"""
is_remove = False
dep_info = DepInfo()
dep_info.PT_FROM = from_name
dep_info.PT_IMPORT = getattr(node, "name")
dep_info.AS = getattr(node, "asname", None)
if dep_info.PT_IMPORT == "*":
import_file_path = get_dep_file_path(self.py_file_path, from_level,
from_name)
pytorch_dependencies = self.file_dependencies[import_file_path]
for pytorch_dep_info in pytorch_dependencies:
current_dep_info = DepInfo()
if not isinstance(pytorch_dep_info, str):
current_dep_info.PT_FROM = pytorch_dep_info.FROM
current_dep_info.PT_IMPORT = pytorch_dep_info.IMPORT
current_dep_info.AS = pytorch_dep_info.AS
current_dep_info.PT_DEPENDENCY = pytorch_dep_info.DEPENDENCY
if "torch" in current_dep_info.PT_DEPENDENCY:
if current_dep_info.PT_DEPENDENCY in API_MAPPER:
current_dep_info.PD_DEPENDENCY = \
API_MAPPER[current_dep_info.PT_DEPENDENCY][0]
if current_dep_info.PT_DEPENDENCY == "torch" and \
isinstance(self._get_scope_node(), ast.Module):
self.is_import_paddle = False
if current_dep_info.PT_FROM is not None:
seg = current_dep_info.PD_DEPENDENCY.split(".")
current_dep_info.PD_IMPORT = seg[-1]
current_dep_info.PD_FROM = \
current_dep_info.PD_DEPENDENCY.replace("." + seg[-1], "")
else:
current_dep_info.PD_IMPORT = \
current_dep_info.PD_DEPENDENCY
elif current_dep_info.PT_DEPENDENCY in REMOVE_API:
scope_node = self._get_scope_node()
for i, n in enumerate(scope_node.body):
if father_node == n:
scope_node.body[i] = ast.parse("\n").body
is_remove = True
else:
self.no_support_apis.append(
current_dep_info.PT_DEPENDENCY)
else:
current_dep_info.PD_DEPENDENCY = pytorch_dep_info
self.scopes_and_dependencies.append(current_dep_info)
return is_remove
dependency_str_list = list()
if dep_info.PT_FROM is None and from_level is not None:
dependency_str_list.append("." * from_level)
elif dep_info.PT_FROM is not None:
dependency_str_list.append(dep_info.PT_FROM)
dependency_str_list.append(dep_info.PT_IMPORT)
dep_info.PT_DEPENDENCY = ".".join(dependency_str_list)
if dep_info.PT_DEPENDENCY.startswith("torch"):
if dep_info.PT_DEPENDENCY in API_MAPPER:
dep_info.PD_DEPENDENCY = API_MAPPER[dep_info.PT_DEPENDENCY][0]
if dep_info.PT_DEPENDENCY == "torch":
self.is_import_paddle = False
if dep_info.PT_FROM is not None:
seg = dep_info.PD_DEPENDENCY.split(".")
setattr(node, "name", seg[-1])
setattr(father_node, "module",
dep_info.PD_DEPENDENCY.replace("." + seg[-1], ""))
dep_info.PD_IMPORT = seg[-1]
dep_info.PD_FROM = dep_info.PD_DEPENDENCY.replace(
"." + seg[-1], "")
else:
setattr(node, "name", dep_info.PD_DEPENDENCY)
dep_info.PD_IMPORT = dep_info.PD_DEPENDENCY
elif dep_info.PT_DEPENDENCY in REMOVE_API:
scope_node = self._get_scope_node()
for i, n in enumerate(scope_node.body):
if father_node == n:
scope_node.body[i] = ast.parse("\n").body
is_remove = True
elif dep_info.PT_DEPENDENCY.startswith("torch"):
self.no_support_apis.append(dep_info.PT_DEPENDENCY)
else:
dep_info.PD_DEPENDENCY = dep_info.PT_DEPENDENCY
self.scopes_and_dependencies.append(dep_info)
return is_remove
def visit_Name(self, node):
""" 获取字符串名字。
"""
pytorch_api, dep_info = self._get_complete_api(getattr(node, "id"))
father_node = self._get_father_node()
if pytorch_api in API_MAPPER:
paddle_api = API_MAPPER[pytorch_api][0]
if isinstance(father_node, ast.Call) and getattr(
father_node.func, "id", None) in ("getattr", "setattr",
"hasattr"):
paddle_api = self._rename(paddle_api, dep_info, pytorch_api,
paddle_api)
for i, arg_node in enumerate(father_node.args):
if astor.to_source(arg_node).strip() == getattr(node, "id"):
father_node.args[i] = ast.parse(paddle_api).body[
0].value
return getattr(node, "id")
def visit_Attribute(self, node):
""" 对属性字符串满足以下4种情况时进行替换:
情况1 —— Class A(nn.Module):将nn.Module替换为nn.Layer;
情况2 —— a = (1, 2, nn.Module):将nn.Module替换为nn.Layer;
情况3 —— def a() -> torch.Tensor:将torch.Tensor替换为paddle.Tensor;
情况4 —— def a(x: torch.Tensor):将torch.Tensor替换为paddle.Tensor;
情况5 —— isinstance(a, nn.Module):将nn.Module替换为nn.Layer;
情况6 —— torch.float32:将torch.float32替换为"float32";
"""
value_node = node.value
attr = node.attr
name = self.visit(value_node)
attr_str = name + "." + attr
pytorch_api, dep_info = self._get_complete_api(attr_str)
father_node = self._get_father_node()
if pytorch_api in API_MAPPER:
paddle_api = API_MAPPER[pytorch_api][0]
if isinstance(father_node, ast.ClassDef):
attr_str = self._rename(attr_str, dep_info, pytorch_api,
paddle_api)
if node in father_node.bases:
father_node.bases[0] = ast.parse(attr_str).body[0].value
return attr_str
elif isinstance(father_node, ast.arguments):
attr_str = self._rename(attr_str, dep_info, pytorch_api,
paddle_api)
for i, default_n in enumerate(father_node.defaults):
if default_n == node:
father_node.defaults[i] = ast.parse(attr_str).body[
0].value
return attr_str
elif isinstance(father_node, ast.Tuple):
paddle_api = self._rename(paddle_api, dep_info, pytorch_api,
paddle_api)
for i, elts_node in enumerate(father_node.elts):
if astor.to_source(elts_node).strip() == attr_str:
father_node.elts[i] = ast.parse(paddle_api).body[
0].value
return paddle_api
elif isinstance(father_node, ast.FunctionDef):
paddle_api = self._rename(paddle_api, dep_info, pytorch_api,
paddle_api)
father_node.returns = ast.parse(paddle_api).body[0].value
return paddle_api
elif isinstance(father_node, ast.arg):
attr_str = self._rename(attr_str, dep_info, pytorch_api,
paddle_api)
father_node.annotation = ast.parse(attr_str).body[0].value
return attr_str
elif isinstance(father_node, ast.Call) and getattr(
father_node.func, "id", None) == "isinstance":
paddle_api = self._rename(paddle_api, dep_info, pytorch_api,
paddle_api)
for i, arg_node in enumerate(father_node.args):
if astor.to_source(arg_node).strip() == attr_str:
father_node.args[i] = ast.parse(paddle_api).body[
0].value
return paddle_api
elif not isinstance(father_node, ast.Call):
# 对torch.float32的处理
for k, v in father_node.__dict__.items():
if v == node:
father_node.k = ast.parse(paddle_api).body[0].value
break
return attr_str
elif pytorch_api in REMOVE_API:
if isinstance(
father_node,
(ast.Assign, ast.If, ast.FunctionDef, ast.ClassDef, ast.Call)):
scope_node = self._get_scope_node()
for i, n in enumerate(scope_node.body):
if father_node == n:
scope_node.body.pop(i)
return None
elif isinstance(father_node, ast.BoolOp):
for i, n in enumerate(father_node.values):
if node == n:
father_node.values[i] = ast.parse("False").body[0].value
return None
else:
if isinstance(pytorch_api, str) and pytorch_api.startswith(
"torch"
) and "(" not in pytorch_api and "[" not in pytorch_api:
if not isinstance(father_node, ast.Attribute):
self.no_support_apis.append(pytorch_api)
return attr_str
def visit_Num(self, node):
""" 返回数值。
"""
return getattr(node, "n")
def visit_keyword(self, node):
""" 返回键值对。
【注意】当value是API_MAPPER中的key时,需要替换为API_MAPPER中对应的Paddle API。
"""
key = getattr(node, "arg")
value_node = getattr(node, "value")
value = self.visit(value_node)
if value in API_MAPPER:
value = API_MAPPER[value][0]
elif isinstance(value, str) and value.startswith(
"torch") and "(" not in value and "[" not in value:
self.no_support_apis.append(value)
return {key: value}
def visit_Tuple(self, node):
""" 返回tuple。
"""
elts_nodes = getattr(node, "elts")
elts = list()
for elts_node in elts_nodes:
elt = self.visit(elts_node)
elts.append(elt if isinstance(elt, str) else str(elt))
elts = "({})".format(", ".join(elts))
return elts
def visit_Assign(self, node):
""" 1. 将Assign节点加入scopes_and_dependencies;
2. 遍历Assign节点的子节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
def visit_Call(self, node):
""" 1. 获取原始函数名并更新为新的函数名。
2. 获取args和kwargs。
3. 根据API_MAPPER映射需要更新的操作,对参数进行处理。
4. 如果有前缀代码和后缀代码,则需要添加相应节点。
"""
# 获取函数名
func_node = node.func
if isinstance(func_node, ast.Attribute) and isinstance(func_node.value,
ast.Call):
func_name = None
else:
func_name = self.visit(func_node)
pytorch_api, dep_info = self._get_complete_api(func_name)
if pytorch_api is None:
self.generic_visit(node)
return
if pytorch_api not in API_MAPPER:
if pytorch_api.startswith(
"torch"
) and "[" not in pytorch_api and "(" not in pytorch_api:
self.no_support_apis.append(pytorch_api)
return
paddle_api = API_MAPPER[pytorch_api][0]
func_name = self._rename(func_name, dep_info, pytorch_api, paddle_api)
setattr(node, "func", ast.parse(func_name).body[0].value)
# 获取args
args_nodes = getattr(node, "args")
args_list = list()
for args_node in args_nodes:
args_list.append(self.visit(args_node))
# 获取keywords
keywords_nodes = getattr(node, "keywords")
kw_dict = dict()
for keywords_node in keywords_nodes:
if list(self.visit(keywords_node).keys())[0] is None:
args_list.append("**{}".format(
list(self.visit(keywords_node).values())[0]))
else:
kw_dict.update(self.visit(keywords_node))
if API_MAPPER[pytorch_api][1] is None:
return
target_name = None
father_node = self._get_father_node()
if isinstance(father_node, ast.Assign):
target_node = father_node.targets[0]
target_name = self.visit(target_node)
mapper = API_MAPPER[pytorch_api][1](func_name, pytorch_api, args_list,
kw_dict, target_name)
prefix_insert_codes, new_code, suffix_insert_codes = mapper.run()
if mapper.func_name.startswith("x2paddle."):
self.is_import_x2paddle = True
scope_node = self._get_scope_node()
if isinstance(ast.parse(new_code).body[0], ast.Assign):
node_index = self._get_current_index(scope_node, node)
scope_node.body[node_index] = ast.parse(
new_code.replace("\n", "")).body[0]
else:
new_call_node = ast.parse(new_code).body[0].value
setattr(node, "func", new_call_node.func) # 修改了fun_name
setattr(node, "args", new_call_node.args)
setattr(node, "keywords", new_call_node.keywords)
for i, n in enumerate(scope_node.body):
if father_node == n:
for code in prefix_insert_codes:
scope_node.body.insert(
i, ast.parse(code.replace("\n", "")).body[0])
i += 1
break
for i, n in enumerate(scope_node.body):
if father_node == n:
j = i + 1
for code in suffix_insert_codes:
scope_node.body.insert(
j, ast.parse(code.replace("\n", "")).body[0])
j += 1
break
def visit_Subscript(self, node):
value_node = node.value
value_name = self.visit(value_node)
pytorch_api, dep_info = self._get_complete_api(value_name)
if pytorch_api in API_MAPPER:
paddle_api = API_MAPPER[pytorch_api][0]
value_name = self._rename(value_name, dep_info, pytorch_api,
paddle_api)
node.value = ast.parse(value_name).body[0]
else:
if isinstance(pytorch_api, str) and pytorch_api.startswith(
"torch") and "(" not in pytorch_api:
self.no_support_apis.append(pytorch_api)
self.visit(node.slice)
self.visit(node.ctx)
def visit_FunctionDef(self, node):
""" 1. 将FunctionDef节点加入scopes_and_dependencies;
2. 遍历FunctionDef节点的子节点;
3. 去除scopes_and_dependencies中FunctionDef节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.FunctionDef):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_ClassDef(self, node):
""" 1. 将ClassDef节点加入scopes_and_dependencies;
2. 遍历ClassDef节点的子节点;
3. 去除scopes_and_dependencies中ClassDef节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.ClassDef):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_If(self, node):
""" 1. 将If节点加入scopes_and_dependencies;
2. 遍历If节点的子节点;
3. 去除scopes_and_dependencies中If节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.If):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_While(self, node):
""" 1. 将While节点加入scopes_and_dependencies;
2. 遍历Try节点的子节点;
3. 去除scopes_and_dependencies中Try节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.While):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_Try(self, node):
""" 1. 将Try节点加入scopes_and_dependencies;
2. 遍历Try节点的子节点;
3. 去除scopes_and_dependencies中Try节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.Try):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_ExtSlice(self, node):
""" 将Index节点替换替换为Num。
"""
dim_nodes = node.dims
for i, dim_node in enumerate(dim_nodes):
if isinstance(dim_node, ast.Index):
dim_nodes[i] = dim_node.value
else:
self.visit(dim_node)
def visit_Str(self, node):
""" 修改模型参数的后缀名。
"""
setattr(node, "s",
node.s.replace(".pth", ".pdiparams").replace(
".pt", ".pdiparams").replace(".ckpt", ".pdiparams"))
def update(py_file_path, file_dependencies):
updater = AstUpdater(py_file_path, file_dependencies)
updater.run()
if len(updater.no_support_apis) > 0:
print("Can not convert the file {}.".format(py_file_path))
print("The unsupported packages or operators are: [{}].".format(
", ".join(set(updater.no_support_apis))))
return None
else:
return updater.root | x2paddle/project_convertor/pytorch/ast_update.py |
import ast
import astor
import sys
from x2paddle.project_convertor.pytorch.mapper import *
import copy
import os.path as osp
from .utils import get_dep_file_path
class DepInfo:
"""
依赖包信息。
PT_FROM代表pytorch from信息的字符串,例如:torch;
PD_FROM代表paddle from信息的字符串,例如:paddle;
PT_IMPORT代表pytorch import信息系的字符串,例如:nn.functional;
PD_IMPORT代表paddle import信息系的字符串,例如:nn.functional;
AS代表as信息的字符串,例如:F;
PT_DEPENDENCY代表由PT_FROM、PT_IMPORT、AS三者组成的字符串,例如:from torch import nn.functional as F。
PD_DEPENDENCY代表由PD_FROM、PD_IMPORT、AS三者组成的字符串,例如:from paddle import nn.functional as F。
"""
PT_FROM = None
PD_FROM = None
PT_IMPORT = None
PD_IMPORT = None
AS = None
PT_DEPENDENCY = None
PD_DEPENDENCY = None
class AstUpdater(ast.NodeVisitor):
""" 更新ast树,将ast树中PyTorch相关的节点转为Paddle相关的节点。
Args:
py_file_path (str): python文件的绝对值路径。
file_dependencies (dict): 当前已经统计的依赖信息,key为python文件的绝对值路径,
value为key文件所对应的依赖信息组成的list。
"""
def __init__(self, py_file_path, file_dependencies):
self.py_file_path = py_file_path
self.root = ast.parse(open(py_file_path, "rb").read())
self.file_dependencies = file_dependencies
self.scopes_and_dependencies = list() # 作用域和依赖组成的stack
self.nodes = list() # ast节点组成的stack
self.no_support_apis = list() # 不支持的API列表
self.is_import_torch2paddle = False # 是否添加import torch2paddle
self.is_import_paddle = True # 是否添加import padddle
self.is_import_x2paddle = False # 是否添加import x2paddle
def _get_scope_node(self):
""" 获取当前节点的作用域。
"""
scope_node = None
for i in range(len(self.scopes_and_dependencies)):
i = -(i + 1)
sd = self.scopes_and_dependencies[i]
if not isinstance(sd, DepInfo) and not isinstance(sd, ast.Assign):
scope_node = sd
break
return scope_node
def _get_current_index(self, scope_node, node):
""" 获取当前节点在其作用域中的索引序号。
"""
current_id = 0
for i, n in enumerate(scope_node.body):
if node == n:
current_id = i
break
return current_id
def _get_father_node(self):
""" 获取父节点。
"""
return self.nodes[-2]
def _get_complete_api(self, api_part_name):
""" 根据部分api名字获取PyTorch的api全名。
情况1:依赖是DepInfo,但其PD_IMPORT为None(非PyTorch的依赖),则pytorch_api为None。
情况2:依赖是DepInfo,且DepInfo的部分PyTorch属性以“torch”开头,则pytorch_api为完整api。
情况3:依赖是ast.Assign节点,则pytorch_api为None。
"""
pytorch_api = None
dep_info = None
if api_part_name is None:
return pytorch_api, dep_info
for i in range(len(self.scopes_and_dependencies)):
i = -(i + 1)
dep_info = self.scopes_and_dependencies[i]
if isinstance(dep_info, DepInfo):
if dep_info.PT_IMPORT is None:
continue
if (dep_info.PT_FROM is not None and "torch" in dep_info.PT_FROM) or \
(dep_info.PT_IMPORT is not None and "torch" in dep_info.PT_IMPORT):
replace_str = None
if dep_info.AS is not None and api_part_name.startswith(
dep_info.AS + "."):
replace_str = dep_info.AS
elif dep_info.AS is None and api_part_name.startswith(
dep_info.PT_IMPORT):
replace_str = dep_info.PT_IMPORT
if replace_str is not None:
pytorch_api = api_part_name.replace(
replace_str, dep_info.PT_DEPENDENCY, 1)
if "torch2paddle" in pytorch_api:
# 说明当前节点是插入的已经替换过的node
pytorch_api = None
break
elif isinstance(dep_info, ast.Assign):
is_customized = False
for s in astor.to_source(dep_info.targets[0]).split(","):
if api_part_name.split(".")[0] == s.strip():
is_customized = True
break
if is_customized:
break
return pytorch_api, dep_info
def _rename(self, name, dep_info, pytorch_api, paddle_api):
""" 对函数名进行重命名。
例如:将nn.Conv2d替换为nn.Conv2D。
"""
pytorch_api_seg = pytorch_api.split(dep_info.PT_IMPORT)
if ".models." in paddle_api:
self.is_import_x2paddle = True
if paddle_api.startswith(dep_info.PD_IMPORT + ".") or \
paddle_api.endswith("." + dep_info.PD_IMPORT) or \
"." + dep_info.PD_IMPORT + "." in paddle_api:
paddle_api_seg = paddle_api.split(dep_info.PD_IMPORT)
if dep_info.AS is None:
name = name.replace(dep_info.PT_IMPORT + pytorch_api_seg[-1],
dep_info.PD_IMPORT + paddle_api_seg[-1])
else:
name = name.replace(pytorch_api_seg[-1], paddle_api_seg[-1])
elif "torch2paddle." in paddle_api:
name = "torch2paddle." + paddle_api.split("torch2paddle.")[-1]
self.is_import_torch2paddle = True
else:
name = paddle_api
return name
def run(self):
self.scopes_and_dependencies.append(self.root)
self.visit(self.root)
for i, node in enumerate(self.root.body):
if isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom):
if self.is_import_torch2paddle:
self.root.body.insert(
i,
ast.parse("from x2paddle import torch2paddle").body[0])
if self.is_import_x2paddle:
self.root.body.insert(i,
ast.parse("import x2paddle").body[0])
if self.is_import_paddle:
self.root.body.insert(i, ast.parse("import paddle").body[0])
break
def visit(self, node):
self.nodes.append(node)
out = super(AstUpdater, self).visit(node)
self.nodes.pop()
if out is not None:
return out
else:
# 出现字符串或者if等节点需要返回字符串
try:
return astor.to_source(node)
except Exception:
return None
def visit_ImportFrom(self, node):
""" 1. 遍历子节点。
2. 将当前from依赖中的多个import拆分成多个import。
例如:from torch import nn, utils 这个node
拆分为:node1:from torch import nn
node2:from torch import utils
拆分原因:
在paddle中父依赖包可能不一致。
"""
scope_node = self._get_scope_node()
current_id = self._get_current_index(scope_node, node)
scope_node.body.pop(current_id)
son_nodes = node.names
for i, son_node in enumerate(son_nodes):
copy_node = copy.deepcopy(node)
copy_node.names = [son_node]
if i == 0:
is_remove = self.visit_alias(son_node, copy_node, node.module,
node.level)
if not is_remove:
scope_node.body.insert(current_id, copy_node)
else:
scope_node.body.insert(current_id + i, copy_node)
def visit_Import(self, node):
""" 遍历子节点。
"""
son_nodes = getattr(node, "names")
for son_node in son_nodes:
self.visit_alias(son_node, node)
def visit_alias(self,
node,
father_node=None,
from_name=None,
from_level=None):
""" 构建DepInfo并将其放入scopes_and_dependencies。
如果import字符串为“*”,获取依赖包所在文件的依赖信息并转换为DepInfo加入当前的scopes_and_dependencies;
反之,直接在scopes_and_dependencies中加入DepInfo。
"""
is_remove = False
dep_info = DepInfo()
dep_info.PT_FROM = from_name
dep_info.PT_IMPORT = getattr(node, "name")
dep_info.AS = getattr(node, "asname", None)
if dep_info.PT_IMPORT == "*":
import_file_path = get_dep_file_path(self.py_file_path, from_level,
from_name)
pytorch_dependencies = self.file_dependencies[import_file_path]
for pytorch_dep_info in pytorch_dependencies:
current_dep_info = DepInfo()
if not isinstance(pytorch_dep_info, str):
current_dep_info.PT_FROM = pytorch_dep_info.FROM
current_dep_info.PT_IMPORT = pytorch_dep_info.IMPORT
current_dep_info.AS = pytorch_dep_info.AS
current_dep_info.PT_DEPENDENCY = pytorch_dep_info.DEPENDENCY
if "torch" in current_dep_info.PT_DEPENDENCY:
if current_dep_info.PT_DEPENDENCY in API_MAPPER:
current_dep_info.PD_DEPENDENCY = \
API_MAPPER[current_dep_info.PT_DEPENDENCY][0]
if current_dep_info.PT_DEPENDENCY == "torch" and \
isinstance(self._get_scope_node(), ast.Module):
self.is_import_paddle = False
if current_dep_info.PT_FROM is not None:
seg = current_dep_info.PD_DEPENDENCY.split(".")
current_dep_info.PD_IMPORT = seg[-1]
current_dep_info.PD_FROM = \
current_dep_info.PD_DEPENDENCY.replace("." + seg[-1], "")
else:
current_dep_info.PD_IMPORT = \
current_dep_info.PD_DEPENDENCY
elif current_dep_info.PT_DEPENDENCY in REMOVE_API:
scope_node = self._get_scope_node()
for i, n in enumerate(scope_node.body):
if father_node == n:
scope_node.body[i] = ast.parse("\n").body
is_remove = True
else:
self.no_support_apis.append(
current_dep_info.PT_DEPENDENCY)
else:
current_dep_info.PD_DEPENDENCY = pytorch_dep_info
self.scopes_and_dependencies.append(current_dep_info)
return is_remove
dependency_str_list = list()
if dep_info.PT_FROM is None and from_level is not None:
dependency_str_list.append("." * from_level)
elif dep_info.PT_FROM is not None:
dependency_str_list.append(dep_info.PT_FROM)
dependency_str_list.append(dep_info.PT_IMPORT)
dep_info.PT_DEPENDENCY = ".".join(dependency_str_list)
if dep_info.PT_DEPENDENCY.startswith("torch"):
if dep_info.PT_DEPENDENCY in API_MAPPER:
dep_info.PD_DEPENDENCY = API_MAPPER[dep_info.PT_DEPENDENCY][0]
if dep_info.PT_DEPENDENCY == "torch":
self.is_import_paddle = False
if dep_info.PT_FROM is not None:
seg = dep_info.PD_DEPENDENCY.split(".")
setattr(node, "name", seg[-1])
setattr(father_node, "module",
dep_info.PD_DEPENDENCY.replace("." + seg[-1], ""))
dep_info.PD_IMPORT = seg[-1]
dep_info.PD_FROM = dep_info.PD_DEPENDENCY.replace(
"." + seg[-1], "")
else:
setattr(node, "name", dep_info.PD_DEPENDENCY)
dep_info.PD_IMPORT = dep_info.PD_DEPENDENCY
elif dep_info.PT_DEPENDENCY in REMOVE_API:
scope_node = self._get_scope_node()
for i, n in enumerate(scope_node.body):
if father_node == n:
scope_node.body[i] = ast.parse("\n").body
is_remove = True
elif dep_info.PT_DEPENDENCY.startswith("torch"):
self.no_support_apis.append(dep_info.PT_DEPENDENCY)
else:
dep_info.PD_DEPENDENCY = dep_info.PT_DEPENDENCY
self.scopes_and_dependencies.append(dep_info)
return is_remove
def visit_Name(self, node):
""" 获取字符串名字。
"""
pytorch_api, dep_info = self._get_complete_api(getattr(node, "id"))
father_node = self._get_father_node()
if pytorch_api in API_MAPPER:
paddle_api = API_MAPPER[pytorch_api][0]
if isinstance(father_node, ast.Call) and getattr(
father_node.func, "id", None) in ("getattr", "setattr",
"hasattr"):
paddle_api = self._rename(paddle_api, dep_info, pytorch_api,
paddle_api)
for i, arg_node in enumerate(father_node.args):
if astor.to_source(arg_node).strip() == getattr(node, "id"):
father_node.args[i] = ast.parse(paddle_api).body[
0].value
return getattr(node, "id")
def visit_Attribute(self, node):
""" 对属性字符串满足以下4种情况时进行替换:
情况1 —— Class A(nn.Module):将nn.Module替换为nn.Layer;
情况2 —— a = (1, 2, nn.Module):将nn.Module替换为nn.Layer;
情况3 —— def a() -> torch.Tensor:将torch.Tensor替换为paddle.Tensor;
情况4 —— def a(x: torch.Tensor):将torch.Tensor替换为paddle.Tensor;
情况5 —— isinstance(a, nn.Module):将nn.Module替换为nn.Layer;
情况6 —— torch.float32:将torch.float32替换为"float32";
"""
value_node = node.value
attr = node.attr
name = self.visit(value_node)
attr_str = name + "." + attr
pytorch_api, dep_info = self._get_complete_api(attr_str)
father_node = self._get_father_node()
if pytorch_api in API_MAPPER:
paddle_api = API_MAPPER[pytorch_api][0]
if isinstance(father_node, ast.ClassDef):
attr_str = self._rename(attr_str, dep_info, pytorch_api,
paddle_api)
if node in father_node.bases:
father_node.bases[0] = ast.parse(attr_str).body[0].value
return attr_str
elif isinstance(father_node, ast.arguments):
attr_str = self._rename(attr_str, dep_info, pytorch_api,
paddle_api)
for i, default_n in enumerate(father_node.defaults):
if default_n == node:
father_node.defaults[i] = ast.parse(attr_str).body[
0].value
return attr_str
elif isinstance(father_node, ast.Tuple):
paddle_api = self._rename(paddle_api, dep_info, pytorch_api,
paddle_api)
for i, elts_node in enumerate(father_node.elts):
if astor.to_source(elts_node).strip() == attr_str:
father_node.elts[i] = ast.parse(paddle_api).body[
0].value
return paddle_api
elif isinstance(father_node, ast.FunctionDef):
paddle_api = self._rename(paddle_api, dep_info, pytorch_api,
paddle_api)
father_node.returns = ast.parse(paddle_api).body[0].value
return paddle_api
elif isinstance(father_node, ast.arg):
attr_str = self._rename(attr_str, dep_info, pytorch_api,
paddle_api)
father_node.annotation = ast.parse(attr_str).body[0].value
return attr_str
elif isinstance(father_node, ast.Call) and getattr(
father_node.func, "id", None) == "isinstance":
paddle_api = self._rename(paddle_api, dep_info, pytorch_api,
paddle_api)
for i, arg_node in enumerate(father_node.args):
if astor.to_source(arg_node).strip() == attr_str:
father_node.args[i] = ast.parse(paddle_api).body[
0].value
return paddle_api
elif not isinstance(father_node, ast.Call):
# 对torch.float32的处理
for k, v in father_node.__dict__.items():
if v == node:
father_node.k = ast.parse(paddle_api).body[0].value
break
return attr_str
elif pytorch_api in REMOVE_API:
if isinstance(
father_node,
(ast.Assign, ast.If, ast.FunctionDef, ast.ClassDef, ast.Call)):
scope_node = self._get_scope_node()
for i, n in enumerate(scope_node.body):
if father_node == n:
scope_node.body.pop(i)
return None
elif isinstance(father_node, ast.BoolOp):
for i, n in enumerate(father_node.values):
if node == n:
father_node.values[i] = ast.parse("False").body[0].value
return None
else:
if isinstance(pytorch_api, str) and pytorch_api.startswith(
"torch"
) and "(" not in pytorch_api and "[" not in pytorch_api:
if not isinstance(father_node, ast.Attribute):
self.no_support_apis.append(pytorch_api)
return attr_str
def visit_Num(self, node):
""" 返回数值。
"""
return getattr(node, "n")
def visit_keyword(self, node):
""" 返回键值对。
【注意】当value是API_MAPPER中的key时,需要替换为API_MAPPER中对应的Paddle API。
"""
key = getattr(node, "arg")
value_node = getattr(node, "value")
value = self.visit(value_node)
if value in API_MAPPER:
value = API_MAPPER[value][0]
elif isinstance(value, str) and value.startswith(
"torch") and "(" not in value and "[" not in value:
self.no_support_apis.append(value)
return {key: value}
def visit_Tuple(self, node):
""" 返回tuple。
"""
elts_nodes = getattr(node, "elts")
elts = list()
for elts_node in elts_nodes:
elt = self.visit(elts_node)
elts.append(elt if isinstance(elt, str) else str(elt))
elts = "({})".format(", ".join(elts))
return elts
def visit_Assign(self, node):
""" 1. 将Assign节点加入scopes_and_dependencies;
2. 遍历Assign节点的子节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
def visit_Call(self, node):
""" 1. 获取原始函数名并更新为新的函数名。
2. 获取args和kwargs。
3. 根据API_MAPPER映射需要更新的操作,对参数进行处理。
4. 如果有前缀代码和后缀代码,则需要添加相应节点。
"""
# 获取函数名
func_node = node.func
if isinstance(func_node, ast.Attribute) and isinstance(func_node.value,
ast.Call):
func_name = None
else:
func_name = self.visit(func_node)
pytorch_api, dep_info = self._get_complete_api(func_name)
if pytorch_api is None:
self.generic_visit(node)
return
if pytorch_api not in API_MAPPER:
if pytorch_api.startswith(
"torch"
) and "[" not in pytorch_api and "(" not in pytorch_api:
self.no_support_apis.append(pytorch_api)
return
paddle_api = API_MAPPER[pytorch_api][0]
func_name = self._rename(func_name, dep_info, pytorch_api, paddle_api)
setattr(node, "func", ast.parse(func_name).body[0].value)
# 获取args
args_nodes = getattr(node, "args")
args_list = list()
for args_node in args_nodes:
args_list.append(self.visit(args_node))
# 获取keywords
keywords_nodes = getattr(node, "keywords")
kw_dict = dict()
for keywords_node in keywords_nodes:
if list(self.visit(keywords_node).keys())[0] is None:
args_list.append("**{}".format(
list(self.visit(keywords_node).values())[0]))
else:
kw_dict.update(self.visit(keywords_node))
if API_MAPPER[pytorch_api][1] is None:
return
target_name = None
father_node = self._get_father_node()
if isinstance(father_node, ast.Assign):
target_node = father_node.targets[0]
target_name = self.visit(target_node)
mapper = API_MAPPER[pytorch_api][1](func_name, pytorch_api, args_list,
kw_dict, target_name)
prefix_insert_codes, new_code, suffix_insert_codes = mapper.run()
if mapper.func_name.startswith("x2paddle."):
self.is_import_x2paddle = True
scope_node = self._get_scope_node()
if isinstance(ast.parse(new_code).body[0], ast.Assign):
node_index = self._get_current_index(scope_node, node)
scope_node.body[node_index] = ast.parse(
new_code.replace("\n", "")).body[0]
else:
new_call_node = ast.parse(new_code).body[0].value
setattr(node, "func", new_call_node.func) # 修改了fun_name
setattr(node, "args", new_call_node.args)
setattr(node, "keywords", new_call_node.keywords)
for i, n in enumerate(scope_node.body):
if father_node == n:
for code in prefix_insert_codes:
scope_node.body.insert(
i, ast.parse(code.replace("\n", "")).body[0])
i += 1
break
for i, n in enumerate(scope_node.body):
if father_node == n:
j = i + 1
for code in suffix_insert_codes:
scope_node.body.insert(
j, ast.parse(code.replace("\n", "")).body[0])
j += 1
break
def visit_Subscript(self, node):
value_node = node.value
value_name = self.visit(value_node)
pytorch_api, dep_info = self._get_complete_api(value_name)
if pytorch_api in API_MAPPER:
paddle_api = API_MAPPER[pytorch_api][0]
value_name = self._rename(value_name, dep_info, pytorch_api,
paddle_api)
node.value = ast.parse(value_name).body[0]
else:
if isinstance(pytorch_api, str) and pytorch_api.startswith(
"torch") and "(" not in pytorch_api:
self.no_support_apis.append(pytorch_api)
self.visit(node.slice)
self.visit(node.ctx)
def visit_FunctionDef(self, node):
""" 1. 将FunctionDef节点加入scopes_and_dependencies;
2. 遍历FunctionDef节点的子节点;
3. 去除scopes_and_dependencies中FunctionDef节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.FunctionDef):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_ClassDef(self, node):
""" 1. 将ClassDef节点加入scopes_and_dependencies;
2. 遍历ClassDef节点的子节点;
3. 去除scopes_and_dependencies中ClassDef节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.ClassDef):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_If(self, node):
""" 1. 将If节点加入scopes_and_dependencies;
2. 遍历If节点的子节点;
3. 去除scopes_and_dependencies中If节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.If):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_While(self, node):
""" 1. 将While节点加入scopes_and_dependencies;
2. 遍历Try节点的子节点;
3. 去除scopes_and_dependencies中Try节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.While):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_Try(self, node):
""" 1. 将Try节点加入scopes_and_dependencies;
2. 遍历Try节点的子节点;
3. 去除scopes_and_dependencies中Try节点以及之后的节点。
"""
self.scopes_and_dependencies.append(node)
self.generic_visit(node)
last_node = self.scopes_and_dependencies.pop(-1)
while not isinstance(last_node, ast.Try):
last_node = self.scopes_and_dependencies.pop(-1)
def visit_ExtSlice(self, node):
""" 将Index节点替换替换为Num。
"""
dim_nodes = node.dims
for i, dim_node in enumerate(dim_nodes):
if isinstance(dim_node, ast.Index):
dim_nodes[i] = dim_node.value
else:
self.visit(dim_node)
def visit_Str(self, node):
""" 修改模型参数的后缀名。
"""
setattr(node, "s",
node.s.replace(".pth", ".pdiparams").replace(
".pt", ".pdiparams").replace(".ckpt", ".pdiparams"))
def update(py_file_path, file_dependencies):
updater = AstUpdater(py_file_path, file_dependencies)
updater.run()
if len(updater.no_support_apis) > 0:
print("Can not convert the file {}.".format(py_file_path))
print("The unsupported packages or operators are: [{}].".format(
", ".join(set(updater.no_support_apis))))
return None
else:
return updater.root | 0.342242 | 0.204521 |
from unittest import TestCase
from nistbeacon.nistbeaconcrypto import NistBeaconCrypto
from unittest.mock import (
Mock,
patch,
)
class TestNistBeaconCrypto(TestCase):
@classmethod
def setUpClass(cls):
cls.verifier2013 = "_VERIFIER_20130905"
cls.verifier2013_timestamp = 1378395540
def test_verify_converts_1_to_bool(self):
"""
Verify that the verify method converts any positive (excluding 1)
value to a 'False' bool.
"""
# Create a mock'd verifier
mock_verifier = Mock()
mock_verifier.verify = Mock(return_value=1)
with patch.object(NistBeaconCrypto, self.verifier2013, mock_verifier):
# noinspection PyTypeChecker
result = NistBeaconCrypto.verify(
self.verifier2013_timestamp,
"junk",
"data",
)
self.assertIsInstance(result, bool)
self.assertTrue(result)
def test_verify_converts_false_int_to_bool(self):
"""
Verify that the verify method converts any integer
value EXCEPT FOR 1 to a 'False' bool.
"""
test_data = [100, 10, 2, 0, -2, -10, -100]
# Create a mock'd verifier
mock_verifier = Mock()
mock_verifier.verify = Mock(side_effect=test_data)
with patch.object(NistBeaconCrypto, self.verifier2013, mock_verifier):
for _ in test_data:
# noinspection PyTypeChecker
result = NistBeaconCrypto.verify(
self.verifier2013_timestamp,
"junk",
"data",
)
self.assertIsInstance(result, bool)
self.assertFalse(result)
def test_verify_does_not_convert_bool(self):
"""
Verify that the verify method does not convert any bool value
"""
test_data = [False, True]
# Create a mock'd verifier
mock_verifier = Mock()
mock_verifier.verify = Mock(side_effect=test_data)
with patch.object(NistBeaconCrypto, self.verifier2013, mock_verifier):
for test_data_point in test_data:
# noinspection PyTypeChecker
result = NistBeaconCrypto.verify(
self.verifier2013_timestamp,
"junk",
"data",
)
self.assertIsInstance(result, bool)
self.assertEqual(test_data_point, result) | tests/unit/nistbeacon/test_nistbeaconcrypto.py | from unittest import TestCase
from nistbeacon.nistbeaconcrypto import NistBeaconCrypto
from unittest.mock import (
Mock,
patch,
)
class TestNistBeaconCrypto(TestCase):
@classmethod
def setUpClass(cls):
cls.verifier2013 = "_VERIFIER_20130905"
cls.verifier2013_timestamp = 1378395540
def test_verify_converts_1_to_bool(self):
"""
Verify that the verify method converts any positive (excluding 1)
value to a 'False' bool.
"""
# Create a mock'd verifier
mock_verifier = Mock()
mock_verifier.verify = Mock(return_value=1)
with patch.object(NistBeaconCrypto, self.verifier2013, mock_verifier):
# noinspection PyTypeChecker
result = NistBeaconCrypto.verify(
self.verifier2013_timestamp,
"junk",
"data",
)
self.assertIsInstance(result, bool)
self.assertTrue(result)
def test_verify_converts_false_int_to_bool(self):
"""
Verify that the verify method converts any integer
value EXCEPT FOR 1 to a 'False' bool.
"""
test_data = [100, 10, 2, 0, -2, -10, -100]
# Create a mock'd verifier
mock_verifier = Mock()
mock_verifier.verify = Mock(side_effect=test_data)
with patch.object(NistBeaconCrypto, self.verifier2013, mock_verifier):
for _ in test_data:
# noinspection PyTypeChecker
result = NistBeaconCrypto.verify(
self.verifier2013_timestamp,
"junk",
"data",
)
self.assertIsInstance(result, bool)
self.assertFalse(result)
def test_verify_does_not_convert_bool(self):
"""
Verify that the verify method does not convert any bool value
"""
test_data = [False, True]
# Create a mock'd verifier
mock_verifier = Mock()
mock_verifier.verify = Mock(side_effect=test_data)
with patch.object(NistBeaconCrypto, self.verifier2013, mock_verifier):
for test_data_point in test_data:
# noinspection PyTypeChecker
result = NistBeaconCrypto.verify(
self.verifier2013_timestamp,
"junk",
"data",
)
self.assertIsInstance(result, bool)
self.assertEqual(test_data_point, result) | 0.820073 | 0.537041 |
r"""
================
Error Middleware
================
.. versionadded:: 0.2.0
Middleware to handle errors in aiohttp applications.
Usage
=====
.. code-block:: python
import re
from aiohttp import web
from aiohttp_middlewares import error_context, error_middleware
# Default error handler
async def error(request: web.Request) -> web.Response:
with error_context(request) as context:
return web.Response(
text=context.message,
status=context.status,
content_type="text/plain"
)
# Error handler for API requests
async def api_error(request: web.Request) -> web.Response:
with error_context(request) as context:
return web.json_response(context.data, status=context.status)
# Basic usage (one error handler for whole application)
app = web.Application(
middlewares=[
error_middleware(default_handler=api_error)
]
)
# Advanced usage (multiple error handlers for different
# application parts)
app = web.Application(
middlewares=[
error_middleware(
default_handler=error,
config={re.compile(r"^\/api"): api_error}
)
]
)
"""
from contextlib import contextmanager
from typing import Dict, Iterator, Optional
import attr
from aiohttp import web
from aiohttp.web_middlewares import _Handler, _Middleware
from .annotations import DictStrAny, Url
from .utils import match_path
DEFAULT_EXCEPTION = Exception("Unhandled aiohttp-middlewares exception.")
IGNORE_LOG_STATUSES = (400, 404, 422)
ERROR_REQUEST_KEY = "error"
Config = Dict[Url, _Handler]
@attr.dataclass
class ErrorContext:
"""Context with all necessary data about the error."""
err: Exception
message: str
status: int
data: DictStrAny
@contextmanager
def error_context(request: web.Request) -> Iterator[ErrorContext]:
"""Context manager to retrieve error data inside of error handler (view).
The context will contain:
- Error itself
- Error message (by default: ``str(err)``)
- Error status (by default: ``500``)
- Error data dict (by default: ``{"detail": str(err)}``)
"""
err = get_error_from_request(request)
message = getattr(err, "message", None) or str(err)
data = getattr(err, "data", None) or {"detail": message}
status = getattr(err, "status", None) or 500
yield ErrorContext(err=err, message=message, status=status, data=data)
def error_middleware(
*, default_handler: _Handler, config: Config = None
) -> _Middleware:
"""Middleware to handle exceptions in aiohttp applications.
To catch all possible errors, please put this middleware on top of your
``middlewares`` list as:
.. code-block:: python
from aiohttp import web
from aiohttp_middlewares import error_middleware, timeout_middleware
app = web.Application(
midllewares=[
error_middleware(...),
timeout_middleware(...)
]
)
:param default_handler:
Default handler to called on error catched by error middleware.
:param config:
When application requires multiple error handlers, provide mapping in
format ``Dict[Url, _Handler]``, where ``Url`` can be an exact string
to match path or regex and ``_Handler`` is a handler to be called when
``Url`` matches current request path if any.
"""
@web.middleware
async def middleware(
request: web.Request, handler: _Handler
) -> web.StreamResponse:
try:
return await handler(request)
except Exception as err:
set_error_to_request(request, err)
error_handler = (
get_error_handler(request, config) or default_handler
)
return await error_handler(request)
return middleware
def get_error_from_request(request: web.Request) -> Exception:
"""Get previously stored error from request dict.
Return default exception if nothing stored before.
"""
return request.get(ERROR_REQUEST_KEY) or DEFAULT_EXCEPTION
def get_error_handler(
request: web.Request, config: Optional[Config]
) -> Optional[_Handler]:
"""Find error handler matching current request path if any."""
if not config:
return None
path = request.rel_url.path
for item, handler in config.items():
if match_path(item, path):
return handler
return None
def set_error_to_request(request: web.Request, err: Exception) -> Exception:
"""Store catched error to request dict."""
request[ERROR_REQUEST_KEY] = err
return err | aiohttp_middlewares/error.py | r"""
================
Error Middleware
================
.. versionadded:: 0.2.0
Middleware to handle errors in aiohttp applications.
Usage
=====
.. code-block:: python
import re
from aiohttp import web
from aiohttp_middlewares import error_context, error_middleware
# Default error handler
async def error(request: web.Request) -> web.Response:
with error_context(request) as context:
return web.Response(
text=context.message,
status=context.status,
content_type="text/plain"
)
# Error handler for API requests
async def api_error(request: web.Request) -> web.Response:
with error_context(request) as context:
return web.json_response(context.data, status=context.status)
# Basic usage (one error handler for whole application)
app = web.Application(
middlewares=[
error_middleware(default_handler=api_error)
]
)
# Advanced usage (multiple error handlers for different
# application parts)
app = web.Application(
middlewares=[
error_middleware(
default_handler=error,
config={re.compile(r"^\/api"): api_error}
)
]
)
"""
from contextlib import contextmanager
from typing import Dict, Iterator, Optional
import attr
from aiohttp import web
from aiohttp.web_middlewares import _Handler, _Middleware
from .annotations import DictStrAny, Url
from .utils import match_path
DEFAULT_EXCEPTION = Exception("Unhandled aiohttp-middlewares exception.")
IGNORE_LOG_STATUSES = (400, 404, 422)
ERROR_REQUEST_KEY = "error"
Config = Dict[Url, _Handler]
@attr.dataclass
class ErrorContext:
"""Context with all necessary data about the error."""
err: Exception
message: str
status: int
data: DictStrAny
@contextmanager
def error_context(request: web.Request) -> Iterator[ErrorContext]:
"""Context manager to retrieve error data inside of error handler (view).
The context will contain:
- Error itself
- Error message (by default: ``str(err)``)
- Error status (by default: ``500``)
- Error data dict (by default: ``{"detail": str(err)}``)
"""
err = get_error_from_request(request)
message = getattr(err, "message", None) or str(err)
data = getattr(err, "data", None) or {"detail": message}
status = getattr(err, "status", None) or 500
yield ErrorContext(err=err, message=message, status=status, data=data)
def error_middleware(
*, default_handler: _Handler, config: Config = None
) -> _Middleware:
"""Middleware to handle exceptions in aiohttp applications.
To catch all possible errors, please put this middleware on top of your
``middlewares`` list as:
.. code-block:: python
from aiohttp import web
from aiohttp_middlewares import error_middleware, timeout_middleware
app = web.Application(
midllewares=[
error_middleware(...),
timeout_middleware(...)
]
)
:param default_handler:
Default handler to called on error catched by error middleware.
:param config:
When application requires multiple error handlers, provide mapping in
format ``Dict[Url, _Handler]``, where ``Url`` can be an exact string
to match path or regex and ``_Handler`` is a handler to be called when
``Url`` matches current request path if any.
"""
@web.middleware
async def middleware(
request: web.Request, handler: _Handler
) -> web.StreamResponse:
try:
return await handler(request)
except Exception as err:
set_error_to_request(request, err)
error_handler = (
get_error_handler(request, config) or default_handler
)
return await error_handler(request)
return middleware
def get_error_from_request(request: web.Request) -> Exception:
"""Get previously stored error from request dict.
Return default exception if nothing stored before.
"""
return request.get(ERROR_REQUEST_KEY) or DEFAULT_EXCEPTION
def get_error_handler(
request: web.Request, config: Optional[Config]
) -> Optional[_Handler]:
"""Find error handler matching current request path if any."""
if not config:
return None
path = request.rel_url.path
for item, handler in config.items():
if match_path(item, path):
return handler
return None
def set_error_to_request(request: web.Request, err: Exception) -> Exception:
"""Store catched error to request dict."""
request[ERROR_REQUEST_KEY] = err
return err | 0.871721 | 0.157947 |
from random import uniform, choice
from tqdm import tqdm
from functools import partial
from p_tqdm import p_map
from .backtest import backtest
from .utils.getters import get_strategy
from numpy import isnan, nan
import warnings
warnings.simplefilter(action='ignore', category=Warning)
def populate(size, config_range):
get_val = lambda k,v: uniform(v[0], v[1]) if isinstance(v[0], float) else int(uniform(v[0], v[1]))
return [{'fitness': None, 'config': {k: get_val(k,v) for k,v in config_range.items()}} for _ in range(size)]
def get(r, d):
s = d.loc[r[-2]:r[-1],]
low = s.loc[s['low']==min(s['low'])]['low'].iat[0]
high = s.loc[s['high']==max(s['high'])]['high'].iat[0]
return [low, high]
def _truncate(d):
d['time'] = d.index
d = d.reset_index()
t = d[((~isnan(d['buy']))|(~isnan(d['sell'])))]
t['ix'] = t.index
t['iy'] = t['ix'].shift(-1)
if len(t) > 0: t.at[t.index[-1], 'iy'] = d.index[-1]
t['iy'] = t['iy'].apply(lambda i: int(i))
t[['low','high']] = [get(r, d) for r in t.itertuples()]
return t.set_index('time').drop(['ix','iy'], axis=1)
def fit(p, data, strategy, truncate):
d = strategy(data.copy(deep=False), p['config'])
t = _truncate(d) if truncate else d
p['fitness'] = backtest(t, p['config'])
return p
def select(data, pop, i, n_iter, strategy, truncate):
pop = list(p_map(partial(fit, data=data, strategy_name=strategy, truncate=truncate), pop, desc=' fitting', leave=False))
pop = sorted(pop, reverse=True, key=lambda p: p['fitness'])
return pop[:int(len(pop)/3)]
def crossover(selected):
return [{'fitness': None, 'config': {k: choice(selected)['config'][k] for k in selected[0]['config'].keys()}} for _ in range(len(selected))]
def mutate(subpop, config_range, max_mut_diff):
def mut_val(k,v):
new_val = -1
while new_val < config_range[k][0] or new_val > config_range[k][1]:
new_val = v * uniform(1-max_mut_diff,1+max_mut_diff)
if not isinstance(config_range[k][0], float):
new_val = int(new_val)
return new_val
return [{'fitness': None, 'config': {k: mut_val(k,v) for k,v in p['config'].items()}} for p in subpop]
def optimize(data, strategy, config_range, pop_size=1000, n_iter=100, max_mut_diff=.2, max_reps=-1, truncate: bool = False):
min_ticks_options = config_range.pop('min_ticks')
ticks = len(data)
reps, best = 0, None
pop = populate(pop_size, config_range)
for i in tqdm(range(n_iter), desc='Generation', leave=False):
selected = select(data, pop, i, n_iter, strategy, truncate)
if max_reps > 0:
if selected[0] == best:
reps += 1
else:
best = selected[0]
reps = 0
if reps > max_reps:
return selected[0]['config']
crossed = crossover(selected)
mutated = mutate(selected, config_range, max_mut_diff)
fill_count = pop_size - 5 - len(mutated) - len(crossed)
pop = [*selected[:5], *mutated, *crossed, *populate(fill_count, config_range)]
result = pop[0]['config']
result['min_ticks'] = max([result[o] for o in min_ticks_options])
return result | yuzu/optimize.py | from random import uniform, choice
from tqdm import tqdm
from functools import partial
from p_tqdm import p_map
from .backtest import backtest
from .utils.getters import get_strategy
from numpy import isnan, nan
import warnings
warnings.simplefilter(action='ignore', category=Warning)
def populate(size, config_range):
get_val = lambda k,v: uniform(v[0], v[1]) if isinstance(v[0], float) else int(uniform(v[0], v[1]))
return [{'fitness': None, 'config': {k: get_val(k,v) for k,v in config_range.items()}} for _ in range(size)]
def get(r, d):
s = d.loc[r[-2]:r[-1],]
low = s.loc[s['low']==min(s['low'])]['low'].iat[0]
high = s.loc[s['high']==max(s['high'])]['high'].iat[0]
return [low, high]
def _truncate(d):
d['time'] = d.index
d = d.reset_index()
t = d[((~isnan(d['buy']))|(~isnan(d['sell'])))]
t['ix'] = t.index
t['iy'] = t['ix'].shift(-1)
if len(t) > 0: t.at[t.index[-1], 'iy'] = d.index[-1]
t['iy'] = t['iy'].apply(lambda i: int(i))
t[['low','high']] = [get(r, d) for r in t.itertuples()]
return t.set_index('time').drop(['ix','iy'], axis=1)
def fit(p, data, strategy, truncate):
d = strategy(data.copy(deep=False), p['config'])
t = _truncate(d) if truncate else d
p['fitness'] = backtest(t, p['config'])
return p
def select(data, pop, i, n_iter, strategy, truncate):
pop = list(p_map(partial(fit, data=data, strategy_name=strategy, truncate=truncate), pop, desc=' fitting', leave=False))
pop = sorted(pop, reverse=True, key=lambda p: p['fitness'])
return pop[:int(len(pop)/3)]
def crossover(selected):
return [{'fitness': None, 'config': {k: choice(selected)['config'][k] for k in selected[0]['config'].keys()}} for _ in range(len(selected))]
def mutate(subpop, config_range, max_mut_diff):
def mut_val(k,v):
new_val = -1
while new_val < config_range[k][0] or new_val > config_range[k][1]:
new_val = v * uniform(1-max_mut_diff,1+max_mut_diff)
if not isinstance(config_range[k][0], float):
new_val = int(new_val)
return new_val
return [{'fitness': None, 'config': {k: mut_val(k,v) for k,v in p['config'].items()}} for p in subpop]
def optimize(data, strategy, config_range, pop_size=1000, n_iter=100, max_mut_diff=.2, max_reps=-1, truncate: bool = False):
min_ticks_options = config_range.pop('min_ticks')
ticks = len(data)
reps, best = 0, None
pop = populate(pop_size, config_range)
for i in tqdm(range(n_iter), desc='Generation', leave=False):
selected = select(data, pop, i, n_iter, strategy, truncate)
if max_reps > 0:
if selected[0] == best:
reps += 1
else:
best = selected[0]
reps = 0
if reps > max_reps:
return selected[0]['config']
crossed = crossover(selected)
mutated = mutate(selected, config_range, max_mut_diff)
fill_count = pop_size - 5 - len(mutated) - len(crossed)
pop = [*selected[:5], *mutated, *crossed, *populate(fill_count, config_range)]
result = pop[0]['config']
result['min_ticks'] = max([result[o] for o in min_ticks_options])
return result | 0.371023 | 0.273356 |
import gym
import logging
from d4rl.pointmaze import waypoint_controller
from d4rl.pointmaze import maze_model
import numpy as np
import pickle
import gzip
import h5py
import argparse
# python scripts/generate_maze2d_datasets.py --env-name maze2d-open-v0 --fixed-target
# python scripts/generate_maze2d_datasets.py --env-name maze2d-umaze-v1 --fixed-target
# python scripts/generate_maze2d_datasets.py --env-name maze2d-medium-v1 --fixed-target
# python scripts/generate_maze2d_datasets.py --env-name maze2d-large-v1 --fixed-target
# python scripts/generate_maze2d_datasets.py --env-name maze2d-large-v0 --fixed-target
def reset_data():
return {'observations': [],
'actions': [],
'terminals': [],
'rewards': [],
'infos/goal': [],
'infos/qpos': [],
'infos/qvel': [],
}
def append_data(data, s, a, tgt, done, env_data):
data['observations'].append(s)
data['actions'].append(a)
data['rewards'].append(0.0)
data['terminals'].append(done)
data['infos/goal'].append(tgt)
data['infos/qpos'].append(env_data.qpos.ravel().copy())
data['infos/qvel'].append(env_data.qvel.ravel().copy())
def npify(data):
for k in data:
if k == 'terminals':
dtype = np.bool_
else:
dtype = np.float32
data[k] = np.array(data[k], dtype=dtype)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--noisy', action='store_true', help='Noisy actions')
parser.add_argument('--fixed-target', action='store_true', help='Fixed target point')
parser.add_argument('--env-name', type=str, default='maze2d-umaze-v1', help='Maze type')
parser.add_argument('--num-samples', type=int, default=int(1e6), help='Num samples to collect')
parser.add_argument('--num-episodes', type=int, default=int(1e3), help='Num episodes to collect')
parser.add_argument('--render', action='store_true', help='Render trajectories')
parser.add_argument('--save-datasets', default= False, action='store_true', help='Save datasets')
args = parser.parse_args()
data = reset_data()
env = gym.make(args.env_name)
maze = env.str_maze_spec
max_episode_steps = env._max_episode_steps
controller = waypoint_controller.WaypointController(maze)
env = maze_model.MazeEnv(maze)
for episode in range(args.num_episodes):
s = env.reset()
act = env.action_space.sample()
done, episode_step, episode_reward = False, 0, 0
if args.fixed_target:
if args.env_name == "maze2d-open-v0":
env.set_target(np.array([2.0, 3.0]))
elif args.env_name == "maze2d-umaze-v1":
env.set_target(np.array([1.0, 1.0]))
elif args.env_name == "maze2d-medium-v1":
env.set_target(np.array([6.0, 6.0]))
elif args.env_name == "maze2d-large-v0" or args.env_name == "maze2d-large-v1":
env.set_target(np.array([7.0, 9.0]))
else:
raise NotImplementedError("You should define goal point before generate dataset.\n",
"Available task: maze2d-umaze-v1 | maze2d-medium-v1 | maze2d-large-v1")
else:
env.set_target()
while not done:
position = s[0:2]
velocity = s[2:4]
act, _done = controller.get_action(episode_step, position, velocity, env._target)
if args.noisy:
act = act + np.random.randn(*act.shape) * 0.5
act = np.clip(act, -1.0, 1.0)
if episode_step >= max_episode_steps:
done = True
append_data(data, s, act, env._target, done, env.sim.data)
ns, r, _, _ = env.step(act)
episode_reward += r
if len(data['observations']) % 10000 == 0:
print(len(data['observations']))
episode_step += 1
if done:
break
else:
s = ns
if args.render:
env.render()
print("episode_reward: ", episode_reward)
if args.save_dataset:
if args.noisy:
fname = '%s-noisy.hdf5' % args.env_name
else:
fname = '%s.hdf5' % args.env_name
dataset = h5py.File(fname, 'w')
npify(data)
for k in data:
dataset.create_dataset(k, data=data[k], compression='gzip')
if __name__ == "__main__":
main() | scripts/generate_maze2d_datasets.py | import gym
import logging
from d4rl.pointmaze import waypoint_controller
from d4rl.pointmaze import maze_model
import numpy as np
import pickle
import gzip
import h5py
import argparse
# python scripts/generate_maze2d_datasets.py --env-name maze2d-open-v0 --fixed-target
# python scripts/generate_maze2d_datasets.py --env-name maze2d-umaze-v1 --fixed-target
# python scripts/generate_maze2d_datasets.py --env-name maze2d-medium-v1 --fixed-target
# python scripts/generate_maze2d_datasets.py --env-name maze2d-large-v1 --fixed-target
# python scripts/generate_maze2d_datasets.py --env-name maze2d-large-v0 --fixed-target
def reset_data():
return {'observations': [],
'actions': [],
'terminals': [],
'rewards': [],
'infos/goal': [],
'infos/qpos': [],
'infos/qvel': [],
}
def append_data(data, s, a, tgt, done, env_data):
data['observations'].append(s)
data['actions'].append(a)
data['rewards'].append(0.0)
data['terminals'].append(done)
data['infos/goal'].append(tgt)
data['infos/qpos'].append(env_data.qpos.ravel().copy())
data['infos/qvel'].append(env_data.qvel.ravel().copy())
def npify(data):
for k in data:
if k == 'terminals':
dtype = np.bool_
else:
dtype = np.float32
data[k] = np.array(data[k], dtype=dtype)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--noisy', action='store_true', help='Noisy actions')
parser.add_argument('--fixed-target', action='store_true', help='Fixed target point')
parser.add_argument('--env-name', type=str, default='maze2d-umaze-v1', help='Maze type')
parser.add_argument('--num-samples', type=int, default=int(1e6), help='Num samples to collect')
parser.add_argument('--num-episodes', type=int, default=int(1e3), help='Num episodes to collect')
parser.add_argument('--render', action='store_true', help='Render trajectories')
parser.add_argument('--save-datasets', default= False, action='store_true', help='Save datasets')
args = parser.parse_args()
data = reset_data()
env = gym.make(args.env_name)
maze = env.str_maze_spec
max_episode_steps = env._max_episode_steps
controller = waypoint_controller.WaypointController(maze)
env = maze_model.MazeEnv(maze)
for episode in range(args.num_episodes):
s = env.reset()
act = env.action_space.sample()
done, episode_step, episode_reward = False, 0, 0
if args.fixed_target:
if args.env_name == "maze2d-open-v0":
env.set_target(np.array([2.0, 3.0]))
elif args.env_name == "maze2d-umaze-v1":
env.set_target(np.array([1.0, 1.0]))
elif args.env_name == "maze2d-medium-v1":
env.set_target(np.array([6.0, 6.0]))
elif args.env_name == "maze2d-large-v0" or args.env_name == "maze2d-large-v1":
env.set_target(np.array([7.0, 9.0]))
else:
raise NotImplementedError("You should define goal point before generate dataset.\n",
"Available task: maze2d-umaze-v1 | maze2d-medium-v1 | maze2d-large-v1")
else:
env.set_target()
while not done:
position = s[0:2]
velocity = s[2:4]
act, _done = controller.get_action(episode_step, position, velocity, env._target)
if args.noisy:
act = act + np.random.randn(*act.shape) * 0.5
act = np.clip(act, -1.0, 1.0)
if episode_step >= max_episode_steps:
done = True
append_data(data, s, act, env._target, done, env.sim.data)
ns, r, _, _ = env.step(act)
episode_reward += r
if len(data['observations']) % 10000 == 0:
print(len(data['observations']))
episode_step += 1
if done:
break
else:
s = ns
if args.render:
env.render()
print("episode_reward: ", episode_reward)
if args.save_dataset:
if args.noisy:
fname = '%s-noisy.hdf5' % args.env_name
else:
fname = '%s.hdf5' % args.env_name
dataset = h5py.File(fname, 'w')
npify(data)
for k in data:
dataset.create_dataset(k, data=data[k], compression='gzip')
if __name__ == "__main__":
main() | 0.368292 | 0.243401 |
import pytest
from main import process_and_cleanup
# Testing the base parsing for if/else
def test_cleanup_graph_base_if():
graph = process_and_cleanup("TestFiles/pytest/if_normal_test_file.COB")
assert graph.get_size() == 3
# Testing simple branches for if/else
def test_cleanup_graph_base_if_left_branch():
graph = process_and_cleanup("TestFiles/pytest/if_left_branch_test_file.COB")
assert graph.get_size() == 4
def test_cleanup_graph_base_if_right_branch():
graph = process_and_cleanup("TestFiles/pytest/if_right_branch_test_file.COB")
assert graph.get_size() == 4
def test_cleanup_graph_base_if_both_branch():
graph = process_and_cleanup("TestFiles/pytest/if_both_branch_test_file.COB")
assert graph.get_size() == 5
# Testing nested branches for if/else
def test_cleanup_graph_base_if_nested_left_branch():
graph = process_and_cleanup("TestFiles/pytest/if_nested_left_branch_test_file.COB")
assert graph.get_size() == 4
def test_cleanup_graph_base_if_nested_right_branch():
graph = process_and_cleanup("TestFiles/pytest/if_nested_right_branch_test_file.COB")
assert graph.get_size() == 4
def test_cleanup_graph_base_if_nested_both_branch():
graph = process_and_cleanup("TestFiles/pytest/if_nested_both_branch_test_file.COB")
assert graph.get_size() == 5
# Testing evaluates
def test_cleanup_graph_simple_evaluate():
graph = process_and_cleanup("TestFiles/pytest/evaluate_simple_test_file.COB")
assert graph.get_size() == 6
def test_cleanup_graph_mixed_evaluate():
graph = process_and_cleanup("TestFiles/pytest/evaluate_if_mix_test_file.COB")
assert graph.get_size() == 8
# Testing the control-loop
def test_cleanup_graph_next_sentence():
graph = process_and_cleanup("TestFiles/pytest/next_sentence_test_file.COB")
assert graph.get_size() == 5
# Testing the simple single label goback loop
def test_cleanup_graph_base_perform_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_base_test_file.COB", label_clean=True)
assert graph.get_size() == 5
def test_cleanup_graph_base_perform_no_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_base_test_file.COB")
assert graph.get_size() == 10
def test_cleanup_graph_chained_perform_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_chained_test_file.COB", label_clean=True)
assert graph.get_size() == 8
def test_cleanup_graph_chained_perform_no_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_chained_test_file.COB")
assert graph.get_size() == 11
def test_cleanup_graph_broken_perform_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_broken_goto_test_file.COB", label_clean=True)
assert graph.get_size() == 8
def test_cleanup_graph_broken_perform_no_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_broken_goto_test_file.COB")
assert graph.get_size() == 11
# Testing the perform thru (multiple label goback)
def test_cleanup_graph_base_perform_thru_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/performThru_base_test_file.COB", label_clean=True)
assert graph.get_size() == 6
def test_cleanup_graph_base_perform_thru_no_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/performThru_base_test_file.COB")
assert graph.get_size() == 10
def test_cleanup_graph_chained_perform_thru_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_chained_test_file.COB", label_clean=True)
assert graph.get_size() == 10
def test_cleanup_graph_chained_perform_thru_no_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_chained_test_file.COB")
assert graph.get_size() == 11
def test_cleanup_graph_goto_perform_thru_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_goto_test_file.COB", label_clean=True)
assert graph.get_size() == 8
def test_cleanup_graph_goto_perform_thru_no_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_goto_test_file.COB")
assert graph.get_size() == 11
def test_cleanup_graph_broken_perform_thru_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_broken_goto_test_file.COB", label_clean=True)
assert graph.get_size() == 9
def test_cleanup_graph_broken_perform_thru_no_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_broken_goto_test_file.COB")
assert graph.get_size() == 11 | src/Test/test_cleanup_graph.py | import pytest
from main import process_and_cleanup
# Testing the base parsing for if/else
def test_cleanup_graph_base_if():
graph = process_and_cleanup("TestFiles/pytest/if_normal_test_file.COB")
assert graph.get_size() == 3
# Testing simple branches for if/else
def test_cleanup_graph_base_if_left_branch():
graph = process_and_cleanup("TestFiles/pytest/if_left_branch_test_file.COB")
assert graph.get_size() == 4
def test_cleanup_graph_base_if_right_branch():
graph = process_and_cleanup("TestFiles/pytest/if_right_branch_test_file.COB")
assert graph.get_size() == 4
def test_cleanup_graph_base_if_both_branch():
graph = process_and_cleanup("TestFiles/pytest/if_both_branch_test_file.COB")
assert graph.get_size() == 5
# Testing nested branches for if/else
def test_cleanup_graph_base_if_nested_left_branch():
graph = process_and_cleanup("TestFiles/pytest/if_nested_left_branch_test_file.COB")
assert graph.get_size() == 4
def test_cleanup_graph_base_if_nested_right_branch():
graph = process_and_cleanup("TestFiles/pytest/if_nested_right_branch_test_file.COB")
assert graph.get_size() == 4
def test_cleanup_graph_base_if_nested_both_branch():
graph = process_and_cleanup("TestFiles/pytest/if_nested_both_branch_test_file.COB")
assert graph.get_size() == 5
# Testing evaluates
def test_cleanup_graph_simple_evaluate():
graph = process_and_cleanup("TestFiles/pytest/evaluate_simple_test_file.COB")
assert graph.get_size() == 6
def test_cleanup_graph_mixed_evaluate():
graph = process_and_cleanup("TestFiles/pytest/evaluate_if_mix_test_file.COB")
assert graph.get_size() == 8
# Testing the control-loop
def test_cleanup_graph_next_sentence():
graph = process_and_cleanup("TestFiles/pytest/next_sentence_test_file.COB")
assert graph.get_size() == 5
# Testing the simple single label goback loop
def test_cleanup_graph_base_perform_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_base_test_file.COB", label_clean=True)
assert graph.get_size() == 5
def test_cleanup_graph_base_perform_no_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_base_test_file.COB")
assert graph.get_size() == 10
def test_cleanup_graph_chained_perform_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_chained_test_file.COB", label_clean=True)
assert graph.get_size() == 8
def test_cleanup_graph_chained_perform_no_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_chained_test_file.COB")
assert graph.get_size() == 11
def test_cleanup_graph_broken_perform_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_broken_goto_test_file.COB", label_clean=True)
assert graph.get_size() == 8
def test_cleanup_graph_broken_perform_no_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/perform_broken_goto_test_file.COB")
assert graph.get_size() == 11
# Testing the perform thru (multiple label goback)
def test_cleanup_graph_base_perform_thru_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/performThru_base_test_file.COB", label_clean=True)
assert graph.get_size() == 6
def test_cleanup_graph_base_perform_thru_no_clean_labels():
graph = process_and_cleanup("TestFiles/pytest/performThru_base_test_file.COB")
assert graph.get_size() == 10
def test_cleanup_graph_chained_perform_thru_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_chained_test_file.COB", label_clean=True)
assert graph.get_size() == 10
def test_cleanup_graph_chained_perform_thru_no_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_chained_test_file.COB")
assert graph.get_size() == 11
def test_cleanup_graph_goto_perform_thru_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_goto_test_file.COB", label_clean=True)
assert graph.get_size() == 8
def test_cleanup_graph_goto_perform_thru_no_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_goto_test_file.COB")
assert graph.get_size() == 11
def test_cleanup_graph_broken_perform_thru_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_broken_goto_test_file.COB", label_clean=True)
assert graph.get_size() == 9
def test_cleanup_graph_broken_perform_thru_no_clean_label():
graph = process_and_cleanup("TestFiles/pytest/performThru_broken_goto_test_file.COB")
assert graph.get_size() == 11 | 0.304145 | 0.592018 |
# # Explore highly co-expressed genes
# In the previous [notebook](2_explore_corr_of_genes.ipynb) we observed that using 39 samples with 201 PAO1-specific genes, that the correlation of accessory-accessory genes is higher compared to the correlation of core-core and core-accessory genes.
#
# Based on this finding, we want to know: *What can explain this difference in correlation distribution?*
#
# This notebook performs a follow-up analysis. In particular this notebook performs a deeper examination of the correlation structure per group (core-core, core-accessory, accessory-accessory) by looking at the trends of the nearest neighbors (i.e. highly correlated genes) of each gene.
# In[74]:
import pandas as pd
import os
import pickle
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from functions import calculations
np.random.seed(123)
# In[75]:
# Input
base_dir = os.path.abspath(os.path.join(os.getcwd(),"../"))
base_intermediate_dir = os.path.join(
base_dir,
"pilot_experiment",
"data",
"tmp")
core_gene_ids_file = os.path.join(
base_intermediate_dir,
"core_gene_ids.pickle")
acc_gene_ids_file = os.path.join(
base_intermediate_dir,
"acc_gene_ids.pickle")
real_all_corr_file = os.path.join(
base_intermediate_dir,
"real_all_corr.pickle")
shuffled_all_corr_file = os.path.join(
base_intermediate_dir,
"shuffled_all_corr.pickle")
# Import Pseudomonas operon annotations from ADAGE repo
# Original source of data is from DOOR
# https://github.com/greenelab/adage/blob/master/Genome_organization/operon_3.txt
# Operons containing at least 3 genes
operon_file = "https://github.com/greenelab/adage/blob/master/Genome_organization/operon_3.txt"
# In[76]:
# Read in gene ids
core_gene_ids = pickle.load(open(core_gene_ids_file, "rb"))
acc_gene_ids = pickle.load(open(acc_gene_ids_file, "rb"))
# Get number of core and accessory genes
num_core_genes = len(core_gene_ids)
num_acc_genes = len(acc_gene_ids)
num_all_genes = num_core_genes + num_acc_genes
# # Extract statistics about co-expression from correlation matrix
# In[77]:
# Define threshold for highly co-expressed genes
coexpression_threshold = 0.9
# ### Co-expression statsitics using real data
# In[78]:
# Get co-expression patterns using real expression data
real_core_df, real_acc_df = calculations.get_coexpression_stats(real_all_corr_file,
operon_file,
core_gene_ids_file,
acc_gene_ids_file,
coexpression_threshold)
# In[79]:
real_core_df.head()
# In[80]:
real_acc_df.head()
# ### Co-expression statistics using shuffled data
# In[81]:
# Get co-expression patterns using shuffled expression data (control)
shuffled_core_df, shuffled_acc_df = calculations.get_coexpression_stats(shuffled_all_corr_file,
operon_file,
core_gene_ids_file,
acc_gene_ids_file,
coexpression_threshold)
shuffled_core_df.head()
# In[82]:
shuffled_acc_df.head()
# # Plot trends in co-expression data
# ## 1. Number of co-expressed genes
# In[83]:
sns.set()
# ### Number of co-expressed genes
# In[84]:
# Get bins using all data
hist, bins_num_coexpressed_real = np.histogram(np.concatenate([real_core_df['num_coexpressed_genes'].values,
real_acc_df['num_coexpressed_genes'].values]))
# Distribution of number of co-expressed genes in real data
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
sns.distplot(real_core_df['num_coexpressed_genes'].tolist(),
label='core',
color='red',
kde=False,
bins=bins_num_coexpressed_real,
ax=axes[0])
sns.distplot(real_acc_df['num_coexpressed_genes'].tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_num_coexpressed_real,
ax=axes[1])
plt.suptitle('Number of co-expressed genes (real data, threshold={})'.format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Number of co-expressed genes', ha='center')
axes[0].set_ylabel('Counts')
# ### Number of nonzero co-expressed genes
# In[85]:
## Remove genes with 0 co-expressed genes
# Get bins using all data
hist, bins_num_coexpressed_real_nonzero = np.histogram(np.concatenate(
[real_core_df[real_core_df['num_coexpressed_genes']>0]['num_coexpressed_genes'].values,
real_acc_df[real_acc_df['num_coexpressed_genes']>0]['num_coexpressed_genes'].values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of number of co-expressed genes in real data
sns.distplot(real_core_df[real_core_df['num_coexpressed_genes']>0]['num_coexpressed_genes'].tolist(),
label='core',
color='red',
kde=False,
bins=bins_num_coexpressed_real_nonzero,
ax=axes[0])
sns.distplot(real_acc_df[real_acc_df['num_coexpressed_genes']>0]['num_coexpressed_genes'].tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_num_coexpressed_real_nonzero,
ax=axes[1])
plt.suptitle('Number of nonzero co-expressed genes (real data, threshold={})'.format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Number of co-expressed genes', ha='center')
axes[0].set_ylabel('Counts')
# In[86]:
# Get bins using all data
hist, bins_num_coexpressed_shuffled = np.histogram(np.concatenate([shuffled_core_df['num_coexpressed_genes'].values,
shuffled_acc_df['num_coexpressed_genes'].values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of number of co-expressed genes in shuffled data
sns.distplot(shuffled_core_df['num_coexpressed_genes'].tolist(),
label='core',
color='red',
kde=False,
bins=bins_num_coexpressed_shuffled,
ax=axes[0])
sns.distplot(shuffled_acc_df['num_coexpressed_genes'].tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_num_coexpressed_shuffled,
ax=axes[1]
)
plt.suptitle('Number of co-expressed genes (shuffled data, threshold={})'.format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Number of co-expressed genes', ha='center')
axes[0].set_ylabel('Counts')
# In[87]:
# Print statistics about co-expressed genes
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- For a given CORE gene, there is a median of {} co-expressed genes'.
format(np.median(real_core_df['num_coexpressed_genes'])))
print('- For a given ACCESSORY gene, there is a median of {} co-expressed genes \n'.
format(np.median(real_acc_df['num_coexpressed_genes'])))
# For shuffled data
print('Using a threshold of {} to define co-expression (shuffled data): \n'.
format(coexpression_threshold))
print('- For a given CORE gene, there is a median of {} co-expressed genes'.
format(np.median(shuffled_core_df['num_coexpressed_genes'])))
print('- For a given ACCESSORY gene, there is a median of {} co-expressed genes'.
format(np.median(shuffled_acc_df['num_coexpressed_genes'])))
# **Overall:**
# * Many core and accessory genes are not co-expressed with other genes or very few genes, as expected
# * As increase threshold (more stringent), there are fewer co-expressed genes, as expected
# * (control, not shown) All genes (threshold=0.75,0.9) are connected to just 1 gene, as expected, since we have destroyed relationships between genes when we shuffled
# * Both core and accessory genes are have the same degree of connectivity
#
# **Observation using All experiments:**
# * At a threshold of 0.5, core genes have a median of 716 genes they are connect to and accessory genes have a median of 601 genes they are connected to
# * At a threshold of 0.75 core genes have a median of 53 genes they are connect to and accessory genes have a median of 74 genes they are connected to
# * At a threshold of 0.9, core and accessory genes have a median of 1 gene that they are connected to
#
# **Observation using only PAO1 experiments:**
# * At a threshold of 0.5, core genes have a median of 1331 genes they are connect to and accessory genes have a median of 1341 genes they are connected to. So there are more connections using only PAO1 genes, which we would expect since the accessory genes are PAO1-specific.
# * At a threshold of 0.75 core genes have a median of 554 genes they are connect to and accessory genes have a median of 576 genes they are connected to
# * At a threshold of 0.9, core genes have a median of 21 gene that they are connected to and accessory genes have a median of 57 genes they are connected to
#
# **Observation using only PA14 experiments:**
# * At a threshold of 0.5, core genes have a median of 1133 genes they are connect to and accessory genes have a median of 1065 genes they are connected to. So there are more connections using only PAO1 genes, which we would expect since the accessory genes are PAO1-specific.
# * At a threshold of 0.75 core genes have a median of 153 genes they are connect to and accessory genes have a median of 132 genes they are connected to
# * At a threshold of 0.9, core genes have a median of 2 gene that they are connected to and accessory genes have a median of 3 genes they are connected to
# ### Compare co-expressed vs not co-expressed genes
# What is the difference between genes that are co-expressed vs those that are not?
# In[15]:
# Get genes that are co-expressed with other genes
coexpressed_core_genes = list(real_core_df[real_core_df['num_coexpressed_genes']>0].index)
coexpressed_acc_genes = list(real_acc_df[real_acc_df['num_coexpressed_genes']>0].index)
# In[16]:
len(coexpressed_core_genes)
# In[17]:
len(coexpressed_acc_genes)
# At a strict threshold of 0.9, all genes are co-expressed with **at least** one other gene. So there are no independent genes.
# ## 2. Percent of co-expressed genes that are NOT in the same operon
# In[15]:
# Calculate the percent of co-expressed genes that are non co-operonic (real data)
real_percent_non_cooperonic_coexpressed_core_genes = (
real_core_df['num_non_cooperonic_coexpressed_genes']/real_core_df['num_coexpressed_genes'])
real_percent_non_cooperonic_coexpressed_acc_genes = (
real_acc_df['num_non_cooperonic_coexpressed_genes']/real_acc_df['num_coexpressed_genes'])
# There are NaNs in cases where there are 0 co-expressed genes and therefore 0 non-cooperonic genes
real_num_core_na = real_percent_non_cooperonic_coexpressed_core_genes.isna().sum()
real_num_acc_na = real_percent_non_cooperonic_coexpressed_acc_genes.isna().sum()
# Since we are concerned with "of those co-expressed genes how many are in NOT in the same operon", we will remove these
real_percent_non_cooperonic_coexpressed_core_genes_noNa = real_percent_non_cooperonic_coexpressed_core_genes.dropna(inplace=False)
real_percent_non_cooperonic_coexpressed_acc_genes_noNa = real_percent_non_cooperonic_coexpressed_acc_genes.dropna(inplace=False)
# In[16]:
## TEST: What does distribution look like before removing NaNs?
# Get bins using all data
hist, bins_num_percent_non_cooperonic_real = np.histogram(
np.concatenate(
[real_percent_non_cooperonic_coexpressed_core_genes.fillna(0),
real_percent_non_cooperonic_coexpressed_acc_genes.fillna(0)]
)
)
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of percent of co-expressed genes that are NOT co-operonic in real data
sns.distplot(real_percent_non_cooperonic_coexpressed_core_genes.fillna(0),
label='core',
color='red',
kde=False,
bins=bins_num_percent_non_cooperonic_real,
ax=axes[0])
sns.distplot(real_percent_non_cooperonic_coexpressed_acc_genes.fillna(0),
label='accessory',
color='blue',
kde=False,
bins=bins_num_percent_non_cooperonic_real,
ax=axes[1])
plt.suptitle('TEST'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes', ha='center')
axes[0].set_ylabel('Count')
# In[17]:
# Get bins using all data
hist, bins_num_percent_non_cooperonic_real = np.histogram(
np.concatenate(
[real_percent_non_cooperonic_coexpressed_core_genes_noNa,
real_percent_non_cooperonic_coexpressed_acc_genes_noNa]
)
)
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of percent of co-expressed genes that are NOT co-operonic in real data
sns.distplot(real_percent_non_cooperonic_coexpressed_core_genes_noNa,
label='core',
color='red',
kde=False,
bins=bins_num_percent_non_cooperonic_real,
ax=axes[0])
sns.distplot(real_percent_non_cooperonic_coexpressed_acc_genes_noNa,
label='accessory',
color='blue',
kde=False,
bins=bins_num_percent_non_cooperonic_real,
ax=axes[1]
)
plt.suptitle('Percent of co-expressed genes that are NOT co-operonic (real data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes', ha='center')
axes[0].set_ylabel('Count')
# In[18]:
# Calculate the percent of co-expressed genes that are non co-operonic (shuffled data)
shuffled_percent_non_cooperonic_coexpressed_core_genes = (
shuffled_core_df['num_non_cooperonic_coexpressed_genes']/shuffled_core_df['num_coexpressed_genes'])
shuffled_percent_non_cooperonic_coexpressed_acc_genes = (
shuffled_acc_df['num_non_cooperonic_coexpressed_genes']/shuffled_acc_df['num_coexpressed_genes'])
# There are NaNs in cases where there are 0 co-expressed genes and therefore 0 non-cooperonic genes
shuffled_num_core_na = shuffled_percent_non_cooperonic_coexpressed_core_genes.isna().sum()
shuffled_num_acc_na = shuffled_percent_non_cooperonic_coexpressed_acc_genes.isna().sum()
# Since we are concerned with "of those co-expressed genes how many are in NOT in the same operon", we will remove these
shuffled_percent_non_cooperonic_coexpressed_core_genes_noNa = shuffled_percent_non_cooperonic_coexpressed_core_genes.dropna(
inplace=False)
shuffled_percent_non_cooperonic_coexpressed_acc_genes_noNa = shuffled_percent_non_cooperonic_coexpressed_acc_genes.dropna(
inplace=False)
# In[19]:
# Get bins using all data
hist, bins_num_percent_non_cooperonic_shuffled = np.histogram(
np.concatenate([shuffled_percent_non_cooperonic_coexpressed_core_genes_noNa,
shuffled_percent_non_cooperonic_coexpressed_acc_genes_noNa]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of percent of co-expressed genes that are NOT co-operonic in shuffled data
sns.distplot(shuffled_percent_non_cooperonic_coexpressed_core_genes_noNa,
label='core',
color='red',
kde=False,
bins=bins_num_percent_non_cooperonic_shuffled,
ax=axes[0])
sns.distplot(shuffled_percent_non_cooperonic_coexpressed_acc_genes_noNa,
label='accessory',
color='blue',
kde=False,
bins=bins_num_percent_non_cooperonic_shuffled,
ax=axes[1])
plt.suptitle('Percent of co-expressed genes that are NOT co-operonic (shuffled data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes', ha='center')
axes[0].set_ylabel('Count')
# In[20]:
# Print statistics about non co-operonic co-expressed genes
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes'.
format(real_num_core_na, round((real_num_core_na/num_core_genes)*100,2)))
print('''- Of those remaining genes, for a given CORE gene,
{}% (median) of the co-expressed genes are NOT in a shared operon'''.
format(round(np.median(real_percent_non_cooperonic_coexpressed_core_genes_noNa)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes'.
format(real_num_acc_na, round(real_num_acc_na/num_acc_genes)*100,2))
print('''- Of those remaining genes, for a given ACCESSORY gene,
{}% (median) of the co-expressed genes are NOT in a shared operon \n'''.
format(round(np.median(real_percent_non_cooperonic_coexpressed_acc_genes_noNa)*100,2)))
# For shuffled data
print('Using a threshold of {} to define co-expression (shuffled data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes'.
format(shuffled_num_core_na, round((shuffled_num_core_na/num_core_genes)*100,2)))
print('''- Of those remaining genes, for a given CORE gene,
{}% (median) of the co-expressed genes are NOT in a shared operon'''.
format(round(np.median(shuffled_percent_non_cooperonic_coexpressed_core_genes_noNa)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes'.
format(shuffled_num_acc_na, round((shuffled_num_acc_na/num_acc_genes)*100,2)))
print('''- Of those remaining genes, for a given ACCESSORY gene,
{}% (median) of the co-expressed genes are NOT in a shared operon'''.
format(round(np.median(shuffled_percent_non_cooperonic_coexpressed_acc_genes_noNa)*100,2)))
# **Observations:**
# * For majority of core genes, their co-expressed genes are not in the same operon. For example if core gene A is co-expressed with genes {X,Y,Z} and A is in operon {A,B,C} there are no intersecting genes.
# * This is the case for most core and accessory genes. There are few co-expression gene sets that overlap with known operons.
# * I would've expected more co-expressed genes to overlap with operons but need to read more about *P. aeruginosa* gene-gene interactions to get more of an intuition.
# * Good to see that as you decrease the threshold there are more non co-operonic gene co-expressed gene sets.
# * (control) There are 0 non-cooperonic co-expressed genes since there are 0 co-expressed genes
# ### Core gene relationships
# For a given core gene, there exists a set of genes that are co-expressed with it. What percent of those co-expressed genes are core?
# Similarly, for a given accessory gene, there exists a set of genes that are co-expressed with it. What percent of those co-expressed genes are core?
# In[21]:
# We only want to consider those genes with some co-expressed genes
real_core_nan_ids = list(
real_percent_non_cooperonic_coexpressed_core_genes[real_percent_non_cooperonic_coexpressed_core_genes.isna()].index)
real_acc_nan_ids = list(
real_percent_non_cooperonic_coexpressed_acc_genes[real_percent_non_cooperonic_coexpressed_acc_genes.isna()].index)
# We also only want to consider only those with some non-cooperonic genes
real_core_zero_ids = list(real_core_df[real_core_df['num_non_cooperonic_coexpressed_genes'] == 0].index)
real_acc_zero_ids = list(real_acc_df[real_acc_df['num_non_cooperonic_coexpressed_genes'] == 0].index)
# Get the union of excluded gene ids
real_exclude_core_ids = set(real_core_zero_ids).union(real_core_nan_ids)
real_exclude_acc_ids = set(real_acc_zero_ids).union(real_acc_nan_ids)
# Since we are concerned with "of those co-expressed gene NOT in the same operon", we will remove the above ids
real_percent_core_with_refcore = real_core_df['percent_non_cooperonic_coexpressed_core'].drop(labels=real_exclude_core_ids)
real_percent_core_with_refacc = real_acc_df['percent_non_cooperonic_coexpressed_core'].drop(labels=real_exclude_acc_ids)
# In[22]:
## Test: Distribution without removing 0 expressed and 0 non co-operonic genes
# Get bins using all data
hist, bins_core_real = np.histogram(np.concatenate([real_core_df['percent_non_cooperonic_coexpressed_core'].values,
real_acc_df['percent_non_cooperonic_coexpressed_core'].values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of core co-expressed genes in real data
sns.distplot(real_core_df['percent_non_cooperonic_coexpressed_core'].tolist(),
label='core',
color='red',
kde=False,
bins=bins_core_real,
ax=axes[0])
sns.distplot(real_acc_df['percent_non_cooperonic_coexpressed_core'].tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_core_real,
ax=axes[1])
plt.suptitle('TEST'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are core', ha='center')
axes[0].set_ylabel('Count')
# In[23]:
# Get bins using all data
hist, bins_core_real = np.histogram(np.concatenate([real_percent_core_with_refcore.values,
real_percent_core_with_refacc.values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of core co-expressed genes in real data
sns.distplot(real_percent_core_with_refcore.tolist(),
label='core',
color='red',
kde=False,
bins=bins_core_real,
ax=axes[0])
sns.distplot(real_percent_core_with_refacc.tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_core_real,
ax=axes[1])
plt.suptitle('Percent of co-expressed non-cooperonic genes that are core (real data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are core', ha='center')
axes[0].set_ylabel('Count')
# In[24]:
# We only want to consider those genes with some co-expressed genes
shuffled_core_nan_ids = list(
shuffled_percent_non_cooperonic_coexpressed_core_genes[
shuffled_percent_non_cooperonic_coexpressed_core_genes.isna()].index)
shuffled_acc_nan_ids = list(
shuffled_percent_non_cooperonic_coexpressed_acc_genes[
shuffled_percent_non_cooperonic_coexpressed_acc_genes.isna()].index)
# We also only want to consider only those with some non-cooperonic genes
shuffled_core_zero_ids = list(shuffled_core_df[shuffled_core_df['num_non_cooperonic_coexpressed_genes'] == 0].index)
shuffled_acc_zero_ids = list(shuffled_acc_df[shuffled_acc_df['num_non_cooperonic_coexpressed_genes'] == 0].index)
# Get the union of excluded gene ids
shuffled_exclude_core_ids = set(shuffled_core_zero_ids).union(shuffled_core_nan_ids)
shuffled_exclude_acc_ids = set(shuffled_acc_zero_ids).union(shuffled_acc_nan_ids)
# Since we are concerned with "of those co-expressed gene NOT in the same operon", we will remove the above ids
shuffled_percent_core_with_refcore = shuffled_core_df['percent_non_cooperonic_coexpressed_core'].drop(labels=shuffled_exclude_core_ids)
shuffled_percent_core_with_refacc = shuffled_acc_df['percent_non_cooperonic_coexpressed_core'].drop(labels=shuffled_exclude_acc_ids)
# In[25]:
# Get bins using all data
hist, bins_core_shuffled = np.histogram(
np.concatenate([shuffled_percent_core_with_refcore.values,
shuffled_percent_core_with_refacc.values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of core co-expressed genes in shuffled data
sns.distplot(shuffled_percent_core_with_refcore.tolist(),
label='core',
color='red',
kde=False,
bins=bins_core_shuffled,
ax=axes[0])
sns.distplot(shuffled_percent_core_with_refacc.tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_core_shuffled,
ax=axes[1])
plt.suptitle('Percent of co-expressed non-cooperonic genes that are core (shuffled data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are core', ha='center')
axes[0].set_ylabel('Count')
# In[26]:
# Print statistics about non co-operonic co-expressed core genes
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(real_exclude_core_ids), round((len(real_exclude_core_ids)/num_core_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given CORE gene,
{}% (median) of co-expressed non co-operonic genes are core genes'''.
format(round(np.median(real_percent_core_with_refcore)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(real_exclude_acc_ids), round((len(real_exclude_acc_ids)/num_acc_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given ACCESSORY gene,
{}% (median) of co-expressed non co-operonic genes are core genes'''.
format(round(np.median(real_percent_core_with_refacc)*100,2)))
# shuffled data
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(shuffled_exclude_core_ids), round((len(shuffled_exclude_core_ids)/num_core_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given CORE gene,
{}% (median) of co-expressed non co-operonic genes are core genes'''.
format(round(np.median(shuffled_percent_core_with_refcore)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(shuffled_exclude_acc_ids), round((len(shuffled_exclude_acc_ids)/num_acc_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given ACCESSORY gene,
{}% (median) of co-expressed non co-operonic genes are core genes'''.
format(round(np.median(shuffled_percent_core_with_refacc)*100,2)))
# ### Accessory gene relationships
# For a given core gene, there exists a set of genes that are co-expressed with it. What percent of those co-expressed genes are accessory?
# Similarly, for a given accessory gene, there exists a set of genes that are co-expressed with it. What percent of those co-expressed genes are accessory?
# In[27]:
# Since we are concerned with "of those co-expressed gene NOT in the same operon", we will remove the above ids
real_percent_acc_with_refcore = real_core_df['percent_non_cooperonic_coexpressed_acc'].drop(labels=real_exclude_core_ids)
real_percent_acc_with_refacc = real_acc_df['percent_non_cooperonic_coexpressed_acc'].drop(labels=real_exclude_acc_ids)
# In[28]:
# Get bins using all data
hist, bins_acc_real = np.histogram(np.concatenate([real_percent_acc_with_refcore.values,
real_percent_acc_with_refacc.values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of accessory co-expressed genes in real data
sns.distplot(real_percent_acc_with_refcore.tolist(),
label='core',
color='red',
kde=False,
bins=bins_acc_real,
ax=axes[0])
sns.distplot(real_percent_acc_with_refacc.tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_acc_real,
ax=axes[1])
plt.suptitle('Percent of co-expressed non-cooperonic genes that are accessory (real data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are accessory', ha='center')
axes[0].set_ylabel('Count')
# In[29]:
# Since we are concerned with "of those co-expressed gene NOT in the same operon", we will remove the above ids
shuffled_percent_acc_with_refcore = shuffled_core_df['percent_non_cooperonic_coexpressed_acc'].drop(labels=shuffled_exclude_core_ids)
shuffled_percent_acc_with_refacc = shuffled_acc_df['percent_non_cooperonic_coexpressed_acc'].drop(labels=shuffled_exclude_acc_ids)
# In[30]:
# Get bins using all data
hist, bins_acc_shuffled = np.histogram(
np.concatenate([shuffled_percent_acc_with_refcore.values,
shuffled_percent_acc_with_refacc.values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of accessory co-expressed genes in shuffled data
sns.distplot(shuffled_percent_acc_with_refcore.tolist(),
label='core',
color='red',
kde=False,
bins=bins_acc_shuffled,
ax=axes[0])
sns.distplot(shuffled_percent_acc_with_refacc.tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_acc_shuffled,
ax=axes[1])
plt.suptitle('Percent of co-expressed non-cooperonic genes that are accessory (shuffled data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are accessory', ha='center')
axes[0].set_ylabel('Count')
# In[31]:
# Print statistics about non co-operonic co-expressed accessory genes
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(real_exclude_core_ids), round((len(real_exclude_core_ids)/num_core_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given CORE gene,
{}% (median) of co-expressed non co-operonic genes are accessory genes'''.
format(round(np.median(real_percent_acc_with_refcore)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(real_exclude_acc_ids), round((len(real_exclude_acc_ids)/num_acc_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given ACCESSORY gene,
{}% (median) of co-expressed non co-operonic genes are accessory genes'''.
format(round(np.median(real_percent_acc_with_refacc)*100,2)))
# shuffled data
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(shuffled_exclude_core_ids), round((len(shuffled_exclude_core_ids)/num_core_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given CORE gene,
{}% (median) of co-expressed non co-operonic genes are accessory genes'''.
format(round(np.median(shuffled_percent_acc_with_refcore)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(shuffled_exclude_acc_ids), round((len(shuffled_exclude_acc_ids)/num_acc_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given ACCESSORY gene,
{}% (median) of co-expressed non co-operonic genes are accessory genes'''.
format(round(np.median(shuffled_percent_acc_with_refacc)*100,2)))
# **Observation:**
# * Core genes tend to be co-expressed with **only** other core genes
# * Many accessory genes tend to be co-expressed with **only** other core genes,
# * Some accessory genes are co-expressed with mix of accessory genes, core genes
# * (control) There are no relationships between core-core, core-accessory, accessory-accessory
# # Manually examine co-expressed and co-operonic genes
# In[32]:
# Get genes where the number of co-expressed genes > 0 AND number of non-operonic genes is 0
# Meaning that all the co-expressed genes are in the same operon
real_refcore_cooperonic = real_core_df[
(real_core_df['num_coexpressed_genes'] > 0) & (real_core_df['num_non_cooperonic_coexpressed_genes'] == 0)]
print(real_refcore_cooperonic.shape)
real_refcore_cooperonic.head(10)
# In[33]:
real_refacc_cooperonic = real_acc_df[
(real_acc_df['num_coexpressed_genes'] > 0) & (real_acc_df['num_non_cooperonic_coexpressed_genes'] == 0)]
print(real_refacc_cooperonic.shape)
real_refacc_cooperonic.head(10)
# In[34]:
# Manually select core reference gene and co-expressed gene set that is 100% co-operonic
# Read in correlation matrix
real_all_corr = pickle.load(open(real_all_corr_file, "rb"))
real_all_corr[real_all_corr.loc['PA1216']>coexpression_threshold]['PA1216']
# Manually selected PA1216. PA1216 is in operon containing PA1216 - PA1221 genes (http://3.209.27.103/feature/show/?id=105200&view=operons)
#
# In[35]:
# Get genes where the number of co-expressed genes > 0 AND number of non-operonic genes > 0
# Meaning that all the co-expressed genes are in the same operon
real_refcore_cooperonic = real_core_df[
(real_core_df['num_coexpressed_genes'] > 0) & (real_core_df['num_non_cooperonic_coexpressed_genes'] > 0)]
print(real_refcore_cooperonic.shape)
real_refcore_cooperonic.head(10)
# In[36]:
real_refacc_cooperonic = real_acc_df[
(real_acc_df['num_coexpressed_genes'] > 0) & (real_acc_df['num_non_cooperonic_coexpressed_genes'] > 0)]
print(real_refacc_cooperonic.shape)
real_refacc_cooperonic.head(10)
# In[37]:
# what does it say in literature, should they be in operon
# Manually select core reference gene and co-expressed gene set that is 100% non co-operonic
real_all_corr.loc['PA0001', real_all_corr.loc['PA0001']>coexpression_threshold]
# Manually selected PA0001. PA0001 is in operon containing PA0002-PA0004 genes (http://www.pseudomonas.com/feature/show/?id=134012&view=operons), which are **not** co-expressed with PA0001. Why is that? | archive/pilot_experiment/nbconverted/4_explore_coExpressed_genes.py |
# # Explore highly co-expressed genes
# In the previous [notebook](2_explore_corr_of_genes.ipynb) we observed that using 39 samples with 201 PAO1-specific genes, that the correlation of accessory-accessory genes is higher compared to the correlation of core-core and core-accessory genes.
#
# Based on this finding, we want to know: *What can explain this difference in correlation distribution?*
#
# This notebook performs a follow-up analysis. In particular this notebook performs a deeper examination of the correlation structure per group (core-core, core-accessory, accessory-accessory) by looking at the trends of the nearest neighbors (i.e. highly correlated genes) of each gene.
# In[74]:
import pandas as pd
import os
import pickle
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from functions import calculations
np.random.seed(123)
# In[75]:
# Input
base_dir = os.path.abspath(os.path.join(os.getcwd(),"../"))
base_intermediate_dir = os.path.join(
base_dir,
"pilot_experiment",
"data",
"tmp")
core_gene_ids_file = os.path.join(
base_intermediate_dir,
"core_gene_ids.pickle")
acc_gene_ids_file = os.path.join(
base_intermediate_dir,
"acc_gene_ids.pickle")
real_all_corr_file = os.path.join(
base_intermediate_dir,
"real_all_corr.pickle")
shuffled_all_corr_file = os.path.join(
base_intermediate_dir,
"shuffled_all_corr.pickle")
# Import Pseudomonas operon annotations from ADAGE repo
# Original source of data is from DOOR
# https://github.com/greenelab/adage/blob/master/Genome_organization/operon_3.txt
# Operons containing at least 3 genes
operon_file = "https://github.com/greenelab/adage/blob/master/Genome_organization/operon_3.txt"
# In[76]:
# Read in gene ids
core_gene_ids = pickle.load(open(core_gene_ids_file, "rb"))
acc_gene_ids = pickle.load(open(acc_gene_ids_file, "rb"))
# Get number of core and accessory genes
num_core_genes = len(core_gene_ids)
num_acc_genes = len(acc_gene_ids)
num_all_genes = num_core_genes + num_acc_genes
# # Extract statistics about co-expression from correlation matrix
# In[77]:
# Define threshold for highly co-expressed genes
coexpression_threshold = 0.9
# ### Co-expression statsitics using real data
# In[78]:
# Get co-expression patterns using real expression data
real_core_df, real_acc_df = calculations.get_coexpression_stats(real_all_corr_file,
operon_file,
core_gene_ids_file,
acc_gene_ids_file,
coexpression_threshold)
# In[79]:
real_core_df.head()
# In[80]:
real_acc_df.head()
# ### Co-expression statistics using shuffled data
# In[81]:
# Get co-expression patterns using shuffled expression data (control)
shuffled_core_df, shuffled_acc_df = calculations.get_coexpression_stats(shuffled_all_corr_file,
operon_file,
core_gene_ids_file,
acc_gene_ids_file,
coexpression_threshold)
shuffled_core_df.head()
# In[82]:
shuffled_acc_df.head()
# # Plot trends in co-expression data
# ## 1. Number of co-expressed genes
# In[83]:
sns.set()
# ### Number of co-expressed genes
# In[84]:
# Get bins using all data
hist, bins_num_coexpressed_real = np.histogram(np.concatenate([real_core_df['num_coexpressed_genes'].values,
real_acc_df['num_coexpressed_genes'].values]))
# Distribution of number of co-expressed genes in real data
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
sns.distplot(real_core_df['num_coexpressed_genes'].tolist(),
label='core',
color='red',
kde=False,
bins=bins_num_coexpressed_real,
ax=axes[0])
sns.distplot(real_acc_df['num_coexpressed_genes'].tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_num_coexpressed_real,
ax=axes[1])
plt.suptitle('Number of co-expressed genes (real data, threshold={})'.format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Number of co-expressed genes', ha='center')
axes[0].set_ylabel('Counts')
# ### Number of nonzero co-expressed genes
# In[85]:
## Remove genes with 0 co-expressed genes
# Get bins using all data
hist, bins_num_coexpressed_real_nonzero = np.histogram(np.concatenate(
[real_core_df[real_core_df['num_coexpressed_genes']>0]['num_coexpressed_genes'].values,
real_acc_df[real_acc_df['num_coexpressed_genes']>0]['num_coexpressed_genes'].values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of number of co-expressed genes in real data
sns.distplot(real_core_df[real_core_df['num_coexpressed_genes']>0]['num_coexpressed_genes'].tolist(),
label='core',
color='red',
kde=False,
bins=bins_num_coexpressed_real_nonzero,
ax=axes[0])
sns.distplot(real_acc_df[real_acc_df['num_coexpressed_genes']>0]['num_coexpressed_genes'].tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_num_coexpressed_real_nonzero,
ax=axes[1])
plt.suptitle('Number of nonzero co-expressed genes (real data, threshold={})'.format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Number of co-expressed genes', ha='center')
axes[0].set_ylabel('Counts')
# In[86]:
# Get bins using all data
hist, bins_num_coexpressed_shuffled = np.histogram(np.concatenate([shuffled_core_df['num_coexpressed_genes'].values,
shuffled_acc_df['num_coexpressed_genes'].values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of number of co-expressed genes in shuffled data
sns.distplot(shuffled_core_df['num_coexpressed_genes'].tolist(),
label='core',
color='red',
kde=False,
bins=bins_num_coexpressed_shuffled,
ax=axes[0])
sns.distplot(shuffled_acc_df['num_coexpressed_genes'].tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_num_coexpressed_shuffled,
ax=axes[1]
)
plt.suptitle('Number of co-expressed genes (shuffled data, threshold={})'.format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Number of co-expressed genes', ha='center')
axes[0].set_ylabel('Counts')
# In[87]:
# Print statistics about co-expressed genes
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- For a given CORE gene, there is a median of {} co-expressed genes'.
format(np.median(real_core_df['num_coexpressed_genes'])))
print('- For a given ACCESSORY gene, there is a median of {} co-expressed genes \n'.
format(np.median(real_acc_df['num_coexpressed_genes'])))
# For shuffled data
print('Using a threshold of {} to define co-expression (shuffled data): \n'.
format(coexpression_threshold))
print('- For a given CORE gene, there is a median of {} co-expressed genes'.
format(np.median(shuffled_core_df['num_coexpressed_genes'])))
print('- For a given ACCESSORY gene, there is a median of {} co-expressed genes'.
format(np.median(shuffled_acc_df['num_coexpressed_genes'])))
# **Overall:**
# * Many core and accessory genes are not co-expressed with other genes or very few genes, as expected
# * As increase threshold (more stringent), there are fewer co-expressed genes, as expected
# * (control, not shown) All genes (threshold=0.75,0.9) are connected to just 1 gene, as expected, since we have destroyed relationships between genes when we shuffled
# * Both core and accessory genes are have the same degree of connectivity
#
# **Observation using All experiments:**
# * At a threshold of 0.5, core genes have a median of 716 genes they are connect to and accessory genes have a median of 601 genes they are connected to
# * At a threshold of 0.75 core genes have a median of 53 genes they are connect to and accessory genes have a median of 74 genes they are connected to
# * At a threshold of 0.9, core and accessory genes have a median of 1 gene that they are connected to
#
# **Observation using only PAO1 experiments:**
# * At a threshold of 0.5, core genes have a median of 1331 genes they are connect to and accessory genes have a median of 1341 genes they are connected to. So there are more connections using only PAO1 genes, which we would expect since the accessory genes are PAO1-specific.
# * At a threshold of 0.75 core genes have a median of 554 genes they are connect to and accessory genes have a median of 576 genes they are connected to
# * At a threshold of 0.9, core genes have a median of 21 gene that they are connected to and accessory genes have a median of 57 genes they are connected to
#
# **Observation using only PA14 experiments:**
# * At a threshold of 0.5, core genes have a median of 1133 genes they are connect to and accessory genes have a median of 1065 genes they are connected to. So there are more connections using only PAO1 genes, which we would expect since the accessory genes are PAO1-specific.
# * At a threshold of 0.75 core genes have a median of 153 genes they are connect to and accessory genes have a median of 132 genes they are connected to
# * At a threshold of 0.9, core genes have a median of 2 gene that they are connected to and accessory genes have a median of 3 genes they are connected to
# ### Compare co-expressed vs not co-expressed genes
# What is the difference between genes that are co-expressed vs those that are not?
# In[15]:
# Get genes that are co-expressed with other genes
coexpressed_core_genes = list(real_core_df[real_core_df['num_coexpressed_genes']>0].index)
coexpressed_acc_genes = list(real_acc_df[real_acc_df['num_coexpressed_genes']>0].index)
# In[16]:
len(coexpressed_core_genes)
# In[17]:
len(coexpressed_acc_genes)
# At a strict threshold of 0.9, all genes are co-expressed with **at least** one other gene. So there are no independent genes.
# ## 2. Percent of co-expressed genes that are NOT in the same operon
# In[15]:
# Calculate the percent of co-expressed genes that are non co-operonic (real data)
real_percent_non_cooperonic_coexpressed_core_genes = (
real_core_df['num_non_cooperonic_coexpressed_genes']/real_core_df['num_coexpressed_genes'])
real_percent_non_cooperonic_coexpressed_acc_genes = (
real_acc_df['num_non_cooperonic_coexpressed_genes']/real_acc_df['num_coexpressed_genes'])
# There are NaNs in cases where there are 0 co-expressed genes and therefore 0 non-cooperonic genes
real_num_core_na = real_percent_non_cooperonic_coexpressed_core_genes.isna().sum()
real_num_acc_na = real_percent_non_cooperonic_coexpressed_acc_genes.isna().sum()
# Since we are concerned with "of those co-expressed genes how many are in NOT in the same operon", we will remove these
real_percent_non_cooperonic_coexpressed_core_genes_noNa = real_percent_non_cooperonic_coexpressed_core_genes.dropna(inplace=False)
real_percent_non_cooperonic_coexpressed_acc_genes_noNa = real_percent_non_cooperonic_coexpressed_acc_genes.dropna(inplace=False)
# In[16]:
## TEST: What does distribution look like before removing NaNs?
# Get bins using all data
hist, bins_num_percent_non_cooperonic_real = np.histogram(
np.concatenate(
[real_percent_non_cooperonic_coexpressed_core_genes.fillna(0),
real_percent_non_cooperonic_coexpressed_acc_genes.fillna(0)]
)
)
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of percent of co-expressed genes that are NOT co-operonic in real data
sns.distplot(real_percent_non_cooperonic_coexpressed_core_genes.fillna(0),
label='core',
color='red',
kde=False,
bins=bins_num_percent_non_cooperonic_real,
ax=axes[0])
sns.distplot(real_percent_non_cooperonic_coexpressed_acc_genes.fillna(0),
label='accessory',
color='blue',
kde=False,
bins=bins_num_percent_non_cooperonic_real,
ax=axes[1])
plt.suptitle('TEST'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes', ha='center')
axes[0].set_ylabel('Count')
# In[17]:
# Get bins using all data
hist, bins_num_percent_non_cooperonic_real = np.histogram(
np.concatenate(
[real_percent_non_cooperonic_coexpressed_core_genes_noNa,
real_percent_non_cooperonic_coexpressed_acc_genes_noNa]
)
)
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of percent of co-expressed genes that are NOT co-operonic in real data
sns.distplot(real_percent_non_cooperonic_coexpressed_core_genes_noNa,
label='core',
color='red',
kde=False,
bins=bins_num_percent_non_cooperonic_real,
ax=axes[0])
sns.distplot(real_percent_non_cooperonic_coexpressed_acc_genes_noNa,
label='accessory',
color='blue',
kde=False,
bins=bins_num_percent_non_cooperonic_real,
ax=axes[1]
)
plt.suptitle('Percent of co-expressed genes that are NOT co-operonic (real data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes', ha='center')
axes[0].set_ylabel('Count')
# In[18]:
# Calculate the percent of co-expressed genes that are non co-operonic (shuffled data)
shuffled_percent_non_cooperonic_coexpressed_core_genes = (
shuffled_core_df['num_non_cooperonic_coexpressed_genes']/shuffled_core_df['num_coexpressed_genes'])
shuffled_percent_non_cooperonic_coexpressed_acc_genes = (
shuffled_acc_df['num_non_cooperonic_coexpressed_genes']/shuffled_acc_df['num_coexpressed_genes'])
# There are NaNs in cases where there are 0 co-expressed genes and therefore 0 non-cooperonic genes
shuffled_num_core_na = shuffled_percent_non_cooperonic_coexpressed_core_genes.isna().sum()
shuffled_num_acc_na = shuffled_percent_non_cooperonic_coexpressed_acc_genes.isna().sum()
# Since we are concerned with "of those co-expressed genes how many are in NOT in the same operon", we will remove these
shuffled_percent_non_cooperonic_coexpressed_core_genes_noNa = shuffled_percent_non_cooperonic_coexpressed_core_genes.dropna(
inplace=False)
shuffled_percent_non_cooperonic_coexpressed_acc_genes_noNa = shuffled_percent_non_cooperonic_coexpressed_acc_genes.dropna(
inplace=False)
# In[19]:
# Get bins using all data
hist, bins_num_percent_non_cooperonic_shuffled = np.histogram(
np.concatenate([shuffled_percent_non_cooperonic_coexpressed_core_genes_noNa,
shuffled_percent_non_cooperonic_coexpressed_acc_genes_noNa]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution of percent of co-expressed genes that are NOT co-operonic in shuffled data
sns.distplot(shuffled_percent_non_cooperonic_coexpressed_core_genes_noNa,
label='core',
color='red',
kde=False,
bins=bins_num_percent_non_cooperonic_shuffled,
ax=axes[0])
sns.distplot(shuffled_percent_non_cooperonic_coexpressed_acc_genes_noNa,
label='accessory',
color='blue',
kde=False,
bins=bins_num_percent_non_cooperonic_shuffled,
ax=axes[1])
plt.suptitle('Percent of co-expressed genes that are NOT co-operonic (shuffled data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes', ha='center')
axes[0].set_ylabel('Count')
# In[20]:
# Print statistics about non co-operonic co-expressed genes
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes'.
format(real_num_core_na, round((real_num_core_na/num_core_genes)*100,2)))
print('''- Of those remaining genes, for a given CORE gene,
{}% (median) of the co-expressed genes are NOT in a shared operon'''.
format(round(np.median(real_percent_non_cooperonic_coexpressed_core_genes_noNa)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes'.
format(real_num_acc_na, round(real_num_acc_na/num_acc_genes)*100,2))
print('''- Of those remaining genes, for a given ACCESSORY gene,
{}% (median) of the co-expressed genes are NOT in a shared operon \n'''.
format(round(np.median(real_percent_non_cooperonic_coexpressed_acc_genes_noNa)*100,2)))
# For shuffled data
print('Using a threshold of {} to define co-expression (shuffled data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes'.
format(shuffled_num_core_na, round((shuffled_num_core_na/num_core_genes)*100,2)))
print('''- Of those remaining genes, for a given CORE gene,
{}% (median) of the co-expressed genes are NOT in a shared operon'''.
format(round(np.median(shuffled_percent_non_cooperonic_coexpressed_core_genes_noNa)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes'.
format(shuffled_num_acc_na, round((shuffled_num_acc_na/num_acc_genes)*100,2)))
print('''- Of those remaining genes, for a given ACCESSORY gene,
{}% (median) of the co-expressed genes are NOT in a shared operon'''.
format(round(np.median(shuffled_percent_non_cooperonic_coexpressed_acc_genes_noNa)*100,2)))
# **Observations:**
# * For majority of core genes, their co-expressed genes are not in the same operon. For example if core gene A is co-expressed with genes {X,Y,Z} and A is in operon {A,B,C} there are no intersecting genes.
# * This is the case for most core and accessory genes. There are few co-expression gene sets that overlap with known operons.
# * I would've expected more co-expressed genes to overlap with operons but need to read more about *P. aeruginosa* gene-gene interactions to get more of an intuition.
# * Good to see that as you decrease the threshold there are more non co-operonic gene co-expressed gene sets.
# * (control) There are 0 non-cooperonic co-expressed genes since there are 0 co-expressed genes
# ### Core gene relationships
# For a given core gene, there exists a set of genes that are co-expressed with it. What percent of those co-expressed genes are core?
# Similarly, for a given accessory gene, there exists a set of genes that are co-expressed with it. What percent of those co-expressed genes are core?
# In[21]:
# We only want to consider those genes with some co-expressed genes
real_core_nan_ids = list(
real_percent_non_cooperonic_coexpressed_core_genes[real_percent_non_cooperonic_coexpressed_core_genes.isna()].index)
real_acc_nan_ids = list(
real_percent_non_cooperonic_coexpressed_acc_genes[real_percent_non_cooperonic_coexpressed_acc_genes.isna()].index)
# We also only want to consider only those with some non-cooperonic genes
real_core_zero_ids = list(real_core_df[real_core_df['num_non_cooperonic_coexpressed_genes'] == 0].index)
real_acc_zero_ids = list(real_acc_df[real_acc_df['num_non_cooperonic_coexpressed_genes'] == 0].index)
# Get the union of excluded gene ids
real_exclude_core_ids = set(real_core_zero_ids).union(real_core_nan_ids)
real_exclude_acc_ids = set(real_acc_zero_ids).union(real_acc_nan_ids)
# Since we are concerned with "of those co-expressed gene NOT in the same operon", we will remove the above ids
real_percent_core_with_refcore = real_core_df['percent_non_cooperonic_coexpressed_core'].drop(labels=real_exclude_core_ids)
real_percent_core_with_refacc = real_acc_df['percent_non_cooperonic_coexpressed_core'].drop(labels=real_exclude_acc_ids)
# In[22]:
## Test: Distribution without removing 0 expressed and 0 non co-operonic genes
# Get bins using all data
hist, bins_core_real = np.histogram(np.concatenate([real_core_df['percent_non_cooperonic_coexpressed_core'].values,
real_acc_df['percent_non_cooperonic_coexpressed_core'].values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of core co-expressed genes in real data
sns.distplot(real_core_df['percent_non_cooperonic_coexpressed_core'].tolist(),
label='core',
color='red',
kde=False,
bins=bins_core_real,
ax=axes[0])
sns.distplot(real_acc_df['percent_non_cooperonic_coexpressed_core'].tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_core_real,
ax=axes[1])
plt.suptitle('TEST'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are core', ha='center')
axes[0].set_ylabel('Count')
# In[23]:
# Get bins using all data
hist, bins_core_real = np.histogram(np.concatenate([real_percent_core_with_refcore.values,
real_percent_core_with_refacc.values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of core co-expressed genes in real data
sns.distplot(real_percent_core_with_refcore.tolist(),
label='core',
color='red',
kde=False,
bins=bins_core_real,
ax=axes[0])
sns.distplot(real_percent_core_with_refacc.tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_core_real,
ax=axes[1])
plt.suptitle('Percent of co-expressed non-cooperonic genes that are core (real data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are core', ha='center')
axes[0].set_ylabel('Count')
# In[24]:
# We only want to consider those genes with some co-expressed genes
shuffled_core_nan_ids = list(
shuffled_percent_non_cooperonic_coexpressed_core_genes[
shuffled_percent_non_cooperonic_coexpressed_core_genes.isna()].index)
shuffled_acc_nan_ids = list(
shuffled_percent_non_cooperonic_coexpressed_acc_genes[
shuffled_percent_non_cooperonic_coexpressed_acc_genes.isna()].index)
# We also only want to consider only those with some non-cooperonic genes
shuffled_core_zero_ids = list(shuffled_core_df[shuffled_core_df['num_non_cooperonic_coexpressed_genes'] == 0].index)
shuffled_acc_zero_ids = list(shuffled_acc_df[shuffled_acc_df['num_non_cooperonic_coexpressed_genes'] == 0].index)
# Get the union of excluded gene ids
shuffled_exclude_core_ids = set(shuffled_core_zero_ids).union(shuffled_core_nan_ids)
shuffled_exclude_acc_ids = set(shuffled_acc_zero_ids).union(shuffled_acc_nan_ids)
# Since we are concerned with "of those co-expressed gene NOT in the same operon", we will remove the above ids
shuffled_percent_core_with_refcore = shuffled_core_df['percent_non_cooperonic_coexpressed_core'].drop(labels=shuffled_exclude_core_ids)
shuffled_percent_core_with_refacc = shuffled_acc_df['percent_non_cooperonic_coexpressed_core'].drop(labels=shuffled_exclude_acc_ids)
# In[25]:
# Get bins using all data
hist, bins_core_shuffled = np.histogram(
np.concatenate([shuffled_percent_core_with_refcore.values,
shuffled_percent_core_with_refacc.values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of core co-expressed genes in shuffled data
sns.distplot(shuffled_percent_core_with_refcore.tolist(),
label='core',
color='red',
kde=False,
bins=bins_core_shuffled,
ax=axes[0])
sns.distplot(shuffled_percent_core_with_refacc.tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_core_shuffled,
ax=axes[1])
plt.suptitle('Percent of co-expressed non-cooperonic genes that are core (shuffled data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are core', ha='center')
axes[0].set_ylabel('Count')
# In[26]:
# Print statistics about non co-operonic co-expressed core genes
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(real_exclude_core_ids), round((len(real_exclude_core_ids)/num_core_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given CORE gene,
{}% (median) of co-expressed non co-operonic genes are core genes'''.
format(round(np.median(real_percent_core_with_refcore)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(real_exclude_acc_ids), round((len(real_exclude_acc_ids)/num_acc_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given ACCESSORY gene,
{}% (median) of co-expressed non co-operonic genes are core genes'''.
format(round(np.median(real_percent_core_with_refacc)*100,2)))
# shuffled data
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(shuffled_exclude_core_ids), round((len(shuffled_exclude_core_ids)/num_core_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given CORE gene,
{}% (median) of co-expressed non co-operonic genes are core genes'''.
format(round(np.median(shuffled_percent_core_with_refcore)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(shuffled_exclude_acc_ids), round((len(shuffled_exclude_acc_ids)/num_acc_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given ACCESSORY gene,
{}% (median) of co-expressed non co-operonic genes are core genes'''.
format(round(np.median(shuffled_percent_core_with_refacc)*100,2)))
# ### Accessory gene relationships
# For a given core gene, there exists a set of genes that are co-expressed with it. What percent of those co-expressed genes are accessory?
# Similarly, for a given accessory gene, there exists a set of genes that are co-expressed with it. What percent of those co-expressed genes are accessory?
# In[27]:
# Since we are concerned with "of those co-expressed gene NOT in the same operon", we will remove the above ids
real_percent_acc_with_refcore = real_core_df['percent_non_cooperonic_coexpressed_acc'].drop(labels=real_exclude_core_ids)
real_percent_acc_with_refacc = real_acc_df['percent_non_cooperonic_coexpressed_acc'].drop(labels=real_exclude_acc_ids)
# In[28]:
# Get bins using all data
hist, bins_acc_real = np.histogram(np.concatenate([real_percent_acc_with_refcore.values,
real_percent_acc_with_refacc.values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of accessory co-expressed genes in real data
sns.distplot(real_percent_acc_with_refcore.tolist(),
label='core',
color='red',
kde=False,
bins=bins_acc_real,
ax=axes[0])
sns.distplot(real_percent_acc_with_refacc.tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_acc_real,
ax=axes[1])
plt.suptitle('Percent of co-expressed non-cooperonic genes that are accessory (real data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are accessory', ha='center')
axes[0].set_ylabel('Count')
# In[29]:
# Since we are concerned with "of those co-expressed gene NOT in the same operon", we will remove the above ids
shuffled_percent_acc_with_refcore = shuffled_core_df['percent_non_cooperonic_coexpressed_acc'].drop(labels=shuffled_exclude_core_ids)
shuffled_percent_acc_with_refacc = shuffled_acc_df['percent_non_cooperonic_coexpressed_acc'].drop(labels=shuffled_exclude_acc_ids)
# In[30]:
# Get bins using all data
hist, bins_acc_shuffled = np.histogram(
np.concatenate([shuffled_percent_acc_with_refcore.values,
shuffled_percent_acc_with_refacc.values]))
# Set up the matplotlib figure
fig, axes = plt.subplots(ncols=2, nrows=1)
# Distribution plot for percent of accessory co-expressed genes in shuffled data
sns.distplot(shuffled_percent_acc_with_refcore.tolist(),
label='core',
color='red',
kde=False,
bins=bins_acc_shuffled,
ax=axes[0])
sns.distplot(shuffled_percent_acc_with_refacc.tolist(),
label='accessory',
color='blue',
kde=False,
bins=bins_acc_shuffled,
ax=axes[1])
plt.suptitle('Percent of co-expressed non-cooperonic genes that are accessory (shuffled data, threshold={})'.
format(coexpression_threshold))
axes[0].legend(prop={'size': 12})
axes[1].legend(prop={'size': 12})
fig.text(0.5, 0.01, 'Percent of co-expressed non-cooperonic genes that are accessory', ha='center')
axes[0].set_ylabel('Count')
# In[31]:
# Print statistics about non co-operonic co-expressed accessory genes
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(real_exclude_core_ids), round((len(real_exclude_core_ids)/num_core_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given CORE gene,
{}% (median) of co-expressed non co-operonic genes are accessory genes'''.
format(round(np.median(real_percent_acc_with_refcore)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(real_exclude_acc_ids), round((len(real_exclude_acc_ids)/num_acc_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given ACCESSORY gene,
{}% (median) of co-expressed non co-operonic genes are accessory genes'''.
format(round(np.median(real_percent_acc_with_refacc)*100,2)))
# shuffled data
print('Using a threshold of {} to define co-expression (real data): \n'.
format(coexpression_threshold))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(shuffled_exclude_core_ids), round((len(shuffled_exclude_core_ids)/num_core_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given CORE gene,
{}% (median) of co-expressed non co-operonic genes are accessory genes'''.
format(round(np.median(shuffled_percent_acc_with_refcore)*100,2)))
print('- We removed {} ({}%) genes that had 0 co-expressed genes or 0 non-cooperonic genes'.
format(len(shuffled_exclude_acc_ids), round((len(shuffled_exclude_acc_ids)/num_acc_genes)*100,2)))
print('''- Of the non-coperonic co-expressed genes, for a given ACCESSORY gene,
{}% (median) of co-expressed non co-operonic genes are accessory genes'''.
format(round(np.median(shuffled_percent_acc_with_refacc)*100,2)))
# **Observation:**
# * Core genes tend to be co-expressed with **only** other core genes
# * Many accessory genes tend to be co-expressed with **only** other core genes,
# * Some accessory genes are co-expressed with mix of accessory genes, core genes
# * (control) There are no relationships between core-core, core-accessory, accessory-accessory
# # Manually examine co-expressed and co-operonic genes
# In[32]:
# Get genes where the number of co-expressed genes > 0 AND number of non-operonic genes is 0
# Meaning that all the co-expressed genes are in the same operon
real_refcore_cooperonic = real_core_df[
(real_core_df['num_coexpressed_genes'] > 0) & (real_core_df['num_non_cooperonic_coexpressed_genes'] == 0)]
print(real_refcore_cooperonic.shape)
real_refcore_cooperonic.head(10)
# In[33]:
real_refacc_cooperonic = real_acc_df[
(real_acc_df['num_coexpressed_genes'] > 0) & (real_acc_df['num_non_cooperonic_coexpressed_genes'] == 0)]
print(real_refacc_cooperonic.shape)
real_refacc_cooperonic.head(10)
# In[34]:
# Manually select core reference gene and co-expressed gene set that is 100% co-operonic
# Read in correlation matrix
real_all_corr = pickle.load(open(real_all_corr_file, "rb"))
real_all_corr[real_all_corr.loc['PA1216']>coexpression_threshold]['PA1216']
# Manually selected PA1216. PA1216 is in operon containing PA1216 - PA1221 genes (http://3.209.27.103/feature/show/?id=105200&view=operons)
#
# In[35]:
# Get genes where the number of co-expressed genes > 0 AND number of non-operonic genes > 0
# Meaning that all the co-expressed genes are in the same operon
real_refcore_cooperonic = real_core_df[
(real_core_df['num_coexpressed_genes'] > 0) & (real_core_df['num_non_cooperonic_coexpressed_genes'] > 0)]
print(real_refcore_cooperonic.shape)
real_refcore_cooperonic.head(10)
# In[36]:
real_refacc_cooperonic = real_acc_df[
(real_acc_df['num_coexpressed_genes'] > 0) & (real_acc_df['num_non_cooperonic_coexpressed_genes'] > 0)]
print(real_refacc_cooperonic.shape)
real_refacc_cooperonic.head(10)
# In[37]:
# what does it say in literature, should they be in operon
# Manually select core reference gene and co-expressed gene set that is 100% non co-operonic
real_all_corr.loc['PA0001', real_all_corr.loc['PA0001']>coexpression_threshold]
# Manually selected PA0001. PA0001 is in operon containing PA0002-PA0004 genes (http://www.pseudomonas.com/feature/show/?id=134012&view=operons), which are **not** co-expressed with PA0001. Why is that? | 0.79166 | 0.69246 |
import os
from os import listdir
from os.path import isfile, join
import numpy as np
import skimage
import skimage.io as io
from PIL import Image
import matplotlib.pyplot as plt
lfsize = [372, 540, 8, 8]
def normalize_lf(lf):
return 2.0*(lf-0.5)
def denormalize_lf(lf):
return lf/2.0+0.5
def read_eslf(filename):
lf = io.imread(filename)
lf = skimage.exposure.adjust_gamma(lf, 0.4)
lf = np.array(lf)
lf = lf[:372*14, :540*14, :3]/255.0
lf = np.reshape(lf, (372, 14, 540, 14, 3))
lf = np.transpose(lf, (0, 2, 1, 3, 4))
lf = lf[:, :, (14//2)-(lfsize[2]//2):(14//2)+(lfsize[2]//2), (14//2)-(lfsize[3]//2):(14//2)+(lfsize[3]//2), :]
return lf
def display_lf(lf, lfsize):
box = 10
box_w = lfsize[2]*10
img = None
for i in range(lfsize[2]):
for j in range(lfsize[3]):
j2 = j if i%2 == 0 else lfsize[2]-1-j
frame = lf[:,:,i,j2,:]
frame = np.clip(frame, 0, 1)
x = i*box
y = j2*box
frame[0:10, 0:10] = 1
frame[0:10, box_w-10:box_w] = 1
frame[box_w-10:box_w, 0:10] = 1
frame[box_w-10:box_w, box_w-10:box_w] = 1
frame[x:x+box, y:y+box] = 0.5
if img is None:
img = plt.imshow(frame)
else:
img.set_data(frame)
plt.pause(0.01)
plt.draw()
def display_lf_folder(path):
files = [os.path.join(path, f) for f in listdir(path) if isfile(join(path, f))]
files = files[600:]
for f in files:
print(f)
lf = read_eslf(f)
display_lf(lf, lfsize)
def display_aif_lf_folder(path):
files = [os.path.join(path, f) for f in listdir(path) if isfile(join(path, f))]
files = files[200:]
img = None
for f in files:
lf = read_eslf(f)
aif = lf[:, :, lfsize[2]//2, lfsize[3]//2, :]
if img is None:
img = plt.imshow(aif)
else:
img.set_data(aif)
plt.pause(0.01)
plt.draw()
def display_4corner(lf):
corners = (lf[:, :, 0, 0, :], lf[:, :, 0, 7, :], lf[:, :, 7, 0, :] ,lf[:, :, 7, 7, :])
img = None
for i in range(4):
if img is None:
img = plt.imshow(corners[i])
plt.draw()
plt.pause(0.3)
else:
img.set_data(corners[i])
plt.draw()
plt.pause(0.3)
def display_4corner_folder(path):
files = [os.path.join(path, f) for f in listdir(path) if isfile(join(path, f))]
for f in files:
lf = read_eslf(f)
display_4corner(lf) | lfutil.py | import os
from os import listdir
from os.path import isfile, join
import numpy as np
import skimage
import skimage.io as io
from PIL import Image
import matplotlib.pyplot as plt
lfsize = [372, 540, 8, 8]
def normalize_lf(lf):
return 2.0*(lf-0.5)
def denormalize_lf(lf):
return lf/2.0+0.5
def read_eslf(filename):
lf = io.imread(filename)
lf = skimage.exposure.adjust_gamma(lf, 0.4)
lf = np.array(lf)
lf = lf[:372*14, :540*14, :3]/255.0
lf = np.reshape(lf, (372, 14, 540, 14, 3))
lf = np.transpose(lf, (0, 2, 1, 3, 4))
lf = lf[:, :, (14//2)-(lfsize[2]//2):(14//2)+(lfsize[2]//2), (14//2)-(lfsize[3]//2):(14//2)+(lfsize[3]//2), :]
return lf
def display_lf(lf, lfsize):
box = 10
box_w = lfsize[2]*10
img = None
for i in range(lfsize[2]):
for j in range(lfsize[3]):
j2 = j if i%2 == 0 else lfsize[2]-1-j
frame = lf[:,:,i,j2,:]
frame = np.clip(frame, 0, 1)
x = i*box
y = j2*box
frame[0:10, 0:10] = 1
frame[0:10, box_w-10:box_w] = 1
frame[box_w-10:box_w, 0:10] = 1
frame[box_w-10:box_w, box_w-10:box_w] = 1
frame[x:x+box, y:y+box] = 0.5
if img is None:
img = plt.imshow(frame)
else:
img.set_data(frame)
plt.pause(0.01)
plt.draw()
def display_lf_folder(path):
files = [os.path.join(path, f) for f in listdir(path) if isfile(join(path, f))]
files = files[600:]
for f in files:
print(f)
lf = read_eslf(f)
display_lf(lf, lfsize)
def display_aif_lf_folder(path):
files = [os.path.join(path, f) for f in listdir(path) if isfile(join(path, f))]
files = files[200:]
img = None
for f in files:
lf = read_eslf(f)
aif = lf[:, :, lfsize[2]//2, lfsize[3]//2, :]
if img is None:
img = plt.imshow(aif)
else:
img.set_data(aif)
plt.pause(0.01)
plt.draw()
def display_4corner(lf):
corners = (lf[:, :, 0, 0, :], lf[:, :, 0, 7, :], lf[:, :, 7, 0, :] ,lf[:, :, 7, 7, :])
img = None
for i in range(4):
if img is None:
img = plt.imshow(corners[i])
plt.draw()
plt.pause(0.3)
else:
img.set_data(corners[i])
plt.draw()
plt.pause(0.3)
def display_4corner_folder(path):
files = [os.path.join(path, f) for f in listdir(path) if isfile(join(path, f))]
for f in files:
lf = read_eslf(f)
display_4corner(lf) | 0.197135 | 0.373219 |
import re
def le_assinatura():
'''
A função lê os valores dos traços linguísticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos.
Returns:
(list): Retorna uma lista com todos os dados digitados pelo usuário.
'''
print("Bem-vindo ao detector automático de COH-PIAH.")
print("Informe a assinatura típica de um aluno infectado: ")
tmp = float(input("Entre o tamanho médio da palavra: "))
rtt = float(input("Entre a relação Type-Token: "))
rhl = float(input("Entre a Razão Hapax Legomana: "))
tms = float(input("Entre o tamanho médio da sentença: "))
cms = float(input("Entre a complexidade média da sentença: "))
tmf = float(input("Entre o tamanho médio de frase: "))
return [tmp, rtt, rhl, tms, cms, tmf]
def le_textos():
'''
A função lê todos os textos a serem comparados e devolve uma lista contendo cada texto como um elemento.
Returns:
textos (list): Retorna uma lista onde cada elemento é um textos.
'''
i = 1
textos = list()
texto = input(f"Digite o texto {i} (aperte enter para sair): ")
while texto:
textos.append(texto)
i += 1
texto = input(f"Digite o texto {i} (aperte enter para sair): ")
return textos
def separa_sentencas(texto):
'''
A função recebe um texto e devolve uma lista das sentenças dentro do texto.
Parameters:
texto (str): Texto digitado pelo usuário.
Returns:
sentenças (list): Retorna uma lista onde cada elemento é uma sentença.
'''
sentenças = re.split(r'[.!?]+', texto)
if sentenças[-1] == '':
del sentenças[-1]
return sentenças
def separa_frases(sentença):
'''
A função recebe uma sentença e devolve uma lista das frases dentro da sentença.
Parameters:
sentença (str): Senteça do texto.
Returns:
(list): Retorna uma lista contendo cada frase da sentença.
'''
return re.split(r'[,:;]+', sentença)
def separa_palavras(frase):
'''
A função recebe uma frase e devolve uma lista das palavras dentro da frase.
Parameters:
frase (str): Frase da sentença.
Returns:
(list): Retorna uma lista contendo cada palavra da frase.
'''
palavras = list()
# Alguns textos podem vir sem espaços após o sinal de pontuação, para prevenir isso:
palavras = frase.replace(',', ' ').replace(';', ' ').replace(':', ' ').replace('.', ' ').replace('?', ' ').replace('!', ' ')
return palavras.split()
def n_palavras_unicas(lista_palavras):
'''
Essa função recebe uma lista de palavras e devolve o número de palavras que aparecem uma única vez.
Parameters:
lista_palavras (list): Lista contendo cada palavra de uma frase.
Returns:
únicas (int): Retorna o total de palavras únicas da frase.
'''
freq = dict()
únicas = 0
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
if freq[p] == 1:
únicas -= 1
freq[p] += 1
else:
freq[p] = 1
únicas += 1
return únicas
def n_palavras_diferentes(lista_palavras):
'''
Essa função recebe uma lista de palavras e devolve o número de palavras diferentes utilizadas.
Parameters:
lista_palavras (list): Lista contendo cada palavra de uma frase.
Returns:
(int): Retorna o total de palavras diferentes da frase.
'''
freq = dict()
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
freq[p] += 1
else:
freq[p] = 1
return len(freq)
def compara_assinatura(as_a, as_b):
'''
Essa função recebe duas assinaturas de texto e devolve o grau de similaridade nas assinaturas.
Parameters:
as_a (list): Assinatura do texto A.
as_b (list): Assinatura do texto B.
'''
similaridade = 0
for i in range(6):
similaridade += abs(as_a[i] - as_b[i])
return (similaridade / 6)
def calcula_assinatura(texto):
'''
Essa função recebe um texto e calcula a assinatura dele.
Parameters:
texto (str): Texto.
Returns:
as_t (list): Lista com a assinatura do texto.
'''
as_t = list()
# Tamanho médio de palavra.
palavras = list()
tamanho_palavras = 0
for p in separa_palavras(texto):
palavras.append(p)
tamanho_palavras += len(p)
tmp = tamanho_palavras / len(palavras)
# Relação Type-Token.
palavras_diferentes = n_palavras_diferentes(palavras)
rtt = palavras_diferentes / len(palavras)
# Razão Hapax Legomana.
palavras_únicas = n_palavras_unicas(palavras)
rhl = palavras_únicas / len(palavras)
# Tamanho médio de sentença.
sentenças = separa_sentencas(texto)
caracteres_sentença = 0
for caractere in sentenças:
caracteres_sentença += len(caractere)
tms = caracteres_sentença / len(sentenças)
# Complexidade de sentença.
total_frases = 0
for s in sentenças:
total_frases += len(separa_frases(s))
cms = total_frases / len(sentenças)
# Tamanho médio de frase.
total_caracteres = 0
for s in sentenças:
for frase in separa_frases(s):
total_caracteres += len(frase)
tmf = total_caracteres / total_frases
as_t.extend((tmp, rtt, rhl, tms, cms, tmf))
return as_t
def avalia_textos(textos, ass_cp):
'''
Essa função recebe uma lista de textos e a assinatura de um aluno portador de COH-PIAH e deve devolve o número do texto com a maior probabilidade de ter sido infectado.
Parameters:
textos (list): Lista contendo vários textos.
ass_cp (float): Assinatura do aluno infectado por COH-PIAH.
Returns:
texto_infectado (int): Número do texto infectado.
'''
assinaturas = list()
for t in textos:
assinaturas.append(calcula_assinatura(t))
i = 0
while i < len(assinaturas):
if i == 0:
ass_infectada = compara_assinatura(assinaturas[i], ass_cp)
texto_infectado = 1
else:
if compara_assinatura(assinaturas[i], ass_cp) < ass_infectada:
ass_infectada = compara_assinatura(assinaturas[i], ass_cp)
texto_infectado += 1
i += 1
return texto_infectado
def main():
ass_cp = le_assinatura()
textos = le_textos()
print(f'O autor do texto {avalia_textos(textos, ass_cp)} está infectado com COH-PIAH.') | Parte 1/Semana 9/CohPiah.py | import re
def le_assinatura():
'''
A função lê os valores dos traços linguísticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos.
Returns:
(list): Retorna uma lista com todos os dados digitados pelo usuário.
'''
print("Bem-vindo ao detector automático de COH-PIAH.")
print("Informe a assinatura típica de um aluno infectado: ")
tmp = float(input("Entre o tamanho médio da palavra: "))
rtt = float(input("Entre a relação Type-Token: "))
rhl = float(input("Entre a Razão Hapax Legomana: "))
tms = float(input("Entre o tamanho médio da sentença: "))
cms = float(input("Entre a complexidade média da sentença: "))
tmf = float(input("Entre o tamanho médio de frase: "))
return [tmp, rtt, rhl, tms, cms, tmf]
def le_textos():
'''
A função lê todos os textos a serem comparados e devolve uma lista contendo cada texto como um elemento.
Returns:
textos (list): Retorna uma lista onde cada elemento é um textos.
'''
i = 1
textos = list()
texto = input(f"Digite o texto {i} (aperte enter para sair): ")
while texto:
textos.append(texto)
i += 1
texto = input(f"Digite o texto {i} (aperte enter para sair): ")
return textos
def separa_sentencas(texto):
'''
A função recebe um texto e devolve uma lista das sentenças dentro do texto.
Parameters:
texto (str): Texto digitado pelo usuário.
Returns:
sentenças (list): Retorna uma lista onde cada elemento é uma sentença.
'''
sentenças = re.split(r'[.!?]+', texto)
if sentenças[-1] == '':
del sentenças[-1]
return sentenças
def separa_frases(sentença):
'''
A função recebe uma sentença e devolve uma lista das frases dentro da sentença.
Parameters:
sentença (str): Senteça do texto.
Returns:
(list): Retorna uma lista contendo cada frase da sentença.
'''
return re.split(r'[,:;]+', sentença)
def separa_palavras(frase):
'''
A função recebe uma frase e devolve uma lista das palavras dentro da frase.
Parameters:
frase (str): Frase da sentença.
Returns:
(list): Retorna uma lista contendo cada palavra da frase.
'''
palavras = list()
# Alguns textos podem vir sem espaços após o sinal de pontuação, para prevenir isso:
palavras = frase.replace(',', ' ').replace(';', ' ').replace(':', ' ').replace('.', ' ').replace('?', ' ').replace('!', ' ')
return palavras.split()
def n_palavras_unicas(lista_palavras):
'''
Essa função recebe uma lista de palavras e devolve o número de palavras que aparecem uma única vez.
Parameters:
lista_palavras (list): Lista contendo cada palavra de uma frase.
Returns:
únicas (int): Retorna o total de palavras únicas da frase.
'''
freq = dict()
únicas = 0
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
if freq[p] == 1:
únicas -= 1
freq[p] += 1
else:
freq[p] = 1
únicas += 1
return únicas
def n_palavras_diferentes(lista_palavras):
'''
Essa função recebe uma lista de palavras e devolve o número de palavras diferentes utilizadas.
Parameters:
lista_palavras (list): Lista contendo cada palavra de uma frase.
Returns:
(int): Retorna o total de palavras diferentes da frase.
'''
freq = dict()
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
freq[p] += 1
else:
freq[p] = 1
return len(freq)
def compara_assinatura(as_a, as_b):
'''
Essa função recebe duas assinaturas de texto e devolve o grau de similaridade nas assinaturas.
Parameters:
as_a (list): Assinatura do texto A.
as_b (list): Assinatura do texto B.
'''
similaridade = 0
for i in range(6):
similaridade += abs(as_a[i] - as_b[i])
return (similaridade / 6)
def calcula_assinatura(texto):
'''
Essa função recebe um texto e calcula a assinatura dele.
Parameters:
texto (str): Texto.
Returns:
as_t (list): Lista com a assinatura do texto.
'''
as_t = list()
# Tamanho médio de palavra.
palavras = list()
tamanho_palavras = 0
for p in separa_palavras(texto):
palavras.append(p)
tamanho_palavras += len(p)
tmp = tamanho_palavras / len(palavras)
# Relação Type-Token.
palavras_diferentes = n_palavras_diferentes(palavras)
rtt = palavras_diferentes / len(palavras)
# Razão Hapax Legomana.
palavras_únicas = n_palavras_unicas(palavras)
rhl = palavras_únicas / len(palavras)
# Tamanho médio de sentença.
sentenças = separa_sentencas(texto)
caracteres_sentença = 0
for caractere in sentenças:
caracteres_sentença += len(caractere)
tms = caracteres_sentença / len(sentenças)
# Complexidade de sentença.
total_frases = 0
for s in sentenças:
total_frases += len(separa_frases(s))
cms = total_frases / len(sentenças)
# Tamanho médio de frase.
total_caracteres = 0
for s in sentenças:
for frase in separa_frases(s):
total_caracteres += len(frase)
tmf = total_caracteres / total_frases
as_t.extend((tmp, rtt, rhl, tms, cms, tmf))
return as_t
def avalia_textos(textos, ass_cp):
'''
Essa função recebe uma lista de textos e a assinatura de um aluno portador de COH-PIAH e deve devolve o número do texto com a maior probabilidade de ter sido infectado.
Parameters:
textos (list): Lista contendo vários textos.
ass_cp (float): Assinatura do aluno infectado por COH-PIAH.
Returns:
texto_infectado (int): Número do texto infectado.
'''
assinaturas = list()
for t in textos:
assinaturas.append(calcula_assinatura(t))
i = 0
while i < len(assinaturas):
if i == 0:
ass_infectada = compara_assinatura(assinaturas[i], ass_cp)
texto_infectado = 1
else:
if compara_assinatura(assinaturas[i], ass_cp) < ass_infectada:
ass_infectada = compara_assinatura(assinaturas[i], ass_cp)
texto_infectado += 1
i += 1
return texto_infectado
def main():
ass_cp = le_assinatura()
textos = le_textos()
print(f'O autor do texto {avalia_textos(textos, ass_cp)} está infectado com COH-PIAH.') | 0.501953 | 0.505798 |
import os, glob, re
import argparse
import uuid
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torch.utils.data.dataloader import default_collate
from torchvision import transforms
import torchvision
import matplotlib.pyplot as plt
from PIL import Image
import wandb
from autoencoder import SimpleResidualEncoder, SimpleResidualDecoder
from som import SomLayer
class SomAutoEncoder(nn.Module):
def __init__(self, embedding_dim, downscale_steps=2, hidden_planes=128, in_channels=3, pass_through_som=False):
super(SomAutoEncoder, self).__init__()
self.encoder = SimpleResidualEncoder(in_channels, embedding_dim, downscale_steps, hidden_planes)
decoder_cfg = [hidden_planes for _ in range(downscale_steps)]
self.decoder = SimpleResidualDecoder(decoder_cfg, in_channels=embedding_dim, out_channels=in_channels)
self.pass_through_som = pass_through_som
self.som = SomLayer(width=128, height=128, embedding_dim=embedding_dim)
def forward(self, x):
h = self.encoder(x)
if self.pass_through_som:
# convert inputs from BCHW -> BHWC
h_in = h.permute(0, 2, 3, 1)
h, h_diff = self.som.forward(h_in)
# convert quantized from BHWC -> BCHW
h = h.permute(0, 3, 1, 2).contiguous()
else:
h_diff = None
return self.decoder(h), h_in, h_diff
# parse bool args correctly, see https://stackoverflow.com/a/43357954
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def load_file_list(file_list_fn, directory_path, pattern):
if os.path.isfile(file_list_fn):
list = torch.load(file_list_fn)
if len(list) > 0:
print('File list loaded with {} file names.'.format(len(list)))
return list
list = []
fn_match = re.compile(pattern, flags=re.IGNORECASE)
file_list = glob.iglob(directory_path, recursive=True)
print('Scanning directory: ', directory_path)
for fn in file_list:
if os.path.isfile(fn):
if fn_match.match(fn):
fn = os.path.abspath(fn)
list.append(fn)
if len(list) == 0:
raise RuntimeError('No matching files found.')
print('Matching files found: {}'.format(len(list)))
torch.save(list, file_list_fn)
print('File \'{}\' written.'.format(file_list_fn))
return list
class FileListImageDataset(Dataset):
def __init__(self, file_names, transform):
super(FileListImageDataset, self).__init__()
self.file_names = file_names
self.transform = transform
def __len__(self):
return len(self.file_names)
def __getitem__(self, index):
fn = self.file_names[index]
try:
img = Image.open(fn).convert('RGB')
if self.transform is not None:
img = self.transform(img)
return img
except Exception as e:
print(e)
def show_batch(x):
x = x.detach().cpu()
grid = torchvision.utils.make_grid(x)
plt.imshow(grid.numpy().transpose((1, 2, 0)))
plt.axis('off')
plt.show()
plt.pause(0.1)
def show_and_save(fn, reconstructions, show=True, save=True):
reconstructions = reconstructions.cpu()
if show:
show_batch(reconstructions)
if fn and save:
torchvision.utils.save_image(reconstructions, fn)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--device', default='cuda', type=str, help='device to use')
parser.add_argument('--device-index', default=1, type=int, help='device index')
parser.add_argument('--manual_seed', default=0, type=int, help='initialization of pseudo-RNG')
parser.add_argument('--batch_size', default=96, type=int, help='batch size')
parser.add_argument('--optimizer', default='AdamW', type=str, help='Optimizer to use (Adam, AdamW)')
parser.add_argument('--lr', default=2e-4, type=float, help='learning rate')
parser.add_argument('--loss_fn', default='SmoothL1', type=str)
parser.add_argument('--downscale_steps', default=3, type=int)
parser.add_argument('--embedding_dim', default=64, type=int)
parser.add_argument('--hidden_planes', default=128, type=int)
parser.add_argument('--file_list_fn', default='imgnet_sm64_files.pth', type=str)
parser.add_argument('--image_dir_path', default='/media/koepf/data_cache/imagenet_small/64x64/**/*', type=str)
parser.add_argument('--image_fn_regex', default='.*\.png$', type=str)
parser.add_argument('--checkpoint_interval', default=2000, type=int)
parser.add_argument('--wandb', default=False, action='store_true')
parser.add_argument('--entity', default='andreaskoepf', type=str)
parser.add_argument('--tags', default=None, type=str)
parser.add_argument('--project', default='finetune_ae', type=str, help='project name for wandb')
parser.add_argument('--name', default='finetune_ae_' + uuid.uuid4().hex, type=str, help='wandb experiment name')
parser.add_argument('--max_epochs', default=10, type=int)
parser.add_argument('--wandb_log_interval', default=500, type=int)
parser.add_argument('--som_checkpoint', default='experiments/som_2b_som_checkpoint_0010000.pth', type=str)
parser.add_argument('--som_adapt_rate', default=0.02, type=float)
parser.add_argument('--som_adapt_radius', default=0.25, type=float)
parser.add_argument('--som_adapt_batch', default=8, type=int)
parser.add_argument('--som_adapt_skip', default=0, type=int)
parser.add_argument('--latent_loss_weight', default=0.25, type=float)
opt = parser.parse_args()
return opt
def train(opt, model, loss_fn, device, data_loader, optimizer, lr_scheduler, chkpt_opt):
plt.ion()
experiment_name = opt.name
checkpoint_interval = opt.checkpoint_interval
max_epochs = opt.max_epochs
wandb_log_interval = opt.wandb_log_interval
som_adapt_rate = opt.som_adapt_rate
som_adapt_radius = opt.som_adapt_radius
som_adapt_batch = opt.som_adapt_batch
som_adapt_interval = opt.som_adapt_skip + 1
latent_loss_weight = opt.latent_loss_weight
train_recon_error = []
step = 1
for epoch in range(max_epochs):
print('Epoch: {}, lr: {}'.format(epoch, lr_scheduler.get_last_lr()))
for t, batch in enumerate(data_loader, 1):
model.train()
batch = batch.to(device)
reconstruction, h_in, h_diff = model(batch)
r_loss = loss_fn(reconstruction, batch)
h_loss = h_diff
loss = r_loss + latent_loss_weight * h_loss
train_recon_error.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
if som_adapt_rate > 0 and step % som_adapt_interval == 0:
som_loss = model.som.adapt(h_in, som_adapt_rate, som_adapt_radius, som_adapt_batch)
else:
som_loss = torch.tensor(0)
wand_log = {'loss': loss.item(), 'r_loss': r_loss, 'h_loss': h_loss, 'lr': lr_scheduler.get_last_lr()[0]}
if som_loss > 0:
wand_log['som_loss'] = som_loss
wandb.log(wand_log)
print('step: {}; loss: {} (h: {}); lr: {}; epoch: {};'.format(step, loss.item(), h_loss.item(), lr_scheduler.get_last_lr()[0], epoch))
if step % checkpoint_interval == 0:
# write model_checkpoint
fn = '{}_checkpoint_{:07d}.pth'.format(experiment_name, step)
print('writing file: ' + fn)
torch.save({
'step': step,
'lr': lr_scheduler.get_last_lr(),
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': { 'train_recon_error': train_recon_error },
'opt': chkpt_opt,
'finetune_opt': opt
}, fn)
fn = '{}_reconst_{:07d}.png'.format(experiment_name, step)
show_and_save(fn, reconstruction, show=False, save=True)
if step % wandb_log_interval == 0:
# log reconstruction to wandb
img_grid = torchvision.utils.make_grid(reconstruction.detach().cpu())
images = wandb.Image(img_grid, caption="Reconstruction")
wandb.log({"reconstruction": images})
step = step + 1
lr_scheduler.step()
# print the number of parameters in a module
def count_parameters(module):
print('Number of parameters: {}'.format(
sum([p.data.nelement() for p in module.parameters()])))
def wandb_init(opt):
if opt.wandb:
wandb_mode = 'online'
wandb.login()
else:
wandb_mode = 'disabled'
tags = []
if opt.tags is not None:
tags.extend(opt.tags.split(','))
wandb.init(project=opt.project, entity=opt.entity, config=vars(opt), tags=tags, mode=wandb_mode, name=opt.name)
def main():
print('Using pytorch version {}'.format(torch.__version__))
opt = parse_args()
print('Options:', opt)
file_names = load_file_list(opt.file_list_fn, opt.image_dir_path, opt.image_fn_regex)
device = torch.device(opt.device, opt.device_index)
print('Device:', device)
torch.manual_seed(opt.manual_seed)
# weights and biases
wandb_init(opt)
batch_size = opt.batch_size
learning_rate = opt.lr
optimizer_name = opt.optimizer
loss_fn_name = opt.loss_fn
print('loading SOM checkpoint: ', opt.som_checkpoint)
checkpoint_data = torch.load(opt.som_checkpoint, map_location=device)
# use checkpoint options
chkpt_opt = checkpoint_data['opt']
embedding_dim = chkpt_opt.embedding_dim
downscale_steps = chkpt_opt.downscale_steps
# data loader
transform = transforms.Compose([
transforms.ToTensor(),
])
ds = FileListImageDataset(file_names, transform)
def remove_none_collate(batch):
batch = list(filter(lambda x : x is not None, batch))
return default_collate(batch)
data_loader = DataLoader(ds, batch_size=batch_size, shuffle=True, collate_fn=remove_none_collate, num_workers=4)
model = SomAutoEncoder(embedding_dim=embedding_dim, downscale_steps=downscale_steps, pass_through_som=True)
model.load_state_dict(checkpoint_data['model_state_dict'])
test_batch = torch.rand(1, 3, 64, 64)
test_latent = model.encoder(test_batch)
print('latent size: ', test_latent.shape)
count_parameters(model)
model.to(device)
if optimizer_name == 'AdamW':
optimizer = optim.AdamW(model.parameters(), lr=learning_rate, amsgrad=False)
elif optimizer_name == 'Adam':
optimizer = optim.Adam(model.parameters(), lr=learning_rate, amsgrad=False)
else:
raise RuntimeError('Unsupported optimizer specified.')
lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.5)
if loss_fn_name == 'SmoothL1':
loss_fn = torch.nn.SmoothL1Loss(reduction='mean')
elif loss_fn_name == 'MSE':
loss_fn = torch.nn.MSELoss(reduction='mean')
elif loss_fn_name== 'MAE' or loss_fn_name == 'L1':
loss_fn = torch.nn.L1Loss(reduction='mean')
else:
raise RuntimeError('Unsupported loss function type specified.')
train(opt, model, loss_fn, device, data_loader, optimizer, lr_scheduler, chkpt_opt)
if __name__ == '__main__':
main() | som-diffusion/finetune_ae.py | import os, glob, re
import argparse
import uuid
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torch.utils.data.dataloader import default_collate
from torchvision import transforms
import torchvision
import matplotlib.pyplot as plt
from PIL import Image
import wandb
from autoencoder import SimpleResidualEncoder, SimpleResidualDecoder
from som import SomLayer
class SomAutoEncoder(nn.Module):
def __init__(self, embedding_dim, downscale_steps=2, hidden_planes=128, in_channels=3, pass_through_som=False):
super(SomAutoEncoder, self).__init__()
self.encoder = SimpleResidualEncoder(in_channels, embedding_dim, downscale_steps, hidden_planes)
decoder_cfg = [hidden_planes for _ in range(downscale_steps)]
self.decoder = SimpleResidualDecoder(decoder_cfg, in_channels=embedding_dim, out_channels=in_channels)
self.pass_through_som = pass_through_som
self.som = SomLayer(width=128, height=128, embedding_dim=embedding_dim)
def forward(self, x):
h = self.encoder(x)
if self.pass_through_som:
# convert inputs from BCHW -> BHWC
h_in = h.permute(0, 2, 3, 1)
h, h_diff = self.som.forward(h_in)
# convert quantized from BHWC -> BCHW
h = h.permute(0, 3, 1, 2).contiguous()
else:
h_diff = None
return self.decoder(h), h_in, h_diff
# parse bool args correctly, see https://stackoverflow.com/a/43357954
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def load_file_list(file_list_fn, directory_path, pattern):
if os.path.isfile(file_list_fn):
list = torch.load(file_list_fn)
if len(list) > 0:
print('File list loaded with {} file names.'.format(len(list)))
return list
list = []
fn_match = re.compile(pattern, flags=re.IGNORECASE)
file_list = glob.iglob(directory_path, recursive=True)
print('Scanning directory: ', directory_path)
for fn in file_list:
if os.path.isfile(fn):
if fn_match.match(fn):
fn = os.path.abspath(fn)
list.append(fn)
if len(list) == 0:
raise RuntimeError('No matching files found.')
print('Matching files found: {}'.format(len(list)))
torch.save(list, file_list_fn)
print('File \'{}\' written.'.format(file_list_fn))
return list
class FileListImageDataset(Dataset):
def __init__(self, file_names, transform):
super(FileListImageDataset, self).__init__()
self.file_names = file_names
self.transform = transform
def __len__(self):
return len(self.file_names)
def __getitem__(self, index):
fn = self.file_names[index]
try:
img = Image.open(fn).convert('RGB')
if self.transform is not None:
img = self.transform(img)
return img
except Exception as e:
print(e)
def show_batch(x):
x = x.detach().cpu()
grid = torchvision.utils.make_grid(x)
plt.imshow(grid.numpy().transpose((1, 2, 0)))
plt.axis('off')
plt.show()
plt.pause(0.1)
def show_and_save(fn, reconstructions, show=True, save=True):
reconstructions = reconstructions.cpu()
if show:
show_batch(reconstructions)
if fn and save:
torchvision.utils.save_image(reconstructions, fn)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--device', default='cuda', type=str, help='device to use')
parser.add_argument('--device-index', default=1, type=int, help='device index')
parser.add_argument('--manual_seed', default=0, type=int, help='initialization of pseudo-RNG')
parser.add_argument('--batch_size', default=96, type=int, help='batch size')
parser.add_argument('--optimizer', default='AdamW', type=str, help='Optimizer to use (Adam, AdamW)')
parser.add_argument('--lr', default=2e-4, type=float, help='learning rate')
parser.add_argument('--loss_fn', default='SmoothL1', type=str)
parser.add_argument('--downscale_steps', default=3, type=int)
parser.add_argument('--embedding_dim', default=64, type=int)
parser.add_argument('--hidden_planes', default=128, type=int)
parser.add_argument('--file_list_fn', default='imgnet_sm64_files.pth', type=str)
parser.add_argument('--image_dir_path', default='/media/koepf/data_cache/imagenet_small/64x64/**/*', type=str)
parser.add_argument('--image_fn_regex', default='.*\.png$', type=str)
parser.add_argument('--checkpoint_interval', default=2000, type=int)
parser.add_argument('--wandb', default=False, action='store_true')
parser.add_argument('--entity', default='andreaskoepf', type=str)
parser.add_argument('--tags', default=None, type=str)
parser.add_argument('--project', default='finetune_ae', type=str, help='project name for wandb')
parser.add_argument('--name', default='finetune_ae_' + uuid.uuid4().hex, type=str, help='wandb experiment name')
parser.add_argument('--max_epochs', default=10, type=int)
parser.add_argument('--wandb_log_interval', default=500, type=int)
parser.add_argument('--som_checkpoint', default='experiments/som_2b_som_checkpoint_0010000.pth', type=str)
parser.add_argument('--som_adapt_rate', default=0.02, type=float)
parser.add_argument('--som_adapt_radius', default=0.25, type=float)
parser.add_argument('--som_adapt_batch', default=8, type=int)
parser.add_argument('--som_adapt_skip', default=0, type=int)
parser.add_argument('--latent_loss_weight', default=0.25, type=float)
opt = parser.parse_args()
return opt
def train(opt, model, loss_fn, device, data_loader, optimizer, lr_scheduler, chkpt_opt):
plt.ion()
experiment_name = opt.name
checkpoint_interval = opt.checkpoint_interval
max_epochs = opt.max_epochs
wandb_log_interval = opt.wandb_log_interval
som_adapt_rate = opt.som_adapt_rate
som_adapt_radius = opt.som_adapt_radius
som_adapt_batch = opt.som_adapt_batch
som_adapt_interval = opt.som_adapt_skip + 1
latent_loss_weight = opt.latent_loss_weight
train_recon_error = []
step = 1
for epoch in range(max_epochs):
print('Epoch: {}, lr: {}'.format(epoch, lr_scheduler.get_last_lr()))
for t, batch in enumerate(data_loader, 1):
model.train()
batch = batch.to(device)
reconstruction, h_in, h_diff = model(batch)
r_loss = loss_fn(reconstruction, batch)
h_loss = h_diff
loss = r_loss + latent_loss_weight * h_loss
train_recon_error.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
if som_adapt_rate > 0 and step % som_adapt_interval == 0:
som_loss = model.som.adapt(h_in, som_adapt_rate, som_adapt_radius, som_adapt_batch)
else:
som_loss = torch.tensor(0)
wand_log = {'loss': loss.item(), 'r_loss': r_loss, 'h_loss': h_loss, 'lr': lr_scheduler.get_last_lr()[0]}
if som_loss > 0:
wand_log['som_loss'] = som_loss
wandb.log(wand_log)
print('step: {}; loss: {} (h: {}); lr: {}; epoch: {};'.format(step, loss.item(), h_loss.item(), lr_scheduler.get_last_lr()[0], epoch))
if step % checkpoint_interval == 0:
# write model_checkpoint
fn = '{}_checkpoint_{:07d}.pth'.format(experiment_name, step)
print('writing file: ' + fn)
torch.save({
'step': step,
'lr': lr_scheduler.get_last_lr(),
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': { 'train_recon_error': train_recon_error },
'opt': chkpt_opt,
'finetune_opt': opt
}, fn)
fn = '{}_reconst_{:07d}.png'.format(experiment_name, step)
show_and_save(fn, reconstruction, show=False, save=True)
if step % wandb_log_interval == 0:
# log reconstruction to wandb
img_grid = torchvision.utils.make_grid(reconstruction.detach().cpu())
images = wandb.Image(img_grid, caption="Reconstruction")
wandb.log({"reconstruction": images})
step = step + 1
lr_scheduler.step()
# print the number of parameters in a module
def count_parameters(module):
print('Number of parameters: {}'.format(
sum([p.data.nelement() for p in module.parameters()])))
def wandb_init(opt):
if opt.wandb:
wandb_mode = 'online'
wandb.login()
else:
wandb_mode = 'disabled'
tags = []
if opt.tags is not None:
tags.extend(opt.tags.split(','))
wandb.init(project=opt.project, entity=opt.entity, config=vars(opt), tags=tags, mode=wandb_mode, name=opt.name)
def main():
print('Using pytorch version {}'.format(torch.__version__))
opt = parse_args()
print('Options:', opt)
file_names = load_file_list(opt.file_list_fn, opt.image_dir_path, opt.image_fn_regex)
device = torch.device(opt.device, opt.device_index)
print('Device:', device)
torch.manual_seed(opt.manual_seed)
# weights and biases
wandb_init(opt)
batch_size = opt.batch_size
learning_rate = opt.lr
optimizer_name = opt.optimizer
loss_fn_name = opt.loss_fn
print('loading SOM checkpoint: ', opt.som_checkpoint)
checkpoint_data = torch.load(opt.som_checkpoint, map_location=device)
# use checkpoint options
chkpt_opt = checkpoint_data['opt']
embedding_dim = chkpt_opt.embedding_dim
downscale_steps = chkpt_opt.downscale_steps
# data loader
transform = transforms.Compose([
transforms.ToTensor(),
])
ds = FileListImageDataset(file_names, transform)
def remove_none_collate(batch):
batch = list(filter(lambda x : x is not None, batch))
return default_collate(batch)
data_loader = DataLoader(ds, batch_size=batch_size, shuffle=True, collate_fn=remove_none_collate, num_workers=4)
model = SomAutoEncoder(embedding_dim=embedding_dim, downscale_steps=downscale_steps, pass_through_som=True)
model.load_state_dict(checkpoint_data['model_state_dict'])
test_batch = torch.rand(1, 3, 64, 64)
test_latent = model.encoder(test_batch)
print('latent size: ', test_latent.shape)
count_parameters(model)
model.to(device)
if optimizer_name == 'AdamW':
optimizer = optim.AdamW(model.parameters(), lr=learning_rate, amsgrad=False)
elif optimizer_name == 'Adam':
optimizer = optim.Adam(model.parameters(), lr=learning_rate, amsgrad=False)
else:
raise RuntimeError('Unsupported optimizer specified.')
lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.5)
if loss_fn_name == 'SmoothL1':
loss_fn = torch.nn.SmoothL1Loss(reduction='mean')
elif loss_fn_name == 'MSE':
loss_fn = torch.nn.MSELoss(reduction='mean')
elif loss_fn_name== 'MAE' or loss_fn_name == 'L1':
loss_fn = torch.nn.L1Loss(reduction='mean')
else:
raise RuntimeError('Unsupported loss function type specified.')
train(opt, model, loss_fn, device, data_loader, optimizer, lr_scheduler, chkpt_opt)
if __name__ == '__main__':
main() | 0.855142 | 0.286104 |
import argparse
from glob import glob
from itertools import chain
import logging
import math
import os
import re
import sys
from time import sleep
from prettytable import PrettyTable
import pytz
import yaml
from investing import __version__
from investing import conf, InvestingLogging
from investing.data import Portfolio, Ticker
from investing.download import holdings
import investing.exceptions as exceptions
import investing.mappings as mappings
from investing.utils import partition, ptable_to_csv, sort_with_na, SubCommandDefaults
# TODO explicit submodule imports with "import investing.x as x"
class Launcher(InvestingLogging):
"""Define and run investing workflows.
Each method should define a workflow (i.e. a combination of tasks using
the other submodules in this package). The main parser allows the
workflows to be easily accessed from the command line. Workflow specific
arguments can be added via the ``subparsers`` dict
:param str workflow: Camel cased name of method to run.
:param bool foreground: Whether or not to log messsages to stdout
:param str save: Local filepath to save results to
:param str branch: Name of git branch to use when running.
"""
def __init__(self):
super(Launcher, self).__init__()
# Add subparsers to top-level parser for each workflow method
workflows = [item for item in dir(self) if callable(getattr(self, item)) and not item.startswith('_')]
parser = argparse.ArgumentParser(
formatter_class=lambda prog: SubCommandDefaults(prog, width=120, max_help_position=50))
parser.add_argument('-f', '--foreground', action='store_true', help='print logs to stdout in addition to file')
parser.add_argument('-v', '--version', action='store_true', help='print package version')
manager = parser.add_subparsers(dest='workflow', metavar='workflow')
subparsers = {}
for w in workflows:
doc = getattr(self, w).__doc__
subparsers.update({w: manager.add_parser(w, description=doc, help=doc)})
# Add workflow-specific args to each subparser
cols = ['ticker', 'name', 'metric']
comp_perf = subparsers['compare_performance']
comp_perf.add_argument('tickers', type=str, help='comma separated ticker symbols (or portfolio names)')
comp_perf.add_argument('-l', '--local_only', action='store_true', help='don\'t download more recent data')
comp_perf.add_argument('-m', '--metrics', type=str, help='comma separate metric keywords')
comp_perf.add_argument('-s', '--sort', type=str, choices=cols, default='metric', help='sorting column')
subparsers['download'].add_argument('ticker', type=str, help='symbol to search for (case insensitive)')
expected_return = subparsers['expected_return']
expected_return.add_argument('tickers', type=str, help='comma separated ticker symbols')
expected_return.add_argument('holding_periods', type=str, help='comma separated financial period keyword(s)')
expected_return.add_argument('weights', nargs='?', help='proportion of each ticker (assumed equal if absent)')
expected_return.add_argument('-l', '--local_only', action='store_true', help='don\'t download more recent data')
expected_return.add_argument('-n', '--num_trials', type=int, default=1000, help='number of Monte Carlo trials')
subparsers['search'].add_argument('ticker', type=str, help='symbol to search for (case insensitive)')
args = parser.parse_args()
# Validate configuration
if not os.path.isdir(conf['paths']['save']):
raise exceptions.ImproperlyConfigured(f'Save directory {conf["paths"]["save"]} does not exist')
for api, key in conf['keys'].items():
if key is None:
raise exceptions.ImproperlyConfigured(f'No API key configured for {api}')
valid_name = re.compile('^[a-z0-9_]+$')
for name, info in conf['portfolios'].items():
if not valid_name.match(name):
raise exceptions.ImproperlyConfigured(
f"Name can only contain lowercase letters, numbers, and underscores: '{name}'")
if name in mappings.ticker2name:
raise exceptions.ImproperlyConfigured(f"Portfolio name cannot match ticker symbol: '{name}'")
portfolio_type = info.get('type')
if portfolio_type not in ['follow', 'manual']:
raise exceptions.ImproperlyConfigured(f'Unknown type {portfolio_type} for {p["name"]} portfolio')
if len(info.get('symbols', [])) == 0:
raise exceptions.ImproperlyConfigured(f'Portfolio {info["name"]} has no symbols defined')
# Check parsed arguments
if args.version:
print(__version__)
sys.exit(0)
if args.workflow is None:
print('workflow is required')
sys.exit(1)
# Setup logging
if args.foreground:
stdout = logging.StreamHandler(stream=sys.stdout)
stdout.setFormatter(self.formatter)
self.logger.addHandler(stdout)
# Run workflow
self.logger.info(f'Running the {args.workflow} workflow')
try:
getattr(self, args.workflow)(args)
self.logger.info(f'Completed the {args.workflow} workflow')
except Exception:
msg = f'Uncaught exception in {args.workflow} workflow'
if not args.foreground:
print(f'{msg}, rerun with -f to see details')
self.logger.exception(msg)
def _format_percent(self, p, decimals=2):
"""Convert decimal percentage to human-readable string
:param float p: Raw percentage
:param int decimals: Precision of displayed value
:return str: Human-readable representation
"""
if math.isnan(p):
return 'NaN'
else:
return f'{p * 100:.{decimals}f}'
def _load_portfolios(self, portfolios=None):
"""Helper function to load unique tickers defined in user's portfolios
Sort returned tickers for better reproducibility in calling scopes
like ``_refresh_tickers``. If a followed portfolio has the ``shared``
flag enabled, only include commonly held tickers
:param dict{dict} portfolio: Specific portfolio to load, otherwise all
:return [str] tickers: Ticker symbols belonging to the portfolio(s)
"""
tickers = []
if portfolios is None:
portfolios = conf['portfolios']
for name, info in portfolios.items():
if info['type'] == 'manual':
tickers += info['symbols']
elif info['type'] == 'follow':
held = {}
for s in info['symbols']:
self.logger.info(f'Downloading holdings for {s}')
held[s] = holdings(s)
if info.get('shared', False):
shared = list(set.intersection(*[set(s) for s in held.values()]))
if len(shared) == 0:
self.logger.warning(f'No shared tickers in {name} portfolio: {", ".join(info["symbols"])}')
tickers += shared
else:
tickers += list(chain(*held.values()))
return sorted(list(set(tickers)))
def _refresh_tickers(self, tickers):
"""Helper function to get most recent ticker data
:param [str] tickers: Stock ticker symbols (case-insensitive)
:return: None
"""
self.logger.info('Sleeping for 12 seconds between API calls (AlphaVantage free tier limitation)')
for i, t in enumerate(tickers, 1):
ticker = Ticker(t)
if ticker.is_current:
self.logger.info(f'{i}/{len(tickers)}: {ticker.symbol} already up-to-date')
continue
try:
ticker.refresh()
except exceptions.APIError:
self.logger.exception(f'Timeseries download error, skipping {ticker.symbol}')
continue
self.logger.info(f'{i}/{len(tickers)}: refreshed {ticker.symbol}')
sleep(12)
def clean_csvs(self, args):
"""Delete local CSVs that are not used in portfolios"""
tickers = self._load_portfolios()
csvs = glob(os.path.join(conf['paths']['save'], '*.csv'))
removed = 0
for c in csvs:
name = os.path.basename(c).split('.')[0]
if name.upper() not in tickers:
os.remove(c)
removed += 1
self.logger.info(f'Removed {removed} of {len(csvs)} CSVs')
def compare_performance(self, args):
"""Calculate historical performance for several stock(s)"""
# Setup data sources
requested = [t.strip() for t in args.tickers.split(',')]
portfolio_names, tickers = partition(requested, lambda t: t in list(conf['portfolios'].keys()))
for p in portfolio_names:
portfolio = {p: conf['portfolios'][p]}
tickers.extend(self._load_portfolios(portfolio))
self.logger.info(f'Received {len(tickers)} symbols to compare performance of')
if args.local_only:
self.logger.info('Using most recent local data')
else:
self.logger.info('Refreshing local data from Alpha Vantage')
self._refresh_tickers(tickers)
# Calculate statistics
comparison = PrettyTable()
if args.metrics is None:
metrics = conf['metrics']
else:
metrics = [m.strip() for m in args.metrics.split(',')]
comparison.field_names = ['Ticker', 'Name'] + [m for m in metrics]
rows = []
for t in tickers:
ticker = Ticker(t)
rows.append([t.upper(), ticker.name] + [self._format_percent(ticker.metric(m)) for m in metrics])
# Output to console and CSV
if args.sort == 'metric':
rows = sorted(rows, key=lambda r: sort_with_na(float(r[-1]), reverse=True))
elif args.sort == 'ticker':
rows = sorted(rows, key=lambda r: r[0])
elif args.sort == 'name':
rows = sorted(rows, key=lambda r: r[1].lower())
else:
self.logger.warning(f"Unknown sorting '{args.sort}', argparse should have raised error")
for r in rows:
comparison.add_row(r)
print(comparison)
self.logger.info('Saving results to comparison.csv')
ptable_to_csv(comparison, 'comparison.csv')
def configure(self, args):
"""Populate YAML fields on initial install"""
print('Please enter the following values to configure your investing install')
save_path = input('Directory to save local stock CSV data: ')
while not os.path.isdir(save_path):
save_path = input('Please enter a valid directory path: ')
locale = input('Your timezone (i.e. US/Mountain, US/Eastern, etc): ')
while locale not in pytz.all_timezones:
locale = input('Please enter a valid timezone or all to show list: ')
if locale == 'all':
print('\n'.join(pytz.all_timezones))
finnhub_key = input('Finnhub API key (see https://finnhub.io/register): ')
alpha_vantage_key = input('AlphaVantage API key (see https://www.alphavantage.co/support/#api-key): ')
metals_key = input('Metals API key (see https://metals-api.com/pricing): ')
config_data = {
'locale': locale,
'keys': {
'alpha_vantage': alpha_vantage_key,
'finnhub': finnhub_key,
'metals': metals_key},
'paths': {
'save': save_path}}
with open('config/investing.yaml', 'w') as stream:
yaml.dump(config_data, stream)
print('Configuration successfully written')
print("Please run 'python launcher.py show_config' to confirm")
def daily_tickers(self, args):
"""Download new time series data for followed tickers"""
tickers = self._load_portfolios()
self.logger.info(f'Checking prices for {len(tickers)} configured tickers')
self._refresh_tickers(tickers)
def download(self, args):
"""Manually download ticker data for a specific symbol"""
self._refresh_tickers([args.ticker])
def expected_return(self, args):
"""Calculate joint return probability across several holdings"""
# Initialize portfolio object
tickers = [t for t in args.tickers.split(',')]
if args.weights is None:
weights = None
else:
weights = [float(w) for w in args.weights.split(',')]
portfolio = Portfolio(tickers, weights)
self.logger.info(f'Initialized {repr(portfolio)}')
# Calculate returns and print results
returns = PrettyTable()
returns.field_names = ['Period', '-σ', 'Mean', '+σ', 'Data Points']
returns.title = portfolio.name
periods = [p for p in args.holding_periods.split(',')]
self.logger.info(f'Simulating composite returns for {periods}')
for p in periods:
return_avg, return_std, min_count = portfolio.expected_return(p, args.num_trials)
returns.add_row([
p,
self._format_percent(return_avg - return_std),
self._format_percent(return_avg),
self._format_percent(return_avg + return_std),
min_count])
print(returns)
self.logger.info('Saving results to returns.csv')
ptable_to_csv(returns, 'returns.csv')
def list(self, args):
"""Print all locally available ticker symbols alphabetically sorted"""
local = [os.path.splitext(f)[0] for f in os.listdir(conf['paths']['save']) if f.endswith('.csv')]
print('\n'.join(sorted(local)))
def search(self, args):
"""Check if ticker data exists locally"""
ticker = Ticker(args.ticker)
if ticker.has_csv:
status = 'Found'
if not ticker.is_current:
status += ' stale'
else:
status = 'Missing'
msg = f'{status} local data for {ticker.symbol}'
if ticker.name == 'Unknown':
msg += ' - name not in mappings.ticker2name, please submit pull request'
else:
msg += f' ({ticker.name})'
print(msg)
def show_config(self, args):
"""Print active configuration values to console for confirmation"""
stream = yaml.dump(conf)
print(stream.replace('\n-', '\n -'))
if __name__ == '__main__':
Launcher() | launcher.py | import argparse
from glob import glob
from itertools import chain
import logging
import math
import os
import re
import sys
from time import sleep
from prettytable import PrettyTable
import pytz
import yaml
from investing import __version__
from investing import conf, InvestingLogging
from investing.data import Portfolio, Ticker
from investing.download import holdings
import investing.exceptions as exceptions
import investing.mappings as mappings
from investing.utils import partition, ptable_to_csv, sort_with_na, SubCommandDefaults
# TODO explicit submodule imports with "import investing.x as x"
class Launcher(InvestingLogging):
"""Define and run investing workflows.
Each method should define a workflow (i.e. a combination of tasks using
the other submodules in this package). The main parser allows the
workflows to be easily accessed from the command line. Workflow specific
arguments can be added via the ``subparsers`` dict
:param str workflow: Camel cased name of method to run.
:param bool foreground: Whether or not to log messsages to stdout
:param str save: Local filepath to save results to
:param str branch: Name of git branch to use when running.
"""
def __init__(self):
super(Launcher, self).__init__()
# Add subparsers to top-level parser for each workflow method
workflows = [item for item in dir(self) if callable(getattr(self, item)) and not item.startswith('_')]
parser = argparse.ArgumentParser(
formatter_class=lambda prog: SubCommandDefaults(prog, width=120, max_help_position=50))
parser.add_argument('-f', '--foreground', action='store_true', help='print logs to stdout in addition to file')
parser.add_argument('-v', '--version', action='store_true', help='print package version')
manager = parser.add_subparsers(dest='workflow', metavar='workflow')
subparsers = {}
for w in workflows:
doc = getattr(self, w).__doc__
subparsers.update({w: manager.add_parser(w, description=doc, help=doc)})
# Add workflow-specific args to each subparser
cols = ['ticker', 'name', 'metric']
comp_perf = subparsers['compare_performance']
comp_perf.add_argument('tickers', type=str, help='comma separated ticker symbols (or portfolio names)')
comp_perf.add_argument('-l', '--local_only', action='store_true', help='don\'t download more recent data')
comp_perf.add_argument('-m', '--metrics', type=str, help='comma separate metric keywords')
comp_perf.add_argument('-s', '--sort', type=str, choices=cols, default='metric', help='sorting column')
subparsers['download'].add_argument('ticker', type=str, help='symbol to search for (case insensitive)')
expected_return = subparsers['expected_return']
expected_return.add_argument('tickers', type=str, help='comma separated ticker symbols')
expected_return.add_argument('holding_periods', type=str, help='comma separated financial period keyword(s)')
expected_return.add_argument('weights', nargs='?', help='proportion of each ticker (assumed equal if absent)')
expected_return.add_argument('-l', '--local_only', action='store_true', help='don\'t download more recent data')
expected_return.add_argument('-n', '--num_trials', type=int, default=1000, help='number of Monte Carlo trials')
subparsers['search'].add_argument('ticker', type=str, help='symbol to search for (case insensitive)')
args = parser.parse_args()
# Validate configuration
if not os.path.isdir(conf['paths']['save']):
raise exceptions.ImproperlyConfigured(f'Save directory {conf["paths"]["save"]} does not exist')
for api, key in conf['keys'].items():
if key is None:
raise exceptions.ImproperlyConfigured(f'No API key configured for {api}')
valid_name = re.compile('^[a-z0-9_]+$')
for name, info in conf['portfolios'].items():
if not valid_name.match(name):
raise exceptions.ImproperlyConfigured(
f"Name can only contain lowercase letters, numbers, and underscores: '{name}'")
if name in mappings.ticker2name:
raise exceptions.ImproperlyConfigured(f"Portfolio name cannot match ticker symbol: '{name}'")
portfolio_type = info.get('type')
if portfolio_type not in ['follow', 'manual']:
raise exceptions.ImproperlyConfigured(f'Unknown type {portfolio_type} for {p["name"]} portfolio')
if len(info.get('symbols', [])) == 0:
raise exceptions.ImproperlyConfigured(f'Portfolio {info["name"]} has no symbols defined')
# Check parsed arguments
if args.version:
print(__version__)
sys.exit(0)
if args.workflow is None:
print('workflow is required')
sys.exit(1)
# Setup logging
if args.foreground:
stdout = logging.StreamHandler(stream=sys.stdout)
stdout.setFormatter(self.formatter)
self.logger.addHandler(stdout)
# Run workflow
self.logger.info(f'Running the {args.workflow} workflow')
try:
getattr(self, args.workflow)(args)
self.logger.info(f'Completed the {args.workflow} workflow')
except Exception:
msg = f'Uncaught exception in {args.workflow} workflow'
if not args.foreground:
print(f'{msg}, rerun with -f to see details')
self.logger.exception(msg)
def _format_percent(self, p, decimals=2):
"""Convert decimal percentage to human-readable string
:param float p: Raw percentage
:param int decimals: Precision of displayed value
:return str: Human-readable representation
"""
if math.isnan(p):
return 'NaN'
else:
return f'{p * 100:.{decimals}f}'
def _load_portfolios(self, portfolios=None):
"""Helper function to load unique tickers defined in user's portfolios
Sort returned tickers for better reproducibility in calling scopes
like ``_refresh_tickers``. If a followed portfolio has the ``shared``
flag enabled, only include commonly held tickers
:param dict{dict} portfolio: Specific portfolio to load, otherwise all
:return [str] tickers: Ticker symbols belonging to the portfolio(s)
"""
tickers = []
if portfolios is None:
portfolios = conf['portfolios']
for name, info in portfolios.items():
if info['type'] == 'manual':
tickers += info['symbols']
elif info['type'] == 'follow':
held = {}
for s in info['symbols']:
self.logger.info(f'Downloading holdings for {s}')
held[s] = holdings(s)
if info.get('shared', False):
shared = list(set.intersection(*[set(s) for s in held.values()]))
if len(shared) == 0:
self.logger.warning(f'No shared tickers in {name} portfolio: {", ".join(info["symbols"])}')
tickers += shared
else:
tickers += list(chain(*held.values()))
return sorted(list(set(tickers)))
def _refresh_tickers(self, tickers):
"""Helper function to get most recent ticker data
:param [str] tickers: Stock ticker symbols (case-insensitive)
:return: None
"""
self.logger.info('Sleeping for 12 seconds between API calls (AlphaVantage free tier limitation)')
for i, t in enumerate(tickers, 1):
ticker = Ticker(t)
if ticker.is_current:
self.logger.info(f'{i}/{len(tickers)}: {ticker.symbol} already up-to-date')
continue
try:
ticker.refresh()
except exceptions.APIError:
self.logger.exception(f'Timeseries download error, skipping {ticker.symbol}')
continue
self.logger.info(f'{i}/{len(tickers)}: refreshed {ticker.symbol}')
sleep(12)
def clean_csvs(self, args):
"""Delete local CSVs that are not used in portfolios"""
tickers = self._load_portfolios()
csvs = glob(os.path.join(conf['paths']['save'], '*.csv'))
removed = 0
for c in csvs:
name = os.path.basename(c).split('.')[0]
if name.upper() not in tickers:
os.remove(c)
removed += 1
self.logger.info(f'Removed {removed} of {len(csvs)} CSVs')
def compare_performance(self, args):
"""Calculate historical performance for several stock(s)"""
# Setup data sources
requested = [t.strip() for t in args.tickers.split(',')]
portfolio_names, tickers = partition(requested, lambda t: t in list(conf['portfolios'].keys()))
for p in portfolio_names:
portfolio = {p: conf['portfolios'][p]}
tickers.extend(self._load_portfolios(portfolio))
self.logger.info(f'Received {len(tickers)} symbols to compare performance of')
if args.local_only:
self.logger.info('Using most recent local data')
else:
self.logger.info('Refreshing local data from Alpha Vantage')
self._refresh_tickers(tickers)
# Calculate statistics
comparison = PrettyTable()
if args.metrics is None:
metrics = conf['metrics']
else:
metrics = [m.strip() for m in args.metrics.split(',')]
comparison.field_names = ['Ticker', 'Name'] + [m for m in metrics]
rows = []
for t in tickers:
ticker = Ticker(t)
rows.append([t.upper(), ticker.name] + [self._format_percent(ticker.metric(m)) for m in metrics])
# Output to console and CSV
if args.sort == 'metric':
rows = sorted(rows, key=lambda r: sort_with_na(float(r[-1]), reverse=True))
elif args.sort == 'ticker':
rows = sorted(rows, key=lambda r: r[0])
elif args.sort == 'name':
rows = sorted(rows, key=lambda r: r[1].lower())
else:
self.logger.warning(f"Unknown sorting '{args.sort}', argparse should have raised error")
for r in rows:
comparison.add_row(r)
print(comparison)
self.logger.info('Saving results to comparison.csv')
ptable_to_csv(comparison, 'comparison.csv')
def configure(self, args):
"""Populate YAML fields on initial install"""
print('Please enter the following values to configure your investing install')
save_path = input('Directory to save local stock CSV data: ')
while not os.path.isdir(save_path):
save_path = input('Please enter a valid directory path: ')
locale = input('Your timezone (i.e. US/Mountain, US/Eastern, etc): ')
while locale not in pytz.all_timezones:
locale = input('Please enter a valid timezone or all to show list: ')
if locale == 'all':
print('\n'.join(pytz.all_timezones))
finnhub_key = input('Finnhub API key (see https://finnhub.io/register): ')
alpha_vantage_key = input('AlphaVantage API key (see https://www.alphavantage.co/support/#api-key): ')
metals_key = input('Metals API key (see https://metals-api.com/pricing): ')
config_data = {
'locale': locale,
'keys': {
'alpha_vantage': alpha_vantage_key,
'finnhub': finnhub_key,
'metals': metals_key},
'paths': {
'save': save_path}}
with open('config/investing.yaml', 'w') as stream:
yaml.dump(config_data, stream)
print('Configuration successfully written')
print("Please run 'python launcher.py show_config' to confirm")
def daily_tickers(self, args):
"""Download new time series data for followed tickers"""
tickers = self._load_portfolios()
self.logger.info(f'Checking prices for {len(tickers)} configured tickers')
self._refresh_tickers(tickers)
def download(self, args):
"""Manually download ticker data for a specific symbol"""
self._refresh_tickers([args.ticker])
def expected_return(self, args):
"""Calculate joint return probability across several holdings"""
# Initialize portfolio object
tickers = [t for t in args.tickers.split(',')]
if args.weights is None:
weights = None
else:
weights = [float(w) for w in args.weights.split(',')]
portfolio = Portfolio(tickers, weights)
self.logger.info(f'Initialized {repr(portfolio)}')
# Calculate returns and print results
returns = PrettyTable()
returns.field_names = ['Period', '-σ', 'Mean', '+σ', 'Data Points']
returns.title = portfolio.name
periods = [p for p in args.holding_periods.split(',')]
self.logger.info(f'Simulating composite returns for {periods}')
for p in periods:
return_avg, return_std, min_count = portfolio.expected_return(p, args.num_trials)
returns.add_row([
p,
self._format_percent(return_avg - return_std),
self._format_percent(return_avg),
self._format_percent(return_avg + return_std),
min_count])
print(returns)
self.logger.info('Saving results to returns.csv')
ptable_to_csv(returns, 'returns.csv')
def list(self, args):
"""Print all locally available ticker symbols alphabetically sorted"""
local = [os.path.splitext(f)[0] for f in os.listdir(conf['paths']['save']) if f.endswith('.csv')]
print('\n'.join(sorted(local)))
def search(self, args):
"""Check if ticker data exists locally"""
ticker = Ticker(args.ticker)
if ticker.has_csv:
status = 'Found'
if not ticker.is_current:
status += ' stale'
else:
status = 'Missing'
msg = f'{status} local data for {ticker.symbol}'
if ticker.name == 'Unknown':
msg += ' - name not in mappings.ticker2name, please submit pull request'
else:
msg += f' ({ticker.name})'
print(msg)
def show_config(self, args):
"""Print active configuration values to console for confirmation"""
stream = yaml.dump(conf)
print(stream.replace('\n-', '\n -'))
if __name__ == '__main__':
Launcher() | 0.494385 | 0.180612 |
import asyncio
from datetime import datetime
import re
import sys
from io import StringIO
from aiogram import Bot, Dispatcher
from aiogram.dispatcher.filters import Filter
from aiogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery
from aiogram.utils.exceptions import MessageNotModified
from cwapi import AsyncChatWarsApiClient, Server as CWServer
from cwapi.requests import CreateAuthCodeRequest, GrantTokenRequest, RequestProfileRequest
from cwapi.responses import ApiException, ForbiddenError, NoSuchUserError
from cwapi.types import Action
from sqlalchemy import Table, Column, MetaData, BigInteger, DateTime, Text, select, and_, update
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.ddl import CreateTable
table = Table(
"kamikadzes",
MetaData(),
Column("user", BigInteger, primary_key=True, unique=True),
Column("token", Text),
Column("name", Text),
Column("atk", BigInteger)
)
class KamikadzeDatabase:
__slots__ = "__sf"
@classmethod
async def connect(cls, session_factory):
self = super().__new__(cls)
self.__sf = session_factory
async with self.__sf.begin() as c:
await c.execute(CreateTable(table, if_not_exists=True))
return self
async def set_user(self, uid: int, token: str, name: str, atk: int):
if not isinstance(uid, int):
raise TypeError(f"uid must be int (got {type(uid) !r})")
if not isinstance(token, str):
raise TypeError(f"token must be str (got {type(uid) !r})")
if not isinstance(name, str):
raise TypeError(f"name must be str (got {type(uid) !r})")
if not isinstance(atk, int):
raise TypeError(f"atk must be int (got {type(uid) !r})")
async with self.__sf.begin() as c:
for rec in await c.execute(select(table).where(table.c.user == uid)):
await c.execute(update(table).where(table.c.user == uid).values(token=token, name=name, atk=atk))
return True
await c.execute(table.insert().values(user=uid, token=token, name=name, atk=atk))
return True
async def get_user(self, uid: int):
if not isinstance(uid, int):
raise TypeError(f"uid must be int (got {type(uid) !r})")
async with self.__sf.begin() as c:
for rec in await c.execute(select(table).where(table.c.user == uid)):
return rec.token, rec.name, rec.atk
return None
async def get_all_users(self):
users = []
async with self.__sf.begin() as c:
for rec in await c.execute(select(table)):
users.append((rec.user, rec.name, rec.atk))
return users
auth_code_pattern = re.compile("^Code (\d+) to authorize [^.]+. This app will have the access to:")
class AuthCodeFilter(Filter):
@staticmethod
async def check(msg: Message):
return msg.is_forward() and msg.forward_from.id == 265204902 and auth_code_pattern.search(msg.text) is not None
class PrefixCheckFilter(Filter):
__slots__ = ("__prefix",)
def __init__(self, prefix):
self.__prefix = prefix
async def check(self, cbq):
return cbq.data.startswith(self.__prefix)
squad_msg_pattern = re.compile(r"^[^(]+\(\D*(\d+)\D+\).+(?:\n([\s\S]*)|)$")
squad_msg_row_pattern = re.compile(r"^\D*(\d+)\D.+tg://user\?id=(\d+)\D")
class KamikadzeBot:
__slots__ = "__bot", "__dp", "__db", "__current_battle", "__cwapi_client"
def __init__(self, token, *, database, cwapi_client):
self.__bot = Bot(token=token)
self.__dp = Dispatcher(self.__bot)
self.__db = database
self.__cwapi_client = cwapi_client
self.__dp.register_message_handler(self.__grant_token, AuthCodeFilter())
self.__dp.register_message_handler(self.__get_me, commands=["me"])
self.__dp.register_message_handler(self.__button, commands=["suicide"])
self.__dp.register_message_handler(self.__wakeup, commands=["wakeup"])
self.__dp.register_message_handler(self.__wakeup_all, commands=["wakeup_all"])
self.__dp.register_callback_query_handler(self.__add, PrefixCheckFilter("add"))
def start(self, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
return loop.create_task(self.run())
async def run(self):
await self.__dp.start_polling()
async def __grant_token(self, msg: Message):
match = auth_code_pattern.search(msg.text)
if match is None:
return
try:
tr = await self.__cwapi_client.ask(GrantTokenRequest(userId=msg.from_user.id, authCode=match.group(1)))
except ApiException as exc:
print(exc.raw, file=sys.stderr)
return
await self.__db.set_user(uid=msg.from_user.id, token=tr.token, name="", atk=0)
await msg.reply_animation("CgACAgIAAxkBAANqYZ6BWAvAk3tUGcPzDQ-Ghos45yYAAncCAALDRClIzjRfROqXvikiBA", caption=f"Запомнил тебя", parse_mode="html")
async def __get_me(self, msg: Message):
data = await self.__db.get_user(msg.from_user.id)
if data is None:
await msg.reply("Ты слишком сильно любишь жить, чтобы мне была интересна информация про тебя")
else:
await msg.reply(f"<code>{data[1]} \u2694\ufe0f{data[2]}</code>", parse_mode="html")
async def __button(self, msg: Message):
await msg.reply("<b>Отряд суицидников (<u>0\u2694\ufe0f</u>):</b>", parse_mode="html", reply_markup=InlineKeyboardMarkup(row_width=1, inline_keyboard=[[InlineKeyboardButton(text="Сдохнуть", callback_data="add")]]))
async def __add(self, query: CallbackQuery):
if (m := squad_msg_pattern.search(query.message.html_text)) is None:
await query.answer("С этим сообщением что то не так")
return
atk = int(m.group(1))
u = None
new_rows = StringIO()
async def proc_user(neg):
nonlocal atk, u, new_rows, self
u = await self.__db.get_user(query.from_user.id)
if u is None:
try:
await self.__cwapi_client.ask(CreateAuthCodeRequest(userId=query.from_user.id))
except NoSuchUserError:
await query.answer("Слабак")
await query.message.reply(f"<a href='tg://user?id={query.from_user.id}'>{query.from_user.full_name}</a> ты нонейм", parse_mode="html")
except ApiException as exc:
print(exc.raw, file=sys.stderr)
return True
await query.answer("Профиль где?")
await query.message.reply(f"<a href='tg://user?id={query.from_user.id}'>{query.from_user.full_name}</a> покажи мне код <s>с банковской карточки</s> который пришёл тебе в игре", parse_mode="html")
return True
try:
pr = await self.__cwapi_client.ask(RequestProfileRequest(token=u[0]))
except ForbiddenError:
await query.answer("Ты пидор")
await query.message.reply(f"<a href='tg://user?id={query.from_user.id}'>{query.from_user.full_name}</a> <code>/revoke</code> для пидоров", parse_mode="html")
return True
except ApiException as exc:
print(exc.raw, file=sys.stderr)
return True
if pr.guild is None:
name = str(pr.castle)
else:
if pr.guild.emoji is None:
name = str(pr.castle)
else:
name = pr.guild.emoji
if pr.guild.tag is not None:
name += f"[{pr.guild.tag}]"
name += pr.userName
await self.__db.set_user(uid=query.from_user.id, token=u[0], name=name, atk=pr.atk)
new_rows.write(f"<code>{str(pr.atk).rjust(5, ' ')}\u2694\ufe0f</code> <a href='tg://user?id={query.from_user.id}'>{name}</a>\n")
atk = atk - neg + pr.atk
for row in filter(bool, (m.group(2) or "").split("\n")):
mm = squad_msg_row_pattern.search(row)
if mm is None:
new_rows.write(row + "\n")
continue
if int(mm.group(2)) == query.from_user.id:
if await proc_user(int(mm.group(1))):
return
else:
new_rows.write(row + "\n")
if u is None:
if await proc_user(0):
return
new_rows.seek(0)
try:
await query.answer("Записан в суицидники")
await query.message.edit_text(f"<b>Отряд суицидников (<u>{atk}\u2694\ufe0f</u>):</b>\n" + new_rows.read(), parse_mode="html", reply_markup=query.message.reply_markup)
except MessageNotModified:
pass
async def __wakeup(self, msg: Message):
if msg.reply_to_message is None:
return
if (m := squad_msg_pattern.search(msg.reply_to_message.html_text)) is None:
return
pings = []
for row in filter(bool, (m.group(2) or "").split("\n")):
mm = squad_msg_row_pattern.search(row)
if mm is None:
continue
u = await self.__db.get_user(int(mm.group(2)))
if u is None:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>нонейм</a> (пидор)")
else:
try:
pr = await self.__cwapi_client.ask(RequestProfileRequest(token=u[0]))
except ForbiddenError:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>{u[1]}</a> (пидор)")
except ApiException as exc:
print(exc.raw, file=sys.stderr)
return True
else:
if pr.action != Action.Conflict:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>{u[1]}</a>")
for q in range(0, len(pings), 3):
await msg.reply("\n".join(pings[q:q + 3]), parse_mode="html")
async def __wakeup_all(self, msg: Message):
if msg.reply_to_message is None:
return
if (m := squad_msg_pattern.search(msg.reply_to_message.html_text)) is None:
return
pings = []
for row in filter(bool, (m.group(2) or "").split("\n")):
mm = squad_msg_row_pattern.search(row)
if mm is None:
continue
u = await self.__db.get_user(int(mm.group(2)))
if u is None:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>нонейм</a> (пидор)")
else:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>{u[1]}</a>")
for q in range(0, len(pings), 3):
await msg.reply("\n".join(pings[q:q + 3]), parse_mode="html")
async def amain(argv):
engine = create_async_engine(f"postgresql+asyncpg://{argv[2]}:{argv[3]}@{argv[4]}:{argv[5]}/{argv[6]}", )
db = await KamikadzeDatabase.connect(sessionmaker(engine, class_=AsyncSession))
cwapi_client = AsyncChatWarsApiClient(CWServer.CW3, argv[7], argv[8])
await cwapi_client.connect()
await KamikadzeBot(argv[1], database=db, cwapi_client=cwapi_client).run()
def main(argv):
asyncio.get_event_loop().run_until_complete(amain(argv))
if __name__ == "__main__":
exit(main(sys.argv)) | cw3_kamikadze_bot.py | import asyncio
from datetime import datetime
import re
import sys
from io import StringIO
from aiogram import Bot, Dispatcher
from aiogram.dispatcher.filters import Filter
from aiogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery
from aiogram.utils.exceptions import MessageNotModified
from cwapi import AsyncChatWarsApiClient, Server as CWServer
from cwapi.requests import CreateAuthCodeRequest, GrantTokenRequest, RequestProfileRequest
from cwapi.responses import ApiException, ForbiddenError, NoSuchUserError
from cwapi.types import Action
from sqlalchemy import Table, Column, MetaData, BigInteger, DateTime, Text, select, and_, update
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.ddl import CreateTable
table = Table(
"kamikadzes",
MetaData(),
Column("user", BigInteger, primary_key=True, unique=True),
Column("token", Text),
Column("name", Text),
Column("atk", BigInteger)
)
class KamikadzeDatabase:
__slots__ = "__sf"
@classmethod
async def connect(cls, session_factory):
self = super().__new__(cls)
self.__sf = session_factory
async with self.__sf.begin() as c:
await c.execute(CreateTable(table, if_not_exists=True))
return self
async def set_user(self, uid: int, token: str, name: str, atk: int):
if not isinstance(uid, int):
raise TypeError(f"uid must be int (got {type(uid) !r})")
if not isinstance(token, str):
raise TypeError(f"token must be str (got {type(uid) !r})")
if not isinstance(name, str):
raise TypeError(f"name must be str (got {type(uid) !r})")
if not isinstance(atk, int):
raise TypeError(f"atk must be int (got {type(uid) !r})")
async with self.__sf.begin() as c:
for rec in await c.execute(select(table).where(table.c.user == uid)):
await c.execute(update(table).where(table.c.user == uid).values(token=token, name=name, atk=atk))
return True
await c.execute(table.insert().values(user=uid, token=token, name=name, atk=atk))
return True
async def get_user(self, uid: int):
if not isinstance(uid, int):
raise TypeError(f"uid must be int (got {type(uid) !r})")
async with self.__sf.begin() as c:
for rec in await c.execute(select(table).where(table.c.user == uid)):
return rec.token, rec.name, rec.atk
return None
async def get_all_users(self):
users = []
async with self.__sf.begin() as c:
for rec in await c.execute(select(table)):
users.append((rec.user, rec.name, rec.atk))
return users
auth_code_pattern = re.compile("^Code (\d+) to authorize [^.]+. This app will have the access to:")
class AuthCodeFilter(Filter):
@staticmethod
async def check(msg: Message):
return msg.is_forward() and msg.forward_from.id == 265204902 and auth_code_pattern.search(msg.text) is not None
class PrefixCheckFilter(Filter):
__slots__ = ("__prefix",)
def __init__(self, prefix):
self.__prefix = prefix
async def check(self, cbq):
return cbq.data.startswith(self.__prefix)
squad_msg_pattern = re.compile(r"^[^(]+\(\D*(\d+)\D+\).+(?:\n([\s\S]*)|)$")
squad_msg_row_pattern = re.compile(r"^\D*(\d+)\D.+tg://user\?id=(\d+)\D")
class KamikadzeBot:
__slots__ = "__bot", "__dp", "__db", "__current_battle", "__cwapi_client"
def __init__(self, token, *, database, cwapi_client):
self.__bot = Bot(token=token)
self.__dp = Dispatcher(self.__bot)
self.__db = database
self.__cwapi_client = cwapi_client
self.__dp.register_message_handler(self.__grant_token, AuthCodeFilter())
self.__dp.register_message_handler(self.__get_me, commands=["me"])
self.__dp.register_message_handler(self.__button, commands=["suicide"])
self.__dp.register_message_handler(self.__wakeup, commands=["wakeup"])
self.__dp.register_message_handler(self.__wakeup_all, commands=["wakeup_all"])
self.__dp.register_callback_query_handler(self.__add, PrefixCheckFilter("add"))
def start(self, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
return loop.create_task(self.run())
async def run(self):
await self.__dp.start_polling()
async def __grant_token(self, msg: Message):
match = auth_code_pattern.search(msg.text)
if match is None:
return
try:
tr = await self.__cwapi_client.ask(GrantTokenRequest(userId=msg.from_user.id, authCode=match.group(1)))
except ApiException as exc:
print(exc.raw, file=sys.stderr)
return
await self.__db.set_user(uid=msg.from_user.id, token=tr.token, name="", atk=0)
await msg.reply_animation("CgACAgIAAxkBAANqYZ6BWAvAk3tUGcPzDQ-Ghos45yYAAncCAALDRClIzjRfROqXvikiBA", caption=f"Запомнил тебя", parse_mode="html")
async def __get_me(self, msg: Message):
data = await self.__db.get_user(msg.from_user.id)
if data is None:
await msg.reply("Ты слишком сильно любишь жить, чтобы мне была интересна информация про тебя")
else:
await msg.reply(f"<code>{data[1]} \u2694\ufe0f{data[2]}</code>", parse_mode="html")
async def __button(self, msg: Message):
await msg.reply("<b>Отряд суицидников (<u>0\u2694\ufe0f</u>):</b>", parse_mode="html", reply_markup=InlineKeyboardMarkup(row_width=1, inline_keyboard=[[InlineKeyboardButton(text="Сдохнуть", callback_data="add")]]))
async def __add(self, query: CallbackQuery):
if (m := squad_msg_pattern.search(query.message.html_text)) is None:
await query.answer("С этим сообщением что то не так")
return
atk = int(m.group(1))
u = None
new_rows = StringIO()
async def proc_user(neg):
nonlocal atk, u, new_rows, self
u = await self.__db.get_user(query.from_user.id)
if u is None:
try:
await self.__cwapi_client.ask(CreateAuthCodeRequest(userId=query.from_user.id))
except NoSuchUserError:
await query.answer("Слабак")
await query.message.reply(f"<a href='tg://user?id={query.from_user.id}'>{query.from_user.full_name}</a> ты нонейм", parse_mode="html")
except ApiException as exc:
print(exc.raw, file=sys.stderr)
return True
await query.answer("Профиль где?")
await query.message.reply(f"<a href='tg://user?id={query.from_user.id}'>{query.from_user.full_name}</a> покажи мне код <s>с банковской карточки</s> который пришёл тебе в игре", parse_mode="html")
return True
try:
pr = await self.__cwapi_client.ask(RequestProfileRequest(token=u[0]))
except ForbiddenError:
await query.answer("Ты пидор")
await query.message.reply(f"<a href='tg://user?id={query.from_user.id}'>{query.from_user.full_name}</a> <code>/revoke</code> для пидоров", parse_mode="html")
return True
except ApiException as exc:
print(exc.raw, file=sys.stderr)
return True
if pr.guild is None:
name = str(pr.castle)
else:
if pr.guild.emoji is None:
name = str(pr.castle)
else:
name = pr.guild.emoji
if pr.guild.tag is not None:
name += f"[{pr.guild.tag}]"
name += pr.userName
await self.__db.set_user(uid=query.from_user.id, token=u[0], name=name, atk=pr.atk)
new_rows.write(f"<code>{str(pr.atk).rjust(5, ' ')}\u2694\ufe0f</code> <a href='tg://user?id={query.from_user.id}'>{name}</a>\n")
atk = atk - neg + pr.atk
for row in filter(bool, (m.group(2) or "").split("\n")):
mm = squad_msg_row_pattern.search(row)
if mm is None:
new_rows.write(row + "\n")
continue
if int(mm.group(2)) == query.from_user.id:
if await proc_user(int(mm.group(1))):
return
else:
new_rows.write(row + "\n")
if u is None:
if await proc_user(0):
return
new_rows.seek(0)
try:
await query.answer("Записан в суицидники")
await query.message.edit_text(f"<b>Отряд суицидников (<u>{atk}\u2694\ufe0f</u>):</b>\n" + new_rows.read(), parse_mode="html", reply_markup=query.message.reply_markup)
except MessageNotModified:
pass
async def __wakeup(self, msg: Message):
if msg.reply_to_message is None:
return
if (m := squad_msg_pattern.search(msg.reply_to_message.html_text)) is None:
return
pings = []
for row in filter(bool, (m.group(2) or "").split("\n")):
mm = squad_msg_row_pattern.search(row)
if mm is None:
continue
u = await self.__db.get_user(int(mm.group(2)))
if u is None:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>нонейм</a> (пидор)")
else:
try:
pr = await self.__cwapi_client.ask(RequestProfileRequest(token=u[0]))
except ForbiddenError:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>{u[1]}</a> (пидор)")
except ApiException as exc:
print(exc.raw, file=sys.stderr)
return True
else:
if pr.action != Action.Conflict:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>{u[1]}</a>")
for q in range(0, len(pings), 3):
await msg.reply("\n".join(pings[q:q + 3]), parse_mode="html")
async def __wakeup_all(self, msg: Message):
if msg.reply_to_message is None:
return
if (m := squad_msg_pattern.search(msg.reply_to_message.html_text)) is None:
return
pings = []
for row in filter(bool, (m.group(2) or "").split("\n")):
mm = squad_msg_row_pattern.search(row)
if mm is None:
continue
u = await self.__db.get_user(int(mm.group(2)))
if u is None:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>нонейм</a> (пидор)")
else:
pings.append(f"<a href='tg://user?id={mm.group(2)}'>{u[1]}</a>")
for q in range(0, len(pings), 3):
await msg.reply("\n".join(pings[q:q + 3]), parse_mode="html")
async def amain(argv):
engine = create_async_engine(f"postgresql+asyncpg://{argv[2]}:{argv[3]}@{argv[4]}:{argv[5]}/{argv[6]}", )
db = await KamikadzeDatabase.connect(sessionmaker(engine, class_=AsyncSession))
cwapi_client = AsyncChatWarsApiClient(CWServer.CW3, argv[7], argv[8])
await cwapi_client.connect()
await KamikadzeBot(argv[1], database=db, cwapi_client=cwapi_client).run()
def main(argv):
asyncio.get_event_loop().run_until_complete(amain(argv))
if __name__ == "__main__":
exit(main(sys.argv)) | 0.355439 | 0.117876 |
__version__ = '0.0.1'
# Helix ALM REST API: http://help.seapine.com/helixalm/rest-api/index.html
API_PATH = {
# Projects Requests for retrieving and switching projects.
'projects': '/projects',
# Security Requests related to security.
'security': '/{projectID}/token',
# Rate Limits Requests related to rate limits.
'rate_limits': '/{projectID}/ratelimits',
# Issues Requests for viewing and updating issues.
'issues': '/{projectID}/issues',
'issues_search': '/{projectID}/issues/search',
'issues_specific': '/{projectID}/issues/{itemID}',
# Issue Attachments Requests for viewing and updating files attached to issues.
'issues_attachments': '/{projectID}/issues/{itemID}/attachments',
'issues_attachments_file': '/{projectID}/issues/{itemID}/attachments/{attachmentID}',
# Issue Events Requests for viewing and updating issue workflow events.
'issues_events': '/{projectID}/issues/{itemID}/events',
'issues_events_specific': '/{projectID}/issues/{itemID}/events/{eventID}',
'issues_events_attachments': '/{projectID}/issues/{itemID}/events/{eventID}/attachments',
'issues_events_attachments_file': '/{projectID}/issues/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Issue foundByRecords Requests for viewing and updating issue Found by records.
'issues_foundByRecords': '/{projectID}/issues/{itemID}/foundByRecords',
'issues_foundByRecords_specific': '/{projectID}/issues/{itemID}/foundByRecords/{foundByRecordID}',
'issues_foundByRecords_attachments': '/{projectID}/issues/{itemID}/foundByRecords/{foundByRecordID}/attachments',
'issues_foundByRecords_attachments_file': '/{projectID}/issues/{itemID}/foundByRecords/{foundByRecordID}/attachments/{attachmentID}',
# Test Cases Requests for viewing and updating test cases.
'test_cases': '/{projectID}/testcases',
'test_cases_search': '/{projectID}/testcases/search',
'test_cases_specific': '/{projectID}/testcases/{itemID}',
# Test Case Attachments Requests for viewing and updating files attached to test cases.
'test_cases_attachments': '/{projectID}/testcases/{itemID}/attachments',
'test_cases_attachments_file': '/{projectID}/testcases/{itemID}/attachments/{attachmentID}',
# Test Case Events Requests for viewing and updating test case workflow events.
'test_cases_events': '/{projectID}/testcases/{itemID}/events',
'test_cases_events_specific': '/{projectID}/testcases/{itemID}/events/{eventID}',
'test_cases_events_attachments': '/{projectID}/testcases/{itemID}/events/{eventID}/attachments',
'test_cases_events_attachments_file': '/{projectID}/testcases/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Test Case Scripts Requests for viewing and updating scripts attached to test cases.
'test_cases_scripts': '/{projectID}/testcases/{itemID}/scripts',
# Test Case Steps Requests for viewing and updating test case steps.
'test_cases_steps': '/{projectID}/testcases/{itemID}/steps',
# Test Case Variants Requests for viewing and updating test case variants.
'test_cases_variants': '/{projectID}/testcases/{itemID}/variants',
# Test Runs Requests for viewing and updating test runs.
'test_runs': '/{projectID}/testruns',
'test_runs_generate': '/{projectID}/testruns/generate',
'test_runs_search': '/{projectID}/testruns/search',
'test_runs_specific': '/{projectID}/testruns/{itemID}',
# Test Run Attachments Requests for viewing and updating files attached to test runs.
'test_runs_attachments': '/{projectID}/testruns/{itemID}/attachments',
'test_runs_attachments_file': '/{projectID}/testruns/{itemID}/attachments/{attachmentID}',
# Test Run Events Requests for viewing and updating test run workflow events.
'test_runs_events': '/{projectID}/testruns/{itemID}/events',
'test_runs_events_specific': '/{projectID}/testruns/{itemID}/events/{eventID}',
'test_runs_events_attachments': '/{projectID}/testruns/{itemID}/events/{eventID}/attachments',
'test_runs_events_attachments_file': '/{projectID}/testruns/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Test Run Scripts Requests for viewing and updating scripts attached to test runs.
'test_runs_scripts': '/{projectID}/testruns/{itemID}/scripts',
# Test Run Steps Requests for viewing and updating test run steps.
'test_runs_steps': '/{projectID}/testruns/{itemID}/steps',
# Test Run Variants Requests for viewing and updating test run variants.
'test_runs_variants': '/{projectID}/testruns/{itemID}/variants',
# Requirements Requests for viewing and updating requirements.
'requirements': '/{projectID}/requirements',
'requirements_search': '/{projectID}/requirements/search',
'requirements_specific': '/{projectID}/requirements/{itemID}',
# Requirement Attachments Requests for viewing and updating files attached to requirements.
'requirements_attachments': '/{projectID}/requirements/{itemID}/attachments',
'requirements_attachments_file': '/{projectID}/requirements/{itemID}/attachments/{attachmentID}',
# Requirement Events Requests for viewing and updating requirement workflow events.
'requirements_events': '/{projectID}/requirements/{itemID}/events',
'requirements_events_specific': '/{projectID}/requirements/{itemID}/events/{eventID}',
'requirements_events_attachments': '/{projectID}/requirements/{itemID}/events/{eventID}/attachments',
'requirements_events_attachments_file': '/{projectID}/requirements/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Requirement Documents Requests for viewing requirement documents that contain a specific requirement.
'requirements_documents': '/{projectID}/requirements/{itemID}/documents',
# Requirement Versions Requests for viewing requirement versions.
'requirements_versions': '/{projectID}/requirements/{itemID}/versions',
# Documents Requests for viewing and udpating requirement documents.
'documents': '/{projectID}/documents',
'documents_search': '/{projectID}/documents/search',
'documents_specific': '/{projectID}/documents/{itemID}',
# Document Attachments Requests for viewing and updating files attached to requirement documents.
'documents_attachments': '/{projectID}/documents/{itemID}/attachments',
'documents_attachments_file': '/{projectID}/documents/{itemID}/attachments/{attachmentID}',
# Document Events Requests for viewing and updating requirement document workflow events.
'documents_events': '/{projectID}/documents/{itemID}/events',
'documents_events_specific': '/{projectID}/documents/{itemID}/events/{eventID}',
'documents_events_attachments': '/{projectID}/documents/{itemID}/events/{eventID}/attachments',
'documents_events_attachments_file': '/{projectID}/documents/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Document Snapshots Requests for creating and viewing requirement document snapshots.
'documents_snapshots': '/{projectID}/documents/{itemID}/snapshots',
# Document Trees Requests for viewing and updating requirement document trees.
'document_trees': '/{projectID}/documentTrees/{itemID}',
'document_trees_nodes': '/{projectID}/documentTrees/{itemID}/nodes',
'document_trees_nodes_specific': '/{projectID}/documentTrees/{itemID}/nodes/{nodeID}',
'document_trees_nodes_child_nodes': '/{projectID}/documentTrees/{itemID}/nodes/{nodeID}/childNodes',
# Files Requests for retrieving files.
'files': '/{projectID}/files/{encodedFileID}',
# Misc Miscellaneous requests.
'not_yet_implemented': '/NotYetImplemented'
} | helixalm/const.py | __version__ = '0.0.1'
# Helix ALM REST API: http://help.seapine.com/helixalm/rest-api/index.html
API_PATH = {
# Projects Requests for retrieving and switching projects.
'projects': '/projects',
# Security Requests related to security.
'security': '/{projectID}/token',
# Rate Limits Requests related to rate limits.
'rate_limits': '/{projectID}/ratelimits',
# Issues Requests for viewing and updating issues.
'issues': '/{projectID}/issues',
'issues_search': '/{projectID}/issues/search',
'issues_specific': '/{projectID}/issues/{itemID}',
# Issue Attachments Requests for viewing and updating files attached to issues.
'issues_attachments': '/{projectID}/issues/{itemID}/attachments',
'issues_attachments_file': '/{projectID}/issues/{itemID}/attachments/{attachmentID}',
# Issue Events Requests for viewing and updating issue workflow events.
'issues_events': '/{projectID}/issues/{itemID}/events',
'issues_events_specific': '/{projectID}/issues/{itemID}/events/{eventID}',
'issues_events_attachments': '/{projectID}/issues/{itemID}/events/{eventID}/attachments',
'issues_events_attachments_file': '/{projectID}/issues/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Issue foundByRecords Requests for viewing and updating issue Found by records.
'issues_foundByRecords': '/{projectID}/issues/{itemID}/foundByRecords',
'issues_foundByRecords_specific': '/{projectID}/issues/{itemID}/foundByRecords/{foundByRecordID}',
'issues_foundByRecords_attachments': '/{projectID}/issues/{itemID}/foundByRecords/{foundByRecordID}/attachments',
'issues_foundByRecords_attachments_file': '/{projectID}/issues/{itemID}/foundByRecords/{foundByRecordID}/attachments/{attachmentID}',
# Test Cases Requests for viewing and updating test cases.
'test_cases': '/{projectID}/testcases',
'test_cases_search': '/{projectID}/testcases/search',
'test_cases_specific': '/{projectID}/testcases/{itemID}',
# Test Case Attachments Requests for viewing and updating files attached to test cases.
'test_cases_attachments': '/{projectID}/testcases/{itemID}/attachments',
'test_cases_attachments_file': '/{projectID}/testcases/{itemID}/attachments/{attachmentID}',
# Test Case Events Requests for viewing and updating test case workflow events.
'test_cases_events': '/{projectID}/testcases/{itemID}/events',
'test_cases_events_specific': '/{projectID}/testcases/{itemID}/events/{eventID}',
'test_cases_events_attachments': '/{projectID}/testcases/{itemID}/events/{eventID}/attachments',
'test_cases_events_attachments_file': '/{projectID}/testcases/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Test Case Scripts Requests for viewing and updating scripts attached to test cases.
'test_cases_scripts': '/{projectID}/testcases/{itemID}/scripts',
# Test Case Steps Requests for viewing and updating test case steps.
'test_cases_steps': '/{projectID}/testcases/{itemID}/steps',
# Test Case Variants Requests for viewing and updating test case variants.
'test_cases_variants': '/{projectID}/testcases/{itemID}/variants',
# Test Runs Requests for viewing and updating test runs.
'test_runs': '/{projectID}/testruns',
'test_runs_generate': '/{projectID}/testruns/generate',
'test_runs_search': '/{projectID}/testruns/search',
'test_runs_specific': '/{projectID}/testruns/{itemID}',
# Test Run Attachments Requests for viewing and updating files attached to test runs.
'test_runs_attachments': '/{projectID}/testruns/{itemID}/attachments',
'test_runs_attachments_file': '/{projectID}/testruns/{itemID}/attachments/{attachmentID}',
# Test Run Events Requests for viewing and updating test run workflow events.
'test_runs_events': '/{projectID}/testruns/{itemID}/events',
'test_runs_events_specific': '/{projectID}/testruns/{itemID}/events/{eventID}',
'test_runs_events_attachments': '/{projectID}/testruns/{itemID}/events/{eventID}/attachments',
'test_runs_events_attachments_file': '/{projectID}/testruns/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Test Run Scripts Requests for viewing and updating scripts attached to test runs.
'test_runs_scripts': '/{projectID}/testruns/{itemID}/scripts',
# Test Run Steps Requests for viewing and updating test run steps.
'test_runs_steps': '/{projectID}/testruns/{itemID}/steps',
# Test Run Variants Requests for viewing and updating test run variants.
'test_runs_variants': '/{projectID}/testruns/{itemID}/variants',
# Requirements Requests for viewing and updating requirements.
'requirements': '/{projectID}/requirements',
'requirements_search': '/{projectID}/requirements/search',
'requirements_specific': '/{projectID}/requirements/{itemID}',
# Requirement Attachments Requests for viewing and updating files attached to requirements.
'requirements_attachments': '/{projectID}/requirements/{itemID}/attachments',
'requirements_attachments_file': '/{projectID}/requirements/{itemID}/attachments/{attachmentID}',
# Requirement Events Requests for viewing and updating requirement workflow events.
'requirements_events': '/{projectID}/requirements/{itemID}/events',
'requirements_events_specific': '/{projectID}/requirements/{itemID}/events/{eventID}',
'requirements_events_attachments': '/{projectID}/requirements/{itemID}/events/{eventID}/attachments',
'requirements_events_attachments_file': '/{projectID}/requirements/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Requirement Documents Requests for viewing requirement documents that contain a specific requirement.
'requirements_documents': '/{projectID}/requirements/{itemID}/documents',
# Requirement Versions Requests for viewing requirement versions.
'requirements_versions': '/{projectID}/requirements/{itemID}/versions',
# Documents Requests for viewing and udpating requirement documents.
'documents': '/{projectID}/documents',
'documents_search': '/{projectID}/documents/search',
'documents_specific': '/{projectID}/documents/{itemID}',
# Document Attachments Requests for viewing and updating files attached to requirement documents.
'documents_attachments': '/{projectID}/documents/{itemID}/attachments',
'documents_attachments_file': '/{projectID}/documents/{itemID}/attachments/{attachmentID}',
# Document Events Requests for viewing and updating requirement document workflow events.
'documents_events': '/{projectID}/documents/{itemID}/events',
'documents_events_specific': '/{projectID}/documents/{itemID}/events/{eventID}',
'documents_events_attachments': '/{projectID}/documents/{itemID}/events/{eventID}/attachments',
'documents_events_attachments_file': '/{projectID}/documents/{itemID}/events/{eventID}/attachments/{attachmentID}',
# Document Snapshots Requests for creating and viewing requirement document snapshots.
'documents_snapshots': '/{projectID}/documents/{itemID}/snapshots',
# Document Trees Requests for viewing and updating requirement document trees.
'document_trees': '/{projectID}/documentTrees/{itemID}',
'document_trees_nodes': '/{projectID}/documentTrees/{itemID}/nodes',
'document_trees_nodes_specific': '/{projectID}/documentTrees/{itemID}/nodes/{nodeID}',
'document_trees_nodes_child_nodes': '/{projectID}/documentTrees/{itemID}/nodes/{nodeID}/childNodes',
# Files Requests for retrieving files.
'files': '/{projectID}/files/{encodedFileID}',
# Misc Miscellaneous requests.
'not_yet_implemented': '/NotYetImplemented'
} | 0.436382 | 0.068475 |
import substratools as tools
import os
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
# input image dimensions
img_rows, img_cols = 28, 28
input_shape = (img_rows, img_cols, 1)
num_classes = 10
class Algo(tools.algo.Algo):
def _normalize_X(self, X):
if K.image_data_format() == "channels_first":
X = X.reshape(X.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
X = X.reshape(X.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
X = X.astype("float32")
X /= 255
print(f"X shape: {X.shape}")
print(f"{X.shape[0]} samples")
return X
def _init_new_model(self):
model = Sequential()
model.add(
Conv2D(32, kernel_size=(3, 3), activation="relu", input_shape=input_shape)
)
model.add(Conv2D(64, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation="softmax"))
model.compile(
loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=["accuracy"],
)
return model
def train(self, X, y, models, rank):
X = self._normalize_X(X)
# convert class vectors to binary class matrices
y = keras.utils.to_categorical(y, num_classes)
model = self._init_new_model()
model.fit(
X,
y,
batch_size=128,
epochs=1,
verbose=1,
)
return model
def predict(self, X, model):
X = self._normalize_X(X)
y_pred = model.predict_classes(X, verbose=0)
return y_pred
def load_model(self, path):
with open(path, "rb") as f:
return keras.models.load_model(f)
def save_model(self, model, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as f:
model.save(f)
if __name__ == "__main__":
tools.algo.execute(Algo()) | examples/mnist/assets/algo_cnn/algo.py | import substratools as tools
import os
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
# input image dimensions
img_rows, img_cols = 28, 28
input_shape = (img_rows, img_cols, 1)
num_classes = 10
class Algo(tools.algo.Algo):
def _normalize_X(self, X):
if K.image_data_format() == "channels_first":
X = X.reshape(X.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
X = X.reshape(X.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
X = X.astype("float32")
X /= 255
print(f"X shape: {X.shape}")
print(f"{X.shape[0]} samples")
return X
def _init_new_model(self):
model = Sequential()
model.add(
Conv2D(32, kernel_size=(3, 3), activation="relu", input_shape=input_shape)
)
model.add(Conv2D(64, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation="softmax"))
model.compile(
loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=["accuracy"],
)
return model
def train(self, X, y, models, rank):
X = self._normalize_X(X)
# convert class vectors to binary class matrices
y = keras.utils.to_categorical(y, num_classes)
model = self._init_new_model()
model.fit(
X,
y,
batch_size=128,
epochs=1,
verbose=1,
)
return model
def predict(self, X, model):
X = self._normalize_X(X)
y_pred = model.predict_classes(X, verbose=0)
return y_pred
def load_model(self, path):
with open(path, "rb") as f:
return keras.models.load_model(f)
def save_model(self, model, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as f:
model.save(f)
if __name__ == "__main__":
tools.algo.execute(Algo()) | 0.837221 | 0.341761 |
import os
from collections import defaultdict
import threading
from tempfile import NamedTemporaryFile
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
try:
from functools import lru_cache # python 3
except ImportError:
from cachetools.func import lru_cache
import pycurl
from skimage.io import imread
import numpy as np
import os
from collections import deque
try:
import signal
from signal import SIGPIPE, SIG_IGN
except ImportError:
pass
else:
signal.signal(SIGPIPE, SIG_IGN)
NUM_WORKERS = 5
MAX_RETRIES = 5
def _on_fail(shape=(8, 256, 256), dtype=np.float32):
return np.zeros(shape, dtype=dtype)
def _load_data(fp):
try:
arr = imread(fp)
if len(arr.shape) == 3:
arr = np.rollaxis(arr, 2, 0)
else:
arr = np.expand_dims(arr, axis=0)
except Exception as e:
arr = _on_fail()
finally:
os.remove(fp)
return arr
def _init_curl(NOSIGNAL=1, CONNECTTIMEOUT=120, TIMEOUT=300):
_curl = pycurl.Curl()
_curl.setopt(pycurl.NOSIGNAL, NOSIGNAL)
_curl.setopt(pycurl.CONNECTTIMEOUT, CONNECTTIMEOUT)
_curl.setopt(pycurl.TIMEOUT, TIMEOUT)
return _curl
def _load_curl(url, token, index, _curl):
_, ext = os.path.splitext(urlparse(url).path)
fd = NamedTemporaryFile(prefix='gbdxtools', suffix=ext, delete=False)
_curl.setopt(pycurl.WRITEDATA, fd.file)
_curl.setopt(pycurl.URL, url)
_curl.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer {}'.format(token)])
_curl.index = index
_curl.token = token
_curl.url = url
_curl.fd = fd
return _curl
def _fd_handler(fd, delete=True):
fd.flush()
fd.close()
if delete:
os.remove(fd.name)
def _cleanup(crec, cmulti):
for _curl in crec:
_curl.close()
cmulti.close()
def load_urls(collection, max_workers=64, max_retries=MAX_RETRIES, shape=(8,256,256),
NOSIGNAL=1, CONNECTTIMEOUT=120, TIMEOUT=300):
ntasks = len(collection)
taskq = deque(collection)
crec = [_init_curl() for _ in range(min(max_workers, ntasks))]
curlq = deque(crec)
runcount = defaultdict(int)
results = defaultdict(_on_fail)
cmulti = pycurl.CurlMulti()
nprocessed = 0
while ntasks > nprocessed:
while taskq and curlq:
url, token, index = taskq.popleft()
index = tuple(index)
_curl = curlq.popleft()
_curl = _load_curl(url, token, index, _curl)
# increment attempt number and add to multi
runcount[index] += 1
cmulti.add_handle(_curl)
while True:
ret, nhandles = cmulti.perform()
if ret != pycurl.E_CALL_MULTI_PERFORM:
break
while True:
nq, suc, failed = cmulti.info_read()
for _curl in suc:
results[_curl.index] = _curl.fd.name
_fd_handler(_curl.fd, delete=False)
_curl.fd = None
cmulti.remove_handle(_curl)
curlq.append(_curl)
nprocessed += 1
for _curl, err_num, err_msg in failed:
_fd_handler(_curl.fd)
_curl.fd = None
if runcount[_curl.index] < max_retries:
taskq.append([_curl.url, _curl.token, _curl.index])
else:
nprocessed += 1
cmulti.remove_handle(_curl)
curlq.append(_curl)
if nq == 0:
break
_cleanup(crec, cmulti)
return {idx: _load_data(results[idx]) if idx in results else _on_fail() for idx in runcount.keys()} | gbdxtools/rda/fetch/conc/libcurl/select.py | import os
from collections import defaultdict
import threading
from tempfile import NamedTemporaryFile
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
try:
from functools import lru_cache # python 3
except ImportError:
from cachetools.func import lru_cache
import pycurl
from skimage.io import imread
import numpy as np
import os
from collections import deque
try:
import signal
from signal import SIGPIPE, SIG_IGN
except ImportError:
pass
else:
signal.signal(SIGPIPE, SIG_IGN)
NUM_WORKERS = 5
MAX_RETRIES = 5
def _on_fail(shape=(8, 256, 256), dtype=np.float32):
return np.zeros(shape, dtype=dtype)
def _load_data(fp):
try:
arr = imread(fp)
if len(arr.shape) == 3:
arr = np.rollaxis(arr, 2, 0)
else:
arr = np.expand_dims(arr, axis=0)
except Exception as e:
arr = _on_fail()
finally:
os.remove(fp)
return arr
def _init_curl(NOSIGNAL=1, CONNECTTIMEOUT=120, TIMEOUT=300):
_curl = pycurl.Curl()
_curl.setopt(pycurl.NOSIGNAL, NOSIGNAL)
_curl.setopt(pycurl.CONNECTTIMEOUT, CONNECTTIMEOUT)
_curl.setopt(pycurl.TIMEOUT, TIMEOUT)
return _curl
def _load_curl(url, token, index, _curl):
_, ext = os.path.splitext(urlparse(url).path)
fd = NamedTemporaryFile(prefix='gbdxtools', suffix=ext, delete=False)
_curl.setopt(pycurl.WRITEDATA, fd.file)
_curl.setopt(pycurl.URL, url)
_curl.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer {}'.format(token)])
_curl.index = index
_curl.token = token
_curl.url = url
_curl.fd = fd
return _curl
def _fd_handler(fd, delete=True):
fd.flush()
fd.close()
if delete:
os.remove(fd.name)
def _cleanup(crec, cmulti):
for _curl in crec:
_curl.close()
cmulti.close()
def load_urls(collection, max_workers=64, max_retries=MAX_RETRIES, shape=(8,256,256),
NOSIGNAL=1, CONNECTTIMEOUT=120, TIMEOUT=300):
ntasks = len(collection)
taskq = deque(collection)
crec = [_init_curl() for _ in range(min(max_workers, ntasks))]
curlq = deque(crec)
runcount = defaultdict(int)
results = defaultdict(_on_fail)
cmulti = pycurl.CurlMulti()
nprocessed = 0
while ntasks > nprocessed:
while taskq and curlq:
url, token, index = taskq.popleft()
index = tuple(index)
_curl = curlq.popleft()
_curl = _load_curl(url, token, index, _curl)
# increment attempt number and add to multi
runcount[index] += 1
cmulti.add_handle(_curl)
while True:
ret, nhandles = cmulti.perform()
if ret != pycurl.E_CALL_MULTI_PERFORM:
break
while True:
nq, suc, failed = cmulti.info_read()
for _curl in suc:
results[_curl.index] = _curl.fd.name
_fd_handler(_curl.fd, delete=False)
_curl.fd = None
cmulti.remove_handle(_curl)
curlq.append(_curl)
nprocessed += 1
for _curl, err_num, err_msg in failed:
_fd_handler(_curl.fd)
_curl.fd = None
if runcount[_curl.index] < max_retries:
taskq.append([_curl.url, _curl.token, _curl.index])
else:
nprocessed += 1
cmulti.remove_handle(_curl)
curlq.append(_curl)
if nq == 0:
break
_cleanup(crec, cmulti)
return {idx: _load_data(results[idx]) if idx in results else _on_fail() for idx in runcount.keys()} | 0.205894 | 0.095392 |
import pytest
from django.test import TestCase, override_settings
from .utils import MIDDLEWARES_FOR_TESTING
class TestResponseFunctionWithoutUser(TestCase):
def test_middleware_simple_get_request(self):
try:
self.client.get('/restframework/simple/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_request(self):
try:
self.client.post('/restframework/simple/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_request(self):
try:
self.client.put('/restframework/simple/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_request(self):
try:
self.client.delete('/restframework/simple/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_get_with_query_string_request(self):
try:
self.client.get('/restframework/simple_with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_with_query_string_request(self):
try:
self.client.post('/restframework/simple_with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_with_query_string_request(self):
try:
self.client.put('/restframework/simple_with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_with_query_string_request(self):
try:
self.client.delete('/restframework/simple_with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
@override_settings(MIDDLEWARE=MIDDLEWARES_FOR_TESTING)
class TestResponseFunctionWithUser(TestCase):
def test_middleware_simple_get_request(self):
try:
self.client.get('/restframework/simple/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_request(self):
try:
self.client.post('/restframework/simple/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_request(self):
try:
self.client.put('/restframework/simple/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_request(self):
try:
self.client.delete('/restframework/simple/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_get_with_query_string_request(self):
try:
self.client.get('/restframework/simple_with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_with_query_string_request(self):
try:
self.client.post('/restframework/simple_with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_with_query_string_request(self):
try:
self.client.put('/restframework/simple_with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_with_query_string_request(self):
try:
self.client.delete('/restframework/simple_with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
class TestResponseClassWithoutUser(TestCase):
def test_middleware_simple_get_request(self):
try:
self.client.get('/restframework/simple/class/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_request(self):
try:
self.client.post('/restframework/simple/class/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_request(self):
try:
self.client.put('/restframework/simple/class/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_request(self):
try:
self.client.delete('/restframework/simple/class/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_get_with_query_string_request(self):
try:
self.client.get('/restframework/simple/class/with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_with_query_string_request(self):
try:
self.client.post('/restframework/simple/class/with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_with_query_string_request(self):
try:
self.client.put('/restframework/simple/class/with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_with_query_string_request(self):
try:
self.client.delete('/restframework/simple/class/with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
@override_settings(MIDDLEWARE=MIDDLEWARES_FOR_TESTING)
class TestResponseClassWithUser(TestCase):
def test_middleware_simple_get_request(self):
try:
self.client.get('/restframework/simple/class/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_request(self):
try:
self.client.post('/restframework/simple/class/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_request(self):
try:
self.client.put('/restframework/simple/class/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_request(self):
try:
self.client.delete('/restframework/simple/class/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_get_with_query_string_request(self):
try:
self.client.get('/restframework/simple/class/with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_with_query_string_request(self):
try:
self.client.post('/restframework/simple/class/with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_with_query_string_request(self):
try:
self.client.put('/restframework/simple/class/with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_with_query_string_request(self):
try:
self.client.delete('/restframework/simple/class/with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}") | tests/test_restframework_response.py | import pytest
from django.test import TestCase, override_settings
from .utils import MIDDLEWARES_FOR_TESTING
class TestResponseFunctionWithoutUser(TestCase):
def test_middleware_simple_get_request(self):
try:
self.client.get('/restframework/simple/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_request(self):
try:
self.client.post('/restframework/simple/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_request(self):
try:
self.client.put('/restframework/simple/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_request(self):
try:
self.client.delete('/restframework/simple/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_get_with_query_string_request(self):
try:
self.client.get('/restframework/simple_with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_with_query_string_request(self):
try:
self.client.post('/restframework/simple_with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_with_query_string_request(self):
try:
self.client.put('/restframework/simple_with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_with_query_string_request(self):
try:
self.client.delete('/restframework/simple_with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
@override_settings(MIDDLEWARE=MIDDLEWARES_FOR_TESTING)
class TestResponseFunctionWithUser(TestCase):
def test_middleware_simple_get_request(self):
try:
self.client.get('/restframework/simple/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_request(self):
try:
self.client.post('/restframework/simple/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_request(self):
try:
self.client.put('/restframework/simple/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_request(self):
try:
self.client.delete('/restframework/simple/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_get_with_query_string_request(self):
try:
self.client.get('/restframework/simple_with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_with_query_string_request(self):
try:
self.client.post('/restframework/simple_with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_with_query_string_request(self):
try:
self.client.put('/restframework/simple_with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_with_query_string_request(self):
try:
self.client.delete('/restframework/simple_with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
class TestResponseClassWithoutUser(TestCase):
def test_middleware_simple_get_request(self):
try:
self.client.get('/restframework/simple/class/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_request(self):
try:
self.client.post('/restframework/simple/class/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_request(self):
try:
self.client.put('/restframework/simple/class/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_request(self):
try:
self.client.delete('/restframework/simple/class/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_get_with_query_string_request(self):
try:
self.client.get('/restframework/simple/class/with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_with_query_string_request(self):
try:
self.client.post('/restframework/simple/class/with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_with_query_string_request(self):
try:
self.client.put('/restframework/simple/class/with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_with_query_string_request(self):
try:
self.client.delete('/restframework/simple/class/with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
@override_settings(MIDDLEWARE=MIDDLEWARES_FOR_TESTING)
class TestResponseClassWithUser(TestCase):
def test_middleware_simple_get_request(self):
try:
self.client.get('/restframework/simple/class/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_request(self):
try:
self.client.post('/restframework/simple/class/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_request(self):
try:
self.client.put('/restframework/simple/class/', data={'data': 'data'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_request(self):
try:
self.client.delete('/restframework/simple/class/')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_get_with_query_string_request(self):
try:
self.client.get('/restframework/simple/class/with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_post_with_query_string_request(self):
try:
self.client.post('/restframework/simple/class/with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_put_with_query_string_request(self):
try:
self.client.put('/restframework/simple/class/with_query_string/?data=data', data={'data_json': 'data_json'}, content_type='application/json')
except Exception as e:
pytest.fail(f"Error: {e}")
def test_middleware_simple_delete_with_query_string_request(self):
try:
self.client.delete('/restframework/simple/class/with_query_string/', {'data': 'data'})
except Exception as e:
pytest.fail(f"Error: {e}") | 0.279828 | 0.197039 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from random import shuffle, randint
from six.moves import range
from itertools import product
from . import (
BaseMazeGame,
WithWaterAndBlocksMixin,
RewardOnEndMixin,
BaseVocabulary,
AbsoluteLocationVocabulary,
)
from mazebase.utils import creationutils
from mazebase.utils.mazeutils import populate_kwargs, MazeException, choice
from mazebase.items import agents
import mazebase.items as mi
class MovingAgent(agents.SingleTileMovable):
'''Agents we only use once don't have to be put in items/Agent.py :)'''
pass
# So we don't have to type as much
class GoalType(RewardOnEndMixin, WithWaterAndBlocksMixin, BaseVocabulary):
pass
def _est(game, s, e):
'''shorthand to estimate reward for an agent to move from s to e'''
visited, path = creationutils.dijkstra(
game, s, creationutils.agent_movefunc, True)
return -visited[e] # Returns distance, which is negation of reward
class SingleGoalApproximateRewardMixin(BaseMazeGame):
def _calculate_approximate_reward(self):
r = _est(self, self.agent.location, self.goal.location)
return super(SingleGoalApproximateRewardMixin,
self)._calculate_approximate_reward() + r
class SingleGoal(GoalType):
''' Agent moves to a single goal '''
def _reset(self):
super(SingleGoal, self)._reset()
loc = choice(creationutils.empty_locations(self))
self.goal = mi.Goal(location=loc)
self._add_item(self.goal)
loc = choice(creationutils.empty_locations(self, bad_blocks=[mi.Block]))
self.agent = MovingAgent(location=loc)
self._add_agent(self.agent, "SingleGoalAgent")
visited, _ = creationutils.dijkstra(self, loc,
creationutils.agent_movefunc)
if self.goal.location not in visited:
raise MazeException("No path to goal")
def _side_information(self):
return super(SingleGoal, self)._side_information() + \
[[self.FEATURE.GOTO] + self.goal.featurize()]
def _finished(self):
return self.agent.location == self.goal.location
class MultiGoals(GoalType):
''' Agent must visit each goal in order, without penalty for visiting out
of order '''
__properties = dict(
n_goals=3,
)
def __init__(self, **kwargs):
populate_kwargs(self, self.__class__.__properties, kwargs)
super(MultiGoals, self).__init__(**kwargs)
def _reset(self):
super(MultiGoals, self)._reset()
self.goals = []
for i in range(self.n_goals):
x, y = choice(creationutils.empty_locations(self))
self.goals.append(mi.Goal(location=(x, y), id=i))
self._add_item(self.goals[i])
shuffle(self.goals)
self.v = 0
x, y = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = MovingAgent(location=(x, y))
self._add_agent(self.agent, "MultiGoalsAgent")
visited, _ = creationutils.dijkstra(self, (x, y),
creationutils.agent_movefunc)
if not all(goal.location in visited for goal in self.goals):
raise MazeException("No path to goal")
def _side_information(self):
return super(MultiGoals, self)._side_information() + \
[[self.FEATURE.ORDERED_OBJ[i], self.FEATURE.GOTO] + x.featurize()
for i, x in enumerate(self.goals)]
def _step(self):
if self.agent.location == self.goals[self.v].location:
self.v = self.v + 1
def _finished(self):
return self.v == self.n_goals
def _calculate_approximate_reward(self):
locs = [self.agent.location] + [g.location for g in self.goals]
r = sum(_est(self, l1, l2) for l1, l2 in zip(locs[:-1], locs[1:]))
return super(MultiGoals, self)._calculate_approximate_reward() + r
class TogglingAgent(agents.SingleTileMovable, agents.Toggling):
pass
class ConditionedGoals(GoalType):
''' Agent must visit goals conditioned on the color of a switch. Penalty
for visiting a wrong goal '''
__properties = dict(
n_goals=3,
n_colors=3,
goal_penalty=0.2
)
def __init__(self, **kwargs):
populate_kwargs(self, self.__class__.__properties, kwargs)
super(ConditionedGoals, self).__init__(**kwargs)
def _reset(self):
super(ConditionedGoals, self)._reset()
x, y = choice(creationutils.empty_locations(self))
self.sw = mi.Switch(
location=(x, y),
nstates=self.n_colors,
start_state=choice(range(self.n_colors)),
)
self._add_item(self.sw)
self.goals = []
for i in range(self.n_goals):
x, y = choice(creationutils.empty_locations(self))
self.goals.append(mi.Goal(location=(x, y), id=i))
self._add_item(self.goals[i])
self.conditions = [randint(0, self.n_goals - 1) for _ in self.goals]
x, y = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = TogglingAgent(location=(x, y))
self._add_agent(self.agent, "ConditionedGoalsAgent")
visited, _ = creationutils.dijkstra(self, (x, y),
creationutils.agent_movefunc)
if (self.sw.location not in visited or
not any(self.goals[i].location in visited
for i in set(self.conditions))):
raise MazeException("No path to goal")
def _get_reward(self, id):
reward = super(ConditionedGoals, self)._get_reward(id)
forbiddens = set(g.location for g in self.goals)
if self.sw.state < len(self.conditions):
forbiddens.remove(
self.goals[self.conditions[self.sw.state]].location)
if self.agent.location in forbiddens:
reward -= self.goal_penalty
return reward
def _finished(self):
if self.sw.state >= len(self.conditions):
return False
return self.agent.location == \
self.goals[self.conditions[self.sw.state]].location
def _side_information(self):
# Featurize the goals, and add it to the features of some dummy
# switches in the right state
return super(ConditionedGoals, self)._side_information() + \
[
[self.FEATURE.IF] +
mi.Switch(nstates=self.n_goals, start_state=i).featurize() +
[self.FEATURE.GOTO] +
self.goals[st].featurize()
for i, st in enumerate(self.conditions)]
def _calculate_approximate_reward(self):
if self.sw.state >= len(self.conditions):
best = -1e100
else:
best = _est(self, self.agent.location,
self.goals[self.conditions[self.sw.state]].location)
sw_dist = _est(self, self.agent.location, self.sw.location)
for i in range(min(self.n_goals, self.n_colors)):
goal_loc = self.goals[self.conditions[i]].location
best = max(
best,
_est(self, self.sw.location, goal_loc) -
((i - self.sw.state) % self.n_colors) * self.turn_penalty +
sw_dist)
return super(ConditionedGoals, self)._calculate_approximate_reward() +\
best + self.goal_penalty
def _accumulate_approximate_rewards(self):
super(ConditionedGoals, self)._accumulate_approximate_rewards()
for x, y in product(range(self.width), range(self.height)):
if self._tile_get_block((x, y), mi.Goal) is not None:
self._approx_reward_map[x][y] += -self.goal_penalty
class Exclusion(GoalType):
''' Agent must visit all goals except those stated in side_information '''
__properties = dict(
goal_penalty=0.5, # penalty for stepping on excluded goal
n_goals=3,
visit_min=1,
visit_max=-1, # -1 = n_goals
)
def __init__(self, **kwargs):
populate_kwargs(self, self.__class__.__properties, kwargs)
super(Exclusion, self).__init__(**kwargs)
def _reset(self):
super(Exclusion, self)._reset()
if self.visit_min < 1:
raise MazeException("visit_min is not >= 1")
if self.visit_max == -1:
self.visit_max = self.n_goals
self.visit = list(range(self.n_goals))
shuffle(self.visit)
to_visit = randint(self.visit_min, self.visit_max)
self.exclude = self.visit[to_visit:]
self.visit = self.visit[:to_visit]
self.visit = dict((x, False) for x in self.visit)
self.goals = []
for i in range(self.n_goals):
x, y = choice(creationutils.empty_locations(self))
self.goals.append(mi.Goal(location=(x, y), id=i))
self._add_item(self.goals[i])
x, y = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = TogglingAgent(location=(x, y))
self._add_agent(self.agent, "ExclusionAgent")
visited, _ = creationutils.dijkstra(self, (x, y),
creationutils.agent_movefunc)
if not all(goal.location in visited for goal in self.goals):
raise MazeException("No path to goal")
def _step(self):
for i in self.visit.keys():
if self.agent.location == self.goals[i].location:
self.visit[i] = True
def _finished(self):
return all(self.visit.values())
def _side_information(self):
return super(Exclusion, self)._side_information() + \
[[self.FEATURE.GOTO, self.FEATURE.ALL]] + \
[[self.FEATURE.AVOID] +
self.goals[i].featurize()
for i in self.exclude]
def _get_reward(self, id):
reward = super(Exclusion, self)._get_reward(id)
for i in self.exclude:
if self.agent.location == self.goals[i].location:
reward -= self.goal_penalty
return reward
def _calculate_approximate_reward(self):
prev = self.agent.location
visited = dict((x, False) for x in self.visit)
so_far = 0
for _ in self.visit:
best_n = None
best = -1e100
for g in [g for g, b in visited.items() if not b]:
t = _est(self, prev, self.goals[g].location)
if t > best:
best = t
best_n = g
prev = self.goals[best_n].location
so_far += best
visited[best_n] = True
return super(Exclusion, self)._calculate_approximate_reward() + so_far
def _accumulate_approximate_rewards(self):
super(Exclusion, self)._accumulate_approximate_rewards()
excludes = [self.goals[i].location for i in self.exclude]
for x, y in product(range(self.width), range(self.height)):
if (x, y) in excludes:
self._approx_reward_map[x][y] += -self.goal_penalty
class GotoType(AbsoluteLocationVocabulary,
GoalType,
):
pass
class Goto(SingleGoalApproximateRewardMixin, GotoType):
''' Agent must go to an absolute location '''
def _reset(self):
super(Goto, self)._reset()
loc = choice(creationutils.empty_locations(self))
self.goal = mi.Goal(location=loc, visible=False)
self._add_item(self.goal)
loc = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = MovingAgent(location=loc)
self._add_agent(self.agent, "GotoAgent")
visited, _ = creationutils.dijkstra(self, loc,
creationutils.agent_movefunc)
if self.goal.location not in visited:
raise MazeException("No path to goal")
def _side_information(self):
return super(Goto, self)._side_information() + \
[[self.FEATURE.GOTO, self._coords2loc(*self.goal.location)]]
def _finished(self):
return self.agent.location == self.goal.location
class GotoHidden(SingleGoalApproximateRewardMixin, GotoType):
'''Agent must go to one of several goals, depending on side_information
'''
__properties = dict(
n_goals=3,
)
def __init__(self, **kwargs):
populate_kwargs(self, self.__class__.__properties, kwargs)
super(GotoHidden, self).__init__(**kwargs)
def _reset(self):
super(GotoHidden, self)._reset()
self.goals = []
for i in range(self.n_goals):
x, y = choice(creationutils.empty_locations(self))
self.goals.append(mi.Goal(location=(x, y), id=i, visible=False))
self._add_item(self.goals[i])
self.goal = choice(self.goals)
x, y = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = MovingAgent(location=(x, y))
self._add_agent(self.agent, "GotoHiddenAgent")
visited, _ = creationutils.dijkstra(self, (x, y),
creationutils.agent_movefunc)
if self.goal.location not in visited:
raise MazeException("No path to goal")
def _side_information(self):
return super(GotoHidden, self)._side_information() + \
[[self._coords2loc(*goal.location)] + goal.featurize()
for goal in self.goals] + \
[[self.FEATURE.GOTO] + self.goal.featurize()]
def _finished(self):
return self.agent.location == self.goal.location | py/mazebase/games/goal_based_games.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from random import shuffle, randint
from six.moves import range
from itertools import product
from . import (
BaseMazeGame,
WithWaterAndBlocksMixin,
RewardOnEndMixin,
BaseVocabulary,
AbsoluteLocationVocabulary,
)
from mazebase.utils import creationutils
from mazebase.utils.mazeutils import populate_kwargs, MazeException, choice
from mazebase.items import agents
import mazebase.items as mi
class MovingAgent(agents.SingleTileMovable):
'''Agents we only use once don't have to be put in items/Agent.py :)'''
pass
# So we don't have to type as much
class GoalType(RewardOnEndMixin, WithWaterAndBlocksMixin, BaseVocabulary):
pass
def _est(game, s, e):
'''shorthand to estimate reward for an agent to move from s to e'''
visited, path = creationutils.dijkstra(
game, s, creationutils.agent_movefunc, True)
return -visited[e] # Returns distance, which is negation of reward
class SingleGoalApproximateRewardMixin(BaseMazeGame):
def _calculate_approximate_reward(self):
r = _est(self, self.agent.location, self.goal.location)
return super(SingleGoalApproximateRewardMixin,
self)._calculate_approximate_reward() + r
class SingleGoal(GoalType):
''' Agent moves to a single goal '''
def _reset(self):
super(SingleGoal, self)._reset()
loc = choice(creationutils.empty_locations(self))
self.goal = mi.Goal(location=loc)
self._add_item(self.goal)
loc = choice(creationutils.empty_locations(self, bad_blocks=[mi.Block]))
self.agent = MovingAgent(location=loc)
self._add_agent(self.agent, "SingleGoalAgent")
visited, _ = creationutils.dijkstra(self, loc,
creationutils.agent_movefunc)
if self.goal.location not in visited:
raise MazeException("No path to goal")
def _side_information(self):
return super(SingleGoal, self)._side_information() + \
[[self.FEATURE.GOTO] + self.goal.featurize()]
def _finished(self):
return self.agent.location == self.goal.location
class MultiGoals(GoalType):
''' Agent must visit each goal in order, without penalty for visiting out
of order '''
__properties = dict(
n_goals=3,
)
def __init__(self, **kwargs):
populate_kwargs(self, self.__class__.__properties, kwargs)
super(MultiGoals, self).__init__(**kwargs)
def _reset(self):
super(MultiGoals, self)._reset()
self.goals = []
for i in range(self.n_goals):
x, y = choice(creationutils.empty_locations(self))
self.goals.append(mi.Goal(location=(x, y), id=i))
self._add_item(self.goals[i])
shuffle(self.goals)
self.v = 0
x, y = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = MovingAgent(location=(x, y))
self._add_agent(self.agent, "MultiGoalsAgent")
visited, _ = creationutils.dijkstra(self, (x, y),
creationutils.agent_movefunc)
if not all(goal.location in visited for goal in self.goals):
raise MazeException("No path to goal")
def _side_information(self):
return super(MultiGoals, self)._side_information() + \
[[self.FEATURE.ORDERED_OBJ[i], self.FEATURE.GOTO] + x.featurize()
for i, x in enumerate(self.goals)]
def _step(self):
if self.agent.location == self.goals[self.v].location:
self.v = self.v + 1
def _finished(self):
return self.v == self.n_goals
def _calculate_approximate_reward(self):
locs = [self.agent.location] + [g.location for g in self.goals]
r = sum(_est(self, l1, l2) for l1, l2 in zip(locs[:-1], locs[1:]))
return super(MultiGoals, self)._calculate_approximate_reward() + r
class TogglingAgent(agents.SingleTileMovable, agents.Toggling):
pass
class ConditionedGoals(GoalType):
''' Agent must visit goals conditioned on the color of a switch. Penalty
for visiting a wrong goal '''
__properties = dict(
n_goals=3,
n_colors=3,
goal_penalty=0.2
)
def __init__(self, **kwargs):
populate_kwargs(self, self.__class__.__properties, kwargs)
super(ConditionedGoals, self).__init__(**kwargs)
def _reset(self):
super(ConditionedGoals, self)._reset()
x, y = choice(creationutils.empty_locations(self))
self.sw = mi.Switch(
location=(x, y),
nstates=self.n_colors,
start_state=choice(range(self.n_colors)),
)
self._add_item(self.sw)
self.goals = []
for i in range(self.n_goals):
x, y = choice(creationutils.empty_locations(self))
self.goals.append(mi.Goal(location=(x, y), id=i))
self._add_item(self.goals[i])
self.conditions = [randint(0, self.n_goals - 1) for _ in self.goals]
x, y = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = TogglingAgent(location=(x, y))
self._add_agent(self.agent, "ConditionedGoalsAgent")
visited, _ = creationutils.dijkstra(self, (x, y),
creationutils.agent_movefunc)
if (self.sw.location not in visited or
not any(self.goals[i].location in visited
for i in set(self.conditions))):
raise MazeException("No path to goal")
def _get_reward(self, id):
reward = super(ConditionedGoals, self)._get_reward(id)
forbiddens = set(g.location for g in self.goals)
if self.sw.state < len(self.conditions):
forbiddens.remove(
self.goals[self.conditions[self.sw.state]].location)
if self.agent.location in forbiddens:
reward -= self.goal_penalty
return reward
def _finished(self):
if self.sw.state >= len(self.conditions):
return False
return self.agent.location == \
self.goals[self.conditions[self.sw.state]].location
def _side_information(self):
# Featurize the goals, and add it to the features of some dummy
# switches in the right state
return super(ConditionedGoals, self)._side_information() + \
[
[self.FEATURE.IF] +
mi.Switch(nstates=self.n_goals, start_state=i).featurize() +
[self.FEATURE.GOTO] +
self.goals[st].featurize()
for i, st in enumerate(self.conditions)]
def _calculate_approximate_reward(self):
if self.sw.state >= len(self.conditions):
best = -1e100
else:
best = _est(self, self.agent.location,
self.goals[self.conditions[self.sw.state]].location)
sw_dist = _est(self, self.agent.location, self.sw.location)
for i in range(min(self.n_goals, self.n_colors)):
goal_loc = self.goals[self.conditions[i]].location
best = max(
best,
_est(self, self.sw.location, goal_loc) -
((i - self.sw.state) % self.n_colors) * self.turn_penalty +
sw_dist)
return super(ConditionedGoals, self)._calculate_approximate_reward() +\
best + self.goal_penalty
def _accumulate_approximate_rewards(self):
super(ConditionedGoals, self)._accumulate_approximate_rewards()
for x, y in product(range(self.width), range(self.height)):
if self._tile_get_block((x, y), mi.Goal) is not None:
self._approx_reward_map[x][y] += -self.goal_penalty
class Exclusion(GoalType):
''' Agent must visit all goals except those stated in side_information '''
__properties = dict(
goal_penalty=0.5, # penalty for stepping on excluded goal
n_goals=3,
visit_min=1,
visit_max=-1, # -1 = n_goals
)
def __init__(self, **kwargs):
populate_kwargs(self, self.__class__.__properties, kwargs)
super(Exclusion, self).__init__(**kwargs)
def _reset(self):
super(Exclusion, self)._reset()
if self.visit_min < 1:
raise MazeException("visit_min is not >= 1")
if self.visit_max == -1:
self.visit_max = self.n_goals
self.visit = list(range(self.n_goals))
shuffle(self.visit)
to_visit = randint(self.visit_min, self.visit_max)
self.exclude = self.visit[to_visit:]
self.visit = self.visit[:to_visit]
self.visit = dict((x, False) for x in self.visit)
self.goals = []
for i in range(self.n_goals):
x, y = choice(creationutils.empty_locations(self))
self.goals.append(mi.Goal(location=(x, y), id=i))
self._add_item(self.goals[i])
x, y = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = TogglingAgent(location=(x, y))
self._add_agent(self.agent, "ExclusionAgent")
visited, _ = creationutils.dijkstra(self, (x, y),
creationutils.agent_movefunc)
if not all(goal.location in visited for goal in self.goals):
raise MazeException("No path to goal")
def _step(self):
for i in self.visit.keys():
if self.agent.location == self.goals[i].location:
self.visit[i] = True
def _finished(self):
return all(self.visit.values())
def _side_information(self):
return super(Exclusion, self)._side_information() + \
[[self.FEATURE.GOTO, self.FEATURE.ALL]] + \
[[self.FEATURE.AVOID] +
self.goals[i].featurize()
for i in self.exclude]
def _get_reward(self, id):
reward = super(Exclusion, self)._get_reward(id)
for i in self.exclude:
if self.agent.location == self.goals[i].location:
reward -= self.goal_penalty
return reward
def _calculate_approximate_reward(self):
prev = self.agent.location
visited = dict((x, False) for x in self.visit)
so_far = 0
for _ in self.visit:
best_n = None
best = -1e100
for g in [g for g, b in visited.items() if not b]:
t = _est(self, prev, self.goals[g].location)
if t > best:
best = t
best_n = g
prev = self.goals[best_n].location
so_far += best
visited[best_n] = True
return super(Exclusion, self)._calculate_approximate_reward() + so_far
def _accumulate_approximate_rewards(self):
super(Exclusion, self)._accumulate_approximate_rewards()
excludes = [self.goals[i].location for i in self.exclude]
for x, y in product(range(self.width), range(self.height)):
if (x, y) in excludes:
self._approx_reward_map[x][y] += -self.goal_penalty
class GotoType(AbsoluteLocationVocabulary,
GoalType,
):
pass
class Goto(SingleGoalApproximateRewardMixin, GotoType):
''' Agent must go to an absolute location '''
def _reset(self):
super(Goto, self)._reset()
loc = choice(creationutils.empty_locations(self))
self.goal = mi.Goal(location=loc, visible=False)
self._add_item(self.goal)
loc = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = MovingAgent(location=loc)
self._add_agent(self.agent, "GotoAgent")
visited, _ = creationutils.dijkstra(self, loc,
creationutils.agent_movefunc)
if self.goal.location not in visited:
raise MazeException("No path to goal")
def _side_information(self):
return super(Goto, self)._side_information() + \
[[self.FEATURE.GOTO, self._coords2loc(*self.goal.location)]]
def _finished(self):
return self.agent.location == self.goal.location
class GotoHidden(SingleGoalApproximateRewardMixin, GotoType):
'''Agent must go to one of several goals, depending on side_information
'''
__properties = dict(
n_goals=3,
)
def __init__(self, **kwargs):
populate_kwargs(self, self.__class__.__properties, kwargs)
super(GotoHidden, self).__init__(**kwargs)
def _reset(self):
super(GotoHidden, self)._reset()
self.goals = []
for i in range(self.n_goals):
x, y = choice(creationutils.empty_locations(self))
self.goals.append(mi.Goal(location=(x, y), id=i, visible=False))
self._add_item(self.goals[i])
self.goal = choice(self.goals)
x, y = choice(creationutils.empty_locations(self,
bad_blocks=[mi.Block]))
self.agent = MovingAgent(location=(x, y))
self._add_agent(self.agent, "GotoHiddenAgent")
visited, _ = creationutils.dijkstra(self, (x, y),
creationutils.agent_movefunc)
if self.goal.location not in visited:
raise MazeException("No path to goal")
def _side_information(self):
return super(GotoHidden, self)._side_information() + \
[[self._coords2loc(*goal.location)] + goal.featurize()
for goal in self.goals] + \
[[self.FEATURE.GOTO] + self.goal.featurize()]
def _finished(self):
return self.agent.location == self.goal.location | 0.750004 | 0.238002 |
from pyox.oozie import Oozie
from pyox.client import ServiceError
import argparse
import sys
import os
import json
from datetime import datetime
def oozie_start_command(client,argv):
cmdparser = argparse.ArgumentParser(prog='pyox oozie start',description='start')
cmdparser.add_argument(
'-p','--property',
dest='property',
action='append',
metavar=('name','value'),
nargs=2,
help="A property name/value pair (e.g., name=value)")
cmdparser.add_argument(
'-P','--properties',
dest='properties',
action='append',
nargs=1,
metavar=('file.json'),
help="Property name/value pairs in JSON format.")
cmdparser.add_argument(
'-d','--definition',
dest='definition',
nargs=1,
metavar=('file.xml'),
help="The workflow definition to copy")
cmdparser.add_argument(
'-cp','--copy',
dest='copy',
action='append',
metavar=('file or file=target'),
nargs=1,
help="A resource to copy (e.g., source or source=dest)")
cmdparser.add_argument(
'--namenode',
nargs=1,
metavar=('node[:port]'),
help="The name node for jobs")
cmdparser.add_argument(
'--tracker',
nargs=1,
metavar=('node[:port]'),
help="The job tracker for jobs")
cmdparser.add_argument(
'-v','--verbose',
action='store_true',
dest='verbose',
default=False,
help="Verbose")
cmdparser.add_argument(
'path',
help='The job path')
args = cmdparser.parse_args(argv)
if args.namenode is not None:
client.namenode = args.namenode
if args.tracker is not None:
client.addProperty('jobTracker',args.tracker)
properties = {}
if args.properties is not None:
for propfile in args.properties:
with open(propfile[0]) as propfilein:
data = json.load(propfilein)
for name in data:
properties[name] = data[name]
if args.property is not None:
for prop in args.property:
properties[prop[0]] = prop[1]
files=[]
if args.copy is not None:
for copy in args.copy:
fpath = copy[0]
eq = fpath.find('=')
if eq==0:
sys.stderr.write('invalid copy argument: '+fpath)
sys.exit(1)
elif eq>0:
dest = fpath[eq+1:]
fpath = fpath[0:eq]
else:
slash = fpath.rfind('/')
dest = fpath[slash+1] if slash>=0 else fpath
files.append((fpath,dest))
if args.definition is not None:
with open(args.definition,'rb') as data:
jobid = client.submit(args.path,properties=properties,workflow=data,copy=files,verbose=args.verbose)
else:
jobid = client.submit(args.path,properties=properties,copy=files,verbose=args.verbose)
print(jobid)
def convert_timestamp(value):
return datetime.strptime(value,'%a, %d %b %Y %H:%M:%S GMT').isoformat() if value is not None else None
def message(action):
code = action.get('errorCode')
message = action.get('errorMessage')
return code + ': ' + message if code is not None else ''
def oozie_status_command(client,argv):
cmdparser = argparse.ArgumentParser(prog='pyox oozie status',description='job status')
cmdparser.add_argument(
'-r','--raw',
action='store_true',
dest='raw',
default=False,
help="return raw JSON")
cmdparser.add_argument(
'-p',
action='store_true',
dest='pretty',
default=False,
help="Pretty print JSON")
cmdparser.add_argument(
'-a',
action='store_true',
dest='actions',
default=False,
help="show error messages")
cmdparser.add_argument(
'-e',
action='store_true',
dest='external_ids',
default=False,
help="show external ids")
cmdparser.add_argument(
'-s','--show',
dest='show',
nargs='?',
default='info',
help="The information about the job to retrieve.")
cmdparser.add_argument(
'-l',
action='store_true',
dest='detailed',
default=False,
help="list details")
cmdparser.add_argument(
'-v','--verbose',
action='store_true',
dest='verbose',
default=False,
help="Verbose")
cmdparser.add_argument(
'jobids',
nargs='*',
help='a list job ids')
args = cmdparser.parse_args(argv)
for jobid in args.jobids:
try:
response = client.status(jobid,show=args.show)
if args.raw or type(response)==str:
if type(response)==str:
sys.stdout.write(response)
elif type(response)==bytes:
sys.stdout.buffer.write(response)
else:
sys.stdout.write('\n')
sys.stdout.write(json.dumps(response,indent=3,sort_keys=True) if args.pretty else json.dumps(response))
sys.stdout.write('\x1e')
else:
actions = response.get('actions')
id_format = '{:' + str(max(list(map(lambda action:len(action.get('id')),actions)) + [len(jobid)])) + 's}'
if not args.raw and args.detailed:
print('\t'.join([id_format.format('JOB'),'{:10s}'.format('STATUS'),'{:10s}'.format('USER'),'{:10s}'.format('NAME'),'{:18s}'.format('START'),'{:18s}'.format('END'),'MESSAGE']))
if args.external_ids:
if actions is not None:
for action in actions:
print('\t'.join(map(lambda x:str(x) if x is not None else '',[id_format.format(action.get('id')),'{:10s}'.format(action.get('status')),'{:10s}'.format(action.get('name')),action.get('externalId')])))
elif args.detailed:
startTime = convert_timestamp(response.get('startTime'))
endTime = convert_timestamp(response.get('endTime'))
lastModTime = convert_timestamp(response.get('lastModTime'))
createdTime = convert_timestamp(response.get('createdTime'))
appName = response.get('appName')
status = response.get('status')
user = response.get('user')
print('\t'.join(map(lambda x:str(x),[id_format.format(jobid),'{:10s}'.format(status),'{:10s}'.format(user),'{:10s}'.format(appName),startTime,endTime])))
if args.actions and actions is not None:
for action in actions:
print('\t'.join(map(lambda x:str(x) if x is not None else '',[id_format.format(action.get('id')),'{:10s}'.format(action.get('status')),'{:10s}'.format(user),'{:10s}'.format(action.get('name')),convert_timestamp(action.get('startTime')),convert_timestamp(action.get('endTime')),message(action)])))
else:
status = response.get('status')
print('{}\t{}'.format(id_format.format(jobid),status))
actions = response.get('actions')
if args.actions and actions is not None:
for action in actions:
print('{}\t{}\t{}'.format(id_format.format(action.get('id')),'{:10s}'.format(action.get('status')),message(action)))
except ServiceError as err:
if err.status_code==404:
if args.raw:
sys.stdout.write('\n')
sys.stdout.write('{{"id":"{}","status":{}}}'.format(jobid,err.status_code))
sys.stdout.write('\x1e')
else:
print('{}\tNOT FOUND'.format(jobid))
else:
if args.raw:
sys.stdout.write('\n')
sys.stdout.write('{{"id":"{}","status":{}}}'.format(jobid,err.status_code))
sys.stdout.write('\x1e')
else:
raise
def oozie_ls_command(client,argv):
cmdparser = argparse.ArgumentParser(prog='pyox oozie status',description='job status')
cmdparser.add_argument(
'-a',
action='store_true',
dest='all',
default=False,
help="show all")
cmdparser.add_argument(
'-l',
action='store_true',
dest='detailed',
default=False,
help="list details")
cmdparser.add_argument(
'-s','--status',
dest='status',
nargs='?',
default='RUNNING',
help="filter by status")
cmdparser.add_argument(
'-o','--offset',
nargs='?',
dest='offset',
type=int,
default=0,
metavar=('offset'),
help="The offset at which to start")
cmdparser.add_argument(
'-n','--count',
nargs='?',
type=int,
default=50,
dest='count',
metavar=('count'),
help="The number of items to return")
cmdparser.add_argument(
'-v','--verbose',
action='store_true',
dest='verbose',
default=False,
help="Verbose")
args = cmdparser.parse_args(argv)
if args.all:
msg = client.list_jobs(offset=args.offset,count=args.count)
else:
msg = client.list_jobs(offset=args.offset,count=args.count,status=args.status)
if args.detailed:
print('\t'.join(['ID','STATUS','NAME','USER','START','END']))
for job in msg['workflows']:
id = job['id']
user = job['user']
status = job['status']
appName = job['appName']
startTime = job['startTime']
endTime = job['endTime']
print('\t'.join(map(lambda x:str(x) if x is not None else '',[id,status,appName,user,startTime,endTime])))
else:
for job in msg['workflows']:
id = job['id']
print(id)
oozie_commands = {
'start' : oozie_start_command,
'status' : oozie_status_command,
'ls' : oozie_ls_command
}
def oozie_command(args):
client = Oozie(base=args.base,secure=args.secure,host=args.hostinfo[0],port=args.hostinfo[1],gateway=args.gateway,username=args.user[0],password=args.user[1])
client.proxies = args.proxies
client.verify = args.verify
if args.verbose:
client.enable_verbose()
if len(args.command)==0:
raise ValueError('One of the following comamnds must be specified: {}'.format(' '.join(oozie_commands.keys())))
func = oozie_commands.get(args.command[0])
if func is None:
raise ValueError('Unrecognized command: {}'.format(args.command[0]))
func(client,args.command[1:]) | pyox/oozie_command.py | from pyox.oozie import Oozie
from pyox.client import ServiceError
import argparse
import sys
import os
import json
from datetime import datetime
def oozie_start_command(client,argv):
cmdparser = argparse.ArgumentParser(prog='pyox oozie start',description='start')
cmdparser.add_argument(
'-p','--property',
dest='property',
action='append',
metavar=('name','value'),
nargs=2,
help="A property name/value pair (e.g., name=value)")
cmdparser.add_argument(
'-P','--properties',
dest='properties',
action='append',
nargs=1,
metavar=('file.json'),
help="Property name/value pairs in JSON format.")
cmdparser.add_argument(
'-d','--definition',
dest='definition',
nargs=1,
metavar=('file.xml'),
help="The workflow definition to copy")
cmdparser.add_argument(
'-cp','--copy',
dest='copy',
action='append',
metavar=('file or file=target'),
nargs=1,
help="A resource to copy (e.g., source or source=dest)")
cmdparser.add_argument(
'--namenode',
nargs=1,
metavar=('node[:port]'),
help="The name node for jobs")
cmdparser.add_argument(
'--tracker',
nargs=1,
metavar=('node[:port]'),
help="The job tracker for jobs")
cmdparser.add_argument(
'-v','--verbose',
action='store_true',
dest='verbose',
default=False,
help="Verbose")
cmdparser.add_argument(
'path',
help='The job path')
args = cmdparser.parse_args(argv)
if args.namenode is not None:
client.namenode = args.namenode
if args.tracker is not None:
client.addProperty('jobTracker',args.tracker)
properties = {}
if args.properties is not None:
for propfile in args.properties:
with open(propfile[0]) as propfilein:
data = json.load(propfilein)
for name in data:
properties[name] = data[name]
if args.property is not None:
for prop in args.property:
properties[prop[0]] = prop[1]
files=[]
if args.copy is not None:
for copy in args.copy:
fpath = copy[0]
eq = fpath.find('=')
if eq==0:
sys.stderr.write('invalid copy argument: '+fpath)
sys.exit(1)
elif eq>0:
dest = fpath[eq+1:]
fpath = fpath[0:eq]
else:
slash = fpath.rfind('/')
dest = fpath[slash+1] if slash>=0 else fpath
files.append((fpath,dest))
if args.definition is not None:
with open(args.definition,'rb') as data:
jobid = client.submit(args.path,properties=properties,workflow=data,copy=files,verbose=args.verbose)
else:
jobid = client.submit(args.path,properties=properties,copy=files,verbose=args.verbose)
print(jobid)
def convert_timestamp(value):
return datetime.strptime(value,'%a, %d %b %Y %H:%M:%S GMT').isoformat() if value is not None else None
def message(action):
code = action.get('errorCode')
message = action.get('errorMessage')
return code + ': ' + message if code is not None else ''
def oozie_status_command(client,argv):
cmdparser = argparse.ArgumentParser(prog='pyox oozie status',description='job status')
cmdparser.add_argument(
'-r','--raw',
action='store_true',
dest='raw',
default=False,
help="return raw JSON")
cmdparser.add_argument(
'-p',
action='store_true',
dest='pretty',
default=False,
help="Pretty print JSON")
cmdparser.add_argument(
'-a',
action='store_true',
dest='actions',
default=False,
help="show error messages")
cmdparser.add_argument(
'-e',
action='store_true',
dest='external_ids',
default=False,
help="show external ids")
cmdparser.add_argument(
'-s','--show',
dest='show',
nargs='?',
default='info',
help="The information about the job to retrieve.")
cmdparser.add_argument(
'-l',
action='store_true',
dest='detailed',
default=False,
help="list details")
cmdparser.add_argument(
'-v','--verbose',
action='store_true',
dest='verbose',
default=False,
help="Verbose")
cmdparser.add_argument(
'jobids',
nargs='*',
help='a list job ids')
args = cmdparser.parse_args(argv)
for jobid in args.jobids:
try:
response = client.status(jobid,show=args.show)
if args.raw or type(response)==str:
if type(response)==str:
sys.stdout.write(response)
elif type(response)==bytes:
sys.stdout.buffer.write(response)
else:
sys.stdout.write('\n')
sys.stdout.write(json.dumps(response,indent=3,sort_keys=True) if args.pretty else json.dumps(response))
sys.stdout.write('\x1e')
else:
actions = response.get('actions')
id_format = '{:' + str(max(list(map(lambda action:len(action.get('id')),actions)) + [len(jobid)])) + 's}'
if not args.raw and args.detailed:
print('\t'.join([id_format.format('JOB'),'{:10s}'.format('STATUS'),'{:10s}'.format('USER'),'{:10s}'.format('NAME'),'{:18s}'.format('START'),'{:18s}'.format('END'),'MESSAGE']))
if args.external_ids:
if actions is not None:
for action in actions:
print('\t'.join(map(lambda x:str(x) if x is not None else '',[id_format.format(action.get('id')),'{:10s}'.format(action.get('status')),'{:10s}'.format(action.get('name')),action.get('externalId')])))
elif args.detailed:
startTime = convert_timestamp(response.get('startTime'))
endTime = convert_timestamp(response.get('endTime'))
lastModTime = convert_timestamp(response.get('lastModTime'))
createdTime = convert_timestamp(response.get('createdTime'))
appName = response.get('appName')
status = response.get('status')
user = response.get('user')
print('\t'.join(map(lambda x:str(x),[id_format.format(jobid),'{:10s}'.format(status),'{:10s}'.format(user),'{:10s}'.format(appName),startTime,endTime])))
if args.actions and actions is not None:
for action in actions:
print('\t'.join(map(lambda x:str(x) if x is not None else '',[id_format.format(action.get('id')),'{:10s}'.format(action.get('status')),'{:10s}'.format(user),'{:10s}'.format(action.get('name')),convert_timestamp(action.get('startTime')),convert_timestamp(action.get('endTime')),message(action)])))
else:
status = response.get('status')
print('{}\t{}'.format(id_format.format(jobid),status))
actions = response.get('actions')
if args.actions and actions is not None:
for action in actions:
print('{}\t{}\t{}'.format(id_format.format(action.get('id')),'{:10s}'.format(action.get('status')),message(action)))
except ServiceError as err:
if err.status_code==404:
if args.raw:
sys.stdout.write('\n')
sys.stdout.write('{{"id":"{}","status":{}}}'.format(jobid,err.status_code))
sys.stdout.write('\x1e')
else:
print('{}\tNOT FOUND'.format(jobid))
else:
if args.raw:
sys.stdout.write('\n')
sys.stdout.write('{{"id":"{}","status":{}}}'.format(jobid,err.status_code))
sys.stdout.write('\x1e')
else:
raise
def oozie_ls_command(client,argv):
cmdparser = argparse.ArgumentParser(prog='pyox oozie status',description='job status')
cmdparser.add_argument(
'-a',
action='store_true',
dest='all',
default=False,
help="show all")
cmdparser.add_argument(
'-l',
action='store_true',
dest='detailed',
default=False,
help="list details")
cmdparser.add_argument(
'-s','--status',
dest='status',
nargs='?',
default='RUNNING',
help="filter by status")
cmdparser.add_argument(
'-o','--offset',
nargs='?',
dest='offset',
type=int,
default=0,
metavar=('offset'),
help="The offset at which to start")
cmdparser.add_argument(
'-n','--count',
nargs='?',
type=int,
default=50,
dest='count',
metavar=('count'),
help="The number of items to return")
cmdparser.add_argument(
'-v','--verbose',
action='store_true',
dest='verbose',
default=False,
help="Verbose")
args = cmdparser.parse_args(argv)
if args.all:
msg = client.list_jobs(offset=args.offset,count=args.count)
else:
msg = client.list_jobs(offset=args.offset,count=args.count,status=args.status)
if args.detailed:
print('\t'.join(['ID','STATUS','NAME','USER','START','END']))
for job in msg['workflows']:
id = job['id']
user = job['user']
status = job['status']
appName = job['appName']
startTime = job['startTime']
endTime = job['endTime']
print('\t'.join(map(lambda x:str(x) if x is not None else '',[id,status,appName,user,startTime,endTime])))
else:
for job in msg['workflows']:
id = job['id']
print(id)
oozie_commands = {
'start' : oozie_start_command,
'status' : oozie_status_command,
'ls' : oozie_ls_command
}
def oozie_command(args):
client = Oozie(base=args.base,secure=args.secure,host=args.hostinfo[0],port=args.hostinfo[1],gateway=args.gateway,username=args.user[0],password=args.user[1])
client.proxies = args.proxies
client.verify = args.verify
if args.verbose:
client.enable_verbose()
if len(args.command)==0:
raise ValueError('One of the following comamnds must be specified: {}'.format(' '.join(oozie_commands.keys())))
func = oozie_commands.get(args.command[0])
if func is None:
raise ValueError('Unrecognized command: {}'.format(args.command[0]))
func(client,args.command[1:]) | 0.176814 | 0.060418 |
from pathlib import Path
import json
import torch
from torch.utils.data import Dataset
from collections import defaultdict
from lib.image import imread, imread_to_gray
from torchvision import transforms
def transpose_dict(d):
dt = defaultdict(list)
for k, v in d.items():
dt[v].append(k)
return dt
class FileSequence(Dataset):
""" Inference-only dataset. A sequence backed by jpeg images and start label pngs. """
def __init__(self, dset_name, seq_name, jpeg_path: Path, anno_path: Path, start_frames: dict, merge_objects=False,
all_annotations=False):
self.dset_name = dset_name
self.name = seq_name
self.images = list(sorted(jpeg_path.glob("*.jpg")))
self.preloaded_images = None
self.anno_path = anno_path
self.start_frames = dict(transpose_dict(start_frames)) # key: frame, value: list of object ids
self.obj_ids = list(start_frames.keys()) if not merge_objects else [1]
self.frame_names = [f.stem for f in self.images]
self.merge_objects = merge_objects
if all_annotations:
self.annos = list(sorted(anno_path.glob("*.png")))
def __len__(self):
return len(self.images)
def __getitem__(self, item):
if self.preloaded_images is not None:
im = self.preloaded_images[item]
else:
im = imread(self.images[item])
lb = []
f = self.frame_name(item)
obj_ids = self.start_frames.get(f, [])
if len(obj_ids) > 0:
lb = imread(self.anno_path / (f + ".png"))
if self.merge_objects:
lb = (lb != 0).byte()
obj_ids = [1]
else:
# 禁用不在第一帧中的label
# Suppress labels of objects not in their start frame (primarily for YouTubeVOS)
suppressed_obj_ids = list(set(lb.unique().tolist()) - set([0] + obj_ids))
for obj_id in suppressed_obj_ids:
lb[lb == obj_id] = 0
return im, lb, obj_ids
def frame_name(self, item):
return self.images[item].stem
def preload(self, device):
""" Preload all images and upload them to the GPU. """
self.preloaded_images = [imread(f).to(device) for f in self.images]
def __repr__(self):
return "%s: %s, %d frames" % (self.dset_name, self.name, len(self.images))
class DAVISDataset:
def __init__(self, path, year: str, split: str, restart: str=None, sequences: (list, tuple)=None,
all_annotations=False):
self.dset_path = Path(path).expanduser().resolve()
if not self.dset_path.exists():
print("Dataset directory '%s' not found." % path)
quit(1)
self.jpeg_path = self.dset_path / "JPEGImages" / "480p"
self.anno_path = self.dset_path / "Annotations" / "480p"
imset = self.dset_path / "ImageSets" / year / (split + ".txt")
self.sequences = [s.strip() for s in sorted(open(imset).readlines())]
self.name = "dv%s%s" % (year, split)
self.year = year
self.all_annotations = all_annotations
if sequences is not None:
assert set(sequences).issubset(self.sequences)
self.sequences = list(sorted(set(self.sequences).intersection(sequences)))
if restart is not None:
assert restart in self.sequences
self.sequences = self.sequences[self.sequences.index(restart):]
self.start_frames = dict()
for seq in self.sequences:
f0 = "00000" # In DAVIS, all objects appear in the first frame
obj_ids = torch.unique(imread(self.anno_path / seq / (f0 + ".png"))).tolist()
self.start_frames[seq] = {obj_id: f0 for obj_id in sorted(obj_ids) if obj_id != 0}
def __len__(self):
return len(self.sequences)
def __getitem__(self, item):
seq = self.sequences[item]
return FileSequence(self.name, seq, self.jpeg_path / seq, self.anno_path / seq, self.start_frames[seq],
merge_objects=self.year == '2016', all_annotations=self.all_annotations)
'''
class DAVISDataset_test:
def __init__(self, path, year: str, split: str, restart: str=None, sequences: (list, tuple)=None,
all_annotations=False):
self.dset_path = Path(path).expanduser().resolve()
if not self.dset_path.exists():
print("Dataset directory '%s' not found." % path)
quit(1)
self.jpeg_path = self.dset_path / "JPEGImages" / "480p"
self.anno_path = self.dset_path / "Annotations" / "480p"
imset = self.dset_path / "ImageSets" / year / (split + ".txt")
self.sequences = [s.strip() for s in sorted(open(imset).readlines())]
self.name = "dv%s%s" % (year, split)
self.year = year
self.all_annotations = all_annotations
if sequences is not None:
assert set(sequences).issubset(self.sequences)
self.sequences = list(sorted(set(self.sequences).intersection(sequences)))
if restart is not None:
assert restart in self.sequences
self.sequences = self.sequences[self.sequences.index(restart):]
self.start_frames = dict()
for seq in self.sequences:
f0 = "00000" # In DAVIS, all objects appear in the first frame
obj_ids = torch.unique(imread(self.anno_path / seq / (f0 + ".png"))).tolist()
self.start_frames[seq] = {obj_id: f0 for obj_id in sorted(obj_ids) if obj_id != 0}
def __len__(self):
return len(self.sequences)
def __getitem__(self, item):
seq = self.sequences[item]
return FileSequence(self.name, seq, self.jpeg_path / seq, self.anno_path / seq, self.start_frames[seq],
merge_objects=self.year == '2016', all_annotations=self.all_annotations)
'''
class YouTubeVOSDataset:
def __init__(self, path, year: str, split: str, restart: str=None, sequences: (list, tuple)=None,
all_annotations=False):
self.dset_path = Path(path).expanduser().resolve()
if not self.dset_path.exists():
print("Dataset directory '%s' not found." % path)
quit(1)
self.name = "ytvos%s%s" % (year, split)
self.year = year
self.all_annotations = all_annotations
if split in ('train', 'train_all_frames', 'jjval', 'jjval_all_frames'):
im_split = "train_all_frames" if split.endswith("_all_frames") else "train"
self.jpeg_path = self.dset_path / im_split / "JPEGImages"
self.anno_path = self.dset_path / "train" / "Annotations"
imset = Path(__file__).parent / ("ytvos_jjvalid.txt" if split.startswith('jjval') else "ytvos_jjtrain.txt")
self.sequences = [s.strip() for s in sorted(open(imset).readlines())]
self.meta = json.load(open(self.dset_path / "train" / "meta.json"))['videos']
elif split in ('test', 'test_all_frames', 'valid', 'valid_all_frames'):
im_split = split
split = split[:-len('_all_frames')] if split.endswith('_all_frames') else split
self.jpeg_path = self.dset_path / im_split / "JPEGImages"
self.anno_path = self.dset_path / split / "Annotations"
self.sequences = [s.name for s in sorted(self.anno_path.glob("*")) if s.is_dir()]
self.meta = json.load(open(self.dset_path / split / "meta.json"))['videos']
if sequences is not None:
assert set(sequences).issubset(self.sequences)
self.sequences = list(sorted(set(self.sequences).intersection(sequences)))
if restart is not None:
assert restart in self.sequences
self.sequences = self.sequences[self.sequences.index(restart):]
self.start_frames = dict()
for seq in self.sequences:
self.start_frames[seq] = {int(obj_id): v['frames'][0] for obj_id, v in self.meta[seq]['objects'].items()}
def __len__(self):
return len(self.sequences)
def __getitem__(self, item):
seq = self.sequences[item]
return FileSequence(self.name, seq, self.jpeg_path / seq, self.anno_path / seq, self.start_frames[seq],
all_annotations=self.all_annotations)
class AlibabaDataset:
def __init__(self, path, year: str, split: str, restart: str=None, sequences: (list, tuple)=None,
all_annotations=False):
self.dset_path = Path(path).expanduser().resolve()
if not self.dset_path.exists():
print("Dataset directory '%s' not found." % path)
quit(1)
self.jpeg_path = self.dset_path / "JPEGImages"
self.anno_path = self.dset_path / "Annotations"
imset = self.dset_path / "ImageSets" / (split + ".txt")
self.sequences = [s.strip() for s in sorted(open(imset).readlines())]
print(self.sequences)
self.name = "ali%s%s" % (year, split)
self.year = year
self.all_annotations = all_annotations
if sequences is not None:
assert set(sequences).issubset(self.sequences)
self.sequences = list(sorted(set(self.sequences).intersection(sequences)))
if restart is not None:
assert restart in self.sequences
self.sequences = self.sequences[self.sequences.index(restart):]
self.start_frames = dict()
for seq in self.sequences:
f0 = "00001" # In DAVIS, all objects appear in the first frame
obj_ids = torch.unique(imread(self.anno_path / seq / (f0 + ".png"))).tolist()
# print("obj_ids:", obj_ids)
self.start_frames[seq] = {obj_id: f0 for obj_id in sorted(obj_ids) if obj_id != 0}
def __len__(self):
return len(self.sequences)
def __getitem__(self, item):
seq = self.sequences[item]
return FileSequence(self.name, seq, self.jpeg_path / seq, self.anno_path / seq, self.start_frames[seq],
merge_objects=self.year == '2015', all_annotations=self.all_annotations) | lib/datasets.py | from pathlib import Path
import json
import torch
from torch.utils.data import Dataset
from collections import defaultdict
from lib.image import imread, imread_to_gray
from torchvision import transforms
def transpose_dict(d):
dt = defaultdict(list)
for k, v in d.items():
dt[v].append(k)
return dt
class FileSequence(Dataset):
""" Inference-only dataset. A sequence backed by jpeg images and start label pngs. """
def __init__(self, dset_name, seq_name, jpeg_path: Path, anno_path: Path, start_frames: dict, merge_objects=False,
all_annotations=False):
self.dset_name = dset_name
self.name = seq_name
self.images = list(sorted(jpeg_path.glob("*.jpg")))
self.preloaded_images = None
self.anno_path = anno_path
self.start_frames = dict(transpose_dict(start_frames)) # key: frame, value: list of object ids
self.obj_ids = list(start_frames.keys()) if not merge_objects else [1]
self.frame_names = [f.stem for f in self.images]
self.merge_objects = merge_objects
if all_annotations:
self.annos = list(sorted(anno_path.glob("*.png")))
def __len__(self):
return len(self.images)
def __getitem__(self, item):
if self.preloaded_images is not None:
im = self.preloaded_images[item]
else:
im = imread(self.images[item])
lb = []
f = self.frame_name(item)
obj_ids = self.start_frames.get(f, [])
if len(obj_ids) > 0:
lb = imread(self.anno_path / (f + ".png"))
if self.merge_objects:
lb = (lb != 0).byte()
obj_ids = [1]
else:
# 禁用不在第一帧中的label
# Suppress labels of objects not in their start frame (primarily for YouTubeVOS)
suppressed_obj_ids = list(set(lb.unique().tolist()) - set([0] + obj_ids))
for obj_id in suppressed_obj_ids:
lb[lb == obj_id] = 0
return im, lb, obj_ids
def frame_name(self, item):
return self.images[item].stem
def preload(self, device):
""" Preload all images and upload them to the GPU. """
self.preloaded_images = [imread(f).to(device) for f in self.images]
def __repr__(self):
return "%s: %s, %d frames" % (self.dset_name, self.name, len(self.images))
class DAVISDataset:
def __init__(self, path, year: str, split: str, restart: str=None, sequences: (list, tuple)=None,
all_annotations=False):
self.dset_path = Path(path).expanduser().resolve()
if not self.dset_path.exists():
print("Dataset directory '%s' not found." % path)
quit(1)
self.jpeg_path = self.dset_path / "JPEGImages" / "480p"
self.anno_path = self.dset_path / "Annotations" / "480p"
imset = self.dset_path / "ImageSets" / year / (split + ".txt")
self.sequences = [s.strip() for s in sorted(open(imset).readlines())]
self.name = "dv%s%s" % (year, split)
self.year = year
self.all_annotations = all_annotations
if sequences is not None:
assert set(sequences).issubset(self.sequences)
self.sequences = list(sorted(set(self.sequences).intersection(sequences)))
if restart is not None:
assert restart in self.sequences
self.sequences = self.sequences[self.sequences.index(restart):]
self.start_frames = dict()
for seq in self.sequences:
f0 = "00000" # In DAVIS, all objects appear in the first frame
obj_ids = torch.unique(imread(self.anno_path / seq / (f0 + ".png"))).tolist()
self.start_frames[seq] = {obj_id: f0 for obj_id in sorted(obj_ids) if obj_id != 0}
def __len__(self):
return len(self.sequences)
def __getitem__(self, item):
seq = self.sequences[item]
return FileSequence(self.name, seq, self.jpeg_path / seq, self.anno_path / seq, self.start_frames[seq],
merge_objects=self.year == '2016', all_annotations=self.all_annotations)
'''
class DAVISDataset_test:
def __init__(self, path, year: str, split: str, restart: str=None, sequences: (list, tuple)=None,
all_annotations=False):
self.dset_path = Path(path).expanduser().resolve()
if not self.dset_path.exists():
print("Dataset directory '%s' not found." % path)
quit(1)
self.jpeg_path = self.dset_path / "JPEGImages" / "480p"
self.anno_path = self.dset_path / "Annotations" / "480p"
imset = self.dset_path / "ImageSets" / year / (split + ".txt")
self.sequences = [s.strip() for s in sorted(open(imset).readlines())]
self.name = "dv%s%s" % (year, split)
self.year = year
self.all_annotations = all_annotations
if sequences is not None:
assert set(sequences).issubset(self.sequences)
self.sequences = list(sorted(set(self.sequences).intersection(sequences)))
if restart is not None:
assert restart in self.sequences
self.sequences = self.sequences[self.sequences.index(restart):]
self.start_frames = dict()
for seq in self.sequences:
f0 = "00000" # In DAVIS, all objects appear in the first frame
obj_ids = torch.unique(imread(self.anno_path / seq / (f0 + ".png"))).tolist()
self.start_frames[seq] = {obj_id: f0 for obj_id in sorted(obj_ids) if obj_id != 0}
def __len__(self):
return len(self.sequences)
def __getitem__(self, item):
seq = self.sequences[item]
return FileSequence(self.name, seq, self.jpeg_path / seq, self.anno_path / seq, self.start_frames[seq],
merge_objects=self.year == '2016', all_annotations=self.all_annotations)
'''
class YouTubeVOSDataset:
def __init__(self, path, year: str, split: str, restart: str=None, sequences: (list, tuple)=None,
all_annotations=False):
self.dset_path = Path(path).expanduser().resolve()
if not self.dset_path.exists():
print("Dataset directory '%s' not found." % path)
quit(1)
self.name = "ytvos%s%s" % (year, split)
self.year = year
self.all_annotations = all_annotations
if split in ('train', 'train_all_frames', 'jjval', 'jjval_all_frames'):
im_split = "train_all_frames" if split.endswith("_all_frames") else "train"
self.jpeg_path = self.dset_path / im_split / "JPEGImages"
self.anno_path = self.dset_path / "train" / "Annotations"
imset = Path(__file__).parent / ("ytvos_jjvalid.txt" if split.startswith('jjval') else "ytvos_jjtrain.txt")
self.sequences = [s.strip() for s in sorted(open(imset).readlines())]
self.meta = json.load(open(self.dset_path / "train" / "meta.json"))['videos']
elif split in ('test', 'test_all_frames', 'valid', 'valid_all_frames'):
im_split = split
split = split[:-len('_all_frames')] if split.endswith('_all_frames') else split
self.jpeg_path = self.dset_path / im_split / "JPEGImages"
self.anno_path = self.dset_path / split / "Annotations"
self.sequences = [s.name for s in sorted(self.anno_path.glob("*")) if s.is_dir()]
self.meta = json.load(open(self.dset_path / split / "meta.json"))['videos']
if sequences is not None:
assert set(sequences).issubset(self.sequences)
self.sequences = list(sorted(set(self.sequences).intersection(sequences)))
if restart is not None:
assert restart in self.sequences
self.sequences = self.sequences[self.sequences.index(restart):]
self.start_frames = dict()
for seq in self.sequences:
self.start_frames[seq] = {int(obj_id): v['frames'][0] for obj_id, v in self.meta[seq]['objects'].items()}
def __len__(self):
return len(self.sequences)
def __getitem__(self, item):
seq = self.sequences[item]
return FileSequence(self.name, seq, self.jpeg_path / seq, self.anno_path / seq, self.start_frames[seq],
all_annotations=self.all_annotations)
class AlibabaDataset:
def __init__(self, path, year: str, split: str, restart: str=None, sequences: (list, tuple)=None,
all_annotations=False):
self.dset_path = Path(path).expanduser().resolve()
if not self.dset_path.exists():
print("Dataset directory '%s' not found." % path)
quit(1)
self.jpeg_path = self.dset_path / "JPEGImages"
self.anno_path = self.dset_path / "Annotations"
imset = self.dset_path / "ImageSets" / (split + ".txt")
self.sequences = [s.strip() for s in sorted(open(imset).readlines())]
print(self.sequences)
self.name = "ali%s%s" % (year, split)
self.year = year
self.all_annotations = all_annotations
if sequences is not None:
assert set(sequences).issubset(self.sequences)
self.sequences = list(sorted(set(self.sequences).intersection(sequences)))
if restart is not None:
assert restart in self.sequences
self.sequences = self.sequences[self.sequences.index(restart):]
self.start_frames = dict()
for seq in self.sequences:
f0 = "00001" # In DAVIS, all objects appear in the first frame
obj_ids = torch.unique(imread(self.anno_path / seq / (f0 + ".png"))).tolist()
# print("obj_ids:", obj_ids)
self.start_frames[seq] = {obj_id: f0 for obj_id in sorted(obj_ids) if obj_id != 0}
def __len__(self):
return len(self.sequences)
def __getitem__(self, item):
seq = self.sequences[item]
return FileSequence(self.name, seq, self.jpeg_path / seq, self.anno_path / seq, self.start_frames[seq],
merge_objects=self.year == '2015', all_annotations=self.all_annotations) | 0.77949 | 0.315921 |
from __future__ import annotations
import dataclasses
import os
import typing as t
from .io import (
read_text_file,
)
from .util import (
ANSIBLE_TEST_TARGET_ROOT,
)
from .util_common import (
ShellScriptTemplate,
set_shebang,
)
from .core_ci import (
SshKey,
)
@dataclasses.dataclass
class Bootstrap:
"""Base class for bootstrapping systems."""
controller: bool
python_versions: t.List[str]
ssh_key: SshKey
@property
def bootstrap_type(self): # type: () -> str
"""The bootstrap type to pass to the bootstrapping script."""
return self.__class__.__name__.replace('Bootstrap', '').lower()
def get_variables(self): # type: () -> t.Dict[str, str]
"""The variables to template in the boostrapping script."""
return dict(
bootstrap_type=self.bootstrap_type,
controller='yes' if self.controller else '',
python_versions=self.python_versions,
ssh_key_type=self.ssh_key.KEY_TYPE,
ssh_private_key=self.ssh_key.key_contents,
ssh_public_key=self.ssh_key.pub_contents,
)
def get_script(self): # type: () -> str
"""Return a shell script to bootstrap the specified host."""
path = os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'setup', 'bootstrap.sh')
content = read_text_file(path)
content = set_shebang(content, '/bin/sh')
template = ShellScriptTemplate(content)
variables = self.get_variables()
script = template.substitute(**variables)
return script
@dataclasses.dataclass
class BootstrapDocker(Bootstrap):
"""Bootstrap docker instances."""
def get_variables(self): # type: () -> t.Dict[str, str]
"""The variables to template in the boostrapping script."""
variables = super().get_variables()
variables.update(
platform='',
platform_version='',
)
return variables
@dataclasses.dataclass
class BootstrapRemote(Bootstrap):
"""Bootstrap remote instances."""
platform: str
platform_version: str
def get_variables(self): # type: () -> t.Dict[str, str]
"""The variables to template in the boostrapping script."""
variables = super().get_variables()
variables.update(
platform=self.platform,
platform_version=self.platform_version,
)
return variables | venv/lib/python3.8/site-packages/ansible_test/_internal/bootstrap.py | from __future__ import annotations
import dataclasses
import os
import typing as t
from .io import (
read_text_file,
)
from .util import (
ANSIBLE_TEST_TARGET_ROOT,
)
from .util_common import (
ShellScriptTemplate,
set_shebang,
)
from .core_ci import (
SshKey,
)
@dataclasses.dataclass
class Bootstrap:
"""Base class for bootstrapping systems."""
controller: bool
python_versions: t.List[str]
ssh_key: SshKey
@property
def bootstrap_type(self): # type: () -> str
"""The bootstrap type to pass to the bootstrapping script."""
return self.__class__.__name__.replace('Bootstrap', '').lower()
def get_variables(self): # type: () -> t.Dict[str, str]
"""The variables to template in the boostrapping script."""
return dict(
bootstrap_type=self.bootstrap_type,
controller='yes' if self.controller else '',
python_versions=self.python_versions,
ssh_key_type=self.ssh_key.KEY_TYPE,
ssh_private_key=self.ssh_key.key_contents,
ssh_public_key=self.ssh_key.pub_contents,
)
def get_script(self): # type: () -> str
"""Return a shell script to bootstrap the specified host."""
path = os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'setup', 'bootstrap.sh')
content = read_text_file(path)
content = set_shebang(content, '/bin/sh')
template = ShellScriptTemplate(content)
variables = self.get_variables()
script = template.substitute(**variables)
return script
@dataclasses.dataclass
class BootstrapDocker(Bootstrap):
"""Bootstrap docker instances."""
def get_variables(self): # type: () -> t.Dict[str, str]
"""The variables to template in the boostrapping script."""
variables = super().get_variables()
variables.update(
platform='',
platform_version='',
)
return variables
@dataclasses.dataclass
class BootstrapRemote(Bootstrap):
"""Bootstrap remote instances."""
platform: str
platform_version: str
def get_variables(self): # type: () -> t.Dict[str, str]
"""The variables to template in the boostrapping script."""
variables = super().get_variables()
variables.update(
platform=self.platform,
platform_version=self.platform_version,
)
return variables | 0.802207 | 0.09899 |
from typing import TypeVar, Generic, Callable, Optional, Tuple
import math
from algo1 import Array
from linkedlist import LinkedList
import linkedlist
K = TypeVar('K')
V = TypeVar('V')
W = TypeVar('W')
class Dic(Generic[K, V]):
""" The dictionary class """
def __init__(self,
_size : int,
_hash_function : Callable[[K], int]):
"""Creates an empty dictionary. It has all empty lists.
Pay the price in size."""
self.table : Array[LinkedList[Tuple[K, V]]] = Array(_size, None)
for idx in range(_size):
self.table[idx] = linkedlist.empty()
self.hash_function = _hash_function
self.size = _size
def multiplicative_hash_function(_size: int, _spread: float) -> Callable[[int], int]:
""" Returns multiplicative hash function """
def hash_func(__key: int) -> int:
return math.floor(_size * ((__key * _spread) % 1))
return hash_func
def golden_ratio() -> float:
""" that number """
return (math.sqrt(5) - 1) / 2
def insert(_dic : Dic[K, V], _key : K, _value : V) -> Dic[K, V]:
""" Insert into a dictionary. """
this_hash = _dic.hash_function(_key)
_dic.table[this_hash] = linkedlist.insert(_dic.table[this_hash], _key, _value)
return _dic
def delete(_dic : Dic[K, V], _key : K) -> Dic[K, V]:
""" Delete a kay from a dictionary """
this_hash = _dic.hash_function(_key)
_dic.table[this_hash] = linkedlist.delete(_dic.table[this_hash], _key)
return _dic
def search(_dic : Dic[K, V], _key : K) -> Optional[V]:
""" Search a key in the table """
this_hash = _dic.hash_function(_key)
return linkedlist.retrieve(_dic.table[this_hash], _key)
def update_with_default(_dic : Dic[K, V],
_update_function : Callable[[V], V],
_key : K ,
_default : V) -> Dic[K, V]:
""" Update the value at `_key` using `_update_function`. Insert `_default`
if `_key` is not pressent. """
this_hash = _dic.hash_function(_key)
_dic.table[this_hash] = linkedlist.update_with_default(
_dic.table[this_hash],
_update_function,
_key,
_default)
return _dic
def assocs(_dic : Dic[K, V]) -> LinkedList[Tuple[K, V]]:
""" A list of pairs key, value """
result : LinkedList[Tuple[K, V]] = linkedlist.empty()
for l in _dic.table.data:
result = linkedlist.rev_concat(
linkedlist.lmap(lambda x : x, l),
result)
return result
def to_list(_dic : Dic[K, V]) -> LinkedList[V]:
""" A list of values """
return linkedlist.lmap(lambda x : x[1], assocs(_dic))
def keys(_dic : Dic[K, V]) -> LinkedList[K]:
""" The keys """
return linkedlist.lmap(lambda x : x[0], assocs(_dic))
def includes(_a : Dic[K, V], _b : Dic[K, V]) -> bool:
""" Wether all the keys of `_b` are included in `_a`
O(|_b|)
"""
keys_b = keys(_b)
return linkedlist.lall(lambda x : not search(_a, x) is None, keys_b)
def dmap(_mapper : Callable[[V], W], _dic : Dic[K, V]) -> Dic[K, W]:
""" Maps the values """
retDic : Dic[K, W] = Dic(_dic.size, _dic.hash_function)
for idx in range(_dic.size):
retDic.table[idx] = linkedlist.lmap(lambda p: (p[0], _mapper(p[1])),
_dic.table[idx])
return retDic
def dic_health(_dic : Dic[K, V]) -> None:
""" Helath report for a directory """
print("Size: ", _dic.size)
collisions : LinkedList[int] = linkedlist.empty()
for idx in range(_dic.size):
collisions = linkedlist.cons(
linkedlist.length(_dic.table[idx]),
collisions)
min_collisions = linkedlist.minimum_by(
lambda x, y: x <= y,
collisions)
if not min_collisions is None:
print("Min collisions: ", min_collisions)
max_collisions = linkedlist.maximum(
linkedlist.lmap(float, collisions))
if not max_collisions is None:
print("Max collisions: ", max_collisions)
elements = linkedlist.lsum(collisions)
print("Elements: ", elements)
collisions = linkedlist.quick_sort_by(lambda x, y: x <= y,
collisions)
median : Optional[int] = linkedlist.index(collisions, _dic.size // 2)
print("Median: ", median)
print("Load factor: ", elements / _dic.size) | libdic.py |
from typing import TypeVar, Generic, Callable, Optional, Tuple
import math
from algo1 import Array
from linkedlist import LinkedList
import linkedlist
K = TypeVar('K')
V = TypeVar('V')
W = TypeVar('W')
class Dic(Generic[K, V]):
""" The dictionary class """
def __init__(self,
_size : int,
_hash_function : Callable[[K], int]):
"""Creates an empty dictionary. It has all empty lists.
Pay the price in size."""
self.table : Array[LinkedList[Tuple[K, V]]] = Array(_size, None)
for idx in range(_size):
self.table[idx] = linkedlist.empty()
self.hash_function = _hash_function
self.size = _size
def multiplicative_hash_function(_size: int, _spread: float) -> Callable[[int], int]:
""" Returns multiplicative hash function """
def hash_func(__key: int) -> int:
return math.floor(_size * ((__key * _spread) % 1))
return hash_func
def golden_ratio() -> float:
""" that number """
return (math.sqrt(5) - 1) / 2
def insert(_dic : Dic[K, V], _key : K, _value : V) -> Dic[K, V]:
""" Insert into a dictionary. """
this_hash = _dic.hash_function(_key)
_dic.table[this_hash] = linkedlist.insert(_dic.table[this_hash], _key, _value)
return _dic
def delete(_dic : Dic[K, V], _key : K) -> Dic[K, V]:
""" Delete a kay from a dictionary """
this_hash = _dic.hash_function(_key)
_dic.table[this_hash] = linkedlist.delete(_dic.table[this_hash], _key)
return _dic
def search(_dic : Dic[K, V], _key : K) -> Optional[V]:
""" Search a key in the table """
this_hash = _dic.hash_function(_key)
return linkedlist.retrieve(_dic.table[this_hash], _key)
def update_with_default(_dic : Dic[K, V],
_update_function : Callable[[V], V],
_key : K ,
_default : V) -> Dic[K, V]:
""" Update the value at `_key` using `_update_function`. Insert `_default`
if `_key` is not pressent. """
this_hash = _dic.hash_function(_key)
_dic.table[this_hash] = linkedlist.update_with_default(
_dic.table[this_hash],
_update_function,
_key,
_default)
return _dic
def assocs(_dic : Dic[K, V]) -> LinkedList[Tuple[K, V]]:
""" A list of pairs key, value """
result : LinkedList[Tuple[K, V]] = linkedlist.empty()
for l in _dic.table.data:
result = linkedlist.rev_concat(
linkedlist.lmap(lambda x : x, l),
result)
return result
def to_list(_dic : Dic[K, V]) -> LinkedList[V]:
""" A list of values """
return linkedlist.lmap(lambda x : x[1], assocs(_dic))
def keys(_dic : Dic[K, V]) -> LinkedList[K]:
""" The keys """
return linkedlist.lmap(lambda x : x[0], assocs(_dic))
def includes(_a : Dic[K, V], _b : Dic[K, V]) -> bool:
""" Wether all the keys of `_b` are included in `_a`
O(|_b|)
"""
keys_b = keys(_b)
return linkedlist.lall(lambda x : not search(_a, x) is None, keys_b)
def dmap(_mapper : Callable[[V], W], _dic : Dic[K, V]) -> Dic[K, W]:
""" Maps the values """
retDic : Dic[K, W] = Dic(_dic.size, _dic.hash_function)
for idx in range(_dic.size):
retDic.table[idx] = linkedlist.lmap(lambda p: (p[0], _mapper(p[1])),
_dic.table[idx])
return retDic
def dic_health(_dic : Dic[K, V]) -> None:
""" Helath report for a directory """
print("Size: ", _dic.size)
collisions : LinkedList[int] = linkedlist.empty()
for idx in range(_dic.size):
collisions = linkedlist.cons(
linkedlist.length(_dic.table[idx]),
collisions)
min_collisions = linkedlist.minimum_by(
lambda x, y: x <= y,
collisions)
if not min_collisions is None:
print("Min collisions: ", min_collisions)
max_collisions = linkedlist.maximum(
linkedlist.lmap(float, collisions))
if not max_collisions is None:
print("Max collisions: ", max_collisions)
elements = linkedlist.lsum(collisions)
print("Elements: ", elements)
collisions = linkedlist.quick_sort_by(lambda x, y: x <= y,
collisions)
median : Optional[int] = linkedlist.index(collisions, _dic.size // 2)
print("Median: ", median)
print("Load factor: ", elements / _dic.size) | 0.934223 | 0.416263 |
from cvxpy.atoms import (bmat, cumsum, diag, kron, conv,
abs, reshape, trace,
upper_tri, conj, imag, real,
norm1, norm_inf, Pnorm,
sigma_max, lambda_max, lambda_sum_largest,
log_det, QuadForm, MatrixFrac)
from cvxpy.atoms.affine.promote import Promote
from cvxpy.atoms.affine.sum import Sum
from cvxpy.atoms.affine.add_expr import AddExpression
from cvxpy.atoms.affine.index import index
from cvxpy.atoms.affine.unary_operators import NegExpression
from cvxpy.atoms.affine.transpose import transpose
from cvxpy.atoms.affine.hstack import Hstack
from cvxpy.atoms.affine.vstack import Vstack
from cvxpy.atoms.norm_nuc import normNuc
from cvxpy.atoms.affine.binary_operators import (MulExpression,
multiply,
DivExpression)
from cvxpy.expressions.constants import Constant
from cvxpy.expressions.variable import Variable
from cvxpy.constraints.zero import Zero
from cvxpy.constraints.psd import PSD
from cvxpy.reductions.complex2real.atom_canonicalizers.abs_canon import abs_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.aff_canon import (separable_canon,
real_canon,
imag_canon,
conj_canon,
binary_canon)
from cvxpy.reductions.complex2real.atom_canonicalizers.pnorm_canon import pnorm_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.matrix_canon import (
hermitian_canon, quad_canon, lambda_sum_largest_canon, norm_nuc_canon, matrix_frac_canon)
from cvxpy.reductions.complex2real.atom_canonicalizers.variable_canon import variable_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.constant_canon import constant_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.zero_canon import zero_canon
CANON_METHODS = {
AddExpression: separable_canon,
bmat: separable_canon,
cumsum: separable_canon,
diag: separable_canon,
Hstack: separable_canon,
index: separable_canon,
Promote: separable_canon,
reshape: separable_canon,
Sum: separable_canon,
trace: separable_canon,
transpose: separable_canon,
NegExpression: separable_canon,
upper_tri: separable_canon,
Vstack: separable_canon,
conv: binary_canon,
DivExpression: binary_canon,
kron: binary_canon,
MulExpression: binary_canon,
multiply: binary_canon,
conj: conj_canon,
imag: imag_canon,
real: real_canon,
Variable: variable_canon,
Constant: constant_canon,
Zero: zero_canon,
PSD: hermitian_canon,
abs: abs_canon,
norm1: pnorm_canon,
norm_inf: pnorm_canon,
Pnorm: pnorm_canon,
lambda_max: hermitian_canon,
log_det: norm_nuc_canon,
normNuc: norm_nuc_canon,
sigma_max: hermitian_canon,
QuadForm: quad_canon,
MatrixFrac: matrix_frac_canon,
lambda_sum_largest: lambda_sum_largest_canon,
} | cvxpy/reductions/complex2real/atom_canonicalizers/__init__.py | from cvxpy.atoms import (bmat, cumsum, diag, kron, conv,
abs, reshape, trace,
upper_tri, conj, imag, real,
norm1, norm_inf, Pnorm,
sigma_max, lambda_max, lambda_sum_largest,
log_det, QuadForm, MatrixFrac)
from cvxpy.atoms.affine.promote import Promote
from cvxpy.atoms.affine.sum import Sum
from cvxpy.atoms.affine.add_expr import AddExpression
from cvxpy.atoms.affine.index import index
from cvxpy.atoms.affine.unary_operators import NegExpression
from cvxpy.atoms.affine.transpose import transpose
from cvxpy.atoms.affine.hstack import Hstack
from cvxpy.atoms.affine.vstack import Vstack
from cvxpy.atoms.norm_nuc import normNuc
from cvxpy.atoms.affine.binary_operators import (MulExpression,
multiply,
DivExpression)
from cvxpy.expressions.constants import Constant
from cvxpy.expressions.variable import Variable
from cvxpy.constraints.zero import Zero
from cvxpy.constraints.psd import PSD
from cvxpy.reductions.complex2real.atom_canonicalizers.abs_canon import abs_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.aff_canon import (separable_canon,
real_canon,
imag_canon,
conj_canon,
binary_canon)
from cvxpy.reductions.complex2real.atom_canonicalizers.pnorm_canon import pnorm_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.matrix_canon import (
hermitian_canon, quad_canon, lambda_sum_largest_canon, norm_nuc_canon, matrix_frac_canon)
from cvxpy.reductions.complex2real.atom_canonicalizers.variable_canon import variable_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.constant_canon import constant_canon
from cvxpy.reductions.complex2real.atom_canonicalizers.zero_canon import zero_canon
CANON_METHODS = {
AddExpression: separable_canon,
bmat: separable_canon,
cumsum: separable_canon,
diag: separable_canon,
Hstack: separable_canon,
index: separable_canon,
Promote: separable_canon,
reshape: separable_canon,
Sum: separable_canon,
trace: separable_canon,
transpose: separable_canon,
NegExpression: separable_canon,
upper_tri: separable_canon,
Vstack: separable_canon,
conv: binary_canon,
DivExpression: binary_canon,
kron: binary_canon,
MulExpression: binary_canon,
multiply: binary_canon,
conj: conj_canon,
imag: imag_canon,
real: real_canon,
Variable: variable_canon,
Constant: constant_canon,
Zero: zero_canon,
PSD: hermitian_canon,
abs: abs_canon,
norm1: pnorm_canon,
norm_inf: pnorm_canon,
Pnorm: pnorm_canon,
lambda_max: hermitian_canon,
log_det: norm_nuc_canon,
normNuc: norm_nuc_canon,
sigma_max: hermitian_canon,
QuadForm: quad_canon,
MatrixFrac: matrix_frac_canon,
lambda_sum_largest: lambda_sum_largest_canon,
} | 0.675551 | 0.403684 |
import decimal
import pickle
import tempfile
from heapq import heappop, heappush
import numpy as np
from gwas import Gwas
from pvalue_handler import PvalueHandler
from vcf import Vcf
def test_convert_pval_to_neg_log10():
p_value_handler = PvalueHandler()
assert p_value_handler.neg_log_of_decimal(decimal.Decimal(1)) == 0
assert p_value_handler.neg_log_of_decimal(decimal.Decimal(0)) == 999
def test_is_valid_float32():
# small
assert not Vcf.is_float32_lossy(1e-37)
assert not Vcf.is_float32_lossy(np.finfo(np.float32).tiny)
assert Vcf.is_float32_lossy(1e-50)
assert not Vcf.is_float32_lossy(-1e-37)
assert Vcf.is_float32_lossy(-1e-50)
# large
assert Vcf.is_float32_lossy(999999999999999999999999999999999999999)
assert Vcf.is_float32_lossy(-999999999999999999999999999999999999999)
assert not Vcf.is_float32_lossy(-99999999999999999999999999999999999999)
assert not Vcf.is_float32_lossy(99999999999999999999999999999999999999)
def test_gwas_unpickle():
p_value_handler = PvalueHandler()
precision_check = {"string": "1E-10000", "nlog_value": 10000}
g1 = [
Gwas("1", 101, "A", "T", 1, 0, 5e-8, 1000, 0.4, "rs1234", None, None, None),
Gwas("1", 105, "A", "T", 1, 0, 5e-8, 1000, 0.4, "rs1234", None, None, None),
Gwas("1", 102, "A", "T", 1, 0, 5e-8, 1000, 0.4, "rs1234", None, None, None),
Gwas(
"1",
103,
"A",
"T",
1,
0,
p_value_handler.neg_log_of_decimal(
p_value_handler.parse_string(precision_check["string"])
),
1000,
0.4,
"rs1234",
None,
None,
None,
),
]
g2 = []
idx = []
results = tempfile.TemporaryFile()
for result in g1:
heappush(idx, (result.pos, results.tell()))
pickle.dump(result, results)
while idx:
pos = heappop(idx)
results.seek(pos[1])
result = pickle.load(results)
g2.append(result)
epsilon = g2[2].nlog_pval / 1000000.0
assert g2[0].pos == 101
assert g2[1].pos == 102
assert g2[2].pos == 103
assert g2[2].nlog_pval > precision_check["nlog_value"] - epsilon
assert g2[2].nlog_pval < precision_check["nlog_value"] + epsilon
assert g2[3].pos == 105
results.close() | test/test_vcf.py | import decimal
import pickle
import tempfile
from heapq import heappop, heappush
import numpy as np
from gwas import Gwas
from pvalue_handler import PvalueHandler
from vcf import Vcf
def test_convert_pval_to_neg_log10():
p_value_handler = PvalueHandler()
assert p_value_handler.neg_log_of_decimal(decimal.Decimal(1)) == 0
assert p_value_handler.neg_log_of_decimal(decimal.Decimal(0)) == 999
def test_is_valid_float32():
# small
assert not Vcf.is_float32_lossy(1e-37)
assert not Vcf.is_float32_lossy(np.finfo(np.float32).tiny)
assert Vcf.is_float32_lossy(1e-50)
assert not Vcf.is_float32_lossy(-1e-37)
assert Vcf.is_float32_lossy(-1e-50)
# large
assert Vcf.is_float32_lossy(999999999999999999999999999999999999999)
assert Vcf.is_float32_lossy(-999999999999999999999999999999999999999)
assert not Vcf.is_float32_lossy(-99999999999999999999999999999999999999)
assert not Vcf.is_float32_lossy(99999999999999999999999999999999999999)
def test_gwas_unpickle():
p_value_handler = PvalueHandler()
precision_check = {"string": "1E-10000", "nlog_value": 10000}
g1 = [
Gwas("1", 101, "A", "T", 1, 0, 5e-8, 1000, 0.4, "rs1234", None, None, None),
Gwas("1", 105, "A", "T", 1, 0, 5e-8, 1000, 0.4, "rs1234", None, None, None),
Gwas("1", 102, "A", "T", 1, 0, 5e-8, 1000, 0.4, "rs1234", None, None, None),
Gwas(
"1",
103,
"A",
"T",
1,
0,
p_value_handler.neg_log_of_decimal(
p_value_handler.parse_string(precision_check["string"])
),
1000,
0.4,
"rs1234",
None,
None,
None,
),
]
g2 = []
idx = []
results = tempfile.TemporaryFile()
for result in g1:
heappush(idx, (result.pos, results.tell()))
pickle.dump(result, results)
while idx:
pos = heappop(idx)
results.seek(pos[1])
result = pickle.load(results)
g2.append(result)
epsilon = g2[2].nlog_pval / 1000000.0
assert g2[0].pos == 101
assert g2[1].pos == 102
assert g2[2].pos == 103
assert g2[2].nlog_pval > precision_check["nlog_value"] - epsilon
assert g2[2].nlog_pval < precision_check["nlog_value"] + epsilon
assert g2[3].pos == 105
results.close() | 0.558327 | 0.519399 |
import numpy as np
from ..core.utils import indices_len, fix_loc, filter_cols
from ..table.module import TableModule
from ..table.table import Table
import numexpr as ne
def make_local(df, px):
arr = df.to_array()
result = {}
class _Aux: pass
aux = _Aux()
for i, n in enumerate(df.columns):
key = f'_{px}__{i}'
result[key] = arr[:, i]
setattr(aux, n, key)
return aux, result
class NumExprABC(TableModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ref_expr = self.expr
def reset(self):
if self.result is not None:
self.result.resize(0)
def run_step(self, run_number, step_size, howlong):
"""
"""
reset_all = False
for slot in self._input_slots.values():
if slot is None:
continue
if slot.updated.any() or slot.deleted.any():
reset_all = True
break
if reset_all:
for slot in self._input_slots.values():
slot.reset()
slot.update(run_number)
self.reset()
for slot in self._input_slots.values():
if slot is None:
continue
if not slot.has_buffered():
return self._return_run_step(self.state_blocked, steps_run=0)
if self.result is None:
if self.has_output_datashape("result"):
dshape_ = self.get_output_datashape("result")
else:
dshape_ = self.get_datashape_from_expr()
self.ref_expr = {k.split(":")[0]:v for (k, v) in self.expr.items()}
self.result = Table(self.generate_table_name(f'num_expr'),
dshape=dshape_, create=True)
local_env = {}
vars_dict = {}
for n, sl in self._input_slots.items():
if n == '_params':
continue
step_size = min(step_size, sl.created.length())
data_ = sl.data()
if step_size == 0 or data_ is None:
return self._return_run_step(self.state_blocked, steps_run=0)
first_slot = None
for n, sl in self._input_slots.items():
if n == '_params':
continue
if first_slot is None:
first_slot = sl
indices = sl.created.next(step_size)
df = self.filter_columns(sl.data(), fix_loc(indices), n)
fobj, dict_ = make_local(df, n)
local_env.update(dict_)
vars_dict[n] = fobj
result = {}
steps = None
for c in self.result.columns:
col_expr_ = self.ref_expr[c]
col_expr_ = col_expr_.format(**vars_dict)
result[c] = ne.evaluate(col_expr_, local_dict=local_env)
if steps is None:
steps = len(result[c])
self.result.append(result)
return self._return_run_step(self.next_state(first_slot), steps_run=steps) | progressivis/linalg/nexpr.py | import numpy as np
from ..core.utils import indices_len, fix_loc, filter_cols
from ..table.module import TableModule
from ..table.table import Table
import numexpr as ne
def make_local(df, px):
arr = df.to_array()
result = {}
class _Aux: pass
aux = _Aux()
for i, n in enumerate(df.columns):
key = f'_{px}__{i}'
result[key] = arr[:, i]
setattr(aux, n, key)
return aux, result
class NumExprABC(TableModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ref_expr = self.expr
def reset(self):
if self.result is not None:
self.result.resize(0)
def run_step(self, run_number, step_size, howlong):
"""
"""
reset_all = False
for slot in self._input_slots.values():
if slot is None:
continue
if slot.updated.any() or slot.deleted.any():
reset_all = True
break
if reset_all:
for slot in self._input_slots.values():
slot.reset()
slot.update(run_number)
self.reset()
for slot in self._input_slots.values():
if slot is None:
continue
if not slot.has_buffered():
return self._return_run_step(self.state_blocked, steps_run=0)
if self.result is None:
if self.has_output_datashape("result"):
dshape_ = self.get_output_datashape("result")
else:
dshape_ = self.get_datashape_from_expr()
self.ref_expr = {k.split(":")[0]:v for (k, v) in self.expr.items()}
self.result = Table(self.generate_table_name(f'num_expr'),
dshape=dshape_, create=True)
local_env = {}
vars_dict = {}
for n, sl in self._input_slots.items():
if n == '_params':
continue
step_size = min(step_size, sl.created.length())
data_ = sl.data()
if step_size == 0 or data_ is None:
return self._return_run_step(self.state_blocked, steps_run=0)
first_slot = None
for n, sl in self._input_slots.items():
if n == '_params':
continue
if first_slot is None:
first_slot = sl
indices = sl.created.next(step_size)
df = self.filter_columns(sl.data(), fix_loc(indices), n)
fobj, dict_ = make_local(df, n)
local_env.update(dict_)
vars_dict[n] = fobj
result = {}
steps = None
for c in self.result.columns:
col_expr_ = self.ref_expr[c]
col_expr_ = col_expr_.format(**vars_dict)
result[c] = ne.evaluate(col_expr_, local_dict=local_env)
if steps is None:
steps = len(result[c])
self.result.append(result)
return self._return_run_step(self.next_state(first_slot), steps_run=steps) | 0.355216 | 0.257018 |
import argparse
from datetime import datetime
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from make_table import get_table
def get_schoopy_plot(table, error_bars=True):
fig, ax = plt.subplots(figsize=(20, 9))
models = set(table.model)
test_datas = set(table.test_data)
alphas = set(table.alpha)
sns.lineplot(data=table,
x="test_iter",
y="test_acc_mean",
hue="model",
size="alpha",
sizes=(2, 8),
style="test_data" if len(test_datas) > 1 else None,
palette="dark",
dashes=True,
units=None,
legend="auto",
ax=ax)
if error_bars and "test_acc_sem" in table.keys():
for model in models:
for test_data in test_datas:
for alpha in alphas:
data = table[(table.model == model) &
(table.test_data == test_data) &
(table.alpha == alpha)]
plt.fill_between(data.test_iter,
data.test_acc_mean - data.test_acc_sem,
data.test_acc_mean + data.test_acc_sem,
alpha=0.1, color="k")
tr = table.max_iters.max() # training regime number
ax.fill_between([0, tr], [105, 105], alpha=0.3, label="Training Regime")
return ax
def main():
parser = argparse.ArgumentParser(description="Analysis parser")
parser.add_argument("--alpha_list", type=float, nargs="+", default=None,
help="only plot models with alphas in given list")
parser.add_argument("filepath", type=str)
parser.add_argument("--filter", type=float, default=None,
help="cutoff for filtering by training acc?")
parser.add_argument("--plot_name", type=str, default=None, help="where to save image?")
parser.add_argument("--max_iters_list", type=int, nargs="+", default=None,
help="only plot models with max iters in given list")
parser.add_argument("--model_list", type=str, nargs="+", default=None,
help="only plot models with model name in given list")
parser.add_argument("--width_list", type=str, nargs="+", default=None,
help="only plot models with widths in given list")
parser.add_argument("--max", action="store_true", help="add max values to table?")
parser.add_argument("--min", action="store_true", help="add min values too table?")
parser.add_argument("--xlim", type=float, nargs="+", default=None, help="x limits for plotting")
parser.add_argument("--ylim", type=float, nargs="+", default=None, help="y limits for plotting")
args = parser.parse_args()
if args.plot_name is None:
now = datetime.now().strftime("%m%d-%H.%M")
args.plot_name = f"schoop{now}.png"
plot_title = "Schoopy Plot"
else:
plot_title = args.plot_name[:-4]
# get table of results
table = get_table(args.filepath,
args.max,
args.min,
filter_at=args.filter,
max_iters_list=args.max_iters_list,
alpha_list=args.alpha_list,
width_list=args.width_list,
model_list=args.model_list)
# reformat and reindex table for plotting purposes
table.columns = table.columns.map("_".join)
table.columns.name = None
table = table.reset_index()
print(table.round(2).to_markdown())
ax = get_schoopy_plot(table)
ax.legend(fontsize=26, loc="upper left", bbox_to_anchor=(1.0, 0.8))
x_max = table.test_iter.max()
x = np.arange(20, x_max + 1, 10 if (x_max <= 100) else 100)
ax.tick_params(axis="y", labelsize=34)
ax.set_xticks(x)
ax.set_xticklabels(x, fontsize=34, rotation=37)
if args.xlim is None:
ax.set_xlim([x.min() - 0.5, x.max() + 0.5])
else:
ax.set_xlim(args.xlim)
if args.ylim is None:
ax.set_ylim([0, 103])
else:
ax.set_ylim(args.ylim)
ax.set_xlabel("Test-Time Iterations", fontsize=34)
ax.set_ylabel("Accuracy (%)", fontsize=34)
ax.set_title(plot_title, fontsize=34)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
plt.tight_layout()
plt.savefig(args.plot_name)
# plt.show()
if __name__ == "__main__":
main() | deepthinking/data_analysis/make_schoop.py | import argparse
from datetime import datetime
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from make_table import get_table
def get_schoopy_plot(table, error_bars=True):
fig, ax = plt.subplots(figsize=(20, 9))
models = set(table.model)
test_datas = set(table.test_data)
alphas = set(table.alpha)
sns.lineplot(data=table,
x="test_iter",
y="test_acc_mean",
hue="model",
size="alpha",
sizes=(2, 8),
style="test_data" if len(test_datas) > 1 else None,
palette="dark",
dashes=True,
units=None,
legend="auto",
ax=ax)
if error_bars and "test_acc_sem" in table.keys():
for model in models:
for test_data in test_datas:
for alpha in alphas:
data = table[(table.model == model) &
(table.test_data == test_data) &
(table.alpha == alpha)]
plt.fill_between(data.test_iter,
data.test_acc_mean - data.test_acc_sem,
data.test_acc_mean + data.test_acc_sem,
alpha=0.1, color="k")
tr = table.max_iters.max() # training regime number
ax.fill_between([0, tr], [105, 105], alpha=0.3, label="Training Regime")
return ax
def main():
parser = argparse.ArgumentParser(description="Analysis parser")
parser.add_argument("--alpha_list", type=float, nargs="+", default=None,
help="only plot models with alphas in given list")
parser.add_argument("filepath", type=str)
parser.add_argument("--filter", type=float, default=None,
help="cutoff for filtering by training acc?")
parser.add_argument("--plot_name", type=str, default=None, help="where to save image?")
parser.add_argument("--max_iters_list", type=int, nargs="+", default=None,
help="only plot models with max iters in given list")
parser.add_argument("--model_list", type=str, nargs="+", default=None,
help="only plot models with model name in given list")
parser.add_argument("--width_list", type=str, nargs="+", default=None,
help="only plot models with widths in given list")
parser.add_argument("--max", action="store_true", help="add max values to table?")
parser.add_argument("--min", action="store_true", help="add min values too table?")
parser.add_argument("--xlim", type=float, nargs="+", default=None, help="x limits for plotting")
parser.add_argument("--ylim", type=float, nargs="+", default=None, help="y limits for plotting")
args = parser.parse_args()
if args.plot_name is None:
now = datetime.now().strftime("%m%d-%H.%M")
args.plot_name = f"schoop{now}.png"
plot_title = "Schoopy Plot"
else:
plot_title = args.plot_name[:-4]
# get table of results
table = get_table(args.filepath,
args.max,
args.min,
filter_at=args.filter,
max_iters_list=args.max_iters_list,
alpha_list=args.alpha_list,
width_list=args.width_list,
model_list=args.model_list)
# reformat and reindex table for plotting purposes
table.columns = table.columns.map("_".join)
table.columns.name = None
table = table.reset_index()
print(table.round(2).to_markdown())
ax = get_schoopy_plot(table)
ax.legend(fontsize=26, loc="upper left", bbox_to_anchor=(1.0, 0.8))
x_max = table.test_iter.max()
x = np.arange(20, x_max + 1, 10 if (x_max <= 100) else 100)
ax.tick_params(axis="y", labelsize=34)
ax.set_xticks(x)
ax.set_xticklabels(x, fontsize=34, rotation=37)
if args.xlim is None:
ax.set_xlim([x.min() - 0.5, x.max() + 0.5])
else:
ax.set_xlim(args.xlim)
if args.ylim is None:
ax.set_ylim([0, 103])
else:
ax.set_ylim(args.ylim)
ax.set_xlabel("Test-Time Iterations", fontsize=34)
ax.set_ylabel("Accuracy (%)", fontsize=34)
ax.set_title(plot_title, fontsize=34)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
plt.tight_layout()
plt.savefig(args.plot_name)
# plt.show()
if __name__ == "__main__":
main() | 0.493164 | 0.499878 |
import ctypes
from ctypes import wintypes
from . import com
from . import winapi
from .wintype import HRESULT, BSTR, CIMTYPE
_In_ = 1
_Out_ = 2
IWbemObjectSink_Indicate_Idx = 3
IWbemObjectSink_SetStatus_Idx = 4
class IWbemObjectSink(com.IUnknown):
def Indicate(self, object_count, obj_array):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lObjectCount'),
(_In_, 'apObjArray'),
)
_Indicate = prototype(IWbemObjectSink_Indicate_Idx,
'Indicate',
paramflags)
_Indicate.errcheck = winapi.RAISE_NON_ZERO_ERR
_Indicate(self.this,
object_count,
obj_array.this if obj_array else None
)
def SetStatus(self, flags, result, param, obj_param):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
HRESULT,
BSTR,
ctypes.POINTER(IWbemClassObject))
paramflags = ((_In_, 'lFlags'),
(_In_, 'hResult'),
(_In_, 'strParam'),
(_In_, 'pObjParam'),
)
_SetStatus = prototype(IWbemObjectSink_SetStatus_Idx,
'SetStatus',
paramflags)
_SetStatus.errcheck = winapi.RAISE_NON_ZERO_ERR
param_bstr = winapi.SysAllocString(param) if param is not None else None
try:
_SetStatus(self.this,
flags,
result,
param_bstr,
obj_param.this if obj_param else None
)
finally:
if param_bstr is not None:
winapi.SysFreeString(param_bstr)
IWbemQualifierSet_Get_Idx = 3
IWbemQualifierSet_Put_Idx = 4
IWbemQualifierSet_Delete_Idx = 5
IWbemQualifierSet_GetNames_Idx = 6
IWbemQualifierSet_BeginEnumeration_Idx = 7
IWbemQualifierSet_Next_Idx = 8
IWbemQualifierSet_EndEnumeration_Idx = 9
class IWbemQualifierSet(com.IUnknown):
def Get(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_Out_, 'pVal'),
(_Out_, 'plFlavor'),
)
_Get = prototype(IWbemQualifierSet_Get_Idx,
'Get',
paramflags)
_Get.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2 = _Get(self.this,
name,
flags
)
return return_obj, return_obj2
def Put(self, name, val, flavor):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(winapi.VARIANT),
ctypes.c_long)
paramflags = ((_In_, 'wszName'),
(_In_, 'pVal'),
(_In_, 'lFlavor'),
)
_Put = prototype(IWbemQualifierSet_Put_Idx,
'Put',
paramflags)
_Put.errcheck = winapi.RAISE_NON_ZERO_ERR
_Put(self.this,
name,
ctypes.byref(val) if val else None,
flavor
)
def Delete(self, name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR)
paramflags = ((_In_, 'wszName'),
)
_Delete = prototype(IWbemQualifierSet_Delete_Idx,
'Delete',
paramflags)
_Delete.errcheck = winapi.RAISE_NON_ZERO_ERR
_Delete(self.this,
name
)
def GetNames(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pNames'),
)
_GetNames = prototype(IWbemQualifierSet_GetNames_Idx,
'GetNames',
paramflags)
_GetNames.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetNames(self.this,
flags
)
return_obj = ctypes.cast(wintypes.LPVOID(return_obj), ctypes.POINTER(winapi.SAFEARRAY))
return return_obj
def BeginEnumeration(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long)
paramflags = ((_In_, 'lFlags'),
)
_BeginEnumeration = prototype(IWbemQualifierSet_BeginEnumeration_Idx,
'BeginEnumeration',
paramflags)
_BeginEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_BeginEnumeration(self.this,
flags
)
def Next(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR),
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pstrName'),
(_Out_, 'pVal'),
(_Out_, 'plFlavor'),
)
_Next = prototype(IWbemQualifierSet_Next_Idx,
'Next',
paramflags)
_Next.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2, return_obj3 = _Next(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj, return_obj2, return_obj3
def EndEnumeration(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_EndEnumeration = prototype(IWbemQualifierSet_EndEnumeration_Idx,
'EndEnumeration',
paramflags)
_EndEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_EndEnumeration(self.this
)
IWbemClassObject_GetQualifierSet_Idx = 3
IWbemClassObject_Get_Idx = 4
IWbemClassObject_Put_Idx = 5
IWbemClassObject_Delete_Idx = 6
IWbemClassObject_GetNames_Idx = 7
IWbemClassObject_BeginEnumeration_Idx = 8
IWbemClassObject_Next_Idx = 9
IWbemClassObject_EndEnumeration_Idx = 10
IWbemClassObject_GetPropertyQualifierSet_Idx = 11
IWbemClassObject_Clone_Idx = 12
IWbemClassObject_GetObjectText_Idx = 13
IWbemClassObject_SpawnDerivedClass_Idx = 14
IWbemClassObject_SpawnInstance_Idx = 15
IWbemClassObject_CompareTo_Idx = 16
IWbemClassObject_GetPropertyOrigin_Idx = 17
IWbemClassObject_InheritsFrom_Idx = 18
IWbemClassObject_GetMethod_Idx = 19
IWbemClassObject_PutMethod_Idx = 20
IWbemClassObject_DeleteMethod_Idx = 21
IWbemClassObject_BeginMethodEnumeration_Idx = 22
IWbemClassObject_NextMethod_Idx = 23
IWbemClassObject_EndMethodEnumeration_Idx = 24
IWbemClassObject_GetMethodQualifierSet_Idx = 25
IWbemClassObject_GetMethodOrigin_Idx = 26
class IWbemClassObject(com.IUnknown):
def GetQualifierSet(self):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_Out_, 'ppQualSet'),
)
_GetQualifierSet = prototype(IWbemClassObject_GetQualifierSet_Idx,
'GetQualifierSet',
paramflags)
_GetQualifierSet.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetQualifierSet(self.this
)
try:
return_obj = IWbemQualifierSet(return_obj)
except WindowsError:
return_obj = None
return return_obj
def Get(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(CIMTYPE),
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_Out_, 'pVal'),
(_Out_, 'pType'),
(_Out_, 'plFlavor'),
)
_Get = prototype(IWbemClassObject_Get_Idx,
'Get',
paramflags)
_Get.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2, return_obj3 = _Get(self.this,
name,
flags
)
return return_obj, return_obj2, return_obj3
def Put(self, name, flags, val, type_param):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT),
CIMTYPE)
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_In_, 'pVal'),
(_In_, 'Type'),
)
_Put = prototype(IWbemClassObject_Put_Idx,
'Put',
paramflags)
_Put.errcheck = winapi.RAISE_NON_ZERO_ERR
_Put(self.this,
name,
flags,
ctypes.byref(val) if val else None,
type_param
)
def Delete(self, name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR)
paramflags = ((_In_, 'wszName'),
)
_Delete = prototype(IWbemClassObject_Delete_Idx,
'Delete',
paramflags)
_Delete.errcheck = winapi.RAISE_NON_ZERO_ERR
_Delete(self.this,
name
)
def GetNames(self, qualifier_name, flags, qualifier_val):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'wszQualifierName'),
(_In_, 'lFlags'),
(_In_, 'pQualifierVal'),
(_Out_, 'pNames'),
)
_GetNames = prototype(IWbemClassObject_GetNames_Idx,
'GetNames',
paramflags)
_GetNames.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetNames(self.this,
qualifier_name,
flags,
ctypes.byref(qualifier_val) if qualifier_val else None
)
return_obj = ctypes.cast(wintypes.LPVOID(return_obj), ctypes.POINTER(winapi.SAFEARRAY))
return return_obj
def BeginEnumeration(self, enum_flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long)
paramflags = ((_In_, 'lEnumFlags'),
)
_BeginEnumeration = prototype(IWbemClassObject_BeginEnumeration_Idx,
'BeginEnumeration',
paramflags)
_BeginEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_BeginEnumeration(self.this,
enum_flags
)
def Next(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR),
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(CIMTYPE),
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'strName'),
(_Out_, 'pVal'),
(_Out_, 'pType'),
(_Out_, 'plFlavor'),
)
_Next = prototype(IWbemClassObject_Next_Idx,
'Next',
paramflags)
_Next.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2, return_obj3, return_obj4 = _Next(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj, return_obj2, return_obj3, return_obj4
def EndEnumeration(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_EndEnumeration = prototype(IWbemClassObject_EndEnumeration_Idx,
'EndEnumeration',
paramflags)
_EndEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_EndEnumeration(self.this
)
def GetPropertyQualifierSet(self, property_param):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'wszProperty'),
(_Out_, 'ppQualSet'),
)
_GetPropertyQualifierSet = prototype(IWbemClassObject_GetPropertyQualifierSet_Idx,
'GetPropertyQualifierSet',
paramflags)
_GetPropertyQualifierSet.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetPropertyQualifierSet(self.this,
property_param
)
try:
return_obj = IWbemQualifierSet(return_obj)
except WindowsError:
return_obj = None
return return_obj
def Clone(self):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_Out_, 'ppCopy'),
)
_Clone = prototype(IWbemClassObject_Clone_Idx,
'Clone',
paramflags)
_Clone.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _Clone(self.this
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetObjectText(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pstrObjectText'),
)
_GetObjectText = prototype(IWbemClassObject_GetObjectText_Idx,
'GetObjectText',
paramflags)
_GetObjectText.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetObjectText(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj
def SpawnDerivedClass(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'ppNewClass'),
)
_SpawnDerivedClass = prototype(IWbemClassObject_SpawnDerivedClass_Idx,
'SpawnDerivedClass',
paramflags)
_SpawnDerivedClass.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _SpawnDerivedClass(self.this,
flags
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def SpawnInstance(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'ppNewInstance'),
)
_SpawnInstance = prototype(IWbemClassObject_SpawnInstance_Idx,
'SpawnInstance',
paramflags)
_SpawnInstance.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _SpawnInstance(self.this,
flags
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def CompareTo(self, flags, compare_to):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(IWbemClassObject))
paramflags = ((_In_, 'lFlags'),
(_In_, 'pCompareTo'),
)
_CompareTo = prototype(IWbemClassObject_CompareTo_Idx,
'CompareTo',
paramflags)
_CompareTo.errcheck = winapi.RAISE_NON_ZERO_ERR
_CompareTo(self.this,
flags,
compare_to.this if compare_to else None
)
def GetPropertyOrigin(self, name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(BSTR))
paramflags = ((_In_, 'wszName'),
(_Out_, 'pstrClassName'),
)
_GetPropertyOrigin = prototype(IWbemClassObject_GetPropertyOrigin_Idx,
'GetPropertyOrigin',
paramflags)
_GetPropertyOrigin.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetPropertyOrigin(self.this,
name
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj
def InheritsFrom(self, ancestor):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR)
paramflags = ((_In_, 'strAncestor'),
)
_InheritsFrom = prototype(IWbemClassObject_InheritsFrom_Idx,
'InheritsFrom',
paramflags)
_InheritsFrom.errcheck = winapi.RAISE_NON_ZERO_ERR
_InheritsFrom(self.this,
ancestor
)
def GetMethod(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_Out_, 'ppInSignature'),
(_Out_, 'ppOutSignature'),
)
_GetMethod = prototype(IWbemClassObject_GetMethod_Idx,
'GetMethod',
paramflags)
_GetMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2 = _GetMethod(self.this,
name,
flags
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
try:
return_obj2 = IWbemClassObject(return_obj2)
except WindowsError:
return_obj2 = None
return return_obj, return_obj2
def PutMethod(self, name, flags, in_signature, out_signature):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(IWbemClassObject),
ctypes.POINTER(IWbemClassObject))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_In_, 'pInSignature'),
(_In_, 'pOutSignature'),
)
_PutMethod = prototype(IWbemClassObject_PutMethod_Idx,
'PutMethod',
paramflags)
_PutMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
_PutMethod(self.this,
name,
flags,
in_signature.this if in_signature else None,
out_signature.this if out_signature else None
)
def DeleteMethod(self, name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR)
paramflags = ((_In_, 'wszName'),
)
_DeleteMethod = prototype(IWbemClassObject_DeleteMethod_Idx,
'DeleteMethod',
paramflags)
_DeleteMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
_DeleteMethod(self.this,
name
)
def BeginMethodEnumeration(self, enum_flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long)
paramflags = ((_In_, 'lEnumFlags'),
)
_BeginMethodEnumeration = prototype(IWbemClassObject_BeginMethodEnumeration_Idx,
'BeginMethodEnumeration',
paramflags)
_BeginMethodEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_BeginMethodEnumeration(self.this,
enum_flags
)
def NextMethod(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR),
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pstrName'),
(_Out_, 'ppInSignature'),
(_Out_, 'ppOutSignature'),
)
_NextMethod = prototype(IWbemClassObject_NextMethod_Idx,
'NextMethod',
paramflags)
_NextMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2, return_obj3 = _NextMethod(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
try:
return_obj2 = IWbemClassObject(return_obj2)
except WindowsError:
return_obj2 = None
try:
return_obj3 = IWbemClassObject(return_obj3)
except WindowsError:
return_obj3 = None
return return_obj, return_obj2, return_obj3
def EndMethodEnumeration(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_EndMethodEnumeration = prototype(IWbemClassObject_EndMethodEnumeration_Idx,
'EndMethodEnumeration',
paramflags)
_EndMethodEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_EndMethodEnumeration(self.this
)
def GetMethodQualifierSet(self, method):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'wszMethod'),
(_Out_, 'ppQualSet'),
)
_GetMethodQualifierSet = prototype(IWbemClassObject_GetMethodQualifierSet_Idx,
'GetMethodQualifierSet',
paramflags)
_GetMethodQualifierSet.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetMethodQualifierSet(self.this,
method
)
try:
return_obj = IWbemQualifierSet(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetMethodOrigin(self, method_name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(BSTR))
paramflags = ((_In_, 'wszMethodName'),
(_Out_, 'pstrClassName'),
)
_GetMethodOrigin = prototype(IWbemClassObject_GetMethodOrigin_Idx,
'GetMethodOrigin',
paramflags)
_GetMethodOrigin.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetMethodOrigin(self.this,
method_name
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj
IEnumWbemClassObject_Reset_Idx = 3
IEnumWbemClassObject_Next_Idx = 4
IEnumWbemClassObject_NextAsync_Idx = 5
IEnumWbemClassObject_Clone_Idx = 6
IEnumWbemClassObject_Skip_Idx = 7
class IEnumWbemClassObject(com.IUnknown):
def Reset(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_Reset = prototype(IEnumWbemClassObject_Reset_Idx,
'Reset',
paramflags)
_Reset.errcheck = winapi.RAISE_NON_ZERO_ERR
_Reset(self.this
)
def Next(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
wintypes.ULONG,
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.ULONG))
paramflags = ((_In_, 'lTimeout'),
(_In_, 'uCount'),
(_Out_, 'apObjects'),
(_Out_, 'puReturned'),
)
_Next = prototype(IEnumWbemClassObject_Next_Idx,
'Next',
paramflags)
_Next.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2 = _Next(self.this,
timeout,
1
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def NextAsync(self, count, sink):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.ULONG,
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'uCount'),
(_In_, 'pSink'),
)
_NextAsync = prototype(IEnumWbemClassObject_NextAsync_Idx,
'NextAsync',
paramflags)
_NextAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
_NextAsync(self.this,
count,
sink.this if sink else None
)
def Clone(self):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_Out_, 'ppEnum'),
)
_Clone = prototype(IEnumWbemClassObject_Clone_Idx,
'Clone',
paramflags)
_Clone.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _Clone(self.this
)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def Skip(self, timeout, count):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
wintypes.ULONG)
paramflags = ((_In_, 'lTimeout'),
(_In_, 'nCount'),
)
_Skip = prototype(IEnumWbemClassObject_Skip_Idx,
'Skip',
paramflags)
_Skip.errcheck = winapi.RAISE_NON_ZERO_ERR
_Skip(self.this,
timeout,
count
)
IWbemCallResult_GetResultObject_Idx = 3
IWbemCallResult_GetResultString_Idx = 4
IWbemCallResult_GetResultServices_Idx = 5
IWbemCallResult_GetCallStatus_Idx = 6
class IWbemCallResult(com.IUnknown):
def GetResultObject(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lTimeout'),
(_Out_, 'ppResultObject'),
)
_GetResultObject = prototype(IWbemCallResult_GetResultObject_Idx,
'GetResultObject',
paramflags)
_GetResultObject.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetResultObject(self.this,
timeout
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetResultString(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR))
paramflags = ((_In_, 'lTimeout'),
(_Out_, 'pstrResultString'),
)
_GetResultString = prototype(IWbemCallResult_GetResultString_Idx,
'GetResultString',
paramflags)
_GetResultString.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetResultString(self.this,
timeout
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj
def GetResultServices(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lTimeout'),
(_Out_, 'ppServices'),
)
_GetResultServices = prototype(IWbemCallResult_GetResultServices_Idx,
'GetResultServices',
paramflags)
_GetResultServices.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetResultServices(self.this,
timeout
)
try:
return_obj = IWbemServices(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetCallStatus(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'lTimeout'),
(_Out_, 'plStatus'),
)
_GetCallStatus = prototype(IWbemCallResult_GetCallStatus_Idx,
'GetCallStatus',
paramflags)
_GetCallStatus.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetCallStatus(self.this,
timeout
)
return return_obj
IWbemContext_Clone_Idx = 3
IWbemContext_GetNames_Idx = 4
IWbemContext_BeginEnumeration_Idx = 5
IWbemContext_Next_Idx = 6
IWbemContext_EndEnumeration_Idx = 7
IWbemContext_SetValue_Idx = 8
IWbemContext_GetValue_Idx = 9
IWbemContext_DeleteValue_Idx = 10
IWbemContext_DeleteAll_Idx = 11
class IWbemContext(com.IUnknown):
def Clone(self):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_Out_, 'ppNewCopy'),
)
_Clone = prototype(IWbemContext_Clone_Idx,
'Clone',
paramflags)
_Clone.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _Clone(self.this
)
try:
return_obj = IWbemContext(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetNames(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pNames'),
)
_GetNames = prototype(IWbemContext_GetNames_Idx,
'GetNames',
paramflags)
_GetNames.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetNames(self.this,
flags
)
return_obj = ctypes.cast(wintypes.LPVOID(return_obj), ctypes.POINTER(winapi.SAFEARRAY))
return return_obj
def BeginEnumeration(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long)
paramflags = ((_In_, 'lFlags'),
)
_BeginEnumeration = prototype(IWbemContext_BeginEnumeration_Idx,
'BeginEnumeration',
paramflags)
_BeginEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_BeginEnumeration(self.this,
flags
)
def Next(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR),
ctypes.POINTER(winapi.VARIANT))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pstrName'),
(_Out_, 'pValue'),
)
_Next = prototype(IWbemContext_Next_Idx,
'Next',
paramflags)
_Next.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2 = _Next(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj, return_obj2
def EndEnumeration(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_EndEnumeration = prototype(IWbemContext_EndEnumeration_Idx,
'EndEnumeration',
paramflags)
_EndEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_EndEnumeration(self.this
)
def SetValue(self, name, flags, value):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_In_, 'pValue'),
)
_SetValue = prototype(IWbemContext_SetValue_Idx,
'SetValue',
paramflags)
_SetValue.errcheck = winapi.RAISE_NON_ZERO_ERR
_SetValue(self.this,
name,
flags,
ctypes.byref(value) if value else None
)
def GetValue(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_Out_, 'pValue'),
)
_GetValue = prototype(IWbemContext_GetValue_Idx,
'GetValue',
paramflags)
_GetValue.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetValue(self.this,
name,
flags
)
return return_obj
def DeleteValue(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long)
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
)
_DeleteValue = prototype(IWbemContext_DeleteValue_Idx,
'DeleteValue',
paramflags)
_DeleteValue.errcheck = winapi.RAISE_NON_ZERO_ERR
_DeleteValue(self.this,
name,
flags
)
def DeleteAll(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_DeleteAll = prototype(IWbemContext_DeleteAll_Idx,
'DeleteAll',
paramflags)
_DeleteAll.errcheck = winapi.RAISE_NON_ZERO_ERR
_DeleteAll(self.this
)
IWbemServices_OpenNamespace_Idx = 3
IWbemServices_CancelAsyncCall_Idx = 4
IWbemServices_QueryObjectSink_Idx = 5
IWbemServices_GetObject_Idx = 6
IWbemServices_GetObjectAsync_Idx = 7
IWbemServices_PutClass_Idx = 8
IWbemServices_PutClassAsync_Idx = 9
IWbemServices_DeleteClass_Idx = 10
IWbemServices_DeleteClassAsync_Idx = 11
IWbemServices_CreateClassEnum_Idx = 12
IWbemServices_CreateClassEnumAsync_Idx = 13
IWbemServices_PutInstance_Idx = 14
IWbemServices_PutInstanceAsync_Idx = 15
IWbemServices_DeleteInstance_Idx = 16
IWbemServices_DeleteInstanceAsync_Idx = 17
IWbemServices_CreateInstanceEnum_Idx = 18
IWbemServices_CreateInstanceEnumAsync_Idx = 19
IWbemServices_ExecQuery_Idx = 20
IWbemServices_ExecQueryAsync_Idx = 21
IWbemServices_ExecNotificationQuery_Idx = 22
IWbemServices_ExecNotificationQueryAsync_Idx = 23
IWbemServices_ExecMethod_Idx = 24
IWbemServices_ExecMethodAsync_Idx = 25
class IWbemServices(com.IUnknown):
def OpenNamespaceWithResult(self, namespace, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strNamespace'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppWorkingNamespace'),
(_Out_, 'ppResult'),
)
_OpenNamespace = prototype(IWbemServices_OpenNamespace_Idx,
'OpenNamespace',
paramflags)
_OpenNamespace.errcheck = winapi.RAISE_NON_ZERO_ERR
namespace_bstr = winapi.SysAllocString(namespace) if namespace is not None else None
try:
return_obj, return_obj2 = _OpenNamespace(self.this,
namespace_bstr,
flags,
ctx.this if ctx else None
)
finally:
if namespace_bstr is not None:
winapi.SysFreeString(namespace_bstr)
try:
return_obj = IWbemServices(return_obj)
except WindowsError:
return_obj = None
try:
return_obj2 = IWbemCallResult(return_obj2)
except WindowsError:
return_obj2 = None
return return_obj, return_obj2
def OpenNamespace(self, namespace, flags, ctx):
return_obj, return_obj2 = self.OpenNamespaceWithResult(namespace, flags, ctx)
if return_obj2:
return_obj2.Release()
return return_obj
def CancelAsyncCall(self, sink):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'pSink'),
)
_CancelAsyncCall = prototype(IWbemServices_CancelAsyncCall_Idx,
'CancelAsyncCall',
paramflags)
_CancelAsyncCall.errcheck = winapi.RAISE_NON_ZERO_ERR
_CancelAsyncCall(self.this,
sink.this if sink else None
)
def QueryObjectSink(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'ppResponseHandler'),
)
_QueryObjectSink = prototype(IWbemServices_QueryObjectSink_Idx,
'QueryObjectSink',
paramflags)
_QueryObjectSink.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _QueryObjectSink(self.this,
flags
)
try:
return_obj = IWbemObjectSink(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetObjectWithResult(self, object_path, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppObject'),
(_Out_, 'ppCallResult'),
)
_GetObject = prototype(IWbemServices_GetObject_Idx,
'GetObject',
paramflags)
_GetObject.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
try:
return_obj, return_obj2 = _GetObject(self.this,
object_path_bstr,
flags,
ctx.this if ctx else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
try:
return_obj2 = IWbemCallResult(return_obj2)
except WindowsError:
return_obj2 = None
return return_obj, return_obj2
def GetObject(self, object_path, flags, ctx):
return_obj, return_obj2 = self.GetObjectWithResult(object_path, flags, ctx)
if return_obj2:
return_obj2.Release()
return return_obj
def GetObjectAsync(self, object_path, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_GetObjectAsync = prototype(IWbemServices_GetObjectAsync_Idx,
'GetObjectAsync',
paramflags)
_GetObjectAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
try:
_GetObjectAsync(self.this,
object_path_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
def PutClassWithResult(self, object_param, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemClassObject),
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'pObject'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppCallResult'),
)
_PutClass = prototype(IWbemServices_PutClass_Idx,
'PutClass',
paramflags)
_PutClass.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _PutClass(self.this,
object_param.this if object_param else None,
flags,
ctx.this if ctx else None
)
try:
return_obj = IWbemCallResult(return_obj)
except WindowsError:
return_obj = None
return return_obj
def PutClass(self, object_param, flags, ctx):
return_obj = self.PutClassWithResult(object_param, flags, ctx)
if return_obj:
return_obj.Release()
def PutClassAsync(self, object_param, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemClassObject),
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'pObject'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_PutClassAsync = prototype(IWbemServices_PutClassAsync_Idx,
'PutClassAsync',
paramflags)
_PutClassAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
_PutClassAsync(self.this,
object_param.this if object_param else None,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
def DeleteClassWithResult(self, class_param, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strClass'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppCallResult'),
)
_DeleteClass = prototype(IWbemServices_DeleteClass_Idx,
'DeleteClass',
paramflags)
_DeleteClass.errcheck = winapi.RAISE_NON_ZERO_ERR
class_param_bstr = winapi.SysAllocString(class_param) if class_param is not None else None
try:
return_obj = _DeleteClass(self.this,
class_param_bstr,
flags,
ctx.this if ctx else None
)
finally:
if class_param_bstr is not None:
winapi.SysFreeString(class_param_bstr)
try:
return_obj = IWbemCallResult(return_obj)
except WindowsError:
return_obj = None
return return_obj
def DeleteClass(self, class_param, flags, ctx):
return_obj = self.DeleteClassWithResult(class_param, flags, ctx)
if return_obj:
return_obj.Release()
def DeleteClassAsync(self, class_param, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strClass'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_DeleteClassAsync = prototype(IWbemServices_DeleteClassAsync_Idx,
'DeleteClassAsync',
paramflags)
_DeleteClassAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
class_param_bstr = winapi.SysAllocString(class_param) if class_param is not None else None
try:
_DeleteClassAsync(self.this,
class_param_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if class_param_bstr is not None:
winapi.SysFreeString(class_param_bstr)
def CreateClassEnum(self, superclass, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strSuperclass'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppEnum'),
)
_CreateClassEnum = prototype(IWbemServices_CreateClassEnum_Idx,
'CreateClassEnum',
paramflags)
_CreateClassEnum.errcheck = winapi.RAISE_NON_ZERO_ERR
superclass_bstr = winapi.SysAllocString(superclass) if superclass is not None else None
try:
return_obj = _CreateClassEnum(self.this,
superclass_bstr,
flags,
ctx.this if ctx else None
)
finally:
if superclass_bstr is not None:
winapi.SysFreeString(superclass_bstr)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def CreateClassEnumAsync(self, superclass, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strSuperclass'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_CreateClassEnumAsync = prototype(IWbemServices_CreateClassEnumAsync_Idx,
'CreateClassEnumAsync',
paramflags)
_CreateClassEnumAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
superclass_bstr = winapi.SysAllocString(superclass) if superclass is not None else None
try:
_CreateClassEnumAsync(self.this,
superclass_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if superclass_bstr is not None:
winapi.SysFreeString(superclass_bstr)
def PutInstanceWithResult(self, inst, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemClassObject),
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'pInst'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppCallResult'),
)
_PutInstance = prototype(IWbemServices_PutInstance_Idx,
'PutInstance',
paramflags)
_PutInstance.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _PutInstance(self.this,
inst.this if inst else None,
flags,
ctx.this if ctx else None
)
try:
return_obj = IWbemCallResult(return_obj)
except WindowsError:
return_obj = None
return return_obj
def PutInstance(self, inst, flags, ctx):
return_obj = self.PutInstanceWithResult(inst, flags, ctx)
if return_obj:
return_obj.Release()
def PutInstanceAsync(self, inst, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemClassObject),
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'pInst'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_PutInstanceAsync = prototype(IWbemServices_PutInstanceAsync_Idx,
'PutInstanceAsync',
paramflags)
_PutInstanceAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
_PutInstanceAsync(self.this,
inst.this if inst else None,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
def DeleteInstanceWithResult(self, object_path, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppCallResult'),
)
_DeleteInstance = prototype(IWbemServices_DeleteInstance_Idx,
'DeleteInstance',
paramflags)
_DeleteInstance.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
try:
return_obj = _DeleteInstance(self.this,
object_path_bstr,
flags,
ctx.this if ctx else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
try:
return_obj = IWbemCallResult(return_obj)
except WindowsError:
return_obj = None
return return_obj
def DeleteInstance(self, object_path, flags, ctx):
return_obj = self.DeleteInstanceWithResult(object_path, flags, ctx)
if return_obj:
return_obj.Release()
def DeleteInstanceAsync(self, object_path, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_DeleteInstanceAsync = prototype(IWbemServices_DeleteInstanceAsync_Idx,
'DeleteInstanceAsync',
paramflags)
_DeleteInstanceAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
try:
_DeleteInstanceAsync(self.this,
object_path_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
def CreateInstanceEnum(self, filter_param, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strFilter'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppEnum'),
)
_CreateInstanceEnum = prototype(IWbemServices_CreateInstanceEnum_Idx,
'CreateInstanceEnum',
paramflags)
_CreateInstanceEnum.errcheck = winapi.RAISE_NON_ZERO_ERR
filter_param_bstr = winapi.SysAllocString(filter_param) if filter_param is not None else None
try:
return_obj = _CreateInstanceEnum(self.this,
filter_param_bstr,
flags,
ctx.this if ctx else None
)
finally:
if filter_param_bstr is not None:
winapi.SysFreeString(filter_param_bstr)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def CreateInstanceEnumAsync(self, filter_param, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strFilter'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_CreateInstanceEnumAsync = prototype(IWbemServices_CreateInstanceEnumAsync_Idx,
'CreateInstanceEnumAsync',
paramflags)
_CreateInstanceEnumAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
filter_param_bstr = winapi.SysAllocString(filter_param) if filter_param is not None else None
try:
_CreateInstanceEnumAsync(self.this,
filter_param_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if filter_param_bstr is not None:
winapi.SysFreeString(filter_param_bstr)
def ExecQuery(self, query_language, query, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strQueryLanguage'),
(_In_, 'strQuery'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppEnum'),
)
_ExecQuery = prototype(IWbemServices_ExecQuery_Idx,
'ExecQuery',
paramflags)
_ExecQuery.errcheck = winapi.RAISE_NON_ZERO_ERR
query_language_bstr = winapi.SysAllocString(query_language) if query_language is not None else None
query_bstr = winapi.SysAllocString(query) if query is not None else None
try:
return_obj = _ExecQuery(self.this,
query_language_bstr,
query_bstr,
flags,
ctx.this if ctx else None
)
finally:
if query_language_bstr is not None:
winapi.SysFreeString(query_language_bstr)
if query_bstr is not None:
winapi.SysFreeString(query_bstr)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def ExecQueryAsync(self, query_language, query, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strQueryLanguage'),
(_In_, 'strQuery'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_ExecQueryAsync = prototype(IWbemServices_ExecQueryAsync_Idx,
'ExecQueryAsync',
paramflags)
_ExecQueryAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
query_language_bstr = winapi.SysAllocString(query_language) if query_language is not None else None
query_bstr = winapi.SysAllocString(query) if query is not None else None
try:
_ExecQueryAsync(self.this,
query_language_bstr,
query_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if query_language_bstr is not None:
winapi.SysFreeString(query_language_bstr)
if query_bstr is not None:
winapi.SysFreeString(query_bstr)
def ExecNotificationQuery(self, query_language, query, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strQueryLanguage'),
(_In_, 'strQuery'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppEnum'),
)
_ExecNotificationQuery = prototype(IWbemServices_ExecNotificationQuery_Idx,
'ExecNotificationQuery',
paramflags)
_ExecNotificationQuery.errcheck = winapi.RAISE_NON_ZERO_ERR
query_language_bstr = winapi.SysAllocString(query_language) if query_language is not None else None
query_bstr = winapi.SysAllocString(query) if query is not None else None
try:
return_obj = _ExecNotificationQuery(self.this,
query_language_bstr,
query_bstr,
flags,
ctx.this if ctx else None
)
finally:
if query_language_bstr is not None:
winapi.SysFreeString(query_language_bstr)
if query_bstr is not None:
winapi.SysFreeString(query_bstr)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def ExecNotificationQueryAsync(self, query_language, query, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strQueryLanguage'),
(_In_, 'strQuery'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_ExecNotificationQueryAsync = prototype(IWbemServices_ExecNotificationQueryAsync_Idx,
'ExecNotificationQueryAsync',
paramflags)
_ExecNotificationQueryAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
query_language_bstr = winapi.SysAllocString(query_language) if query_language is not None else None
query_bstr = winapi.SysAllocString(query) if query is not None else None
try:
_ExecNotificationQueryAsync(self.this,
query_language_bstr,
query_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if query_language_bstr is not None:
winapi.SysFreeString(query_language_bstr)
if query_bstr is not None:
winapi.SysFreeString(query_bstr)
def ExecMethodWithResult(self, object_path, method_name, flags, ctx, in_params):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemClassObject),
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'strMethodName'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pInParams'),
(_Out_, 'ppOutParams'),
(_Out_, 'ppCallResult'),
)
_ExecMethod = prototype(IWbemServices_ExecMethod_Idx,
'ExecMethod',
paramflags)
_ExecMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
method_name_bstr = winapi.SysAllocString(method_name) if method_name is not None else None
try:
return_obj, return_obj2 = _ExecMethod(self.this,
object_path_bstr,
method_name_bstr,
flags,
ctx.this if ctx else None,
in_params.this if in_params else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
if method_name_bstr is not None:
winapi.SysFreeString(method_name_bstr)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
try:
return_obj2 = IWbemCallResult(return_obj2)
except WindowsError:
return_obj2 = None
return return_obj, return_obj2
def ExecMethod(self, object_path, method_name, flags, ctx, in_params):
return_obj, return_obj2 = self.ExecMethodWithResult(object_path, method_name, flags, ctx, in_params)
if return_obj2:
return_obj2.Release()
return return_obj
def ExecMethodAsync(self, object_path, method_name, flags, ctx, in_params, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemClassObject),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'strMethodName'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pInParams'),
(_In_, 'pResponseHandler'),
)
_ExecMethodAsync = prototype(IWbemServices_ExecMethodAsync_Idx,
'ExecMethodAsync',
paramflags)
_ExecMethodAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
method_name_bstr = winapi.SysAllocString(method_name) if method_name is not None else None
try:
_ExecMethodAsync(self.this,
object_path_bstr,
method_name_bstr,
flags,
ctx.this if ctx else None,
in_params.this if in_params else None,
response_handler.this if response_handler else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
if method_name_bstr is not None:
winapi.SysFreeString(method_name_bstr)
IWbemLocator_ConnectServer_Idx = 3
class IWbemLocator(com.IUnknown):
def ConnectServer(self, network_resource, user, password, locale, security_flags, authority, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
BSTR,
BSTR,
ctypes.c_long,
BSTR,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strNetworkResource'),
(_In_, 'strUser'),
(_In_, 'strPassword'),
(_In_, 'strLocale'),
(_In_, 'lSecurityFlags'),
(_In_, 'strAuthority'),
(_In_, 'pCtx'),
(_Out_, 'ppNamespace'),
)
_ConnectServer = prototype(IWbemLocator_ConnectServer_Idx,
'ConnectServer',
paramflags)
_ConnectServer.errcheck = winapi.RAISE_NON_ZERO_ERR
network_resource_bstr = winapi.SysAllocString(network_resource) if network_resource is not None else None
user_bstr = winapi.SysAllocString(user) if user is not None else None
password_bstr = winapi.SysAllocString(password) if password is not None else None
locale_bstr = winapi.SysAllocString(locale) if locale is not None else None
authority_bstr = winapi.SysAllocString(authority) if authority is not None else None
try:
return_obj = _ConnectServer(self.this,
network_resource_bstr,
user_bstr,
password_bstr,
locale_bstr,
security_flags,
authority_bstr,
ctx.this if ctx else None
)
finally:
if network_resource_bstr is not None:
winapi.SysFreeString(network_resource_bstr)
if user_bstr is not None:
winapi.SysFreeString(user_bstr)
if password_bstr is not None:
winapi.SysFreeString(password_bstr)
if locale_bstr is not None:
winapi.SysFreeString(locale_bstr)
if authority_bstr is not None:
winapi.SysFreeString(authority_bstr)
try:
return_obj = IWbemServices(return_obj)
except WindowsError:
return_obj = None
return return_obj
class WMI(com.COM):
'''
Wrapper class for WMI interactions. WMI initialization / uninitialization are done via ctxmgr.
N.B. If using this class, do not call init() and fini() directly. Only use through via ctxmgr
'''
def __init__(self,
net_resource,
user=None,
password=<PASSWORD>,
locale=None,
sec_flags=0,
auth=None,
ctx=None,
cls_ctx=com.CLSCTX_INPROC_SERVER,
authn_svc=winapi.RPC_C_AUTHN_WINNT,
authz_svc=winapi.RPC_C_AUTHZ_NONE,
spn=None,
auth_info=None,
coinit=com.COINIT_MULTITHREADED,
authn_level=winapi.RPC_C_AUTHN_LEVEL_DEFAULT,
imp_level=winapi.RPC_C_IMP_LEVEL_IMPERSONATE,
auth_list=None,
capabilities=winapi.EOAC_NONE):
self._net_resource = net_resource
self._user = user
self._password = password
self._locale = locale
self._sec_flags = sec_flags
self._auth = auth
self._ctx = ctx
self._cls_ctx = cls_ctx
self._authn_svc = authn_svc
self._authz_svc = authz_svc
self._spn = spn
self._auth_info = auth_info
self._authn_level = authn_level
self._imp_level = imp_level
self._auth_list = auth_list
self._capabilities = capabilities
self.service = None
super(WMI, self).__init__(coinit)
def __enter__(self):
self.init()
return self.service
def __exit__(self, exc_type, exc_val, exc_tb):
self.fini()
def init(self):
super(WMI, self).init()
self.initialize_security(None,
-1,
None,
self._authn_level,
self._imp_level,
self._auth_list,
self._capabilities)
locator = self.create_instance(winapi.CLSID_WbemLocator,
None,
self._cls_ctx,
winapi.IID_IWbemLocator,
IWbemLocator)
try:
self.service = locator.ConnectServer(self._net_resource,
self._user,
self._password,
self._locale,
self._sec_flags,
self._auth,
self._ctx)
finally:
locator.Release()
self.set_proxy_blanket(self.service.this,
self._authn_svc,
self._authz_svc,
self._spn,
self._authn_level,
self._imp_level,
self._auth_info,
self._capabilities)
def fini(self):
while self.service.Release():
pass
super(WMI, self).fini() | cwmi/wmi.py |
import ctypes
from ctypes import wintypes
from . import com
from . import winapi
from .wintype import HRESULT, BSTR, CIMTYPE
_In_ = 1
_Out_ = 2
IWbemObjectSink_Indicate_Idx = 3
IWbemObjectSink_SetStatus_Idx = 4
class IWbemObjectSink(com.IUnknown):
def Indicate(self, object_count, obj_array):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lObjectCount'),
(_In_, 'apObjArray'),
)
_Indicate = prototype(IWbemObjectSink_Indicate_Idx,
'Indicate',
paramflags)
_Indicate.errcheck = winapi.RAISE_NON_ZERO_ERR
_Indicate(self.this,
object_count,
obj_array.this if obj_array else None
)
def SetStatus(self, flags, result, param, obj_param):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
HRESULT,
BSTR,
ctypes.POINTER(IWbemClassObject))
paramflags = ((_In_, 'lFlags'),
(_In_, 'hResult'),
(_In_, 'strParam'),
(_In_, 'pObjParam'),
)
_SetStatus = prototype(IWbemObjectSink_SetStatus_Idx,
'SetStatus',
paramflags)
_SetStatus.errcheck = winapi.RAISE_NON_ZERO_ERR
param_bstr = winapi.SysAllocString(param) if param is not None else None
try:
_SetStatus(self.this,
flags,
result,
param_bstr,
obj_param.this if obj_param else None
)
finally:
if param_bstr is not None:
winapi.SysFreeString(param_bstr)
IWbemQualifierSet_Get_Idx = 3
IWbemQualifierSet_Put_Idx = 4
IWbemQualifierSet_Delete_Idx = 5
IWbemQualifierSet_GetNames_Idx = 6
IWbemQualifierSet_BeginEnumeration_Idx = 7
IWbemQualifierSet_Next_Idx = 8
IWbemQualifierSet_EndEnumeration_Idx = 9
class IWbemQualifierSet(com.IUnknown):
def Get(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_Out_, 'pVal'),
(_Out_, 'plFlavor'),
)
_Get = prototype(IWbemQualifierSet_Get_Idx,
'Get',
paramflags)
_Get.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2 = _Get(self.this,
name,
flags
)
return return_obj, return_obj2
def Put(self, name, val, flavor):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(winapi.VARIANT),
ctypes.c_long)
paramflags = ((_In_, 'wszName'),
(_In_, 'pVal'),
(_In_, 'lFlavor'),
)
_Put = prototype(IWbemQualifierSet_Put_Idx,
'Put',
paramflags)
_Put.errcheck = winapi.RAISE_NON_ZERO_ERR
_Put(self.this,
name,
ctypes.byref(val) if val else None,
flavor
)
def Delete(self, name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR)
paramflags = ((_In_, 'wszName'),
)
_Delete = prototype(IWbemQualifierSet_Delete_Idx,
'Delete',
paramflags)
_Delete.errcheck = winapi.RAISE_NON_ZERO_ERR
_Delete(self.this,
name
)
def GetNames(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pNames'),
)
_GetNames = prototype(IWbemQualifierSet_GetNames_Idx,
'GetNames',
paramflags)
_GetNames.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetNames(self.this,
flags
)
return_obj = ctypes.cast(wintypes.LPVOID(return_obj), ctypes.POINTER(winapi.SAFEARRAY))
return return_obj
def BeginEnumeration(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long)
paramflags = ((_In_, 'lFlags'),
)
_BeginEnumeration = prototype(IWbemQualifierSet_BeginEnumeration_Idx,
'BeginEnumeration',
paramflags)
_BeginEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_BeginEnumeration(self.this,
flags
)
def Next(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR),
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pstrName'),
(_Out_, 'pVal'),
(_Out_, 'plFlavor'),
)
_Next = prototype(IWbemQualifierSet_Next_Idx,
'Next',
paramflags)
_Next.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2, return_obj3 = _Next(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj, return_obj2, return_obj3
def EndEnumeration(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_EndEnumeration = prototype(IWbemQualifierSet_EndEnumeration_Idx,
'EndEnumeration',
paramflags)
_EndEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_EndEnumeration(self.this
)
IWbemClassObject_GetQualifierSet_Idx = 3
IWbemClassObject_Get_Idx = 4
IWbemClassObject_Put_Idx = 5
IWbemClassObject_Delete_Idx = 6
IWbemClassObject_GetNames_Idx = 7
IWbemClassObject_BeginEnumeration_Idx = 8
IWbemClassObject_Next_Idx = 9
IWbemClassObject_EndEnumeration_Idx = 10
IWbemClassObject_GetPropertyQualifierSet_Idx = 11
IWbemClassObject_Clone_Idx = 12
IWbemClassObject_GetObjectText_Idx = 13
IWbemClassObject_SpawnDerivedClass_Idx = 14
IWbemClassObject_SpawnInstance_Idx = 15
IWbemClassObject_CompareTo_Idx = 16
IWbemClassObject_GetPropertyOrigin_Idx = 17
IWbemClassObject_InheritsFrom_Idx = 18
IWbemClassObject_GetMethod_Idx = 19
IWbemClassObject_PutMethod_Idx = 20
IWbemClassObject_DeleteMethod_Idx = 21
IWbemClassObject_BeginMethodEnumeration_Idx = 22
IWbemClassObject_NextMethod_Idx = 23
IWbemClassObject_EndMethodEnumeration_Idx = 24
IWbemClassObject_GetMethodQualifierSet_Idx = 25
IWbemClassObject_GetMethodOrigin_Idx = 26
class IWbemClassObject(com.IUnknown):
def GetQualifierSet(self):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_Out_, 'ppQualSet'),
)
_GetQualifierSet = prototype(IWbemClassObject_GetQualifierSet_Idx,
'GetQualifierSet',
paramflags)
_GetQualifierSet.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetQualifierSet(self.this
)
try:
return_obj = IWbemQualifierSet(return_obj)
except WindowsError:
return_obj = None
return return_obj
def Get(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(CIMTYPE),
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_Out_, 'pVal'),
(_Out_, 'pType'),
(_Out_, 'plFlavor'),
)
_Get = prototype(IWbemClassObject_Get_Idx,
'Get',
paramflags)
_Get.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2, return_obj3 = _Get(self.this,
name,
flags
)
return return_obj, return_obj2, return_obj3
def Put(self, name, flags, val, type_param):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT),
CIMTYPE)
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_In_, 'pVal'),
(_In_, 'Type'),
)
_Put = prototype(IWbemClassObject_Put_Idx,
'Put',
paramflags)
_Put.errcheck = winapi.RAISE_NON_ZERO_ERR
_Put(self.this,
name,
flags,
ctypes.byref(val) if val else None,
type_param
)
def Delete(self, name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR)
paramflags = ((_In_, 'wszName'),
)
_Delete = prototype(IWbemClassObject_Delete_Idx,
'Delete',
paramflags)
_Delete.errcheck = winapi.RAISE_NON_ZERO_ERR
_Delete(self.this,
name
)
def GetNames(self, qualifier_name, flags, qualifier_val):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'wszQualifierName'),
(_In_, 'lFlags'),
(_In_, 'pQualifierVal'),
(_Out_, 'pNames'),
)
_GetNames = prototype(IWbemClassObject_GetNames_Idx,
'GetNames',
paramflags)
_GetNames.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetNames(self.this,
qualifier_name,
flags,
ctypes.byref(qualifier_val) if qualifier_val else None
)
return_obj = ctypes.cast(wintypes.LPVOID(return_obj), ctypes.POINTER(winapi.SAFEARRAY))
return return_obj
def BeginEnumeration(self, enum_flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long)
paramflags = ((_In_, 'lEnumFlags'),
)
_BeginEnumeration = prototype(IWbemClassObject_BeginEnumeration_Idx,
'BeginEnumeration',
paramflags)
_BeginEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_BeginEnumeration(self.this,
enum_flags
)
def Next(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR),
ctypes.POINTER(winapi.VARIANT),
ctypes.POINTER(CIMTYPE),
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'strName'),
(_Out_, 'pVal'),
(_Out_, 'pType'),
(_Out_, 'plFlavor'),
)
_Next = prototype(IWbemClassObject_Next_Idx,
'Next',
paramflags)
_Next.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2, return_obj3, return_obj4 = _Next(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj, return_obj2, return_obj3, return_obj4
def EndEnumeration(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_EndEnumeration = prototype(IWbemClassObject_EndEnumeration_Idx,
'EndEnumeration',
paramflags)
_EndEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_EndEnumeration(self.this
)
def GetPropertyQualifierSet(self, property_param):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'wszProperty'),
(_Out_, 'ppQualSet'),
)
_GetPropertyQualifierSet = prototype(IWbemClassObject_GetPropertyQualifierSet_Idx,
'GetPropertyQualifierSet',
paramflags)
_GetPropertyQualifierSet.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetPropertyQualifierSet(self.this,
property_param
)
try:
return_obj = IWbemQualifierSet(return_obj)
except WindowsError:
return_obj = None
return return_obj
def Clone(self):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_Out_, 'ppCopy'),
)
_Clone = prototype(IWbemClassObject_Clone_Idx,
'Clone',
paramflags)
_Clone.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _Clone(self.this
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetObjectText(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pstrObjectText'),
)
_GetObjectText = prototype(IWbemClassObject_GetObjectText_Idx,
'GetObjectText',
paramflags)
_GetObjectText.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetObjectText(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj
def SpawnDerivedClass(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'ppNewClass'),
)
_SpawnDerivedClass = prototype(IWbemClassObject_SpawnDerivedClass_Idx,
'SpawnDerivedClass',
paramflags)
_SpawnDerivedClass.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _SpawnDerivedClass(self.this,
flags
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def SpawnInstance(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'ppNewInstance'),
)
_SpawnInstance = prototype(IWbemClassObject_SpawnInstance_Idx,
'SpawnInstance',
paramflags)
_SpawnInstance.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _SpawnInstance(self.this,
flags
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def CompareTo(self, flags, compare_to):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(IWbemClassObject))
paramflags = ((_In_, 'lFlags'),
(_In_, 'pCompareTo'),
)
_CompareTo = prototype(IWbemClassObject_CompareTo_Idx,
'CompareTo',
paramflags)
_CompareTo.errcheck = winapi.RAISE_NON_ZERO_ERR
_CompareTo(self.this,
flags,
compare_to.this if compare_to else None
)
def GetPropertyOrigin(self, name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(BSTR))
paramflags = ((_In_, 'wszName'),
(_Out_, 'pstrClassName'),
)
_GetPropertyOrigin = prototype(IWbemClassObject_GetPropertyOrigin_Idx,
'GetPropertyOrigin',
paramflags)
_GetPropertyOrigin.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetPropertyOrigin(self.this,
name
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj
def InheritsFrom(self, ancestor):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR)
paramflags = ((_In_, 'strAncestor'),
)
_InheritsFrom = prototype(IWbemClassObject_InheritsFrom_Idx,
'InheritsFrom',
paramflags)
_InheritsFrom.errcheck = winapi.RAISE_NON_ZERO_ERR
_InheritsFrom(self.this,
ancestor
)
def GetMethod(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_Out_, 'ppInSignature'),
(_Out_, 'ppOutSignature'),
)
_GetMethod = prototype(IWbemClassObject_GetMethod_Idx,
'GetMethod',
paramflags)
_GetMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2 = _GetMethod(self.this,
name,
flags
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
try:
return_obj2 = IWbemClassObject(return_obj2)
except WindowsError:
return_obj2 = None
return return_obj, return_obj2
def PutMethod(self, name, flags, in_signature, out_signature):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(IWbemClassObject),
ctypes.POINTER(IWbemClassObject))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_In_, 'pInSignature'),
(_In_, 'pOutSignature'),
)
_PutMethod = prototype(IWbemClassObject_PutMethod_Idx,
'PutMethod',
paramflags)
_PutMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
_PutMethod(self.this,
name,
flags,
in_signature.this if in_signature else None,
out_signature.this if out_signature else None
)
def DeleteMethod(self, name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR)
paramflags = ((_In_, 'wszName'),
)
_DeleteMethod = prototype(IWbemClassObject_DeleteMethod_Idx,
'DeleteMethod',
paramflags)
_DeleteMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
_DeleteMethod(self.this,
name
)
def BeginMethodEnumeration(self, enum_flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long)
paramflags = ((_In_, 'lEnumFlags'),
)
_BeginMethodEnumeration = prototype(IWbemClassObject_BeginMethodEnumeration_Idx,
'BeginMethodEnumeration',
paramflags)
_BeginMethodEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_BeginMethodEnumeration(self.this,
enum_flags
)
def NextMethod(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR),
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pstrName'),
(_Out_, 'ppInSignature'),
(_Out_, 'ppOutSignature'),
)
_NextMethod = prototype(IWbemClassObject_NextMethod_Idx,
'NextMethod',
paramflags)
_NextMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2, return_obj3 = _NextMethod(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
try:
return_obj2 = IWbemClassObject(return_obj2)
except WindowsError:
return_obj2 = None
try:
return_obj3 = IWbemClassObject(return_obj3)
except WindowsError:
return_obj3 = None
return return_obj, return_obj2, return_obj3
def EndMethodEnumeration(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_EndMethodEnumeration = prototype(IWbemClassObject_EndMethodEnumeration_Idx,
'EndMethodEnumeration',
paramflags)
_EndMethodEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_EndMethodEnumeration(self.this
)
def GetMethodQualifierSet(self, method):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'wszMethod'),
(_Out_, 'ppQualSet'),
)
_GetMethodQualifierSet = prototype(IWbemClassObject_GetMethodQualifierSet_Idx,
'GetMethodQualifierSet',
paramflags)
_GetMethodQualifierSet.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetMethodQualifierSet(self.this,
method
)
try:
return_obj = IWbemQualifierSet(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetMethodOrigin(self, method_name):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.POINTER(BSTR))
paramflags = ((_In_, 'wszMethodName'),
(_Out_, 'pstrClassName'),
)
_GetMethodOrigin = prototype(IWbemClassObject_GetMethodOrigin_Idx,
'GetMethodOrigin',
paramflags)
_GetMethodOrigin.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetMethodOrigin(self.this,
method_name
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj
IEnumWbemClassObject_Reset_Idx = 3
IEnumWbemClassObject_Next_Idx = 4
IEnumWbemClassObject_NextAsync_Idx = 5
IEnumWbemClassObject_Clone_Idx = 6
IEnumWbemClassObject_Skip_Idx = 7
class IEnumWbemClassObject(com.IUnknown):
def Reset(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_Reset = prototype(IEnumWbemClassObject_Reset_Idx,
'Reset',
paramflags)
_Reset.errcheck = winapi.RAISE_NON_ZERO_ERR
_Reset(self.this
)
def Next(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
wintypes.ULONG,
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.ULONG))
paramflags = ((_In_, 'lTimeout'),
(_In_, 'uCount'),
(_Out_, 'apObjects'),
(_Out_, 'puReturned'),
)
_Next = prototype(IEnumWbemClassObject_Next_Idx,
'Next',
paramflags)
_Next.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2 = _Next(self.this,
timeout,
1
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def NextAsync(self, count, sink):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.ULONG,
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'uCount'),
(_In_, 'pSink'),
)
_NextAsync = prototype(IEnumWbemClassObject_NextAsync_Idx,
'NextAsync',
paramflags)
_NextAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
_NextAsync(self.this,
count,
sink.this if sink else None
)
def Clone(self):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_Out_, 'ppEnum'),
)
_Clone = prototype(IEnumWbemClassObject_Clone_Idx,
'Clone',
paramflags)
_Clone.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _Clone(self.this
)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def Skip(self, timeout, count):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
wintypes.ULONG)
paramflags = ((_In_, 'lTimeout'),
(_In_, 'nCount'),
)
_Skip = prototype(IEnumWbemClassObject_Skip_Idx,
'Skip',
paramflags)
_Skip.errcheck = winapi.RAISE_NON_ZERO_ERR
_Skip(self.this,
timeout,
count
)
IWbemCallResult_GetResultObject_Idx = 3
IWbemCallResult_GetResultString_Idx = 4
IWbemCallResult_GetResultServices_Idx = 5
IWbemCallResult_GetCallStatus_Idx = 6
class IWbemCallResult(com.IUnknown):
def GetResultObject(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lTimeout'),
(_Out_, 'ppResultObject'),
)
_GetResultObject = prototype(IWbemCallResult_GetResultObject_Idx,
'GetResultObject',
paramflags)
_GetResultObject.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetResultObject(self.this,
timeout
)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetResultString(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR))
paramflags = ((_In_, 'lTimeout'),
(_Out_, 'pstrResultString'),
)
_GetResultString = prototype(IWbemCallResult_GetResultString_Idx,
'GetResultString',
paramflags)
_GetResultString.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetResultString(self.this,
timeout
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj
def GetResultServices(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lTimeout'),
(_Out_, 'ppServices'),
)
_GetResultServices = prototype(IWbemCallResult_GetResultServices_Idx,
'GetResultServices',
paramflags)
_GetResultServices.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetResultServices(self.this,
timeout
)
try:
return_obj = IWbemServices(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetCallStatus(self, timeout):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(ctypes.c_long))
paramflags = ((_In_, 'lTimeout'),
(_Out_, 'plStatus'),
)
_GetCallStatus = prototype(IWbemCallResult_GetCallStatus_Idx,
'GetCallStatus',
paramflags)
_GetCallStatus.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetCallStatus(self.this,
timeout
)
return return_obj
IWbemContext_Clone_Idx = 3
IWbemContext_GetNames_Idx = 4
IWbemContext_BeginEnumeration_Idx = 5
IWbemContext_Next_Idx = 6
IWbemContext_EndEnumeration_Idx = 7
IWbemContext_SetValue_Idx = 8
IWbemContext_GetValue_Idx = 9
IWbemContext_DeleteValue_Idx = 10
IWbemContext_DeleteAll_Idx = 11
class IWbemContext(com.IUnknown):
def Clone(self):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_Out_, 'ppNewCopy'),
)
_Clone = prototype(IWbemContext_Clone_Idx,
'Clone',
paramflags)
_Clone.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _Clone(self.this
)
try:
return_obj = IWbemContext(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetNames(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pNames'),
)
_GetNames = prototype(IWbemContext_GetNames_Idx,
'GetNames',
paramflags)
_GetNames.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetNames(self.this,
flags
)
return_obj = ctypes.cast(wintypes.LPVOID(return_obj), ctypes.POINTER(winapi.SAFEARRAY))
return return_obj
def BeginEnumeration(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long)
paramflags = ((_In_, 'lFlags'),
)
_BeginEnumeration = prototype(IWbemContext_BeginEnumeration_Idx,
'BeginEnumeration',
paramflags)
_BeginEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_BeginEnumeration(self.this,
flags
)
def Next(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(BSTR),
ctypes.POINTER(winapi.VARIANT))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'pstrName'),
(_Out_, 'pValue'),
)
_Next = prototype(IWbemContext_Next_Idx,
'Next',
paramflags)
_Next.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj, return_obj2 = _Next(self.this,
flags
)
return_obj = winapi.convert_bstr_to_str(return_obj)
return return_obj, return_obj2
def EndEnumeration(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_EndEnumeration = prototype(IWbemContext_EndEnumeration_Idx,
'EndEnumeration',
paramflags)
_EndEnumeration.errcheck = winapi.RAISE_NON_ZERO_ERR
_EndEnumeration(self.this
)
def SetValue(self, name, flags, value):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_In_, 'pValue'),
)
_SetValue = prototype(IWbemContext_SetValue_Idx,
'SetValue',
paramflags)
_SetValue.errcheck = winapi.RAISE_NON_ZERO_ERR
_SetValue(self.this,
name,
flags,
ctypes.byref(value) if value else None
)
def GetValue(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long,
ctypes.POINTER(winapi.VARIANT))
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
(_Out_, 'pValue'),
)
_GetValue = prototype(IWbemContext_GetValue_Idx,
'GetValue',
paramflags)
_GetValue.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _GetValue(self.this,
name,
flags
)
return return_obj
def DeleteValue(self, name, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
wintypes.LPCWSTR,
ctypes.c_long)
paramflags = ((_In_, 'wszName'),
(_In_, 'lFlags'),
)
_DeleteValue = prototype(IWbemContext_DeleteValue_Idx,
'DeleteValue',
paramflags)
_DeleteValue.errcheck = winapi.RAISE_NON_ZERO_ERR
_DeleteValue(self.this,
name,
flags
)
def DeleteAll(self):
prototype = ctypes.WINFUNCTYPE(HRESULT)
paramflags = ()
_DeleteAll = prototype(IWbemContext_DeleteAll_Idx,
'DeleteAll',
paramflags)
_DeleteAll.errcheck = winapi.RAISE_NON_ZERO_ERR
_DeleteAll(self.this
)
IWbemServices_OpenNamespace_Idx = 3
IWbemServices_CancelAsyncCall_Idx = 4
IWbemServices_QueryObjectSink_Idx = 5
IWbemServices_GetObject_Idx = 6
IWbemServices_GetObjectAsync_Idx = 7
IWbemServices_PutClass_Idx = 8
IWbemServices_PutClassAsync_Idx = 9
IWbemServices_DeleteClass_Idx = 10
IWbemServices_DeleteClassAsync_Idx = 11
IWbemServices_CreateClassEnum_Idx = 12
IWbemServices_CreateClassEnumAsync_Idx = 13
IWbemServices_PutInstance_Idx = 14
IWbemServices_PutInstanceAsync_Idx = 15
IWbemServices_DeleteInstance_Idx = 16
IWbemServices_DeleteInstanceAsync_Idx = 17
IWbemServices_CreateInstanceEnum_Idx = 18
IWbemServices_CreateInstanceEnumAsync_Idx = 19
IWbemServices_ExecQuery_Idx = 20
IWbemServices_ExecQueryAsync_Idx = 21
IWbemServices_ExecNotificationQuery_Idx = 22
IWbemServices_ExecNotificationQueryAsync_Idx = 23
IWbemServices_ExecMethod_Idx = 24
IWbemServices_ExecMethodAsync_Idx = 25
class IWbemServices(com.IUnknown):
def OpenNamespaceWithResult(self, namespace, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strNamespace'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppWorkingNamespace'),
(_Out_, 'ppResult'),
)
_OpenNamespace = prototype(IWbemServices_OpenNamespace_Idx,
'OpenNamespace',
paramflags)
_OpenNamespace.errcheck = winapi.RAISE_NON_ZERO_ERR
namespace_bstr = winapi.SysAllocString(namespace) if namespace is not None else None
try:
return_obj, return_obj2 = _OpenNamespace(self.this,
namespace_bstr,
flags,
ctx.this if ctx else None
)
finally:
if namespace_bstr is not None:
winapi.SysFreeString(namespace_bstr)
try:
return_obj = IWbemServices(return_obj)
except WindowsError:
return_obj = None
try:
return_obj2 = IWbemCallResult(return_obj2)
except WindowsError:
return_obj2 = None
return return_obj, return_obj2
def OpenNamespace(self, namespace, flags, ctx):
return_obj, return_obj2 = self.OpenNamespaceWithResult(namespace, flags, ctx)
if return_obj2:
return_obj2.Release()
return return_obj
def CancelAsyncCall(self, sink):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'pSink'),
)
_CancelAsyncCall = prototype(IWbemServices_CancelAsyncCall_Idx,
'CancelAsyncCall',
paramflags)
_CancelAsyncCall.errcheck = winapi.RAISE_NON_ZERO_ERR
_CancelAsyncCall(self.this,
sink.this if sink else None
)
def QueryObjectSink(self, flags):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.c_long,
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'lFlags'),
(_Out_, 'ppResponseHandler'),
)
_QueryObjectSink = prototype(IWbemServices_QueryObjectSink_Idx,
'QueryObjectSink',
paramflags)
_QueryObjectSink.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _QueryObjectSink(self.this,
flags
)
try:
return_obj = IWbemObjectSink(return_obj)
except WindowsError:
return_obj = None
return return_obj
def GetObjectWithResult(self, object_path, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppObject'),
(_Out_, 'ppCallResult'),
)
_GetObject = prototype(IWbemServices_GetObject_Idx,
'GetObject',
paramflags)
_GetObject.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
try:
return_obj, return_obj2 = _GetObject(self.this,
object_path_bstr,
flags,
ctx.this if ctx else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
try:
return_obj2 = IWbemCallResult(return_obj2)
except WindowsError:
return_obj2 = None
return return_obj, return_obj2
def GetObject(self, object_path, flags, ctx):
return_obj, return_obj2 = self.GetObjectWithResult(object_path, flags, ctx)
if return_obj2:
return_obj2.Release()
return return_obj
def GetObjectAsync(self, object_path, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_GetObjectAsync = prototype(IWbemServices_GetObjectAsync_Idx,
'GetObjectAsync',
paramflags)
_GetObjectAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
try:
_GetObjectAsync(self.this,
object_path_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
def PutClassWithResult(self, object_param, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemClassObject),
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'pObject'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppCallResult'),
)
_PutClass = prototype(IWbemServices_PutClass_Idx,
'PutClass',
paramflags)
_PutClass.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _PutClass(self.this,
object_param.this if object_param else None,
flags,
ctx.this if ctx else None
)
try:
return_obj = IWbemCallResult(return_obj)
except WindowsError:
return_obj = None
return return_obj
def PutClass(self, object_param, flags, ctx):
return_obj = self.PutClassWithResult(object_param, flags, ctx)
if return_obj:
return_obj.Release()
def PutClassAsync(self, object_param, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemClassObject),
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'pObject'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_PutClassAsync = prototype(IWbemServices_PutClassAsync_Idx,
'PutClassAsync',
paramflags)
_PutClassAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
_PutClassAsync(self.this,
object_param.this if object_param else None,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
def DeleteClassWithResult(self, class_param, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strClass'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppCallResult'),
)
_DeleteClass = prototype(IWbemServices_DeleteClass_Idx,
'DeleteClass',
paramflags)
_DeleteClass.errcheck = winapi.RAISE_NON_ZERO_ERR
class_param_bstr = winapi.SysAllocString(class_param) if class_param is not None else None
try:
return_obj = _DeleteClass(self.this,
class_param_bstr,
flags,
ctx.this if ctx else None
)
finally:
if class_param_bstr is not None:
winapi.SysFreeString(class_param_bstr)
try:
return_obj = IWbemCallResult(return_obj)
except WindowsError:
return_obj = None
return return_obj
def DeleteClass(self, class_param, flags, ctx):
return_obj = self.DeleteClassWithResult(class_param, flags, ctx)
if return_obj:
return_obj.Release()
def DeleteClassAsync(self, class_param, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strClass'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_DeleteClassAsync = prototype(IWbemServices_DeleteClassAsync_Idx,
'DeleteClassAsync',
paramflags)
_DeleteClassAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
class_param_bstr = winapi.SysAllocString(class_param) if class_param is not None else None
try:
_DeleteClassAsync(self.this,
class_param_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if class_param_bstr is not None:
winapi.SysFreeString(class_param_bstr)
def CreateClassEnum(self, superclass, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strSuperclass'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppEnum'),
)
_CreateClassEnum = prototype(IWbemServices_CreateClassEnum_Idx,
'CreateClassEnum',
paramflags)
_CreateClassEnum.errcheck = winapi.RAISE_NON_ZERO_ERR
superclass_bstr = winapi.SysAllocString(superclass) if superclass is not None else None
try:
return_obj = _CreateClassEnum(self.this,
superclass_bstr,
flags,
ctx.this if ctx else None
)
finally:
if superclass_bstr is not None:
winapi.SysFreeString(superclass_bstr)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def CreateClassEnumAsync(self, superclass, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strSuperclass'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_CreateClassEnumAsync = prototype(IWbemServices_CreateClassEnumAsync_Idx,
'CreateClassEnumAsync',
paramflags)
_CreateClassEnumAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
superclass_bstr = winapi.SysAllocString(superclass) if superclass is not None else None
try:
_CreateClassEnumAsync(self.this,
superclass_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if superclass_bstr is not None:
winapi.SysFreeString(superclass_bstr)
def PutInstanceWithResult(self, inst, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemClassObject),
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'pInst'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppCallResult'),
)
_PutInstance = prototype(IWbemServices_PutInstance_Idx,
'PutInstance',
paramflags)
_PutInstance.errcheck = winapi.RAISE_NON_ZERO_ERR
return_obj = _PutInstance(self.this,
inst.this if inst else None,
flags,
ctx.this if ctx else None
)
try:
return_obj = IWbemCallResult(return_obj)
except WindowsError:
return_obj = None
return return_obj
def PutInstance(self, inst, flags, ctx):
return_obj = self.PutInstanceWithResult(inst, flags, ctx)
if return_obj:
return_obj.Release()
def PutInstanceAsync(self, inst, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
ctypes.POINTER(IWbemClassObject),
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'pInst'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_PutInstanceAsync = prototype(IWbemServices_PutInstanceAsync_Idx,
'PutInstanceAsync',
paramflags)
_PutInstanceAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
_PutInstanceAsync(self.this,
inst.this if inst else None,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
def DeleteInstanceWithResult(self, object_path, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppCallResult'),
)
_DeleteInstance = prototype(IWbemServices_DeleteInstance_Idx,
'DeleteInstance',
paramflags)
_DeleteInstance.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
try:
return_obj = _DeleteInstance(self.this,
object_path_bstr,
flags,
ctx.this if ctx else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
try:
return_obj = IWbemCallResult(return_obj)
except WindowsError:
return_obj = None
return return_obj
def DeleteInstance(self, object_path, flags, ctx):
return_obj = self.DeleteInstanceWithResult(object_path, flags, ctx)
if return_obj:
return_obj.Release()
def DeleteInstanceAsync(self, object_path, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_DeleteInstanceAsync = prototype(IWbemServices_DeleteInstanceAsync_Idx,
'DeleteInstanceAsync',
paramflags)
_DeleteInstanceAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
try:
_DeleteInstanceAsync(self.this,
object_path_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
def CreateInstanceEnum(self, filter_param, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strFilter'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppEnum'),
)
_CreateInstanceEnum = prototype(IWbemServices_CreateInstanceEnum_Idx,
'CreateInstanceEnum',
paramflags)
_CreateInstanceEnum.errcheck = winapi.RAISE_NON_ZERO_ERR
filter_param_bstr = winapi.SysAllocString(filter_param) if filter_param is not None else None
try:
return_obj = _CreateInstanceEnum(self.this,
filter_param_bstr,
flags,
ctx.this if ctx else None
)
finally:
if filter_param_bstr is not None:
winapi.SysFreeString(filter_param_bstr)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def CreateInstanceEnumAsync(self, filter_param, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strFilter'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_CreateInstanceEnumAsync = prototype(IWbemServices_CreateInstanceEnumAsync_Idx,
'CreateInstanceEnumAsync',
paramflags)
_CreateInstanceEnumAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
filter_param_bstr = winapi.SysAllocString(filter_param) if filter_param is not None else None
try:
_CreateInstanceEnumAsync(self.this,
filter_param_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if filter_param_bstr is not None:
winapi.SysFreeString(filter_param_bstr)
def ExecQuery(self, query_language, query, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strQueryLanguage'),
(_In_, 'strQuery'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppEnum'),
)
_ExecQuery = prototype(IWbemServices_ExecQuery_Idx,
'ExecQuery',
paramflags)
_ExecQuery.errcheck = winapi.RAISE_NON_ZERO_ERR
query_language_bstr = winapi.SysAllocString(query_language) if query_language is not None else None
query_bstr = winapi.SysAllocString(query) if query is not None else None
try:
return_obj = _ExecQuery(self.this,
query_language_bstr,
query_bstr,
flags,
ctx.this if ctx else None
)
finally:
if query_language_bstr is not None:
winapi.SysFreeString(query_language_bstr)
if query_bstr is not None:
winapi.SysFreeString(query_bstr)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def ExecQueryAsync(self, query_language, query, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strQueryLanguage'),
(_In_, 'strQuery'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_ExecQueryAsync = prototype(IWbemServices_ExecQueryAsync_Idx,
'ExecQueryAsync',
paramflags)
_ExecQueryAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
query_language_bstr = winapi.SysAllocString(query_language) if query_language is not None else None
query_bstr = winapi.SysAllocString(query) if query is not None else None
try:
_ExecQueryAsync(self.this,
query_language_bstr,
query_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if query_language_bstr is not None:
winapi.SysFreeString(query_language_bstr)
if query_bstr is not None:
winapi.SysFreeString(query_bstr)
def ExecNotificationQuery(self, query_language, query, flags, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strQueryLanguage'),
(_In_, 'strQuery'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_Out_, 'ppEnum'),
)
_ExecNotificationQuery = prototype(IWbemServices_ExecNotificationQuery_Idx,
'ExecNotificationQuery',
paramflags)
_ExecNotificationQuery.errcheck = winapi.RAISE_NON_ZERO_ERR
query_language_bstr = winapi.SysAllocString(query_language) if query_language is not None else None
query_bstr = winapi.SysAllocString(query) if query is not None else None
try:
return_obj = _ExecNotificationQuery(self.this,
query_language_bstr,
query_bstr,
flags,
ctx.this if ctx else None
)
finally:
if query_language_bstr is not None:
winapi.SysFreeString(query_language_bstr)
if query_bstr is not None:
winapi.SysFreeString(query_bstr)
try:
return_obj = IEnumWbemClassObject(return_obj)
except WindowsError:
return_obj = None
return return_obj
def ExecNotificationQueryAsync(self, query_language, query, flags, ctx, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strQueryLanguage'),
(_In_, 'strQuery'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pResponseHandler'),
)
_ExecNotificationQueryAsync = prototype(IWbemServices_ExecNotificationQueryAsync_Idx,
'ExecNotificationQueryAsync',
paramflags)
_ExecNotificationQueryAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
query_language_bstr = winapi.SysAllocString(query_language) if query_language is not None else None
query_bstr = winapi.SysAllocString(query) if query is not None else None
try:
_ExecNotificationQueryAsync(self.this,
query_language_bstr,
query_bstr,
flags,
ctx.this if ctx else None,
response_handler.this if response_handler else None
)
finally:
if query_language_bstr is not None:
winapi.SysFreeString(query_language_bstr)
if query_bstr is not None:
winapi.SysFreeString(query_bstr)
def ExecMethodWithResult(self, object_path, method_name, flags, ctx, in_params):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemClassObject),
ctypes.POINTER(wintypes.LPVOID),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'strMethodName'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pInParams'),
(_Out_, 'ppOutParams'),
(_Out_, 'ppCallResult'),
)
_ExecMethod = prototype(IWbemServices_ExecMethod_Idx,
'ExecMethod',
paramflags)
_ExecMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
method_name_bstr = winapi.SysAllocString(method_name) if method_name is not None else None
try:
return_obj, return_obj2 = _ExecMethod(self.this,
object_path_bstr,
method_name_bstr,
flags,
ctx.this if ctx else None,
in_params.this if in_params else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
if method_name_bstr is not None:
winapi.SysFreeString(method_name_bstr)
try:
return_obj = IWbemClassObject(return_obj)
except WindowsError:
return_obj = None
try:
return_obj2 = IWbemCallResult(return_obj2)
except WindowsError:
return_obj2 = None
return return_obj, return_obj2
def ExecMethod(self, object_path, method_name, flags, ctx, in_params):
return_obj, return_obj2 = self.ExecMethodWithResult(object_path, method_name, flags, ctx, in_params)
if return_obj2:
return_obj2.Release()
return return_obj
def ExecMethodAsync(self, object_path, method_name, flags, ctx, in_params, response_handler):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
ctypes.c_long,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(IWbemClassObject),
ctypes.POINTER(IWbemObjectSink))
paramflags = ((_In_, 'strObjectPath'),
(_In_, 'strMethodName'),
(_In_, 'lFlags'),
(_In_, 'pCtx'),
(_In_, 'pInParams'),
(_In_, 'pResponseHandler'),
)
_ExecMethodAsync = prototype(IWbemServices_ExecMethodAsync_Idx,
'ExecMethodAsync',
paramflags)
_ExecMethodAsync.errcheck = winapi.RAISE_NON_ZERO_ERR
object_path_bstr = winapi.SysAllocString(object_path) if object_path is not None else None
method_name_bstr = winapi.SysAllocString(method_name) if method_name is not None else None
try:
_ExecMethodAsync(self.this,
object_path_bstr,
method_name_bstr,
flags,
ctx.this if ctx else None,
in_params.this if in_params else None,
response_handler.this if response_handler else None
)
finally:
if object_path_bstr is not None:
winapi.SysFreeString(object_path_bstr)
if method_name_bstr is not None:
winapi.SysFreeString(method_name_bstr)
IWbemLocator_ConnectServer_Idx = 3
class IWbemLocator(com.IUnknown):
def ConnectServer(self, network_resource, user, password, locale, security_flags, authority, ctx):
prototype = ctypes.WINFUNCTYPE(HRESULT,
BSTR,
BSTR,
BSTR,
BSTR,
ctypes.c_long,
BSTR,
ctypes.POINTER(IWbemContext),
ctypes.POINTER(wintypes.LPVOID))
paramflags = ((_In_, 'strNetworkResource'),
(_In_, 'strUser'),
(_In_, 'strPassword'),
(_In_, 'strLocale'),
(_In_, 'lSecurityFlags'),
(_In_, 'strAuthority'),
(_In_, 'pCtx'),
(_Out_, 'ppNamespace'),
)
_ConnectServer = prototype(IWbemLocator_ConnectServer_Idx,
'ConnectServer',
paramflags)
_ConnectServer.errcheck = winapi.RAISE_NON_ZERO_ERR
network_resource_bstr = winapi.SysAllocString(network_resource) if network_resource is not None else None
user_bstr = winapi.SysAllocString(user) if user is not None else None
password_bstr = winapi.SysAllocString(password) if password is not None else None
locale_bstr = winapi.SysAllocString(locale) if locale is not None else None
authority_bstr = winapi.SysAllocString(authority) if authority is not None else None
try:
return_obj = _ConnectServer(self.this,
network_resource_bstr,
user_bstr,
password_bstr,
locale_bstr,
security_flags,
authority_bstr,
ctx.this if ctx else None
)
finally:
if network_resource_bstr is not None:
winapi.SysFreeString(network_resource_bstr)
if user_bstr is not None:
winapi.SysFreeString(user_bstr)
if password_bstr is not None:
winapi.SysFreeString(password_bstr)
if locale_bstr is not None:
winapi.SysFreeString(locale_bstr)
if authority_bstr is not None:
winapi.SysFreeString(authority_bstr)
try:
return_obj = IWbemServices(return_obj)
except WindowsError:
return_obj = None
return return_obj
class WMI(com.COM):
'''
Wrapper class for WMI interactions. WMI initialization / uninitialization are done via ctxmgr.
N.B. If using this class, do not call init() and fini() directly. Only use through via ctxmgr
'''
def __init__(self,
net_resource,
user=None,
password=<PASSWORD>,
locale=None,
sec_flags=0,
auth=None,
ctx=None,
cls_ctx=com.CLSCTX_INPROC_SERVER,
authn_svc=winapi.RPC_C_AUTHN_WINNT,
authz_svc=winapi.RPC_C_AUTHZ_NONE,
spn=None,
auth_info=None,
coinit=com.COINIT_MULTITHREADED,
authn_level=winapi.RPC_C_AUTHN_LEVEL_DEFAULT,
imp_level=winapi.RPC_C_IMP_LEVEL_IMPERSONATE,
auth_list=None,
capabilities=winapi.EOAC_NONE):
self._net_resource = net_resource
self._user = user
self._password = password
self._locale = locale
self._sec_flags = sec_flags
self._auth = auth
self._ctx = ctx
self._cls_ctx = cls_ctx
self._authn_svc = authn_svc
self._authz_svc = authz_svc
self._spn = spn
self._auth_info = auth_info
self._authn_level = authn_level
self._imp_level = imp_level
self._auth_list = auth_list
self._capabilities = capabilities
self.service = None
super(WMI, self).__init__(coinit)
def __enter__(self):
self.init()
return self.service
def __exit__(self, exc_type, exc_val, exc_tb):
self.fini()
def init(self):
super(WMI, self).init()
self.initialize_security(None,
-1,
None,
self._authn_level,
self._imp_level,
self._auth_list,
self._capabilities)
locator = self.create_instance(winapi.CLSID_WbemLocator,
None,
self._cls_ctx,
winapi.IID_IWbemLocator,
IWbemLocator)
try:
self.service = locator.ConnectServer(self._net_resource,
self._user,
self._password,
self._locale,
self._sec_flags,
self._auth,
self._ctx)
finally:
locator.Release()
self.set_proxy_blanket(self.service.this,
self._authn_svc,
self._authz_svc,
self._spn,
self._authn_level,
self._imp_level,
self._auth_info,
self._capabilities)
def fini(self):
while self.service.Release():
pass
super(WMI, self).fini() | 0.331552 | 0.100437 |
import numpy as np
import torch
from tqdm import tqdm
import os
from warnings import warn
from nsgt import NSGT_sliced, LogScale, LinScale, MelScale, OctScale, SndReader, BarkScale, VQLogScale
from nsgt_orig import NSGT_sliced as NSGT_sliced_old
import time
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("input", type=str, help="Input file")
parser.add_argument("--output", type=str, help="Output data file (.npz, .hd5, .pkl)")
parser.add_argument("--sr", type=int, default=44100, help="Sample rate used for the NSGT (default=%(default)s)")
parser.add_argument("--fmin", type=float, default=50, help="Minimum frequency in Hz (default=%(default)s)")
parser.add_argument("--fmax", type=float, default=22050, help="Maximum frequency in Hz (default=%(default)s)")
parser.add_argument("--scale", choices=('oct','cqlog','vqlog','mel','bark'), default='cqlog', help="Frequency scale oct, log, lin, or mel (default='%(default)s')")
parser.add_argument("--bins", type=int, default=50, help="Number of frequency bins (total or per octave, default=%(default)s)")
parser.add_argument("--real", action='store_true', help="Assume real signal")
parser.add_argument("--old", action='store_true', help="Use old transform")
parser.add_argument("--matrixform", action='store_true', help="Use regular time division over frequency bins (matrix form)")
parser.add_argument("--torch-device", type=str, help="Which pytorch device to use", default="cpu")
parser.add_argument("--reducedform", type=int, default=0, help="If real, omit bins for f=0 and f=fs/2 (--reducedform=1), or also the transition bands (--reducedform=2) (default=%(default)s)")
parser.add_argument("--multithreading", action='store_true', help="Use multithreading")
parser.add_argument("--bench-iter", type=int, default=1000, help="Benchmark iterations")
args = parser.parse_args()
if not os.path.exists(args.input):
parser.error("Input file '%s' not found"%args.input)
fs = args.sr
# build transform
scales = {'cqlog':LogScale, 'lin':LinScale, 'mel':MelScale, 'oct':OctScale, 'bark':BarkScale, 'vqlog':VQLogScale}
try:
scale = scales[args.scale]
except KeyError:
parser.error('Scale unknown (--scale option)')
scl = scale(args.fmin, args.fmax, args.bins, beyond=int(args.reducedform == 2))
sllen, trlen = scl.suggested_sllen_trlen(fs)
# Read audio data
sf = SndReader(args.input, sr=fs, chns=2)
# store generator into a list
signal_orig = list(sf())
if args.old:
slicq = NSGT_sliced_old(scl, sllen, trlen, fs,
real=True,
matrixform=args.matrixform,
multithreading=args.multithreading,
multichannel=True
)
# read slices from audio file and mix down signal, if necessary at all
signal = ((np.mean(s, axis=0),) for s in signal_orig)
else:
slicq = NSGT_sliced(scl, sllen, trlen, fs,
real=True,
matrixform=args.matrixform,
multichannel=True,
device=args.torch_device
)
signal = [torch.tensor(sig, device=args.torch_device) for sig in signal_orig]
pad = signal[0].shape[-1]-signal[-1].shape[-1]
signal[-1] = torch.nn.functional.pad(signal[-1], (0, pad), mode='constant', value=0)
signal = torch.cat(signal, dim=-1)
tot = 0.
for _ in tqdm(range(args.bench_iter)):
start = time.time()
if args.old:
# generator for forward transformation
c = slicq.forward(signal)
c_list = list(c)
sig_recon = slicq.backward(c_list)
sig = list(sig_recon)
else:
# torch
c = slicq.forward((signal,))
sig_recon = slicq.backward(c, signal.shape[-1])
tot += time.time() - start
# recreate generator
if args.old:
signal = ((np.mean(s, axis=0),) for s in signal_orig)
tot /= float(args.bench_iter)
print(f'total time: {tot:.2f}s') | examples/benchmark.py | import numpy as np
import torch
from tqdm import tqdm
import os
from warnings import warn
from nsgt import NSGT_sliced, LogScale, LinScale, MelScale, OctScale, SndReader, BarkScale, VQLogScale
from nsgt_orig import NSGT_sliced as NSGT_sliced_old
import time
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("input", type=str, help="Input file")
parser.add_argument("--output", type=str, help="Output data file (.npz, .hd5, .pkl)")
parser.add_argument("--sr", type=int, default=44100, help="Sample rate used for the NSGT (default=%(default)s)")
parser.add_argument("--fmin", type=float, default=50, help="Minimum frequency in Hz (default=%(default)s)")
parser.add_argument("--fmax", type=float, default=22050, help="Maximum frequency in Hz (default=%(default)s)")
parser.add_argument("--scale", choices=('oct','cqlog','vqlog','mel','bark'), default='cqlog', help="Frequency scale oct, log, lin, or mel (default='%(default)s')")
parser.add_argument("--bins", type=int, default=50, help="Number of frequency bins (total or per octave, default=%(default)s)")
parser.add_argument("--real", action='store_true', help="Assume real signal")
parser.add_argument("--old", action='store_true', help="Use old transform")
parser.add_argument("--matrixform", action='store_true', help="Use regular time division over frequency bins (matrix form)")
parser.add_argument("--torch-device", type=str, help="Which pytorch device to use", default="cpu")
parser.add_argument("--reducedform", type=int, default=0, help="If real, omit bins for f=0 and f=fs/2 (--reducedform=1), or also the transition bands (--reducedform=2) (default=%(default)s)")
parser.add_argument("--multithreading", action='store_true', help="Use multithreading")
parser.add_argument("--bench-iter", type=int, default=1000, help="Benchmark iterations")
args = parser.parse_args()
if not os.path.exists(args.input):
parser.error("Input file '%s' not found"%args.input)
fs = args.sr
# build transform
scales = {'cqlog':LogScale, 'lin':LinScale, 'mel':MelScale, 'oct':OctScale, 'bark':BarkScale, 'vqlog':VQLogScale}
try:
scale = scales[args.scale]
except KeyError:
parser.error('Scale unknown (--scale option)')
scl = scale(args.fmin, args.fmax, args.bins, beyond=int(args.reducedform == 2))
sllen, trlen = scl.suggested_sllen_trlen(fs)
# Read audio data
sf = SndReader(args.input, sr=fs, chns=2)
# store generator into a list
signal_orig = list(sf())
if args.old:
slicq = NSGT_sliced_old(scl, sllen, trlen, fs,
real=True,
matrixform=args.matrixform,
multithreading=args.multithreading,
multichannel=True
)
# read slices from audio file and mix down signal, if necessary at all
signal = ((np.mean(s, axis=0),) for s in signal_orig)
else:
slicq = NSGT_sliced(scl, sllen, trlen, fs,
real=True,
matrixform=args.matrixform,
multichannel=True,
device=args.torch_device
)
signal = [torch.tensor(sig, device=args.torch_device) for sig in signal_orig]
pad = signal[0].shape[-1]-signal[-1].shape[-1]
signal[-1] = torch.nn.functional.pad(signal[-1], (0, pad), mode='constant', value=0)
signal = torch.cat(signal, dim=-1)
tot = 0.
for _ in tqdm(range(args.bench_iter)):
start = time.time()
if args.old:
# generator for forward transformation
c = slicq.forward(signal)
c_list = list(c)
sig_recon = slicq.backward(c_list)
sig = list(sig_recon)
else:
# torch
c = slicq.forward((signal,))
sig_recon = slicq.backward(c, signal.shape[-1])
tot += time.time() - start
# recreate generator
if args.old:
signal = ((np.mean(s, axis=0),) for s in signal_orig)
tot /= float(args.bench_iter)
print(f'total time: {tot:.2f}s') | 0.466846 | 0.121869 |
from utils import update_model, save_simple_metrics_report, get_model_performance_test_set
from sklearn.model_selection import train_test_split, cross_validate, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingRegressor
import logging
import sys
import numpy as np
import pandas as pd
logging.basicConfig(
format='%(asctime)s %(levelname)s:%(name)s: %(message)s',
level=logging.INFO,
datefmt='%H:%M:%S',
stream=sys.stderr
)
logger = logging.getLogger(__name__)
logger.info('Loading Data...')
data = pd.read_csv('dataset/full_data.csv')
logger.info('Loading model...')
model = Pipeline([
('imputer', SimpleImputer(strategy='mean',missing_values=np.nan)),
('core_model', GradientBoostingRegressor())
])
logger.info('Seraparating dataset into train and test')
X = data.drop(['worldwide_gross'], axis= 1)
y = data['worldwide_gross']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.35, random_state=42)
logger.info('Setting Hyperparameter to tune')
param_tuning = {'core_model__n_estimators':range(20,301,20)}
grid_search = GridSearchCV(model, param_grid= param_tuning, scoring='r2', cv=5)
logger.info('Starting grid search...')
grid_search.fit(X_train, y_train)
logger.info('Cross validating with best model...')
final_result = cross_validate(grid_search.best_estimator_, X_train, y_train, return_train_score=True, cv=5)
train_score = np.mean(final_result['train_score'])
test_score = np.mean(final_result['test_score'])
assert train_score > 0.7
assert test_score > 0.65
logger.info(f'Train Score: {train_score}')
logger.info(f'Test Score: {test_score}')
logger.info('Updating model...')
update_model(grid_search.best_estimator_)
logger.info('Generating model report...')
validation_score = grid_search.best_estimator_.score(X_test, y_test)
save_simple_metrics_report(train_score, test_score, validation_score, grid_search.best_estimator_)
y_test_pred = grid_search.best_estimator_.predict(X_test)
get_model_performance_test_set(y_test, y_test_pred)
logger.info('Training Finished') | src/train.py | from utils import update_model, save_simple_metrics_report, get_model_performance_test_set
from sklearn.model_selection import train_test_split, cross_validate, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingRegressor
import logging
import sys
import numpy as np
import pandas as pd
logging.basicConfig(
format='%(asctime)s %(levelname)s:%(name)s: %(message)s',
level=logging.INFO,
datefmt='%H:%M:%S',
stream=sys.stderr
)
logger = logging.getLogger(__name__)
logger.info('Loading Data...')
data = pd.read_csv('dataset/full_data.csv')
logger.info('Loading model...')
model = Pipeline([
('imputer', SimpleImputer(strategy='mean',missing_values=np.nan)),
('core_model', GradientBoostingRegressor())
])
logger.info('Seraparating dataset into train and test')
X = data.drop(['worldwide_gross'], axis= 1)
y = data['worldwide_gross']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.35, random_state=42)
logger.info('Setting Hyperparameter to tune')
param_tuning = {'core_model__n_estimators':range(20,301,20)}
grid_search = GridSearchCV(model, param_grid= param_tuning, scoring='r2', cv=5)
logger.info('Starting grid search...')
grid_search.fit(X_train, y_train)
logger.info('Cross validating with best model...')
final_result = cross_validate(grid_search.best_estimator_, X_train, y_train, return_train_score=True, cv=5)
train_score = np.mean(final_result['train_score'])
test_score = np.mean(final_result['test_score'])
assert train_score > 0.7
assert test_score > 0.65
logger.info(f'Train Score: {train_score}')
logger.info(f'Test Score: {test_score}')
logger.info('Updating model...')
update_model(grid_search.best_estimator_)
logger.info('Generating model report...')
validation_score = grid_search.best_estimator_.score(X_test, y_test)
save_simple_metrics_report(train_score, test_score, validation_score, grid_search.best_estimator_)
y_test_pred = grid_search.best_estimator_.predict(X_test)
get_model_performance_test_set(y_test, y_test_pred)
logger.info('Training Finished') | 0.494873 | 0.336195 |
import pytest
import os
import numpy as np
from numpy.linalg import eigvalsh
from openfermion import QubitOperator, InteractionOperator, get_sparse_operator, get_ground_state
from zquantum.core.openfermion import save_qubit_operator_set, load_qubit_operator_set, save_interaction_operator, load_interaction_operator, load_qubit_operator
from operators import concatenate_qubit_operator_lists, get_one_qubit_hydrogen_hamiltonian
from math import isclose
h2_hamiltonian_grouped = [
QubitOperator("-0.04475014401986127 [X0 X1 Y2 Y3]"),
QubitOperator("0.04475014401986127 [X0 Y1 Y2 X3]"),
QubitOperator("0.04475014401986127 [Y0 X1 X2 Y3]"),
QubitOperator("-0.04475014401986127 [Y0 Y1 X2 X3]"),
QubitOperator(
"""0.17771287459806312 [Z0] +
0.1705973832722407 [Z0 Z1] +
0.12293305054268083 [Z0 Z2] +
0.1676831945625421 [Z0 Z3] +
0.17771287459806312 [Z1] +
0.1676831945625421 [Z1 Z2] +
0.12293305054268083 [Z1 Z3] +
-0.24274280496459985 [Z2] +
0.17627640802761105 [Z2 Z3] +
-0.24274280496459985 [Z3]"""
),
]
# Interaction Hamiltonian of H2 (0.74 A, STO-3G) generated using openfermion-psi4
constant = 0.7151043387432434
one_body_tensor = np.array([[-1.253309786435, 0. , 0. ,
0. ],
[ 0. , -1.253309786435, 0. ,
0. ],
[ 0. , 0. , -0.475068848992,
0. ],
[ 0. , 0. , 0. ,
-0.475068848992]])
two_body_tensor = np.array([[[[0.337377963374, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.090605231017,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0.337377963374, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.090605231017,
0. ]],
[[0. , 0. , 0.090605231017,
0. ],
[0. , 0. , 0. ,
0. ],
[0.331855700645, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.090605231017,
0. ],
[0. , 0. , 0. ,
0. ],
[0.331855700645, 0. , 0. ,
0. ]]],
[[[0. , 0.337377963374, 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.090605231017],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0.337377963374, 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.090605231017]],
[[0. , 0. , 0. ,
0.090605231017],
[0. , 0. , 0. ,
0. ],
[0. , 0.331855700645, 0. ,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.090605231017],
[0. , 0. , 0. ,
0. ],
[0. , 0.331855700645, 0. ,
0. ]]],
[[[0. , 0. , 0.331855700645,
0. ],
[0. , 0. , 0. ,
0. ],
[0.090605231017, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.331855700645,
0. ],
[0. , 0. , 0. ,
0. ],
[0.090605231017, 0. , 0. ,
0. ]],
[[0.090605231017, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.348825752213,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0.090605231017, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.348825752213,
0. ]]],
[[[0. , 0. , 0. ,
0.331855700645],
[0. , 0. , 0. ,
0. ],
[0. , 0.090605231017, 0. ,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.331855700645],
[0. , 0. , 0. ,
0. ],
[0. , 0.090605231017, 0. ,
0. ]],
[[0. , 0.090605231017, 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.348825752213],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0.090605231017, 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.348825752213]]]])
def test_concatenate_qubit_operator_lists():
group_A = h2_hamiltonian_grouped[:3]
group_B = h2_hamiltonian_grouped[3:]
save_qubit_operator_set(group_A, "groupA.json")
save_qubit_operator_set(group_B, "groupB.json")
concatenate_qubit_operator_lists("groupA.json", "groupB.json")
group_read = load_qubit_operator_set("concatenated-qubit-operators.json")
os.remove("groupA.json")
os.remove("groupB.json")
os.remove("concatenated-qubit-operators.json")
assert group_read == h2_hamiltonian_grouped
def test_get_one_qubit_hydrogen_hamiltonian():
# Define interaction hamiltonian
h2_hamiltonian_int = InteractionOperator(constant=constant, one_body_tensor=one_body_tensor, two_body_tensor=two_body_tensor)
save_interaction_operator(h2_hamiltonian_int, 'interaction-operator.json')
get_one_qubit_hydrogen_hamiltonian('interaction-operator.json')
h2_1qubit = load_qubit_operator('qubit-operator.json')
h2_1qubit_sparse = get_sparse_operator(h2_1qubit, n_qubits=1)
h2_1qubit_dense = h2_1qubit_sparse.toarray()
#print(h2_1qubit_dense)
e_1q = eigvalsh(h2_1qubit_dense)
gs_4q = get_ground_state(get_sparse_operator(h2_hamiltonian_int))
os.remove('interaction-operator.json')
os.remove('qubit-operator.json')
assert isclose(e_1q[0], gs_4q[0]) | steps/operators_test.py | import pytest
import os
import numpy as np
from numpy.linalg import eigvalsh
from openfermion import QubitOperator, InteractionOperator, get_sparse_operator, get_ground_state
from zquantum.core.openfermion import save_qubit_operator_set, load_qubit_operator_set, save_interaction_operator, load_interaction_operator, load_qubit_operator
from operators import concatenate_qubit_operator_lists, get_one_qubit_hydrogen_hamiltonian
from math import isclose
h2_hamiltonian_grouped = [
QubitOperator("-0.04475014401986127 [X0 X1 Y2 Y3]"),
QubitOperator("0.04475014401986127 [X0 Y1 Y2 X3]"),
QubitOperator("0.04475014401986127 [Y0 X1 X2 Y3]"),
QubitOperator("-0.04475014401986127 [Y0 Y1 X2 X3]"),
QubitOperator(
"""0.17771287459806312 [Z0] +
0.1705973832722407 [Z0 Z1] +
0.12293305054268083 [Z0 Z2] +
0.1676831945625421 [Z0 Z3] +
0.17771287459806312 [Z1] +
0.1676831945625421 [Z1 Z2] +
0.12293305054268083 [Z1 Z3] +
-0.24274280496459985 [Z2] +
0.17627640802761105 [Z2 Z3] +
-0.24274280496459985 [Z3]"""
),
]
# Interaction Hamiltonian of H2 (0.74 A, STO-3G) generated using openfermion-psi4
constant = 0.7151043387432434
one_body_tensor = np.array([[-1.253309786435, 0. , 0. ,
0. ],
[ 0. , -1.253309786435, 0. ,
0. ],
[ 0. , 0. , -0.475068848992,
0. ],
[ 0. , 0. , 0. ,
-0.475068848992]])
two_body_tensor = np.array([[[[0.337377963374, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.090605231017,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0.337377963374, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.090605231017,
0. ]],
[[0. , 0. , 0.090605231017,
0. ],
[0. , 0. , 0. ,
0. ],
[0.331855700645, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.090605231017,
0. ],
[0. , 0. , 0. ,
0. ],
[0.331855700645, 0. , 0. ,
0. ]]],
[[[0. , 0.337377963374, 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.090605231017],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0.337377963374, 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.090605231017]],
[[0. , 0. , 0. ,
0.090605231017],
[0. , 0. , 0. ,
0. ],
[0. , 0.331855700645, 0. ,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.090605231017],
[0. , 0. , 0. ,
0. ],
[0. , 0.331855700645, 0. ,
0. ]]],
[[[0. , 0. , 0.331855700645,
0. ],
[0. , 0. , 0. ,
0. ],
[0.090605231017, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.331855700645,
0. ],
[0. , 0. , 0. ,
0. ],
[0.090605231017, 0. , 0. ,
0. ]],
[[0.090605231017, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.348825752213,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0.090605231017, 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0.348825752213,
0. ]]],
[[[0. , 0. , 0. ,
0.331855700645],
[0. , 0. , 0. ,
0. ],
[0. , 0.090605231017, 0. ,
0. ],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.331855700645],
[0. , 0. , 0. ,
0. ],
[0. , 0.090605231017, 0. ,
0. ]],
[[0. , 0.090605231017, 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.348825752213],
[0. , 0. , 0. ,
0. ]],
[[0. , 0. , 0. ,
0. ],
[0. , 0.090605231017, 0. ,
0. ],
[0. , 0. , 0. ,
0. ],
[0. , 0. , 0. ,
0.348825752213]]]])
def test_concatenate_qubit_operator_lists():
group_A = h2_hamiltonian_grouped[:3]
group_B = h2_hamiltonian_grouped[3:]
save_qubit_operator_set(group_A, "groupA.json")
save_qubit_operator_set(group_B, "groupB.json")
concatenate_qubit_operator_lists("groupA.json", "groupB.json")
group_read = load_qubit_operator_set("concatenated-qubit-operators.json")
os.remove("groupA.json")
os.remove("groupB.json")
os.remove("concatenated-qubit-operators.json")
assert group_read == h2_hamiltonian_grouped
def test_get_one_qubit_hydrogen_hamiltonian():
# Define interaction hamiltonian
h2_hamiltonian_int = InteractionOperator(constant=constant, one_body_tensor=one_body_tensor, two_body_tensor=two_body_tensor)
save_interaction_operator(h2_hamiltonian_int, 'interaction-operator.json')
get_one_qubit_hydrogen_hamiltonian('interaction-operator.json')
h2_1qubit = load_qubit_operator('qubit-operator.json')
h2_1qubit_sparse = get_sparse_operator(h2_1qubit, n_qubits=1)
h2_1qubit_dense = h2_1qubit_sparse.toarray()
#print(h2_1qubit_dense)
e_1q = eigvalsh(h2_1qubit_dense)
gs_4q = get_ground_state(get_sparse_operator(h2_hamiltonian_int))
os.remove('interaction-operator.json')
os.remove('qubit-operator.json')
assert isclose(e_1q[0], gs_4q[0]) | 0.259263 | 0.406214 |
import numpy as np
import scipy as sp
class Quad_Sampler(object):
"""
Class for drawing samples from an arbitrary one-dimensional probability distribution using numerical integration
and interpolation. In general this will be superior to more sophisticated sampling methods for 1D problems.
Assumes that priors are uniform.
Args:
ln_likelihood: Function which takes the independent variable x as its first argument and returns the log
of the likelihood function, p(d|x,I), up to a constant. May take other *args or **kwargs.
priors: List-type of the form [a,b], where a and b define the upper and lower bounds of the uniform
prior p(x|I).
optioinal:
vect: (bool) Set to true if the log-likelihood accepts a vectorized input.
"""
def __init__(self, ln_likelihood, priors, vect=False):
self._ln_likelihood = ln_likelihood
self._a, self._b = priors
self._vect = vect
# Default values
self.ln_Z = np.nan
self.mean = np.nan
self.std = np.nan
def fit(self, n_pts=200, args=(), **kwargs):
"""
Perform the fit.
Optional:
n_pts: (int) Number of evenly-spaced points over which to compute the probability.
args: (tuple) All additional arguments to be passed on the the likelihood function.
**kwargs: All other keywords are passed on the the likelihood function.
"""
# Evaluate the pdf
self.xs = np.linspace(self._a, self._b, num=n_pts)
if self._vect:
self.ln_pdf = self._ln_likelihood(self.xs, *args, **kwargs)
else:
self.ln_pdf = np.array([self._ln_likelihood(x, *args, **kwargs) for x in self.xs])
# Rescale with the maxima
ln_C = np.amax(self.ln_pdf)
pdf_scaled = np.exp(self.ln_pdf - ln_C)
# Compute the evidence and rescale
Z_scaled = np.trapz(pdf_scaled, x=self.xs)
self.ln_Z = np.log(Z_scaled) + ln_C
self.pdf = pdf_scaled / Z_scaled
self.cdf = sp.integrate.cumtrapz(self.pdf, x=self.xs, initial=0)
# Estimate summary statistics - assuming a normal distribution
samples = self.get_samples(1000)
self.mean = np.mean(samples)
self.std = np.std(samples)
def get_samples(self, n_samples):
"""
"""
u_samp = np.random.rand(n_samples)
return np.interp(u_samp, self.cdf, self.xs)
class Quad_Sampler_ND(object):
"""
Class for drawing samples from an arbitrary N-dimensional probability distribution using numerical integration
and interpolation. This can be useful for problems with a low number of dimensions (~3) for which the likelihood
function can be computed quickly (<< 1 second).
Assumes that priors are uniform. Currently does not support vectorized likelihoods.
Args:
ln_likelihood: Function which takes the independent variables (x1, x2, ..., xN) as its first argument and returns
the log of the likelihood function, p(d|x1,...,I), up to a constant. May take other *args or **kwargs.
priors: List of tuples, of the form [(a1,b1), (a2,b2), ..., (aN,bN)] where a and b define the upper and lower bounds
of the uniform prior p(x1,...|I).
optioinal:
vect: (bool) Set to true if the log-likelihood accepts a vectorized input.
"""
def __init__(self, ln_likelihood, ndim, priors):
self._ln_likelihood = ln_likelihood
self.ndim = ndim
self._a = np.zeros(self.ndim)
self._b = np.zeros(self.ndim)
for n in range(self.ndim):
self._a[n], self._b[n] = priors[n]
# Default values
self.ln_Z = np.nan
self.mean = np.nan
self.std = np.nan
def fit(self, n_pts=200, args=(), **kwargs):
"""
Perform the fit.
Optional:
n_pts: (int) Number of evenly-spaced points over which to compute the probability.
args: (tuple) All additional arguments to be passed on the the likelihood function.
**kwargs: All other keywords are passed on the the likelihood function.
This doesn't work yet.
"""
# Construct the evaluation grid
self.xs = np.zeros([self.ndim, n_pts])
for n in range(slef.ndim):
self.xs[n,:] = np.linspace(self._a[n], self._b[n], num=n_pts)
# Evaluate the pdf
self.ln_pdf = np.zeros([self.ndim, n_pts])
for n in range(slef.ndim):
self.ln_pdf[n] = np.array([self._ln_likelihood(x, *args, **kwargs) for x in self.xs[n]])
# Rescale with the maxima
ln_C = np.amax(self.ln_pdf)
pdf_scaled = np.exp(self.ln_pdf - ln_C)
# Compute the evidence and rescale
Z_scaled = np.trapz(pdf_scaled, x=self.xs)
self.ln_Z = np.log(Z_scaled) + ln_C
self.pdf = pdf_scaled / Z_scaled
self.cdf = sp.integrate.cumtrapz(self.pdf, x=self.xs, initial=0)
# Estimate summary statistics - assuming a normal distribution
samples = self.get_samples(1000)
self.mean = np.mean(samples)
self.std = np.std(samples)
def get_samples(self, n_samples):
"""
"""
u_samp = np.random.rand(n_samples)
return np.interp(u_samp, self.cdf, self.xs)
# ------------------------------------------------ MESXR Sampler ------------------------------------------------
import time
import emcee
import mst_ida.models.mesxr3 as m3
import mst_ida.data.mesxr as mesxr
import mst_ida.analysis.ida as ida
import mst_ida.analysis.emissivity as em
import mst_ida.models.base.response as rsp
from mst_ida.utilities.functions import identify_outliers
from mst_ida.models.base.geometry import flux_coords, sunflower_points
default_priors = {
'alpha':((10, 14), (0.1,18), (0.1,18))
}
class MESXR_Emiss_Sampler(object):
"""
"""
def __init__(self, shot, frame, flux=None, Ec_ref=3.0, priors=None, indices=np.arange(5,55), Ew=300.,
method='alpha', nwalkers=32, center=True, delta_a=0.06, delta_h=0.01, manual=None):
# Load the data
self.shot = shot
if manual is not None:
self.mesxr_data = manual['data']
self.mesxr_sigmas = manual['sigmas']
self.signed_ps = manual['impact_p']
self.thresholds = manual['thresholds']
else:
self.frame = frame
self.mesxr_data, self.mesxr_sigmas, self.signed_ps, self.thresholds = mesxr.get_8c_data(self.shot, self.frame, center=center)
# Model and geometry
if flux is None:
self.flux = flux_coords(delta_a=delta_a, delta_h=delta_h)
else:
self.flux = flux
self.method = method
self.p3det = m3.MESXR(shot=self.shot, center=center)
self.gij_set = {}
self.ss_set = {}
for Ec in self.thresholds:
self.gij_set[Ec], self.ss_set[Ec] = em.get_geometry_matrix(self.flux, self.p3det)
# Include specified data points
self.indices = np.arange(6,55)
z = {Ec:np.maximum(self.mesxr_data[Ec][self.indices]+1, 1) for Ec in self.thresholds}
self.ln_data_fact = {Ec:-np.sum(sp.special.loggamma(z[Ec])) for Ec in self.thresholds}
# Set up the priors
if priors is None:
self.priors = default_priors[self.method]
else:
self.priors = priors
# Sampler parameters
self.nwalkers = nwalkers
self.pos0 = self.get_pos0()
self.ndim = self.pos0.shape[1]
# Set up the samplers
moves = [(emcee.moves.DEMove(), 0.8), (emcee.moves.DESnookerMove(), 0.2),]
self.samplers = {}
for index, Ec in enumerate(self.thresholds):
self.samplers[Ec] = emcee.EnsembleSampler(self.nwalkers, self.ndim, self.ln_prob, moves=moves, kwargs={'Ec':Ec})
# Set up ratio curves
self.Ew = Ew
self.Ec_ref = Ec_ref
self.temps = np.linspace(10, 3000, num=6000)
self.ratios= {}
for Ec in self.thresholds:
if Ec != self.Ec_ref:
self.ratios[Ec] = np.array([self.model_ratio(Te,Ec*1000.) for Te in self.temps])
def fit(self, nsteps=10000, remove_outliers=True, resume=False, burn_step=3000, n_samples=5000, progress=True):
"""
"""
# MCMC sampling
if nsteps is not None:
for Ec in self.thresholds:
if not resume:
#print('Beginning sampling for Ec = ' + str(Ec) + ' keV')
time.sleep(1)
self.samplers[Ec].run_mcmc(self.pos0, nsteps, progress=progress)
else:
#print('Resuming sampling for Ec = ' + str(Ec) + ' keV')
time.sleep(1)
self.samplers[Ec].run_mcmc(None, nsteps, progress=progress)
self.samples = {Ec:self.samplers[Ec].get_chain(discard=burn_step, flat=True) for Ec in self.thresholds}
# Remove points from poorly-converged walkers
if remove_outliers:
for Ec in self.thresholds:
self.samples[Ec] = identify_outliers(self.samples[Ec])
# Save the average fit parameters
self.theta_avg = {Ec:np.average(self.samples[Ec], axis=0) for Ec in self.thresholds}
# Get the emissivity profile samples
self.n_samples = n_samples
self.emiss_samples = {Ec:self.get_emiss_samples(self.samples[Ec], Ec=Ec, n_samples=n_samples) for Ec in self.thresholds}
self.emiss_CIs = {Ec:ida.profile_confidence(self.emiss_samples[Ec]) for Ec in self.thresholds}
def get_Te_samples(self, slim=0.7, include=[4.0, 5.0]):
"""
"""
ss = self.ss_set[self.Ec_ref].ravel()
sn = np.argmin(np.abs(ss - slim))
s_vals = self.ss_set[self.Ec_ref].ravel()[:sn]
Te_avg_prof_samples = np.zeros([self.n_samples, sn])
for s_index in range(sn):
ratios = {Ec:self.emiss_samples[Ec][:,s_index]/self.emiss_samples[self.Ec_ref][:,s_index] for Ec in include}
Te_samples = {Ec:self.Te_from_R(ratios[Ec], Ec=Ec) for Ec in include}
Te_avg_prof_samples[:,s_index] = sum([Te_samples[Ec] for Ec in include]) / len(include)
Te_avg_CI = ida.profile_confidence(Te_avg_prof_samples)
return s_vals, Te_avg_prof_samples, Te_avg_CI
# ----------------------------------------------- Emissivity Model -----------------------------------------------
def emiss_model_alpha(self, ss, Xem, alpha, beta):
return (10.**Xem)*(1 - ss**alpha)**beta
def emiss_model(self, *args):
if self.method == 'alpha':
return self.emiss_model_alpha(*args)
else:
raise KeyError('Please select a valid fitting method.')
def get_model(self, theta, Ec=3.0):
gij = self.gij_set[Ec]
ss = self.ss_set[Ec]
emiss = self.emiss_model(ss, *theta)
bright = np.dot(gij, emiss).squeeze()
return self.p3det.etendue[Ec]*bright
# ----------------------------------------------- Bayesian Methods -----------------------------------------------
def ln_prob(self, theta, Ec=3.0):
lp = self.ln_prior(theta)
if np.isfinite(lp):
return lp + self.ln_likelihood(theta, Ec=Ec)
else:
return -np.inf
def ln_likelihood(self, theta, Ec=3.0):
data = self.mesxr_data[Ec][self.indices]
model = self.get_model(theta, Ec=Ec)[self.indices]
return -np.sum(model - data*np.log(model)) + self.ln_data_fact[Ec]
def ln_prior(self, theta):
if self.method == 'alpha':
return self.ln_prior_alpha(*theta)
else:
raise KeyError('Method not recognized.')
def ln_prior_alpha(self, Xem, alpha, beta):
X_min, X_max = self.priors[0]
al_min, al_max = self.priors[1]
bt_min, bt_max = self.priors[2]
if (X_min < Xem < X_max) and (al_min < alpha < al_max) and (bt_min < beta < bt_max):
return 0.0
else:
return - np.inf
def get_pos0(self):
if self.method == 'alpha':
X_min, X_max = self.priors[0]
al_min, al_max = self.priors[1]
bt_min, bt_max = self.priors[2]
pos0 = np.zeros([self.nwalkers, 3])
pos0[:,0] = (X_max - X_min)*np.random.random(size=self.nwalkers) + X_min
pos0[:,1] = (al_max - al_min)*np.random.random(size=self.nwalkers) + al_min
pos0[:,2] = (bt_max - bt_min)*np.random.random(size=self.nwalkers) + bt_min
return pos0
# ----------------------------------------------- Ratio Model -----------------------------------------------
def Te_from_R(self, rs, Ec=4.0):
if Ec > self.Ec_ref:
return np.interp(rs, self.ratios[Ec], self.temps)
else:
# Reverse to avoid interpolation error
return np.interp(rs, np.flip(self.ratios[Ec]), np.flip(self.temps))
def get_en_int(self, Te, Ec):
"""
Model the local emissivity, to a constant factor.
"""
en = np.linspace(1500, 20000, num=1000)
resp = rsp.Pilatus_Response(Ec, self.Ew)
return np.trapz(resp(en)*np.exp(-en/Te)/np.sqrt(Te)/en, x=en)
def model_ratio(self, Te, Ec):
"""
Get the ratio for a given Te and Ec relative to the reference
"""
en_int = self.get_en_int(Te, Ec)
ref = self.get_en_int(Te, self.Ec_ref*1000.)
return en_int / ref
# ----------------------------------------------- Analysis Methods -----------------------------------------------
def get_emiss_samples(self, samples, n_samples=5000, Ec=3.0):
"""
"""
ss = self.ss_set[Ec]
emiss_samples = np.zeros([n_samples, len(ss)])
for index,n in enumerate(np.random.randint(samples.shape[0]-1, size=n_samples)):
emiss_samples[index,:] = self.emiss_model(ss, *samples[n,:]).squeeze()
return emiss_samples
def get_params(self):
"""
Return LaTeX fromatted strings for each parameter.
"""
if self.method == 'alpha':
return [r'$X_{\varepsilon}$', r'$\alpha$', r'$\beta$']
else:
return []
# ----------------------------------------------- Diagnostic Plots -----------------------------------------------
import mst_ida.analysis.plots as idap
from matplotlib.lines import Line2D
from mst_ida.utilities.graphics import *
def burn_plot(sampler, Ec=3.0, burn_step=30000):
params = sampler.get_params()
return idap.burn_plot(sampler.samplers[Ec].chain, burn_step, sampler.nwalkers, indices=range(len(params)), labels=params, figsize=(8,6))
def distplot(sampler, Ec=3.0):
return distplot(sampler.samples[Ec], labels=sampler.get_params())
def emiss_xs_plot(sampler, Ec=3.0, shax=False):
"""
Plot the cross-section (XS) using the average parameter values.
"""
fig, ax = plt.subplots(1,1)
xs, ys = sunflower_points(5000)
s_xs = sampler.flux.rho(xs, ys)
emiss_xs_samples = np.zeros([sampler.n_samples, len(s_xs)])
for n in range(sampler.n_samples):
emiss_xs_samples[n,:] = sampler.emiss_model(s_xs, *sampler.samples[Ec][n,:])
emiss_xs = np.average(emiss_xs_samples, axis=0)
cax = plt.tricontourf(xs, ys, emiss_xs, 50, cmap='plasma')
plt.colorbar(cax, label=r'SXR emission (ph ms$^{-1}$ m$^{-3}$ sr$^{-1}$)')
plt.xlabel(r'$R - R_0$ (m)')
plt.ylabel(r'$Z$ (m)')
overplot_shell(plt.gca())
text(0.11, 0.96, r'$E_c = {0:.1f}$ keV'.format(Ec), plt.gca())
if shax:
levels = [0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
cax = plt.tricontour(sampler.flux.xs, sampler.flux.ys, sampler.flux.ss, levels, colors='black')
return fig, ax
def emiss_prof_plot(sampler):
fig, ax = plt.subplots(1,1)
labels = ['{0:.1f} keV'.format(Ec) for Ec in sampler.thresholds]
nlabels = len(labels)
custom_lines = [Line2D([0], [0], color='xkcd:bright blue', lw=4),
Line2D([0], [0], color='xkcd:red', lw=4),
Line2D([0], [0], color='xkcd:kelly green', lw=4),
Line2D([0], [0], color='xkcd:steel', lw=4),
Line2D([0], [0], color='xkcd:bright blue', lw=4),
Line2D([0], [0], color='xkcd:red', lw=4),
Line2D([0], [0], color='xkcd:kelly green', lw=4),
Line2D([0], [0], color='xkcd:steel', lw=4)]
for index,Ec in enumerate(sampler.thresholds):
ss = sampler.ss_set[Ec].ravel()
idap.profile_CIs(ax, sampler.emiss_CIs[Ec], ss, ylim=[0,1], ylabel=r'$\varepsilon(s)$', cid=(index%4)+1, legend=False)
ax.set_ylabel(r'SXR emission (ph ms$^{-1}$ m$^{-3}$ sr$^{-1}$)')
ax.set_xlabel('Flux $\psi$ (norm.)')
ax.legend(custom_lines[:nlabels], labels)
return fig, ax
def Te_prof_plot(sampler, ax=None, legend=True, **kwargs):
s_vals, Te_avg_prof_samples, Te_avg_CI = sampler.get_Te_samples(**kwargs)
if ax is None:
fig, ax = plt.subplots(1,1)
idap.profile_CIs(ax, Te_avg_CI, s_vals, ylim=[0,1], ylabel=r'$T_e$', legend=legend)
ax.set_ylabel('Electron temperature (eV)')
ax.set_xlabel(r'Flux surface label $\psi$')
return ax
def get_fit_plot(sampler, n_samples=1000):
fig, ax = plt.subplots(1,1)
for Ec in sampler.thresholds:
model_samples = np.zeros([n_samples, 60])
for index,n in enumerate(np.random.randint(sampler.samples[Ec].shape[0]-1, size=n_samples)):
theta = sampler.samples[Ec][n,:]
model_samples[index,:] = sampler.get_model(theta, Ec=Ec)
model_CI = ida.profile_confidence(model_samples)
ax.errorbar(sampler.signed_ps[Ec], sampler.mesxr_data[Ec], yerr=sampler.mesxr_sigmas[Ec], marker='o', ms=3, capsize=3,
linestyle='none', label='Data', zorder=100)
idap.profile_CIs(plt.gca(), model_CI, sampler.p3det.p[Ec], ylim=[-0.45,0.45], ylabel=r'$N_\gamma$', legend=False, cid=4)
plt.xlabel('Chord radius (m)')
plt.ylabel('Counts (photons/ms)')
plt.xlim([-0.45, 0.45])
plt.ylim([0,None])
return fig, ax
def get_hist_plot(sampler, s_index=0, include=None, xlim=(500,2000)):
if include is None:
include = [Ec for Ec in sampler.thresholds if Ec != sampler.Ec_ref]
ratios = {Ec:sampler.emiss_samples[Ec][:,s_index]/sampler.emiss_samples[sampler.Ec_ref][:,s_index] for Ec in include}
Te_samples = {Ec:sampler.Te_from_R(ratios[Ec], Ec=Ec) for Ec in include}
s_vals, Te_avg_samples, Te_avg_CI = sampler.get_Te_samples(include=include)
fig, ax = plt.subplots(1,1)
norm = Normalize(min(include), max(include))
cmap = cm.jet
for Ec in include:
hout = plt.hist(Te_samples[Ec], bins=100, histtype='step', density=True, color='black', range=xlim)
kde = sp.stats.gaussian_kde(Te_samples[Ec])
tes = np.linspace(*xlim, num=2000)
plt.plot(tes, kde(tes), label=Ec, color=cmap(norm(Ec)))
hout = plt.hist(Te_avg_samples[:,s_index], bins=100, histtype='step', density=True, color='black', range=xlim)
kde = sp.stats.gaussian_kde(Te_avg_samples[:,s_index])
tes = np.linspace(*xlim, num=2000)
plt.plot(tes, kde(tes), color='black', linestyle='--', label='Average')
plt.legend()
plt.xlabel('Electron temperature (eV)')
plt.ylabel(r'$p(T_e|d)$')
return fig, ax | mst_ida/analysis/samplers.py | import numpy as np
import scipy as sp
class Quad_Sampler(object):
"""
Class for drawing samples from an arbitrary one-dimensional probability distribution using numerical integration
and interpolation. In general this will be superior to more sophisticated sampling methods for 1D problems.
Assumes that priors are uniform.
Args:
ln_likelihood: Function which takes the independent variable x as its first argument and returns the log
of the likelihood function, p(d|x,I), up to a constant. May take other *args or **kwargs.
priors: List-type of the form [a,b], where a and b define the upper and lower bounds of the uniform
prior p(x|I).
optioinal:
vect: (bool) Set to true if the log-likelihood accepts a vectorized input.
"""
def __init__(self, ln_likelihood, priors, vect=False):
self._ln_likelihood = ln_likelihood
self._a, self._b = priors
self._vect = vect
# Default values
self.ln_Z = np.nan
self.mean = np.nan
self.std = np.nan
def fit(self, n_pts=200, args=(), **kwargs):
"""
Perform the fit.
Optional:
n_pts: (int) Number of evenly-spaced points over which to compute the probability.
args: (tuple) All additional arguments to be passed on the the likelihood function.
**kwargs: All other keywords are passed on the the likelihood function.
"""
# Evaluate the pdf
self.xs = np.linspace(self._a, self._b, num=n_pts)
if self._vect:
self.ln_pdf = self._ln_likelihood(self.xs, *args, **kwargs)
else:
self.ln_pdf = np.array([self._ln_likelihood(x, *args, **kwargs) for x in self.xs])
# Rescale with the maxima
ln_C = np.amax(self.ln_pdf)
pdf_scaled = np.exp(self.ln_pdf - ln_C)
# Compute the evidence and rescale
Z_scaled = np.trapz(pdf_scaled, x=self.xs)
self.ln_Z = np.log(Z_scaled) + ln_C
self.pdf = pdf_scaled / Z_scaled
self.cdf = sp.integrate.cumtrapz(self.pdf, x=self.xs, initial=0)
# Estimate summary statistics - assuming a normal distribution
samples = self.get_samples(1000)
self.mean = np.mean(samples)
self.std = np.std(samples)
def get_samples(self, n_samples):
"""
"""
u_samp = np.random.rand(n_samples)
return np.interp(u_samp, self.cdf, self.xs)
class Quad_Sampler_ND(object):
"""
Class for drawing samples from an arbitrary N-dimensional probability distribution using numerical integration
and interpolation. This can be useful for problems with a low number of dimensions (~3) for which the likelihood
function can be computed quickly (<< 1 second).
Assumes that priors are uniform. Currently does not support vectorized likelihoods.
Args:
ln_likelihood: Function which takes the independent variables (x1, x2, ..., xN) as its first argument and returns
the log of the likelihood function, p(d|x1,...,I), up to a constant. May take other *args or **kwargs.
priors: List of tuples, of the form [(a1,b1), (a2,b2), ..., (aN,bN)] where a and b define the upper and lower bounds
of the uniform prior p(x1,...|I).
optioinal:
vect: (bool) Set to true if the log-likelihood accepts a vectorized input.
"""
def __init__(self, ln_likelihood, ndim, priors):
self._ln_likelihood = ln_likelihood
self.ndim = ndim
self._a = np.zeros(self.ndim)
self._b = np.zeros(self.ndim)
for n in range(self.ndim):
self._a[n], self._b[n] = priors[n]
# Default values
self.ln_Z = np.nan
self.mean = np.nan
self.std = np.nan
def fit(self, n_pts=200, args=(), **kwargs):
"""
Perform the fit.
Optional:
n_pts: (int) Number of evenly-spaced points over which to compute the probability.
args: (tuple) All additional arguments to be passed on the the likelihood function.
**kwargs: All other keywords are passed on the the likelihood function.
This doesn't work yet.
"""
# Construct the evaluation grid
self.xs = np.zeros([self.ndim, n_pts])
for n in range(slef.ndim):
self.xs[n,:] = np.linspace(self._a[n], self._b[n], num=n_pts)
# Evaluate the pdf
self.ln_pdf = np.zeros([self.ndim, n_pts])
for n in range(slef.ndim):
self.ln_pdf[n] = np.array([self._ln_likelihood(x, *args, **kwargs) for x in self.xs[n]])
# Rescale with the maxima
ln_C = np.amax(self.ln_pdf)
pdf_scaled = np.exp(self.ln_pdf - ln_C)
# Compute the evidence and rescale
Z_scaled = np.trapz(pdf_scaled, x=self.xs)
self.ln_Z = np.log(Z_scaled) + ln_C
self.pdf = pdf_scaled / Z_scaled
self.cdf = sp.integrate.cumtrapz(self.pdf, x=self.xs, initial=0)
# Estimate summary statistics - assuming a normal distribution
samples = self.get_samples(1000)
self.mean = np.mean(samples)
self.std = np.std(samples)
def get_samples(self, n_samples):
"""
"""
u_samp = np.random.rand(n_samples)
return np.interp(u_samp, self.cdf, self.xs)
# ------------------------------------------------ MESXR Sampler ------------------------------------------------
import time
import emcee
import mst_ida.models.mesxr3 as m3
import mst_ida.data.mesxr as mesxr
import mst_ida.analysis.ida as ida
import mst_ida.analysis.emissivity as em
import mst_ida.models.base.response as rsp
from mst_ida.utilities.functions import identify_outliers
from mst_ida.models.base.geometry import flux_coords, sunflower_points
default_priors = {
'alpha':((10, 14), (0.1,18), (0.1,18))
}
class MESXR_Emiss_Sampler(object):
"""
"""
def __init__(self, shot, frame, flux=None, Ec_ref=3.0, priors=None, indices=np.arange(5,55), Ew=300.,
method='alpha', nwalkers=32, center=True, delta_a=0.06, delta_h=0.01, manual=None):
# Load the data
self.shot = shot
if manual is not None:
self.mesxr_data = manual['data']
self.mesxr_sigmas = manual['sigmas']
self.signed_ps = manual['impact_p']
self.thresholds = manual['thresholds']
else:
self.frame = frame
self.mesxr_data, self.mesxr_sigmas, self.signed_ps, self.thresholds = mesxr.get_8c_data(self.shot, self.frame, center=center)
# Model and geometry
if flux is None:
self.flux = flux_coords(delta_a=delta_a, delta_h=delta_h)
else:
self.flux = flux
self.method = method
self.p3det = m3.MESXR(shot=self.shot, center=center)
self.gij_set = {}
self.ss_set = {}
for Ec in self.thresholds:
self.gij_set[Ec], self.ss_set[Ec] = em.get_geometry_matrix(self.flux, self.p3det)
# Include specified data points
self.indices = np.arange(6,55)
z = {Ec:np.maximum(self.mesxr_data[Ec][self.indices]+1, 1) for Ec in self.thresholds}
self.ln_data_fact = {Ec:-np.sum(sp.special.loggamma(z[Ec])) for Ec in self.thresholds}
# Set up the priors
if priors is None:
self.priors = default_priors[self.method]
else:
self.priors = priors
# Sampler parameters
self.nwalkers = nwalkers
self.pos0 = self.get_pos0()
self.ndim = self.pos0.shape[1]
# Set up the samplers
moves = [(emcee.moves.DEMove(), 0.8), (emcee.moves.DESnookerMove(), 0.2),]
self.samplers = {}
for index, Ec in enumerate(self.thresholds):
self.samplers[Ec] = emcee.EnsembleSampler(self.nwalkers, self.ndim, self.ln_prob, moves=moves, kwargs={'Ec':Ec})
# Set up ratio curves
self.Ew = Ew
self.Ec_ref = Ec_ref
self.temps = np.linspace(10, 3000, num=6000)
self.ratios= {}
for Ec in self.thresholds:
if Ec != self.Ec_ref:
self.ratios[Ec] = np.array([self.model_ratio(Te,Ec*1000.) for Te in self.temps])
def fit(self, nsteps=10000, remove_outliers=True, resume=False, burn_step=3000, n_samples=5000, progress=True):
"""
"""
# MCMC sampling
if nsteps is not None:
for Ec in self.thresholds:
if not resume:
#print('Beginning sampling for Ec = ' + str(Ec) + ' keV')
time.sleep(1)
self.samplers[Ec].run_mcmc(self.pos0, nsteps, progress=progress)
else:
#print('Resuming sampling for Ec = ' + str(Ec) + ' keV')
time.sleep(1)
self.samplers[Ec].run_mcmc(None, nsteps, progress=progress)
self.samples = {Ec:self.samplers[Ec].get_chain(discard=burn_step, flat=True) for Ec in self.thresholds}
# Remove points from poorly-converged walkers
if remove_outliers:
for Ec in self.thresholds:
self.samples[Ec] = identify_outliers(self.samples[Ec])
# Save the average fit parameters
self.theta_avg = {Ec:np.average(self.samples[Ec], axis=0) for Ec in self.thresholds}
# Get the emissivity profile samples
self.n_samples = n_samples
self.emiss_samples = {Ec:self.get_emiss_samples(self.samples[Ec], Ec=Ec, n_samples=n_samples) for Ec in self.thresholds}
self.emiss_CIs = {Ec:ida.profile_confidence(self.emiss_samples[Ec]) for Ec in self.thresholds}
def get_Te_samples(self, slim=0.7, include=[4.0, 5.0]):
"""
"""
ss = self.ss_set[self.Ec_ref].ravel()
sn = np.argmin(np.abs(ss - slim))
s_vals = self.ss_set[self.Ec_ref].ravel()[:sn]
Te_avg_prof_samples = np.zeros([self.n_samples, sn])
for s_index in range(sn):
ratios = {Ec:self.emiss_samples[Ec][:,s_index]/self.emiss_samples[self.Ec_ref][:,s_index] for Ec in include}
Te_samples = {Ec:self.Te_from_R(ratios[Ec], Ec=Ec) for Ec in include}
Te_avg_prof_samples[:,s_index] = sum([Te_samples[Ec] for Ec in include]) / len(include)
Te_avg_CI = ida.profile_confidence(Te_avg_prof_samples)
return s_vals, Te_avg_prof_samples, Te_avg_CI
# ----------------------------------------------- Emissivity Model -----------------------------------------------
def emiss_model_alpha(self, ss, Xem, alpha, beta):
return (10.**Xem)*(1 - ss**alpha)**beta
def emiss_model(self, *args):
if self.method == 'alpha':
return self.emiss_model_alpha(*args)
else:
raise KeyError('Please select a valid fitting method.')
def get_model(self, theta, Ec=3.0):
gij = self.gij_set[Ec]
ss = self.ss_set[Ec]
emiss = self.emiss_model(ss, *theta)
bright = np.dot(gij, emiss).squeeze()
return self.p3det.etendue[Ec]*bright
# ----------------------------------------------- Bayesian Methods -----------------------------------------------
def ln_prob(self, theta, Ec=3.0):
lp = self.ln_prior(theta)
if np.isfinite(lp):
return lp + self.ln_likelihood(theta, Ec=Ec)
else:
return -np.inf
def ln_likelihood(self, theta, Ec=3.0):
data = self.mesxr_data[Ec][self.indices]
model = self.get_model(theta, Ec=Ec)[self.indices]
return -np.sum(model - data*np.log(model)) + self.ln_data_fact[Ec]
def ln_prior(self, theta):
if self.method == 'alpha':
return self.ln_prior_alpha(*theta)
else:
raise KeyError('Method not recognized.')
def ln_prior_alpha(self, Xem, alpha, beta):
X_min, X_max = self.priors[0]
al_min, al_max = self.priors[1]
bt_min, bt_max = self.priors[2]
if (X_min < Xem < X_max) and (al_min < alpha < al_max) and (bt_min < beta < bt_max):
return 0.0
else:
return - np.inf
def get_pos0(self):
if self.method == 'alpha':
X_min, X_max = self.priors[0]
al_min, al_max = self.priors[1]
bt_min, bt_max = self.priors[2]
pos0 = np.zeros([self.nwalkers, 3])
pos0[:,0] = (X_max - X_min)*np.random.random(size=self.nwalkers) + X_min
pos0[:,1] = (al_max - al_min)*np.random.random(size=self.nwalkers) + al_min
pos0[:,2] = (bt_max - bt_min)*np.random.random(size=self.nwalkers) + bt_min
return pos0
# ----------------------------------------------- Ratio Model -----------------------------------------------
def Te_from_R(self, rs, Ec=4.0):
if Ec > self.Ec_ref:
return np.interp(rs, self.ratios[Ec], self.temps)
else:
# Reverse to avoid interpolation error
return np.interp(rs, np.flip(self.ratios[Ec]), np.flip(self.temps))
def get_en_int(self, Te, Ec):
"""
Model the local emissivity, to a constant factor.
"""
en = np.linspace(1500, 20000, num=1000)
resp = rsp.Pilatus_Response(Ec, self.Ew)
return np.trapz(resp(en)*np.exp(-en/Te)/np.sqrt(Te)/en, x=en)
def model_ratio(self, Te, Ec):
"""
Get the ratio for a given Te and Ec relative to the reference
"""
en_int = self.get_en_int(Te, Ec)
ref = self.get_en_int(Te, self.Ec_ref*1000.)
return en_int / ref
# ----------------------------------------------- Analysis Methods -----------------------------------------------
def get_emiss_samples(self, samples, n_samples=5000, Ec=3.0):
"""
"""
ss = self.ss_set[Ec]
emiss_samples = np.zeros([n_samples, len(ss)])
for index,n in enumerate(np.random.randint(samples.shape[0]-1, size=n_samples)):
emiss_samples[index,:] = self.emiss_model(ss, *samples[n,:]).squeeze()
return emiss_samples
def get_params(self):
"""
Return LaTeX fromatted strings for each parameter.
"""
if self.method == 'alpha':
return [r'$X_{\varepsilon}$', r'$\alpha$', r'$\beta$']
else:
return []
# ----------------------------------------------- Diagnostic Plots -----------------------------------------------
import mst_ida.analysis.plots as idap
from matplotlib.lines import Line2D
from mst_ida.utilities.graphics import *
def burn_plot(sampler, Ec=3.0, burn_step=30000):
params = sampler.get_params()
return idap.burn_plot(sampler.samplers[Ec].chain, burn_step, sampler.nwalkers, indices=range(len(params)), labels=params, figsize=(8,6))
def distplot(sampler, Ec=3.0):
return distplot(sampler.samples[Ec], labels=sampler.get_params())
def emiss_xs_plot(sampler, Ec=3.0, shax=False):
"""
Plot the cross-section (XS) using the average parameter values.
"""
fig, ax = plt.subplots(1,1)
xs, ys = sunflower_points(5000)
s_xs = sampler.flux.rho(xs, ys)
emiss_xs_samples = np.zeros([sampler.n_samples, len(s_xs)])
for n in range(sampler.n_samples):
emiss_xs_samples[n,:] = sampler.emiss_model(s_xs, *sampler.samples[Ec][n,:])
emiss_xs = np.average(emiss_xs_samples, axis=0)
cax = plt.tricontourf(xs, ys, emiss_xs, 50, cmap='plasma')
plt.colorbar(cax, label=r'SXR emission (ph ms$^{-1}$ m$^{-3}$ sr$^{-1}$)')
plt.xlabel(r'$R - R_0$ (m)')
plt.ylabel(r'$Z$ (m)')
overplot_shell(plt.gca())
text(0.11, 0.96, r'$E_c = {0:.1f}$ keV'.format(Ec), plt.gca())
if shax:
levels = [0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
cax = plt.tricontour(sampler.flux.xs, sampler.flux.ys, sampler.flux.ss, levels, colors='black')
return fig, ax
def emiss_prof_plot(sampler):
fig, ax = plt.subplots(1,1)
labels = ['{0:.1f} keV'.format(Ec) for Ec in sampler.thresholds]
nlabels = len(labels)
custom_lines = [Line2D([0], [0], color='xkcd:bright blue', lw=4),
Line2D([0], [0], color='xkcd:red', lw=4),
Line2D([0], [0], color='xkcd:kelly green', lw=4),
Line2D([0], [0], color='xkcd:steel', lw=4),
Line2D([0], [0], color='xkcd:bright blue', lw=4),
Line2D([0], [0], color='xkcd:red', lw=4),
Line2D([0], [0], color='xkcd:kelly green', lw=4),
Line2D([0], [0], color='xkcd:steel', lw=4)]
for index,Ec in enumerate(sampler.thresholds):
ss = sampler.ss_set[Ec].ravel()
idap.profile_CIs(ax, sampler.emiss_CIs[Ec], ss, ylim=[0,1], ylabel=r'$\varepsilon(s)$', cid=(index%4)+1, legend=False)
ax.set_ylabel(r'SXR emission (ph ms$^{-1}$ m$^{-3}$ sr$^{-1}$)')
ax.set_xlabel('Flux $\psi$ (norm.)')
ax.legend(custom_lines[:nlabels], labels)
return fig, ax
def Te_prof_plot(sampler, ax=None, legend=True, **kwargs):
s_vals, Te_avg_prof_samples, Te_avg_CI = sampler.get_Te_samples(**kwargs)
if ax is None:
fig, ax = plt.subplots(1,1)
idap.profile_CIs(ax, Te_avg_CI, s_vals, ylim=[0,1], ylabel=r'$T_e$', legend=legend)
ax.set_ylabel('Electron temperature (eV)')
ax.set_xlabel(r'Flux surface label $\psi$')
return ax
def get_fit_plot(sampler, n_samples=1000):
fig, ax = plt.subplots(1,1)
for Ec in sampler.thresholds:
model_samples = np.zeros([n_samples, 60])
for index,n in enumerate(np.random.randint(sampler.samples[Ec].shape[0]-1, size=n_samples)):
theta = sampler.samples[Ec][n,:]
model_samples[index,:] = sampler.get_model(theta, Ec=Ec)
model_CI = ida.profile_confidence(model_samples)
ax.errorbar(sampler.signed_ps[Ec], sampler.mesxr_data[Ec], yerr=sampler.mesxr_sigmas[Ec], marker='o', ms=3, capsize=3,
linestyle='none', label='Data', zorder=100)
idap.profile_CIs(plt.gca(), model_CI, sampler.p3det.p[Ec], ylim=[-0.45,0.45], ylabel=r'$N_\gamma$', legend=False, cid=4)
plt.xlabel('Chord radius (m)')
plt.ylabel('Counts (photons/ms)')
plt.xlim([-0.45, 0.45])
plt.ylim([0,None])
return fig, ax
def get_hist_plot(sampler, s_index=0, include=None, xlim=(500,2000)):
if include is None:
include = [Ec for Ec in sampler.thresholds if Ec != sampler.Ec_ref]
ratios = {Ec:sampler.emiss_samples[Ec][:,s_index]/sampler.emiss_samples[sampler.Ec_ref][:,s_index] for Ec in include}
Te_samples = {Ec:sampler.Te_from_R(ratios[Ec], Ec=Ec) for Ec in include}
s_vals, Te_avg_samples, Te_avg_CI = sampler.get_Te_samples(include=include)
fig, ax = plt.subplots(1,1)
norm = Normalize(min(include), max(include))
cmap = cm.jet
for Ec in include:
hout = plt.hist(Te_samples[Ec], bins=100, histtype='step', density=True, color='black', range=xlim)
kde = sp.stats.gaussian_kde(Te_samples[Ec])
tes = np.linspace(*xlim, num=2000)
plt.plot(tes, kde(tes), label=Ec, color=cmap(norm(Ec)))
hout = plt.hist(Te_avg_samples[:,s_index], bins=100, histtype='step', density=True, color='black', range=xlim)
kde = sp.stats.gaussian_kde(Te_avg_samples[:,s_index])
tes = np.linspace(*xlim, num=2000)
plt.plot(tes, kde(tes), color='black', linestyle='--', label='Average')
plt.legend()
plt.xlabel('Electron temperature (eV)')
plt.ylabel(r'$p(T_e|d)$')
return fig, ax | 0.892457 | 0.697467 |
"""Export current configuration of an Anthos cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.anthos import anthoscli_backend
from googlecloudsdk.command_lib.anthos import flags
from googlecloudsdk.command_lib.util.args import common_args
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Export(base.BinaryBackedCommand):
"""Export current configuration of an Anthos cluster."""
detailed_help = {
'EXAMPLES': """
To export configuration from cluster 'my-cluster' to the local directory
`my-dir` using project 'my-project':
$ {command} my-cluster --project=my-project --output-directory=my-dir
""",
}
@staticmethod
def Args(parser):
flags.GetClusterFlag(positional=True,
help_override='The cluster name from '
'which to export the '
'configurations.').AddToParser(parser)
flags.GetLocationFlag().AddToParser(parser)
flags.GetOutputDirFlag().AddToParser(parser)
common_args.ProjectArgument(
help_text_to_overwrite='Project ID.').AddToParser(parser)
def Run(self, args):
command_executor = anthoscli_backend.AnthosCliWrapper()
export_project = args.project or properties.VALUES.core.project.Get()
cluster = args.CLUSTER or properties.VALUES.compute.zone.Get()
location = args.location
output_dir = args.OUTPUT_DIRECTORY
auth_cred = anthoscli_backend.GetAuthToken(
account=properties.VALUES.core.account.Get(), operation='export')
log.status.Print('Starting export of cluster [{}] using '
'project [{}]'.format(cluster, export_project))
response = command_executor(command='export',
cluster=cluster,
project=export_project,
location=location,
output_dir=output_dir,
show_exec_error=args.show_exec_error,
env=anthoscli_backend.GetEnvArgsForCommand(
extra_vars={'GCLOUD_AUTH_PLUGIN': 'true'}),
stdin=auth_cred)
return self._DefaultOperationResponseHandler(response) | lib/surface/anthos/export.py | """Export current configuration of an Anthos cluster."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.anthos import anthoscli_backend
from googlecloudsdk.command_lib.anthos import flags
from googlecloudsdk.command_lib.util.args import common_args
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class Export(base.BinaryBackedCommand):
"""Export current configuration of an Anthos cluster."""
detailed_help = {
'EXAMPLES': """
To export configuration from cluster 'my-cluster' to the local directory
`my-dir` using project 'my-project':
$ {command} my-cluster --project=my-project --output-directory=my-dir
""",
}
@staticmethod
def Args(parser):
flags.GetClusterFlag(positional=True,
help_override='The cluster name from '
'which to export the '
'configurations.').AddToParser(parser)
flags.GetLocationFlag().AddToParser(parser)
flags.GetOutputDirFlag().AddToParser(parser)
common_args.ProjectArgument(
help_text_to_overwrite='Project ID.').AddToParser(parser)
def Run(self, args):
command_executor = anthoscli_backend.AnthosCliWrapper()
export_project = args.project or properties.VALUES.core.project.Get()
cluster = args.CLUSTER or properties.VALUES.compute.zone.Get()
location = args.location
output_dir = args.OUTPUT_DIRECTORY
auth_cred = anthoscli_backend.GetAuthToken(
account=properties.VALUES.core.account.Get(), operation='export')
log.status.Print('Starting export of cluster [{}] using '
'project [{}]'.format(cluster, export_project))
response = command_executor(command='export',
cluster=cluster,
project=export_project,
location=location,
output_dir=output_dir,
show_exec_error=args.show_exec_error,
env=anthoscli_backend.GetEnvArgsForCommand(
extra_vars={'GCLOUD_AUTH_PLUGIN': 'true'}),
stdin=auth_cred)
return self._DefaultOperationResponseHandler(response) | 0.719679 | 0.167015 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from parameters import param_keys
#ToDo : explore idea to give parameter as placeholder to varying size in
# validation. Think is not possible, because batch size is defined when val
# iterator is created
class TrainIteratorBuilder(object):
def __init__(self, params, post_batch_processing=None,
pre_batch_processing=None, drop_remainder=False):
self.dataset, self.sample_ph, self.label_ph = \
self._create_dataset_with_placeholders(params)
self.dataset = self._shuffle_and_repeat(
self.dataset, params[param_keys.SHUFFLE_BUFFER_SIZE])
self.dataset = self._preprocess_batch(
self.dataset, pre_batch_processing)
self.dataset = self._batch_dataset(
self.dataset, params[param_keys.BATCH_SIZE], drop_remainder)
self.dataset = self._preprocess_batch(
self.dataset, post_batch_processing)
self.dataset = self._prefetch_batches(
self.dataset, params[param_keys.PREFETCH_BUFFER_SIZE])
self.iterator = self._make_iterator(self.dataset)
def _create_dataset_with_placeholders(self, params):
sample_ph = tf.placeholder(
dtype=tf.float32,
shape=(None, params[param_keys.INPUT_IMAGE_SIZE],
params[param_keys.INPUT_IMAGE_SIZE],
params[param_keys.N_INPUT_CHANNELS]))
# label_ph = tf.placeholder(
# dtype=tf.int64,
# shape=(None))
# batch_size = tf.constant(params[param_keys.BATCH_SIZE])
dataset = tf.data.Dataset.from_tensor_slices((sample_ph))#, batch_size))
#label_ph))
return dataset, sample_ph, None#label_ph
def _shuffle_and_repeat(self, dataset, shuffle_buffer):
dataset = dataset.shuffle(buffer_size=shuffle_buffer)
dataset = dataset.repeat()
return dataset
def _batch_dataset(self, dataset, batch_size, drop_remainder):
return dataset.batch(batch_size=batch_size,
drop_remainder=drop_remainder)
def _preprocess_batch(self, dataset, preprocessing_function):
if preprocessing_function is None:
return dataset
else:
return dataset.map(preprocessing_function)
def _prefetch_batches(self, dataset, prefetch_buffer):
return dataset.prefetch(buffer_size=prefetch_buffer)
def _make_iterator(self, dataset):
return dataset.make_initializable_iterator()
def get_global_iterator(self):
handle_ph = tf.placeholder(tf.string, shape=[])
global_iterator = tf.data.Iterator.from_string_handle(
handle_ph, self.dataset.output_types, self.dataset.output_shapes)
return handle_ph, global_iterator
def get_placeholders(self):
return self.sample_ph, self.label_ph
def get_iterator(self):
return self.iterator
def get_iterator_and_ph(self):
return self.iterator, self.sample_ph, self.label_ph | modules/iterators/train_iterator.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from parameters import param_keys
#ToDo : explore idea to give parameter as placeholder to varying size in
# validation. Think is not possible, because batch size is defined when val
# iterator is created
class TrainIteratorBuilder(object):
def __init__(self, params, post_batch_processing=None,
pre_batch_processing=None, drop_remainder=False):
self.dataset, self.sample_ph, self.label_ph = \
self._create_dataset_with_placeholders(params)
self.dataset = self._shuffle_and_repeat(
self.dataset, params[param_keys.SHUFFLE_BUFFER_SIZE])
self.dataset = self._preprocess_batch(
self.dataset, pre_batch_processing)
self.dataset = self._batch_dataset(
self.dataset, params[param_keys.BATCH_SIZE], drop_remainder)
self.dataset = self._preprocess_batch(
self.dataset, post_batch_processing)
self.dataset = self._prefetch_batches(
self.dataset, params[param_keys.PREFETCH_BUFFER_SIZE])
self.iterator = self._make_iterator(self.dataset)
def _create_dataset_with_placeholders(self, params):
sample_ph = tf.placeholder(
dtype=tf.float32,
shape=(None, params[param_keys.INPUT_IMAGE_SIZE],
params[param_keys.INPUT_IMAGE_SIZE],
params[param_keys.N_INPUT_CHANNELS]))
# label_ph = tf.placeholder(
# dtype=tf.int64,
# shape=(None))
# batch_size = tf.constant(params[param_keys.BATCH_SIZE])
dataset = tf.data.Dataset.from_tensor_slices((sample_ph))#, batch_size))
#label_ph))
return dataset, sample_ph, None#label_ph
def _shuffle_and_repeat(self, dataset, shuffle_buffer):
dataset = dataset.shuffle(buffer_size=shuffle_buffer)
dataset = dataset.repeat()
return dataset
def _batch_dataset(self, dataset, batch_size, drop_remainder):
return dataset.batch(batch_size=batch_size,
drop_remainder=drop_remainder)
def _preprocess_batch(self, dataset, preprocessing_function):
if preprocessing_function is None:
return dataset
else:
return dataset.map(preprocessing_function)
def _prefetch_batches(self, dataset, prefetch_buffer):
return dataset.prefetch(buffer_size=prefetch_buffer)
def _make_iterator(self, dataset):
return dataset.make_initializable_iterator()
def get_global_iterator(self):
handle_ph = tf.placeholder(tf.string, shape=[])
global_iterator = tf.data.Iterator.from_string_handle(
handle_ph, self.dataset.output_types, self.dataset.output_shapes)
return handle_ph, global_iterator
def get_placeholders(self):
return self.sample_ph, self.label_ph
def get_iterator(self):
return self.iterator
def get_iterator_and_ph(self):
return self.iterator, self.sample_ph, self.label_ph | 0.786664 | 0.184694 |
import pytest
import numpy as np
import jax
import pyscf
from pyscfad import gto
from pyscfad.lib import numpy as jnp
TOL_VAL = 1e-12
TOL_NUC = 1e-10
TOL_CS = 1e-10
TOL_EXP = 1e-9
TOL_NUC2 = 5e-9
TEST_SET = ["int1e_ovlp", "int1e_kin", "int1e_nuc",
"int1e_rinv",]
TEST_SET_ECP = ["ECPscalar"]
TEST_SET_NUC = ["int1e_nuc"]
TEST_SET_2C2E = ["int2c2e",]
@pytest.fixture
def get_mol0():
mol = pyscf.M(
atom = 'O 0. 0. 0.; H 0. , -0.757 , 0.587; H 0. , 0.757 , 0.587',
basis = 'ccpvdz',
verbose=0,
)
return mol
@pytest.fixture
def get_mol():
mol = gto.Mole()
mol.atom = 'O 0. 0. 0.; H 0. , -0.757 , 0.587; H 0. , 0.757 , 0.587'
mol.basis = 'ccpvdz'
mol.verbose=0
mol.build(trace_coords=True, trace_exp=True, trace_ctr_coeff=True)
return mol
@pytest.fixture
def get_mol_ecp0():
mol = pyscf.M(
atom = '''
Na 0. 0. 0.
H 0. 0. 1.
''',
basis = {'Na':'lanl2dz', 'H':'sto3g'},
ecp = {'Na':'lanl2dz'},
verbose=0,
)
return mol
@pytest.fixture
def get_mol_ecp():
mol = gto.Mole()
mol.atom = '''
Na 0. 0. 0.
H 0. 0. 1.
'''
mol.basis = {'Na':'lanl2dz', 'H':'sto3g'}
mol.ecp = {'Na':'lanl2dz'}
mol.verbose=0
mol.build(trace_coords=True, trace_exp=True, trace_ctr_coeff=True)
return mol
def grad_analyt(mol, intor):
atmlst = range(mol.natm)
aoslices = mol.aoslice_by_atom()
nao = mol.nao
g = np.zeros((nao,nao,mol.natm,3))
s1 = -mol.intor(intor, comp=3)
for k, ia in enumerate(atmlst):
p0, p1 = aoslices[ia,2:]
g[p0:p1,:,k] += s1[:,p0:p1].transpose(1,2,0)
g[:,p0:p1,k] += s1[:,p0:p1].transpose(2,1,0)
return g
def nuc_grad_analyt(mol):
atmlst = range(mol.natm)
aoslices = mol.aoslice_by_atom()
nao = mol.nao
g = np.zeros((nao,nao,mol.natm,3))
h1 = -mol.intor("int1e_ipnuc", comp=3)
for k, ia in enumerate(atmlst):
p0, p1 = aoslices [ia,2:]
with mol.with_rinv_at_nucleus(ia):
vrinv = mol.intor('int1e_iprinv', comp=3)
vrinv *= -mol.atom_charge(ia)
vrinv[:,p0:p1] += h1[:,p0:p1]
g[:,:,k] = vrinv.transpose(1,2,0) + vrinv.transpose(2,1,0)
return g
def ECPscalar_grad_analyt(mol):
atmlst = range(mol.natm)
aoslices = mol.aoslice_by_atom()
nao = mol.nao
g = np.zeros((nao,nao,mol.natm,3))
h1 = -mol.intor("ECPscalar_ipnuc", comp=3)
for k, ia in enumerate(atmlst):
p0, p1 = aoslices [ia,2:]
with mol.with_rinv_at_nucleus(ia):
vrinv = mol.intor('ECPscalar_iprinv', comp=3)
vrinv[:,p0:p1] += h1[:,p0:p1]
g[:,:,k] = vrinv.transpose(1,2,0) + vrinv.transpose(2,1,0)
return g
def four_point_fd(mol, intor, _env_of, disp=1e-4):
grad_fd = []
for _, ptr_exp in enumerate(_env_of):
#ptr_exp = _env_of[i]
mol._env[ptr_exp] += disp
sp = mol.intor(intor)
mol._env[ptr_exp] += disp
sp2 = mol.intor(intor)
mol._env[ptr_exp] -= disp * 4.
sm2 = mol.intor(intor)
mol._env[ptr_exp] += disp
sm = mol.intor(intor)
g = (8.*(sp-sm) - sp2 + sm2) / (12.*disp)
grad_fd.append(g)
mol._env[ptr_exp] += disp
return np.asarray(grad_fd).transpose(1,2,0)
def cs_grad_fd(mol, intor):
disp = 1e-3
_, _, _env_of = gto.mole.setup_ctr_coeff(mol)
g = four_point_fd(mol, intor, _env_of, disp)
return g
def exp_grad_fd(mol, intor):
disp = 1e-4
_, _, _env_of = gto.mole.setup_exp(mol)
g = four_point_fd(mol, intor, _env_of, disp)
return g
def func(mol, intor):
return mol.intor(intor)
def func1(mol, intor):
return jnp.linalg.norm(mol.intor(intor))
def _test_int1e_value(intor, mol0, mol1, tol=TOL_VAL):
v0 = mol0.intor(intor)
v1 = mol1.intor(intor)
assert abs(v1-v0).max() < tol
def _test_int1e_deriv_fd(intor, mol0, mol1, funfd, jacattr, tol):
v0 = mol0.intor(intor)
jac_fd = funfd(mol0, intor)
jac_fwd = jax.jacfwd(func)(mol1, intor)
jac_rev = jax.jacrev(func)(mol1, intor)
assert abs(getattr(jac_fwd, jacattr) - jac_fd).max() < tol
assert abs(getattr(jac_rev, jacattr) - jac_fd).max() < tol
g0 = np.einsum("ij,ijx->x", v0, jac_fd) / np.linalg.norm(v0)
jac_fwd = jax.jacfwd(func1)(mol1, intor)
jac_rev = jax.jacrev(func1)(mol1, intor)
assert abs(getattr(jac_fwd, jacattr) - g0).max() < tol
assert abs(getattr(jac_rev, jacattr) - g0).max() < tol
def _test_int1e_deriv_cs(intor, mol0, mol1, tol=TOL_CS):
_test_int1e_deriv_fd(intor, mol0, mol1,
cs_grad_fd, "ctr_coeff", tol)
def _test_int1e_deriv_exp(intor, mol0, mol1, tol=TOL_EXP):
_test_int1e_deriv_fd(intor, mol0, mol1,
exp_grad_fd, "exp", tol)
def _test_int1e_deriv_nuc(intor, mol0, mol1, funanal, args, tol=TOL_NUC):
v0 = mol0.intor(intor)
jac0 = funanal(*args)
jac_fwd = jax.jacfwd(func)(mol1, intor)
jac_rev = jax.jacrev(func)(mol1, intor)
assert abs(jac_fwd.coords - jac0).max() < tol
assert abs(jac_rev.coords - jac0).max() < tol
g0 = np.einsum("ij,ijnx->nx", v0, jac0) / np.linalg.norm(v0)
jac_fwd = jax.jacfwd(func1)(mol1, intor)
jac_rev = jax.jacrev(func1)(mol1, intor)
assert abs(jac_fwd.coords - g0).max() < tol
assert abs(jac_rev.coords - g0).max() < tol
# pylint: disable=redefined-outer-name
def test_int1e_deriv1(get_mol0, get_mol, get_mol_ecp0, get_mol_ecp):
mol0 = get_mol0
mol1 = get_mol
for intor in TEST_SET:
_test_int1e_value(intor, mol0, mol1)
_test_int1e_deriv_cs(intor, mol0, mol1)
_test_int1e_deriv_exp(intor, mol0, mol1)
for intor in set(TEST_SET) - set(TEST_SET_NUC):
_test_int1e_deriv_nuc(intor, mol0, mol1, grad_analyt,
(mol0, intor.replace("int1e_", "int1e_ip")))
for intor in TEST_SET_NUC:
_test_int1e_deriv_nuc(intor, mol0, mol1, nuc_grad_analyt, (mol0,))
molecp0 = get_mol_ecp0
molecp1 = get_mol_ecp
for intor in TEST_SET_ECP:
_test_int1e_value(intor, molecp0, molecp1)
_test_int1e_deriv_cs(intor, molecp0, molecp1)
_test_int1e_deriv_exp(intor, molecp0, molecp1)
_test_int1e_deriv_nuc(intor, molecp0, molecp1, ECPscalar_grad_analyt, (molecp0,))
for intor in TEST_SET_2C2E:
_test_int1e_value(intor, mol0, mol1)
_test_int1e_deriv_cs(intor, mol0, mol1)
_test_int1e_deriv_exp(intor, mol0, mol1, tol=5e-8)
_test_int1e_deriv_nuc(intor, mol0, mol1, grad_analyt,
(mol0, intor.replace("int2c2e", "int2c2e_ip1"))) | pyscfad/gto/test/test_int1e.py | import pytest
import numpy as np
import jax
import pyscf
from pyscfad import gto
from pyscfad.lib import numpy as jnp
TOL_VAL = 1e-12
TOL_NUC = 1e-10
TOL_CS = 1e-10
TOL_EXP = 1e-9
TOL_NUC2 = 5e-9
TEST_SET = ["int1e_ovlp", "int1e_kin", "int1e_nuc",
"int1e_rinv",]
TEST_SET_ECP = ["ECPscalar"]
TEST_SET_NUC = ["int1e_nuc"]
TEST_SET_2C2E = ["int2c2e",]
@pytest.fixture
def get_mol0():
mol = pyscf.M(
atom = 'O 0. 0. 0.; H 0. , -0.757 , 0.587; H 0. , 0.757 , 0.587',
basis = 'ccpvdz',
verbose=0,
)
return mol
@pytest.fixture
def get_mol():
mol = gto.Mole()
mol.atom = 'O 0. 0. 0.; H 0. , -0.757 , 0.587; H 0. , 0.757 , 0.587'
mol.basis = 'ccpvdz'
mol.verbose=0
mol.build(trace_coords=True, trace_exp=True, trace_ctr_coeff=True)
return mol
@pytest.fixture
def get_mol_ecp0():
mol = pyscf.M(
atom = '''
Na 0. 0. 0.
H 0. 0. 1.
''',
basis = {'Na':'lanl2dz', 'H':'sto3g'},
ecp = {'Na':'lanl2dz'},
verbose=0,
)
return mol
@pytest.fixture
def get_mol_ecp():
mol = gto.Mole()
mol.atom = '''
Na 0. 0. 0.
H 0. 0. 1.
'''
mol.basis = {'Na':'lanl2dz', 'H':'sto3g'}
mol.ecp = {'Na':'lanl2dz'}
mol.verbose=0
mol.build(trace_coords=True, trace_exp=True, trace_ctr_coeff=True)
return mol
def grad_analyt(mol, intor):
atmlst = range(mol.natm)
aoslices = mol.aoslice_by_atom()
nao = mol.nao
g = np.zeros((nao,nao,mol.natm,3))
s1 = -mol.intor(intor, comp=3)
for k, ia in enumerate(atmlst):
p0, p1 = aoslices[ia,2:]
g[p0:p1,:,k] += s1[:,p0:p1].transpose(1,2,0)
g[:,p0:p1,k] += s1[:,p0:p1].transpose(2,1,0)
return g
def nuc_grad_analyt(mol):
atmlst = range(mol.natm)
aoslices = mol.aoslice_by_atom()
nao = mol.nao
g = np.zeros((nao,nao,mol.natm,3))
h1 = -mol.intor("int1e_ipnuc", comp=3)
for k, ia in enumerate(atmlst):
p0, p1 = aoslices [ia,2:]
with mol.with_rinv_at_nucleus(ia):
vrinv = mol.intor('int1e_iprinv', comp=3)
vrinv *= -mol.atom_charge(ia)
vrinv[:,p0:p1] += h1[:,p0:p1]
g[:,:,k] = vrinv.transpose(1,2,0) + vrinv.transpose(2,1,0)
return g
def ECPscalar_grad_analyt(mol):
atmlst = range(mol.natm)
aoslices = mol.aoslice_by_atom()
nao = mol.nao
g = np.zeros((nao,nao,mol.natm,3))
h1 = -mol.intor("ECPscalar_ipnuc", comp=3)
for k, ia in enumerate(atmlst):
p0, p1 = aoslices [ia,2:]
with mol.with_rinv_at_nucleus(ia):
vrinv = mol.intor('ECPscalar_iprinv', comp=3)
vrinv[:,p0:p1] += h1[:,p0:p1]
g[:,:,k] = vrinv.transpose(1,2,0) + vrinv.transpose(2,1,0)
return g
def four_point_fd(mol, intor, _env_of, disp=1e-4):
grad_fd = []
for _, ptr_exp in enumerate(_env_of):
#ptr_exp = _env_of[i]
mol._env[ptr_exp] += disp
sp = mol.intor(intor)
mol._env[ptr_exp] += disp
sp2 = mol.intor(intor)
mol._env[ptr_exp] -= disp * 4.
sm2 = mol.intor(intor)
mol._env[ptr_exp] += disp
sm = mol.intor(intor)
g = (8.*(sp-sm) - sp2 + sm2) / (12.*disp)
grad_fd.append(g)
mol._env[ptr_exp] += disp
return np.asarray(grad_fd).transpose(1,2,0)
def cs_grad_fd(mol, intor):
disp = 1e-3
_, _, _env_of = gto.mole.setup_ctr_coeff(mol)
g = four_point_fd(mol, intor, _env_of, disp)
return g
def exp_grad_fd(mol, intor):
disp = 1e-4
_, _, _env_of = gto.mole.setup_exp(mol)
g = four_point_fd(mol, intor, _env_of, disp)
return g
def func(mol, intor):
return mol.intor(intor)
def func1(mol, intor):
return jnp.linalg.norm(mol.intor(intor))
def _test_int1e_value(intor, mol0, mol1, tol=TOL_VAL):
v0 = mol0.intor(intor)
v1 = mol1.intor(intor)
assert abs(v1-v0).max() < tol
def _test_int1e_deriv_fd(intor, mol0, mol1, funfd, jacattr, tol):
v0 = mol0.intor(intor)
jac_fd = funfd(mol0, intor)
jac_fwd = jax.jacfwd(func)(mol1, intor)
jac_rev = jax.jacrev(func)(mol1, intor)
assert abs(getattr(jac_fwd, jacattr) - jac_fd).max() < tol
assert abs(getattr(jac_rev, jacattr) - jac_fd).max() < tol
g0 = np.einsum("ij,ijx->x", v0, jac_fd) / np.linalg.norm(v0)
jac_fwd = jax.jacfwd(func1)(mol1, intor)
jac_rev = jax.jacrev(func1)(mol1, intor)
assert abs(getattr(jac_fwd, jacattr) - g0).max() < tol
assert abs(getattr(jac_rev, jacattr) - g0).max() < tol
def _test_int1e_deriv_cs(intor, mol0, mol1, tol=TOL_CS):
_test_int1e_deriv_fd(intor, mol0, mol1,
cs_grad_fd, "ctr_coeff", tol)
def _test_int1e_deriv_exp(intor, mol0, mol1, tol=TOL_EXP):
_test_int1e_deriv_fd(intor, mol0, mol1,
exp_grad_fd, "exp", tol)
def _test_int1e_deriv_nuc(intor, mol0, mol1, funanal, args, tol=TOL_NUC):
v0 = mol0.intor(intor)
jac0 = funanal(*args)
jac_fwd = jax.jacfwd(func)(mol1, intor)
jac_rev = jax.jacrev(func)(mol1, intor)
assert abs(jac_fwd.coords - jac0).max() < tol
assert abs(jac_rev.coords - jac0).max() < tol
g0 = np.einsum("ij,ijnx->nx", v0, jac0) / np.linalg.norm(v0)
jac_fwd = jax.jacfwd(func1)(mol1, intor)
jac_rev = jax.jacrev(func1)(mol1, intor)
assert abs(jac_fwd.coords - g0).max() < tol
assert abs(jac_rev.coords - g0).max() < tol
# pylint: disable=redefined-outer-name
def test_int1e_deriv1(get_mol0, get_mol, get_mol_ecp0, get_mol_ecp):
mol0 = get_mol0
mol1 = get_mol
for intor in TEST_SET:
_test_int1e_value(intor, mol0, mol1)
_test_int1e_deriv_cs(intor, mol0, mol1)
_test_int1e_deriv_exp(intor, mol0, mol1)
for intor in set(TEST_SET) - set(TEST_SET_NUC):
_test_int1e_deriv_nuc(intor, mol0, mol1, grad_analyt,
(mol0, intor.replace("int1e_", "int1e_ip")))
for intor in TEST_SET_NUC:
_test_int1e_deriv_nuc(intor, mol0, mol1, nuc_grad_analyt, (mol0,))
molecp0 = get_mol_ecp0
molecp1 = get_mol_ecp
for intor in TEST_SET_ECP:
_test_int1e_value(intor, molecp0, molecp1)
_test_int1e_deriv_cs(intor, molecp0, molecp1)
_test_int1e_deriv_exp(intor, molecp0, molecp1)
_test_int1e_deriv_nuc(intor, molecp0, molecp1, ECPscalar_grad_analyt, (molecp0,))
for intor in TEST_SET_2C2E:
_test_int1e_value(intor, mol0, mol1)
_test_int1e_deriv_cs(intor, mol0, mol1)
_test_int1e_deriv_exp(intor, mol0, mol1, tol=5e-8)
_test_int1e_deriv_nuc(intor, mol0, mol1, grad_analyt,
(mol0, intor.replace("int2c2e", "int2c2e_ip1"))) | 0.28279 | 0.433142 |