text stringlengths 957 885k |
|---|
<gh_stars>1-10
import gc
import os
from distutils.util import strtobool
from pathlib import Path
from typing import Optional, Union
import numpy as np
import scipy.sparse as sps
_USE_NUMBA = bool(strtobool(os.environ.get("USE_NUMBA", "True")))
_USE_NUMBA_PARALLEL = bool(strtobool(os.environ.get("USE_NUMBA_PARALLEL", "True")))
if _USE_NUMBA:
from numba import njit, prange
else:
prange = range
def njit(*args, **kwargs):
def nojit(f):
return f
return nojit
from .serializer import deserialize_eals_joblib, serialize_eals_joblib
from .util import Timer
class ElementwiseAlternatingLeastSquares:
"""Element-wise Alternating Least Squares (eALS)
Parameters
----------
factors: int
Dimension of latent vectors
w0: float
Overall weight of missing data
alpha: float
Control parameter for significance level of popular items
regularization: float
Regularization parameter lambda
init_mean: float
Mean of initial latent vectors
init_stdev: float
Standard deviation of initial latent vectors
num_iter: int
The number of iterations for batch training
num_iter_online: int
The number of iterations for online training
dtype: type
Data type of the rating matrix passed to fit()
random_state: int
Numpy random seed
Attributes
----------
user_factors: numpy.ndarray
Latent vectors for users
item_factors: numpy.ndarray
Latent vectors for items
Notes
----------
Original eALS paper and Java inplementation
- https://arxiv.org/abs/1708.05024
- https://github.com/hexiangnan/sigir16-eals
"""
def __init__(
self,
factors: int = 64,
w0: float = 10,
alpha: float = 0.75,
regularization: float = 0.01,
init_mean: float = 0,
init_stdev: float = 0.01,
num_iter: int = 50,
num_iter_online: int = 1,
dtype: type = np.float32,
random_state: Optional[int] = None,
) -> None:
self.factors = factors
self.w0 = w0
self.alpha = alpha
self.regularization = regularization
self.init_mean = init_mean
self.init_stdev = init_stdev
self.num_iter = num_iter
self.num_iter_online = num_iter_online
self.dtype = dtype
self.random_state = random_state
# "batch" (use csr/csc matrix) or "online" (use lil matrix)
self._training_mode = "batch"
@property
def user_factors(self) -> np.ndarray:
return self.U
@property
def item_factors(self) -> np.ndarray:
return self.V
@property
def user_items(self) -> sps.spmatrix:
if self._training_mode == "batch":
return self._user_items
if self._training_mode == "online":
return self._user_items_lil
raise NotImplementedError(
f"property user_items for self._training_mode='{self._training_mode}' is not defined"
)
def fit(
self, user_items: sps.spmatrix, show_loss: bool = False, postprocess: bool = True
) -> None:
"""Fit the model to the given rating data from scratch
Parameters
----------
user_items: scipy.sparse.spmatrix
Rating matrix for user-item pairs
show_loss: bool
Whether to compute and print the loss after each iteration
postprocess: bool
If True, change the format of the rating matrix from CSR to LIL
in order to update_model() after fit().
This postprocessing may add some performance overhead for large data.
"""
self._init_data(user_items)
timer = Timer()
for iter in range(self.num_iter):
self._update_user_and_SU_all()
if show_loss:
self._print_loss(iter + 1, "update_user", timer.elapsed())
self._update_item_and_SV_all()
if show_loss:
self._print_loss(iter + 1, "update_item", timer.elapsed())
if postprocess:
self._convert_data_for_online_training()
def update_model(self, u: int, i: int, show_loss: bool = False) -> None:
"""Update the model for single, possibly new user-item pair
Parameters
----------
u: int
User index
i: int
Item index
show_loss: bool
Whether to compute and print the loss after each iteration.
Enabling this option may slow down training.
"""
timer = Timer()
self._convert_data_for_online_training()
self._expand_data(u, i)
self._user_items_lil[u, i] = 1
self._user_items_lil_t[i, u] = 1
# a new item
if self.Wi[i] == 0:
# NOTE: This update rule for Wi does not seem to be described in the paper.
self.Wi[i] = self.w0 / self.item_count
for f in range(self.factors):
for k in range(f + 1):
val = self.SV[f, k] + self.V[i, f] * self.V[i, k] * self.Wi[i]
self.SV[f, k] = val
self.SV[k, f] = val
for _ in range(self.num_iter_online):
old_user_vec = self._update_user(u)
self._update_SU(u, old_user_vec)
old_item_vec = self._update_item(i)
self._update_SV(i, old_item_vec)
if show_loss:
self._print_loss(1, "update_model", timer.elapsed())
def _init_data(self, user_items: sps.spmatrix) -> None:
"""Initialize parameters and hyperparameters before batch training"""
# coerce user_items to csr matrix with float32 type
if not isinstance(user_items, sps.csr_matrix):
print("converting user_items to CSR matrix")
user_items = user_items.tocsr()
if user_items.dtype != self.dtype:
print(f"converting type of user_items to {self.dtype}")
user_items = user_items.astype(self.dtype)
self._user_items = user_items
self._user_items_csc = self._user_items.tocsc()
self.user_count, self.item_count = self._user_items.shape
# item frequencies
p = self._user_items_csc.getnnz(axis=0)
# item popularities
p = (p / p.sum()) ** self.alpha
# confidence that item i missed by users is a true negative assessment
self.Wi = p / p.sum() * self.w0
# data and weights for online training
self._user_items_lil = sps.lil_matrix((0, 0))
self._user_items_lil_t = sps.lil_matrix((0, 0))
if self.random_state is not None:
np.random.seed(self.random_state)
self.U = self._init_U()
self.V = self._init_V()
self.SU = self.U.T @ self.U
self.SV = (self.V.T * self.Wi) @ self.V
self._training_mode = "batch"
def _init_U(self) -> np.ndarray:
U0: np.ndarray = np.random.normal(
self.init_mean, self.init_stdev, (self.user_count, self.factors)
)
return U0
def _init_V(self) -> np.ndarray:
V0: np.ndarray = np.random.normal(
self.init_mean, self.init_stdev, (self.item_count, self.factors)
)
return V0
def _convert_data_for_online_training(self) -> None:
"""convert matrices to lil for online training"""
if self._training_mode == "online":
return
del self._user_items_csc
gc.collect()
self._user_items_lil = self._user_items.tolil()
del self._user_items
gc.collect()
self._user_items_lil_t = self._user_items_lil.T
self._training_mode = "online"
def _convert_data_for_batch_training(self) -> None:
"""convert matrices to csr for batch training"""
if self._training_mode == "batch":
return
del self._user_items_lil_t
gc.collect()
self._user_items = self._user_items_lil.tocsr()
del self._user_items_lil
gc.collect()
self._user_items_csc = self._user_items.tocsc()
self._training_mode = "batch"
def _update_user(self, u: int) -> sps.spmatrix:
"""Update the user latent vector"""
self._convert_data_for_online_training()
old_user_vec = self.U[[u]]
_update_user(
u,
np.array(self._user_items_lil.rows[u], dtype=np.int32),
np.array(self._user_items_lil.data[u], dtype=self.dtype),
self.U,
self.V,
self.SV,
self.Wi,
self.factors,
self.regularization,
)
return old_user_vec
def _update_SU(self, u: int, old_user_vec: sps.spmatrix) -> None:
_update_SU(self.SU, old_user_vec, self.U[[u]])
def _update_user_and_SU_all(self) -> None:
self._convert_data_for_batch_training()
_update_user_and_SU_all(
self._user_items.indptr,
self._user_items.indices,
self._user_items.data,
self.U,
self.V,
self.SU,
self.SV,
self.Wi,
self.factors,
self.regularization,
self.user_count,
)
def _update_item(self, i: int) -> sps.spmatrix:
"""Update the item latent vector"""
self._convert_data_for_online_training()
old_item_vec = self.V[[i]]
_update_item(
i,
np.array(self._user_items_lil_t.rows[i], dtype=np.int32),
np.array(self._user_items_lil_t.data[i], dtype=self.dtype),
self.U,
self.V,
self.SU,
self.Wi,
self.factors,
self.regularization,
)
return old_item_vec
def _update_SV(self, i: int, old_item_vec: sps.spmatrix) -> None:
_update_SV(self.SV, old_item_vec, self.V[[i]], self.Wi[i])
def _update_item_and_SV_all(self) -> None:
self._convert_data_for_batch_training()
_update_item_and_SV_all(
self._user_items_csc.indptr,
self._user_items_csc.indices,
self._user_items_csc.data,
self.U,
self.V,
self.SU,
self.SV,
self.Wi,
self.factors,
self.regularization,
self.item_count,
)
def _expand_data(self, u: int, i: int) -> None:
"""Expand matrices for a new user-item pair if necessary"""
extra_count = 100
if u >= self.user_count:
new_user_count = u + extra_count
else:
new_user_count = self.user_count
if i >= self.item_count:
new_item_count = i + extra_count
else:
new_item_count = self.item_count
if new_user_count > self.user_count or new_item_count > self.item_count:
self._user_items_lil.resize(new_user_count, new_item_count)
self._user_items_lil_t.resize(new_item_count, new_user_count)
if new_user_count > self.user_count:
adding_user_count = new_user_count - self.user_count
# user_count, factors
self.U = np.vstack((self.U, np.zeros((adding_user_count, self.U.shape[1]))))
if new_item_count > self.item_count:
adding_item_count = new_item_count - self.item_count
# item_count, factors
self.V = np.vstack((self.V, np.zeros((adding_item_count, self.V.shape[1]))))
self.Wi = np.append(self.Wi, np.zeros(adding_item_count))
self.user_count = new_user_count
self.item_count = new_item_count
def calc_loss(self) -> float:
loss: float
if self._training_mode == "batch":
loss = _calc_loss_csr(
self._user_items.indptr,
self._user_items.indices,
self._user_items.data,
self.U,
self.V,
self.SV,
self.Wi,
self.user_count,
self.regularization,
)
elif self._training_mode == "online":
loss = _calc_loss_lil(
self._user_items_lil_t.rows,
self._user_items_lil_t.data,
self.U,
self.V,
self.SV,
self.Wi,
self.user_count,
self.item_count,
self.regularization,
self.dtype,
)
else:
raise NotImplementedError(
f"calc_loss() for self._training_mode='{self._training_mode}' is not defined"
)
return loss
def _print_loss(self, iter: int, message: str, elapsed: float) -> None:
"""Print the loss per nonzero element of user_items"""
loss = self.calc_loss() / self.user_items.nnz
print(f"iter={iter} {message} loss={loss:.4f} ({elapsed:.4f} sec)")
def save(self, file: Union[Path, str], compress: Union[bool, int] = True) -> None:
"""Save the model in joblib format
Parameters
----------
file: Union[pathlib.Path, str]
File to save the model
compress: Union[bool, int]
Joblib compression level (0-9).
False or 0 disables compression.
True (default) is equal to compression level 3.
"""
serialize_eals_joblib(file, self, compress=compress)
def load_model(file: Union[Path, str]) -> ElementwiseAlternatingLeastSquares:
"""Load the model from a joblib file
Parameters
----------
file: Union[pathlib.Path, str]
File to load the model from
"""
return deserialize_eals_joblib(file)
# Actual implementation of eALS with Numba JIT
@njit(
# TODO: Explicit type annotations slow down computation. Why?
# "(i8,i4[:],f4[:],f8[:,:],f8[:,:],f8[:,:],f4[:],f8[:],i8,f8)"
)
def _update_user(u, item_inds, item_ratings, U, V, SV, Wi, factors, regularization):
# Matrix U will be modified. Other arguments are read-only.
if len(item_inds) == 0:
return
V_items = V[item_inds]
pred_items = V_items @ U[u]
w_diff = (item_ratings > 0) - Wi[item_inds]
for f in range(factors):
numer = 0
for k in range(factors):
if k != f:
numer -= U[u, k] * SV[f, k]
denom = SV[f, f] + regularization
for i in range(len(item_inds)):
pred_items[i] -= V_items[i, f] * U[u, f]
numer += (item_ratings[i] - w_diff[i] * pred_items[i]) * V_items[i, f]
denom += w_diff[i] * (V_items[i, f] ** 2)
new_u = numer / denom
U[u, f] = new_u
for i in range(len(item_inds)):
pred_items[i] += V_items[i, f] * new_u
@njit()
def _update_SU(SU, old_user_vec, new_user_vec):
SU -= old_user_vec.T @ old_user_vec - new_user_vec.T @ new_user_vec
@njit(
# "(i4[:],i4[:],f4[:],f8[:,:],f8[:,:],f8[:,:],f8[:,:],i4[:],f4[:],f8[:],i8,f8,i8)",
parallel=_USE_NUMBA_PARALLEL,
)
def _update_user_and_SU_all(
indptr, indices, data, U, V, SU, SV, Wi, factors, regularization, user_count
):
# U and SU will be modified. Other arguments are read-only.
for u in prange(user_count):
item_inds = indices[indptr[u] : indptr[u + 1]]
item_ratings = data[indptr[u] : indptr[u + 1]]
_update_user(u, item_inds, item_ratings, U, V, SV, Wi, factors, regularization)
# in-place assignment
SU[:] = U.T @ U
@njit(
# "(i8,i4[:],f4[:],f8[:,:],f8[:,:],f8[:,:],f4[:],f8[:],i8,f8)"
)
def _update_item(i, user_inds, user_ratings, U, V, SU, Wi, factors, regularization):
# Matrix V will be modified. Other arguments are read-only.
if len(user_inds) == 0:
return
U_users = U[user_inds]
pred_users = U_users @ V[i]
w_diff = (user_ratings > 0) - Wi[i]
for f in range(factors):
numer = 0
for k in range(factors):
if k != f:
numer -= V[i, k] * SU[f, k]
numer *= Wi[i]
denom = SU[f, f] * Wi[i] + regularization
for u in range(len(user_inds)):
pred_users[u] -= U_users[u, f] * V[i, f]
numer += (user_ratings[u] - w_diff[u] * pred_users[u]) * U_users[u, f]
denom += w_diff[u] * (U_users[u, f] ** 2)
new_i = numer / denom
V[i, f] = new_i
for u in range(len(user_inds)):
pred_users[u] += U_users[u, f] * new_i
@njit()
def _update_SV(SV, old_item_vec, new_item_vec, Wii):
SV -= (old_item_vec.T @ old_item_vec - new_item_vec.T @ new_item_vec) * Wii
@njit(
# "(i4[:],i4[:],f4[:],f8[:,:],f8[:,:],f8[:,:],f8[:,:],i4[:],f4[:],f8[:],i8,f8,i8)",
parallel=_USE_NUMBA_PARALLEL,
)
def _update_item_and_SV_all(
indptr, indices, data, U, V, SU, SV, Wi, factors, regularization, item_count
):
# V and SV will be modified. Other arguments are read-only.
for i in prange(item_count):
user_inds = indices[indptr[i] : indptr[i + 1]]
user_ratings = data[indptr[i] : indptr[i + 1]]
_update_item(i, user_inds, user_ratings, U, V, SU, Wi, factors, regularization)
# in-place assignment
SV[:] = (V.T * Wi) @ V
@njit(
# "(i4[:],i4[:],f4[:],f8[:,:],f8[:,:],f8[:,:],i4[:],f4[:],f8[:],i8,f8)"
)
def _calc_loss_csr(
indptr, indices, data, U, V, SV, Wi, user_count, regularization
):
loss = ((U ** 2).sum() + (V ** 2).sum()) * regularization
for u in range(user_count):
item_indices = indices[indptr[u] : indptr[u + 1]]
ratings = data[indptr[u] : indptr[u + 1]]
for i, rating in zip(item_indices, ratings):
pred = U[u] @ V[i]
loss += (rating - pred) ** 2
# for non-missing items
loss -= Wi[i] * (pred ** 2)
# sum of (Wi[i] * (pred ** 2)) for all (= missing + non-missing) items
loss += SV @ U[u] @ U[u]
return loss
@njit(
# "f8(f8[:,:],f8[:,:],f8[:,:],i8,f8)"
)
def _calc_loss_lil_init(U, V, SV, user_count, regularization):
loss = ((U ** 2).sum() + (V ** 2).sum()) * regularization
for u in range(user_count):
loss += SV @ U[u] @ U[u]
return loss
@njit(
# "f8(i8,i4[:],f4[:],f4[:],f8[:,:],f8[:,:],f8[:])"
)
def _calc_loss_lil_inner_loop(i, indices, ratings, U, V, Wi):
l = 0
for u, rating in zip(indices, ratings):
pred = U[u] @ V[i]
l += (rating - pred) ** 2
l -= Wi[i] * (pred ** 2)
return l
# TODO: @njit does not improve performance of this function. Better way to implement it?
def _calc_loss_lil(
cols: np.ndarray,
data: np.ndarray,
U: np.ndarray,
V: np.ndarray,
SV: np.ndarray,
Wi: np.ndarray,
user_count: int,
item_count: int,
regularization: float,
dtype: type,
) -> float:
loss: float = _calc_loss_lil_init(U, V, SV, user_count, regularization)
for i in range(item_count):
if not cols[i]:
continue
user_indices = np.array(cols[i], dtype=np.int32)
ratings = np.array(data[i], dtype=dtype)
loss += _calc_loss_lil_inner_loop(i, user_indices, ratings, U, V, Wi)
return loss
|
<reponame>kotania/impy
'''This module initializes lists of namedtuple that link the definitions
of models and their various versions to the existing wrapper classes.
'''
from collections import namedtuple
from impy.models import (sibyll, dpmjetIII, epos, phojet, urqmd, pythia6,
pythia8, qgsjet)
# Objects of this type contain all default initialization directions
# for each interaction model and create dictionaries that link the
# these settings to either the 'tag' or the 'crmc_id'
InteractionModelDef = namedtuple('InteractionModelDef', [
'tag', 'name', 'version', 'crmc_id', 'library_name', 'RunClass',
'EventClass', 'output_frame'
])
# The list of available interaction models. Extend with new models or
# versions when available
interaction_model_nt_init = [
[
'SIBYLL23D', 'SIBYLL', '2.3d', -1, 'sib23d', sibyll.SIBYLLRun,
sibyll.SibyllEvent, 'center-of-mass'
],
# This was the default version that was firstly circulated in CORSIKA
[
'SIBYLL23C', 'SIBYLL', '2.3c', -1, 'sib23c01', sibyll.SIBYLLRun,
sibyll.SibyllEvent, 'center-of-mass'
],
# The c03 version was also in CORSIKA until 2020
[
'SIBYLL23C03', 'SIBYLL', '2.3c03', -1, 'sib23c03', sibyll.SIBYLLRun,
sibyll.SibyllEvent, 'center-of-mass'
],
# The latest patch c04 was renamed to d, to generate less confusion
[
'SIBYLL23C04', 'SIBYLL', '2.3d', -1, 'sib23d', sibyll.SIBYLLRun,
sibyll.SibyllEvent, 'center-of-mass'
],
# The other versions are development versions and won't be distributed with impy (maybe)
[
'SIBYLL23C00', 'SIBYLL', '2.3c00', -1, 'sib23c00', sibyll.SIBYLLRun,
sibyll.SibyllEvent, 'center-of-mass'
],
[
'SIBYLL23C01', 'SIBYLL', '2.3c01', -1, 'sib23c01', sibyll.SIBYLLRun,
sibyll.SibyllEvent, 'center-of-mass'
],
[
'SIBYLL23C02', 'SIBYLL', '2.3c02', -1, 'sib23c02', sibyll.SIBYLLRun,
sibyll.SibyllEvent, 'center-of-mass'
],
[
'SIBYLL23', 'SIBYLL', '2.3', -1, 'sib23', sibyll.SIBYLLRun,
sibyll.SibyllEvent, 'center-of-mass'
],
[
'SIBYLL21', 'SIBYLL', '2.1', -1, 'sib21', sibyll.SIBYLLRun,
sibyll.SibyllEvent, 'center-of-mass'
],
[
'DPMJETIII191', 'DPMJET-III', '19.1', -1, 'dpmjetIII191',
dpmjetIII.DpmjetIIIRun, dpmjetIII.DpmjetIIIEvent, 'center-of-mass'
],
[
'DPMJETIII192', 'DPMJET-III', '19.2', -1, 'dpmjetIII191',
dpmjetIII.DpmjetIIIRun, dpmjetIII.DpmjetIIIEvent, 'center-of-mass'
],
[
'DPMJETIII306', 'DPMJET-III', '3.0-6', -1, 'dpmjet306',
dpmjetIII.DpmjetIIIRun, dpmjetIII.DpmjetIIIEvent, 'center-of-mass'
],
[
'EPOSLHC', 'EPOS', 'LHC', -1, 'eposlhc', epos.EPOSRun, epos.EPOSEvent,
'center-of-mass'
],
[
'PHOJET112', 'PHOJET', '1.12-35', -1, 'dpmjet306',
phojet.PHOJETRun, phojet.PhojetEvent, 'center-of-mass'
],
[
'PHOJET191', 'PHOJET', '19.1', -1, 'dpmjetIII191', phojet.PHOJETRun,
phojet.PhojetEvent, 'center-of-mass'
],
[
'URQMD34', 'UrQMD', '3.4', -1, 'urqmd34', urqmd.UrQMDRun,
urqmd.UrQMDEvent, 'center-of-mass'
],
[
'PYTHIA6', 'Pythia', '6.428', -1, 'pythia6', pythia6.PYTHIA6Run,
pythia6.PYTHIA6Event, 'center-of-mass'
],
[
'PYTHIA8', 'Pythia', '8.240', -1, 'pythia8', pythia8.PYTHIA8Run,
pythia8.PYTHIA8Event, 'center-of-mass'
],
[
'QGSJET01C', 'QGSJet', '01c', -1, 'qgs01', qgsjet.QGSJet01Run,
qgsjet.QGSJETEvent, 'laboratory'
],
[
'QGSJETII03', 'QGSJet', 'II-03', -1, 'qgsII03', qgsjet.QGSJetIIRun,
qgsjet.QGSJETEvent, 'laboratory'
],
[
'QGSJETII04', 'QGSJet', 'II-04', -1, 'qgsII04', qgsjet.QGSJetIIRun,
qgsjet.QGSJETEvent, 'laboratory'
]
]
# Different kinds of lookup-maps/dictionaries to refer to models by name
# or ID
interaction_model_by_tag = {}
interaction_model_by_crmc_id = {}
for arg_tup in interaction_model_nt_init:
nt = InteractionModelDef(*arg_tup)
interaction_model_by_tag[nt.tag] = nt
interaction_model_by_crmc_id[nt.crmc_id] = nt
def make_generator_instance(int_model_def):
"""Returns instance of a <Model>Run.
"""
return int_model_def.RunClass(int_model_def)
|
import torch
import numpy as np
from openmixup.models.utils import precision_recall_f1, support
from openmixup.utils import build_from_cfg, print_log
from .registry import DATASETS, PIPELINES
from .base import BaseDataset
from torchvision.transforms import Compose
from .utils import to_numpy
try:
from skimage.feature import hog, local_binary_pattern
except:
print("Please install scikit-image.")
@DATASETS.register_module
class MaskedImageDataset(BaseDataset):
"""The dataset outputs a processed image with mask for Masked Image Modeling.
Args:
data_source (dict): Data source defined in
`mmselfsup.datasets.data_sources`.
pipeline (list[dict]): A list of basic augmentations dict, where each element
represents an operation defined in `mmselfsup.datasets.pipelines`.
mask_pipeline (list[dict]): A list of mask generation dict.
feature_mode (str): Mode of predefined feature extraction as MIM targets.
feature_args (dict): A args dict of feature extraction. Defaults to None.
prefetch (bool, optional): Whether to prefetch data. Defaults to False.
"""
def __init__(self,
data_source,
pipeline, mask_pipeline=None,
feature_mode=None, feature_args=dict(),
prefetch=False):
super(MaskedImageDataset, self).__init__(data_source, pipeline, prefetch)
self.mask_pipeline = mask_pipeline
self.feature_mode = feature_mode
assert self.feature_mode in [None, 'hog', 'lbp',]
if self.mask_pipeline is not None:
if self.feature_mode in ['hog', 'lbp']:
assert prefetch == True, "Feature extraction needs uint8 images."
else:
assert prefetch == False, "Turn off `prefetch` when use RGB target."
mask_pipeline = [build_from_cfg(p, PIPELINES) for p in mask_pipeline]
self.mask_pipeline = Compose(mask_pipeline)
self.return_label = self.data_source.return_label
if self.feature_mode == 'hog':
self.feature_args = dict(
orientations=feature_args.get('orientations', 9),
pixels_per_cell=feature_args.get('pixels_per_cell', (8, 8)),
cells_per_block=feature_args.get('cells_per_block', (1, 1)),
feature_vector=False, visualize=False, multichannel=True,
)
elif self.feature_mode == 'lbp':
self.feature_args = dict(
P=feature_args.get('P', 8),
R=feature_args.get('R', 8),
method=feature_args.get('method', 'nri_uniform'),
)
def __getitem__(self, idx):
ret_dict = dict(idx=idx)
if self.return_label:
img, target = self.data_source.get_sample(idx)
ret_dict['gt_label'] = target
else:
img = self.data_source.get_sample(idx)
# process img
img = self.pipeline(img)
img_mim = None
if self.mask_pipeline is not None:
# get predefined masks
mask = self.mask_pipeline(img)
if isinstance(mask, tuple):
img_mim, mask = mask
# get features with processed img (not ToTensor)
if self.feature_mode is not None:
if self.feature_mode == 'hog':
feat = hog(np.array(img, dtype=np.uint8), **self.feature_args).squeeze()
elif self.feature_mode == 'lbp':
feat = local_binary_pattern(
np.array(img.convert('L'), dtype=np.uint8).squeeze(), **self.feature_args)
feat = np.expand_dims(feat, axis=2) / np.max(feat)
# [H, W, 3] -> [C', H', W']
feat = torch.from_numpy(feat).type(torch.float32).permute(2, 0, 1)
mask = [mask, feat] # extracted feature as the MIM target
else:
mask = [mask, img] # raw RGB img as the MIM target
ret_dict['mask'] = mask
# update masked img as the input
if img_mim is not None:
img = img_mim
if self.prefetch:
img = torch.from_numpy(to_numpy(img))
ret_dict['img'] = img
return ret_dict
def evaluate(self,
scores, keyword, logger=None,
metric='accuracy', metric_options=None, topk=(1, 5)):
"""The evaluation function to output accuracy (supervised).
Args:
scores (dict): The key-value pair is the output head name and
corresponding prediction values.
keyword (str): The corresponding head name.
logger (logging.Logger | str | None, optional): The defined logger
to be used. Defaults to None.
metric (str | list[str]): Metrics to be evaluated. Default to `accuracy`.
metric_options (dict, optional): Options for calculating metrics.
Allowed keys are 'thrs' and 'average_mode'. Defaults to None.
topk (tuple(int)): The output includes topk accuracy.
Returns:
dict: evaluation results
"""
if metric_options is None:
metric_options = dict(average_mode='macro')
if isinstance(metric, str):
metrics = [metric]
else:
metrics = metric
eval_res = {}
eval_log = []
allowed_metrics = ['accuracy', 'precision', 'recall', 'f1_score', 'support',]
average_mode = metric_options.get('average_mode', 'macro')
invalid_metrics = set(metrics) - set(allowed_metrics)
if len(invalid_metrics) != 0:
raise ValueError(f'metric {invalid_metrics} is not supported.')
target = torch.LongTensor(self.data_source.labels)
assert scores.size(0) == target.size(0), \
"Inconsistent length for results and labels, {} vs {}".format(
scores.size(0), target.size(0))
if 'accuracy' in metrics:
_, pred = scores.topk(max(topk), dim=1, largest=True, sorted=True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred)) # KxN
for k in topk:
correct_k = correct[:k].contiguous().view(-1).float().sum(0).item()
acc = correct_k * 100.0 / scores.size(0)
eval_res[f"{keyword}_top{k}"] = acc
eval_log.append("{}_top{}: {:.03f}".format(keyword, k, acc))
if 'support' in metrics:
support_value = support(scores, target, average_mode=average_mode)
eval_res[f'{keyword}_support'] = support_value
eval_log.append("{}_support: {:.03f}".format(keyword, support_value))
precision_recall_f1_keys = ['precision', 'recall', 'f1_score']
if len(set(metrics) & set(precision_recall_f1_keys)) != 0:
thrs = metric_options.get('thrs', 0.)
if thrs is not None:
precision_recall_f1_values = precision_recall_f1(
scores, target, average_mode=average_mode, thrs=thrs)
else:
precision_recall_f1_values = precision_recall_f1(
scores, target, average_mode=average_mode)
for key, values in zip(precision_recall_f1_keys,
precision_recall_f1_values):
if key in metrics:
if isinstance(thrs, tuple):
eval_res.update({f'{key}_thr_{thr:.2f}': value
for thr, value in zip(thrs, values)
})
else:
eval_res[key] = values
eval_log.append("{}_{}: {:.03f}".format(keyword, key, values))
if logger is not None and logger != 'silent':
for _log in eval_log:
print_log(_log, logger=logger)
return eval_res
|
<gh_stars>0
from os import listdir
from os.path import isfile, join
from subprocess import run, PIPE
from typing import List, Dict
from .... import R
import kfp
import pytest
import yaml
import tempfile
"""
To run these tests from your terminal, go to the tests directory and run:
`python -m pytest -s -n 3 run_integration_tests.py`
This script runs all the flows in the `flows` directory. It creates
each kfp run, waits for the run to fully complete, and prints whether
or not the run was successful. It also checks to make sure the logging
functionality works.
More specifically, the tests spawn KFP runs and ensure the spawning processes
have a returncode of 0. If any test fails within KFP, an exception
is raised, the test fails, and the user can access the run link to the failed
KFP run.
Parameters:
-n: specifies the number of parallel processes used by PyTest.
Sometimes, the tests may fail on KFP due to resource quota issues. If they do,
try reducing -n (number of parallel processes) so less simultaneous
KFP runs will be scheduled.
"""
def _python():
if R.use_r():
return "python3"
else:
return "python"
def obtain_flow_file_paths(flow_dir_path: str) -> List[str]:
file_paths = [
file_name
for file_name in listdir(flow_dir_path)
if isfile(join(flow_dir_path, file_name))
and not file_name.startswith(".")
and not "raise_error_flow" in file_name
and not "accelerator_flow" in file_name
]
return file_paths
# this test ensures the integration tests fail correctly
def test_raise_failure_flow(pytestconfig) -> None:
test_cmd = (
f"{_python()} flows/raise_error_flow.py --datastore=s3 kfp run "
f"--wait-for-completion --workflow-timeout 1800 "
f"--max-parallelism 3 --experiment metaflow_test --tag test_t1 "
)
if pytestconfig.getoption("image"):
test_cmd += (
f"--no-s3-code-package --base-image {pytestconfig.getoption('image')}"
)
run_and_wait_process = run(
test_cmd,
universal_newlines=True,
stdout=PIPE,
shell=True,
)
# this ensures the integration testing framework correctly catches a failing flow
# and reports the error
assert run_and_wait_process.returncode == 1
return
def exists_nvidia_accelerator(node_selector_term: Dict) -> bool:
for affinity_match_expression in node_selector_term["matchExpressions"]:
if (
affinity_match_expression["key"] == "k8s.amazonaws.com/accelerator"
and affinity_match_expression["operator"] == "In"
and "nvidia-tesla-v100" in affinity_match_expression["values"]
):
return True
return False
def is_nvidia_accelerator_noschedule(toleration: Dict) -> bool:
if (
toleration["effect"] == "NoSchedule"
and toleration["key"] == "k8s.amazonaws.com/accelerator"
and toleration["operator"] == "Equal"
and toleration["value"] == "nvidia-tesla-v100"
):
return True
return False
def test_compile_only_accelerator_test() -> None:
with tempfile.TemporaryDirectory() as yaml_tmp_dir:
yaml_file_path = join(yaml_tmp_dir, "accelerator_flow.yaml")
compile_to_yaml_cmd = (
f"{_python()} flows/accelerator_flow.py --datastore=s3 kfp run "
f" --no-s3-code-package --yaml-only --pipeline-path {yaml_file_path}"
)
compile_to_yaml_process = run(
compile_to_yaml_cmd,
universal_newlines=True,
stdout=PIPE,
shell=True,
)
assert compile_to_yaml_process.returncode == 0
with open(f"{yaml_file_path}", "r") as stream:
try:
flow_yaml = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
for step in flow_yaml["spec"]["templates"]:
if step["name"] == "start":
start_step = step
break
affinity_found = False
for node_selector_term in start_step["affinity"]["nodeAffinity"][
"requiredDuringSchedulingIgnoredDuringExecution"
]["nodeSelectorTerms"]:
if exists_nvidia_accelerator(node_selector_term):
affinity_found = True
break
assert affinity_found
toleration_found = False
for toleration in start_step["tolerations"]:
if is_nvidia_accelerator_noschedule(toleration):
toleration_found = True
break
assert toleration_found
@pytest.mark.parametrize("flow_file_path", obtain_flow_file_paths("flows"))
def test_flows(pytestconfig, flow_file_path: str) -> None:
full_path = join("flows", flow_file_path)
# In the process below, stdout=PIPE because we only want to capture stdout.
# The reason is that the click echo function prints to stderr, and contains
# the main logs (run link, graph validation, package uploading, etc). We
# want to ensure these logs are visible to users and not captured.
# We use the print function in kfp_cli.py to print a magic token containing the
# run id and capture this to correctly test logging. See the
# `check_valid_logs_process` process.
test_cmd = (
f"{_python()} {full_path} --datastore=s3 kfp run "
f"--wait-for-completion --workflow-timeout 1800 "
f"--max-parallelism 3 --experiment metaflow_test --tag test_t1 "
)
if pytestconfig.getoption("image"):
test_cmd += (
f"--no-s3-code-package --base-image {pytestconfig.getoption('image')}"
)
run_and_wait_process = run(
test_cmd,
universal_newlines=True,
stdout=PIPE,
shell=True,
)
assert run_and_wait_process.returncode == 0
return
|
import numpy as np
from cv2 import cv2
def ORB(template_gray, target_gray, debug=False):
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(template_gray, None)
kp2, des2 = orb.detectAndCompute(target_gray, None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x: x.distance)
good_matches = matches[:10]
src_pts = np.float32(
[kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
dst_pts = np.float32(
[kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
matchesMask = mask.ravel().tolist()
h, w = template_gray.shape[:2]
pts = np.float32([[0, 0], [0, h-1], [w-1, h-1], [w-1, 0]]
).reshape(-1, 1, 2)
dst = cv2.perspectiveTransform(pts, M)
dst = np.int32(dst)
pos = [(dst[0][0][0].T+dst[2][0][0].T)/2,
(dst[0][0][1].T+dst[2][0][1].T)/2]
if debug:
dst += (w, 0) # adding offset
draw_params = dict(matchColor=(0, 255, 0), # draw matches in green color
singlePointColor=None,
matchesMask=matchesMask, # draw only inliers
flags=2)
img3 = cv2.drawMatches(
template_gray, kp1, target_gray, kp2, good_matches, None, **draw_params)
img3 = cv2.polylines(img3, [np.int32(dst)], True,
(0, 0, 255), 3, cv2.LINE_AA)
cv2.imwrite(
'{}/image.png'.format("C:/Users/Paver/Desktop/GIT/flipper/EXAMPLE"), img3)
return pos
def sift(template_gray, target_gray, debug=False, filename="SIFT_image"):
try:
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(template_gray, None)
kp2, des2 = sift.detectAndCompute(target_gray, None)
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
goodMatch = []
for m, n in matches:
if m.distance < 0.50*n.distance:
goodMatch.append(m)
src_pts = np.float32(
[kp1[m.queryIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
dst_pts = np.float32(
[kp2[m.trainIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
h, w = template_gray.shape[:2]
pts = np.float32([[0, 0], [0, h-1], [w-1, h-1], [w-1, 0]]
).reshape(-1, 1, 2)
dst = cv2.perspectiveTransform(pts, M)
dst = np.int32(dst)
pos = [(dst[0][0][0].T+dst[2][0][0].T)/2,
(dst[0][0][1].T+dst[2][0][1].T)/2]
if debug:
matchesMask = mask.ravel().tolist()
dst += (w, 0) # adding offset
draw_params = dict(matchColor=(0, 255, 0), # draw matches in green color
singlePointColor=None,
matchesMask=matchesMask, # draw only inliers
flags=2)
img3 = cv2.drawMatches(
template_gray, kp1, target_gray, kp2, goodMatch, None, **draw_params)
img3 = cv2.polylines(img3, [np.int32(dst)], True,
(0, 0, 255), 3, cv2.LINE_AA)
cv2.imshow('{}.png'.format(filename), img3)
cv2.waitKey(0)
cv2.destroyAllWindows()
return pos
except:
return False
def match_template(template, target, debug=False):
find_height, find_width = template.shape[:2:]
result = cv2.matchTemplate(
target, template, cv2.TM_CCOEFF_NORMED)
if debug:
cv2.imshow("template", template)
cv2.imshow("target", target)
cv2.waitKey(0)
cv2.destroyAllWindows()
reslist = cv2.minMaxLoc(result)
if debug:
cv2.rectangle(target, reslist[3], (
reslist[3][0]+find_width, reslist[3][1]+find_height), color=(0, 250, 0), thickness=2)
cv2.imwrite('image.png', target)
if reslist[1] > 0.7:
if debug:
print("[Detect]acc rate:", round(reslist[1], 2))
cv2.imwrite('image.png', target)
pos = [reslist[3][0]+find_width/2, reslist[3][1]+find_height/2]
return pos
return False
|
from django.db import models
from django.utils import timezone
from postgres_copy import CopyManager
from django.contrib.postgres.fields import JSONField
# image Table
class Image(models.Model):
image_name = models.CharField(max_length=512, blank=False, primary_key=True)
publisher = models.CharField(max_length=64)
created_at = models.DateTimeField(null=True)
updated_at = models.DateTimeField(null=True)
short_description = models.TextField(blank=True, null=True)
source = models.CharField(max_length=32, blank=True, null=True)
certification_status = models.CharField(max_length=32, blank=True, null=True)
repository_type = models.CharField(max_length=32, blank=True, null=True)
status = models.SmallIntegerField(blank=True, null=True)
is_private = models.BooleanField(blank=True, null=True)
is_automated = models.BooleanField(blank=True, null=True)
star_count = models.IntegerField(blank=True, null=True)
pull_count = models.IntegerField(blank=True, null=True)
is_migrated = models.BooleanField(blank=True, null=True)
has_starred = models.BooleanField(blank=True, null=True)
full_description = models.TextField(blank=True, null=True)
affiliation = models.CharField(max_length=32, blank=True, null=True)
tags_count = models.IntegerField(blank=True, null=True)
tags = JSONField(blank=True, null=True)
builds_count = models.IntegerField(blank=True, null=True)
builds = JSONField(blank=True, null=True)
latest_dockerfile = models.TextField(blank=True, null=True)
source_repo_id = models.IntegerField(blank=True, null=True)
source_repo = models.CharField(max_length=512, blank=True, null=True)
source_repo_location = models.CharField(max_length=16, blank=True, null=True, choices=[('GitHub', 'GitHub'), ('Bitbucket', 'Bitbucket')])
source_repo_source = models.CharField(max_length=16, blank=True, null=True, choices=[('CI', 'CI'), ('NameMatch', 'NameMatch')])
last_sent = models.DateTimeField(default=None, blank=True, null=True)
complete = models.BooleanField(default=False, blank=True, null=True)
error = models.BooleanField(default=False, blank=True, null=True)
response = JSONField(blank=True, null=True)
pagination = JSONField(blank=True, null=True, default=None)
objects = CopyManager()
def __unicode__(self):
return self.image_name
def __str__(self):
return self.__unicode__()
def update_last_sent(self):
self.refresh_from_db()
self.last_sent = timezone.now()
self.save()
def to_dict(self):
return {
'image_name': self.image_name,
'publisher': self.publisher,
'created_at': self.created_at,
'updated_at': self.updated_at,
'short_description': self.short_description,
'source': self.source,
'certification_status': self.certification_status,
'repository_type': self.repository_type,
'status': self.status,
'is_private': self.is_private,
'is_automated': self.is_automated,
'star_count': self.star_count,
'pull_count': self.pull_count,
'is_migrated': self.is_migrated,
'has_starred': self.has_starred,
'full_description': self.full_description,
'affiliation': self.affiliation,
'tags_count': self.tags_count,
'tags': self.tags,
'builds_count': self.builds_count,
'builds': self.builds,
'latest_dockerfile': self.latest_dockerfile,
'source_repo_id': self.source_repo_id,
'source_repo': self.source_repo,
'source_repo_location': self.source_repo_location,
'source_repo_source': self.source_repo_source
}
def to_task_dict(self):
return {
'image_name': self.image_name,
'publisher': self.publisher,
'pagination': self.pagination
}
# tag Table
class Tag(models.Model):
id = models.AutoField(primary_key=True)
image_name = models.CharField(max_length=512, blank=False, null=False)
tag_name = models.CharField(max_length=512, blank=True, null=True)
full_size = models.BigIntegerField(blank=True, null=True)
last_updated = models.DateTimeField(blank=True, null=True)
last_updater_username = models.CharField(max_length=64, blank=True, null=True)
last_updater_id = models.CharField(max_length=128, blank=True, null=True)
creator_id = models.CharField(max_length=128, blank=True, null=True)
tag_id = models.CharField(max_length=128, blank=True, null=True)
architecture = models.CharField(max_length=64, blank=True, null=True)
features = models.CharField(max_length=512, blank=True, null=True)
variant = models.CharField(max_length=512, blank=True, null=True)
digest_sha = models.CharField(max_length=128, blank=True, null=True)
os = models.CharField(max_length=64, blank=True, null=True)
os_features = models.CharField(max_length=512, blank=True, null=True)
os_version = models.CharField(max_length=512, blank=True, null=True)
image_size = models.BigIntegerField(blank=True, null=True)
repository_id = models.CharField(max_length=128, blank=True, null=True)
image_id = models.CharField(max_length=128, blank=True, null=True)
v2 = models.BooleanField(blank=True, null=True)
objects = CopyManager()
def __unicode__(self):
return self.image_name
def __str__(self):
return self.__unicode__()
def get_id(self):
return self.id
def to_dict(self):
return {
'id' : self.id,
'image_name': self.image_name,
'tag_name': self.tag_name,
'full_size': self.full_size,
'last_updated': self.last_updated,
'last_updater_username': self.last_updater_username,
'last_updater_id': self.last_updater_id,
'creator_id': self.creator_id,
'tag_id': self.tag_id,
'architecture': self.architecture,
'features': self.features,
'variant': self.variant,
'digest_sha': self.digest_sha,
'os': self.os,
'os_features': self.os_features,
'os_version': self.os_version,
'image_size': self.image_size,
'repository_id': self.repository_id,
'image_id': self.image_id,
'v2': self.v2
}
# build Table
class Build(models.Model):
id = models.AutoField(primary_key=True)
image_name = models.CharField(max_length=512, blank=False, null=False)
build_tag = models.CharField(max_length=512, blank=True, null=True)
commit_sha = models.CharField(max_length=128, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
started_at = models.DateTimeField(blank=True, null=True)
ended_at = models.DateTimeField(blank=True, null=True)
source_repo = models.CharField(max_length=512, blank=True, null=True)
state = models.CharField(max_length=32, blank=True, null=True)
build_code = models.CharField(max_length=128, blank=True, null=True)
user = models.CharField(max_length=64, blank=True, null=True)
uuid = models.CharField(max_length=128, blank=True, null=True)
objects = CopyManager()
def __unicode__(self):
return self.image_name
def __str__(self):
return self.__unicode__()
def get_id(self):
return self.id
def to_dict(self):
return {
'id': self.id,
'image_name': self.image_name,
'build_tag': self.build_tag,
'commit_sha': self.commit_sha,
'created_at': self.created_at,
'started_at': self.started_at,
'ended_at': self.ended_at,
'source_repo': self.source_repo,
'state': self.state,
'build_code': self.build_code,
'user': self.user,
'uuid': self.uuid
}
# dockerhub_user Table
class DockerHubUser(models.Model):
username = models.CharField(max_length=64, primary_key=True)
uid = models.CharField(max_length=128, null=True, blank=True)
created_at = models.DateTimeField(null=True, blank=True)
full_name = models.CharField(max_length=512, blank=True, null=True)
location = models.CharField(max_length=512, blank=True, null=True)
company = models.CharField(max_length=512, blank=True, null=True)
profile_url = models.CharField(max_length=512, blank=True, null=True)
type = models.CharField(max_length=64, blank=True, null=True)
objects = CopyManager()
def __str__(self):
return self.username
def to_dict(self):
return {
'username': self.username,
'uid': self.uid
}
# github_user Table
class GitHubUser(models.Model):
username = models.CharField(max_length=64, primary_key=True)
user_id = models.CharField(max_length=64, blank=True, null=True)
user_type = models.CharField(max_length=64, blank=True, null=True)
name = models.CharField(max_length=512, blank=True, null=True)
company = models.CharField(max_length=512, blank=True, null=True)
blog = models.CharField(max_length=512, blank=True, null=True)
location = models.CharField(max_length=512, blank=True, null=True)
email = models.CharField(max_length=512, blank=True, null=True)
hireable = models.CharField(max_length=512, blank=True, null=True)
bio = models.TextField(blank=True, null=True)
public_repos = models.IntegerField(blank=True, null=True)
public_gists = models.IntegerField(blank=True, null=True)
followers = models.IntegerField(blank=True, null=True)
following = models.IntegerField(blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
objects = CopyManager()
def __unicode__(self):
return self.username
def __str__(self):
return self.__unicode__()
def to_dict(self):
return {
'username': self.username,
'user_id': self.user_id,
'user_type': self.user_type,
'name': self.name,
'company': self.company,
'blog': self.blog,
'location': self.location,
'email': self.email,
'hireable': self.hireable,
'bio': self.bio,
'public_repos': self.public_repos,
'public_gists': self.public_gists,
'followers': self.followers,
'following': self.following,
'created_at': self.created_at,
'updated_at': self.updated_at
}
# bitbucket_user Table
class BitbucketUser(models.Model):
username = models.CharField(max_length=64, primary_key=True)
user_id = models.CharField(max_length=64, blank=True, null=True)
user_type = models.CharField(max_length=64, blank=True, null=True)
name = models.CharField(max_length=512, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
objects = CopyManager()
def __unicode__(self):
return self.username
def __str__(self):
return self.__unicode__()
def to_dict(self):
return {
'username': self.username,
'user_id': self.user_id,
'user_type': self.user_type,
'name': self.name,
'created_at': self.created_at
}
# repository Table
class Repository(models.Model):
repo_id = models.AutoField(primary_key=True)
repo_name = models.CharField(max_length=512, null=False, blank=False)
full_name = models.CharField(max_length=512, null=True, blank=True)
repo_location = models.CharField(max_length=16, null=False, blank=False, choices=[('GitHub', 'GitHub'), ('Bitbucket', 'Bitbucket')])
owner = models.CharField(max_length=64, blank=True, null=True)
owner_id = models.CharField(max_length=64, blank=True, null=True)
description = models.TextField(blank=True, null=True)
fork = models.BooleanField(blank=True, null=True)
branches = JSONField(blank=True, null=True)
tags = JSONField(blank=True, null=True)
releases = JSONField(blank=True, null=True)
languages = JSONField(blank=True, null=True)
language = models.CharField(max_length=64, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
pushed_at = models.DateTimeField(blank=True, null=True)
homepage = models.CharField(max_length=512, blank=True, null=True)
size = models.IntegerField(blank=True, null=True)
commits_count = models.IntegerField(blank=True, null=True)
commits = JSONField(blank=True, null=True)
stargazers_count = models.IntegerField(blank=True, null=True)
watchers_count = models.IntegerField(blank=True, null=True)
has_issues = models.BooleanField(blank=True, null=True)
has_projects = models.BooleanField(blank=True, null=True)
has_downloads = models.BooleanField(blank=True, null=True)
has_wiki = models.BooleanField(blank=True, null=True)
has_pages = models.BooleanField(blank=True, null=True)
forks_count = models.IntegerField(blank=True, null=True)
archived = models.BooleanField(blank=True, null=True)
disabled = models.BooleanField(blank=True, null=True)
open_issues_count = models.IntegerField(blank=True, null=True)
license = models.CharField(max_length=64, blank=True, null=True)
forks = models.IntegerField(blank=True, null=True)
open_issues = models.IntegerField(blank=True, null=True)
watchers = models.IntegerField(blank=True, null=True)
default_branch = models.CharField(max_length=512, blank=True, null=True)
network_count = models.IntegerField(blank=True, null=True)
subscribers_count = models.IntegerField(blank=True, null=True)
objects = CopyManager()
def __unicode__(self):
return self.repo_name
def __str__(self):
return self.__unicode__()
def get_id(self):
return self.repo_id
def get_name(self):
return self.repo_name
def get_location(self):
return self.repo_location
def to_dict(self):
return {
'repo_id': self.repo_id,
'repo_name': self.repo_name,
'repo_location': self.repo_location,
'repo_source': self.repo_source,
'owner': self.owner,
'owner_id': self.owner_id,
'description': self.description,
'fork': self.fork,
'tags': self.tags,
'releases': self.releases,
'languages': self.languages,
'language': self.language,
'created_at': self.created_at,
'updated_at': self.updated_at,
'pushed_at': self.pushed_at,
'homepage': self.homepage,
'size': self.size,
'commits_count': self.commits_count,
'commits': self.commits,
'stargazers_count': self.stargazers_count,
'watchers_count': self.watchers_count,
'has_issues': self.has_issues,
'has_projects': self.has_projects,
'has_downloads': self.has_downloads,
'has_wiki': self.has_wiki,
'has_pages': self.has_pages,
'forks_count': self.forks_count,
'archived': self.archived,
'disabled': self.disabled,
'open_issues_count': self.open_issues_count,
'license': self.license,
'forks': self.forks,
'open_issues': self.open_issues,
'watchers': self.watchers,
'default_branch': self.default_branch,
'network_count': self.network_count,
'subscribers_count': self.subscribers_count
}
# commit Table
class Commit(models.Model):
commit_id = models.AutoField(primary_key = True)
commit_sha = models.CharField(max_length=128)
repo_id = models.IntegerField(blank=False, null=False)
parents = JSONField(blank=True, null=True)
message = models.TextField(blank=True, null=True)
author_username = models.CharField(max_length=64, blank=True, null=True)
committer_username = models.CharField(max_length=64, blank=True, null=True)
author_id = models.CharField(max_length=64, blank=True, null=True)
committer_id = models.CharField(max_length=64, blank=True, null=True)
repo_name = models.CharField(max_length=512, blank=False, null=False)
repo_location = models.CharField(max_length=16, null=False, blank=False, choices=[('GitHub', 'GitHub'), ('Bitbucket', 'Bitbucket')])
stats_total = models.IntegerField(blank=True, null=True)
stats_additions = models.IntegerField(blank=True, null=True)
stats_deletions = models.IntegerField(blank=True, null=True)
changed_file_count = models.IntegerField(blank=True, null=True)
changed_files = JSONField(blank=True, null=True)
author_committed_at = models.DateTimeField(blank=True, null=True)
committer_committed_at = models.DateTimeField(blank=True, null=True)
objects = CopyManager()
def __unicode__(self):
return self.repo_name
def __str__(self):
return self.__unicode__()
def get_id(self):
return self.commit_id
def to_dict(self):
return {
'commit_id': self.commit_id,
'commit_sha': self.commit_sha,
'repo_id': self.repo_id,
'parents': self.parents,
'message': self.message,
'author_username': self.author_username,
'committer_username': self.committer_username,
'author_id': self.author_id,
'committer_id': self.committer_id,
'repo_name': self.repo_name,
'repo_location': self.repo_location,
'stats_total': self.stats_total,
'stats_additions': self.stats_additions,
'stats_deletions': self.stats_deletions,
'changed_file_count': self.changed_file_count,
'changed_files': self.changed_files,
'author_committed_at': self.author_committed_at,
'committer_committed_at': self.committer_committed_at
}
# dockerfile Table
class Dockerfile(models.Model):
dockerfile_id = models.AutoField(primary_key=True)
image_name = models.CharField(max_length=512, blank=False, null=False)
content = models.TextField(blank=True, null=True)
filename = models.CharField(max_length=512, blank=True, null=True)
path = models.CharField(max_length=512, blank=True, null=True)
repo_id = models.IntegerField(blank=False, null=False)
repo_name = models.CharField(max_length=512, blank=False, null=False)
repo_location = models.CharField(max_length=16, null=False, blank=False, choices=[('GitHub', 'GitHub'), ('Bitbucket', 'Bitbucket')])
commit_sha = models.CharField(max_length=128, blank=False, null=False)
diff = models.TextField(blank=True, null=True)
author_committed_at = models.DateTimeField(blank=True, null=True)
committer_committed_at = models.DateTimeField(blank=True, null=True)
message = models.TextField(blank=True, null=True)
objects = CopyManager()
def __unicode__(self):
return self.image_name
def __str__(self):
return self.__unicode__()
def get_id(self):
return self.dockerfile_id
def to_dict(self):
return {
'dockerfile_id': self.dockerfile_id,
'image_name': self.image_name,
'content': self.content,
'filename': self.filename,
'path': self.path,
'repo_id': self.repo_id,
'repo_name': self.repo_name,
'repo_location': self.repo_location,
'commit_sha': self.commit_sha,
'diff': self.diff
}
# changed_file Table
class ChangedFile(models.Model):
changedfile_id = models.AutoField(primary_key=True)
repo_id = models.IntegerField(blank=True, null=True)
commit_sha = models.CharField(max_length=128)
filename = models.TextField(blank=True, null=True)
status = models.CharField(max_length=64, blank=True, null=True)
additions_count = models.IntegerField(blank=True, null=True)
deletions_count = models.IntegerField(blank=True, null=True)
changes_count = models.IntegerField(blank=True, null=True)
patch = models.TextField(blank=True, null=True)
objects = CopyManager()
def __unicode__(self):
return self.changedfile_id
def get_id(self):
return self.changedfile_id
def __str__(self):
return self.__unicode__()
def to_dict(self):
return {
'changedfile_id': self.changedfile_id,
'commit_sha': self.commit_sha,
'filename': self.filename,
'status': self.status,
'additions_count': self.additions_count,
'deletions_count': self.deletions_count,
'changes_count': self.changes_count,
'patch': self.patch
}
# image_name_crawler_task Table
class ImageNameCrawlerTask(models.Model):
keyword = models.CharField(max_length=32, primary_key=True)
last_sent = models.DateTimeField(default=None, blank=True, null=True)
complete = models.BooleanField(default=False)
image_count = models.IntegerField(null=True)
error_response = models.TextField(blank=True, null=True)
objects = CopyManager()
def update_last_sent(self):
self.refresh_from_db()
self.last_sent = timezone.now()
self.save()
def __str__(self):
return self.keyword
def to_dict(self):
return {
'keyword': self.keyword,
'last_sent': self.last_sent,
'complete': self.complete,
'image_count': self.image_count,
'error_response': self.error_response
}
def to_task_dict(self):
return {
'keyword': self.keyword
}
# token Table used for the token pool
class AuthToken(models.Model):
token = models.CharField(max_length=128, primary_key=True)
in_use = models.BooleanField(default=False, blank=False, null=False)
last_sent = models.DateTimeField(default=None, blank=True, null=True)
last_update = models.DateTimeField(default=None, blank=True, null=True)
limit_remaining = models.IntegerField(default=None, blank=True, null=True)
limit_reset_time = models.DateTimeField(default=None, blank=True, null=True)
token_type = models.CharField(max_length=16, default=None, blank=False, null=True) # GitHub or Bitbucket
objects = CopyManager()
def update_last_sent(self):
self.refresh_from_db()
self.last_sent = timezone.now()
self.save()
def claim_in_use(self):
self.refresh_from_db()
self.in_use = True
self.save()
def __str__(self):
return self.token
def to_dict(self):
return {
'token':self.token,
'in_use':self.in_use,
'last_sent':self.last_sent,
'last_update':self.last_update,
'limit_remaining':self.limit_remaining,
'limit_reset_time':self.limit_reset_time,
'token_type':self.token_type
} |
# -*- coding: utf-8 -*-
"""Shared logic and abstractions of frameworks."""
import os
import abc
import copy
import json
import time
import filecmp
import re
import six
import gzip
import shutil
import collections
import traceback
from nmtwizard.logger import get_logger
from nmtwizard import config as config_util
from nmtwizard import data as data_util
from nmtwizard import serving
from nmtwizard import tokenizer
from nmtwizard import preprocess
from nmtwizard import utility
logger = get_logger(__name__)
@six.add_metaclass(abc.ABCMeta)
class Framework(utility.Utility):
"""Base class for frameworks."""
def __init__(self, stateless=False, support_multi_training_files=False):
"""Initializes the framework.
Args:
stateless: If True, no models are generated or fetched. This is the case
for local frameworks that are bridges to remote services (e.g. Google Translate).
support_multi_training_files: If True, the framework should implement the
training API receiving a data directory as argument and additional per file
metadata.
"""
super(Framework, self).__init__()
self._stateless = stateless
self._support_multi_training_files = support_multi_training_files
self._models_dir = os.getenv('MODELS_DIR')
if not stateless and not os.path.exists(self._models_dir):
os.makedirs(self._models_dir)
@property
def name(self):
return "NMT framework"
@abc.abstractmethod
def train(self,
config,
src_file,
tgt_file,
src_vocab_info,
tgt_vocab_info,
align_file=None,
model_path=None,
gpuid=0):
"""Trains for one epoch.
Args:
config: The run configuration.
src_file: The local path to the preprocessed (if any) source file.
tgt_file: The local path to the preprocessed (if any) target file.
align_file: The local path to the alignment file (between source and target).
src_vocab_info: Source vocabulary metadata (see _get_vocab_info).
tgt_vocab_info: Target vocabulary metadata (see _get_vocab_info).
model_path: The path to a model to load from.
gpuid: The GPU identifier.
Returns:
A dictionary of filenames to paths of objects to save in the model package.
"""
raise NotImplementedError()
@abc.abstractmethod
def trans(self, config, model_path, input, output, gpuid=0):
"""Translates a file.
Args:
config: The run configuration.
model_path: The path to the model to use.
input: The local path to the preprocessed (if any) source file.
output: The local path to the file that should contain the translation.
gpuid: The GPU identifier.
"""
raise NotImplementedError()
def translate_as_release(self,
config,
model_path,
input,
output,
optimization_level=None,
gpuid=0):
"""Translates a file in release condition.
This is useful when the released model contains optimizations that
change the translation result (e.g. quantization).
By default, assumes that the released model does not change the results
and calls the standard translation method. Otherwise, the framework
should release the given checkpoint and adapt the translation logic.
Args:
config: The run configuration.
model_path: The path to the checkpoint to release.
input: The local path to the preprocessed (if any) source file.
output: The local path to the file that should contain the translation.
optimization_level: An integer defining the level of optimization to
apply to the released model. 0 = no optimization, 1 = quantization.
gpuid: The GPU identifier.
"""
return self.trans(config, model_path, input, output, gpuid=gpuid)
@abc.abstractmethod
def release(self, config, model_path, optimization_level=None, gpuid=0):
"""Releases a model for serving.
Args:
config: The run configuration.
model_path: The path to the model to release.
optimization_level: An integer defining the level of optimization to
apply to the released model. 0 = no optimization, 1 = quantization.
gpuid: The GPU identifier.
Returns:
A dictionary of filenames to paths of objects to save in the released model package.
"""
raise NotImplementedError()
@abc.abstractmethod
def serve(self, config, model_path, gpuid=0):
"""Loads the model for serving.
Frameworks could start a backend server or simply load the model from Python.
Args:
config: The run configuration.
model_path: The path to the model to serve.
gpuid: The GPU identifier.
Returns:
A tuple with the created process (if any) and a dictionary containing
information to use the model (e.g. port number for a backend server).
"""
raise NotImplementedError()
@abc.abstractmethod
def forward_request(self, model_info, inputs, outputs=None, options=None):
"""Forwards a translation request to the model.
Args:
model_info: The information to reach the model, as returned by serve().
inputs: A list of inputs.
outputs: A list of (possibly partial) outputs.
options: Additional translation options.
Returns:
A list of list (batch x num. hypotheses) of serving.TranslationOutput.
"""
raise NotImplementedError()
def train_multi_files(self,
config,
data_dir,
src_vocab_info,
tgt_vocab_info,
model_path=None,
num_samples=None,
samples_metadata=None,
gpuid=0):
"""Trains for one epoch on a directory of data.
If the framework set support_multi_training_files to False (the default),
the standard train API will be called on a single parallel file.
Args:
config: The run configuration.
data_dir: The directory containing the training files.
src_vocab_info: Source vocabulary metadata (see _get_vocab_info).
tgt_vocab_info: Target vocabulary metadata (see _get_vocab_info).
model_path: The path to a model to load from.
num_samples: The total number of sentences of the training data.
samples_metadata: A dictionary mapping filenames to extra metadata set
in the distribution configuration.
gpuid: The GPU identifier.
Returns:
See train().
"""
if self._support_multi_training_files:
raise NotImplementedError()
else:
return self.train(
config,
os.path.join(data_dir, 'train.%s' % config['source']),
os.path.join(data_dir, 'train.%s' % config['target']),
src_vocab_info,
tgt_vocab_info,
align_file=os.path.join(data_dir, 'train.align'),
model_path=model_path,
gpuid=gpuid)
def declare_arguments(self, parser):
subparsers = parser.add_subparsers(help='Run type', dest='cmd')
parser_train = subparsers.add_parser('train', help='Run a training.')
parser_trans = subparsers.add_parser('trans', help='Run a translation.')
parser_trans.add_argument('-i', '--input', required=True, nargs='+',
help='Input files')
parser_trans.add_argument('-o', '--output', required=True, nargs='+',
help='Output files')
parser_trans.add_argument('--copy_source', default=False, action='store_true',
help=('Copy source files on same storage and same name '
'as the outputs (useful for chaining back-translation '
'trainings). By default, the original source file is '
'copied but when --no_postprocess is used, the '
'preprocessed source file is copied instead.'))
parser_trans.add_argument('--as_release', default=False, action='store_true',
help='Translate from a released model.')
parser_trans.add_argument('--add_bt_tag', default=False, action='store_true',
help=('Add back-translation tag to the front of the generated output. ',
'Refer to https://arxiv.org/pdf/1906.06442.pdf'))
parser_trans.add_argument('--release_optimization_level', type=int, default=1,
help=('Control the level of optimization applied to '
'released models (for compatible frameworks). '
'0 = no optimization, 1 = quantization.'))
parser_trans.add_argument('--no_postprocess', default=False, action='store_true',
help='Do not apply postprocessing on the target files.')
parser_release = subparsers.add_parser('release', help='Release a model for serving.')
parser_release.add_argument('-d', '--destination', default=None,
help='Released model storage (defaults to the model storage).')
parser_release.add_argument('-o', '--optimization_level', type=int, default=1,
help=('Control the level of optimization applied to '
'released models (for compatible frameworks). '
'0 = no optimization, 1 = quantization.'))
parser_serve = subparsers.add_parser('serve', help='Serve a model.')
parser_serve.add_argument('-hs', '--host', default="0.0.0.0",
help='Serving hostname.')
parser_serve.add_argument('-p', '--port', type=int, default=4000,
help='Serving port.')
parser_serve.add_argument('--release_optimization_level', type=int, default=1,
help=('Control the level of optimization applied to '
'released models (for compatible frameworks). '
'0 = no optimization, 1 = quantization.'))
parser_preprocess = subparsers.add_parser('preprocess', help='Sample and preprocess corpus.')
parser_preprocess.add_argument('--build_model', default=False, action='store_true',
help='Preprocess data into a model.')
parser.build_vocab = subparsers.add_parser('buildvocab', help='Build vocabularies.')
self.parser = parser
def exec_function(self, args):
"""Main entrypoint."""
if self._config is None and self._model is None:
self.parser.error('at least one of --config or --model options must be set')
config = self._config or {}
parent_model = self._model or config.get('model')
if parent_model is not None and not self._stateless:
# Download model locally and merge the configuration.
remote_model_path = self._storage.join(self._model_storage_read, parent_model)
model_path = os.path.join(self._models_dir, parent_model)
model_config = utility.fetch_model(
self._storage,
remote_model_path,
model_path,
should_check_integrity)
if 'modelType' not in model_config:
if parent_model.endswith('_release'):
model_config['modelType'] = 'release'
else:
model_config['modelType'] = 'checkpoint'
config = config_util.update_config(
copy.deepcopy(model_config), config, mode=args.config_update_mode)
else:
model_path = None
model_config = None
if args.cmd == 'train':
if parent_model is not None and config['modelType'] not in ('checkpoint', 'base', 'preprocess'):
raise ValueError('cannot train from a model that is not a training checkpoint, '
'a base model, or a preprocess model')
return self.train_wrapper(
self._task_id,
config,
self._storage,
self._model_storage_write,
self._image,
parent_model=parent_model,
model_path=model_path,
model_config=model_config,
gpuid=self._gpuid,
push_model=not self._no_push)
elif args.cmd == 'buildvocab':
self.build_vocab(
self._task_id,
config,
self._storage,
self._model_storage_write,
self._image,
push_model=not self._no_push)
elif args.cmd == 'trans':
if not self._stateless and (parent_model is None or config['modelType'] != 'checkpoint'):
raise ValueError('translation requires a training checkpoint')
return self.trans_wrapper(
config,
model_path,
self._storage,
args.input,
args.output,
as_release=args.as_release,
release_optimization_level=args.release_optimization_level,
gpuid=self._gpuid,
copy_source=args.copy_source,
add_bt_tag=args.add_bt_tag,
no_postprocess=args.no_postprocess)
elif args.cmd == 'release':
if not self._stateless and (parent_model is None or config['modelType'] != 'checkpoint'):
raise ValueError('releasing requires a training checkpoint')
if args.destination is None:
args.destination = self._model_storage_write
self.release_wrapper(
config,
model_path,
self._image,
storage=self._storage,
destination=args.destination,
optimization_level=args.optimization_level,
gpuid=self._gpuid,
push_model=not self._no_push)
elif args.cmd == 'serve':
if (not self._stateless
and (parent_model is None
or config['modelType'] not in ('checkpoint', 'release'))):
raise ValueError('serving requires a training checkpoint or a released model')
if config['modelType'] == 'checkpoint':
model_path = self.release_wrapper(
config,
model_path,
self._image,
local_destination=self._output_dir,
optimization_level=args.release_optimization_level,
gpuid=self._gpuid,
push_model=False)
config = utility.load_model_config(model_path)
self.serve_wrapper(
config, model_path, args.host, args.port, gpuid=self._gpuid)
elif args.cmd == 'preprocess':
if not args.build_model:
self.preprocess(config, self._storage)
else:
if parent_model is not None and config['modelType'] not in ('checkpoint', 'base'):
raise ValueError('cannot preprocess from a model that is not a training '
'checkpoint or a base model')
return self.preprocess_into_model(
self._task_id,
config,
self._storage,
self._model_storage_write,
self._image,
parent_model=parent_model,
model_path=model_path,
model_config=model_config,
push_model=not self._no_push)
def train_wrapper(self,
model_id,
config,
storage,
model_storage,
image,
parent_model=None,
model_path=None,
model_config=None,
gpuid=0,
push_model=True):
logger.info('Starting training model %s', model_id)
start_time = time.time()
parent_model_type = config.get('modelType') if model_path is not None else None
local_config = self._finalize_config(config)
if parent_model_type == 'preprocess':
data_dir = os.path.join(model_path, 'data')
num_samples = config['sampling']['numSamples']
samples_metadata = config['sampling']['samplesMetadata']
tokens_to_add = {}
del config['sampling']
logger.info('Using preprocessed data from %s' % data_dir)
else:
data_dir, num_samples, distribution_summary, samples_metadata, tokens_to_add = (
self._build_data(local_config))
src_vocab_info, tgt_vocab_info, _ = self._get_vocabs_info(
config,
local_config,
model_config=model_config,
tokens_to_add=tokens_to_add)
if parent_model_type in ('base',):
model_path = None
objects = self.train_multi_files(
local_config,
data_dir,
src_vocab_info,
tgt_vocab_info,
model_path=model_path,
num_samples=num_samples,
samples_metadata=samples_metadata,
gpuid=gpuid)
end_time = time.time()
logger.info('Finished training model %s in %s seconds', model_id, str(end_time-start_time))
# Fill training details.
config['model'] = model_id
config['modelType'] = 'checkpoint'
config['imageTag'] = image
build_info = {
'containerId': os.uname()[1],
'endDate': end_time,
'startDate': start_time
}
if parent_model_type == 'preprocess':
# Inherit distribution summary and the parent from the preprocess run.
config['build'].update(build_info)
else:
if parent_model:
config['parent_model'] = parent_model
parent_build_info = config.get('build')
build_info = self._summarize_data_distribution(
build_info, distribution_summary, parent_build_info=parent_build_info)
config['build'] = build_info
# Build and push the model package.
bundle_dependencies(objects, config, local_config)
objects_dir = os.path.join(self._models_dir, model_id)
utility.build_model_dir(objects_dir, objects, config, should_check_integrity)
if push_model:
storage.push(objects_dir, storage.join(model_storage, model_id))
return {
'num_sentences': config['build'].get('sentenceCount')
}
def build_vocab(self,
model_id,
config,
storage,
model_storage,
image,
push_model=True):
start_time = time.time()
local_config = self._finalize_config(config)
objects, tokenization_config = self._generate_vocabularies(local_config)
end_time = time.time()
local_config['tokenization'] = utility.resolve_environment_variables(tokenization_config)
config['tokenization'] = tokenization_config
config['model'] = model_id
config['modelType'] = 'base'
config['imageTag'] = image
config['build'] = {
'containerId': os.uname()[1],
'endDate': end_time,
'startDate': start_time
}
bundle_dependencies(objects, config, local_config)
objects_dir = os.path.join(self._models_dir, model_id)
utility.build_model_dir(objects_dir, objects, config, should_check_integrity)
if push_model:
storage.push(objects_dir, storage.join(model_storage, model_id))
def trans_wrapper(self,
config,
model_path,
storage,
inputs,
outputs,
as_release=False,
release_optimization_level=None,
gpuid=0,
copy_source=False,
add_bt_tag=False,
no_postprocess=False):
if len(inputs) != len(outputs):
raise ValueError("Mismatch of input/output files number, got %d and %d" % (
len(inputs), len(outputs)))
def translate_fn(*args, **kwargs):
if as_release:
return self.translate_as_release(
*args, optimization_level=release_optimization_level, **kwargs)
else:
return self.trans(*args, **kwargs)
local_config = self._finalize_config(config, training=False)
failed_translation = 0
translated_lines = 0
generated_tokens = 0
for input, output in zip(inputs, outputs):
try:
path_input = os.path.join(self._data_dir, storage.split(input)[-1])
path_output = os.path.join(self._output_dir, storage.split(output)[-1])
storage.get_file(input, path_input)
path_input_unzipped = decompress_file(path_input)
path_input_unzipped_parts = path_input_unzipped.split('.')
if copy_source and len(path_input_unzipped_parts) < 2:
raise ValueError("In copy_source mode, input files should have language suffix")
path_output_is_zipped = False
if path_output.endswith(".gz"):
path_output_is_zipped = True
path_output = path_output[:-3]
path_output_parts = path_output.split('.')
if copy_source and len(path_output_parts) < 2:
raise ValueError("In copy_source mode, output files should have language suffix")
logger.info('Starting translation %s to %s', path_input, path_output)
start_time = time.time()
path_input_preprocessed = self._preprocess_file(local_config, path_input_unzipped)
metadata = None
if isinstance(path_input_preprocessed, tuple):
path_input_preprocessed, metadata = path_input_preprocessed
translate_fn(local_config,
model_path,
path_input_preprocessed,
path_output,
gpuid=gpuid)
if metadata is not None:
path_input_preprocessed = (path_input_preprocessed, metadata)
num_lines, num_tokens = file_stats(path_output)
translated_lines += num_lines
generated_tokens += num_tokens
if not no_postprocess:
path_output = self._postprocess_file(
local_config, path_input_preprocessed, path_output)
if copy_source:
copied_input = output
copied_input_parts = copied_input.split('.')
source_to_copy = (
path_input_unzipped if not no_postprocess else path_input_preprocessed)
if path_output_is_zipped:
copied_input_parts[-2] = path_input_unzipped_parts[-1]
if path_input_unzipped == path_input:
path_input = compress_file(source_to_copy)
else:
copied_input_parts[-1] = path_input_unzipped_parts[-1]
path_input = source_to_copy
storage.push(path_input, ".".join(copied_input_parts))
if add_bt_tag:
post_add_bt_tag(path_output)
if path_output_is_zipped:
path_output = compress_file(path_output)
storage.push(path_output, output)
end_time = time.time()
logger.info('Finished translation in %s seconds', str(end_time-start_time))
except Exception as e:
# Catch any exception to not impact other translations.
filename = path_input if not isinstance(path_input, tuple) else path_input[0]
logger.error("Translation of file %s failed with error:\n%s" % (
filename, traceback.format_exc()))
logger.warning("Skipping translation of %s" % filename)
failed_translation += 1
if failed_translation == len(inputs):
raise RuntimeError("All translation failed, see error logs")
return {
'num_sentences': translated_lines,
'num_tokens': generated_tokens
}
def release_wrapper(self,
config,
model_path,
image,
storage=None,
local_destination=None,
destination=None,
optimization_level=None,
gpuid=0,
push_model=True):
local_config = self._finalize_config(config, training=False)
objects = self.release(
local_config,
model_path,
optimization_level=optimization_level,
gpuid=gpuid)
bundle_dependencies(objects, config, local_config)
model_id = config['model'] + '_release'
config['model'] = model_id
config['modelType'] = 'release'
config['imageTag'] = image
for name in ("parent_model", "build", "data"):
if name in config:
del config[name]
model_options = {}
supported_features = config.get('supported_features')
if supported_features is not None:
model_options['supported_features'] = supported_features
inference_options = config.get('inference_options')
if inference_options is not None:
schema = config_util.validate_inference_options(inference_options, config)
model_options['json_schema'] = schema
if model_options:
options_path = os.path.join(self._output_dir, 'options.json')
with open(options_path, 'w') as options_file:
json.dump(model_options, options_file)
objects[os.path.basename(options_path)] = options_path
if local_destination is None:
local_destination = self._models_dir
objects_dir = os.path.join(local_destination, model_id)
utility.build_model_dir(objects_dir, objects, config, should_check_integrity)
if push_model:
storage.push(objects_dir, storage.join(destination, model_id))
return objects_dir
def serve_wrapper(self, config, model_path, host, port, gpuid=0):
local_config = self._finalize_config(config, training=False)
serving.start_server(
host,
port,
local_config,
self._serving_state(local_config),
lambda: self.serve(local_config, model_path, gpuid=gpuid),
self._preprocess_input,
self.forward_request,
self._postprocess_output)
def preprocess(self, config, storage):
logger.info('Starting preprocessing data ')
start_time = time.time()
local_config = self._finalize_config(config)
outputs = self._generate_training_data(local_config)
data_dir = outputs[0]
end_time = time.time()
logger.info('Finished preprocessing data in %s seconds into %s',
str(end_time-start_time), data_dir)
def preprocess_into_model(self,
model_id,
config,
storage,
model_storage,
image,
parent_model=None,
model_path=None,
model_config=None,
push_model=True):
logger.info('Starting preprocessing %s', model_id)
start_time = time.time()
local_config = self._finalize_config(config)
data_dir, num_samples, distribution_summary, samples_metadata, tokens_to_add = (
self._build_data(local_config))
end_time = time.time()
logger.info('Finished preprocessing %s in %s seconds', model_id, str(end_time-start_time))
_, _, parent_dependencies = self._get_vocabs_info(
config,
local_config,
model_config=model_config,
tokens_to_add=tokens_to_add,
keep_previous=True)
# Fill training details.
if parent_model:
config['parent_model'] = parent_model
config['model'] = model_id
config['modelType'] = 'preprocess'
config['imageTag'] = image
config['sampling'] = {
'numSamples': num_samples,
'samplesMetadata': samples_metadata}
parent_build_info = config.get('build')
build_info = {
'containerId': os.uname()[1],
'endDate': end_time,
'startDate': start_time
}
build_info = self._summarize_data_distribution(
build_info, distribution_summary, parent_build_info=parent_build_info)
config['build'] = build_info
# Build and push the model package.
objects = {'data': data_dir}
bundle_dependencies(objects, config, local_config)
# Forward other files from the parent model that are not tracked by the config.
if model_path is not None:
for f in os.listdir(model_path):
if f not in objects and f not in parent_dependencies:
objects[f] = os.path.join(model_path, f)
objects_dir = os.path.join(self._models_dir, model_id)
utility.build_model_dir(objects_dir, objects, config, should_check_integrity)
if push_model:
storage.push(objects_dir, storage.join(model_storage, model_id))
return {
'num_sentences': build_info.get('sentenceCount')
}
def _get_vocabs_info(self,
config,
local_config,
model_config=None,
tokens_to_add=None,
keep_previous=False):
if tokens_to_add is None:
tokens_to_add = {}
tok_config = config.get('tokenization', {})
tok_local_config = local_config.get('tokenization', {})
joint_vocab = is_joint_vocab(tok_config)
parent_dependencies = {}
if model_config:
model_tok_config = model_config.get('tokenization', {})
model_tok_local_config = self._finalize_config(model_tok_config)
model_joint_vocab = is_joint_vocab(model_tok_config)
if joint_vocab != model_joint_vocab:
raise ValueError("Changing joint vocabularies to split vocabularies "
"(or vice-versa) is currently not supported.")
if keep_previous:
bundle_dependencies(
parent_dependencies,
copy.deepcopy(model_tok_config),
copy.deepcopy(model_tok_local_config))
else:
model_tok_config = None
model_tok_local_config = None
source_tokens_to_add = tokens_to_add.get('source') or []
target_tokens_to_add = tokens_to_add.get('target') or []
if joint_vocab:
source_tokens_to_add = set(list(source_tokens_to_add) + list(target_tokens_to_add))
target_tokens_to_add = source_tokens_to_add
src_info = self._get_vocab_info(
'source',
tok_config,
tok_local_config,
model_config=model_tok_config,
local_model_config=model_tok_local_config,
tokens_to_add=source_tokens_to_add,
keep_previous=keep_previous,
joint_vocab=joint_vocab)
tgt_info = self._get_vocab_info(
'target',
tok_config,
tok_local_config,
model_config=model_tok_config,
local_model_config=model_tok_local_config,
tokens_to_add=target_tokens_to_add,
keep_previous=keep_previous,
joint_vocab=joint_vocab)
return src_info, tgt_info, parent_dependencies
def _get_vocab_info(self,
side,
config,
local_config,
model_config=None,
local_model_config=None,
tokens_to_add=None,
keep_previous=False,
joint_vocab=False):
if not config:
return None
opt = config.get(side)
if opt is None or 'vocabulary' not in opt:
return None
local_opt = local_config[side]
vocab_name = side if not joint_vocab else 'joint'
current_basename = '%s-vocab.txt' % vocab_name
current_vocab = self._convert_vocab(
local_opt['vocabulary'], basename=current_basename)
# First read previous_vocabulary if given.
previous_basename = 'previous-%s-vocab.txt' % vocab_name
previous_vocab = local_opt.get('previous_vocabulary')
if previous_vocab is not None:
previous_vocab = self._convert_vocab(
previous_vocab, basename=previous_basename)
del opt['previous_vocabulary']
del local_opt['previous_vocabulary']
# Otherwise check if the vocabulary is different than the parent model.
elif model_config is not None:
model_opt = model_config[side]
local_model_opt = local_model_config[side]
previous_vocab = self._convert_vocab(
local_model_opt['vocabulary'], basename=previous_basename)
vocab_changed = not filecmp.cmp(previous_vocab, current_vocab)
if vocab_changed:
if not opt.get('replace_vocab', False):
raise ValueError('%s vocabulary has changed but replace_vocab is not set.'
% vocab_name.capitalize())
if keep_previous:
opt['previous_vocabulary'] = os.path.join("${MODEL_DIR}", previous_basename)
local_opt['previous_vocabulary'] = local_model_opt['vocabulary']
else:
os.remove(previous_vocab)
previous_vocab = None
if 'replace_vocab' in opt:
del opt['replace_vocab']
del local_opt['replace_vocab']
if tokens_to_add:
new_filename = next_filename_version(os.path.basename(local_opt["vocabulary"]))
new_vocab = os.path.join(self._data_dir, new_filename)
shutil.copy(local_opt["vocabulary"], new_vocab)
with open(new_vocab, "a") as vocab:
for token in tokens_to_add:
vocab.write("%s\n" % token)
if previous_vocab is None:
previous_vocab = current_vocab
if keep_previous:
opt['previous_vocabulary'] = opt['vocabulary']
local_opt['previous_vocabulary'] = local_opt['vocabulary']
current_vocab = self._convert_vocab(
new_vocab, basename="updated-%s-vocab.txt" % vocab_name)
opt["vocabulary"] = new_vocab
local_opt["vocabulary"] = new_vocab
VocabInfo = collections.namedtuple('VocabInfo', ['current', 'previous'])
return VocabInfo(current=current_vocab, previous=previous_vocab)
def _serving_state(self, config):
state = {}
if 'tokenization' in config:
tok_config = config['tokenization']
state['src_tokenizer'] = tokenizer.build_tokenizer(tok_config['source'])
state['tgt_tokenizer'] = tokenizer.build_tokenizer(tok_config['target'])
return state
def _preprocess_input(self, state, source, target, config):
def _maybe_tokenize(tokenizer, text):
if isinstance(text, list):
return text
if tokenizer is None:
return text.split()
return tokenizer.tokenize(text)[0]
source = _maybe_tokenize(state.get('src_tokenizer'), source)
if target is not None:
target = _maybe_tokenize(state.get('tgt_tokenizer'), target)
return source, target
def _postprocess_output(self, state, source, target, config):
if not isinstance(target, list):
return target
tokenizer = state.get('tgt_tokenizer')
if tokenizer is None:
return ' '.join(target)
return tokenizer.detokenize(target)
def _preprocess_file(self, config, input):
if 'tokenization' in config:
tok_config = config['tokenization']
src_tokenizer = tokenizer.build_tokenizer(tok_config['source'])
output = "%s.tok" % input
tokenizer.tokenize_file(src_tokenizer, input, output)
return output
return input
def _postprocess_file(self, config, source, target):
if 'tokenization' in config:
tok_config = config['tokenization']
tgt_tokenizer = tokenizer.build_tokenizer(tok_config['target'])
output = "%s.detok" % target
tokenizer.detokenize_file(tgt_tokenizer, target, output)
return output
return target
def _convert_vocab(self, vocab_file, basename=None):
if basename is None:
basename = os.path.basename(vocab_file)
converted_vocab_file = os.path.join(self._data_dir, basename)
with open(vocab_file, 'rb') as vocab, open(converted_vocab_file, 'wb') as converted_vocab:
header = True
index = 0
for line in vocab:
if header and line.startswith(b'#'):
continue
header = False
token = line.strip().split()[0]
self._map_vocab_entry(index, token, converted_vocab)
index += 1
return converted_vocab_file
def _build_data(self, config):
data_dir, train_dir, num_samples, distribution_summary, samples_metadata = (
self._generate_training_data(config))
if num_samples == 0:
raise RuntimeError('data sampling generated 0 sentences')
if distribution_summary is not None:
tokens_to_add = distribution_summary.get("tokens_to_add")
else:
tokens_to_add = None
if not self._support_multi_training_files:
data_dir = self._merge_multi_training_files(
data_dir, train_dir, config['source'], config['target'])
return data_dir, num_samples, distribution_summary, samples_metadata, tokens_to_add
def _merge_multi_training_files(self, data_path, train_dir, source, target):
merged_dir = os.path.join(self._data_dir, 'merged')
if not os.path.exists(merged_dir):
os.mkdir(merged_dir)
merged_path = os.path.join(merged_dir, train_dir)
logger.info('Merging training data to %s/train.{%s,%s}',
merged_path, source, target)
data_util.merge_files_in_directory(data_path, merged_path, source, target)
return merged_path
def _generate_training_data(self, config):
return preprocess.generate_preprocessed_data(config, self._corpus_dir, self._data_dir)
def _generate_vocabularies(self, config):
return preprocess.generate_vocabularies(config, self._corpus_dir, self._data_dir)
def _summarize_data_distribution(self, build_info, distribution, parent_build_info=None):
build_info['distribution'] = distribution
if distribution is not None:
cum_sent_count = 0
if parent_build_info is not None:
cum_sent_count = parent_build_info.get('cumSentenceCount')
sent_count = sum(v.get('lines_filtered', 0) for v in six.itervalues(distribution))
build_info['sentenceCount'] = sent_count
build_info['cumSentenceCount'] = (
cum_sent_count + sent_count if cum_sent_count is not None else None)
return build_info
def _finalize_config(self, config, training=True):
config = utility.resolve_environment_variables(config, training=training)
config = self._upgrade_data_config(config, training=training)
config = utility.resolve_remote_files(config, self._shared_dir, self._storage)
return config
def _upgrade_data_config(self, config, training=True):
if not training or 'data' not in config or 'sample_dist' not in config['data']:
return config
data = config['data']
if 'train_dir' in data:
train_dir = data['train_dir']
del data['train_dir']
else:
train_dir = 'train'
basedir = os.path.join(self._corpus_dir, train_dir)
for dist in data['sample_dist']:
if not self._storage.is_managed_path(dist['path']) and not os.path.isabs(dist['path']):
dist['path'] = os.path.join(basedir, dist['path'])
return config
def bundle_dependencies(objects, config, local_config):
"""Bundles additional resources in the model package."""
if local_config is None:
return config
if isinstance(config, list):
for i, _ in enumerate(config):
config[i] = bundle_dependencies(objects, config[i], local_config[i])
return config
elif isinstance(config, dict):
for k, v in six.iteritems(config):
if k in ('sample_dist', 'build'):
continue
config[k] = bundle_dependencies(objects, v, local_config.get(k))
return config
else:
if isinstance(config, six.string_types):
if os.path.isabs(config) and os.path.exists(config):
filename = os.path.basename(config)
else:
match = utility.ENVVAR_ABS_RE.match(config)
if match and "TRAIN" not in match.group(1):
filename = match.group(2)
else:
filename = None
if filename is not None:
objects[filename] = local_config
return '${MODEL_DIR}/%s' % filename
return config
def should_check_integrity(f):
"""Returns True if f should be checked for integrity."""
return f not in ('README.md', 'TRAINING_LOG', 'checksum.md5', 'data') and not f.startswith('.')
def file_stats(path):
num_lines = 0
num_tokens = 0
with open(path, "rb") as f:
for line in f:
num_lines += 1
num_tokens += len(line.strip().split())
return num_lines, num_tokens
def compress_file(path_input):
path_input_new = path_input
if not path_input.endswith(".gz"):
logger.info('Starting gzip %s', path_input)
path_input_new += ".gz"
with open(path_input, 'rb') as f_in, gzip.open(path_input_new, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
return path_input_new
def decompress_file(path_input):
path_input_new = path_input
if path_input.endswith(".gz"):
logger.info('Starting unzip %s', path_input)
path_input_new = path_input[:-3]
with gzip.open(path_input, 'rb') as f_in, open(path_input_new, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
return path_input_new
def post_add_bt_tag(path_input):
const_bt_tag = "⦅mrk_bt⦆"
path_input_new = '%s.raw' % path_input
os.rename(path_input, path_input_new)
with open(path_input_new, 'r') as f_in, open(path_input, 'w') as f_out:
for line in f_in:
f_out.write('%s %s' % (const_bt_tag, line))
def next_filename_version(filename):
regexp = re.compile(r'^(.+)\.v([0-9]+)$')
match = regexp.match(filename)
if match:
filename = match.group(1)
version = int(match.group(2)) + 1
else:
version = 2
return '%s.v%d' % (filename, version)
def is_joint_vocab(tokenization_config):
source = tokenization_config.get('source', {})
target = tokenization_config.get('target', {})
return source.get('vocabulary') == target.get('vocabulary')
|
<gh_stars>1000+
"""shell
pip install autokeras
"""
import os
import numpy as np
import tensorflow as tf
from sklearn.datasets import load_files
import autokeras as ak
"""
## A Simple Example
The first step is to prepare your data. Here we use the [IMDB
dataset](https://keras.io/datasets/#imdb-movie-reviews-sentiment-classification)
as an example.
"""
dataset = tf.keras.utils.get_file(
fname="aclImdb.tar.gz",
origin="http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz",
extract=True,
)
# set path to dataset
IMDB_DATADIR = os.path.join(os.path.dirname(dataset), "aclImdb")
classes = ["pos", "neg"]
train_data = load_files(
os.path.join(IMDB_DATADIR, "train"), shuffle=True, categories=classes
)
test_data = load_files(
os.path.join(IMDB_DATADIR, "test"), shuffle=False, categories=classes
)
x_train = np.array(train_data.data)
y_train = np.array(train_data.target)
x_test = np.array(test_data.data)
y_test = np.array(test_data.target)
print(x_train.shape) # (25000,)
print(y_train.shape) # (25000, 1)
print(x_train[0][:50]) # this film was just brilliant casting
"""
The second step is to run the [TextClassifier](/text_classifier). As a quick
demo, we set epochs to 2. You can also leave the epochs unspecified for an
adaptive number of epochs.
"""
# Initialize the text classifier.
clf = ak.TextClassifier(
overwrite=True, max_trials=1
) # It only tries 1 model as a quick demo.
# Feed the text classifier with training data.
clf.fit(x_train, y_train, epochs=2)
# Predict with the best model.
predicted_y = clf.predict(x_test)
# Evaluate the best model with testing data.
print(clf.evaluate(x_test, y_test))
"""
## Validation Data
By default, AutoKeras use the last 20% of training data as validation data. As
shown in the example below, you can use `validation_split` to specify the
percentage.
"""
clf.fit(
x_train,
y_train,
# Split the training data and use the last 15% as validation data.
validation_split=0.15,
)
"""
You can also use your own validation set instead of splitting it from the
training data with `validation_data`.
"""
split = 5000
x_val = x_train[split:]
y_val = y_train[split:]
x_train = x_train[:split]
y_train = y_train[:split]
clf.fit(
x_train,
y_train,
epochs=2,
# Use your own validation set.
validation_data=(x_val, y_val),
)
"""
## Customized Search Space
For advanced users, you may customize your search space by using
[AutoModel](/auto_model/#automodel-class) instead of
[TextClassifier](/text_classifier). You can configure the
[TextBlock](/block/#textblock-class) for some high-level configurations, e.g.,
`vectorizer` for the type of text vectorization method to use. You can use
'sequence', which uses [TextToInteSequence](/block/#texttointsequence-class) to
convert the words to integers and use [Embedding](/block/#embedding-class) for
embedding the integer sequences, or you can use 'ngram', which uses
[TextToNgramVector](/block/#texttongramvector-class) to vectorize the
sentences. You can also do not specify these arguments, which would leave the
different choices to be tuned automatically. See the following example for
detail.
"""
input_node = ak.TextInput()
output_node = ak.TextBlock(block_type="ngram")(input_node)
output_node = ak.ClassificationHead()(output_node)
clf = ak.AutoModel(
inputs=input_node, outputs=output_node, overwrite=True, max_trials=1
)
clf.fit(x_train, y_train, epochs=2)
"""
The usage of [AutoModel](/auto_model/#automodel-class) is similar to the
[functional API](https://www.tensorflow.org/guide/keras/functional) of Keras.
Basically, you are building a graph, whose edges are blocks and the nodes are
intermediate outputs of blocks. To add an edge from `input_node` to
`output_node` with `output_node = ak.[some_block]([block_args])(input_node)`.
You can even also use more fine grained blocks to customize the search space
even further. See the following example.
"""
input_node = ak.TextInput()
output_node = ak.TextToIntSequence()(input_node)
output_node = ak.Embedding()(output_node)
# Use separable Conv layers in Keras.
output_node = ak.ConvBlock(separable=True)(output_node)
output_node = ak.ClassificationHead()(output_node)
clf = ak.AutoModel(
inputs=input_node, outputs=output_node, overwrite=True, max_trials=1
)
clf.fit(x_train, y_train, epochs=2)
"""
## Data Format
The AutoKeras TextClassifier is quite flexible for the data format.
For the text, the input data should be one-dimensional For the classification
labels, AutoKeras accepts both plain labels, i.e. strings or integers, and
one-hot encoded encoded labels, i.e. vectors of 0s and 1s.
We also support using [tf.data.Dataset](
https://www.tensorflow.org/api_docs/python/tf/data/Dataset?version=stable)
format for the training data.
"""
train_set = tf.data.Dataset.from_tensor_slices(((x_train,), (y_train,))).batch(32)
test_set = tf.data.Dataset.from_tensor_slices(((x_test,), (y_test,))).batch(32)
clf = ak.TextClassifier(overwrite=True, max_trials=2)
# Feed the tensorflow Dataset to the classifier.
clf.fit(train_set, epochs=2)
# Predict with the best model.
predicted_y = clf.predict(test_set)
# Evaluate the best model with testing data.
print(clf.evaluate(test_set))
"""
## Reference
[TextClassifier](/text_classifier),
[AutoModel](/auto_model/#automodel-class),
[TextBlock](/block/#textblock-class),
[TextToInteSequence](/block/#texttointsequence-class),
[Embedding](/block/#embedding-class),
[TextToNgramVector](/block/#texttongramvector-class),
[ConvBlock](/block/#convblock-class),
[TextInput](/node/#textinput-class),
[ClassificationHead](/block/#classificationhead-class).
"""
|
<gh_stars>10-100
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import boto3
import botocore
import os
import logging
from gamekithelpers import ddb
from gamekithelpers.handler_request import get_player_id, get_path_param, log_event
from gamekithelpers.handler_response import response_envelope, return_response
from gamekithelpers.validation import is_valid_primary_identifier
logger = logging.getLogger()
logger.setLevel(logging.INFO)
s3_resource = boto3.resource('s3')
def lambda_handler(event, context):
"""
Delete the player's specified save slot from S3 and DynamoDB.
It's okay to call this Lambda for a non-existent save slot. The Lambda will still return a success.
After a save slot is deleted it no longer counts towards the player's max SLOT_LIMIT.
Parameters:
Request Context:
custom:gk_user_id: str
The player_id of the save slot to delete. This value comes from the Cognito Authorizer that validates the
API Gateway request.
Path Parameters:
slot_name: str
The slot name of the save file to delete.
Limited to 512 characters long, using alphanumeric characters, dashes (-), underscores (_), and periods (.).
This lambda will return an error if a malformed slot name is provided.
Errors:
400 Bad Request - Returned when a malformed 'slot_name' path parameter is provided.
401 Unauthorized - Returned when the 'custom:gk_user_id' parameter is missing from the request context.
403 Forbidden - Returned when the owner AWS account of the bucket does not match the caller account.
"""
log_event(event)
# Get player_id from requestContext:
player_id = get_player_id(event)
if player_id is None:
return response_envelope(status_code=401)
# Get path param inputs:
slot_name = get_path_param(event, 'slot_name')
if not is_valid_primary_identifier(slot_name):
logger.error(f'Malformed slot_name: {slot_name} provided for player_id: {player_id}')
return response_envelope(status_code=400)
# Delete the save:
try:
delete_save_slot(player_id, slot_name)
# Construct response object:
return return_response(204, None)
except botocore.exceptions.ClientError as error:
if error.response['Error']['Code'] == 'AccessDenied':
# Construct forbidden response object:
return response_envelope(status_code=403)
else:
# Maintain previous behavior until more error codes are implemented
raise error
def delete_save_slot(player_id: str, slot_name: str) -> None:
"""Delete the save slot object from S3 and the metadata from DynamoDB."""
delete_slot_object(player_id, slot_name)
delete_slot_metadata(player_id, slot_name)
def delete_slot_object(player_id: str, slot_name: str) -> None:
"""Delete the save slot object from S3."""
bucket_name = os.environ.get('GAMESAVES_BUCKET_NAME')
key = f"{player_id}/{slot_name}"
s3_object = s3_resource.Object(bucket_name, key)
s3_object.delete(
ExpectedBucketOwner=os.environ.get('AWS_ACCOUNT_ID')
)
def delete_slot_metadata(player_id: str, slot_name: str) -> None:
"""Delete the slot metadata from DynamoDB."""
gamesaves_table = ddb.get_table(table_name=os.environ.get('GAMESAVES_TABLE_NAME'))
gamesaves_table.delete_item(
Key={
'player_id': player_id,
'slot_name': slot_name,
},
ReturnValues='NONE',
ReturnConsumedCapacity='NONE',
)
|
<filename>backend/fullBack.py
import networkx as nx
import matplotlib.pyplot as plt
import random
from itertools import combinations
"""
all these added below
1. cycle
2. star
3. tree
4. path
5. complete
6. bipartite
7. hypercubes
8. petersen
9. custom
10.temporal
1. bfs
2. dfs
3. dijkstra
4. cycle det
5. foremost
need adding/doing: temporal-done
!!!!!!!!!!temporal!!!!!!!!! -done
"""
def cycle(numNodes):
#this clears the canvas to allow a new graph to be drawn
plt.clf()
#initialise networkx graph object
#G= nx.Graph()
G = nx.cycle_graph(numNodes)
## #if the number of nodes is selected is 1, add only one node
## if numNodes == 1:
## G.add_node(0)
##
## #if the number of nodes is selected is >1, add all nodes up to the value
## #of numNodes
## elif numNodes > 1:
## G.add_node(0)
##
## #adding edges and nodes at the same time
## for i in range(0,numNodes-1):
## G.add_node(i)
## G.add_edge(i,i+1)
##
## #add edge from starting node to ending node
## G.add_edge(0,numNodes-1)
#gathers all the nodes and edges created and draws them on a networkx canvas
#with the labels starting from 1 to numNodes and all the nodes coloured
#white
#G.add_nodes_from(G.nodes(), colour='never coloured')
positions = nx.spring_layout(G)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
#matplotlib function that saves the graph creates as a png
plt.savefig((str(numNodes)+"cycle.png"), dpi=300)
#convert graph created into a list of lists, where each index represents
#the node, and the list at that index contains the nodes it is connected to
#by an edge
adjlist=[]
x = nx.convert.to_dict_of_lists(G)
for i in x.values():
adjlist.append(i)
#adjlist is returned in the case of the user wanting to see a search alg
#implemented on the graph, the same graph can easily be used, the graph
#itself is returned as well as thet positions of the nodes to aid with
#consistency
return adjlist,G,positions
def star(numNodes):
plt.clf()
G= nx.Graph()
if numNodes == 1:
G.add_node(0)
#if the number of nodes is >1, we are able to create this star effect
#where the first node is joined by an edge to all other nodes and all
#other nodes are joined by an edge only to the central (first) node
elif numNodes > 1:
G.add_node(0)
for i in range(1,numNodes):
G.add_node(i)
G.add_edge(0,i)
#draw graph wiith white nodes and at generated positions with
#numbered labels. save graph as png
G.add_nodes_from(G.nodes(), colour='never coloured')
positions = nx.spring_layout(G)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
plt.savefig((str(numNodes)+"star.png"), dpi=300)
#convert graph to a list of vertices joined by an edge at that index
adjlist=[]
x = nx.convert.to_dict_of_lists(G)
for i in x.values():
adjlist.append(i)
#return the above generated list with the graph and the node positions
return adjlist,G,positions
def tree(numNodes):
for trying in range(10):
plt.clf()
G= nx.Graph()
if numNodes == 1:
G.add_node(0)
break
elif numNodes > 1:
G.add_node(0)
for i in range(1,numNodes):
G.add_node(i)
prob = random.uniform(0,1)
print(prob)
if prob>0.5:
randy = random.randint(0,i-1)
G.add_edge(randy,i)
else:
G.add_edge(i,i-1)
if numNodes <= 3:
break
no3 = False
save2 = []
deg3=[]
ones = []
for i in G.nodes():#range(0,numNodes):
x = [n for n in G.neighbors(i)]
print(x,'nodes',i)
if len(x)==3:
no3=True
deg3.append(i)
break
if len(x)==2:
save2.append(i)
if len(x)==1:
ones.append(i)
## print('/////')
## print(save2)
if no3==True:
break
## print('/////')
## plt.clf()
## G= nx.Graph()
## if numNodes == 1:
## G.add_node(0)
## elif numNodes > 1:
## G.add_node(0)
## for i in range(1,numNodes):
## G.add_node(i)
## prob = random.uniform(0,1)
## print(prob)
## if prob>0.5:
## randy = random.randint(0,i-1)
## G.add_edge(randy,i)
## else:
## G.add_edge(i,i-1)
print(G.edges())
G.add_nodes_from(G.nodes(), colour='never coloured')
positions = nx.spring_layout(G)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
plt.savefig((str(numNodes)+"tree.png"), dpi=300)
adjlist=[]
xx = nx.convert.to_dict_of_lists(G)
for i in xx.values():
adjlist.append(i)
return adjlist,G,positions
def path(numNodes):
plt.clf()
G= nx.Graph()
if numNodes == 1:
G.add_node(0)
elif numNodes > 1:
G.add_node(0)
for i in range(0,numNodes-1):
G.add_node(i)
G.add_edge(i,i+1)
G.add_nodes_from(G.nodes(), colour='never coloured')
positions = nx.spring_layout(G)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
plt.savefig((str(numNodes)+"path.png"), dpi=300)
adjlist=[]
x = nx.convert.to_dict_of_lists(G)
for i in x.values():
adjlist.append(i)
return adjlist,G,positions
def complete(numNodes):
plt.clf()
G= nx.Graph()
if numNodes == 1:
G.add_node(0)
elif numNodes > 1:
G.add_node(0)
for i in range(1,numNodes):
G.add_node(i)
for j in range(0,i):
G.add_edge(j,i)
G.add_nodes_from(G.nodes(), colour='never coloured')
positions = nx.spring_layout(G)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
plt.savefig((str(numNodes)+"complete.png"), dpi=300)
adjlist=[]
x = nx.convert.to_dict_of_lists(G)
for i in x.values():
adjlist.append(i)
return adjlist,G,positions
def bipartite(numNodes):
plt.clf()
odds=[]
evens=[]
colours=[]
B = nx.Graph()
for i in range(0,numNodes):
if ((i%2)==0):
evens.append(i)
B.add_node(i)
colours.append('red')
else:
odds.append(i)
B.add_node(i)
colours.append('blue')
for i in range(0,numNodes-1):
B.add_edge(i,i+1)
#just adds a few more edges on
if numNodes>3:
for j in range(0,numNodes-1):
x=random.uniform(0, 1)
if x>0.6:
y=random.randint(0, len(evens)-2)
z=random.randint(0, len(odds)-2)
if z!=y:
B.add_edge(odds[z],evens[y])
lhs = nx.bipartite.sets(B)[0]
positions = nx.bipartite_layout(B, lhs)
nx.draw_networkx_labels(B, pos=positions,labels={n: n+1 for n in B})
nx.draw(B, pos=positions,node_color=colours)
plt.savefig((str(numNodes)+"bipartite.png"), dpi=300)
adjlist=[]
x = nx.convert.to_dict_of_lists(B)
for i in x.values():
adjlist.append(i)
return adjlist,B,positions
def hypercube(n):
plt.clf()
if n==1:
x= nx.Graph()
x.add_node(0)
elif n==8:
x= nx.Graph()
for i in range(0,n):
x.add_node(i)
x.add_edge(0,1)
x.add_edge(0,2)
x.add_edge(0,3)
x.add_edge(1,4)
x.add_edge(1,5)
x.add_edge(2,4)
x.add_edge(2,6)
x.add_edge(3,5)
x.add_edge(3,6)
x.add_edge(4,7)
x.add_edge(5,7)
x.add_edge(6,7)
elif n==4:
x= nx.Graph()
for i in range(0,n):
x.add_node(i)
x.add_edge(0,1)
x.add_edge(1,2)
x.add_edge(2,3)
x.add_edge(0,3)
elif n==2:
x= nx.Graph()
for i in range(0,n):
print(i)
x.add_node(i)
x.add_edge(0,1)
positions = nx.spring_layout(x, scale=0.8)
nx.draw(x, pos=positions,node_color='white', width=1, edge_color="black", style="solid")
nx.draw_networkx_labels(x, pos=positions,labels={u: u+1 for u in x})
#fits everything in
plt.margins(0.15)
plt.savefig((str(n)+"hypercube.png"), dpi=800)
adjlist=[]
h = nx.convert.to_dict_of_lists(x)
for i in h.values():
adjlist.append(i)
return adjlist,x,positions
def petersen():
plt.clf()
Graph = nx.petersen_graph()
nx.draw_shell(Graph, nlist=[range(5, 10), range(5)], font_weight='bold',node_color='white')
positions = nx.shell_layout(Graph, nlist=[range(5, 10), range(5)])
nx.draw_networkx_labels(Graph, pos=positions,labels={n: n+1 for n in Graph})
plt.savefig(("petersen.png"), dpi=800)
adjlist=[]
x = nx.convert.to_dict_of_lists(Graph)
for i in x.values():
adjlist.append(i)
return adjlist,Graph,positions
#custom([[0,0,1],[0,0,1],[1,1,0]])
def custom(adj):
plt.clf()
G= nx.Graph()
for i in range(0,len(adj)):
G.add_node(i)
for i in range(0,len(adj)):
for j in range(0,len(adj[i])):
if(adj[i][j]==1):
G.add_edge(i,j)
G.add_nodes_from(G.nodes(), colour='never coloured')
positions = nx.spring_layout(G)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
plt.savefig((str(len(adj))+"custom.png"), dpi=300)
adjlist=[]
x = nx.convert.to_dict_of_lists(G)
for i in x.values():
adjlist.append(i)
return adjlist,G,positions
def cycleDetection(adjlist,G,positions):
plt.clf()
x=[]
try:
x=list(nx.find_cycle(G, orientation="original"))
except:
pass
G.add_nodes_from(G.nodes(), colour='never coloured')
for e in G.edges():
G[e[0]][e[1]]['color'] = 'black'
for i in x:
if(((e[0]==i[0])and(e[1]==i[1]))or((e[1]==i[0])and(e[0]==i[1]))):
G[e[0]][e[1]]['color'] = 'red'
node_colour_list=['white']*len(adjlist)
order=0
edge_colour_list = [G[e[0]][e[1]]['color'] for e in G.edges()]
nx.draw(G, pos=positions,node_color=node_colour_list,edge_color=edge_colour_list)
#nx.draw_networkx_labels(G, pos=positions)
try:
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
except:
nx.draw_networkx_labels(G, pos=positions)
plt.savefig((str(order)+"cycledetection.png"), dpi=300)
#colour nodes that are in the cycle
order+=1
for e in G.nodes():
coloured=False
for i in x:
if((e==i[0])):
node_colour_list[e]='pink'
coloured=True
break
if(coloured==False):
node_colour_list[e]='white'
else:
edge_colour_list = [G[e[0]][e[1]]['color'] for e in G.edges()]
nx.draw(G, pos=positions,node_color=node_colour_list,edge_color=edge_colour_list)
try:
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
except:
nx.draw_networkx_labels(G, pos=positions)
plt.savefig((str(order)+"cycledetection.png"), dpi=300)
order+=1
def bfs(adjlist,G,positions):
#visited list- check if bfs already seen
visited=[0]*len(adjlist)
queue=[]
tour=[0]
r=0
queue.extend(adjlist[0])#=adjlist[0]
#keeps track of which index of colourList we are allowed to colour the node in
colourCount=0
colourList = ['#FFB6C1','#836FFF','#7FFFD4','#7D9EC0','#CAE1FF','#458B00','#FFFF00','#FFA07A','#F5DEB3','#FF3030','#CDC9C9','#EE7AE9','#A0522D','#00EE00','#FF9912','#E3CF57','#B3EE3A','#FF3E96','#00F5FF','#BF3EFF','#4876FF']
#colourList=['orange','blue','yellow','red','purple','cyan','pink','green','grey','indigo']
#initialise an all white list for the nodes that have not yet been coloured
#will get coloured as we go on
vColour=['#ffffff']*len(adjlist)
#draws first stage and saves (non coloured graph)
nx.draw(G, pos=positions,node_color=vColour)
#nx.draw_networkx_labels(G, pos=positions)
order=0
plt.savefig((str(order)+"bfs.png"), dpi=300)
#adds orange to first node 0 (which is node 1 on networkx graph)
vColour[0]=colourList[colourCount]
colourCount+=1
#draws first COLOURED stage and saves
order=1
nx.draw(G, pos=positions,node_color=vColour)
#nx.draw_networkx_labels(G, pos=positions)
plt.savefig((str(order)+"bfs.png"), dpi=300)
order=2
while(len(queue)!=0):
a=len(queue)
secondq=[]
for i in queue:
secondq.append(i)
visited[r]=1
#r keeps track of the first node in queue
r=queue[0]
tour.append(r)
#everything thats in the queue at this moment in time must have come from the same node (if not already coloured)
#therefore can be coloured the next colour in the list initialised at the top
#save new drawn graph at each coloured node stage
for i in queue:
if vColour[i]=='#ffffff':
vColour[i]=colourList[colourCount]
nx.draw(G, pos=positions,node_color=vColour)
plt.savefig((str(order)+"bfs.png"), dpi=300)
order+=1
colourCount+=1
queue.remove(r)
#add all unvisited nodes that are adjacent to the queue to repeat
for x in secondq:
for i in range(0,len(adjlist[x])):#and (x not in tour)
if(visited[adjlist[x][i]]==0 and (adjlist[x][i] not in queue)):
queue.append(adjlist[x][i])
def dfs(adjlist,G,positions):
#keeps track of which index of colourList we are allowed to colour the node in
colourCount=0
colourList=['orange','blue','yellow','red','purple','grey','pink','green','grey']
#initialise an all white list for the nodes that have not yet been coloured
#will get coloured as we go on
vColour=['#ffffff']*len(adjlist)
#draws first stage and saves (non coloured graph)
nx.draw(G, pos=positions,node_color=vColour)
#nx.draw_networkx_labels(G, pos=positions)
order=0
plt.savefig((str(order)+"dfs.png"), dpi=300)
#adds orange to first node 0 (which is node 1 on networkx graph)
vColour[0]=colourList[colourCount]
order=1
visited = [False] * len(adjlist)
s=0
stack = []
stack.append(s)
while (len(stack)):
# Pop a vertex from stack and print it
s = stack[-1]
stack.pop()
# stack may contain same vertex twice, need to print the popped item only
# if not visited.
if (not visited[s]):
vColour[s]=colourList[colourCount]
nx.draw(G, pos=positions,node_color=vColour)
plt.savefig((str(order)+"dfs.png"), dpi=300)
order+=1
visited[s] = True
# Get all adjacent vertices of the popped vertex s
# If a adjacent has not been visited, then push it
# to the stack.
for node in adjlist[s]:
if (not visited[node]):
stack.append(node)
#used for dijkstra
def backtrace(parent, start, end):
path = [end]
while path[-1] != start:
path.append(parent[path[-1]])
path.reverse()
return path
def dijkstra(adjlist,graph,positions,source,target):
source=source-1
target=target-1
queue = []
visited = {}
distance = {}
shortest_distance = {}
parent = {}
colours=['white']*len(adjlist)
for node in range(len(graph)):
distance[node] = None
visited[node] = False
parent[node] = None
shortest_distance[node] = float("inf")
queue.append(source)
distance[source] = 0
while len(queue) != 0:
current = queue.pop(0)
visited[current] = True
if current == target:
shortpath = (backtrace(parent, source, target))
for neighbor in graph[current]:
if visited[neighbor] == False:
distance[neighbor] = distance[current] + 1
if distance[neighbor] < shortest_distance[neighbor]:
shortest_distance[neighbor] = distance[neighbor]
parent[neighbor] = current
queue.append(neighbor)
nx.draw(graph,pos=positions,node_color='white', width=1, style="solid" )
try:
nx.draw_networkx_labels(graph, pos=positions,labels={n: n+1 for n in graph})
except:
nx.draw_networkx_labels(graph, pos=positions)
order=0
plt.savefig((str(order)+"dijkstra.png"), dpi=300)
for i in shortpath:
colours[i]='orange'
order+=1
nx.draw(graph, pos=positions,node_color=colours)
try:
nx.draw_networkx_labels(graph, pos=positions,labels={n: n+1 for n in graph})
except:
nx.draw_networkx_labels(graph, pos=positions)
plt.savefig((str(order)+"dijkstra.png"), dpi=300)
def temporal(num,max_life):
## if num <1 or num>10:
## print("please ennter number of nodes between 1 and 10")
## exit()
vertices=[]
for i in range(num):
vertices.append(i)
## if max_life < (2*num):
## print("please enter max_life which is atleast twice the number of nodes")
## exit()
## if max_life > 20:
## print("please enter max_life which is atleast twice the number of nodes and not more than 2")
## exit()
edges_not_used= list(combinations((vertices),2)) #getting all possible combinations of length 2
# print("combinations possible",edges_not_used)
plt.clf() #used to clear the current figure
G= nx.Graph()
order=0
for i in range(0,num):
G.add_node(i)
G.add_nodes_from(G.nodes(), colour='never coloured')
positions = nx.spring_layout(G,scale=0.2)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
plt.savefig((str(order)+"temporal.png"), dpi=300)
order+=1
main=[]
for j in range(0,max_life):
#print("j",j)
lst1=[]
G.remove_edges_from(list(G.edges()))
for k in range(0,num):
#print("k",k)
for q in range(0,num):
#print("q",q)
probability = random.uniform(0, 1)
if(k!=q):#edges created with random probability
if(probability<(1/(num))): #create random edges at diff times
if((k,q) in edges_not_used) or ((q,k) in edges_not_used):
vertices_traversed= (k,q)
lst1.append(vertices_traversed)
G.add_edge(k,q)
if(k,q) in edges_not_used:
edges_not_used.remove((k,q))
if(q,k) in edges_not_used:
edges_not_used.remove((q,k))
plt.clf()
main.append(lst1)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
plt.savefig((str(order)+"temporal.png"), dpi=300)
order+=1
return G.edges
#temporal(no_of_nodes, max_life)
f =temporal(10,20)
#no_of_nodes(n): 1 to 10
#max_life: >= 2n and max 20
def temporal_foremost(num,max_life,src):
src=src-1
## if num <1 or num>10:
## print("please ennter number of nodes between 1 and 10")
## exit()
vertices=[]
for i in range(num):
vertices.append(i)
## if check not in vertices:
## print("please ennter a source vertex between 1 and your max no. of nodes")
## exit()
##
## if max_life < (2*num):
## print("please enter max_life which is atleast twice the number of nodes")
## exit()
##
## if max_life > 20:
## print("please enter max_life which is atleast twice the number of nodes and not more than 2")
## exit()
edges_not_used= list(combinations((vertices),2)) #getting all possible combinations of length 2
#print("combinations possible",edges_not_used)
plt.clf() #used to clear the current figure
G= nx.Graph()
order=0
for i in range(0,num):
G.add_node(i)
G.add_nodes_from(G.nodes(), colour='never coloured')
positions = nx.spring_layout(G,scale=0.2)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
plt.savefig((str(order)+"temporal.png"), dpi=300)
order+=1
main=[]
for j in range(0,max_life):
lst1=[]
G.remove_edges_from(list(G.edges()))
for k in range(0,num):
for q in range(0,num):
probability = random.uniform(0, 1)
if(k!=q):#edges created with random probability
if(probability<(1/(num))): #create random edges at diff times
if((k,q) in edges_not_used) or ((q,k) in edges_not_used):
if j==0:
k=src
vertices_traversed= (k,q)
lst1.append(vertices_traversed)
G.add_edge(k,q)
if(k,q) in edges_not_used:
edges_not_used.remove((k,q))
if(q,k) in edges_not_used:
edges_not_used.remove((q,k))
plt.clf()
main.append(lst1)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels={n: n+1 for n in G})
plt.savefig((str(order)+"temporal.png"), dpi=300)
order+=1
#If dest and source vertex found, we apply algorithm to find shortest path
S=[] #creating a list called 'S' of (u,v) and (v,u) edges since our graph is undirectes
for i in range(len(main)):
new=[]
for each in main[i]:
a=each[0]
b=each[1]
one= (a,b)
swap=(b,a)
new.append(one)
new.append(swap)
S.append(new)
#print("S",S)
null='-'
vertices_traversed=[src]
parents={}
arrival_time={}
parents[src]= null
arrival_time[src]= 0
#Part of the algorithm
#finding time at which edges appear and adding it to the dict arrival_time
#setting parents of all vertices to null
for i in range(len(S)):
for each in S[i]:
if each[0] not in vertices_traversed:
vertices_traversed.append(each[0])
arrival_time[each[0]]= i+1
parents[each[0]]= null
if each[1] not in vertices_traversed:
vertices_traversed.append(each[1])
arrival_time[each[1]]= i+1
parents[each[1]]= null
#print("arrival_time",arrival_time)
#print("parents",parents)
#dst here is the vertex that appears latest
dst=vertices_traversed[-1]
R= [src]
#print("R",R)
#print("dst",dst)
for l in range(len(S)):
for each in S[l]:
a=each[0]
b=each[1]
if (a in R and b not in R): #main algorithm of foremost jounrey
if arrival_time[a] < l+1:
parents[b]= a
arrival_time[b]= l+1
R.append(b)
elif (b in R and a not in R): #i have also taking reverse since our graph is undirected
if arrival_time[b] < l+1:
parents[a]= b
arrival_time[a]= l+1
R.append(a)
#print("arrival_time",arrival_time)
#print("parents",parents)
#print("R222",R)
traverse=[] #to add all edges in the order they will be traversed
for i in range(max_life):
for each in arrival_time:
if (arrival_time[each]==i):
lst2=(parents[each],each)
traverse.append(lst2)
del traverse[0]
#print("traverse",traverse)
final=0 #to calculage total time taken
if len(R)!= len(vertices):
print("Path not found, you can try again by increasing max_life")
for i in vertices:
final+= arrival_time[i]
#print("final",final)
G.remove_edges_from(list(G.edges())) #to label edges with time at which they appear
for each in traverse:
G.add_edge(each[0],each[1])
G[each[0]][each[1]]['time'] = arrival_time[each[1]]
labels={} #to label nodes, source node also labelled
for n in G.nodes:
#print(n)
if n==src:
labels[n]= str(n+1) + '$: SOURCE$'
else:
labels[n]= n+1
plt.clf()#Plotting edges from the list traversed
main.append(lst1)
nx.draw(G, pos=positions,node_color='white')
nx.draw_networkx_labels(G, pos=positions,labels=labels)
b=dict(((u, v), d) for u, v, d in G.edges(data=True))
nx.draw_networkx_edge_labels(G,pos=positions, edge_labels=b ,font_color='red')
final=str(max_life+1)
name_of_final= final+ "temporal.png"
plt.savefig((name_of_final), dpi=250)
return G.edges
#temporal_foremost(no_of_nodes, max_life,source_node)
f =temporal_foremost(10,20,1)
#no_of_nodes(n): 1 to 10
#max_life: >= 2n and max 20
#enter source_vertex
|
from __future__ import annotations
from babi.screen import VERSION_STR
from testing.runner import and_exit
def test_window_height_2(run, tmpdir):
# 2 tall:
# - header is hidden, otherwise behaviour is normal
f = tmpdir.join("f.txt")
f.write("hello world")
with run(str(f)) as h, and_exit(h):
h.await_text("hello world")
with h.resize(width=80, height=2):
h.await_text_missing(VERSION_STR)
h.assert_full_contents("hello world\n\n")
h.press("^J")
h.await_text("unknown key")
h.await_text(VERSION_STR)
def test_window_height_1(run, tmpdir):
# 1 tall:
# - only file contents as body
# - status takes precedence over body, but cleared after single action
f = tmpdir.join("f.txt")
f.write("hello world")
with run(str(f)) as h, and_exit(h):
h.await_text("hello world")
with h.resize(width=80, height=1):
h.await_text_missing(VERSION_STR)
h.assert_full_contents("hello world\n")
h.press("^J")
h.await_text("unknown key")
h.press("Right")
h.await_text_missing("unknown key")
h.press("Down")
def test_reacts_to_resize(run):
with run() as h, and_exit(h):
h.await_text("<<new file>>")
with h.resize(width=10, height=20):
h.await_text_missing("<<new file>>")
h.await_text("<<new file>>")
def test_resize_scrolls_up(run, ten_lines):
with run(str(ten_lines)) as h, and_exit(h):
h.await_text("line_9")
for _ in range(7):
h.press("Down")
h.await_cursor_position(x=0, y=8)
# a resize to a height of 10 should not scroll
with h.resize(width=80, height=10):
h.await_text_missing("line_8")
h.await_cursor_position(x=0, y=8)
h.await_text("line_8")
# but a resize to smaller should
with h.resize(width=80, height=9):
h.await_text_missing("line_0")
h.await_cursor_position(x=0, y=4)
# make sure we're still on the same line
h.assert_cursor_line_equals("line_7")
def test_resize_scroll_does_not_go_negative(run, ten_lines):
with run(str(ten_lines)) as h, and_exit(h):
for _ in range(5):
h.press("Down")
h.await_cursor_position(x=0, y=6)
with h.resize(width=80, height=7):
h.await_text_missing("line_9")
h.await_text("line_9")
for _ in range(3):
h.press("Up")
h.assert_screen_line_equals(1, "line_0")
def test_horizontal_scrolling(run, tmpdir):
f = tmpdir.join("f")
lots_of_text = "".join("".join(str(i) * 10 for i in range(10)) for _ in range(10))
f.write(f"line1\n{lots_of_text}\n")
with run(str(f)) as h, and_exit(h):
h.await_text("6777777777»")
h.press("Down")
for _ in range(78):
h.press("Right")
h.await_text("6777777777»")
h.press("Right")
h.await_text("«77777778")
h.await_text("344444444445»")
h.await_cursor_position(x=7, y=2)
for _ in range(71):
h.press("Right")
h.await_text("«77777778")
h.await_text("344444444445»")
h.press("Right")
h.await_text("«444445")
h.await_text("1222»")
def test_horizontal_scrolling_exact_width(run, tmpdir):
f = tmpdir.join("f")
f.write("0" * 80)
with run(str(f)) as h, and_exit(h):
h.await_text("000")
for _ in range(78):
h.press("Right")
h.await_text_missing("»")
h.await_cursor_position(x=78, y=1)
h.press("Right")
h.await_text("«0000000")
h.await_cursor_position(x=7, y=1)
def test_horizontal_scrolling_narrow_window(run, tmpdir):
f = tmpdir.join("f")
f.write("".join(str(i) * 10 for i in range(10)))
with run(str(f)) as h, and_exit(h):
with h.resize(width=5, height=24):
h.await_text("0000»")
for _ in range(3):
h.press("Right")
h.await_text("0000»")
h.press("Right")
h.await_cursor_position(x=3, y=1)
h.await_text("«000»")
for _ in range(6):
h.press("Right")
h.await_text("«001»")
def test_window_width_1(run, tmpdir):
f = tmpdir.join("f")
f.write("hello")
with run(str(f)) as h, and_exit(h):
with h.resize(width=1, height=24):
h.await_text("»")
for _ in range(3):
h.press("Right")
h.await_text("hello")
h.await_cursor_position(x=3, y=1)
def test_resize_while_cursor_at_bottom(run, tmpdir):
f = tmpdir.join("f")
f.write("x\n" * 35)
with run(str(f), height=40) as h, and_exit(h):
h.press("^End")
h.await_cursor_position(x=0, y=36)
with h.resize(width=80, height=5):
h.await_cursor_position(x=0, y=2)
|
<reponame>atzberg/gmls-nets
"""
.. image:: overview.png
PyTorch implementation of GMLS-Nets. Module for neural networks for
processing scattered data sets using Generalized Moving Least Squares (GMLS).
If you find these codes or methods helpful for your project, please cite:
| @article{trask_patel_gross_atzberger_GMLS_Nets_2019,
| title={GMLS-Nets: A framework for learning from unstructured data},
| author={<NAME>, <NAME>, <NAME>, <NAME>},
| journal={arXiv:1909.05371},
| month={September},
| year={2019},
| url={https://arxiv.org/abs/1909.05371}
| }
"""
# Authors: <NAME> and <NAME>
# Website: http://atzberger.org/
import torch;
import torch.nn as nn;
import torchvision;
import torchvision.transforms as transforms;
import numpy as np;
import scipy.spatial as spatial # used for finding neighbors within distance $\delta$
from collections import OrderedDict;
import pickle as p;
import pdb;
import time;
# ====================================
# Custom Functions
# ====================================
class MapToPoly_Function(torch.autograd.Function):
r"""
This layer processes a collection of scattered data points consisting of a collection
of values :math:`u_j` at points :math:`x_j`. For a collection of target points
:math:`x_i`, local least-squares problems are solved for obtaining a local representation
of the data over a polynomial space. The layer outputs a collection of polynomial
coefficients :math:`c(x_i)` at each point and the collection of target points :math:`x_i`.
"""
@staticmethod
def weight_one_minus_r(z1,z2,params):
r"""Weight function :math:`\omega(x_j,x_i) = \left(1 - r/\epsilon\right)^{\bar{p}}_+.`
Args:
z1 (Tensor): The first point. Tensor of shape [1,num_dims].
z2 (Tensor): The second point. Tensor of shape [1,num_dims].
params (dict): The parameters are 'p' for decay power and 'epsilon' for support size.
Returns:
Tensor: The weight evaluation over points.
"""
epsilon = params['epsilon']; p = params['p'];
r = torch.sqrt(torch.sum(torch.pow(z1 - z2,2),1));
diff = torch.clamp(1 - (r/epsilon),min=0);
eval = torch.pow(diff,p);
return eval;
@staticmethod
def get_num_polys(porder,num_dim=None):
r""" Returns the number of polynomials of given porder. """
if num_dim == 1:
num_polys = porder + 1;
elif num_dim == 2:
num_polys = int((porder + 2)*(porder + 1)/2);
elif num_dim == 3:
num_polys = 0;
for beta in range(0,porder + 1):
num_polys += int((porder - beta + 2)*(porder - beta + 1)/2);
else:
raise Exception("Number of dimensions not implemented currently. \n num_dim = %d."%num_dim);
return num_polys;
@staticmethod
def eval_poly(pts_x,pts_x2_i0,c_star_i0,porder,flag_verbose):
r""" Evaluates the polynomials locally around a target point xi given coefficients c. """
# Evaluates the polynomial locally (this helps to assess the current fit).
# Implemented for 1D, 2D, and 3D.
#
# 2D:
# Computes Taylor Polynomials over x and y.
# T_{k1,k2}(x1,x2) = (1.0/(k1 + k2)!)*(x1 - x01)^{k1}*(x2 - x02)^{k2}.
# of terms is N = (porder + 1)*(porder + 2)/2.
#
# WARNING: Note the role of factorials and orthogonality here. The Taylor
# expansion/polynomial formulation is not ideal and can give ill-conditioning.
# It would be better to use orthogonal polynomials or other bases.
#
num_dim = pts_x.shape[1];
if num_dim == 1:
II = 0;
alpha_factorial = 1.0;
eval_p = torch.zeros(pts_x.shape[0],device=c_star_i0.device);
for alpha in np.arange(0,porder + 1):
if alpha >= 2:
alpha_factorial *= alpha;
if flag_verbose > 1: print("alpha = " + str(alpha)); print("k = " + str(k));
# for now, (x - x_*)^k, but ideally use orthogonal polynomials
base_poly = torch.pow(pts_x[:,0] - pts_x2_i0[0],alpha);
base_poly = base_poly/alpha_factorial;
eval_p += c_star_i0[II]*base_poly;
II += 1;
elif num_dim == 2:
II = 0;
alpha_factorial = 1.0;
eval_p = torch.zeros(pts_x.shape[0],device=c_star_i0.device);
for alpha in np.arange(0,porder + 1):
if alpha >= 2:
alpha_factorial *= alpha;
for k in np.arange(0,alpha + 1):
if flag_verbose > 1: print("alpha = " + str(alpha)); print("k = " + str(k));
# for now, (x - x_*)^k, but ideally use orthogonal polynomials
base_poly = torch.pow(pts_x[:,0] - pts_x2_i0[0],alpha - k);
# for now, (x - x_*)^k, but ideally use orthogonal polynomials
base_poly = base_poly*torch.pow(pts_x[:,1] - pts_x2_i0[1],k);
base_poly = base_poly/alpha_factorial;
eval_p += c_star_i0[II]*base_poly;
II += 1;
elif num_dim == 3: # caution, below gives initial results, but should be more fully validated
II = 0;
alpha_factorial = 1.0;
eval_p = torch.zeros(pts_x.shape[0],device=c_star_i0.device);
for beta in np.arange(0,porder + 1):
base_poly = torch.pow(pts_x[:,2] - pts_x2_i0[2],beta);
for alpha in np.arange(0,porder - beta + 1):
if alpha >= 2:
alpha_factorial *= alpha;
for k in np.arange(0,alpha + 1):
if flag_verbose > 1: print("alpha = " + str(alpha)); print("k = " + str(k));
# for now, (x - x_*)^k, but ideally use orthogonal polynomials
base_poly = base_poly*torch.pow(pts_x[:,0] - pts_x2_i0[0],alpha - k);
base_poly = base_poly*torch.pow(pts_x[:,1] - pts_x2_i0[1],k);
base_poly = base_poly/alpha_factorial;
eval_p += c_star_i0[II]*base_poly;
II += 1;
else:
raise Exception("Number of dimensions not implemented currently. \n num_dim = %d."%num_dim);
return eval_p;
@staticmethod
def generate_mapping(weight_func,weight_func_params,
porder,epsilon,
pts_x1,pts_x2,
tree_points=None,device=None,
flag_verbose=0):
r""" Generates for caching the data for the mapping from field values (uj,xj) :math:`\rightarrow` (ci,xi).
This help optimize codes and speed up later calculations that are done repeatedly."""
if device is None:
device = torch.device('cpu');
map_data = {};
num_dim = pts_x1.shape[1];
if pts_x2 is None:
pts_x2 = pts_x1;
pts_x1 = pts_x1.to(device);
pts_x2 = pts_x2.to(device);
pts_x1_numpy = None; pts_x2_numpy = None;
if tree_points is None: # build kd-tree of points for neighbor listing
if pts_x1_numpy is None: pts_x1_numpy = pts_x1.cpu().numpy();
tree_points = spatial.cKDTree(pts_x1_numpy);
# Maps from u(x_j) on $x_j \in \mathcal{S}^1$ to a
# polynomial representations in overlapping regions $\Omega_i$ at locations
# around points $x_i \in \mathcal{S}^2$.
# These two sample sets need not be the same allowing mappings between point locations.
# Computes polynomials over x and y.
# Number of terms in 2D is num_polys = (porder + 1)*(porder + 2)/2.
num_pts1 = pts_x1.shape[0]; num_pts2 = pts_x2.shape[0];
num_polys = MapToPoly_Function.get_num_polys(porder,num_dim);
if flag_verbose > 0:
print("num_polys = " + str(num_polys));
M = torch.zeros((num_pts2,num_polys,num_polys),device=device); # assemble matrix at each grid-point
M_inv = torch.zeros((num_pts2,num_polys,num_polys),device=device); # assemble matrix at each grid-point
#svd_U = torch.zeros((num_pts2,num_polys,num_polys)); # assemble matrix at each grid-point
#svd_S = torch.zeros((num_pts2,num_polys,num_polys)); # assemble matrix at each grid-point
#svd_V = torch.zeros((num_pts2,num_polys,num_polys)); # assemble matrix at each grid-point
vec_rij = torch.zeros((num_pts2,num_polys,num_pts1),device=device); # @optimize: ideally should be sparse matrix.
# build up the batch of linear systems for each target point
for i in np.arange(0,num_pts2): # loop over the points $x_i$
if (flag_verbose > 0) & (i % 100 == 0): print("i = " + str(i) + " : num_pts2 = " + str(num_pts2));
if pts_x2_numpy is None: pts_x2_numpy = pts_x2.cpu().numpy();
indices_xj_i = tree_points.query_ball_point(pts_x2_numpy[i,:], epsilon); # find all points with distance
# less than epsilon from xi.
for j in indices_xj_i: # @optimize later to use only local points, and where weights are non-zero.
if flag_verbose > 1: print("j = " + str(j));
vec_p_j = torch.zeros(num_polys,device=device);
w_ij = weight_func(pts_x1[j,:].unsqueeze(0), pts_x2[i,:].unsqueeze(0), weight_func_params); # can optimize for sub-lists outer-product
# Computes Taylor Polynomials over x,y,z.
#
# 2D Case:
# T_{k1,k2}(x1,x2) = (1.0/(k1 + k2)!)*(x1 - x01)^{k1}*(x2 - x02)^{k2}.
# number of terms is N = (porder + 1)*(porder + 2)/2.
# computes polynomials over x and y.
#
# WARNING: The monomial basis is non-ideal and can lead to ill-conditioned linear algebra.
# This ultimately should be generalized in the future to other bases, ideally orthogonal,
# which would help both with efficiency and conditioning of the linear algebra.
#
if num_dim == 1:
# number of terms is N = porder + 1.
II = 0;
for alpha in np.arange(0,porder + 1):
if flag_verbose > 1: print("alpha = " + str(alpha)); print("k = " + str(k));
# for now, (x - x_*)^k, but ideally use orthogonal polynomials
vec_p_j[II] = torch.pow(pts_x1[j,0] - pts_x2[i,0], alpha);
II += 1;
elif num_dim == 2:
# number of terms is N = (porder + 1)*(porder + 2)/2.
II = 0;
for alpha in np.arange(0,porder + 1):
for k in np.arange(0,alpha + 1):
if flag_verbose > 1: print("alpha = " + str(alpha)); print("k = " + str(k));
# for now, (x - x_*)^k, but ideally use orthogonal polynomials
vec_p_j[II] = torch.pow(pts_x1[j,0] - pts_x2[i,0], alpha - k);
vec_p_j[II] = vec_p_j[II]*torch.pow(pts_x1[j,1] - pts_x2[i,1], k);
II += 1;
elif num_dim == 3:
# number of terms is N = sum_{alpha_3 = 0}^porder [(porder - alpha_3+ 1)*(porder - alpha_3 + 2)/2.
II = 0;
for beta in np.arange(0,porder + 1):
vec_p_j[II] = torch.pow(pts_x1[j,2] - pts_x2[i,2],beta);
for alpha in np.arange(0,porder - beta + 1):
for k in np.arange(0,alpha + 1):
if flag_verbose > 1:
print("beta = " + str(beta)); print("alpha = " + str(alpha)); print("k = " + str(k));
# for now, (x - x_*)^k, but ideally use orthogonal polynomials
vec_p_j[II] = vec_p_j[II]*torch.pow(pts_x1[j,0] - pts_x2[i,0],alpha - k);
vec_p_j[II] = vec_p_j[II]*torch.pow(pts_x1[j,1] - pts_x2[i,1],k);
II += 1;
# add contributions to the M(x_i) and r(x_i) terms
# r += (w_ij*u[j])*vec_p_j;
vec_rij[i,:,j] = w_ij*vec_p_j;
M[i,:,:] += torch.ger(vec_p_j,vec_p_j)*w_ij; # outer-product of vectors (build match of matrices)
# Compute the SVD of M for purposes of computing the pseudo-inverse (for solving least-squares problem).
# Note: M is always symmetric positive semi-definite, so U and V should be transposes of each other
# and sigma^2 are the eigenvalues squared. This simplifies some expressions.
U,S,V = torch.svd(M[i,:,:]); # M = U*SS*V^T, note SS = diag(S)
threshold_nonzero = 1e-9; # threshold for the largest singular value to consider being non-zero.
I_nonzero = (S > threshold_nonzero);
S_inv = 0.0*S;
S_inv[I_nonzero] = 1.0/S[I_nonzero];
SS_inv = torch.diag(S_inv);
M_inv[i,:,:] = torch.matmul(V,torch.matmul(SS_inv,U.t())); # pseudo-inverse of M^{-1} = V*S^{-1}*U^T
# Save the linear system information for the least-squares problem at each target point $xi$.
map_data['M'] = M;
map_data['M_inv'] = M_inv;
map_data['vec_rij'] = vec_rij;
return map_data;
@staticmethod
def get_poly_1D_u(u, porder, weight_func, weight_func_params,
pts_x1, epsilon = None, pts_x2 = None, cached_data=None,
tree_points = None, device=None, flag_verbose = 0):
r""" Compute the polynomial coefficients in the case of a scalar field. Would not typically call directly, used for internal purposes. """
# We assume that all inputs are pytorch tensors
# Assumes:
# pts_x1.size = [num_pts,num_dim]
# pts_x2.size = [num_pts,num_dim]
#
# @optimize: Should cache the points and neighbor lists... then using torch.solve, torch.ger.
# Should vectorize all of the for-loop operations via Lambdifying polynomial evals.
# Should avoid numpy calculations, maybe cache numpy copy of data if needed to avoid .cpu() transfer calls.
# Use batching over points to do solves, then GPU parallizable and faster.
#
if device is None:
device = torch.device('cpu'); # default cpu device
if (u.dim() > 1):
print("u.dim = " + str(u.dim()));
print("u.shape = " + str(u.shape));
raise Exception("Assumes input with dimension == 1.");
if (cached_data is None) or ('map_data' not in cached_data) or (cached_data['map_data'] is None):
generate_mapping = MapToPoly_Function.generate_mapping;
if pts_x2 is None:
pts_x2 = pts_x1;
map_data = generate_mapping(weight_func,weight_func_params,
porder,epsilon,
pts_x1,pts_x2,tree_points,device);
if cached_data is not None:
cached_data['map_data'] = map_data;
else:
map_data = cached_data['map_data']; # use cached data
if flag_verbose > 0:
print("num_pts1 = " + str(num_pts1) + ", num_pts2 = " + str(num_pts2));
if epsilon is None:
raise Exception('The epsilon ball size to use around xi must be specified.')
# Maps from u(x_j) on $x_j \in \mathcal{S}^1$ to a
# polynomial representations in overlapping regions $\Omega_i$ at locations
# around points $x_i \in \mathcal{S}^2$.
# These two sample sets need not be the same allowing mappings between point sets.
# Computes polynomials over x and y.
# For 2D case, number of terms is num_polys = (porder + 1)*(porder + 2)/2.
#c_star[:,i] = np.linalg.solve(np_M,np_r); # "c^*(x_i) = M^{-1}*r."
vec_rij = map_data['vec_rij'];
M_inv = map_data['M_inv'];
r_all = torch.matmul(vec_rij,u);
c_star = torch.bmm(M_inv,r_all.unsqueeze(2)); # perform batch matric-vector multiplications
c_star = c_star.squeeze(2); # convert to list of vectors
output = c_star;
output = output.float(); # Map to float type for GPU / PyTorch Module compatibilities.
return output, pts_x2;
@staticmethod
def forward(ctx, input, porder, weight_func, weight_func_params,
pts_x1, epsilon = None, pts_x2 = None, cached_data=None,
tree_points = None, device = None, flag_verbose = 0):
r"""
For a field u specified at points xj, performs the mapping to coefficients c at points xi, (uj,xj) :math:`\rightarrow` (ci,xi).
Args:
input (Tensor): The input field data uj.
porder (int): Order of the basis to use (polynomial degree).
weight_func (function): Weight function to use.
weight_func_params (dict): Weight function parameters.
pts_x1 (Tensor): The collection of domain points :math:`x_j`.
epsilon (float): The :math:`\epsilon`-neighborhood size to use to sort points (should be compatible with choice of weight_func_params).
pts_x2 (Tensor): The collection of target points :math:`x_i`.
cache_data (dict): Stored data to help speed up repeated calculations.
tree_points (dict): Stored data to help speed up repeated calculations.
device (torch.device): Device on which to perform calculations (GPU or other, default is CPU).
flag_verbose (int): Level of reporting on progress during the calculations.
Returns:
tuple of (ci,xi): The coefficient values ci at the target points xi. The target points xi.
"""
if device is None:
device = torch.device('cpu');
ctx.atz_name = 'MapToPoly_Function';
ctx.save_for_backward(input,pts_x1,pts_x2);
ctx.atz_porder = porder;
ctx.atz_weight_func = weight_func;
ctx.atz_weight_func_params = weight_func_params;
get_poly_1D_u = MapToPoly_Function.get_poly_1D_u;
get_num_polys = MapToPoly_Function.get_num_polys;
input_dim = input.dim();
if input_dim >= 1: # compute c_star in batches
pts_x1_numpy = None;
pts_x2_numpy = None;
if pts_x2 is None:
pts_x2 = pts_x1;
# reshape the data to handle as a batch [batch_size, uj_data_size]
# We assume u is input in the form [I,k,xj], u_I(k,xj), the index I is arbitrary.
u = input;
if input_dim == 2: # need to unsqueeze, so 2D we are mapping
# [k,xj] --> [I,k,xj] --> [II,c] --> [I,k,xi,c] --> [k,xi,c]
u = u.unsqueeze(0); # u(k,xj) assumed in our calculations here
if input_dim == 1: # need to unsqueeze, so 1D we are mapping
# [xj] --> [I,k,xj] --> [II,c] --> [I,k,xi,c] --> [xi,c]
u = u.unsqueeze(0); # u(k,xj) assumed in our calculations here
u = u.unsqueeze(0); # u(k,xj) assumed in our calculations here
u_num_dim = u.dim();
size_nm1 = 1;
for d in range(u_num_dim - 1):
size_nm1 *= u.shape[d];
uu = u.contiguous().view((size_nm1,u.shape[-1]));
# compute the sizes of c_star and number of points
num_dim = pts_x1.shape[1];
num_polys = get_num_polys(porder,num_dim);
num_pts2 = pts_x2.shape[0];
# output needs to be of size [batch_size, xi_data_size, num_polys]
output = torch.zeros((uu.shape[0],num_pts2,num_polys),device=device); # will reshape at the end
# loop over the batches and compute the c_star in each case
if cached_data is None:
cached_data = {}; # create empty, which can be computed first time to store data.
if tree_points is None:
if pts_x1_numpy is None: pts_x1_numpy = pts_x1.cpu().numpy();
tree_points = spatial.cKDTree(pts_x1_numpy);
for k in range(uu.shape[0]):
uuu = uu[k,:];
out, pts_x2 = get_poly_1D_u(uuu,porder,weight_func,weight_func_params,
pts_x1,epsilon,pts_x2,cached_data,
tree_points,flag_verbose);
output[k,:,:] = out;
# final output should be [*, xi_data_size, num_polys], where * is the original sizes
# for indices [i1,i2,...in,k_channel,xi_data,c_poly_coeff].
output = output.view(*u.shape[0:u_num_dim-1],num_pts2,num_polys);
if input_dim == 2: # 2D special case we just return k, xi, c (otherwise feed input 3D [I,k,u(xj)] I=1,k=1).
output = output.squeeze(0);
if input_dim == 1: # 1D special case we just return xi, c (otherwise feed input 3D [I,k,u(xj)] I=1,k=1).
output = output.squeeze(0);
output = output.squeeze(0);
else:
print("input.dim = " + str(input.dim()));
print("input.shape = " + str(input.shape));
raise Exception("input tensor dimension not yet supported, only dim = 1 and dim = 3 currently.");
ctx.atz_cached_data = cached_data;
pts_x2_clone = pts_x2.clone();
return output, pts_x2_clone;
@staticmethod
def backward(ctx,grad_output,grad_pts_x2):
r""" Consider a field u specified at points xj and the mapping to coefficients c at points xi, (uj,xj) --> (ci,xi).
Computes the gradient of the mapping for backward propagation.
"""
flag_time_it = False;
if flag_time_it:
time_1 = time.time();
input,pts_x1,pts_x2 = ctx.saved_tensors;
porder = ctx.atz_porder;
weight_func = ctx.atz_weight_func;
weight_func_params = ctx.atz_weight_func_params;
cached_data = ctx.atz_cached_data;
#grad_input = grad_weight_func = grad_weight_func_params = None;
grad_uj = None;
# we only compute the gradient in x_i, if it is requested (for efficiency)
if ctx.needs_input_grad[0]: # derivative in uj
map_data = cached_data['map_data']; # use cached data
vec_rij = map_data['vec_rij'];
M_inv = map_data['M_inv'];
# c_i = M_{i}^{-1} r_i^T u
# dF/du = dF/dc*dc/du,
#
# We can express this using dF/uj = sum_i dF/dci*dci/duj
#
# grad_output = dF/dc, grad_input = dF/du
#
# [grad_input]_j = sum_i dF/ci*dci/duj.
#
# In practice, we have both batch and channel indices so
# grad_output.shape = [batchI,channelI,i,compK]
# grad_output[batchI,channelI,i,compK] = F(batchI,channelI) with respect to ci[compK](batchI,channelI).
#
# grad_input[batchI,channelI,j] =
#
# We use matrix broadcasting to get this outcome in practice.
#
# @optimize can optimize, since uj only contributes non-zero to a few ci's... and could try to use sparse matrix multiplications.
A1 = torch.bmm(M_inv,vec_rij); # dci/du, grad = grad[i,compK,j]
A2 = A1.unsqueeze(0).unsqueeze(0); # match grad_output tensor rank, for grad[batchI,channelI,i,compK,j]
A3 = grad_output.unsqueeze(4); # grad_output[batchI,channelI,i,compK,j]
A4 = A3*A2; # elementwise multiplication
A5 = torch.sum(A4,3); # contract on index compK
A6 = torch.sum(A5,2); # contract on index i
grad_uj = A6;
else:
msg_str = "Requested a currently un-implemented gradient for this map: \n";
msg_str += "ctx.needs_input_grad = \n" + str(ctx.needs_input_grad);
raise Exception(msg_str);
if flag_time_it:
msg = 'MapToPoly_Function->backward():';
msg += 'elapsed_time = %.4e'%(time.time() - time_1);
print(msg);
return grad_uj,None,None,None,None,None,None,None,None,None,None; # since no trainable parts for these components of map
class MaxPoolOverPoints_Function(torch.autograd.Function):
r"""Applies a max-pooling operation to obtain values :math:`v_i = \max_{j \in \mathcal{N}_i(\epsilon)} \{u_j\}.` """
# @optimize: Should cache the points and neighbor lists.
# Should avoid numpy calculations, maybe cache numpy copy of data if needed to avoid .cpu() transfer calls.
# Use batching over points to do solves, then GPU parallizable and faster.
@staticmethod
def forward(ctx,input,pts_x1,epsilon=None,pts_x2=None,
indices_xj_i_cache=None,tree_points=None,
flag_verbose=0):
r"""Compute max pool operation from values at points (uj,xj) to obtain (vi,xi).
Args:
input (Tensor): The uj values at the location of points xj.
pts_x1 (Tensor): The collection of domain points :math:`x_j`.
epsilon (float): The :math:`\epsilon`-neighborhood size to use to sort points (should be compatible with choice of weight_func_params).
pts_x2 (Tensor): The collection of target points :math:`x_i`.
tree_points (dict): Stored data to help speed up repeated calculations.
flag_verbose (int): Level of reporting on progress during the calculations.
Returns:
tuple: The collection ui at target points (same size as uj in the non-j indices). The collection xi of target points. Tuple of form (ui,xi).
Note:
We assume that all inputs are pytorch tensors with pts_x1.shape = [num_pts,num_dim] and similarly for pts_x2.
"""
ctx.atz_name = 'MaxPoolOverPoints_Function';
ctx.save_for_backward(input,pts_x1,pts_x2);
u = input.clone(); # map input values u(xj) at xj to max value in epsilon neighborhood to u(xi) at xi points.
# Assumes that input is of size [k1,k2,...,kn,j], where k1,...,kn are any indices.
# We perform maxing over batch over all non-indices in j.
# We reshape tensor to the form [*,j] where one index in *=index(k1,...,kn).
u_num_dim = u.dim();
size_nm1 = 1;
for d in range(u_num_dim - 1):
size_nm1 *= u.shape[d];
uj = u.contiguous().view((size_nm1,u.shape[-1])); # reshape so indices --> [I,j], I = index(k1,...,kn).
# reshaped
if pts_x2 is None:
pts_x2 = pts_x1;
pts_x1_numpy = pts_x1.cpu().numpy(); pts_x2_numpy = pts_x2.cpu().numpy(); # move to cpu to get numpy data
pts_x1 = pts_x1.to(input.device); pts_x2 = pts_x2.to(input.device); # push back to GPU [@optimize later]
num_pts1 = pts_x1.size()[0]; num_pts2 = pts_x2.size()[0];
if flag_verbose > 0:
print("num_pts1 = " + str(num_pts1) + ", num_pts2 = " + str(num_pts2));
if epsilon is None:
raise Exception('The epsilon ball size to use around xi must be specified.');
ctx.atz_epsilon = epsilon;
if indices_xj_i_cache is None:
flag_need_indices_xj_i = True;
else:
flag_need_indices_xj_i = False;
if flag_need_indices_xj_i and tree_points is None: # build kd-tree of points for neighbor listing
tree_points = spatial.cKDTree(pts_x1_numpy);
ctx.atz_tree_points = tree_points;
ctx.indices_xj_i_cache = indices_xj_i_cache;
# Maps from u(x_j) on $x_j \in \mathcal{S}^1$ to a u(x_i) giving max values in epsilon neighborhoods.
# @optimize by caching these data structure for re-use later
ui = torch.zeros(size_nm1,num_pts2,requires_grad=False,device=input.device);
ui_argmax_j = torch.zeros(size_nm1,num_pts2,dtype=torch.int64,requires_grad=False,device=input.device);
# assumes array of form [*,num_pts2], will be reshaped to match uj, [*,num_pts2].
for i in np.arange(0,num_pts2): # loop over the points $x_i$
if flag_verbose > 1: print("i = " + str(i) + " : num_pts2 = " + str(num_pts2));
# find all points distance epsilon from xi
if flag_need_indices_xj_i:
indices_xj_i = tree_points.query_ball_point(pts_x2_numpy[i,:], epsilon);
indices_xj_i = torch.Tensor(indices_xj_i).long();
indices_xj_i.to(uj.device);
else:
indices_xj_i = indices_xj_i_cache[i,:]; # @optimize should consider replacing with better data structures
# take max over neighborhood. Assumes for now that ui is scalar.
uuj = uj[:,indices_xj_i];
qq = torch.max(uuj,dim=-1,keepdim=True);
ui[:,i] = qq[0].squeeze(-1); # store max value
jj = qq[1].squeeze(-1); # store index of max value
ui_argmax_j[:,i] = indices_xj_i[jj]; # store global index of the max value
# reshape the tensor from ui[I,i] to the form uui[k1,k2,...kn,i]
uui = ui.view(*u.shape[0:u_num_dim-1],num_pts2);
uui_argmax_j = ui_argmax_j.view(*u.shape[0:u_num_dim-1],num_pts2);
ctx.atz_uui_argmax_j = uui_argmax_j; # save for gradient calculation
output = uui; # for now, we assume for now that ui is scalar array of size [num_pts2]
output = output.to(input.device);
return output, pts_x2.clone();
@staticmethod
def backward(ctx,grad_output,grad_pts_x2):
r"""Compute gradients of the max pool operations from values at points (uj,xj) --> (max_ui,xi). """
flag_time_it = False;
if flag_time_it:
time_11 = time.time();
# Compute df/dx from df/dy using the Chain Rule df/dx = df/dx*dy/dx.
# Compute the gradient with respect to inputs, dz/dx.
#
# Consider z = f(g(x)), where we refer to x as the inputs and y = g(x) as outputs.
# If we know dz/dy, we would like to compute dz/dx. This will follow from the chain-rule
# as dz/dx = (dz/dy)*(dy/dx). We call dz/dy the gradient with respect to output and we call
# dy/dx the gradient with respect to input.
#
# Note: the grad_output can be larger than the size of the input vector if we include in our
# definition of gradient_input the derivatives with respect to weights. Should think of everything
# input as tilde_x = [x,weights,bias,etc...], then grad_output = dz/dtilde_x.
input,pts_x1,pts_x2 = ctx.saved_tensors;
uui_argmax_j = ctx.atz_uui_argmax_j;
#grad_input = grad_weight_func = grad_weight_func_params = None;
grad_input = None;
# We only compute the gradient in xi, if it is requested (for efficiency)
# stubs for later possible use, but not needed for now
if ctx.needs_input_grad[1] or ctx.needs_input_grad[2]:
msg_str = "Currently requested a non-trainable gradient for this map: \n";
msg_str += "ctx.needs_input_grad = \n" + str(ctx.needs_input_grad);
raise Exception(msg_str);
if ctx.needs_input_grad[0]:
# Compute dL/duj = (dL/dvi)*(dvi/duj), here vi = uui.
# For the max-pool case, notice that dvi/duj is non-zero only when the index uj
# was the maximum value in the neighborhood of vi. Notice subtle issue with
# right and left derivatives being different, so max is not differentiable for ties.
# We use the right derivative lim_h (q(x + h) - q(x))/h, here.
# We assume that uj.size = [k1,k2,...,kn,j], ui.size = [k1,k2,...,kn,i].
# These are reshaped so that uuj.size = [I,j] and uui.size = [I,i].
input_dim = input.dim();
size_uj = input.size();
size_uj_nm1 = np.prod(size_uj[0:input_dim-1]); # exclude last index size
#ss_grad_input = input.new_zeros(size_uj_nm1,size_uj[-1]); # to store dL/duj, [I,j] indexing.
ss_grad_output = grad_output.contiguous().view((size_uj_nm1,grad_output.shape[-1])); # reshape so index [I,i].
ss_uui_argmax_j = uui_argmax_j.contiguous().view((size_uj_nm1,grad_output.shape[-1])); # reshape so index [I,i].
# assign the entries k_i = argmax_{j in Omega_i} uj, reshaped so [*,j] = val[*,j].
flag_method = 'method1';
if flag_method == 'method1':
flag_time_it = False;
if flag_time_it:
time_0 = time.time();
I = torch.arange(0,size_uj_nm1,dtype=torch.int64,device=input.device);
vec_ones = torch.ones(grad_output.shape[-1],dtype=torch.int64,device=input.device);
II = torch.ger(I.float(),vec_ones.float()); # careful int --> float conv
II = II.flatten();
JJ = ss_uui_argmax_j.flatten();
IJ_indices1 = torch.stack((II,JJ.float())).long();
i_index = torch.arange(0,grad_output.shape[-1],dtype=torch.int64,device=input.device);
vec_ones = torch.ones(size_uj_nm1,dtype=torch.int64,device=input.device);
KK = torch.ger(vec_ones.float(),i_index.float()); # careful int --> float conv
KK = KK.flatten();
IJ_indices2 = torch.stack((II,KK)).long();
# We aim to compute dL/duj = dL/d\bar{u}_i*d\bar{u}_i/duj.
#
# This is done efficiently by constructing a sparse matrix using how \bar{u}_i
# depends on the uj. Sometimes the same uj contributes multiple times to
# a given \bar{u}_i entry, so we add together those contributions, as would
# occur in an explicit multiplication of the terms above for dL/duj.
# This is acheived efficiently using the .add() for sparse tensors in PyTorch.
# We construct entries of the sparse matrix and coelesce them (add repeats).
vals = ss_grad_output[IJ_indices2[0,:],IJ_indices2[1,:]]; # @optimize, maybe just flatten
N1 = size_uj_nm1; N2 = size_uj[-1]; sz = torch.Size([N1,N2]);
ss_grad_input = torch.sparse.FloatTensor(IJ_indices1,vals,sz).coalesce().to_dense();
if flag_time_it:
time_1 = time.time();
print("time: backward(): compute ss_grad_input = %.4e sec"%(time_1 - time_0));
elif flag_method == 'method2':
II = torch.arange(0,size_uj_nm1,dtype=torch.int64);
i_index = torch.arange(0,grad_output.shape[-1],dtype=torch.int64);
# @optimize by vectorizing this calculation
for I in II:
for j in range(0,i_index.shape[0]):
ss_grad_input[I,ss_uui_argmax_j[I,j]] += ss_grad_output[I,i_index[j]];
else:
raise Exception("flag_method type not recognized.\n flag_method = %s"%flag_method);
# reshape
grad_input = ss_grad_input.view(*size_uj[0:input_dim - 1],size_uj[-1]);
if flag_time_it:
msg = 'atzGMLS_MaxPool2D_Function->backward(): ';
msg += 'elapsed_time = %.4e'%(time.time() - time_11);
print(msg);
return grad_input,None,None,None,None,None,None; # since no trainable parts for components of this map
class ExtractFromTuple_Function(torch.autograd.Function):
r"""Extracts from a tuple of outputs one of the components."""
@staticmethod
def forward(ctx,input,index):
r"""Extracts tuple entry with the specified index."""
ctx.atz_name = 'ExtractFromTuple_Function';
extracted = input[index];
output = extracted.clone(); # clone added for safety
return output;
@staticmethod
def backward(ctx,grad_output): # number grad's needs to match outputs of forward
r"""Computes gradient of the extraction."""
raise Exception('This backward is not implemented, since PyTorch automatically handled this in the past.');
return None,None;
# ====================================
# Custom Modules
# ====================================
class PdbSetTraceLayer(nn.Module):
r"""Allows for placing break-points within the call sequence of layers using pdb.set_trace(). Helpful for debugging networks."""
def __init__(self):
r"""Initialization (currently nothing to do, but call super-class)."""
super(PdbSetTraceLayer, self).__init__()
def forward(self, input):
r"""Executes a PDB breakpoint inside of a running network to help with debugging."""
out = input.clone(); # added clone to avoid .grad_fn overwrite
pdb.set_trace();
return out;
class ExtractFromTuple(nn.Module):
r"""Extracts from a tuple of outputs one of the components."""
def __init__(self,index=0):
r"""Initializes the index to extract."""
super(ExtractFromTuple, self).__init__()
self.index = index;
def forward(self, input):
r"""Extracts the tuple entry with the specified index."""
extracted = input[self.index];
extracted_clone = extracted.clone(); # cloned to avoid overwrite of .grad_fn
return extracted_clone;
class ReshapeLayer(nn.Module):
r"""Performs reshaping of a tensor output within a network."""
def __init__(self,reshape,permute=None):
r"""Initializes the reshaping form to use followed by the indexing permulation to apply."""
super(ReshapeLayer, self).__init__()
self.reshape = reshape;
self.permute = permute;
def forward(self, input):
r"""Reshapes the tensor followed by applying a permutation to the indexing."""
reshape = self.reshape;
permute = self.permute;
A = input.contiguous();
out = A.view(*reshape);
if permute is not None:
out = out.permute(*permute);
return out;
class PermuteLayer(nn.Module):
r"""Performs permutation of indices of a tensor output within a network."""
def __init__(self,permute=None):
r"""Initializes the indexing permuation to apply to tensors."""
super(PermuteLayer, self).__init__()
self.permute = permute;
def forward(self, input):
r"""Applies and indexing permuation to the input tensor."""
permute = self.permute;
input_clone = input.clone(); # adding clone to avoid .grad_fn overwrites
out = input_clone.permute(*permute);
return out;
class MLP_Pointwise(nn.Module):
r"""Creates a collection of multilayer perceptrons (MLPs) for each output channel.
The MLPs are then applied at each target point xi.
"""
def create_mlp_unit(self,layer_sizes,unit_name='',flag_bias=True):
r"""Creates an instance of an MLP with specified layer sizes. """
layer_dict = OrderedDict();
NN = len(layer_sizes);
for i in range(NN - 1):
key_str = unit_name + ':hidden_layer_%.4d'%(i + 1);
layer_dict[key_str] = nn.Linear(layer_sizes[i], layer_sizes[i+1],bias=flag_bias);
if i < NN - 2: # last layer should be linear
key_str = unit_name + ':relu_%.4d'%(i + 1);
layer_dict[key_str] = nn.ReLU();
mlp_unit = nn.Sequential(layer_dict); # uses ordered dictionary to create network
return mlp_unit;
def __init__(self,layer_sizes,channels_in=1,channels_out=1,flag_bias=True,flag_verbose=0):
r"""Initializes the structure of the pointwise MLP module with layer sizes, number input channels, number of output channels.
Args:
layer_sizes (list): The number of hidden units in each layer.
channels_in (int): The number of input channels.
channels_out (int): The number of output channels.
flag_bias (bool): If the MLP should include the additive bias b added into layers.
flag_verbose (int): The level of messages generated on progress of the calculation.
"""
super(MLP_Pointwise, self).__init__();
self.layer_sizes = layer_sizes;
self.flag_bias = flag_bias;
self.depth = len(layer_sizes);
self.channels_in = channels_in;
self.channels_out = channels_out;
# create intermediate layers
mlp_list = nn.ModuleList();
layer_sizes_unit = layer_sizes.copy(); # we use inputs k*c to cross channels in practice in our unit MLPs
layer_sizes_unit[0] = layer_sizes_unit[0]*channels_in; # modify the input to have proper size combined k*c
for ell in range(channels_out):
mlp_unit = self.create_mlp_unit(layer_sizes_unit,'unit_ell_%.4d'%ell,flag_bias=flag_bias);
mlp_list.append(mlp_unit);
self.mlp_list = mlp_list;
def forward(self, input, params = None):
r"""Applies the specified MLP pointwise to the collection of input data to produce pointwise entries of the output channels."""
#
# Assumes the tensor has the form [i1,i2,...in,k,c], the last two indices are the
# channel index k, and the coefficient index c, combine for ease of use, but can reshape.
# We collapse input tensor with indexing [i1,i2,...in,k,c] to a [I,k*c] tensor, where
# I is general index, k is channel, and c are coefficient index.
#
s = input.shape;
num_dim = input.dim();
if (s[-2] != self.channels_in) or (s[-1] != self.layer_sizes[0]): # check correct sized inputs
print("input.shape = " + str(input.shape));
raise Exception("MLP assumes an input tensor of size [*,%d,%d]"%(self.channels_in,self.layer_sizes[0]));
calc_size1 = 1.0;
for d in range(num_dim-2):
calc_size1 *= s[d];
calc_size1 = int(calc_size1);
x = input.contiguous().view(calc_size1,s[num_dim-2]*s[num_dim-1]); # shape input to have indexing [I,k*NN + c]
if params is None:
output = torch.zeros((self.channels_out,x.shape[0]),device=input.device); # shape [ell,*]
for ell in range(self.channels_out):
mlp_q = self.mlp_list[ell];
output[ell,:] = mlp_q.forward(x).squeeze(-1); # reduce from [N,1] to [N]
s = input.shape;
output = output.view(self.channels_out,*s[0:num_dim-2]); # shape to have index [ell,i1,i2,...,in]
nn = output.dim();
p_ind = np.arange(nn) + 1;
p_ind[nn-1] = 0;
p_ind = tuple(p_ind);
output = output.permute(p_ind); # [*,ell] indexing of final shape
else:
raise Exception("Not yet implemented for setting parameters.");
return output; # [*,ell] indexing of final shape
def to(self, device):
r"""Moves data to GPU or other specified device."""
super(MLP_Pointwise, self).to(device);
for ell in range(self.channels_out):
mlp_q = self.mlp_list[ell];
mlp_q.to(device);
return self;
class MLP1(nn.Module):
r"""Creates a multilayer perceptron (MLP). """
def __init__(self, layer_sizes, flag_bias = True, flag_verbose=0):
r"""Initializes MLP and specified layer sizes."""
super(MLP1, self).__init__();
self.layer_sizes = layer_sizes;
self.flag_bias = flag_bias;
self.depth = len(layer_sizes);
# create intermediate layers
layer_dict = OrderedDict();
NN = len(layer_sizes);
for i in range(NN - 1):
key_str = 'hidden_layer_%.4d'%(i + 1);
layer_dict[key_str] = nn.Linear(layer_sizes[i], layer_sizes[i+1],bias=flag_bias);
if i < NN - 2: # last layer should be linear
key_str = 'relu_%.4d'%(i + 1);
layer_dict[key_str] = nn.ReLU();
self.layers = nn.Sequential(layer_dict); # uses ordered dictionary to create network
def forward(self, input, params = None):
r"""Applies the MLP to the input data.
Args:
input (Tensor): The coefficient channel data organized as one stacked
vector of size Nc*M, where Nc is number of channels and M is number of
coefficients per channel.
Returns:
Tensor: The evaluation of the network. Returns tensor of size [batch,1].
"""
# evaluate network with specified layers
if params is None:
eval = self.layers.forward(input);
else:
raise Exception("Not yet implemented for setting parameters.");
return eval;
def to(self, device):
r"""Moves data to GPU or other specified device."""
super(MLP1, self).to(device);
self.layers = self.layers.to(device);
return self;
class MapToPoly(nn.Module):
r"""
This layer processes a collection of scattered data points consisting of a collection
of values :math:`u_j` at points :math:`x_j`. For a collection of target points
:math:`x_i`, local least-squares problems are solved for obtaining a local representation
of the data over a polynomial space. The layer outputs a collection of polynomial
coefficients :math:`c(x_i)` at each point and the collection of target points :math:`x_i`.
"""
def __init__(self, porder, weight_func, weight_func_params, pts_x1,
epsilon = None,pts_x2 = None,tree_points = None,
device = None,flag_verbose = 0,**extra_params):
r"""Initializes the layer for mapping between field data uj at points xj to the
local polynomial reconstruction represented by coefficients ci at target points xi.
Args:
porder (int): Order of the basis to use. For polynomial basis is the degree.
weight_func (func): Weight function to use.
weight_func_params (dict): Weight function parameters.
pts_x1 (Tensor): The collection of domain points :math:`x_j`.
epsilon (float): The :math:`\epsilon`-neighborhood size to use to sort points (should be compatible with choice of weight_func_params).
pts_x2 (Tensor): The collection of target points :math:`x_i`.
tree_points (dict): Stored data to help speed up repeated calculations.
device: Device on which to perform calculations (GPU or other, default is CPU).
flag_verbose (int): Level of reporting on progress during the calculations.
**extra_params: Extra parameters allowing for specifying layer name and caching mode.
"""
super(MapToPoly, self).__init__();
self.flag_verbose = flag_verbose;
if device is None:
device = torch.device('cpu');
self.device = device;
if 'name' in extra_params:
self.name = extra_params['name'];
else:
self.name = "default_name";
if 'flag_cache_mode' in extra_params:
flag_cache_mode = extra_params['flag_cache_mode'];
else:
flag_cache_mode = 'generate1';
if flag_cache_mode == 'generate1': # setup from scratch
self.porder = porder;
self.weight_func = weight_func;
self.weight_func_params = weight_func_params;
self.pts_x1 = pts_x1;
self.pts_x2 = pts_x2;
self.pts_x1_numpy = None;
self.pts_x2_numpy = None;
if self.pts_x2 is None:
self.pts_x2 = pts_x1;
self.epsilon = epsilon;
if tree_points is None: # build kd-tree of points for neighbor listing
if self.pts_x1_numpy is None: self.pts_x1_numpy = pts_x1.cpu().numpy();
self.tree_points = spatial.cKDTree(self.pts_x1_numpy);
if device is None:
device = torch.device('cpu');
self.device = device;
self.cached_data = {}; # create empty cache for storing data
generate_mapping = MapToPoly_Function.generate_mapping;
self.cached_data['map_data'] = generate_mapping(self.weight_func,self.weight_func_params,
self.porder,self.epsilon,
self.pts_x1,self.pts_x2,
self.tree_points,self.device,
self.flag_verbose);
elif flag_cache_mode == 'load_from_file': # setup by loading data from cache file
if 'cache_filename' in extra_params:
cache_filename = extra_params['cache_filename'];
else:
raise Exception('No cache_filename specified.');
self.load_cache_data(cache_filename); # load data from file
else:
print("flag_cache_mode = " + str(flag_cache_mode));
raise Exception('flag_cache_mode is invalid.');
def save_cache_data(self,cache_filename):
r"""Save needed matrices and related data to .pickle for later cached use. (Warning: prototype codes here currently and not tested)."""
# collect the data to save
d = {};
d['porder'] = self.porder;
d['epsilon'] = self.epsilon;
if self.pts_x1_numpy is None: self.pts_x1_numpy = pts_x1.cpu().numpy();
d['pts_x1'] = self.pts_x1_numpy;
if self.pts_x2_numpy is None: self.pts_x2_numpy = pts_x2.cpu().numpy();
d['pts_x2'] = self.pts_x2_numpy;
d['weight_func_str'] = str(self.weight_func);
d['weight_func_params'] = self.weight_func_params;
d['version'] = __version__; # Module version
d['cached_data'] = self.cached_data;
# write the data to disk
f = open(cache_filename,'wb');
p.dump(d,f); # load the data from file
f.close();
def load_cache_data(self,cache_filename):
r"""Load the needed matrices and related data from .pickle. (Warning: prototype codes here currently and not tested)."""
f = open(cache_filename,'rb');
d = p.load(f); # load the data from file
f.close();
print(d.keys())
self.porder = d['porder'];
self.epsilon = d['epsilon'];
self.weight_func = d['weight_func_str'];
self.weight_func_params = d['weight_func_params'];
self.pts_x1 = torch.from_numpy(d['pts_x1']).to(device);
self.pts_x2 = torch.from_numpy(d['pts_x2']).to(device);
self.pts_x1_numpy = d['pts_x1'];
self.pts_x2_numpy = d['pts_x2'];
if self.pts_x2 is None:
self.pts_x2 = pts_x1;
# build kd-tree of points for neighbor listing
if self.pts_x1_numpy is None: self.pts_x1_numpy = pts_x1.cpu().numpy();
self.tree_points = spatial.cKDTree(self.pts_x1_numpy);
self.cached_data = d['cached_data'];
def eval_poly(self,pts_x,pts_x2_i0,c_star_i0,porder=None,flag_verbose=None):
r"""Evaluates the polynomial reconstruction around a given target point pts_x2_i0."""
if porder is None:
porder = self.porder;
if flag_verbose is None:
flag_verbose = self.flag_verbose;
MapToPoly_Function.eval_poly(pts_x,pts_x2_i0,c_star_i0,porder,flag_verbose);
def forward(self, input): # define the action of this layer
r"""For a field u specified at points xj, performs the mapping to coefficients c at points xi, (uj,xj) :math:`\rightarrow` (ci,xi)."""
flag_time_it = False;
if flag_time_it:
time_1 = time.time();
# We evaluate the action of the function, backward will be called automatically when computing gradients.
uj = input;
output = MapToPoly_Function.apply(uj,self.porder,
self.weight_func,self.weight_func_params,
self.pts_x1,self.epsilon,self.pts_x2,
self.cached_data,self.tree_points,self.device,
self.flag_verbose);
if flag_time_it:
msg = 'MapToPoly->forward(): ';
msg += 'elapsed_time = %.4e'%(time.time() - time_1);
print(msg);
return output;
def extra_repr(self):
r"""Displays information associated with this module."""
# Display some extra information about this layer.
return 'porder={}, weight_func={}, weight_func_params={}, pts_x1={}, pts_x2={}'.format(
self.porder, self.weight_func, self.weight_func_params, self.pts_x1.shape, self.pts_x2.shape
);
def to(self, device):
r"""Moves data to GPU or other specified device."""
super(MapToPoly,self).to(device);
self.pts_x1 = self.pts_x1.to(device);
self.pts_x2 = self.pts_x2.to(device);
return self;
class MaxPoolOverPoints(nn.Module):
r"""Applies a max-pooling operation to obtain values :math:`v_i = \max_{j \in \mathcal{N}_i(\epsilon)} \{u_j\}.` """
def __init__(self,pts_x1,epsilon=None,pts_x2=None,
indices_xj_i_cache=None,tree_points=None,
device=None,flag_verbose=0,**extra_params):
r"""Setup of max-pooling operation.
Args:
pts_x1 (Tensor): The collection of domain points :math:`x_j`. We assume size [num_pts,num_dim].
epsilon (float): The :math:`\epsilon`-neighborhood size to use to sort points (should be compatible with choice of weight_func_params).
pts_x2 (Tensor): The collection of target points :math:`x_i`.
indices_xj_i_cache (dict): Stored data to help speed up repeated calculations.
tree_points (dict): Stored data to help speed up repeated calculations.
device: Device on which to perform calculations (GPU or other, default is CPU).
flag_verbose (int): Level of reporting on progress during the calculations.
**extra_params (dict): Extra parameters allowing for specifying layer name and caching mode.
"""
super(MaxPoolOverPoints,self).__init__();
self.flag_verbose = flag_verbose;
if device is None:
device = torch.device('cpu');
self.device = device;
if 'name' in extra_params:
self.name = extra_params['name'];
else:
self.name = "default_name";
if 'flag_cache_mode' in extra_params:
flag_cache_mode = extra_params['flag_cache_mode'];
else:
flag_cache_mode = 'generate1';
if flag_cache_mode == 'generate1': # setup from scratch
self.pts_x1 = pts_x1;
self.pts_x2 = pts_x2;
self.pts_x1_numpy = None;
self.pts_x2_numpy = None;
if self.pts_x2 is None:
self.pts_x2 = pts_x1;
self.epsilon = epsilon;
if tree_points is None: # build kd-tree of points for neighbor listing
if self.pts_x1_numpy is None: self.pts_x1_numpy = pts_x1.cpu().numpy();
self.tree_points = spatial.cKDTree(self.pts_x1_numpy);
if indices_xj_i_cache is None:
self.indices_xj_i_cache = None; # cache the neighbor lists around each xi
else:
self.indices_xj_i_cache = indices_xj_i_cache;
if device is None:
device = torch.device('cpu');
self.device = device;
self.cached_data = {}; # create empty cache for storing data
elif flag_cache_mode == 'load_from_file': # setup by loading data from cache file
if 'cache_filename' in extra_params:
cache_filename = extra_params['cache_filename'];
else:
raise Exception('No cache_filename specified.');
self.load_cache_data(cache_filename); # load data from file
else:
print("flag_cache_mode = " + str(flag_cache_mode));
raise Exception('flag_cache_mode is invalid.');
def save_cache_data(self,cache_filename):
r"""Save data to .pickle file for caching. (Warning: Prototype placeholder code.)"""
# collect the data to save
d = {};
d['epsilon'] = self.epsilon;
if self.pts_x1_numpy is None: self.pts_x1_numpy = pts_x1.cpu().numpy();
d['pts_x1'] = self.pts_x1_numpy;
if self.pts_x2_numpy is None: self.pts_x2_numpy = pts_x2.cpu().numpy();
d['pts_x2'] = self.pts_x2_numpy;
d['version'] = __version__; # Module version
d['cached_data'] = self.cached_data;
# write the data to disk
f = open(cache_filename,'wb');
p.dump(d,f); # load the data from file
f.close();
def load_cache_data(self,cache_filename):
r"""Load data to .pickle file for caching. (Warning: Prototype placeholder code.)"""
f = open(cache_filename,'rb');
d = p.load(f); # load the data from file
f.close();
print(d.keys())
self.epsilon = d['epsilon'];
self.pts_x1 = torch.from_numpy(d['pts_x1']).to(device);
self.pts_x2 = torch.from_numpy(d['pts_x2']).to(device);
self.pts_x1_numpy = d['pts_x1'];
self.pts_x2_numpy = d['pts_x2'];
if self.pts_x2 is None:
self.pts_x2 = pts_x1;
# build kd-tree of points for neighbor listing
if self.pts_x1_numpy is None: self.pts_x1_numpy = pts_x1.cpu().numpy();
self.tree_points = spatial.cKDTree(self.pts_x1_numpy);
self.cached_data = d['cached_data'];
def forward(self, input): # define the action of this layer
r"""Applies a max-pooling operation to obtain values :math:`v_i = \max_{j \in \mathcal{N}_i(\epsilon)} \{u_j\}.`
Args:
input (Tensor): The collection uj of field values at the points xj.
Returns:
Tensor: The collection of field values vi at the target points xi.
"""
flag_time_it = False;
if flag_time_it:
time_1 = time.time();
uj = input;
output = MaxPoolOverPoints_Function.apply(uj,self.pts_x1,self.epsilon,self.pts_x2,
self.indices_xj_i_cache,self.tree_points,
self.flag_verbose);
if flag_time_it:
msg = 'MaxPoolOverPoints->forward(): ';
msg += 'elapsed_time = %.4e'%(time.time() - time_1);
print(msg);
return output;
def extra_repr(self):
r"""Displays information associated with this module."""
return 'pts_x1={}, pts_x2={}'.format(self.pts_x1.shape, self.pts_x2.shape);
def to(self, device):
r"""Moves data to GPU or other specified device."""
super(MaxPoolOverPoints, self).to(device);
self.pts_x1 = self.pts_x1.to(device);
self.pts_x2 = self.pts_x2.to(device);
return self;
class GMLS_Layer(nn.Module):
r"""The GMLS-Layer processes scattered data by using Generalized Moving Least
Squares (GMLS) to construct a local reconstruction of the data (here polynomials).
This is represented by coefficients that are mapped to approximate the action of
linear or non-linear operators on the input field.
As depicted above, the architecture processes a collection of input channels
into intermediate coefficient channels. The coefficient channels are
then collectively mapped to output channels. The mappings can be any unit
for which back-propagation can be performed. This includes linear
layers or non-linear maps based on multilayer perceptrons (MLPs).
Examples:
Here is a typical way to construct a GMLS-Layer. This is done in
the following stages.
``(i)`` Construct the scattered data locations xj, xi at which processing will occur. Here, we create points in 2D.
>>> xj = torch.randn((100,2),device=device); xi = torch.randn((100,2),device=device);
``(ii)`` Construct the mapping unit that will be applied pointwise. Here we create an MLP
with Nc input coefficient channels and channels_out output channels.
>>> layer_sizes = [];
>>> num_input = Nc*num_polys; # number of channels (NC) X number polynomials (num_polys) (cross-channel coupling allowed)
>>> num_depth = 4; num_hidden = 100; channels_out = 16; # depth, width, number of output filters
>>> layer_sizes.append(num_polys);
>>> for k in range(num_depth):
>>> layer_sizes.append(num_hidden);
>>> layer_sizes.append(1); # a single unit always gives scalar output, we then use channels_out units.
>>> mlp_q_map1 = gmlsnets_pytorch.nn.MLP_Pointwise(layer_sizes,channels_out=channels_out);
``(iii)`` Create the GMLS-Layer using these components.
>>> weight_func1 = gmlsnets_pytorch.nn.MapToPoly_Function.weight_one_minus_r;
>>> weight_func_params = {'epsilon':1e-3,'p'=4};
>>> gmls_layer_params = {
'flag_case':'standard','porder':4,'Nc':3,
'mlp_q1':mlp_q_map1,
'pts_x1':xj,'pts_x2':xi,'epsilon':1e-3,
'weight_func1':weight_func1,'weight_func1_params':weight_func1_params,
'device':device,'flag_verbose':0
};
>>> gmls_layer=gmlsnets_pytorch.nn.GMLS_Layer(**gmls_layer_params);
Here is an example of how a GMLS-Layer and other modules in this package
can be used to process scattered data. This could be part of a larger
neural network in practice (see example codes for more information). For instance,
>>> layer1 = nn.Sequential(gmls_layer, # produces output tuple of tensors (ci,xi) with shapes ([batch,ci,xi],[xi]).
#PdbSetTraceLayer(),
ExtractFromTuple(index=0), # from output keep only the ui part and discard the xi part.
#PdbSetTraceLayer(),
PermuteLayer((0,2,1)) # organize indexing to be [batch,xi,ci], for further processing.
).to(device);
You can uncomment the PdbSetTraceLayer() to get breakpoints for state information and tensor shapes during processing.
The PermuteLayer() changes the order of the indexing. Also can use ReshapeLayer() to reshape the tensors, which is
especially useful for processing data related to CNNs.
Much of the construction can be further simplified by writing a few wrapper classes for your most common use cases.
More information also can be found in the example codes directory.
"""
def __init__(self, flag_case, porder, pts_x1, epsilon, weight_func, weight_func_params,
mlp_q = None,pts_x2 = None, device = None, flag_verbose = 0):
r"""
Initializes the GMLS layer.
Args:
flag_case (str): Flag for the type of architecture to use (default is 'standard').
porder (int): Order of the basis to use (polynomial degree).
pts_x1 (Tensor): The collection of domain points :math:`x_j`.
epsilon (float): The :math:`\epsilon`-neighborhood size to use to sort points (should be compatible with choice of weight_func_params).
weight_func (func): Weight function to use.
weight_func_params (dict): Weight function parameters.
mlp_q (module): Mapping q unit for computing :math:`q(c)`, where c are the coefficients.
pts_x2 (Tensor): The collection of target points :math:`x_i`.
device: Device on which to perform calculations (GPU or other, default is CPU).
flag_verbose (int): Level of reporting on progress during the calculations.
"""
super(GMLS_Layer, self).__init__();
if flag_case is None:
self.flag_case = 'standard';
else:
self.flag_case = flag_case;
if device is None:
device = torch.device('cpu');
self.device = device;
if self.flag_case == 'standard':
tree_points = None;
self.MapToPoly_1 = MapToPoly(porder, weight_func, weight_func_params,
pts_x1, epsilon, pts_x2, tree_points,
device, flag_verbose);
if mlp_q is None: # if not specified then create some default custom layers
raise Exception("Need to specify the mlp_q module for mapping coefficients to output.");
else: # in this case initialized outside
self.mlp_q = mlp_q;
else:
print("flag_case = " + str(flag_case));
print("self.flag_case = " + str(self.flag_case));
raise Exception('flag_case not valid.');
def forward(self, input):
r"""Computes GMLS-Layer processing scattered data input field uj to obtain output field vi.
Args:
input (Tensor): Input channels uj organized in the shape [batch,xj,uj].
Returns:
tuple: The output channels and point locations (vi,xi). The field vi = q(ci).
"""
if self.flag_case == 'standard':
map_output = self.MapToPoly_1.forward(input);
c_star_i = map_output[0];
pts_x2 = map_output[1];
# MLP should apply across all channels and coefficients (coeff capture spatial, like kernel)
fc_input = c_star_i.permute((0,2,1,3)); # we organize as [batchI,ptsI,channelsI,coeffI]
# We assume MLP can process channelI*Nc + coeffI.
# We assume output of out = fc, has shape [batchI,ptsI,channelsNew]
# Outside routines can reshape that into an nD array again for structure samples or use over scattered samples.
q_of_c_star_i = self.mlp_q.forward(fc_input);
pts_x2_p = None; # currently returns None to simplify back-prop and debugging, but could just return the pts_x2.
return_vals = q_of_c_star_i, pts_x2_p;
return return_vals;
def to(self, device):
r"""Moves data to GPU or other specified device."""
super(GMLS_Layer, self).to(device);
self.MapToPoly_1 = self.MapToPoly_1.to(device);
self.mlp_q = self.mlp_q.to(device);
return self;
|
<gh_stars>1-10
#!/usr/bin/env python3
# Copyright (C) 2016 <NAME> <<EMAIL>>
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.
import sys
from testrunner import run
def test1(term):
term.expect_exact("######################### TEST1:")
term.expect_exact("first: sem_init")
term.expect_exact("first: thread create")
term.expect_exact("first: thread created")
term.expect_exact("first: sem_getvalue")
term.expect_exact("first: sem_getvalue != 0")
term.expect_exact("first: do yield")
term.expect_exact("second: sem_trywait")
term.expect_exact("second: sem_trywait done with == 0")
term.expect_exact("second: wait for post")
term.expect_exact("first: done yield")
term.expect_exact("first: sem_trywait")
term.expect_exact("first: sem_trywait FAILED")
term.expect_exact("first: sem_trywait done")
term.expect_exact("first: sem_post")
term.expect_exact("second: sem was posted")
term.expect_exact("second: end")
term.expect_exact("first: sem_post done")
term.expect_exact("first: sem_destroy")
term.expect_exact("first: end")
def test2(term):
term.expect_exact("######################### TEST2:")
term.expect_exact("first: sem_init")
term.expect_exact("first: thread create: 5")
term.expect_exact("first: thread created: priority 5 (1/5)")
term.expect_exact("first: thread create: 4")
term.expect_exact("first: thread created: priority 4 (2/5)")
term.expect_exact("first: thread create: 3")
term.expect_exact("first: thread created: priority 3 (3/5)")
term.expect_exact("first: thread create: 2")
term.expect_exact("first: thread created: priority 2 (4/5)")
term.expect_exact("first: thread create: 1")
term.expect_exact("first: thread created: priority 1 (5/5)")
term.expect_exact("------------------------------------------")
term.expect_exact("post no. 0")
term.expect_exact("Thread 'priority 1' woke up.")
term.expect_exact("Back in main thread.")
term.expect_exact("post no. 1")
term.expect_exact("Thread 'priority 2' woke up.")
term.expect_exact("Back in main thread.")
term.expect_exact("post no. 2")
term.expect_exact("Thread 'priority 3' woke up.")
term.expect_exact("Back in main thread.")
term.expect_exact("post no. 3")
term.expect_exact("Thread 'priority 4' woke up.")
term.expect_exact("Back in main thread.")
term.expect_exact("post no. 4")
term.expect_exact("Thread 'priority 5' woke up.")
term.expect_exact("Back in main thread.")
def test3(term):
term.expect_exact("######################### TEST3:")
term.expect_exact("first: sem_init s1")
term.expect_exact("first: sem_init s2")
term.expect_exact("first: create thread 1")
term.expect_exact("first: create thread 2")
term.expect_exact("------------------------------------------")
term.expect_exact("post s1")
term.expect_exact("Thread 1 woke up after waiting for s1.")
term.expect_exact("post s2")
term.expect_exact("Thread 2 woke up after waiting for s2.")
term.expect_exact("post s2")
term.expect_exact("Thread 1 woke up after waiting for s2.")
term.expect_exact("post s1")
term.expect_exact("Thread 2 woke up after waiting for s1.")
def test4(term):
term.expect_exact("######################### TEST4:")
term.expect_exact("first: sem_init s1")
term.expect_exact("first: wait 1 sec for s1")
term.expect_exact("first: timed out")
term.expect(r"first: waited 1\d{6} usec")
def testfunc(child):
test1(child)
test2(child)
test3(child)
test4(child)
child.expect("######################### DONE")
if __name__ == "__main__":
sys.exit(run(testfunc))
|
<reponame>Pandentia/journal
import pymongo.results
import pytz
import typing
from autoslot import Slots
from journal.db.util import id_to_time
if typing.TYPE_CHECKING:
from journal.db import DatabaseInterface, User
class Entry(Slots):
def __init__(self, db: 'DatabaseInterface' = None, **data):
self.db = db
self.id = data.get('_id') or self.db.id_gen.generate()
self.timestamp = data.get('timestamp', id_to_time(self.id)).astimezone(
pytz.timezone(data.get('timezone', 'UTC'))
)
self._author_id = data.get('author_id')
self._title = data.get('title') or 'Untitled entry'
self._content = data.get('content') or ''
self._tags = data.get('tags') or []
def serialize(self) -> typing.Dict[str, typing.Any]:
"""Returns a MongoDB-friendly dictionary for a replace() call."""
return {
'_id': self.id,
'author_id': self._author_id,
'title': self._title,
'content': self._content,
'tags': self._tags,
'timestamp': self.timestamp,
'timezone': (self.timestamp.tzinfo or pytz.UTC).zone,
}
def to_json(self) -> dict:
data = self.serialize()
data['timestamp'] = data['timestamp'].isoformat()
return data
def commit(self) -> pymongo.results.UpdateResult:
res = self.db.entries.replace_one({'_id': self.id}, self.serialize())
assert res.matched_count == 1
return res
@property
def author_id(self) -> typing.Optional[int]:
return self._author_id
@property
def author(self):
return self.db.get_user(id=self._author_id)
@author.setter
def author(self, value: 'User'):
# noinspection PyAttributeOutsideInit
self._author_id = value.id
@property
def title(self):
return self._title
@property
def timestamp_human(self):
return self.timestamp.strftime('%Y-%m-%d %H:%M:%S %Z') # TODO: per-user formatting options?
@title.setter
def title(self, value):
if value:
self._title = value.strip()
@property
def content(self):
return self._content
@content.setter
def content(self, value):
if value:
self._content = value.strip()
@property
def tags(self):
return self._tags
@tags.setter
def tags(self, value: typing.List[str]):
# we transform from list -> set -> list to remove duplicates
self._tags = list(set(sorted(x.strip().lower() for x in value if x.strip())))
@property
def tags_human(self):
return ', '.join(self._tags)
@tags_human.setter
def tags_human(self, tag_string: str):
# IDEA likes to complain when we call our own properties
# noinspection PyAttributeOutsideInit
self.tags = tag_string.split(',')
def new(self) -> 'Entry':
"""Initializes the database record and returns itself."""
self.db.entries.insert_one(self.serialize())
return self
def delete(self):
"""Clears the database record"""
res = self.db.entries.delete_one({'_id': self.id})
assert res.deleted_count == 1
def can_access(self, user: 'User') -> bool:
"""Returns whether a user has access to this entry or not."""
return self.author_id == user.id # TODO: sharing feature
def can_edit(self, user: 'User') -> bool:
"""Returns whether a user has owner rights on this entry."""
return self.author_id == user.id # (this one can probably stay as-is)
def __repr__(self):
return '<Entry id={0.id!r} author_id={0.author_id!r} title={0.title!r}>'.format(self)
|
<reponame>yashpatel12/CPIMS-api-newtest<filename>cpovc_offline_mode/helpers.py<gh_stars>1-10
import base64
import json
import logging
from django.core.cache import cache
from django.utils import timezone
from cpovc_forms.models import OVCCareEvents, OVCCareAssessment, OVCCareEAV, OVCCarePriority, OVCCareServices, \
OVCCareF1B, OVCCareCasePlan, OVCCareForms
from cpovc_main.functions import new_guid_32, convert_date
from cpovc_main.models import SetupList
from cpovc_ovc.functions import get_house_hold
from cpovc_ovc.models import OVCEducation, OVCHealth, OVCHHMembers, OVCHouseHold, OVCRegistration
from cpovc_registry.models import RegPerson
logger = logging.getLogger(__name__)
def get_ovc_school_details(ovc):
if ovc.school_level == "SLNS":
return {}
schools = OVCEducation.objects.filter(person_id=ovc.person.id, is_void=False)[:1]
if not schools:
return {}
school = schools[0]
return {
'school_name': school.school.school_name,
'school_class': school.school_class,
'admission_type': school.admission_type
}
def get_ovc_facility_details(ovc):
if ovc.hiv_status != 'HSTP':
return {}
health_facilities = OVCHealth.objects.filter(person_id=ovc.person.id)[:1]
if not health_facilities:
return {}
health = health_facilities[0]
return {
'name': health.facility.facility_name,
'art_status': health.art_status,
'date_linked': health.date_linked.strftime('%d/%m/%Y'),
'ccc_number': health.ccc_number
}
def get_ovc_household_members(ovc):
ovc_reg_id = ovc.person.id
ovc_household = OVCHHMembers.objects.filter(is_void=False, person_id=ovc_reg_id)[:1]
if not ovc_household:
return []
ovc_household = ovc_household[0]
member_types = {
'TBVC': 'Sibling',
'TOVC': 'Enrolled OVC'
}
def _is_household_head(hh_member):
if not hh_member.hh_head:
if hh_member.member_type == 'TBVC' or hh_member.member_type == 'TOVC':
return "N/A"
else:
return "No"
else:
return "Yes({})".format(ovc_household.house_hold.head_identifier)
# Get HH members
household_id = ovc_household.house_hold.id
household_members = OVCHHMembers.objects.filter(
is_void=False, house_hold_id=household_id).order_by("-hh_head")
household_members = household_members.exclude(person_id=ovc_reg_id)[:10] # limit 10
return [{
'first_name': member.person.first_name,
'surname': member.person.surname,
'age': member.person.age,
'type': member_types.get(member.member_type, 'Parent/Guardian'),
'phone_number': member.person.des_phone_number,
'alive': 'Yes' if member.member_alive == 'AYES' else 'No',
'hiv_status': member.hiv_status,
'household_head': _is_household_head(member)
} for member in household_members]
def get_services():
olmis_domain_id = 'olmis_domain_id'
olmis_assessment_domain_id = 'olmis_assessment_domain_id'
olmis = 'olmis'
olmis_priority_service = 'olmis_priority_service'
data = {
olmis_domain_id: {},
olmis_assessment_domain_id: {},
olmis: {},
olmis_priority_service: {}
}
field_names = [olmis_domain_id, olmis_assessment_domain_id, olmis, olmis_priority_service]
def append_domain_data(domain, field, items):
for elem in items:
if domain in data[field]:
data[field][domain].append(elem)
else:
data[field][domain] = [elem]
def service_to_dict(service_obj):
return {
'field_name': service_obj.field_name,
'item_sub_category': service_obj.item_description,
'status': 1 if service_obj.item_sub_category else 0,
'item_sub_category_id': service_obj.item_id
}
for field_name in field_names:
services = []
if field_name in [olmis_domain_id, olmis_assessment_domain_id, olmis, olmis_priority_service]:
services = SetupList.objects.filter(field_name=field_name, is_void=False)
if field_name == olmis:
services = SetupList.objects.filter(field_name__icontains='olmis', is_void=False)
for service in services:
service_sub_category = service.item_sub_category
if not service_sub_category:
append_domain_data(service.item_id, field_name, [service_to_dict(service)])
else:
sub_categories = SetupList.objects.filter(field_name=service_sub_category, is_void=False)
sub_categories_as_dict = [service_to_dict(item) for item in sub_categories]
append_domain_data(service.item_id, field_name, sub_categories_as_dict)
return data
def save_submitted_form1a(user_id, ovc_id, form_data, org_unit_primary, org_unit_attached):
assessment = form_data.get('assessment', {'assessments': []})
priority = form_data.get('priority', {'priorities': []})
service = form_data.get('service', {'services': []})
_handle_assessment(
user_id,
ovc_id,
assessment['assessments'],
assessment.get("date_of_assessment", None))
_handle_critical_event(user_id, ovc_id, form_data.get('event', None))
_handle_priority(
user_id,
ovc_id,
priority['priorities'],
priority.get("date_of_priority", None))
_handle_services(
user_id,
ovc_id,
service['services'],
service.get("date_of_service", None),
org_unit_primary,
org_unit_attached)
def _create_ovc_care_event(user_id, ovc_id, event_date):
event_type_id = 'FSAM'
person = RegPerson.objects.get(pk=int(ovc_id))
event_counter = OVCCareEvents.objects.filter(event_type_id=event_type_id, person=person, is_void=False).count()
ovc_care_event = OVCCareEvents(
event_type_id=event_type_id,
event_counter=event_counter,
event_score=0,
date_of_event=convert_date(event_date),
created_by=user_id,
person=person
)
ovc_care_event.save()
return ovc_care_event.pk
def _get_decoded_list_from_cache(cache_key):
cache_items = cache.get(cache_key, None)
if cache_items:
return json.loads(base64.b64decode(cache_items))
return []
def _add_list_items_to_cache(cache_key, items):
cache_timeout = 86400 # 1Day
cache.set(cache_key, base64.b64encode(json.dumps(items)), cache_timeout)
def _handle_critical_event(user_id, ovc_id, critical_event):
if not critical_event:
return
cache_key = "critical_event_offline_{}".format(ovc_id)
events_list = critical_event.get("olmis_critical_event", None)
event_date = critical_event.get("date_of_event", None)
if not events_list or not event_date:
return
events = events_list.split(",")
events_per_date = []
for event in events:
events_per_date.append(base64.b64encode("{}#{}".format(event, event_date)))
events_to_add = []
cached_events = _get_decoded_list_from_cache(cache_key)
for event in events_per_date:
if event not in cached_events:
cached_events.append(event)
events_to_add.append(event)
_add_list_items_to_cache(cache_key, cached_events)
if events_to_add:
ovc_care_event_id = _create_ovc_care_event(user_id, ovc_id, event_date)
for item in events_to_add:
events = base64.b64decode(item).split("#")
OVCCareEAV(
entity='CEVT',
attribute='FSAM',
value=events[0],
event=OVCCareEvents.objects.get(pk=ovc_care_event_id)).save()
def _handle_assessment(user_id, ovc_id, assessments, date_of_assessment):
if not assessments or not date_of_assessment:
return
cache_key = "assessment_offline_{}".format(ovc_id)
assessments_to_add = []
for assessment in assessments:
not_added = _add_assessments_to_cache(
cache_key,
assessment['olmis_assessment_domain'],
assessment['olmis_assessment_coreservice'],
assessment['olmis_assessment_coreservice_status'],
date_of_assessment)
for item in not_added:
assessments_to_add.append(item)
if assessments_to_add:
service_grouping_id = new_guid_32()
ovc_care_event_id = _create_ovc_care_event(user_id, ovc_id, date_of_assessment)
for item in assessments_to_add:
events = item.split("#")
OVCCareAssessment(
domain=events[0],
service=events[1],
service_status=events[2],
event=OVCCareEvents.objects.get(pk=ovc_care_event_id),
service_grouping_id=service_grouping_id
).save()
def _add_assessments_to_cache(cache_key, domain, service, status, date_of_assessment):
statuses = status.split(",")
statuses_per_domain_service = []
for status in statuses:
statuses_per_domain_service.append("{}#{}#{}#{}".format(domain, service, status, date_of_assessment))
assessments_to_add = []
assessments_from_cache = _get_decoded_list_from_cache(cache_key)
for assessment in statuses_per_domain_service:
if assessment not in assessments_from_cache:
assessments_from_cache.append(assessment)
assessments_to_add.append(assessment)
_add_list_items_to_cache(cache_key, assessments_from_cache)
return assessments_to_add
def _handle_priority(user_id, ovc_id, priorities, date_of_priority):
if not priorities or not date_of_priority:
return
cache_key = "priority_offline_{}".format(ovc_id)
priority_to_add = []
for priority in priorities:
not_added = _add_priority_to_cache(
cache_key,
priority['olmis_priority_domain'],
priority['olmis_priority_service'],
date_of_priority)
for item in not_added:
priority_to_add.append(item)
if priority_to_add:
service_grouping_id = new_guid_32()
ovc_care_event_id = _create_ovc_care_event(user_id, ovc_id, date_of_priority)
for item in priority_to_add:
events = item.split("#")
OVCCarePriority(
domain=events[0],
service=events[1],
event=OVCCareEvents.objects.get(pk=ovc_care_event_id),
service_grouping_id=service_grouping_id
).save()
def _add_priority_to_cache(cache_key, domain, service, date_of_priority):
services = service.split(",")
service_per_domain = []
for service in services:
service_per_domain.append("{}#{}#{}".format(domain, service, date_of_priority))
priorities_to_to_add = []
priorities_from_cache = _get_decoded_list_from_cache(cache_key)
for priority in service_per_domain:
if priority not in priorities_from_cache:
priorities_from_cache.append(priority)
priorities_to_to_add.append(priority)
_add_list_items_to_cache(cache_key, priorities_from_cache)
return priorities_to_to_add
def _handle_services(user_id, ovc_id, services, date_of_service, org_unit_primary, org_unit_attached):
if not services or not date_of_service:
return
cache_key = "service_offline_{}".format(ovc_id)
services_to_add = []
for service in services:
not_added = _add_service_to_cache(
cache_key,
service['olmis_domain'],
service['olmis_service'],
service['olmis_service_date'],
date_of_service)
for item in not_added:
services_to_add.append(item)
if services_to_add:
service_grouping_id = new_guid_32()
ovc_care_event_id = _create_ovc_care_event(user_id, ovc_id, date_of_service)
org_unit = org_unit_primary if org_unit_primary else org_unit_attached[0]
for item in services_to_add:
events = item.split("#")
OVCCareServices(
domain=events[0],
service_provided=events[1],
date_of_encounter_event=convert_date(events[2]) if not events[2] or events[2] != 'None' or events[2] != '' else None,
service_provider=org_unit,
event=OVCCareEvents.objects.get(pk=ovc_care_event_id),
service_grouping_id=service_grouping_id
).save()
def _add_service_to_cache(cache_key, domain, service_list, service_date, date_of_priority):
services = service_list.split(",")
service_per_domain = []
for service in services:
service_per_domain.append("{}#{}#{}#{}".format(domain, service, service_date, date_of_priority))
services_to_to_add = []
services_from_cache = _get_decoded_list_from_cache(cache_key)
for service in service_per_domain:
if service not in services_from_cache:
services_from_cache.append(service)
services_to_to_add.append(service)
_add_list_items_to_cache(cache_key, services_from_cache)
return services_to_to_add
def save_submitted_form1b(user_id, ovc_id, form_data):
caretaker_id = form_data.get('caretaker_id')
person_id = form_data.get('person_id')
service_date = form_data.get('olmis_service_date')
services = form_data.get('services')
cache_key = "form1b_offline_{}_{}".format(ovc_id, service_date)
is_form1b_submitted = cache.get(cache_key, False)
if not is_form1b_submitted:
logger.info("About to save Form1b for ovc_id: {} | Cache Key: {}".format(ovc_id, cache_key))
domains = {'SC': 'DSHC', 'PS': 'DPSS', 'PG': 'DPRO',
'HE': 'DHES', 'HG': 'DHNU', 'EG': 'DEDU'}
household = get_house_hold(caretaker_id)
household_id = household.id if household else None
event_date = convert_date(service_date)
new_event = OVCCareEvents(
event_type_id='FM1B', created_by=user_id,
person_id=caretaker_id, house_hold_id=household_id,
date_of_event=event_date)
new_event.save()
# Attach services
for service in services:
service = str(service)
domain_id = service[:2]
domain = domains[domain_id]
OVCCareF1B(
event_id=new_event.pk,
domain=domain,
entity=service).save()
cache.set(cache_key, True)
else:
logger.info("Form1B already submitted for ovc_id: {} on date: {} | Cache Key: {}".format(
ovc_id, service_date, cache_key))
def save_submitted_case_plan_template(user_id, ovc_id, form_data):
for i in range(0, len(form_data['domain'])):
domain = form_data['domain'][i]
goal = form_data['goal'][i]
gaps = form_data['gaps'][i]
actions = form_data['actions'][i]
services = form_data['services'][i]
responsible = form_data['responsible'][i]
date = form_data['date'][i]
actual_completion_date = form_data['actual_completion_date'][i]
results = form_data['results'][i]
reasons = form_data['reasons'][i]
cpt_date_caseplan = form_data['cpt_date_caseplan'][i]
cache_key = "_".join([str(ovc_id), domain, goal, gaps, actions, responsible, date, actual_completion_date, results, reasons,
cpt_date_caseplan]).replace(' ', '=')
data_from_cache = json.loads(cache.get(cache_key, json.dumps({'services': [], 'ovc_care_event_id': None})))
services_from_cache = data_from_cache['services']
ovc_care_event_id = data_from_cache['ovc_care_event_id']
services_to_add = []
child = RegPerson.objects.get(id=ovc_id)
house_hold = OVCHouseHold.objects.get(id=OVCHHMembers.objects.get(person=child).house_hold_id)
event_type_id = 'CPAR'
caregiver_id = OVCRegistration.objects.get(person=child).caretaker_id
date_format = '%Y-%m-%d'
if services_from_cache:
for service in services:
if service not in services_from_cache:
services_to_add.append(service)
else:
services_to_add = services
if not services_to_add:
logger.info("No case plan services to add")
return
if not ovc_care_event_id:
event_counter = OVCCareEvents.objects.filter(
event_type_id=event_type_id, person=ovc_id, is_void=False).count()
ovc_care_event = OVCCareEvents.objects.create(
event_type_id=event_type_id,
event_counter=event_counter,
event_score=0,
created_by=user_id,
person=child,
house_hold=house_hold)
else:
ovc_care_event = OVCCareEvents.objects.get(event=ovc_care_event_id)
for service in services_to_add:
services_from_cache.append(service)
OVCCareCasePlan(
domain=domain,
goal=goal,
person_id=child.id,
caregiver=RegPerson.objects.get(id=caregiver_id),
household=house_hold,
need=gaps,
priority=actions,
cp_service=service,
responsible=responsible,
date_of_previous_event=timezone.now(),
date_of_event=convert_date(cpt_date_caseplan, fmt=date_format),
form=OVCCareForms.objects.get(name='OVCCareCasePlan'),
completion_date=convert_date(cpt_date_caseplan, fmt=date_format),
actual_completion_date=convert_date(actual_completion_date, fmt=date_format),
results=results,
reasons=reasons,
case_plan_status='D',
event=ovc_care_event
).save()
cache.set(
cache_key,
json.dumps({'services': services_from_cache, 'ovc_care_event_id': str(ovc_care_event.event)}))
logger.info("Successfully saved Case Plan Template, cache_key: {}".format(cache_key))
|
<filename>zigzag/zigzag.py
from random import random
from typing import List
class Kline:
def __init__(self, idx, high, low) -> None:
self.idx = idx
self.high = high
self.low = low
class Point:
def __init__(self, kline: Kline, is_low) -> None:
self.kline = kline
self.is_low = is_low
class Zigzag:
def __init__(self) -> None:
self.depth = 12
self.deviation = 3.0
self.data: List[Kline] = []
self.points: List[Point] = []
@staticmethod
def find_min(data: List[Kline]):
min = data[0]
for d in data:
if d.low < min.low:
min = d
return min
@staticmethod
def find_max(data: List[Kline]):
max = data[0]
for d in data:
if d.high > max.high:
max = d
return max
def init_points(self):
self.points.clear()
init_low, init_high = self.find_min(self.data[0:self.depth]), self.find_max(self.data[0:self.depth])
if init_low.idx < init_high.idx:
self.points.append(Point(init_low, True))
self.points.append(Point(init_high, False))
else:
self.points.append(Point(init_high, False))
self.points.append(Point(init_low, True))
def init_position(self):
if len(self.points) < 2:
self.init_points()
def find_points(self):
# TODO: 考虑极端情况,单个k线既有最大值,也有最小值
# TODO: 当历史数据即将处理完时,停止处理,信号值为划线分析趋势
previous = self.points[-1]
step = previous.kline.idx + 1
while step < len(self.data):
pivot = self.data[step]
if previous.is_low:
if pivot.low < previous.kline.low:
self.points[-1] = Point(pivot, True)
elif pivot.high > previous.kline.low * (1 + self.deviation/100):
self.points.append(Point(pivot, False))
else:
if pivot.high > previous.kline.high:
self.points[-1] = Point(pivot, False)
elif pivot.low < previous.kline.high * (1 - self.deviation/100):
self.points.append(Point(pivot, True))
previous = self.points[-1]
step = step + 1
if __name__ == "__main__":
z = Zigzag()
high = 10000
low = 10000
for i in range(1000):
is_up = random() > 0.5
if is_up:
low = high
high = high * (1 + random() / 100)
else:
high = low
low = low * (1 - random() / 100)
z.data.append(Kline(i, high, low))
z.init_points()
z.init_position()
z.find_points()
# import matplotlib.pyplot as plt
x, y1, y2 = [], [], []
for d in z.data:
x.append(d.idx)
y1.append(d.low)
y2.append(d.high)
scatter_x1, scatter_y1 = [], []
scatter_x2, scatter_y2 = [], []
for d in z.points:
if d.is_low:
scatter_x1.append(d.kline.idx)
scatter_y1.append(d.kline.low)
else:
scatter_x2.append(d.kline.idx)
scatter_y2.append(d.kline.high)
import matplotlib.pyplot as plt
fig, ax = plt.subplots(num='123')
p1, = ax.plot(x, y1, "g-")
p2, = ax.plot(x, y2, "r-")
x = ax.scatter(x=scatter_x1, y=scatter_y1, s=25, c='black', marker='^')
x = ax.scatter(x=scatter_x2, y=scatter_y2, s=25, c='blue', marker='v')
plt.show()
|
<gh_stars>1-10
#!/usr/bin/env python
#
# Copyright 2020 VMware, Inc.
# SPDX-License-Identifier: BSD-2-Clause OR GPL-3.0-only
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: nsxt_policy_l2_bridge_ep_profile
short_description: Create or Delete a Policy L2 Bridge Endpoint Profile
description:
Creates or deletes a Policy L2 Bridge Endpoint Profile
Required attributes include id and display_name.
version_added: "2.9"
author: <NAME>
options:
hostname:
description: Deployed NSX manager hostname.
required: true
type: str
username:
description: The username to authenticate with the NSX manager.
type: str
password:
description:
- The password to authenticate with the NSX manager.
- Must be specified if username is specified
type: str
ca_path:
description: Path to the CA bundle to be used to verify host's SSL
certificate
type: str
nsx_cert_path:
description: Path to the certificate created for the Principal
Identity using which the CRUD operations should be
performed
type: str
nsx_key_path:
description:
- Path to the certificate key created for the Principal Identity
using which the CRUD operations should be performed
- Must be specified if nsx_cert_path is specified
type: str
request_headers:
description: HTTP request headers to be sent to the host while making
any request
type: dict
display_name:
description:
- Display name.
- If resource ID is not specified, display_name will be used as ID.
required: false
type: str
state:
choices:
- present
- absent
description: "State can be either 'present' or 'absent'.
'present' is used to create or update resource.
'absent' is used to delete resource."
required: true
validate_certs:
description: Enable server certificate verification.
type: bool
default: False
tags:
description: Opaque identifiers meaningful to the API user.
type: dict
suboptions:
scope:
description: Tag scope.
required: true
type: str
tag:
description: Tag value.
required: true
type: str
do_wait_till_create:
type: bool
default: false
description:
- Can be used to wait for the realization of subresource before the
request to create the next resource is sent to the Manager.
- Can be specified for each subresource.
id:
description: The id of the Policy L2 Bridge Endpoint Profile
required: false
type: str
description:
description: Resource description.
type: str
edge_nodes_info:
description:
- List of dicts that comprise of information to form policy paths
to edge nodes. Edge allocation for L2 bridging
- Minimim 1 and Maximum 2 list elements
type: list
element: dict
suboptions:
site_id:
description: site_id where edge node is located
default: default
type: str
enforcementpoint_id:
description: enforcementpoint_id where edge node is
located
default: default
type: str
edge_cluster_id:
description: edge_cluster_id where edge node is located
type: str
edge_cluster_display_name:
description:
- display name of the edge cluster
- either this or edge_cluster_id must be specified. If both
are specified, edge_cluster_id takes precedence
type: str
edge_node_id:
description: ID of the edge node
type: str
edge_node_display_name:
description:
- Display name of the edge node.
- either this or edge_node_id must be specified. If both
are specified, edge_node_id takes precedence
type: str
failover_mode:
description: Failover mode for the edge bridge cluster
type: str
default: PREEMPTIVE
choices:
- PREEMPTIVE
- NON_PREEMPTIVE
ha_mode:
description: High avaialability mode can be active-active or
active-standby. High availability mode cannot be modified
after realization
type: str
default: ACTIVE_STANDBY
choices:
- ACTIVE_STANDBY
'''
EXAMPLES = '''
- name: create L2 Bridge Endpoint Profile
nsxt_policy_l2_bridge_ep_profile:
hostname: "10.10.10.10"
nsx_cert_path: /root/com.vmware.nsx.ncp/nsx.crt
nsx_key_path: /root/com.vmware.nsx.ncp/nsx.key
validate_certs: False
id: test-ep-profile
display_name: test-ep-profile
state: present
edge_nodes_info:
- edge_cluster_display_name: edge-cluster-1
edge_node_id: 123471da-3823-11ea-9170-000c291a8262
failover_mode: PREEMPTIVE
ha_mode: ACTIVE_STANDBY
tags:
- tag: "my-tag"
scope: "my-scope"
'''
RETURN = '''# '''
import json
import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.nsxt_base_resource import NSXTBaseRealizableResource
from ansible.module_utils.nsxt_resource_urls import (
EDGE_CLUSTER_URL, EDGE_NODE_URL, L2_BRIDGE_EP_PROFILE_URL)
from ansible.module_utils.policy_resource_specs.l2_bridge_ep_profile import (
SPEC as L2BridgeEpProfileSpec)
from ansible.module_utils._text import to_native
class NSXTL2BridgeEpProfile(NSXTBaseRealizableResource):
@staticmethod
def get_resource_spec():
return L2BridgeEpProfileSpec
@staticmethod
def get_resource_base_url(baseline_args=None):
return L2_BRIDGE_EP_PROFILE_URL.format(
baseline_args['site_id'], baseline_args['enforcementpoint_id'])
def update_resource_params(self, nsx_resource_params):
nsx_resource_params.pop('site_id')
nsx_resource_params.pop('enforcementpoint_id')
edge_nodes_info = nsx_resource_params.pop(
"edge_nodes_info")
nsx_resource_params["edge_paths"] = []
for edge_node_info in edge_nodes_info:
site_id = edge_node_info['site_id']
enforcementpoint_id = edge_node_info['enforcementpoint_id']
edge_cluster_base_url = (
EDGE_CLUSTER_URL.format(site_id, enforcementpoint_id))
edge_cluster_id = self.get_id_using_attr_name_else_fail(
"edge_cluster", edge_node_info,
edge_cluster_base_url, "Edge Cluster")
edge_node_base_url = EDGE_NODE_URL.format(
site_id, enforcementpoint_id, edge_cluster_id)
edge_node_id = self.get_id_using_attr_name_else_fail(
"edge_node", edge_node_info,
edge_node_base_url, "Edge Node")
nsx_resource_params["edge_paths"].append(
edge_node_base_url + "/" + edge_node_id)
if __name__ == '__main__':
l2_bridge_ep_profile = NSXTL2BridgeEpProfile()
l2_bridge_ep_profile.realize(baseline_arg_names=[
'site_id', 'enforcementpoint_id'])
|
<gh_stars>1-10
# coding: utf-8
from ctypes import *
import sys,getopt,time
###########################################
class VSC_level_desc(Structure):
_fields_ = [
("verbosity" ,c_uint), #unsigned verbosity;
("label", c_char_p), #const char *label; /* label */
("sdesc", c_char_p), #const char *sdesc; /* short description */
("ldesc", c_char_p), #const char *ldesc; /* long description */
]
class VSC_type_desc(Structure):
_fields_ = [
("label", c_char_p), #const char *label; /* label */
("sdesc", c_char_p), #const char *sdesc; /* short description */
("ldesc", c_char_p), #const char *ldesc; /* long description */
]
class VSM_fantom(Structure):
_fields_ = [
("chunk", c_void_p), #struct VSM_chunk *chunk;
("b", c_void_p), #void *b; /* first byte of payload */
("e", c_void_p), #void *e; /* first byte past payload */
#("priv", c_uint), #uintptr_t priv; /* VSM private */
("priv", c_void_p), #uintptr_t priv; /* VSM private */
("_class", c_char * 8), #char class[VSM_MARKER_LEN];
("type", c_char * 8), #char type[VSM_MARKER_LEN];
("ident", c_char * 128), #char ident[VSM_IDENT_LEN];
]
class VSC_section(Structure):
_fields_ = [
("type", c_char_p), #const char *type;
("ident", c_char_p), #const char *ident;
("desc", POINTER(VSC_type_desc)), #const struct VSC_type_desc *desc;
("fantom", POINTER(VSM_fantom)), #struct VSM_fantom *fantom;
]
class VSC_desc(Structure):
_fields_ = [
("name", c_char_p), #const char *name; /* field name */
("fmt", c_char_p), #const char *fmt; /* field format ("uint64_t") */
("flag", c_int), #int flag; /* 'c' = counter, 'g' = gauge */
("sdesc", c_char_p), #const char *sdesc; /* short description */
("ldesc", c_char_p), #const char *ldesc; /* long description */
("level", POINTER(VSC_level_desc)), #const struct VSC_level_desc *level;
]
class VSC_point(Structure):
_fields_ = [
("desc", POINTER(VSC_desc)), #const struct VSC_desc *desc; /* point description */
#("ptr", c_void_p), #const volatile void *ptr; /* field value */
("ptr", POINTER(c_ulonglong)), #const volatile void *ptr; /* field value */
("section", POINTER(VSC_section)), #const struct VSC_section *section;
]
#typedef int VSC_iter_f(void *priv, const struct VSC_point *const pt);
VSC_iter_f = CFUNCTYPE(
c_int,
c_void_p,
POINTER(VSC_point)
)
###########################################
class VSLC_ptr(Structure):
_fields_ = [
("ptr" , POINTER(c_uint32)), #const uint32_t *ptr; /* Record pointer */
("priv", c_uint), #unsigned priv;
]
class VSL_cursor(Structure):
_fields_ = [
("rec" , VSLC_ptr), #struct VSLC_ptr rec;
("priv_tbl", c_void_p), #const void *priv_tbl;
("priv_data", c_void_p), #void *priv_data;
]
class VSL_transaction(Structure):
_fields_ = [
("level" , c_uint), #unsigned level;
("vxid", c_int32), #int32_t vxid;
("vxid_parent", c_int32), #int32_t vxid_parent;
("type", c_int), #enum VSL_transaction_e type;
("reason", c_int), #enum VSL_reason_e reason;
("c", POINTER(VSL_cursor)), #struct VSL_cursor *c;
]
class VTAILQ_HEAD(Structure):
_fields_ = [
("vtqh_first" , c_void_p), #struct type *vtqh_first; /* first element */ \
("vtqh_last", POINTER(c_void_p)), #struct type **vtqh_last; /* addr of last next element */ \
]
class vbitmap(Structure):
_fields_ = [
("bits" , c_void_p), #VBITMAP_TYPE *bits;
("nbits", c_uint), #unsigned nbits;
]
class vsb(Structure):
_fields_ = [
("magic" , c_uint), #unsigned magic;
("s_buf", c_char_p), #char *s_buf; /* storage buffer */
("s_error", c_int), #int s_error; /* current error code */
#("s_size", c_ssize_t), #ssize_t s_size; /* size of storage buffer */
#("s_len", c_ssize_t), #ssize_t s_len; /* current length of string */
("s_size", c_long), #ssize_t s_size; /* size of storage buffer */
("s_len", c_long), #ssize_t s_len; /* current length of string */
("s_flags", c_int), #int s_flags; /* flags */
]
class VSL_data(Structure):
_fields_ = [
("magic", c_uint), #unsigned magic;
("diag", POINTER(vsb)), #struct vsb *diag;
("flags", c_uint), #unsigned flags;
("vbm_select", POINTER(vbitmap)), #struct vbitmap *vbm_select;
("vbm_supress", POINTER(vbitmap)), #struct vbitmap *vbm_supress;
("vslf_select", VTAILQ_HEAD), #vslf_list vslf_select;
("vslf_suppress", VTAILQ_HEAD), #vslf_list vslf_suppress;
("b_opt", c_int), #int b_opt;
("c_opt", c_int), #int c_opt;
("C_opt", c_int), #int C_opt;
("L_opt", c_int), #int L_opt;
("T_opt", c_double), #double T_opt;
("v_opt", c_int), #int v_opt;
]
#typedef int VSLQ_dispatch_f(struct VSL_data *vsl, struct VSL_transaction * const trans[], void *priv);
VSLQ_dispatch_f = CFUNCTYPE(
c_int,
POINTER(VSL_data),
POINTER(POINTER(VSL_transaction)),
c_void_p
)
class VarnishAPIDefine40:
def __init__(self):
self.VSL_COPT_TAIL = (1 << 0)
self.VSL_COPT_BATCH = (1 << 1)
self.VSL_COPT_TAILSTOP = (1 << 2)
self.SLT_F_BINARY = (1 << 1)
'''
//////////////////////////////
enum VSL_transaction_e {
VSL_t_unknown,
VSL_t_sess,
VSL_t_req,
VSL_t_bereq,
VSL_t_raw,
VSL_t__MAX,
};
'''
self.VSL_t_unknown = 0
self.VSL_t_sess = 1
self.VSL_t_req = 2
self.VSL_t_bereq = 3
self.VSL_t_raw = 4
self.VSL_t__MAX = 5
'''
//////////////////////////////
enum VSL_reason_e {
VSL_r_unknown,
VSL_r_http_1,
VSL_r_rxreq,
VSL_r_esi,
VSL_r_restart,
VSL_r_pass,
VSL_r_fetch,
VSL_r_bgfetch,
VSL_r_pipe,
VSL_r__MAX,
};
'''
self.VSL_r_unknown = 0
self.VSL_r_http_1 = 1
self.VSL_r_rxreq = 2
self.VSL_r_esi = 3
self.VSL_r_restart = 4
self.VSL_r_pass = 5
self.VSL_r_fetch = 6
self.VSL_r_bgfetch = 7
self.VSL_r_pipe = 8
self.VSL_r__MAX = 9
class LIBVARNISHAPI13:
def __init__(self,lib):
self.VSL_CursorFile = lib.VSL_CursorFile
self.VSL_CursorFile.restype = c_void_p
self.VSL_CursorVSM = lib.VSL_CursorVSM
self.VSL_CursorVSM.restype = c_void_p
self.VSL_Error = lib.VSL_Error
self.VSL_Error.restype = c_char_p
self.VSM_Error = lib.VSM_Error
self.VSM_Error.restype = c_char_p
self.VSM_Name = lib.VSM_Name
self.VSM_Name.restype = c_char_p
self.VSLQ_New = lib.VSLQ_New
self.VSLQ_New.restype = c_void_p
self.VSLQ_New.argtypes = [c_void_p, POINTER(c_void_p),c_int,c_char_p]
self.VSLQ_Delete = lib.VSLQ_Delete
self.VSLQ_Delete.argtypes = [POINTER(c_void_p)]
#self.VSLQ_Dispatch = lib.VSLQ_Dispatch
#self.VSLQ_Dispatch.restype = c_int
#self.VSLQ_Dispatch.argtypes = (c_void_p, CFUNCTYPE ,c_void_p)
class VSLUtil:
def tag2Var(self, tag, data):
ret = {'key':'','val':'','vkey':''}
if not self.__tags.has_key(tag):
return ret
r = self.__tags[tag]
ret['vkey'] = r.split(' ',1)[-1].split('.',1)[0]
if r == '':
return ret
elif r[-1:] == '.':
spl = data.split(': ',1)
ret['key'] = r + spl[0]
ret['val'] = spl[1]
else:
ret['key'] = r
ret['val'] = data
return (ret)
def tag2VarName(self, tag, data):
return self.tag2Var(tag, data)['key']
__tags = {
'Debug' : '',
'Error' : '',
'CLI' : '',
'SessOpen' : '',
'SessClose' : '',
'BackendOpen' : '', #Change key count at varnish41(4->6)
'BackendReuse' : '',
'BackendClose' : '',
'HttpGarbage' : '',
'Backend' : '',
'Length' : '',
'FetchError' : '',
'BogoHeader' : '',
'LostHeader' : '',
'TTL' : '',
'Fetch_Body' : '',
'VCL_acl' : '',
'VCL_call' : '',
'VCL_trace' : '',
'VCL_return' : '',
'ReqStart' : 'client.ip',
'Hit' : '',
'HitPass' : '',
'ExpBan' : '',
'ExpKill' : '',
'WorkThread' : '',
'ESI_xmlerror' : '',
'Hash' : '', #Change log data type(str->bin)
'Backend_health' : '',
'VCL_Log' : '',
'VCL_Error' : '',
'Gzip' : '',
'Link' : '',
'Begin' : '',
'End' : '',
'VSL' : '',
'Storage' : '',
'Timestamp' : '',
'ReqAcct' : '',
'ESI_BodyBytes' : '', #Only Varnish40X
'PipeAcct' : '',
'BereqAcct' : '',
'ReqMethod' : 'req.method',
'ReqURL' : 'req.url',
'ReqProtocol' : 'req.proto',
'ReqStatus' : '',
'ReqReason' : '',
'ReqHeader' : 'req.http.',
'ReqUnset' : 'unset req.http.',
'ReqLost' : '',
'RespMethod' : '',
'RespURL' : '',
'RespProtocol' : 'resp.proto',
'RespStatus' : 'resp.status',
'RespReason' : 'resp.reason',
'RespHeader' : 'resp.http.',
'RespUnset' : 'unset resp.http.',
'RespLost' : '',
'BereqMethod' : 'bereq.method',
'BereqURL' : 'bereq.url',
'BereqProtocol' : 'bereq.proto',
'BereqStatus' : '',
'BereqReason' : '',
'BereqHeader' : 'bereq.http.',
'BereqUnset' : 'unset bereq.http.',
'BereqLost' : '',
'BerespMethod' : '',
'BerespURL' : '',
'BerespProtocol' : 'beresp.proto',
'BerespStatus' : 'beresp.status',
'BerespReason' : 'beresp.reason',
'BerespHeader' : 'beresp.http.',
'BerespUnset' : 'unset beresp.http.',
'BerespLost' : '',
'ObjMethod' : '',
'ObjURL' : '',
'ObjProtocol' : 'obj.proto',
'ObjStatus' : 'obj.status',
'ObjReason' : 'obj.reason',
'ObjHeader' : 'obj.http.',
'ObjUnset' : 'unset obj.http.',
'ObjLost' : '',
'Proxy' : '', #Only Varnish41x
'ProxyGarbage' : '', #Only Varnish41x
'VfpAcct' : '', #Only Varnish41x
'Witness' : '', #Only Varnish41x
}
class VarnishAPI:
def __init__(self, sopath = 'libvarnishapi.so.1'):
self.lib = cdll[sopath]
self.lva = LIBVARNISHAPI13(self.lib)
self.defi = VarnishAPIDefine40()
self.__cb = None
self.vsm = self.lib.VSM_New()
self.d_opt = 0
VSLTAGS = c_char_p * 256
self.VSL_tags = VSLTAGS.in_dll(self.lib, "VSL_tags")
VSLTAGFLAGS = c_uint * 256
self.VSL_tagflags = VSLTAGFLAGS.in_dll(self.lib, "VSL_tagflags")
VSLQGROUPING = c_char_p * 4
self.VSLQ_grouping = VSLQGROUPING.in_dll(self.lib, "VSLQ_grouping")
self.error = ''
def ArgDefault(self, op, arg):
if op == "n":
#インスタンス指定
i = self.lib.VSM_n_Arg(self.vsm, arg)
if i <= 0:
error = "%s" % self.lib.VSM_Error(self.vsm).rstrip()
return(i)
elif op == "N":
#VSMファイル指定
i = self.lib.VSM_N_Arg(self.vsm, arg)
if i <= 0:
error = "%s" % self.lib.VSM_Error(self.vsm).rstrip()
return(i)
self.d_opt = 1
return(None)
class VarnishStat(VarnishAPI):
def __init__(self, opt='', sopath = 'libvarnishapi.so.1'):
VarnishAPI.__init__(self,sopath)
self.name = ''
if len(opt)>0:
self.__setArg(opt)
if self.lib.VSM_Open(self.vsm):
self.error = "Can't open VSM file (%s)" % self.lib.VSM_Error(self.vsm).rstrip()
else:
self.name = self.lva.VSM_Name(self.vsm)
def __setArg(self,opt):
opts, args = getopt.getopt(opt,"N:n:")
error = 0
for o in opts:
op = o[0].lstrip('-')
arg = o[1]
self.__Arg(op,arg)
if error:
self.error = error
return(0)
return(1)
def __Arg(self, op, arg):
#default
i = VarnishAPI.ArgDefault(self,op, arg)
if i < 0:
return(i)
def __getstat(self, priv, pt):
if not bool(pt):
return(0)
val = pt[0].ptr[0]
sec = pt[0].section
key = ''
type = sec[0].fantom[0].type
ident = sec[0].fantom[0].ident
if type != '':
key += type + '.'
if ident != '':
key += ident + '.'
key += pt[0].desc[0].name
self.__buf[key]={'val':val,'desc':pt[0].desc[0].sdesc}
return(0)
def getStats(self):
self.__buf = {}
self.lib.VSC_Iter(self.vsm, None, VSC_iter_f(self.__getstat), None);
return self.__buf
def Fini(self):
if self.vsm:
self.lib.VSM_Delete(self.vsm)
self.vsm = 0
class VarnishLog(VarnishAPI):
def __init__(self, opt = '', sopath = 'libvarnishapi.so.1'):
VarnishAPI.__init__(self,sopath)
self.vut = VSLUtil()
self.vsl = self.lib.VSL_New()
self.vslq = None
self.__g_arg = 0
self.__q_arg = None
self.__r_arg = 0
self.name = ''
if len(opt)>0:
self.__setArg(opt)
self.__Setup()
def __setArg(self,opt):
opts, args = getopt.getopt(opt,"bcCdx:X:r:q:N:n:I:i:g:")
error = 0
for o in opts:
op = o[0].lstrip('-')
arg = o[1]
self.__Arg(op,arg)
#Check
if self.__r_arg and self.vsm:
error = "Can't have both -n and -r options"
if error:
self.error = error
return(0)
return(1)
def __Arg(self, op, arg):
i = VarnishAPI.ArgDefault(self,op, arg)
if i != None:
return(i)
if op == "d":
#先頭から
self.d_opt = 1
elif op == "g":
#グルーピング指定
self.__g_arg = self.__VSLQ_Name2Grouping(arg)
if self.__g_arg == -2:
error = "Ambiguous grouping type: %s" % (arg)
return(self.__g_arg)
elif self.__g_arg < 0:
error = "Unknown grouping type: %s" % (arg)
return(self.__g_arg)
#elif op == "P":
# #PID指定は対応しない
elif op == "q":
#VSL-query
self.__q_arg = arg
elif op == "r":
#バイナリファイル
self.__r_arg = arg
else:
#default
i = self.__VSL_Arg(op, arg);
if i < 0:
error = "%s" % self.lib.VSL_Error(self.vsl)
return(i)
def __Setup(self):
if self.__r_arg:
c = self.lva.VSL_CursorFile(self.vsl, self.__r_arg, 0);
else:
if self.lib.VSM_Open(self.vsm):
self.error = "Can't open VSM file (%s)" % self.lib.VSM_Error(self.vsm).rstrip()
return(0)
self.name = self.lva.VSM_Name(self.vsm)
c = self.lva.VSL_CursorVSM(self.vsl, self.vsm,
(self.defi.VSL_COPT_TAILSTOP if self.d_opt else self.defi.VSL_COPT_TAIL) | self.defi.VSL_COPT_BATCH
)
if not c:
self.error = "Can't open log (%s)" % self.lva.VSL_Error(self.vsl)
print self.error
return(0)
#query
z = cast(c,c_void_p)
self.vslq = self.lva.VSLQ_New(self.vsl,z, self.__g_arg, self.__q_arg);
if not self.vslq:
self.error = "Query expression error:\n%s" % self.lib.VSL_Error(self.vsl)
return(0)
return(1)
def __cbMain(self,cb,priv=None):
self.__cb = cb
self.__priv = priv
if not self.vslq:
#Reconnect VSM
time.sleep(0.1)
if self.lib.VSM_Open(self.vsm):
self.lib.VSM_ResetError(self.vsm)
return(1)
c = self.lva.VSL_CursorVSM(self.vsl, self.vsm,self.defi.VSL_COPT_TAIL | self.defi.VSL_COPT_BATCH);
if not c:
self.lib.VSM_ResetError(self.vsm)
self.lib.VSM_Close(self.vsm)
return(1)
z = cast(c,c_void_p)
self.vslq = self.lva.VSLQ_New(self.vsl, z, self.__g_arg, self.__q_arg);
self.error = 'Log reacquired'
i = self.lib.VSLQ_Dispatch(self.vslq, VSLQ_dispatch_f(self.__callBack), None);
return(i)
def Dispatch(self,cb,priv=None):
i = self.__cbMain(cb,priv)
if i > -2:
return i
if not self.vsm:
return i
self.lib.VSLQ_Flush(self.vslq, VSLQ_dispatch_f(self.__callBack), None);
self.lva.VSLQ_Delete(byref(cast(self.vslq,c_void_p)))
self.vslq = None
if i == -2:
self.error = "Log abandoned"
self.lib.VSM_Close(self.vsm)
if i < -2:
self.error = "Log overrun"
return i
def Fini(self):
if self.vslq:
self.lva.VSLQ_Delete(byref(cast(self.vslq,c_void_p)))
self.vslq = 0
if self.vsl:
self.lib.VSL_Delete(self.vsl)
self.vsl = 0
if self.vsm:
self.lib.VSM_Delete(self.vsm)
self.vsm = 0
def __VSL_Arg(self, opt, arg = '\0'):
return self.lib.VSL_Arg(self.vsl, ord(opt), arg)
def __VSLQ_Name2Grouping(self, arg):
return self.lib.VSLQ_Name2Grouping(arg, -1)
def __callBack(self,vsl, pt, fo):
idx = -1
while 1:
idx += 1
t = pt[idx]
if not bool(t):
break
tra=t[0]
c =tra.c[0]
cbd = {
'level' : tra.level,
'vxid' : tra.vxid,
'vxid_parent' : tra.vxid_parent,
'reason' : tra.reason,
}
if vsl[0].c_opt or vsl[0].b_opt:
if tra.type == self.defi.VSL_t_req and not vsl[0].c_opt:
continue
elif tra.type == self.defi.VSL_t_bereq and not vsl[0].b_opt:
continue
elif tra.type != self.defi.VSL_t_raw:
continue
while 1:
i = self.lib.VSL_Next(tra.c);
if i < 0:
return (i)
if i == 0:
break
if not self.lib.VSL_Match(self.vsl, tra.c):
continue
#decode vxid type ...
length =c.rec.ptr[0] & 0xffff
cbd['length']=length
cbd['data'] =string_at(c.rec.ptr,length + 8)[8:]
tag =c.rec.ptr[0] >> 24
cbd['tag'] =tag
if c.rec.ptr[1] &(1<< 30):
cbd['type'] = 'c'
elif c.rec.ptr[1] &(1<< 31):
cbd['type'] = 'b'
else:
cbd['type'] = '-'
cbd['isbin'] = self.VSL_tagflags[tag] & self.defi.SLT_F_BINARY
if self.__cb:
self.__cb(self,cbd,self.__priv)
return(0)
|
<gh_stars>10-100
import asyncio
import webbrowser
from logging import getLogger
from typing import List
from kivymd.uix.list import ImageLeftWidget, OneLineListItem, ThreeLineAvatarIconListItem
from naturtag.app import get_app
from naturtag.controllers import Controller, TaxonBatchLoader
from naturtag.models import Taxon, get_icon_path
from naturtag.widgets import StarButton
logger = getLogger().getChild(__name__)
class TaxonViewController(Controller):
"""Controller class to manage displaying info about a selected taxon"""
def __init__(self, screen):
super().__init__(screen)
# Controls
self.taxon_link = screen.taxon_links.ids.selected_taxon_link_button
self.taxon_parent_button = screen.taxon_links.ids.taxon_parent_button
self.taxon_parent_button.bind(on_release=lambda x: self.select_taxon(x.taxon.parent))
# Outputs
self.selected_taxon = None
self.taxon_photo = screen.selected_taxon_photo
self.taxon_ancestors_label = screen.taxonomy_section.ids.taxon_ancestors_label
self.taxon_children_label = screen.taxonomy_section.ids.taxon_children_label
self.taxon_ancestors = screen.taxonomy_section.ids.taxon_ancestors
self.taxon_children = screen.taxonomy_section.ids.taxon_children
self.basic_info = screen.basic_info_section
def select_taxon(
self,
taxon_obj: Taxon = None,
taxon_dict: dict = None,
id: int = None,
if_empty: bool = False,
):
"""Update taxon info display by either object, ID, partial record, or complete record"""
# Initialize from object, dict, or ID
if if_empty and self.selected_taxon is not None:
return
if not any([taxon_obj, taxon_dict, id]):
return
if not taxon_obj:
taxon_obj = Taxon.from_json(taxon_dict) if taxon_dict else Taxon.from_id(int(id))
# Don't need to do anything if this taxon is already selected
if self.selected_taxon is not None and taxon_obj.id == self.selected_taxon.id:
return
logger.info(f'Taxon: Selecting taxon {taxon_obj.id}')
self.basic_info.clear_widgets()
self.selected_taxon = taxon_obj
asyncio.run(self.load_taxon_info())
# Add to taxon history, and update taxon id on image selector screen
get_app().update_history(self.selected_taxon.id)
get_app().select_taxon_from_photo(self.selected_taxon.id)
async def load_taxon_info(self):
await asyncio.gather(
self.load_photo_section(),
self.load_basic_info_section(),
self.load_taxonomy(),
)
async def load_photo_section(self):
"""Load taxon photo + links"""
logger.info('Taxon: Loading photo section')
if self.selected_taxon.default_photo.medium_url:
self.taxon_photo.source = self.selected_taxon.default_photo.medium_url
# Configure link to iNaturalist page
self.taxon_link.bind(on_release=lambda *x: webbrowser.open(self.selected_taxon.url))
self.taxon_link.tooltip_text = self.selected_taxon.url
self.taxon_link.disabled = False
# Configure 'View parent' button
if self.selected_taxon.parent:
self.taxon_parent_button.disabled = False
self.taxon_parent_button.taxon = self.selected_taxon
self.taxon_parent_button.tooltip_text = f'Go to {self.selected_taxon.parent.name}'
else:
self.taxon_parent_button.disabled = True
self.taxon_parent_button.tooltip_text = ''
async def load_basic_info_section(self):
"""Load basic info for the currently selected taxon"""
# Name, rank
logger.info('Taxon: Loading basic info section')
item = ThreeLineAvatarIconListItem(
text=self.selected_taxon.name,
secondary_text=self.selected_taxon.rank.title(),
tertiary_text=self.selected_taxon.preferred_common_name,
)
# Icon (if available)
icon_path = get_icon_path(self.selected_taxon.iconic_taxon_id)
if icon_path:
item.add_widget(ImageLeftWidget(source=icon_path))
self.basic_info.add_widget(item)
# Star Button
star_icon = StarButton(
self.selected_taxon.id,
is_selected=get_app().is_starred(self.selected_taxon.id),
)
star_icon.bind(on_release=self.on_star)
item.add_widget(star_icon)
# Other attrs
for k in ['id', 'is_active', 'observations_count', 'complete_species_count']:
label = k.title().replace('_', ' ')
value = getattr(self.selected_taxon, k)
item = OneLineListItem(text=f'{label}: {value}')
self.basic_info.add_widget(item)
async def load_taxonomy(self):
"""Populate ancestors and children for the currently selected taxon"""
total_taxa = len(self.selected_taxon.parent_taxa) + len(self.selected_taxon.child_taxa)
# Set up batch loader + event bindings
if self.loader:
self.loader.cancel()
self.loader = TaxonBatchLoader()
self.start_progress(total_taxa, self.loader)
# Start loading ancestors
logger.info(f'Taxon: Loading {len(self.selected_taxon.parent_taxa)} ancestors')
self.taxon_ancestors_label.text = _get_label('Ancestors', self.selected_taxon.parent_taxa)
self.taxon_ancestors.clear_widgets()
self.loader.add_batch(self.selected_taxon.ancestor_ids, parent=self.taxon_ancestors)
logger.info(f'Taxon: Loading {len(self.selected_taxon.child_taxa)} children')
self.taxon_children_label.text = _get_label('Children', self.selected_taxon.child_taxa)
self.taxon_children.clear_widgets()
self.loader.add_batch(self.selected_taxon.child_ids, parent=self.taxon_children)
self.loader.start_thread()
def on_star(self, button):
"""Either add or remove a taxon from the starred list"""
if button.is_selected:
get_app().add_star(self.selected_taxon.id)
else:
get_app().remove_star(self.selected_taxon.id)
def _get_label(text: str, items: List) -> str:
return text + (f' ({len(items)})' if items else '')
|
import numpy as np
from scipy.special import ndtr,log_ndtr
from reciprocalspaceship.utils import compute_structurefactor_multiplicity
def _acentric_posterior(Iobs, SigIobs, Sigma):
"""
Compute the mean and std deviation of the truncated normal
French-Wiilson posterior.
Parameters
----------
Iobs : np.ndarray (float)
Observed merged refl intensities
SigIobs : np.ndarray (float)
Observed merged refl std deviation
Sigma : np.ndarray (float)
Average intensity in the resolution bin corresponding to Iobs, SigIobs
"""
Iobs = np.array(Iobs, dtype=np.float64)
SigIobs = np.array(SigIobs, dtype=np.float64)
Sigma = np.array(Sigma, dtype=np.float64)
def log_phi(x):
#return np.exp(-0.5*x**2)/np.sqrt(2*np.pi)
return -0.5*x**2 - np.log(np.sqrt(2*np.pi))
a = 0.
s = SigIobs
u = (Iobs - s**2/Sigma)
alpha = (a-u)/s
#Z = 1. - ndtr(alpha)
log_Z = log_ndtr(-alpha) #<--this is the same thing, I promise
#mean = u + s * phi(alpha)/Z
mean = u + np.exp(np.log(s) + log_phi(alpha) - log_Z)
variance = s**2 * (1 + \
#alpha*phi(alpha)/Z - \
alpha * np.exp(log_phi(alpha) - log_Z) - \
#(phi(alpha)/Z)**2
np.exp(2. * log_phi(alpha) - 2. * log_Z)
)
return mean, np.sqrt(variance)
def _centric_posterior_quad(Iobs, SigIobs, Sigma, npoints=100):
"""
Use Gaussian-Legendre quadrature to estimate posterior intensities
under a Wilson prior.
Parameters
----------
Iobs : array (float)
Observed merged refl intensities
SigIobs : array (float)
Observed merged refl std deviation
Sigma : array (float)
Average intensity in the resolution bin corresponding to Iobs, SigIobs
npoints : int
Number of sample points and weights (must be >= 1)
"""
Iobs = np.array(Iobs, dtype=np.float64)
SigIobs = np.array(SigIobs, dtype=np.float64)
Sigma = np.array(Sigma, dtype=np.float64)
loc = Iobs-SigIobs**2/2/Sigma
scale = SigIobs
upper = np.abs(Iobs) + 10.*SigIobs
lower = 0.
upper = upper[:,None]
grid,weights = np.polynomial.legendre.leggauss(npoints)
weights = weights[None,:]
grid = grid[None,:]
J = (upper - lower)*grid/2. + (upper + lower) / 2.
prefactor = (upper - lower)/2.
scale = scale[:,None]
loc = loc[:,None]
P = np.power(J, -0.5)*np.exp(-0.5*((J-loc)/scale)**2)
Z = np.sum(prefactor*weights*P, axis=1)[:,None]
mean = np.sum(prefactor*weights*J*P/Z, axis=1)
variance = np.sum(prefactor*weights*J*J*P/Z, axis=1) - mean**2
return mean,np.sqrt(variance)
def mean_intensity_by_miller_index(I, H, bandwidth):
"""
Use a gaussian kernel smoother to compute mean intensities as a function of miller index.
Parameters
----------
I : array
Array of observed intensities
H : array
Nx3 array of miller indices
bandwidth : float(optional)
Kernel bandwidth in miller units
Returns
-------
Sigma : array
Array of point estimates for the mean intensity at each miller index in H.
"""
H = np.array(H, dtype=np.float32)
I = np.array(I, dtype=np.float32)
bandwidth = np.float32(bandwidth)**2.
n = len(I)
S = np.zeros(n)
for i in range(n):
K = np.exp(-0.5*((H - H[i])*(H - H[i])).sum(1)/bandwidth)
S[i] = (I*K).sum()/K.sum()
return S
def mean_intensity_by_resolution(I, dHKL, bins=50, gridpoints=None):
"""
Use a gaussian kernel smoother to compute mean intensities as a function of resolution.
The kernel smoother is evaulated over the specified number of gridpoints and then interpolated.
Kernel bandwidth is derived from `bins` as follows
>>> X = dHKL**-2
bw = (X.max() - X.min)/bins
Parameters
----------
I : array
Array of observed intensities
dHKL : array
Array of reflection resolutions
bins : float(optional)
"bins" is used to determine the kernel bandwidth.
gridpoints : int(optional)
Number of gridpoints at which to estimate the mean intensity. This will default to 20*bins
Returns
-------
Sigma : array
Array of point estimates for the mean intensity at resolution in dHKL.
"""
#Use double precision
I = np.array(I, dtype=np.float64)
dHKL = np.array(dHKL, dtype=np.float64)
if gridpoints is None:
gridpoints = int(bins*20)
X = dHKL**-2.
bw = (X.max() - X.min())/bins
#Evaulate the kernel smoother over grid points
grid = np.linspace(X.min(), X.max(), gridpoints)
K = np.exp(-0.5*((X[:,None] - grid[None,:])/bw)**2.)
K = K/K.sum(0)
protos = I@K
#Use a kernel smoother to interpolate the grid points
bw = grid[1] - grid[0]
K = np.exp(-0.5*((X[:,None] - grid[None,:])/bw)**2.)
K = K/K.sum(1)[:,None]
Sigma = K@protos
return Sigma
def scale_merged_intensities(ds, intensity_key, sigma_key, output_columns=None,
dropna=True, inplace=False, mean_intensity_method="isotropic",
bins=100, bw=2.0):
"""
Scales merged intensities using Bayesian statistics in order to
estimate structure factor amplitudes. This method is based on the approach
by French and Wilson [1]_, and is useful for improving the estimates
of negative and small intensities in order to ensure that structure
factor moduli are strictly positive.
The mean and standard deviation of acentric reflections are computed
analytically from a truncated normal distribution. The mean and
standard deviation for centric reflections are computed by numerical
integration of the posterior intensity distribution under a Wilson
prior, and then by interpolation with a kernel smoother.
Notes
-----
This method follows the same approach as French and Wilson, with
the following modifications:
* Numerical integration under a Wilson prior is used to estimate the
mean and standard deviation of centric reflections at runtime,
rather than using precomputed results and a look-up table.
* Same procedure is used for all centric reflections; original work
handled high intensity centric reflections differently.
Parameters
----------
ds : DataSet
Input DataSet containing columns with intensity_key and sigma_key
labels
intensity_key : str
Column label for intensities to be scaled
sigma_key : str
Column label for error estimates of intensities being scaled
output_columns : list or tuple of column names
Column labels to be added to ds for recording scaled I, SigI, F,
and SigF, respectively. output_columns must have len=4.
dropna : bool
Whether to drop reflections with NaNs in intensity_key or sigma_key
columns
inplace : bool
Whether to modify the DataSet in place or create a copy
mean_intensity_method : str ["isotropic" or "anisotropic"]
If "isotropic", mean intensity is determined by resolution bin.
If "anisotropic", mean intensity is determined by Miller index
using provided bandwidth.
bins : int or array
Either an integer number of n bins. Or an array of bin edges with
shape==(n, 2). Only affects output if mean_intensity_method is
\"isotropic\".
bw : float
Bandwidth to use for computing anisotropic mean intensity. This
parameter controls the distance that each reflection impacts in
reciprocal space. Only affects output if mean_intensity_method is
\"anisotropic\".
Returns
-------
DataSet
DataSet with 4 additional columns corresponding to scaled I, SigI,
F, and SigF.
References
----------
.. [1] <NAME>. and <NAME>. \"On the Treatment of Negative Intensity
Observations,\" Acta Cryst. A34 (1978).
"""
if not inplace:
ds = ds.copy()
# Sanitize input or check for invalid reflections
if dropna:
ds.dropna(subset=[intensity_key, sigma_key], inplace=True)
else:
if ds[[intensity_key, sigma_key]].isna().to_numpy().any():
raise ValueError(f"Input {ds.__class__.__name__} contains NaNs "
f"in columns '{intensity_key}' and/or 'sigma_key'. "
f"Please fix these input values, or run with dropna=True")
# Accessory columns needed for algorithm
if 'dHKL' not in ds:
ds.compute_dHKL(inplace=True)
if 'CENTRIC' not in ds:
ds.label_centrics(inplace=True)
if output_columns:
outputI, outputSigI, outputF, outputSigF = output_columns
else:
columns = ["FW-I", "FW-SIGI", "FW-F", "FW-SIGF"]
outputI, outputSigI, outputF, outputSigF = columns
# Input data for posterior calculations
I, Sig = ds[intensity_key].to_numpy(), ds[sigma_key].to_numpy()
if mean_intensity_method == "isotropic":
dHKL = ds['dHKL'].to_numpy(dtype=np.float64)
Sigma = mean_intensity_by_resolution(I, dHKL, bins)
elif mean_intensity_method == "anisotropic":
Sigma = mean_intensity_by_miller_index(I, ds.get_hkls(), bw)
multiplicity = compute_structurefactor_multiplicity(ds.get_hkls(), ds.spacegroup)
Sigma = Sigma * multiplicity
# Initialize outputs
ds[outputI] = 0.
ds[outputSigI] = 0.
# We will get posterior centric intensities from integration
mean, std = _centric_posterior_quad(
ds.loc[ds.CENTRIC, intensity_key].to_numpy(),
ds.loc[ds.CENTRIC, sigma_key].to_numpy(),
Sigma[ds.CENTRIC]
)
ds.loc[ds.CENTRIC, outputI] = mean
ds.loc[ds.CENTRIC, outputSigI] = std
# We will get posterior acentric intensities from analytical expressions
mean, std = _acentric_posterior(
ds.loc[~ds.CENTRIC, intensity_key].to_numpy(),
ds.loc[~ds.CENTRIC, sigma_key].to_numpy(),
Sigma[~ds.CENTRIC]
)
ds.loc[~ds.CENTRIC, outputI] = mean
ds.loc[~ds.CENTRIC, outputSigI] = std
# Convert dtypes of columns to MTZDtypes
ds[outputI] = ds[outputI].astype("Intensity")
ds[outputSigI] = ds[outputSigI].astype("Stddev")
ds[outputF] = np.sqrt(ds[outputI]).astype("SFAmplitude")
ds[outputSigF] = (ds[outputSigI]/(2*ds[outputF])).astype("Stddev")
return ds
if __name__=="__main__": # pragma: no cover
import reciprocalspaceship as rs
from sys import argv
ds = rs.read_mtz(argv[1]).dropna()
ds = ds.stack_anomalous()
ds = scale_merged_intensities(ds, "IMEAN", "SIGIMEAN")
from IPython import embed
embed(colors='Linux')
|
def copy_nested_list(l):
"""Return a copy of list l to one level of nesting"""
return [list(i) for i in l]
def normalize_table(table, n):
"""Return a normalized version of table such that it has n columns in each row, possibly with empty cells"""
normalized_table = copy_nested_list(table)
for row in normalized_table:
while len(row) < n:
row.append("")
return normalized_table
def column_widths(table):
"""Get the maximum size for each column in table"""
return [max(map(len, col)) for col in zip(*table)]
def align_table(table, align):
"""Return table justified according to align"""
widths = column_widths(table)
new_table = copy_nested_list(table)
for row in new_table:
for cell_num, cell in enumerate(row):
row[cell_num] = "{:{align}{width}}".format(
cell, align=align[cell_num], width=widths[cell_num]
)
return new_table
def header_line(length, border="-"):
"""Return header of length"""
return border * length
def md_alignment(alignment):
"""Given alignment option, return corresponding markdown"""
if alignment == "<":
return ":", "-"
elif alignment == ">":
return "-", ":"
else:
return "-", "-"
def latex_alignment(alignment):
"""Given alignment option, return corresponding latex"""
if alignment == "<":
return "l"
elif alignment == ">":
return "r"
def markdown_header(table, align):
"""Get markdown header for table according to given alignment options"""
widths = column_widths(table)
header_line = []
for i, w in enumerate(widths):
if w < 3:
raise ValueError
left, right = md_alignment(align[i])
header_line.append(left + "-" * (w - 2) + right)
return header_line
def add_markdown_header(table, align):
"""Add markdown header lines to table"""
new_table = copy_nested_list(table)
new_table.insert(1, markdown_header(table, align))
return new_table
def add_header(table, align):
"""Add header lines to table"""
widths = column_widths(table)
new_table = copy_nested_list(table)
for index in (0, 2):
new_table.insert(index, [header_line(w) for w in widths])
return new_table
def add_padding(table, padding):
"""Return a version of table which is padded according to inputted padding"""
new_table = copy_nested_list(table)
for i, row in enumerate(new_table):
padding_string = " " * padding
for j, cell in enumerate(row):
left = padding_string
right = padding_string
if j == 0:
left = ""
elif j == len(row) - 1:
right = ""
new_table[i][j] = left + new_table[i][j] + right
return new_table
def join_columns_with_divider(table, decorator):
"""Join each line in table with the decorator string between each cell"""
return [decorator.join(row) for row in table]
def join_formatted_lines(lines):
"""Return the finished output"""
return "\n".join(lines)
def add_latex_line_endings(lines):
"""Add latex newline character to each line"""
return [line + r" \\" for line in lines]
def add_latex_table_environment(lines, number_of_columns, alignment):
"""Add latex environment specification"""
lines = list(lines)
latex_alignments = [latex_alignment(j) for j in alignment]
alignment_line = "{{{}}}".format("".join(latex_alignments))
lines.insert(0, r"\begin{tabular}" + alignment_line)
lines.append(r"\end{tabular}")
return lines
def right_strip_lines(lines):
"""Remove trailing spaces on each line"""
return [line.rstrip() for line in lines]
def select_columns_from_table(table, columns, alignment):
new_table = []
new_alignment = []
for row in table:
new_row = []
for column_number in columns:
index_number = column_number - 1
cell = row[index_number]
new_row.append(cell)
new_table.append(new_row)
for column_number in columns:
index_number = column_number - 1
new_alignment.append(alignment[index_number])
return new_table, new_alignment
def run_pipeline(args):
"""Run the printing pipeline according to arguments given"""
raw_table = args["content"]
alignment = args["align"]
padding = args["padding"]
output_as_markdown = args["markdown"]
output_as_latex = args["latex"]
output_as_header = args["header"]
decorator = args["decorator"]
columns_to_print = args["columns"]
number_of_columns = len(columns_to_print)
if args["numeric"] is not None:
transposed_table = list(zip(*raw_table))
for column_number, decimal_numbers in args["numeric"]:
numeric_column = transposed_table[column_number - 1]
new_column = []
for number in numeric_column:
try:
number = f"%.{decimal_numbers}f" % float(number)
except:
number = number
new_column.append(number)
transposed_table[column_number - 1] = new_column
raw_table = list(zip(*transposed_table))
raw_table_subset, alignment_subset = select_columns_from_table(
raw_table, columns_to_print, alignment
)
normalized_table = normalize_table(raw_table_subset, number_of_columns)
justified_table = align_table(normalized_table, alignment_subset)
padded_table = add_padding(justified_table, padding)
if output_as_markdown:
padded_table = add_markdown_header(padded_table, alignment_subset)
if output_as_header:
padded_table = add_header(padded_table, alignment_subset)
lines = join_columns_with_divider(padded_table, decorator)
if output_as_latex:
lines = add_latex_line_endings(lines)
lines = add_latex_table_environment(lines, number_of_columns, alignment)
else:
lines = right_strip_lines(lines)
finished_output = join_formatted_lines(lines)
return finished_output
|
<filename>face_detector_ssd/dataset/create_dataset.py
import json
import os
import sys
from io import BytesIO
import tensorflow as tf
import numpy as np
from PIL import Image, ImageDraw
from jaccard_overlap import jaccard_overlap
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_string('base_dir', None,
"処理対象の画像とJSONがある起点ディレクトリ")
tf.flags.DEFINE_string('output_dir', None,
"出力先ディレクトリ")
tf.flags.DEFINE_boolean('debug', False,
"デバッグ用に矩形を表示した画像を出力する")
from playground.plan_boundingbox import create_ssd_layers, create_boxes
# from playground.plan_boundingbox2 import create_ssd_layers, create_boxes
# from playground.plan_boundingbox_lightweight import create_ssd_layers, create_boxes
IMAGE_SIZE = 256
FEATURE_MAP_SHAPE = [1, 16, 16, 3]
THRESHOLD_OVERLAP = 0.4
def _calc_jaccard_overlap(face, box):
box_rect = (box.left, box.top, box.right, box.bottom)
face_rect = (face['left'], face['top'], face['right'], face['bottom'])
overlap = jaccard_overlap(face_rect, box_rect)
return overlap
def _assign_box(face_regions, boxes):
face_count = len(face_regions)
match_count = 0
for face_region in face_regions:
rect = face_region['rect']
sorted_boxes = sorted(boxes,
key=lambda box: _calc_jaccard_overlap(rect, box),
reverse=True)
matched = False
for index, box in enumerate(sorted_boxes):
if box.label_mask == 1:
continue
overlap = _calc_jaccard_overlap(rect, box)
if overlap == 0:
continue
if (index == 0 or overlap >= THRESHOLD_OVERLAP):
if not matched:
match_count += 1
matched = True
box.label_mask = 1
box.label = [1.0]
box.offset = [
rect['left'] - box.left,
rect['top'] - box.top,
rect['right'] - box.right,
rect['bottom'] - box.bottom,
]
return face_count, match_count
def _int64_list_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def _float64_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _create_tfrecord(image, image_file_name, boxes, tfrecord_path):
byte_io = BytesIO()
image.save(byte_io, format="jpeg")
byte_io.seek(0)
jpeg_image_data = byte_io.read()
tfrecord_name = os.path.basename(tfrecord_path)
label_masks = np.array(list(
map(lambda box: box.label_mask, boxes))).flatten()
labels = np.array(list(map(lambda box: box.label, boxes))).flatten()
offsets = np.array(list(map(lambda box: box.offset, boxes))).flatten()
options = tf.python_io.TFRecordOptions(
tf.python_io.TFRecordCompressionType.GZIP)
with tf.python_io.TFRecordWriter(tfrecord_path, options) as writer:
example = tf.train.Example(features=tf.train.Features(feature={
'tfrecord_name': _bytes_feature(tfrecord_name.encode()),
'image_file_name': _bytes_feature(image_file_name.encode()),
'image': _bytes_feature(jpeg_image_data),
'labels': _float64_feature(labels),
'label_masks': _float64_feature(label_masks),
'offset': _float64_feature(offsets),
}))
writer.write(example.SerializeToString())
def _create_image_data(image_path, image_size=IMAGE_SIZE, rotate=None):
with Image.open(image_path) as image:
image = image.resize((image_size, image_size)) \
.convert('RGB')
if rotate is not None:
# 反時計回り(counter clockwise)
image = image.rotate(360 - 90 * rotate)
return image
def _rotate_clockwise(regions, rotate):
for region in regions:
rect = region['rect']
for i in range(rotate):
left = rect['left']
top = rect['top']
right = rect['right']
bottom = rect['bottom']
rect['left'] = 1.0 - bottom
rect['top'] = left
rect['right'] = 1.0 - top
rect['bottom'] = right
def _load_annotation(json_path, rotate=None):
with open(json_path) as fp:
annotation = json.load(fp)
if rotate is not None:
_rotate_clockwise(annotation['regions'], rotate=rotate)
return annotation
def _create_debug_image(image, boxes, output_image_path):
draw = ImageDraw.Draw(image)
for box in boxes:
if box.label == [0]:
continue
rect = [
(box.left + box.offset[0]) * image.width,
(box.top + box.offset[1]) * image.height,
(box.right + box.offset[2]) * image.width,
(box.bottom + box.offset[3]) * image.height
]
draw.rectangle(rect, outline=0xff0000)
image.save(output_image_path, format='jpeg')
def main(argv=None):
assert FLAGS.base_dir, 'Directory base_dir not set.'
assert os.path.exists(FLAGS.base_dir), \
'Directory %s not exist.' % FLAGS.base_dir
os.makedirs(FLAGS.output_dir, exist_ok=True)
files = os.listdir(FLAGS.base_dir)
json_files = filter(lambda f: f.endswith('.json'), files)
json_file_paths = list(
map(lambda f: os.path.join(FLAGS.base_dir, f), json_files))
feature_map = tf.get_variable(shape=FEATURE_MAP_SHAPE,
name='feature_map')
ssd_layers = create_ssd_layers(feature_map)
file_count = len(json_file_paths)
total_face_count = 0
total_match_count = 0
for index, json_path in enumerate(json_file_paths):
for rotate in range(4):
annotation = _load_annotation(json_path, rotate=rotate)
image_file_name = annotation['file_name']
regions = annotation['regions']
face_regions = list(
filter(lambda region: region['label'] == 0, regions))
boxes = create_boxes(ssd_layers)
face_count, match_count = _assign_box(face_regions, boxes)
total_face_count += face_count
total_match_count += match_count
image_path = os.path.join(FLAGS.base_dir, image_file_name)
image = _create_image_data(image_path, rotate=rotate)
name, _ = os.path.splitext(image_file_name)
tfrecord_name = '%s_%d.tfrecord' % (name, rotate)
tfrecord_path = os.path.join(FLAGS.output_dir, tfrecord_name)
_create_tfrecord(image, image_file_name, boxes, tfrecord_path)
if FLAGS.debug:
debug_image_file_name = '%s_%d.jpg' % (name, rotate)
debug_image_file_path = os.path.join(FLAGS.output_dir,
debug_image_file_name)
_create_debug_image(image, boxes, debug_image_file_path)
percentage = total_match_count / float(total_face_count)
print('%d/%d, %d/%d - %f' % (index + 1, file_count,
total_match_count, total_face_count,
percentage))
if __name__ == "__main__":
main(sys.argv)
|
"""
Copyright (C) 2017, <NAME>
Example:
tc = TypeContext()
@tc.prototype("test", "pipe", "field")
class ModelA(ModelBase):
fieldA = Int8()
class Child(ModelBase):
fieldB = Int8()
fieldC = Int32()
fieldA = Uint32()
inst = mc.init_instance()
inst.test.fieldA = 3
inst.test.Child.fieldC
inst.test.Child.fieldB
inst.test.Child.fieldA
"""
import pservlet
import types
import inspect
class Primitive(object):
"""
Represents a primitive type
"""
__is_type_model__ = True
def read(self, instance, accessor):
"""
Read the primitive data from the type instance with given accessor
"""
raise NotImplemented
def write(self, instance, accessor):
"""
Write the primitve data from the type instance with given accessor
"""
raise NotImplemented
def _create_value_accessor(type_obj, accessor):
"""
Create a field accessor that defines the read and write to a initialized field
"""
def _getter(self):
return type_obj.read(self.instance, accessor)
def _setter(self, val):
type_obj.write(self.instance, accessor, val)
return (_getter, _setter)
def _get_type_model_obj():
"""
Create a pstd type model object
"""
return pservlet.TypeModel()
def _get_type_model_inst(model):
"""
Create a pstd type instance object from the given model
"""
return pservlet.TypeInstance(model)
def _get_accessor(type_model, pipe, field):
"""
Create an accessor that can access the given pipe's given field with the specified type model
"""
return type_model.accessor(pipe, field)
class _Instance(object):
"""
The class used to access the typed data in the strong typed pipe system
This class is the the actual interface for value access.
For each servlet execution, the execute function should create an model
instance by calling ModelCollection.init_instance()
"""
def __init__(self, inst, types):
self._inst = inst
self._types = types
self._type_inst = {}
def __getattribute__(self, key):
if key == "_types":
return object.__getattribute__(self, key)
if key in self._types:
if key not in self._type_inst:
self._type_inst[key] = self._types[key](self._inst)
return self._type_inst[key]
else:
return object.__getattribute__(self, key)
class ModelBase(object):
"""
The base class for the type model. We can define the type accessing model by inheriting this class with the decorator
TypeContext.model_class
"""
__children__ = []
__primitives__ = {}
def __init__(self, type_instance):
self.instance = type_instance
for name,child in self.__children__:
child_inst = child(type_instance)
setattr(self, name, child_inst)
def __getattribute__(self, key):
if key[:2] == "__" or key not in self.__primitives__:
return object.__getattribute__(self, key)
else:
return self.__primitives__[key][0](self)
def __setattr__(self, key, val):
if key[:2] == "__" or key not in self.__primitives__:
return object.__setattr__(self, key, val)
else:
return self.__primitives__[key][1](self, val)
class TypeContext(object):
"""
The strong typed pipe context, which should be constructed in the initailization callback
in the servlet
"""
def __init__(self):
self._model = _get_type_model_obj()
self._types = {}
def _add_model(self, name, pipe, field, model):
def _patch_class(cls, prefix):
cls.__children__ = []
cls.__primitives__ = {}
for name in dir(cls):
obj = getattr(cls, name)
if getattr(obj, "__is_type_model__", False):
accessor = _get_accessor(self._model, pipe, prefix + ("." if prefix else "") + name)
cls.__primitives__[name] = _create_value_accessor(obj, accessor)
elif inspect.isclass(obj) and issubclass(obj, ModelBase):
cls.__children__.append((name, obj))
setattr(cls, name, _patch_class(obj, prefix + ("." if prefix else "") + name))
return cls
self._types[name] = _patch_class(model, field)
def model_class(self, name, pipe, field = ""):
"""
The decorator used to define a model class
name The name for this model
pipe The pipe from which we read/write the data
field The field expression we want to access
"""
def _decorator(cls):
if issubclass(cls, ModelBase):
self._add_model(name, pipe, field, cls)
else:
raise TypeError("The model class must be a subclass of ModelBase")
return None
return _decorator
def init_instance(self):
"""
Initialize a new type accessor instance, this should be used in the execute function
"""
return _Instance(_get_type_model_inst(self._model), self._types)
def _define_int_primitive(size, signed):
class IntField(Primitive):
def __init__(self):
self.size = size
self.signed = signed
def read(self, instance, accessor):
return instance.read_int(accessor, self.size, self.signed + 0)
def write(self, instance, accessor, value):
return instance.write_int(accessor, self.size, self.signed + 0, int(value))
return IntField
def _define_float_primitive(size):
class FloatField(Primitive):
def __init__(self):
self.size = size
def read(self, instance, accessor):
return instance.read_float(accessor, self.size)
def write(self, instance, accessor, value):
return instance.write_float(accessor, self.size, float(value))
return FloatField
Int8 = _define_int_primitive(1, True)
Int16 = _define_int_primitive(2, True)
Int32 = _define_int_primitive(4, True)
Int64 = _define_int_primitive(8, True)
Uint8 = _define_int_primitive(1, False)
Uint16 = _define_int_primitive(2, False)
Uint32 = _define_int_primitive(4, False)
Uint64 = _define_int_primitive(8, False)
Float = _define_float_primitive(4)
Double = _define_float_primitive(8)
ScopeToken = _define_int_primitive(4, False)
|
from vnpy.trader.object import (
TickData,
OrderData,
TradeData,
PositionData,
AccountData,
ContractData,
OrderRequest,
CancelRequest,
SubscribeRequest,
HistoryRequest,
)
from vnpy.trader.constant import (
Direction,
Exchange,
OrderType,
Product,
Status,
OptionType
)
from vnpy.trader.gateway import BaseGateway
from vnpy.api.websocket import WebsocketClient
from vnpy.event import Event
from time import sleep
from datetime import datetime
from copy import copy
WEBSOCKET_HOST = 'wss://www.deribit.com/ws/api/v2'
SANDBOX_WEBSOCKET_HOST = 'wss://testapp.deribit.com/ws/api/v2'
PRODUCT_DERIBIT2VT = {
"future": Product.FUTURES,
"option": Product.OPTION
}
OPTIONTYPE_DERIBIT2VT = {
"call": OptionType.CALL,
"put": OptionType.PUT
}
DIRECTION_VT2DERIBIT = {Direction.LONG: "buy", Direction.SHORT: "sell"}
ORDERTYPE_VT2DERIBIT = {
OrderType.LIMIT: "limit",
OrderType.MARKET: "market",
}
ORDERTYPE_DERIBIT2VT = {v: k for k, v in ORDERTYPE_VT2DERIBIT.items()}
DIRECTION_DERIBIT2VT = {v: k for k, v in DIRECTION_VT2DERIBIT.items()}
STATUS_DERIBIT2VT = {
"open": Status.NOTTRADED,
"filled": Status.ALLTRADED,
"rejected": Status.REJECTED,
"cancelled": Status.CANCELLED,
}
class DeribitGateway(BaseGateway):
""""""
default_setting = {
"user_id": "",
"secret": "",
"proxy_host": "",
"proxy_port": "",
"server": ["SAND_BOX", "REAL"],
}
exchanges = [Exchange.DERIBIT]
def __init__(self, event_engine):
""""""
super().__init__(event_engine, "DERIBIT")
self.ws_api = DeribitWebsocketApi(self)
def connect(self, setting: dict):
""""""
key = setting["user_id"]
secret = setting["secret"]
proxy_host = setting["proxy_host"]
proxy_port = setting["proxy_port"]
server = setting['server']
if proxy_port.isdigit():
proxy_port = int(proxy_port)
else:
proxy_port = 0
self.ws_api.connect(
key,
secret,
server,
proxy_host,
proxy_port,
)
def subscribe(self, req: SubscribeRequest):
""""""
self.ws_api.subscribe(req)
def send_order(self, req: OrderRequest):
""""""
return self.ws_api.send_order(req)
def cancel_order(self, req: CancelRequest):
""""""
return self.ws_api.cancel_order(req)
def query_account(self):
""""""
self.ws_api.query_account()
def query_position(self):
"""
Query holding positions.
"""
self.ws_api.query_position()
def query_history(self, req: HistoryRequest):
"""
Query bar history data.
"""
pass
def init_query(self):
""""""
pass
def process_timer_event(self, event: Event):
""""""
pass
def close(self):
""""""
self.ws_api.stop()
class DeribitWebsocketApi(WebsocketClient):
""""""
def __init__(self, gateway: BaseGateway):
""""""
super().__init__()
self.gateway = gateway
self.gateway_name = gateway.gateway_name
self.key = ""
self.secret = ""
self.access_token = ""
self.id = 1
self.id_callback = {}
self.callbacks = {
"ticker": self.on_ticker,
"book": self.on_orderbook,
"user": self.on_user_change,
}
self.ticks = {}
self.asks = {}
self.bids = {}
self.query_ins_done = False
self.query_pos_done = False
self.query_acc_done = False
def connect(
self,
key: str,
secret: str,
server: str,
proxy_host: str,
proxy_port: int
):
""""""
self.gateway.write_log("开始连接ws接口")
self.key = key
self.secret = secret.encode()
if server == "REAL":
self.init(WEBSOCKET_HOST, proxy_host, proxy_port)
else:
self.init(SANDBOX_WEBSOCKET_HOST, proxy_host, proxy_port)
self.start()
sleep(5)
self.init_query()
self.gateway.write_log("Deribit接口连接成功")
def init_query(self):
""""""
self.query_instrument()
self.wait_instrument()
self.get_access_token()
self.wait_access_token()
self.query_position()
self.wait_position()
self.query_account()
self.wait_account()
def subscribe(self, req: SubscribeRequest):
""""""
symbol = req.symbol
self.ticks[symbol] = TickData(
gateway_name=self.gateway_name,
symbol=symbol,
exchange=Exchange.DERIBIT,
datetime=datetime.now(),
)
channels = [
"ticker." + symbol + ".raw",
"user.changes." + symbol + ".raw",
"book." + symbol + ".raw",
]
msg = {
"jsonrpc": "2.0",
"method": "private/subscribe",
"id": self.id,
"params": {
"channels": channels,
"access_token": self.access_token}
}
self.id += 1
self.send_packet(msg)
def send_order(self, req: OrderRequest):
""""""
orderid = self.id
order = req.create_order_data(orderid, self.gateway_name)
self.gateway.on_order(order)
side = DIRECTION_VT2DERIBIT[req.direction]
symbol = req.symbol
order_type = ORDERTYPE_VT2DERIBIT[req.type]
msg = {
"jsonrpc": "2.0",
"id": self.id,
"method": "private/" + side,
"params": {
"instrument_name": symbol,
"amount": req.volume,
"type": order_type,
"label": orderid,
}
}
self.id += 1
if req.type == OrderType.LIMIT:
msg['params']['price'] = req.price
self.send_packet(msg)
return order.vt_orderid
def cancel_order(self, req: CancelRequest):
""""""
msg = {
"jsonrpc": "2.0",
"id": self.id,
"method": "private/cancel",
"params": {
"order_id": req.orderid,
"access_token": self.access_token,
}
}
self.id_callback[self.id] = self.on_cancel_order
self.id += 1
self.send_packet(msg)
def get_access_token(self):
"""
use the access key and secret to get access token
"""
msg = {
"jsonrpc": "2.0",
"id": self.id,
"method": "public/auth",
"params": {
"grant_type": "client_credentials",
"client_id": self.key,
"client_secret": self.secret.decode()
}
}
self.id_callback[self.id] = self.on_access_token
self.id += 1
self.send_packet(msg)
def query_instrument(self):
""""""
msg_btc = {
"jsonrpc": "2.0",
"id": self.id,
"method": "public/get_instruments",
"params": {
"currency": "BTC",
"expired": False,
}
}
self.id_callback[self.id] = self.on_query_instrument
self.id += 1
msg_eth = {
"jsonrpc": "2.0",
"id": self.id,
"method": "public/get_instruments",
"params": {
"currency": "ETH",
"expired": False
}
}
self.id_callback[self.id] = self.on_query_instrument
self.id += 1
self.send_packet(msg_btc)
self.send_packet(msg_eth)
def query_account(self):
""""""
for curr in ['BTC', 'ETH']:
msg = {
"jsonrpc": "2.0",
"id": self.id,
"method": "private/get_deposits",
"params": {
"currency": curr,
"access_token": self.access_token}
}
self.send_packet(msg)
self.id_callback[self.id] = self.on_query_account
self.id += 1
def query_position(self):
""""""
for kind in ['future', 'option']:
for curr in ['BTC', 'ETH']:
msg = {
"jsonrpc": "2.0",
"id": self.id,
"method": "private/get_positions",
"params": {
"currency": curr,
"kind": kind,
"access_token": self.access_token,
}
}
self.send_packet(msg)
self.id_callback[self.id] = self.on_query_position
self.id += 1
def on_packet(self, packet: dict):
"""
callback when data is received and unpacked
"""
if 'id' in packet.keys():
packet_id = packet['id']
if packet_id in self.id_callback.keys():
callback = self.id_callback[packet_id]
callback(packet)
elif 'params' in packet.keys():
channel = packet["params"]["channel"]
kind = channel.split(".")[0]
callback = self.callbacks[kind]
callback(packet)
def on_access_token(self, packet: dict):
""""""
data = packet['result']
self.access_token = data['access_token']
def on_query_instrument(self, packet: list):
""""""
data = packet['result']
for d in data:
product = PRODUCT_DERIBIT2VT[d['kind']]
if product == Product.FUTURES:
contract = ContractData(
symbol=d['instrument_name'],
exchange=Exchange.DERIBIT,
name=d['instrument_name'],
product=product,
pricetick=d['tick_size'],
size=d['contract_size'],
min_volume=d['min_trade_amount'],
net_position=True,
history_data=False,
gateway_name=self.gateway_name,
)
else:
expiry = datetime.fromtimestamp(d['expiration_timestamp'] / 1000)
option_type = OPTIONTYPE_DERIBIT2VT[d['option_type']]
contract = ContractData(
symbol=d['instrument_name'],
exchange=Exchange.DERIBIT,
name=d['instrument_name'],
product=product,
pricetick=d['tick_size'],
size=d['contract_size'],
min_volume=d['min_trade_amount'],
option_strike=d['strike'],
option_underlying=d['base_currency'],
option_type=option_type,
option_expiry=expiry,
gateway_name=self.gateway_name,
)
self.gateway.on_contract(contract)
self.query_ins_done = True
def on_query_position(self, packet: list):
""""""
data = packet['result']
for pos in data:
position = PositionData(
symbol=pos['instrument_name'],
exchange=Exchange.DERIBIT,
direction=Direction.NET,
volume=pos['size'],
pnl=float(pos['floating_profit_loss']),
gateway_name=self.gateway_name,
)
self.gateway.on_position(position)
self.query_pos_done = True
def on_query_account(self, packet: dict):
""""""
data = packet['result']
data = data['data']
for account in data:
Account = AccountData(
gateway_name=self.gateway_name,
accountid=account['address'],
balance=account['amount'],
)
self.gateway.on_account(copy(Account))
self.query_acc_done = True
def on_cancel_order(self, packet: dict):
""""""
data = packet['result']
orderid = data['label']
order = OrderData(
symbol=data['instrument_name'],
exchange=Exchange.DERIBIT,
type=ORDERTYPE_DERIBIT2VT[data['order_type']],
orderid=orderid,
direction=DIRECTION_DERIBIT2VT[data['direction']],
price=float(data['price']),
volume=float(data['amount']),
traded=float(data['filled_amount']),
time=str(datetime.fromtimestamp(data['last_update_timestamp'] / 1000)),
status=STATUS_DERIBIT2VT[data['order_state']],
gateway_name=self.gateway_name,
)
self.gateway.on_order(copy(order))
def on_user_change(self, packet: dict):
""""""
data = packet['params']['data']
trades = data['trades']
positions = data['positions']
orders = data['orders']
if orders:
for order in orders:
self._on_order(order)
if trades:
for trade in trades:
self._on_trade(trade, orders[0]['order_id'])
if positions:
for position in positions:
self._on_position(position)
def _on_order(self, data: dict):
""""""
orderid = data['label']
order = OrderData(
symbol=data['instrument_name'],
exchange=Exchange.DERIBIT,
type=ORDERTYPE_DERIBIT2VT[data['order_type']],
orderid=orderid,
direction=DIRECTION_DERIBIT2VT[data['direction']],
price=float(data['price']),
volume=float(data['amount']),
traded=float(data['filled_amount']),
time=str(datetime.fromtimestamp(data['last_update_timestamp'] / 1000)),
status=STATUS_DERIBIT2VT[data['order_state']],
gateway_name=self.gateway_name,
)
self.gateway.on_order(copy(order))
def _on_trade(self, data: list, orderid):
""""""
trade = TradeData(
symbol=data['instrument_name'],
exchange=Exchange.DERIBIT,
orderid=orderid,
tradeid=data['trade_id'],
direction=DIRECTION_DERIBIT2VT[data['direction']],
price=float(data['price']),
volume=float(data['amount']),
time=str(datetime.fromtimestamp(data['timestamp'] / 1000)),
gateway_name=self.gateway_name,
)
self.gateway.on_trade(trade)
def _on_position(self, data: dict):
""""""
pos = PositionData(
symbol=data['instrument_name'],
exchange=Exchange.DERIBIT,
direction=Direction.NET,
volume=data['size'],
price=data['settlement_price'],
pnl=float(data['floating_profit_loss']),
gateway_name=self.gateway_name,
)
self.gateway.on_position(pos)
def on_ticker(self, packet: dict):
""""""
data = packet['params']['data']
symbol = data['instrument_name']
tick = self.ticks.get(symbol, None)
if not tick:
return
tick.bid_price_1 = data['best_bid_price']
tick.bid_volume_1 = data['best_bid_amount']
tick.ask_price_1 = data['best_ask_price']
tick.ask_volume_1 = data['best_ask_amount']
tick.high_price = data['stats']['high']
tick.low_price = data['stats']['low']
tick.volume = data['stats']['volume']
tick.datetime = datetime.fromtimestamp(data['timestamp'] / 1000)
self.gateway.on_tick(copy(tick))
def on_orderbook(self, packet: dict):
""""""
data = packet['params']['data']
if 'prev_change_id' not in data.keys():
self.on_book_snapshot(packet)
else:
self.on_book_change(packet)
def on_book_snapshot(self, packet: dict):
""""""
ins = packet['params']['data']['instrument_name']
asks = packet['params']['data']['asks']
bids = packet['params']['data']['bids']
self.asks[ins] = {}
self.bids[ins] = {}
Asks = self.asks[ins]
Bids = self.bids[ins]
for ask in asks:
Asks[ask[1]] = ask[2]
for bid in bids:
Bids[bid[1]] = bid[2]
def on_book_change(self, packet: dict):
""""""
ins = packet['params']['data']['instrument_name']
asks = packet['params']['data']['asks']
bids = packet['params']['data']['bids']
Asks = self.asks[ins]
Bids = self.bids[ins]
if(len(asks)):
for ask in asks:
if ask[0] == 'new':
Asks[ask[1]] = ask[2]
elif ask[0] == 'delete':
del Asks[ask[1]]
else:
Asks[ask[1]] = ask[2]
if(len(bids)):
for bid in bids:
if bid[0] == 'new':
Bids[bid[1]] = bid[2]
elif bid[0] == 'delete':
del Bids[bid[1]]
else:
Bids[bid[1]] = bid[2]
tick = self.ticks[ins]
bids_keys = Bids.keys()
bids_keys = sorted(bids_keys, reverse=True)
tick.bid_price_1 = bids_keys[0]
tick.bid_price_2 = bids_keys[1]
tick.bid_price_3 = bids_keys[2]
tick.bid_price_4 = bids_keys[3]
tick.bid_price_5 = bids_keys[4]
tick.bid_volume_1 = Bids[bids_keys[0]]
tick.bid_volume_2 = Bids[bids_keys[1]]
tick.bid_volume_3 = Bids[bids_keys[2]]
tick.bid_volume_4 = Bids[bids_keys[3]]
tick.bid_volume_5 = Bids[bids_keys[4]]
asks_keys = Asks.keys()
asks_keys = sorted(asks_keys)
tick.ask_price_1 = asks_keys[0]
tick.ask_price_2 = asks_keys[1]
tick.ask_price_3 = asks_keys[2]
tick.ask_price_4 = asks_keys[3]
tick.ask_price_5 = asks_keys[4]
tick.ask_volume_1 = Asks[asks_keys[0]]
tick.ask_volume_2 = Asks[asks_keys[1]]
tick.ask_volume_3 = Asks[asks_keys[2]]
tick.ask_volume_4 = Asks[asks_keys[3]]
tick.ask_volume_5 = Asks[asks_keys[4]]
tick.datetime = datetime.fromtimestamp(packet['params']['data']['timestamp'] / 1000)
self.gateway.on_tick(copy(tick))
def wait_access_token(self):
""""""
while not self.access_token:
sleep(0.5)
def wait_instrument(self):
""""""
while not self.query_ins_done:
sleep(0.5)
self.gateway.write_log("合约信息查询成功")
def wait_position(self):
""""""
while not self.query_pos_done:
sleep(0.5)
self.gateway.write_log("持仓查询成功")
def wait_account(self):
""""""
while not self.query_acc_done:
sleep(0.5)
self.gateway.write_log("账户查询成功")
|
<filename>Experiments/main_bigram_next_exp.py
import sys
sys.path.insert(0, '../')
import re
from Code.bigram import BigramModel
from Experiments.bigram_next import BigramModelNext
DATA_PATH = '../DataSets/'
OUTPUT_DIR = '../Output/BigramExperiment/'
TRAINING_FILES = {
'en': ['en-the-little-prince.txt', 'en-moby-dick.txt'],
'fr': ['fr-le-petit-prince.txt', 'fr-vingt-mille-lieues-sous-les-mers.txt'],
'ot': ['sp-el-principito.txt', 'sp-moby-dick.txt']
}
LANGUAGES = {
'en': 'ENGLISH',
'fr': "FRENCH",
'ot': "OTHER"
}
SENTENCES = {
"What restaurant?",
"Un bon chef",
"What boutique?",
"What boutique should we shop at?",
"Un bon chef m'as parle l'autre jour.",
"What restaurant is your favorite?",
"What restaurant should we eat at?"
}
def main():
trained_models = train_models()
output_results(trained_models[0], trained_models[1])
def train_models():
bigrams = {}
next_bigrams = {}
for language, documents in TRAINING_FILES.items():
bigram = BigramModel(user_smoothing=0.5)
next_bigram = BigramModelNext(user_smoothing = 0.5)
for document in documents:
text = load_file(DATA_PATH + language + "/" + document)
bigram.train(text)
next_bigram.train(text)
bigrams[language] = bigram
next_bigrams[language]= next_bigram
return [bigrams, next_bigrams]
def output_results(bigrams, next_bigrams):
orig_stdout = sys.stdout
output_file_template = OUTPUT_DIR + "out"
sentence_num = 1
#dictionary of results from testing sentences
for sentence in SENTENCES:
#change output location
writer = open(output_file_template+str(sentence_num)+'.txt', 'w')
sys.stdout = writer
print(sentence + "\n")
bigram_output(sentence, bigrams)
bigram_output(sentence, next_bigrams, False)
sentence_num += 1
#close writer
sys.stdout = orig_stdout
writer.close()
def bigram_output(sentence, bigrams, prev = True):
result_cumul = {}
result_single = {}
result_prob = {}
char1 = None
char2 = None
print("---------------- ")
if prev:
print("BIGRAM MODEL: ")
else:
print("BIGRAM NEXT MODEL: ")
text = clean_string(sentence)
output_dir = OUTPUT_DIR + "model/"
#Get and store test results
for language, bigram in bigrams.items():
results = bigram.test(text)
bigram.dump_probs(output_dir + "bigram" + language.upper() + ".txt")
result_prob[language] = results[0]
result_single[language] = results[1]
result_cumul[language] = results[2]
#Output results according to format in project specs
for i in range(len(text)-1):
#For bigram printing
j = 0
for language, result_array in result_cumul.items():
result_array_single = result_single[language]
key = list(result_array[i].keys())[0]
prob_single = result_array_single[i][key]
prob_cumul = result_array[i][key]
if j == 0:
if prev:
print("Bigram: " + key)
else:
print("Bigram Next: " + key)
if prev:
char1 = str(key[1])
char2 = str(key[0])
else:
char1 = str(key[0])
char2 = str(key[1])
print (LANGUAGES[language] + ": P("+ char1 + "|" + char2 + ") = " + str(prob_single) + " ==> log prob of sentence so far: " + str(prob_cumul))
j += 1
print()
print("According to the bigram model, the sentence is in " + get_best_language(result_prob))
#find best language with total probabilities
def get_best_language(result_prob):
best_prob = None
best_lang = None
for language in result_prob:
prob = result_prob[language]
if not best_prob:
best_prob = prob
best_lang = language
elif prob > best_prob:
best_prob = prob
best_lang = language
return LANGUAGES[best_lang]
#Returns cleaned content of file
def load_file(filePath):
with open(filePath, 'r', encoding="utf8", errors='ignore') as myfile:
content=myfile.read()
return clean_string(content)
def clean_string(string):
return re.sub("[^a-z]","", string.lower().replace('\n', ''))
if __name__ == '__main__':
main()
|
<reponame>cytomine/S_Segment-CV-AdaptThres-Sample<gh_stars>1-10
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2019. Authors: see NOTICE file.
# *
# * Licensed under the Apache License, Version 2.0 (the "License");
# * you may not use this file except in compliance with the License.
# * You may obtain a copy of the License at
# *
# * http://www.apache.org/licenses/LICENSE-2.0
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from operator import attrgetter
import cv2
import numpy as np
from cytomine import CytomineJob
from cytomine.models import ImageInstance, ImageInstanceCollection, AnnotationCollection, Annotation
from cytomine.utilities.software import parse_domain_list
from shapely.geometry import Polygon
__author__ = "<NAME> <<EMAIL>>"
__contributors__ = ["<NAME> <<EMAIL>>", "<NAME>"]
__copyright__ = "Copyright 2010-2022 University of Liège, Belgium, https://uliege.cytomine.org/"
def find_components(image):
contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
components = []
if len(contours) > 0:
top_index = 0
tops_remaining = True
while tops_remaining:
exterior = contours[top_index][:, 0, :].tolist()
interiors = []
# check if there are children and process if necessary
if hierarchy[0][top_index][2] != -1:
sub_index = hierarchy[0][top_index][2]
subs_remaining = True
while subs_remaining:
interiors.append(contours[sub_index][:, 0, :].tolist())
# check if there is another sub contour
if hierarchy[0][sub_index][0] != -1:
sub_index = hierarchy[0][sub_index][0]
else:
subs_remaining = False
# add component tuple to components only if exterior is a polygon
if len(exterior) > 3:
components.append((exterior, interiors))
# check if there is another top contour
if hierarchy[0][top_index][0] != -1:
top_index = hierarchy[0][top_index][0]
else:
tops_remaining = False
return components
def main(argv):
with CytomineJob.from_cli(argv) as cj:
images = ImageInstanceCollection()
if cj.parameters.cytomine_id_images is not None:
id_images = parse_domain_list(cj.parameters.cytomine_id_images)
images.extend([ImageInstance().fetch(_id) for _id in id_images])
else:
images = images.fetch_with_filter("project", cj.parameters.cytomine_id_project)
for image in cj.monitor(images, prefix="Running detection on image", period=0.1):
# Resize image if needed
resize_ratio = max(image.width, image.height) / cj.parameters.max_image_size
if resize_ratio < 1:
resize_ratio = 1
resized_width = int(image.width / resize_ratio)
resized_height = int(image.height / resize_ratio)
bit_depth = image.bitDepth if image.bitDepth is not None else 8
image.dump(dest_pattern="/tmp/{id}.jpg", max_size=max(resized_width, resized_height), bits=bit_depth)
img = cv2.imread(image.filename, cv2.IMREAD_GRAYSCALE)
thresholded_img = cv2.adaptiveThreshold(img, 2**bit_depth, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, cj.parameters.threshold_blocksize,
cj.parameters.threshold_constant)
kernel = np.ones((5, 5), np.uint8)
eroded_img = cv2.erode(thresholded_img, kernel, iterations=cj.parameters.erode_iterations)
dilated_img = cv2.dilate(eroded_img, kernel, iterations=cj.parameters.dilate_iterations)
extension = 10
extended_img = cv2.copyMakeBorder(dilated_img, extension, extension, extension, extension,
cv2.BORDER_CONSTANT, value=2**bit_depth)
components = find_components(extended_img)
zoom_factor = image.width / float(resized_width)
for i, component in enumerate(components):
converted = []
for point in component[0]:
x = int((point[0] - extension) * zoom_factor)
y = int(image.height - ((point[1] - extension) * zoom_factor))
converted.append((x, y))
components[i] = Polygon(converted)
# Find largest component (whole image)
largest = max(components, key=attrgetter('area'))
components.remove(largest)
# Only keep components greater than 5% of whole image
min_area = int((cj.parameters.image_area_perc_threshold/100) * image.width * image.height)
annotations = AnnotationCollection()
for component in components:
if component.area > min_area:
annotations.append(Annotation(location=component.wkt, id_image=image.id,
id_terms=[cj.parameters.cytomine_id_predicted_term],
id_project=cj.parameters.cytomine_id_project))
if len(annotations) % 100 == 0:
annotations.save()
annotations = AnnotationCollection()
annotations.save()
cj.job.update(statusComment="Finished.")
if __name__ == "__main__":
import sys
main(sys.argv[1:])
|
<reponame>yuvalabou/homeassistant
"""Base HACS class."""
from __future__ import annotations
import asyncio
from dataclasses import asdict, dataclass, field
from datetime import timedelta
import gzip
import json
import logging
import math
import os
import pathlib
import shutil
from typing import TYPE_CHECKING, Any, Awaitable, Callable
from aiogithubapi import (
AIOGitHubAPIException,
GitHub,
GitHubAPI,
GitHubAuthenticationException,
GitHubException,
GitHubNotModifiedException,
GitHubRatelimitException,
)
from aiogithubapi.objects.repository import AIOGitHubAPIRepository
from aiohttp.client import ClientSession, ClientTimeout
from awesomeversion import AwesomeVersion
from homeassistant.config_entries import ConfigEntry, ConfigEntryState
from homeassistant.const import EVENT_HOMEASSISTANT_FINAL_WRITE, Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.loader import Integration
from homeassistant.util import dt
from .const import TV
from .enums import (
ConfigurationType,
HacsCategory,
HacsDisabledReason,
HacsDispatchEvent,
HacsGitHubRepo,
HacsStage,
LovelaceMode,
)
from .exceptions import (
AddonRepositoryException,
HacsException,
HacsExecutionStillInProgress,
HacsExpectedException,
HacsRepositoryArchivedException,
HacsRepositoryExistException,
HomeAssistantCoreRepositoryException,
)
from .repositories import RERPOSITORY_CLASSES
from .utils.decode import decode_content
from .utils.logger import get_hacs_logger
from .utils.queue_manager import QueueManager
from .utils.store import async_load_from_store, async_save_to_store
if TYPE_CHECKING:
from .repositories.base import HacsRepository
from .utils.data import HacsData
from .validate.manager import ValidationManager
@dataclass
class RemovedRepository:
"""Removed repository."""
repository: str | None = None
reason: str | None = None
link: str | None = None
removal_type: str = None # archived, not_compliant, critical, dev, broken
acknowledged: bool = False
def update_data(self, data: dict):
"""Update data of the repository."""
for key in data:
if data[key] is None:
continue
if key in (
"reason",
"link",
"removal_type",
"acknowledged",
):
self.__setattr__(key, data[key])
def to_json(self):
"""Return a JSON representation of the data."""
return {
"repository": self.repository,
"reason": self.reason,
"link": self.link,
"removal_type": self.removal_type,
"acknowledged": self.acknowledged,
}
@dataclass
class HacsConfiguration:
"""HacsConfiguration class."""
appdaemon_path: str = "appdaemon/apps/"
appdaemon: bool = False
config: dict[str, Any] = field(default_factory=dict)
config_entry: ConfigEntry | None = None
config_type: ConfigurationType | None = None
country: str = "ALL"
debug: bool = False
dev: bool = False
experimental: bool = False
frontend_repo_url: str = ""
frontend_repo: str = ""
netdaemon_path: str = "netdaemon/apps/"
netdaemon: bool = False
plugin_path: str = "www/community/"
python_script_path: str = "python_scripts/"
python_script: bool = False
release_limit: int = 5
sidepanel_icon: str = "hacs:hacs"
sidepanel_title: str = "HACS"
theme_path: str = "themes/"
theme: bool = False
token: str = None
def to_json(self) -> str:
"""Return a json string."""
return asdict(self)
def update_from_dict(self, data: dict) -> None:
"""Set attributes from dicts."""
if not isinstance(data, dict):
raise HacsException("Configuration is not valid.")
for key in data:
self.__setattr__(key, data[key])
@dataclass
class HacsCore:
"""HACS Core info."""
config_path: pathlib.Path | None = None
ha_version: AwesomeVersion | None = None
lovelace_mode = LovelaceMode("yaml")
@dataclass
class HacsCommon:
"""Common for HACS."""
categories: set[str] = field(default_factory=set)
renamed_repositories: dict[str, str] = field(default_factory=dict)
archived_repositories: list[str] = field(default_factory=list)
ignored_repositories: list[str] = field(default_factory=list)
skip: list[str] = field(default_factory=list)
@dataclass
class HacsStatus:
"""HacsStatus."""
startup: bool = True
new: bool = False
reloading_data: bool = False
upgrading_all: bool = False
@dataclass
class HacsSystem:
"""HACS System info."""
disabled_reason: HacsDisabledReason | None = None
running: bool = False
stage = HacsStage.SETUP
action: bool = False
@property
def disabled(self) -> bool:
"""Return if HACS is disabled."""
return self.disabled_reason is not None
@dataclass
class HacsRepositories:
"""HACS Repositories."""
_default_repositories: set[str] = field(default_factory=set)
_repositories: list[HacsRepository] = field(default_factory=list)
_repositories_by_full_name: dict[str, str] = field(default_factory=dict)
_repositories_by_id: dict[str, str] = field(default_factory=dict)
_removed_repositories: list[RemovedRepository] = field(default_factory=list)
@property
def list_all(self) -> list[HacsRepository]:
"""Return a list of repositories."""
return self._repositories
@property
def list_removed(self) -> list[RemovedRepository]:
"""Return a list of removed repositories."""
return self._removed_repositories
@property
def list_downloaded(self) -> list[HacsRepository]:
"""Return a list of downloaded repositories."""
return [repo for repo in self._repositories if repo.data.installed]
def register(self, repository: HacsRepository, default: bool = False) -> None:
"""Register a repository."""
repo_id = str(repository.data.id)
if repo_id == "0":
return
if self.is_registered(repository_id=repo_id):
return
if repository not in self._repositories:
self._repositories.append(repository)
self._repositories_by_id[repo_id] = repository
self._repositories_by_full_name[repository.data.full_name_lower] = repository
if default:
self.mark_default(repository)
def unregister(self, repository: HacsRepository) -> None:
"""Unregister a repository."""
repo_id = str(repository.data.id)
if repo_id == "0":
return
if not self.is_registered(repository_id=repo_id):
return
if self.is_default(repo_id):
self._default_repositories.remove(repo_id)
if repository in self._repositories:
self._repositories.remove(repository)
self._repositories_by_id.pop(repo_id, None)
self._repositories_by_full_name.pop(repository.data.full_name_lower, None)
def mark_default(self, repository: HacsRepository) -> None:
"""Mark a repository as default."""
repo_id = str(repository.data.id)
if repo_id == "0":
return
if not self.is_registered(repository_id=repo_id):
return
self._default_repositories.add(repo_id)
def set_repository_id(self, repository, repo_id):
"""Update a repository id."""
existing_repo_id = str(repository.data.id)
if existing_repo_id == repo_id:
return
if existing_repo_id != "0":
raise ValueError(
f"The repo id for {repository.data.full_name_lower} "
f"is already set to {existing_repo_id}"
)
repository.data.id = repo_id
self.register(repository)
def is_default(self, repository_id: str | None = None) -> bool:
"""Check if a repository is default."""
if not repository_id:
return False
return repository_id in self._default_repositories
def is_registered(
self,
repository_id: str | None = None,
repository_full_name: str | None = None,
) -> bool:
"""Check if a repository is registered."""
if repository_id is not None:
return repository_id in self._repositories_by_id
if repository_full_name is not None:
return repository_full_name in self._repositories_by_full_name
return False
def is_downloaded(
self,
repository_id: str | None = None,
repository_full_name: str | None = None,
) -> bool:
"""Check if a repository is registered."""
if repository_id is not None:
repo = self.get_by_id(repository_id)
if repository_full_name is not None:
repo = self.get_by_full_name(repository_full_name)
if repo is None:
return False
return repo.data.installed
def get_by_id(self, repository_id: str | None) -> HacsRepository | None:
"""Get repository by id."""
if not repository_id:
return None
return self._repositories_by_id.get(str(repository_id))
def get_by_full_name(self, repository_full_name: str | None) -> HacsRepository | None:
"""Get repository by full name."""
if not repository_full_name:
return None
return self._repositories_by_full_name.get(repository_full_name.lower())
def is_removed(self, repository_full_name: str) -> bool:
"""Check if a repository is removed."""
return repository_full_name in (
repository.repository for repository in self._removed_repositories
)
def removed_repository(self, repository_full_name: str) -> RemovedRepository:
"""Get repository by full name."""
if self.is_removed(repository_full_name):
if removed := [
repository
for repository in self._removed_repositories
if repository.repository == repository_full_name
]:
return removed[0]
removed = RemovedRepository(repository=repository_full_name)
self._removed_repositories.append(removed)
return removed
class HacsBase:
"""Base HACS class."""
common = HacsCommon()
configuration = HacsConfiguration()
core = HacsCore()
data: HacsData | None = None
frontend_version: str | None = None
github: GitHub | None = None
githubapi: GitHubAPI | None = None
hass: HomeAssistant | None = None
integration: Integration | None = None
log: logging.Logger = get_hacs_logger()
queue: QueueManager | None = None
recuring_tasks = []
repositories: HacsRepositories = HacsRepositories()
repository: AIOGitHubAPIRepository | None = None
session: ClientSession | None = None
stage: HacsStage | None = None
status = HacsStatus()
system = HacsSystem()
validation: ValidationManager | None = None
version: str | None = None
@property
def integration_dir(self) -> pathlib.Path:
"""Return the HACS integration dir."""
return self.integration.file_path
def set_stage(self, stage: HacsStage | None) -> None:
"""Set HACS stage."""
if stage and self.stage == stage:
return
self.stage = stage
if stage is not None:
self.log.info("Stage changed: %s", self.stage)
self.async_dispatch(HacsDispatchEvent.STAGE, {"stage": self.stage})
def disable_hacs(self, reason: HacsDisabledReason) -> None:
"""Disable HACS."""
if self.system.disabled_reason == reason:
return
self.system.disabled_reason = reason
if reason != HacsDisabledReason.REMOVED:
self.log.error("HACS is disabled - %s", reason)
if (
reason == HacsDisabledReason.INVALID_TOKEN
and self.configuration.config_type == ConfigurationType.CONFIG_ENTRY
):
self.configuration.config_entry.state = ConfigEntryState.SETUP_ERROR
self.configuration.config_entry.reason = "Authentication failed"
self.hass.add_job(self.configuration.config_entry.async_start_reauth, self.hass)
def enable_hacs(self) -> None:
"""Enable HACS."""
if self.system.disabled_reason is not None:
self.system.disabled_reason = None
self.log.info("HACS is enabled")
def enable_hacs_category(self, category: HacsCategory) -> None:
"""Enable HACS category."""
if category not in self.common.categories:
self.log.info("Enable category: %s", category)
self.common.categories.add(category)
def disable_hacs_category(self, category: HacsCategory) -> None:
"""Disable HACS category."""
if category in self.common.categories:
self.log.info("Disabling category: %s", category)
self.common.categories.pop(category)
async def async_save_file(self, file_path: str, content: Any) -> bool:
"""Save a file."""
def _write_file():
with open(
file_path,
mode="w" if isinstance(content, str) else "wb",
encoding="utf-8" if isinstance(content, str) else None,
errors="ignore" if isinstance(content, str) else None,
) as file_handler:
file_handler.write(content)
# Create gz for .js files
if os.path.isfile(file_path):
if file_path.endswith(".js"):
with open(file_path, "rb") as f_in:
with gzip.open(file_path + ".gz", "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
# LEGACY! Remove with 2.0
if "themes" in file_path and file_path.endswith(".yaml"):
filename = file_path.split("/")[-1]
base = file_path.split("/themes/")[0]
combined = f"{base}/themes/{filename}"
if os.path.exists(combined):
self.log.info("Removing old theme file %s", combined)
os.remove(combined)
try:
await self.hass.async_add_executor_job(_write_file)
except BaseException as error: # lgtm [py/catch-base-exception] pylint: disable=broad-except
self.log.error("Could not write data to %s - %s", file_path, error)
return False
return os.path.exists(file_path)
async def async_can_update(self) -> int:
"""Helper to calculate the number of repositories we can fetch data for."""
try:
response = await self.async_github_api_method(self.githubapi.rate_limit)
if ((limit := response.data.resources.core.remaining or 0) - 1000) >= 10:
return math.floor((limit - 1000) / 10)
reset = dt.as_local(dt.utc_from_timestamp(response.data.resources.core.reset))
self.log.info(
"GitHub API ratelimited - %s remaining (%s)",
response.data.resources.core.remaining,
f"{reset.hour}:{reset.minute}:{reset.second}",
)
self.disable_hacs(HacsDisabledReason.RATE_LIMIT)
except BaseException as exception: # lgtm [py/catch-base-exception] pylint: disable=broad-except
self.log.exception(exception)
return 0
async def async_github_get_hacs_default_file(self, filename: str) -> list:
"""Get the content of a default file."""
response = await self.async_github_api_method(
method=self.githubapi.repos.contents.get,
repository=HacsGitHubRepo.DEFAULT,
path=filename,
)
if response is None:
return []
return json.loads(decode_content(response.data.content))
async def async_github_api_method(
self,
method: Callable[[], Awaitable[TV]],
*args,
raise_exception: bool = True,
**kwargs,
) -> TV | None:
"""Call a GitHub API method"""
_exception = None
try:
return await method(*args, **kwargs)
except GitHubAuthenticationException as exception:
self.disable_hacs(HacsDisabledReason.INVALID_TOKEN)
_exception = exception
except GitHubRatelimitException as exception:
self.disable_hacs(HacsDisabledReason.RATE_LIMIT)
_exception = exception
except GitHubNotModifiedException as exception:
raise exception
except GitHubException as exception:
_exception = exception
except BaseException as exception: # lgtm [py/catch-base-exception] pylint: disable=broad-except
self.log.exception(exception)
_exception = exception
if raise_exception and _exception is not None:
raise HacsException(_exception)
return None
async def async_register_repository(
self,
repository_full_name: str,
category: HacsCategory,
*,
check: bool = True,
ref: str | None = None,
repository_id: str | None = None,
default: bool = False,
) -> None:
"""Register a repository."""
if repository_full_name in self.common.skip:
if repository_full_name != HacsGitHubRepo.INTEGRATION:
raise HacsExpectedException(f"Skipping {repository_full_name}")
if repository_full_name == "home-assistant/core":
raise HomeAssistantCoreRepositoryException()
if repository_full_name == "home-assistant/addons" or repository_full_name.startswith(
"hassio-addons/"
):
raise AddonRepositoryException()
if category not in RERPOSITORY_CLASSES:
raise HacsException(f"{category} is not a valid repository category.")
if (renamed := self.common.renamed_repositories.get(repository_full_name)) is not None:
repository_full_name = renamed
repository: HacsRepository = RERPOSITORY_CLASSES[category](self, repository_full_name)
if check:
try:
await repository.async_registration(ref)
if self.status.new:
repository.data.new = False
if repository.validate.errors:
self.common.skip.append(repository.data.full_name)
if not self.status.startup:
self.log.error("Validation for %s failed.", repository_full_name)
if self.system.action:
raise HacsException(
f"::error:: Validation for {repository_full_name} failed."
)
return repository.validate.errors
if self.system.action:
repository.logger.info("%s Validation completed", repository.string)
else:
repository.logger.info("%s Registration completed", repository.string)
except (HacsRepositoryExistException, HacsRepositoryArchivedException):
return
except AIOGitHubAPIException as exception:
self.common.skip.append(repository.data.full_name)
raise HacsException(
f"Validation for {repository_full_name} failed with {exception}."
) from exception
if repository_id is not None:
repository.data.id = repository_id
if str(repository.data.id) != "0" and (
exists := self.repositories.get_by_id(repository.data.id)
):
self.repositories.unregister(exists)
else:
if self.hass is not None and ((check and repository.data.new) or self.status.new):
self.async_dispatch(
HacsDispatchEvent.REPOSITORY,
{
"action": "registration",
"repository": repository.data.full_name,
"repository_id": repository.data.id,
},
)
self.repositories.register(repository, default)
async def startup_tasks(self, _=None) -> None:
"""Tasks that are started after setup."""
self.set_stage(HacsStage.STARTUP)
try:
repository = self.repositories.get_by_full_name(HacsGitHubRepo.INTEGRATION)
if repository is None:
await self.async_register_repository(
repository_full_name=HacsGitHubRepo.INTEGRATION,
category=HacsCategory.INTEGRATION,
default=True,
)
repository = self.repositories.get_by_full_name(HacsGitHubRepo.INTEGRATION)
if repository is None:
raise HacsException("Unknown error")
repository.data.installed = True
repository.data.installed_version = self.integration.version.string
repository.data.new = False
repository.data.releases = True
self.repository = repository.repository_object
self.repositories.mark_default(repository)
except HacsException as exception:
if "403" in str(exception):
self.log.critical(
"GitHub API is ratelimited, or the token is wrong.",
)
else:
self.log.critical("Could not load HACS! - %s", exception)
self.disable_hacs(HacsDisabledReason.LOAD_HACS)
if critical := await async_load_from_store(self.hass, "critical"):
for repo in critical:
if not repo["acknowledged"]:
self.log.critical("URGENT!: Check the HACS panel!")
self.hass.components.persistent_notification.create(
title="URGENT!", message="**Check the HACS panel!**"
)
break
self.recuring_tasks.append(
self.hass.helpers.event.async_track_time_interval(
self.async_get_all_category_repositories, timedelta(hours=3)
)
)
self.recuring_tasks.append(
self.hass.helpers.event.async_track_time_interval(
self.async_update_all_repositories, timedelta(hours=25)
)
)
self.recuring_tasks.append(
self.hass.helpers.event.async_track_time_interval(
self.async_check_rate_limit, timedelta(minutes=5)
)
)
self.recuring_tasks.append(
self.hass.helpers.event.async_track_time_interval(
self.async_prosess_queue, timedelta(minutes=10)
)
)
self.recuring_tasks.append(
self.hass.helpers.event.async_track_time_interval(
self.async_update_downloaded_repositories, timedelta(hours=2)
)
)
self.recuring_tasks.append(
self.hass.helpers.event.async_track_time_interval(
self.async_handle_critical_repositories, timedelta(hours=2)
)
)
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_FINAL_WRITE, self.data.async_force_write
)
self.status.startup = False
self.async_dispatch(HacsDispatchEvent.STATUS, {})
await self.async_handle_removed_repositories()
await self.async_get_all_category_repositories()
await self.async_update_downloaded_repositories()
self.set_stage(HacsStage.RUNNING)
self.async_dispatch(HacsDispatchEvent.RELOAD, {"force": True})
await self.async_handle_critical_repositories()
await self.async_prosess_queue()
self.async_dispatch(HacsDispatchEvent.STATUS, {})
async def async_download_file(self, url: str, *, headers: dict | None = None) -> bytes | None:
"""Download files, and return the content."""
if url is None:
return None
if "tags/" in url:
url = url.replace("tags/", "")
self.log.debug("Downloading %s", url)
timeouts = 0
while timeouts < 5:
try:
request = await self.session.get(
url=url,
timeout=ClientTimeout(total=60),
headers=headers,
)
# Make sure that we got a valid result
if request.status == 200:
return await request.read()
raise HacsException(
f"Got status code {request.status} when trying to download {url}"
)
except asyncio.TimeoutError:
self.log.warning(
"A timeout of 60! seconds was encountered while downloading %s, "
"using over 60 seconds to download a single file is not normal. "
"This is not a problem with HACS but how your host communicates with GitHub. "
"Retrying up to 5 times to mask/hide your host/network problems to "
"stop the flow of issues opened about it. "
"Tries left %s",
url,
(4 - timeouts),
)
timeouts += 1
await asyncio.sleep(1)
continue
except BaseException as exception: # lgtm [py/catch-base-exception] pylint: disable=broad-except
self.log.exception("Download failed - %s", exception)
return None
async def async_recreate_entities(self) -> None:
"""Recreate entities."""
if self.configuration == ConfigurationType.YAML or not self.configuration.experimental:
return
platforms = [Platform.SENSOR, Platform.UPDATE]
await self.hass.config_entries.async_unload_platforms(
entry=self.configuration.config_entry,
platforms=platforms,
)
self.hass.config_entries.async_setup_platforms(self.configuration.config_entry, platforms)
@callback
def async_dispatch(self, signal: HacsDispatchEvent, data: dict | None = None) -> None:
"""Dispatch a signal with data."""
async_dispatcher_send(self.hass, signal, data)
def set_active_categories(self) -> None:
"""Set the active categories."""
self.common.categories = set()
for category in (HacsCategory.INTEGRATION, HacsCategory.PLUGIN):
self.enable_hacs_category(HacsCategory(category))
if HacsCategory.PYTHON_SCRIPT in self.hass.config.components:
self.enable_hacs_category(HacsCategory.PYTHON_SCRIPT)
if self.hass.services.has_service("frontend", "reload_themes"):
self.enable_hacs_category(HacsCategory.THEME)
if self.configuration.appdaemon:
self.enable_hacs_category(HacsCategory.APPDAEMON)
if self.configuration.netdaemon:
self.enable_hacs_category(HacsCategory.NETDAEMON)
async def async_get_all_category_repositories(self, _=None) -> None:
"""Get all category repositories."""
if self.system.disabled:
return
self.log.info("Loading known repositories")
await asyncio.gather(
*[
self.async_get_category_repositories(HacsCategory(category))
for category in self.common.categories or []
]
)
async def async_get_category_repositories(self, category: HacsCategory) -> None:
"""Get repositories from category."""
if self.system.disabled:
return
try:
repositories = await self.async_github_get_hacs_default_file(category)
except HacsException:
return
for repo in repositories:
if self.common.renamed_repositories.get(repo):
repo = self.common.renamed_repositories[repo]
if self.repositories.is_removed(repo):
continue
if repo in self.common.archived_repositories:
continue
repository = self.repositories.get_by_full_name(repo)
if repository is not None:
self.repositories.mark_default(repository)
if self.status.new and self.configuration.dev:
# Force update for new installations
self.queue.add(repository.common_update())
continue
self.queue.add(
self.async_register_repository(
repository_full_name=repo,
category=category,
default=True,
)
)
async def async_update_all_repositories(self, _=None) -> None:
"""Update all repositories."""
if self.system.disabled:
return
self.log.debug("Starting recurring background task for all repositories")
for repository in self.repositories.list_all:
if repository.data.category in self.common.categories:
self.queue.add(repository.common_update())
self.async_dispatch(HacsDispatchEvent.REPOSITORY, {"action": "reload"})
self.log.debug("Recurring background task for all repositories done")
async def async_check_rate_limit(self, _=None) -> None:
"""Check rate limit."""
if not self.system.disabled or self.system.disabled_reason != HacsDisabledReason.RATE_LIMIT:
return
self.log.debug("Checking if ratelimit has lifted")
can_update = await self.async_can_update()
self.log.debug("Ratelimit indicate we can update %s", can_update)
if can_update > 0:
self.enable_hacs()
await self.async_prosess_queue()
async def async_prosess_queue(self, _=None) -> None:
"""Process the queue."""
if self.system.disabled:
self.log.debug("HACS is disabled")
return
if not self.queue.has_pending_tasks:
self.log.debug("Nothing in the queue")
return
if self.queue.running:
self.log.debug("Queue is already running")
return
async def _handle_queue():
if not self.queue.has_pending_tasks:
await self.data.async_write()
return
can_update = await self.async_can_update()
self.log.debug(
"Can update %s repositories, " "items in queue %s",
can_update,
self.queue.pending_tasks,
)
if can_update != 0:
try:
await self.queue.execute(can_update)
except HacsExecutionStillInProgress:
return
await _handle_queue()
await _handle_queue()
async def async_handle_removed_repositories(self, _=None) -> None:
"""Handle removed repositories."""
if self.system.disabled:
return
need_to_save = False
self.log.info("Loading removed repositories")
try:
removed_repositories = await self.async_github_get_hacs_default_file(
HacsCategory.REMOVED
)
except HacsException:
return
for item in removed_repositories:
removed = self.repositories.removed_repository(item["repository"])
removed.update_data(item)
for removed in self.repositories.list_removed:
if (repository := self.repositories.get_by_full_name(removed.repository)) is None:
continue
if repository.data.full_name in self.common.ignored_repositories:
continue
if repository.data.installed and removed.removal_type != "critical":
self.log.warning(
"You have '%s' installed with HACS "
"this repository has been removed from HACS, please consider removing it. "
"Removal reason (%s)",
repository.data.full_name,
removed.reason,
)
else:
need_to_save = True
repository.remove()
if need_to_save:
await self.data.async_write()
async def async_update_downloaded_repositories(self, _=None) -> None:
"""Execute the task."""
if self.system.disabled:
return
self.log.info("Starting recurring background task for downloaded repositories")
for repository in self.repositories.list_downloaded:
if repository.data.category in self.common.categories:
self.queue.add(repository.update_repository(ignore_issues=True))
self.log.debug("Recurring background task for downloaded repositories done")
async def async_handle_critical_repositories(self, _=None) -> None:
"""Handle critical repositories."""
critical_queue = QueueManager(hass=self.hass)
instored = []
critical = []
was_installed = False
try:
critical = await self.async_github_get_hacs_default_file("critical")
except GitHubNotModifiedException:
return
except HacsException:
pass
if not critical:
self.log.debug("No critical repositories")
return
stored_critical = await async_load_from_store(self.hass, "critical")
for stored in stored_critical or []:
instored.append(stored["repository"])
stored_critical = []
for repository in critical:
removed_repo = self.repositories.removed_repository(repository["repository"])
removed_repo.removal_type = "critical"
repo = self.repositories.get_by_full_name(repository["repository"])
stored = {
"repository": repository["repository"],
"reason": repository["reason"],
"link": repository["link"],
"acknowledged": True,
}
if repository["repository"] not in instored:
if repo is not None and repo.data.installed:
self.log.critical(
"Removing repository %s, it is marked as critical",
repository["repository"],
)
was_installed = True
stored["acknowledged"] = False
# Remove from HACS
critical_queue.add(repo.uninstall())
repo.remove()
stored_critical.append(stored)
removed_repo.update_data(stored)
# Uninstall
await critical_queue.execute()
# Save to FS
await async_save_to_store(self.hass, "critical", stored_critical)
# Restart HASS
if was_installed:
self.log.critical("Restarting Home Assistant")
self.hass.async_create_task(self.hass.async_stop(100))
|
<reponame>nicholaspcr/Inicia-o_Cient-fica
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pymoo.factory import get_problem, get_performance_indicator, get_reference_directions, get_visualization
from pymoo.performance_indicator.hv import Hypervolume
import os
import sys
# important methods -> ref_point
ref_point = np.array([ 2.9699152058577947 , 4.985423795813952, 6.988314095918014])
metric = Hypervolume(ref_point=ref_point, normalize=False)
problem = "wfg1"
# 1 -> [488.4435867485893 ,471.03860764532106 , 501.59485141330845 ]
# 2 -> [ 2.7640053099955044, 2.5431893060817545 , 2.676556552035201]
# 3 -> [ 1692.099007341335 , 1678.2523471910183 , 1812.180711990459 ]
# 4 -> [ 2.80704182512513 , 2.6906135709301386 , 2.534695795120166]
# 5 -> [ 2.352652061652649 , 2.504239438737515 , 2.7298272947925213]
# 6 -> [ 10.548625453871612 , 10.612209406392823 , 10.634665459827534 ]
# 7 -> [ 1, 1, 27.9038366074846 ]
# WFGS
# 1 -> [ 2.9699152058577947 , 4.985423795813952, 6.988314095918014]
# general constants
NUM_EXECS = 30
variants = ["rand1", "rand2", "best1", "best2", "currtobest1", "pbest/P-0.05", "pbest/P-0.1", "pbest/P-0.15", "pbest/P-0.2"]
#
base_path = "/home/nick/.gode/mode/paretoFront/" + problem + "/"
# data for the plot
HVData = []
# file related constants
GEN = 251
NP = 100
for varIndex in range(len(variants)):
execFiles = []
# reads from each execution of the variant
for i in range(NUM_EXECS):
filePath = base_path + variants[varIndex] + "/exec-" + str(i+1) + '.csv'
execFiles.append(
pd.read_csv(
filePath,
sep=';|\n', engine='python'
)
)
# data of variant
variantHV = np.array([])
for i in range(GEN):
genHV = 0.0
for file in execFiles:
# A = np.reshape(file["A"], (NP,GEN))
A = file["A"]
B = file["B"]
C = file["C"]
genData = []
for j in range(NP*i, NP*(i+1)):
genData.append(np.array([
A[j],
B[j],
C[j]
]))
#genData = np.array([
# A[i*NP:(i+1)*NP],
# B[i*NP:(i+1)*NP],
# C[i*NP:(i+1)*NP]
#])
genHV = genHV + metric.calc(np.array(genData))
genHV = genHV / float(len(execFiles))
variantHV = np.append(variantHV, genHV)
HVData.append(variantHV)
#for gen in range(0, GEN):
# # sum of the avarage HV of each element
# genHV = 0.0
# for file in execFiles:
# populationArray = []
# for i in range(NP):
# populationArray.append(np.array([
# file.iloc[(gen*3)][i],
# file.iloc[(gen*3)+1][i],
# file.iloc[(gen*3)+2][i],
# ]))
# variantArray = np.array(populationArray)
# genHV = genHV + metric.calc(variantArray)
# genHV = genHV / float(len(execFiles))
# variantHV = np.append(variantHV, genHV)
#HVData.append(variantHV)
for i in range(len(HVData)):
x = np.linspace(0, len(HVData[i]), len(HVData[i]))
plt.scatter(x, HVData[i], s=2, alpha=0.6, label=variants[i])
plt.title(problem)
plt.suptitle("Average Hypervolume per Generations")
plt.xlabel("generations")
plt.ylabel("HV")
plt.legend()
plt.show()
|
import os
import pytest
import subprocess
import time
import unittest
from tests.e2e import setup_e2e
debug_log = "--logging-level=DEBUG"
indexing_sleep_time = 1 # wait 1 second to confirm server has indexed updates
project_name = "not-default-name"
group_name = "test-ing-group"
workbook_name = "namebasic"
# to run this suite:
# pytest -q tests/e2e/language_tests.py
# you can either run setup with a stored credentials file, or simply log in
# before running the suite so a session is active
# All tests in this suite are about handling non-English language scenarios
def _test_command(test_args: list[str]):
# this will raise an exception if it gets a non-zero return code
# that should bubble up and fail the test?
# dist/exe calling_args = [setup_e2e.exe] + test_args + [debug_log]
calling_args = ["python", "-m", "tabcmd"] + test_args + [debug_log] + ["--language", "fr", "--no-certcheck"]
print(calling_args)
return subprocess.check_call(calling_args)
# This calls dist/tabcmd/tabcmd.exe
class OnlineCommandTest(unittest.TestCase):
published = False
gotten = False
@pytest.mark.order(1)
def test_login_all_languages(self):
languages = ["de", "en", "es", "fr", "it", "ja", "ko", "pt", "sv", "zh"]
failed = False
for lang in languages:
try:
setup_e2e.login("--language", lang)
except Exception as e:
failed = True
print("FAILED on {}".format(lang))
if failed:
raise SystemExit(2)
def _create_project(self, project_name, parent_path=None):
command = "createproject"
arguments = [command, "--name", project_name]
if parent_path:
arguments.append("--parent-project-path")
arguments.append(parent_path)
print(arguments)
_test_command(arguments)
def _delete_project(self, project_name, parent_path=None):
command = "deleteproject"
arguments = [command, project_name]
if parent_path:
arguments.append("--parent-project-path")
arguments.append(parent_path)
_test_command(arguments)
def _publish_samples(self, project_name):
command = "publishsamples"
arguments = [command, "--name", project_name]
_test_command(arguments)
def _publish_wb(self, file, name):
command = "publish"
arguments = [command, file, "--name", name, "--overwrite"]
return _test_command(arguments)
def _delete_wb(self, file):
command = "delete"
arguments = [command, "-w", file]
_test_command(arguments)
def _get_view(self, wb_name_on_server, sheet_name):
server_file = "/views/" + wb_name_on_server + "/" + sheet_name
command = "get"
arguments = [command, server_file]
_test_command(arguments)
def _get_custom_view(self):
command = "get"
def _get_view_with_filters(self):
command = "get"
def _create_extract(self, wb_name):
command = "createextracts"
arguments = [command, "-w", wb_name, "--encrypt"]
_test_command(arguments)
# variation: url
def _refresh_extract(self, wb_name):
command = "refreshextracts"
arguments = [command, "--workbook", wb_name]
_test_command(arguments)
def _delete_extract(self, wb_name):
command = "deleteextracts"
arguments = [command, "-w", wb_name]
_test_command(arguments)
# actual tests
TWBX_FILE_WITH_EXTRACT = "extract-data-access.twbx"
TWBX_WITH_EXTRACT_NAME = "WorkbookWithExtract"
TWBX_WITH_EXTRACT_SHEET = "sheet1"
TWBX_FILE_WITHOUT_EXTRACT = "simple-data.twbx"
TWBX_WITHOUT_EXTRACT_NAME = "WorkbookWithoutExtract"
@pytest.mark.order(2)
def test_create_site_users(self):
command = "createsiteusers"
users = os.path.join("tests", "assets", "detailed_users.csv")
arguments = [command, users, "--role", "Publisher"]
_test_command(arguments)
@pytest.mark.order(3)
def test_creategroup(self):
groupname = group_name
command = "creategroup"
arguments = [command, groupname]
_test_command(arguments)
@pytest.mark.order(4)
def test_add_users_to_group(self):
groupname = group_name
command = "addusers"
filename = os.path.join("tests", "assets", "usernames.csv")
arguments = [command, groupname, "--users", filename]
_test_command(arguments)
@pytest.mark.order(5)
def test_remove_users_to_group(self):
groupname = group_name
command = "removeusers"
filename = os.path.join("tests", "assets", "usernames.csv")
arguments = [command, groupname, "--users", filename]
_test_command(arguments)
@pytest.mark.order(6)
def test_deletegroup(self):
groupname = group_name
command = "deletegroup"
arguments = [command, groupname]
_test_command(arguments)
@pytest.mark.order(7)
def test_publish_samples(self):
project_name = "sample-proj"
self._create_project(project_name)
time.sleep(indexing_sleep_time)
self._publish_samples(project_name)
self._delete_project(project_name)
@pytest.mark.order(8)
def test_create_projects(self):
# project 1
self._create_project(project_name)
time.sleep(indexing_sleep_time)
# project 2
self._create_project("project_name_2", project_name)
time.sleep(indexing_sleep_time)
# project 3
parent_path = "{0}/{1}".format(project_name, project_name)
self._create_project(project_name, parent_path)
time.sleep(indexing_sleep_time)
@pytest.mark.order(9)
def test_delete_projects(self):
self._delete_project("project_name_2", project_name) # project 2
self._delete_project(project_name)
@pytest.mark.order(10)
def test_publish(self):
name_on_server = OnlineCommandTest.TWBX_WITH_EXTRACT_NAME
file = os.path.join("tests", "assets", OnlineCommandTest.TWBX_FILE_WITH_EXTRACT)
self._publish_wb(file, name_on_server)
@pytest.mark.order(10)
def test__get_wb(self):
wb_name_on_server = OnlineCommandTest.TWBX_WITH_EXTRACT_NAME
self._get_workbook(wb_name_on_server + ".twbx")
@pytest.mark.order(10)
def test__get_view(self):
wb_name_on_server = OnlineCommandTest.TWBX_WITH_EXTRACT_NAME
sheet_name = OnlineCommandTest.TWBX_WITH_EXTRACT_SHEET
self._get_view(wb_name_on_server, sheet_name + ".pdf")
@pytest.mark.order(11)
def test__delete_wb(self):
name_on_server = OnlineCommandTest.TWBX_WITH_EXTRACT_NAME
self._delete_wb(name_on_server)
@pytest.mark.order(12)
def test_create_extract(self):
# This workbook doesn't work for creating an extract
name_on_server = OnlineCommandTest.TWBX_WITHOUT_EXTRACT_NAME
file = os.path.join("tests", "assets", OnlineCommandTest.TWBX_FILE_WITHOUT_EXTRACT)
self._publish_wb(file, name_on_server)
# which damn workbook will work here self._create_extract(name_on_server)
@pytest.mark.order(13)
def test_refresh_extract(self):
name_on_server = OnlineCommandTest.TWBX_WITH_EXTRACT_NAME
self._refresh_extract(name_on_server)
@pytest.mark.order(14)
def test_delete_extract(self):
name_on_server = OnlineCommandTest.TWBX_WITH_EXTRACT_NAME
file = os.path.join("tests", "assets", OnlineCommandTest.TWBX_FILE_WITH_EXTRACT)
self._publish_wb(file, name_on_server)
# self._delete_extract(name_on_server)
self._delete_wb(name_on_server)
def test_version(self):
_test_command(["-v"])
def test_help(self):
_test_command(["help"])
# this just gets in the way :(
# def test_logout(self):
# _test_command(["logout"])
@pytest.mark.order(15)
def test_export(self):
name_on_server = OnlineCommandTest.TWBX_WITH_EXTRACT_NAME
file = os.path.join("tests", "assets", OnlineCommandTest.TWBX_FILE_WITH_EXTRACT)
self._publish_wb(file, name_on_server)
command = "export"
friendly_name = name_on_server + "/" + OnlineCommandTest.TWBX_WITH_EXTRACT_SHEET
arguments = [command, friendly_name, "--fullpdf", "-f", "exported_file.pdf"]
_test_command(arguments)
@pytest.mark.order(16)
def test_delete_site_users(self):
command = "deletesiteusers"
users = os.path.join("tests", "assets", "usernames.csv")
_test_command([command, users])
|
<reponame>nanusefue/CAP2-1<filename>cap2/extensions/experimental/tcems/cli.py
import click
import luigi
import time
import logging
from .tcem_repertoire import TcemRepertoire
from .tcem_aa_db import TcemNrAaDb
from ....pangea.cli import set_config
from ....pangea.api import (
wrap_task,
recursively_wrap_task,
)
from ....pangea.pangea_sample import PangeaGroup, PangeaTag
from ....pipeline.preprocessing import (
BaseReads,
)
from ....constants import DATA_TYPES
from ....utils import chunks
from ....setup_logging import *
import logging
logger = logging.getLogger('cap2')
@click.group('tcems')
def tcems_cli():
pass
@tcems_cli.group('run')
def run_cli():
pass
def get_task_list_for_sample(sample, stage, config, **kwargs):
base_reads = wrap_task(
sample, BaseReads, config_path=config, requires_reads=True, **kwargs
)
base_reads.upload_allowed = False
tcem_rep = recursively_wrap_task(
sample,
TcemRepertoire,
config_path=config,
module_substitute_tasks={BaseReads: base_reads},
**kwargs,
)
tasks = [tcem_rep]
return tasks
def _process_one_sample_chunk(chunk, scheduler_url, workers,
stage, config, clean_reads, **kwargs):
tasks = []
for sample in chunk:
tasks += get_task_list_for_sample(
sample, stage, config, **kwargs
)
if not scheduler_url:
luigi.build(tasks, local_scheduler=True, workers=workers)
else:
luigi.build(tasks, scheduler_url=scheduler_url, workers=workers)
return chunk
def _process_samples_in_chunks(samples, scheduler_url, batch_size, timelimit, workers,
stage, config, clean_reads, **kwargs):
start_time, completed = time.time(), []
logger.info(f'Processing {len(samples)} samples')
for chunk in chunks(samples, batch_size):
logger.info(f'Completed processing {len(completed)} samples')
if timelimit and (time.time() - start_time) > (60 * 60 * timelimit):
logger.info(f'Timelimit reached. Stopping.')
return completed
completed += _process_one_sample_chunk(
chunk, scheduler_url, workers,
stage, config, clean_reads, **kwargs
)
return completed
@run_cli.command('db')
@click.option('-c', '--config', type=click.Path(), default='', envvar='CAP2_CONFIG')
@click.option('-l', '--log-level', default=30)
@click.option('--scheduler-url', default=None, envvar='CAP2_LUIGI_SCHEDULER_URL')
@click.option('-w', '--workers', default=1)
@click.option('-t', '--threads', default=1)
def cli_run_db(config, log_level, scheduler_url, workers, threads):
logger.info('Building TCEM databases')
instance = TcemNrAaDb(cores=threads, config_filename=config)
tasks = [instance]
if not scheduler_url:
luigi.build(tasks, local_scheduler=True, workers=workers)
else:
luigi.build(tasks, scheduler_url=scheduler_url, workers=workers)
@run_cli.command('samples')
@click.option('-c', '--config', type=click.Path(), default='', envvar='CAP2_CONFIG')
@click.option('-l', '--log-level', default=30)
@click.option('--clean-reads/--all-reads', default=False)
@click.option('--upload/--no-upload', default=True)
@click.option('--download-only/--run', default=False)
@click.option('--scheduler-url', default=None, envvar='CAP2_LUIGI_SCHEDULER_URL')
@click.option('--max-attempts', default=2)
@click.option('-k', '--data-kind', default='short_read', type=click.Choice(DATA_TYPES))
@click.option('-b', '--batch-size', default=10, help='Number of samples to process in parallel')
@click.option('-w', '--workers', default=1)
@click.option('-t', '--threads', default=1)
@click.option('--timelimit', default=0, help='Stop adding jobs after N hours')
@click.option('--endpoint', default='https://pangea.gimmebio.com')
@click.option('-e', '--email', envvar='PANGEA_USER')
@click.option('-p', '--password', envvar='PANGEA_PASS')
@click.option('-s', '--stage', type=click.Choice(['all']))
@click.option('--random-seed', type=int, default=None)
@click.argument('org_name')
@click.argument('grp_name')
def cli_run_samples(config, log_level, clean_reads, upload, download_only, scheduler_url,
max_attempts, data_kind,
batch_size, workers, threads, timelimit,
endpoint, email, password, stage, random_seed,
org_name, grp_name):
set_config(endpoint, email, password, org_name, grp_name,
upload_allowed=upload, download_only=download_only, name_is_uuid=True, data_kind=data_kind)
group = PangeaGroup(grp_name, email, password, endpoint, org_name)
samples = [
samp for samp in group.pangea_samples(randomize=True, seed=random_seed, kind=data_kind)
if not clean_reads or samp.has_clean_reads()
]
completed = _process_samples_in_chunks(
samples, scheduler_url, batch_size, timelimit, workers,
stage, config, clean_reads, cores=threads,
)
|
import os
import cv2
import torch
import pickle
import tempfile
import numpy as np
from utils_cv.action_recognition.dataset import VideoDataset, \
get_transforms, get_default_tfms_config
from perception.common.video import read_frames_dir, read_all_frames
from interaction.scenario import scenario_to_id, id_to_scenario, \
scenario_classes
from interaction.common.data_v2 import check_passive_interaction, sample_frames
from interaction.common.utils import timestamp_to_ms
def get_tfms_config(for_train):
cfg = get_default_tfms_config(for_train)
cfg.set('random_crop', False)
cfg.set('input_size', 224)
cfg.set('im_scale', 224)
return cfg
def make_boxed_img(img, bg_fill=[128, 128, 128], resize_to=416):
aspect_ratio = min(resize_to * 1.0 / img.shape[0],
resize_to * 1.0 / img.shape[1])
new_h = int(img.shape[0] * aspect_ratio)
new_w = int(img.shape[1] * aspect_ratio)
resized_img = cv2.resize(img, (new_w, new_h))
# Generate canvas with size (resize_to, resize_to)
boxed_img = np.zeros((resize_to, resize_to, 3)).astype(np.uint8)
boxed_img[:, :] = np.array(bg_fill).astype(np.uint8)
# Paste resized image
y_offset = (resize_to - new_h) // 2
x_offset = (resize_to - new_w) // 2
boxed_img[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = resized_img
return boxed_img
class FramesDataset(VideoDataset):
"""
Override some member functions to support v2 dataset
via reading frames.
"""
def __init__(self,
train_dataset_pkl,
test_dataset_pkl,
train_full_neg_txt,
test_full_neg_txt,
eval_txt=None,
group_by='Scenario',
root='data/xiaodu_clips_v2',
neg_root='data/full_neg_data',
wae_lst_pkl='data/raw_wae/wae_lst.pkl',
seed=None,
sample_length=8,
sample_interval=100.,
batch_size=8,
check_passive=False,
warning=True):
assert group_by in ['Scenario', 'WAE_id']
self.group_by = group_by
self.root = root
self.neg_root = neg_root
self.sample_interval = sample_interval
self.check_passive = check_passive
if group_by == 'WAE_id':
wae_lst_len = self._get_wae_lst_len(wae_lst_pkl)
self.classes = ['wae_{}'.format(i) for i in range(wae_lst_len)]
elif group_by == 'Scenario':
self.classes = scenario_classes(version='v2')
train_split_file = self._generate_tmp_split_file(
'train', train_dataset_pkl, train_full_neg_txt)
if eval_txt is None:
test_split_file = self._generate_tmp_split_file(
'test', test_dataset_pkl, test_full_neg_txt)
else:
test_split_file = self._generate_eval_tmp_file(eval_txt)
train_cfg = get_tfms_config(True)
test_cfg = get_tfms_config(False)
super(FramesDataset, self).__init__(
root=root,
seed=seed,
num_samples=1,
sample_length=sample_length,
train_split_file=train_split_file,
test_split_file=test_split_file,
train_transforms=get_transforms(True, train_cfg),
test_transforms=get_transforms(False, test_cfg),
batch_size=batch_size,
warning=warning)
# os.remove(train_split_file)
# os.remove(test_split_file)
def _get_wae_lst_len(self, pkl):
with open(pkl, 'rb') as f:
lst = pickle.load(f)
return len(lst)
def _generate_tmp_split_file(self, split_type, pkl, txt):
pos_anno_lst = []
with open(pkl, 'rb') as f:
for anno in pickle.load(f):
video_id = '{}-{}'.format(anno['VideoID'], anno['Time'])
if self.group_by == 'Scenario':
label = scenario_to_id(anno['Scenario'], version='v2')
label_name = anno['Scenario'].lower().replace(' ', '_')
pos_anno_lst.append([video_id, label, label_name])
elif self.group_by == 'WAE_id':
label = anno['WAE_id']
pos_anno_lst.append([video_id, label])
neg_anno_lst = []
with open(txt, 'r') as f:
for line in f.readlines():
path = line.strip()
video_id = os.path.basename(path)
path = os.path.join(self.neg_root, video_id)
assert os.path.exists(path)
if self.check_passive and check_passive_interaction(path):
continue
if self.group_by == 'Scenario':
label = scenario_to_id('null', version='v2')
label_name = 'null'
neg_anno_lst.append([video_id, label, label_name])
elif self.group_by == 'WAE_id':
label = 0
neg_anno_lst.append([video_id, label])
records = []
if split_type == 'test':
records.extend(neg_anno_lst)
records.extend(pos_anno_lst)
else:
# TODO: rebalance different pos annos
if len(neg_anno_lst) > len(pos_anno_lst):
repeats = int(len(neg_anno_lst) / len(pos_anno_lst))
records.extend(neg_anno_lst)
for _ in range(repeats):
records.extend(pos_anno_lst)
residual = len(neg_anno_lst) % len(pos_anno_lst)
ids = np.arange(len(pos_anno_lst))
np.random.shuffle(ids)
for i in ids[:residual]:
records.append(pos_anno_lst[i])
else:
repeats = int(len(pos_anno_lst) / len(neg_anno_lst))
records.extend(pos_anno_lst)
for _ in range(repeats):
records.extend(neg_anno_lst)
residual = len(pos_anno_lst) % len(neg_anno_lst)
ids = np.arange(len(neg_anno_lst))
np.random.shuffle(ids)
for i in ids[:residual]:
records.append(neg_anno_lst[i])
ids = np.arange(len(records))
np.random.shuffle(ids)
records = [records[i] for i in ids]
fd, path = tempfile.mkstemp(suffix=split_type)
with os.fdopen(fd, 'w') as tmp:
for record in records:
tmp.write(' '.join([str(e) for e in record]) + '\n')
print('Wrote {}'.format(path))
return path
def _generate_eval_tmp_file(self, eval_txt):
records = []
with open(eval_txt, 'r') as f:
for line in f.readlines():
info = line.strip().split(' ')
video_id = '{}-{}'.format(info[1], info[2])
if self.group_by == 'Scenario':
label = int(info[4]) if int(info[0]) == 1 else 0
name = id_to_scenario(label, version='v2')
label_name = name.lower().replace(' ', '_')
records.append([video_id, label, label_name])
elif self.group_by == 'WAE_id':
label = int(info[3]) if int(info[0]) == 1 else 0
records.append([video_id, label])
ids = np.arange(len(records))
np.random.shuffle(ids)
records = [records[i] for i in ids]
fd, path = tempfile.mkstemp(suffix='eval')
with os.fdopen(fd, 'w') as tmp:
for record in records:
tmp.write(' '.join([str(e) for e in record]) + '\n')
print('Wrote {}'.format(path))
return path
def __getitem__(self, idx):
"""
Return:
(clips (torch.tensor), label (int))
"""
record = self.video_records[idx]
if '-' in record.path and ',' not in record.path:
sep = record.path.rindex('-')
video_id = record.path[:sep]
timestamp = record.path[sep:]
te = timestamp_to_ms(timestamp)
ts = te - self.sample_length * self.sample_interval
frames_dir = os.path.join(self.root, video_id)
frames = read_frames_dir(frames_dir, max(0.0, ts), te)
frames = sample_frames(frames, self.sample_length)
elif '-' in record.path and ',' in record.path:
sep = record.path.rindex('-')
frame_dir = record.path[:sep]
frame_ids = record.path[sep:].split(',')[-self.sample_length:]
frames = [cv2.imread(os.path.join(frame_dir, '{}.jpg'.format(i)))
for i in frame_ids]
else:
video_id = record.path
frames_dir = os.path.join(self.neg_root, video_id)
frames = read_all_frames(frames_dir)
frames = sample_frames(frames, self.sample_length)
frames = [make_boxed_img(i) for i in frames]
frames = [i[:, :, ::-1] for i in frames] # utils_cv uses RGB
clip = np.array(frames)
return self.transforms(torch.from_numpy(clip)), record.label
|
"""fips verb to build the samples webpage"""
import os
import yaml
import shutil
import subprocess
import glob
from string import Template
from mod import log, util, project, emscripten, android
# sample attributes
samples = [
[ 'clear', 'clear-sapp.c', None],
[ 'triangle', 'triangle-sapp.c', 'triangle-sapp.glsl'],
[ 'quad', 'quad-sapp.c', 'quad-sapp.glsl'],
[ 'bufferoffsets', 'bufferoffsets-sapp.c', 'bufferoffsets-sapp.glsl'],
[ 'cube', 'cube-sapp.c', 'cube-sapp.glsl'],
[ 'noninterleaved', 'noninterleaved-sapp.c', 'noninterleaved-sapp.glsl'],
[ 'texcube', 'texcube-sapp.c', 'texcube-sapp.glsl' ],
[ 'offscreen', 'offscreen-sapp.c', 'offscreen-sapp.glsl' ],
[ 'instancing', 'instancing-sapp.c', 'instancing-sapp.glsl' ],
[ 'mrt', 'mrt-sapp.c', 'mrt-sapp.glsl' ],
[ 'arraytex', 'arraytex-sapp.c', 'arraytex-sapp.glsl' ],
[ 'dyntex', 'dyntex-sapp.c', 'dyntex-sapp.glsl'],
[ 'uvwrap', 'uvwrap-sapp.c', 'uvwrap-sapp.glsl'],
[ 'mipmap', 'mipmap-sapp.c', 'mipmap-sapp.glsl'],
[ 'blend', 'blend-sapp.c', 'blend-sapp.glsl' ],
[ 'sdf', 'sdf-sapp.c', 'sdf-sapp.glsl'],
[ 'imgui', 'imgui-sapp.cc', None ],
[ 'imgui-highdpi', 'imgui-highdpi-sapp.cc', None ],
[ 'cimgui', 'cimgui-sapp.c', None ],
[ 'imgui-usercallback', 'imgui-usercallback-sapp.c', 'imgui-usercallback-sapp.glsl'],
[ 'sgl-microui', 'sgl-microui-sapp.c', None],
[ 'fontstash', 'fontstash-sapp.c', None],
[ 'events', 'events-sapp.cc', None],
[ 'pixelformats', 'pixelformats-sapp.c', None],
[ 'pixelformats-gles2', 'pixelformats-sapp.c', None],
[ 'saudio', 'saudio-sapp.c', None],
[ 'modplay', 'modplay-sapp.c', None],
[ 'noentry', 'noentry-sapp.c', 'noentry-sapp.glsl' ],
[ 'sgl', 'sgl-sapp.c', None ],
[ 'sgl-lines', 'sgl-lines-sapp.c', None ],
[ 'loadpng', 'loadpng-sapp.c', 'loadpng-sapp.glsl'],
[ 'plmpeg', 'plmpeg-sapp.c', 'plmpeg-sapp.glsl'],
[ 'cgltf', 'cgltf-sapp.c', 'cgltf-sapp.glsl'],
[ 'cubemaprt', 'cubemaprt-sapp.c', 'cubemaprt-sapp.glsl']
]
# assets that must also be copied
assets = [
"baboon.png",
"bjork-all-is-full-of-love.mpg",
"DamagedHelmet.gltf",
"DamagedHelmet.bin",
"Default_AO.basis",
"Default_albedo.basis",
"Default_emissive.basis",
"Default_metalRoughness.basis",
"Default_normal.basis",
"DroidSerif-Regular.ttf",
"DroidSerif-Italic.ttf",
"DroidSerif-Bold.ttf",
"DroidSansJapanese.ttf"
]
# webpage template arguments
GitHubSamplesURL = 'https://github.com/floooh/sokol-samples/tree/master/sapp/'
# build configuration
BuildConfig = 'sapp-wgpu-wasm-vscode-release'
#-------------------------------------------------------------------------------
def deploy_webpage(fips_dir, proj_dir, webpage_dir) :
"""builds the final webpage under under fips-deploy/sokol-webpage"""
ws_dir = util.get_workspace_dir(fips_dir)
wasm_deploy_dir = '{}/fips-deploy/sokol-samples/{}'.format(ws_dir, BuildConfig)
# create directories
if not os.path.exists(webpage_dir):
os.makedirs(webpage_dir)
# build the thumbnail gallery
content = ''
for sample in samples:
name = sample[0]
log.info('> adding thumbnail for {}'.format(name))
url = "{}-sapp.html".format(name)
ui_url = "{}-sapp-ui.html".format(name)
img_name = name + '.jpg'
img_path = proj_dir + '/webpage/' + img_name
if not os.path.exists(img_path):
img_name = 'dummy.jpg'
img_path = proj_dir + 'webpage/dummy.jpg'
content += '<div class="thumb">\n'
content += ' <div class="thumb-title">{}</div>\n'.format(name)
if os.path.exists(wasm_deploy_dir + '/' + name + '-sapp-ui.js'):
content += '<a class="img-btn-link" href="{}"><div class="img-btn">UI</div></a>'.format(ui_url)
content += ' <div class="img-frame"><a href="{}"><img class="image" src="{}"></img></a></div>\n'.format(url,img_name)
content += '</div>\n'
# populate the html template, and write to the build directory
with open(proj_dir + '/webpage/index.html', 'r') as f:
templ = Template(f.read())
html = templ.safe_substitute(samples=content)
with open(webpage_dir + '/index.html', 'w') as f :
f.write(html)
# copy other required files
for name in ['dummy.jpg', 'favicon.png']:
log.info('> copy file: {}'.format(name))
shutil.copy(proj_dir + '/webpage/' + name, webpage_dir + '/' + name)
# generate WebAssembly HTML pages
if emscripten.check_exists(fips_dir):
for sample in samples :
name = sample[0]
source = sample[1]
glsl = sample[2]
log.info('> generate wasm HTML page: {}'.format(name))
for postfix in ['sapp', 'sapp-ui']:
for ext in ['wasm', 'js'] :
src_path = '{}/{}-{}.{}'.format(wasm_deploy_dir, name, postfix, ext)
if os.path.isfile(src_path) :
shutil.copy(src_path, '{}/'.format(webpage_dir))
with open(proj_dir + '/webpage/wasm.html', 'r') as f :
templ = Template(f.read())
src_url = GitHubSamplesURL + source
if glsl is None:
glsl_url = "."
glsl_hidden = "hidden"
else:
glsl_url = GitHubSamplesURL + glsl
glsl_hidden = ""
html = templ.safe_substitute(name=name, prog=name+'-'+postfix, source=src_url, glsl=glsl_url, hidden=glsl_hidden)
with open('{}/{}-{}.html'.format(webpage_dir, name, postfix), 'w') as f :
f.write(html)
# copy assets from deploy directory
for asset in assets:
log.info('> copy asset file: {}'.format(asset))
src_path = '{}/{}'.format(wasm_deploy_dir, asset)
if os.path.isfile(src_path):
shutil.copy(src_path, webpage_dir)
# copy the screenshots
for sample in samples :
img_name = sample[0] + '.jpg'
img_path = proj_dir + '/webpage/' + img_name
if os.path.exists(img_path):
log.info('> copy screenshot: {}'.format(img_name))
shutil.copy(img_path, webpage_dir + '/' + img_name)
#-------------------------------------------------------------------------------
def build_deploy_webpage(fips_dir, proj_dir, rebuild) :
# if webpage dir exists, clear it first
ws_dir = util.get_workspace_dir(fips_dir)
webpage_dir = '{}/fips-deploy/sokol-webpage'.format(ws_dir)
if rebuild :
if os.path.isdir(webpage_dir) :
shutil.rmtree(webpage_dir)
if not os.path.isdir(webpage_dir) :
os.makedirs(webpage_dir)
# compile samples
if emscripten.check_exists(fips_dir) :
project.gen(fips_dir, proj_dir, BuildConfig)
project.build(fips_dir, proj_dir, BuildConfig)
# deploy the webpage
deploy_webpage(fips_dir, proj_dir, webpage_dir)
log.colored(log.GREEN, 'Generated Samples web page under {}.'.format(webpage_dir))
#-------------------------------------------------------------------------------
def serve_webpage(fips_dir, proj_dir) :
ws_dir = util.get_workspace_dir(fips_dir)
webpage_dir = '{}/fips-deploy/sokol-webpage'.format(ws_dir)
p = util.get_host_platform()
if p == 'osx' :
try :
subprocess.call(
'http-server -c-1 -g -o'.format(fips_dir),
cwd = webpage_dir, shell=True)
except KeyboardInterrupt :
pass
elif p == 'win':
try:
subprocess.call(
'http-server -c-1 -g -o'.format(fips_dir),
cwd = webpage_dir, shell=True)
except KeyboardInterrupt:
pass
elif p == 'linux':
try:
subprocess.call(
'http-server -c-1 -g -o'.format(fips_dir),
cwd = webpage_dir, shell=True)
except KeyboardInterrupt:
pass
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
if len(args) > 0 :
if args[0] == 'build' :
build_deploy_webpage(fips_dir, proj_dir, False)
elif args[0] == 'rebuild' :
build_deploy_webpage(fips_dir, proj_dir, True)
elif args[0] == 'serve' :
serve_webpage(fips_dir, proj_dir)
else :
log.error("Invalid param '{}', expected 'build' or 'serve'".format(args[0]))
else :
log.error("Param 'build' or 'serve' expected")
#-------------------------------------------------------------------------------
def help() :
log.info(log.YELLOW +
'fips wgpu_webpage build\n' +
'fips wgpu_webpage rebuild\n' +
'fips wgpu_webpage serve\n' +
log.DEF +
' build sokol samples webpage')
|
class DataGridViewCheckBoxColumn(DataGridViewColumn,ICloneable,IDisposable,IComponent):
"""
Hosts a collection of System.Windows.Forms.DataGridViewCheckBoxCell objects.
DataGridViewCheckBoxColumn()
DataGridViewCheckBoxColumn(threeState: bool)
"""
def Dispose(self):
"""
Dispose(self: DataGridViewColumn,disposing: bool)
disposing: true to release both managed and unmanaged resources; false to release only unmanaged resources.
"""
pass
def OnDataGridViewChanged(self,*args):
"""
OnDataGridViewChanged(self: DataGridViewBand)
Called when the band is associated with a different System.Windows.Forms.DataGridView.
"""
pass
def RaiseCellClick(self,*args):
"""
RaiseCellClick(self: DataGridViewElement,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellClick event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def RaiseCellContentClick(self,*args):
"""
RaiseCellContentClick(self: DataGridViewElement,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellContentClick event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def RaiseCellContentDoubleClick(self,*args):
"""
RaiseCellContentDoubleClick(self: DataGridViewElement,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellContentDoubleClick event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def RaiseCellValueChanged(self,*args):
"""
RaiseCellValueChanged(self: DataGridViewElement,e: DataGridViewCellEventArgs)
Raises the System.Windows.Forms.DataGridView.CellValueChanged event.
e: A System.Windows.Forms.DataGridViewCellEventArgs that contains the event data.
"""
pass
def RaiseDataError(self,*args):
"""
RaiseDataError(self: DataGridViewElement,e: DataGridViewDataErrorEventArgs)
Raises the System.Windows.Forms.DataGridView.DataError event.
e: A System.Windows.Forms.DataGridViewDataErrorEventArgs that contains the event data.
"""
pass
def RaiseMouseWheel(self,*args):
"""
RaiseMouseWheel(self: DataGridViewElement,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseWheel event.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def ToString(self):
"""
ToString(self: DataGridViewCheckBoxColumn) -> str
Returns: A System.String that describes the column.
"""
pass
def __enter__(self,*args):
"""
__enter__(self: IDisposable) -> object
Provides the implementation of __enter__ for objects which implement IDisposable.
"""
pass
def __exit__(self,*args):
"""
__exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)
Provides the implementation of __exit__ for objects which implement IDisposable.
"""
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,threeState=None):
"""
__new__(cls: type)
__new__(cls: type,threeState: bool)
"""
pass
def __str__(self,*args):
pass
CellTemplate=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the template used to create new cells.
Get: CellTemplate(self: DataGridViewCheckBoxColumn) -> DataGridViewCell
Set: CellTemplate(self: DataGridViewCheckBoxColumn)=value
"""
DefaultCellStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the column's default cell style.
Get: DefaultCellStyle(self: DataGridViewCheckBoxColumn) -> DataGridViewCellStyle
Set: DefaultCellStyle(self: DataGridViewCheckBoxColumn)=value
"""
FalseValue=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the underlying value corresponding to a cell value of false,which appears as an unchecked box.
Get: FalseValue(self: DataGridViewCheckBoxColumn) -> object
Set: FalseValue(self: DataGridViewCheckBoxColumn)=value
"""
FlatStyle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the flat style appearance of the check box cells.
Get: FlatStyle(self: DataGridViewCheckBoxColumn) -> FlatStyle
Set: FlatStyle(self: DataGridViewCheckBoxColumn)=value
"""
HeaderCellCore=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the header cell of the System.Windows.Forms.DataGridViewBand.
"""
IndeterminateValue=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the underlying value corresponding to an indeterminate or null cell value,which appears as a disabled checkbox.
Get: IndeterminateValue(self: DataGridViewCheckBoxColumn) -> object
Set: IndeterminateValue(self: DataGridViewCheckBoxColumn)=value
"""
IsRow=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the band represents a row.
"""
ThreeState=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the hosted check box cells will allow three check states rather than two.
Get: ThreeState(self: DataGridViewCheckBoxColumn) -> bool
Set: ThreeState(self: DataGridViewCheckBoxColumn)=value
"""
TrueValue=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the underlying value corresponding to a cell value of true,which appears as a checked box.
Get: TrueValue(self: DataGridViewCheckBoxColumn) -> object
Set: TrueValue(self: DataGridViewCheckBoxColumn)=value
"""
|
<filename>model.py
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from pytorch_lightning.metrics.functional.classification import accuracy
class BaseModel(pl.LightningModule):
def __init__(self):
super().__init__()
def training_step(self, batch, batch_idx):
x, y = batch
output = self(x)
loss = F.binary_cross_entropy(output, y.float())
acc = accuracy(torch.round(output), y.float())
self.log("train_loss", loss, logger=True)
self.log("train_acc", acc, logger=True)
return {"loss": loss, "train_acc": acc}
def training_epoch_end(self, outputs):
avg_loss = torch.stack([i["loss"] for i in outputs]).mean()
avg_acc = torch.stack([i["train_acc"] for i in outputs]).mean()
print(
"---\nEpoch {} average training loss: {:12.4f}\n"
"Epoch {} average training accuracy: {:8.4f}\n---".format(
self.current_epoch, avg_loss, self.current_epoch, avg_acc
)
)
def validation_step(self, batch, batch_idx):
x, y = batch
output = self(x)
loss = F.binary_cross_entropy(output, y.float())
acc = accuracy(torch.round(output), y.float())
self.log("val_loss", loss, logger=True)
self.log("val_acc", acc, logger=True)
return {"val_loss": loss, "val_acc": acc}
def validation_epoch_end(self, outputs):
avg_loss = torch.stack([i["val_loss"] for i in outputs]).mean()
avg_acc = torch.stack([i["val_acc"] for i in outputs]).mean()
print(
"---\nEpoch {} average validation loss: {:10.4f}\n"
"Epoch {} average validation accuracy: {:6.4f}\n---".format(
self.current_epoch, avg_loss, self.current_epoch, avg_acc
)
)
def test_step(self, batch, batch_idx):
x, y = batch
output = self(x)
loss = F.binary_cross_entropy(output, y.float())
acc = accuracy(torch.round(output), y.float())
return {"test_loss": loss, "test_acc": acc}
def configure_optimizers(self):
return optim.Adam(self.parameters(), lr=1e-3)
class BiLSTM(BaseModel):
def __init__(
self,
num_embeddings=10000,
embedding_dim=16,
hidden_size=64,
num_layers=1,
bidirectional=True,
output_size=1,
):
super().__init__()
self.embedding = nn.Embedding(
num_embeddings=num_embeddings + 1, embedding_dim=embedding_dim
)
self.lstm = nn.LSTM(
input_size=embedding_dim,
hidden_size=hidden_size,
num_layers=num_layers,
bidirectional=bidirectional,
batch_first=True,
)
self.linear = nn.Linear(hidden_size * 2, output_size)
def forward(self, x):
batch_size = x.size(0)
hidden = self.init_hidden(batch_size)
# (batch_size, sequence_length)
x = x.long()
# (batch_size, sequence_length, embedding_dim)
embedded = self.embedding(x)
# (batch_size, sequence_length, num_directions * hidden_size)
lstm_out, hidden = self.lstm(embedded, hidden)
# (batch_size, sequence_length, num_directions, hidden_size)
lstm_out = lstm_out.contiguous().view(
-1, self.sequence_length, 2, self.hidden_size
)
# (batch_size, num_directions * hidden_size / 2)
lstm_out_backward = lstm_out[:, 0, 1, :]
# (batch_size, num_directions * hidden_size / 2)
lstm_out_forward = lstm_out[:, -1, 0, :]
# (batch_size, num_directions * hidden_size)
lstm_out = torch.cat((lstm_out_backward, lstm_out_forward), dim=1)
# (batch_size, 1)
# pooled = self.pooling(lstm_out)
# (batch_size, 1)
out = torch.relu(self.linear(lstm_out))
out = torch.squeeze(torch.sigmoid(out))
return out
def init_hidden(self, batch_size):
weight = next(self.parameters()).data
hidden = (
weight.new(
self.num_layers * 2, batch_size, self.hidden_size
).zero_(),
weight.new(
self.num_layers * 2, batch_size, self.hidden_size
).zero_(),
)
return hidden
class FCNN(BaseModel):
def __init__(
self,
num_embeddings=10000,
embedding_dim=16,
hidden_size=64,
sequence_length=512,
output_size=1,
):
super().__init__()
self.embedding = nn.Embedding(
num_embeddings=num_embeddings, embedding_dim=embedding_dim
)
self.flatten = nn.Flatten()
self.linear_mid = nn.Linear(
sequence_length * embedding_dim, hidden_size
)
self.linear_out = nn.Linear(hidden_size, output_size)
def forward(self, x):
# (batch_size, sequence_length)
x = x.long()
# (batch_size, sequence_length, embedding_dim)
embedded = self.embedding(x)
# (batch_size, sequence_length * embedding_dim)
flattened = self.flatten(embedded)
# (batch_size, hidden_size)
linear_mid_out = torch.relu(self.linear_mid(flattened))
# (batch_size, output_size)
out = torch.squeeze(torch.sigmoid(self.linear_out(linear_mid_out)))
return out
|
"""This script can be used to generate a Aruco marker board. This board is used in the
camera pose estimation.
.. note::
**Printing instructions:**
- Make sure Scale to fit is selected.
- Verify the size of the markers after the board is printed. If
size does not match change the settings below or in the detection algorithm.
Source code
----------------------------
.. literalinclude:: /../../panda_autograsp/scripts/generate_arucoboard.py
:language: python
:linenos:
:lines: 20-
"""
# Main python packages
import os
import pickle
import cv2
from cv2 import aruco
import datetime
# Panda_autograsp modules, msgs and srvs
from panda_autograsp import Logger
# Get required paths
SAVE_DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
# Create script logger
script_logger = Logger.get_logger("generate_arucoboard.py")
#################################################
# Script settings ###############################
#################################################
MARKERS_X = 4
MARKERS_Y = 6
MARKER_LENGTH = 0.032 # [M]
MARKER_SEPARATION = 0.009 # [M]
ARUCO_DICT_TYPE = aruco.DICT_6X6_50 # [ROWSxCOLUMNS_LIBRARY_SIZE]
IM_OUT_SIZE = (1100, 1681) # Pixel size == Pattern size
MARGIN_SIZE = 0
#################################################
# Main script ###################################
#################################################
if __name__ == "__main__":
# set root logger format
root_logger = Logger.get_logger(
log_file=os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"..",
"logs/generate_arucoboard.log",
)
)
)
# Welcome message
print(
"== Generate arucoboard script ==\n"
"This script can be used to generate "
"a Aruco marker board. This board is used "
"in the camera pose estimation.\n"
)
# Save config settings
config_dict = {
"MARKERS_X": MARKERS_X,
"MARKERS_Y": MARKERS_Y,
"MARKER_LENGTH": 0.032,
"MARKER_SEPARATION": 0.009,
"ARUCO_DICT_TYPE": ARUCO_DICT_TYPE,
"IM_OUT_SIZE": IM_OUT_SIZE,
"MARGIN_SIZE": MARGIN_SIZE,
}
config_save_str = os.path.abspath(
os.path.join(SAVE_DIR_PATH, "../cfg/_cfg/aruco_config.dict")
)
with open(config_save_str, "wb") as config_dict_file:
pickle.dump(config_dict, config_dict_file)
# Create aruco gridboard
ARUCO_DICT = aruco.Dictionary_get(ARUCO_DICT_TYPE)
gridboard = aruco.GridBoard_create(
markersX=MARKERS_X,
markersY=MARKERS_Y,
markerLength=MARKER_LENGTH,
markerSeparation=MARKER_SEPARATION,
dictionary=ARUCO_DICT,
)
# Create an image from the gridboard
gridboard_img = gridboard.draw(
outSize=IM_OUT_SIZE, marginSize=MARGIN_SIZE, borderBits=1
)
# Display and save gridboard image
cv2.namedWindow("aruco-board")
cv2.imshow("aruco-board", gridboard_img)
while True:
k = cv2.waitKey(100)
# Break if someone presses q or esc
if (k == 27) or (k == ord("q")):
print("Closing window")
break
# Break if window is closed
if cv2.getWindowProperty("aruco-board", cv2.WND_PROP_VISIBLE) < 1:
break
cv2.destroyAllWindows()
# Save generated Arucoboard
time_str = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
img_save_dir = os.path.abspath(os.path.join(SAVE_DIR_PATH, ("../data/calib")))
img_save_pth = os.path.abspath(
os.path.join(img_save_dir, "arucoboard" + "_" + time_str + ".jpg")
)
if not os.path.exists(img_save_dir):
os.makedirs(img_save_dir)
cv2.imwrite(img_save_pth, gridboard_img)
print("Aruco board saved to %s" % img_save_pth)
|
<gh_stars>0
from rest_framework import serializers
from django.db.models import Q, F, Avg, Max, Min, Count, Sum
from app.models import *
class UserDataSerializer(serializers.ModelSerializer):
user_school = serializers.SerializerMethodField()
user_class = serializers.SerializerMethodField()
user_team = serializers.SerializerMethodField()
user_address = serializers.SerializerMethodField()
registration_time = serializers.SerializerMethodField()
user_solution_data = serializers.SerializerMethodField()
class Meta:
model = User
fields = (
'user_id',
'user_name',
'user_nick',
'user_introduce',
'user_power',
'user_score',
'user_sex',
'user_telephone',
'user_email',
'user_birthday',
'user_school',
'user_class',
'user_team',
'user_address',
'registration_time',
'user_solution_data'
)
def get_user_school(self, obj):
user = obj
user_school = School.objects.filter(school_id=user.user_school)
if user_school.exists():
return user_school.values().first()
else:
return None
def get_user_class(self, obj):
user = obj
user_class = Class.objects.filter(class_id=user.user_class)
if user_class.exists():
return user_class.values().first()
else:
return None
def get_user_team(self, obj):
user = obj
user_team = Class.objects.filter(class_id=user.user_team)
if user_team.exists():
return user_team.values().first()
else:
return None
def get_user_address(self, obj):
user = obj
user_address = Municipality.objects.filter(municipality_id=user.user_address)
if user_address.exists():
return user_address.values().first()
else:
return None
def get_registration_time(self, obj):
user = obj
registration_time = Password.objects.filter(user_id=user.user_id)
if registration_time.exists():
return registration_time.first().registration_time
else:
return None
def get_user_solution_data(self, obj):
solution_data = {
'user_solved': [],
'user_submit': 0,
'user_accurate': 0,
'format_error': 0,
'wrong_answer': 0,
'time_over': 0,
'memory_over': 0,
'output_over': 0,
'runtime_error': 0,
'compile_error': 0
}
user = obj
solution_data_submit = Solution.objects.filter(user_id=user.user_id)
solution_data['user_submit'] = len(solution_data_submit)
if solution_data_submit.exists():
solution_data['user_solved'] = list(solution_data_submit.filter(run_result=4).values('problem_id').annotate(number=Count('user_id')))
solution_data['user_accurate'] = solution_data_submit.filter(run_result=4).count()
solution_data['format_error'] = solution_data_submit.filter(run_result=5).count()
solution_data['wrong_answer'] = solution_data_submit.filter(run_result=6).count()
solution_data['time_over'] = solution_data_submit.filter(run_result=7).count()
solution_data['memory_over'] = solution_data_submit.filter(run_result=8).count()
solution_data['output_over'] = solution_data_submit.filter(run_result=9).count()
solution_data['runtime_error'] = solution_data_submit.filter(run_result=10).count()
solution_data['compile_error'] = solution_data_submit.filter(run_result=11).count()
return solution_data |
import os
import sys
import json
import logging
import pandas as pd
from tqdm import tqdm
import numpy as np
import gensim
from keras import backend as K
from keras.engine import Layer
try:
import cPickle as pickle
except ImportError:
import pickle
try:
import nirvana_dl
except ImportError:
pass
def load_data(fname, **kwargs):
func = kwargs.get('func', None)
if func is not None:
del kwargs['func']
df = pd.read_csv(fname, **kwargs)
if func is not None:
return func(df.values)
return df
class Params(object):
def __init__(self, config=None):
self._params = self._load_from_file(config)
def __getitem__(self, key):
return self._params.get(key, None)
def _load_from_file(self, fname):
if fname is None:
return {}
elif fname == 'nirvana':
return nirvana_dl.params()
elif isinstance(fname, dict):
return fname
with open(fname) as f:
return json.loads(f.read())
def get(self, key):
return self._params.get(key, None)
class Embeds(object):
def __init__(self):
self.word_index = {}
self.word_index_reverse = {}
self.matrix = None
self.shape = (0, 0)
def __getitem__(self, key):
idx = self.word_index.get(key, None)
if idx is not None:
return self.matrix[idx]
return None
def __contains__(self, key):
return self[key] is not None
def _process_line(self, line, embed_dim):
line = line.rstrip().split(' ')
word = ' '.join(line[:-embed_dim])
vec = line[-embed_dim:]
return word, [float(val) for val in vec]
def _read_raw_file(self, fname):
with open(fname) as f:
tech_line = f.readline()
word_count, embed_dim = tech_line.rstrip().split()
word_count = int(word_count) + 1
embed_dim = int(embed_dim[0])
print('dict_size = {}'.format(word_count))
print('embed_dim = {}'.format(embed_dim))
self.matrix = np.zeros((word_count, embed_dim))
self.word_index = {}
self.word_index_reverse = {}
for i, line in tqdm(enumerate(f), file=sys.stdout):
word, vec = self._process_line(line, embed_dim)
self.matrix[i+1] = vec
self.word_index[word] = i+1
self.word_index_reverse[i+1] = word
self.shape = (word_count, embed_dim)
return self
def _read_struct_file(self, fname, format):
if format == 'json':
data = json.load(open(fname))
elif format == 'pickle':
data = pickle.load(open(fname, 'rb'))
elif format in ('word2vec', 'binary'):
data = gensim.models.KeyedVectors.load_word2vec_format(fname, binary=format=='binary')
word_count = len(data) + 1
embed_dim = len(data.values()[0])
self.word_index = {}
self.word_index_reverse = {}
self.matrix = np.zeros((word_count, embed_dim))
for i, (word, vec) in enumerate(data.items()):
self.matrix[i+1] = vec
self.word_index[word] = i+1
self.word_index_reverse[i+1] = word
return self
def save(self, fname):
if os.path.exists(fname):
os.remove(fname)
with open(fname, 'a') as f:
f.write('{} {}\n'.format(*self.shape))
for i,line in enumerate(self.matrix[1:]):
line = [str(val) for val in line]
line = ' '.join(line)
f.write('{} {}\n'.format(self.word_index_reverse[i+1], line))
return self
def load(self, fname, format='raw'):
if format == 'raw':
self._read_raw_file(fname)
else:
self._read_struct_file(fname, format)
return self
def set_matrix(self, max_words, word_index):
words_not_found = []
word_count = min(max_words, len(word_index)) + 1
matrix = np.zeros((word_count, self.shape[1]))
word_index_reverse = {idx : word for word, idx in word_index.items()}
for word, i in word_index.items():
if i >= word_count:
break
vec = self[word]
if vec is not None and len(vec) > 0:
matrix[i] = vec
else:
words_not_found.append(word)
self.matrix = matrix
self.word_index = word_index
self.word_index_reverse = word_index_reverse
self.shape = (word_count, self.shape[1])
return words_not_found
def get_matrix(self):
return self.matrix
class Logger(object):
def __init__(self, logger, fname=None, format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s"):
self.logFormatter = logging.Formatter(format)
self.rootLogger = logger
self.rootLogger.setLevel(logging.DEBUG)
self.consoleHandler = logging.StreamHandler(sys.stdout)
self.consoleHandler.setFormatter(self.logFormatter)
self.rootLogger.addHandler(self.consoleHandler)
if fname is not None:
self.fileHandler = logging.FileHandler(fname)
self.fileHandler.setFormatter(self.logFormatter)
self.rootLogger.addHandler(self.fileHandler)
def warn(self, message):
self.rootLogger.warn(message)
def info(self, message):
self.rootLogger.info(message)
def debug(self, message):
self.rootLogger.debug(message)
class GlobalZeroMaskedAveragePooling1D(Layer):
def __init__(self, **kwargs):
super(GlobalZeroMaskedAveragePooling1D, self).__init__(**kwargs)
def build(self, input_shape):
self.output_dim = input_shape[1]
self.repeat_dim = input_shape[2]
def compute_output_shape(self, input_shape):
return (input_shape[0], input_shape[-1])
def call(self, x, mask=None):
mask = K.not_equal(K.sum(K.abs(x), axis=2, keepdims=True), 0)
n = K.sum(K.cast(mask, 'float32'), axis=1, keepdims=False)
x_mean = K.sum(x, axis=1, keepdims=False) / (n + 1)
return K.cast(x_mean, 'float32')
def compute_mask(self, x, mask=None):
return None
class GlobalSumPooling1D(Layer):
def __init__(self, **kwargs):
super(GlobalSumPooling1D, self).__init__(**kwargs)
def build(self, input_shape):
self.output_dim = input_shape[1]
self.repeat_dim = input_shape[2]
def compute_output_shape(self, input_shape):
return (input_shape[0], input_shape[-1])
def call(self, x, mask=None):
return K.sum(x, axis=1, keepdims=False)
def compute_mask(self, x, mask=None):
return None
def embed_aggregate(seq, embeds, func=np.sum, normalize=False):
embed = np.zeros(embeds.shape[1])
nozeros = 0
for value in seq:
if value == 0 or value > embeds.shape[0]:
continue
embed = func([embed, embeds.matrix[value]], axis=0)
nozeros += 1
if normalize:
embed /= nozeros + 1
return embed
def similarity(seq1, seq2, embeds, pool='max', func=lambda x1, x2: x1 + x2):
pooling = {
'max': {'func': np.max},
'avg': {'func': np.sum, 'normalize': True},
'sum': {'func': np.sum, 'normalize': False}
}
embed1 = embed_aggregate(seq1, embeds, **pooling[pool])
embed2 = embed_aggregate(seq2, embeds, **pooling[pool])
return func(embed1, embed2)
|
<reponame>kconner/white-elephant<filename>main.py
__author__ = 'derekbrameyer'
import random
import json
import datetime
def main():
maxstealcount = 2
currentturn=1
boolines = json.loads(open("boo_lines.json").read())
reportlines = json.loads(open("report_lines.json").read())
print greenify("\nWelcome to White Elephant! Please input names line by line. When you are finished inputting names, press enter on a blank line.\n")
fullname = "tester"
participants = []
gifts = []
while fullname:
fullname = raw_input(greenify("Participant name: "))
participants.append(Participant(fullname, None))
participants.pop()
global should_save
should_save = raw_input(greenify("\nType 1 to also generate a document of the game: "))
if should_save is '1':
should_save = True
global save_document
filename = datetime.datetime.now().strftime("%Y%m%d") + "_" + datetime.datetime.now().strftime("%H%M") + "_white_elephant.txt"
print filename
save_document = open(filename, "w")
print "\nRandomizing the order...\n"
random.shuffle(participants)
participants.reverse()
firstparticipant = participants.pop()
print_and_save("=======================", True)
print_and_save(" TURN 1", True)
print_and_save("=======================", True)
print_and_save(firstparticipant.fullname + " is up first! What gift did they get?", False)
giftname = raw_input(greenify("The gift is a/an: "))
save_to_file("The gift is a/an: " + giftname)
gift = Gift(giftname, 0, firstparticipant)
firstparticipant.gift = gift
gifts.append(gift)
# 0 = steal
# 1 = pick new gift
previous_action = 1
while len(participants) > 0 or nextparticipant is not None:
# only iterate through the list if it was a random gift last time
if previous_action == 1:
nextparticipant = participants.pop()
currentturn += 1
giftsinturn = list(gifts)
if previous_action == 0:
print_and_save("\n\nWelp, we're on to " + nextparticipant.fullname + ". Are they stealing or picking a new gift?", False)
else:
print_and_save("Cool! An amazing " + gift.name + "! What a gift!\n\n", False)
print_and_save("=======================", True)
print_and_save(" TURN " + str(currentturn), True)
print_and_save("=======================", True)
print_and_save("Now we're on to " + nextparticipant.fullname + ". Are they stealing or picking a new gift?", False)
if len(giftsinturn) > 0:
action = raw_input(greenify("Input 1 to steal or 2 to pick a new gift: "))
save_to_file("Input 1 to steal or 2 to pick a new gift: " + action)
else:
print_and_save("Actually, looks like there are no gifts left to steal! Moving on...", False)
action = "0"
if action == "1":
print_and_save("We're stealing! What does " + nextparticipant.fullname + " want?\n", False)
displayCount = 1
for gift in giftsinturn:
print_and_save("Gift " + str(displayCount) + ": " + gift.name + " (Owner: " + gift.owner.fullname + ", Steals: " + str(gift.steals) + ")", False)
displayCount += 1
giftstealcount = maxstealcount + 1
while giftstealcount >= maxstealcount:
giftselection = raw_input(greenify("\nGift to steal (a number): "))
save_to_file("\nGift to steal (a number): " + giftselection)
stolengift = giftsinturn[int(giftselection) - 1]
giftstealcount = stolengift.steals
if giftstealcount >= maxstealcount:
print_and_save("I can't let you do that Star Fox! You'll have to select another gift.", False)
giftsinturn.remove(stolengift)
newowner = nextparticipant
nextparticipant = stolengift.owner
nextparticipant.gift = None
stolengift.owner = newowner
newowner.gift = stolengift
stolengift.steals += 1
random.shuffle(boolines)
print_and_save(boolines[0] % (newowner.fullname, stolengift.name, nextparticipant.fullname), False)
# TODO If gift has max steals, print something
if stolengift.steals >= maxstealcount:
print_and_save("Congrats to " + stolengift.owner.fullname + " for being the true owner of a shiny new " + stolengift.name + "!", False)
previous_action = 0
else:
print_and_save("What gift did " + nextparticipant.fullname + " get?", False)
giftname = raw_input(greenify("The gift is a/an: "))
save_to_file("The gift is a/an: " + giftname)
gift = Gift(giftname, 0, nextparticipant)
nextparticipant.gift = gift
gifts.append(gift)
previous_action = 1
nextparticipant = None
# wrap up with the first participant optionally stealing again
if previous_action == 0:
print_and_save("\n\n", False)
print_and_save("=======================", True)
print_and_save(" LAST TURN", True)
print_and_save("=======================", True)
print_and_save("Welp, we're almost done. Back to " + firstparticipant.fullname + ", who has the option to force a swap!", False)
else:
print_and_save("Cool! An amazing " + gift.name + "! What a gift!\n\n", False)
print_and_save("=======================", True)
print_and_save(" LAST TURN", True)
print_and_save("=======================", True)
print_and_save("Back to " + firstparticipant.fullname + ", who has the option to force a swap!", False)
print_and_save("Select the gift to swap for. If they're not swapping, input 0.\n", False)
displayCount = 1
owner_pivot_idx = 0
for gift in gifts:
# don't display the owner's gift
if gift.owner.fullname is firstparticipant.fullname:
owner_pivot_idx = displayCount - 1
continue
print_and_save("Gift " + str(displayCount) + ": " + gift.name + " (Owner: " + gift.owner.fullname + ", Steals: " + str(gift.steals) + ")", False)
displayCount += 1
giftstealcount = maxstealcount + 1
while giftstealcount >= maxstealcount:
giftselection = raw_input(greenify("\nGift to swap (a number): "))
save_to_file("\nGift to swap (a number): " + giftselection)
if giftselection == "0":
print_and_save("No swap! What a pal.", False)
break
if giftselection > owner_pivot_idx:
giftselection = str(int(giftselection) + 1)
gifttoswap = gifts[int(giftselection) - 1]
giftstealcount = gifttoswap.steals
if giftstealcount >= maxstealcount:
print_and_save("I can't let you do that Star Fox! You'll have to select another gift.", False)
if giftselection != "0":
oldowner = gifttoswap.owner
swappedgift = firstparticipant.gift
swappedgift.owner = oldowner
oldowner.gift = swappedgift
gifttoswap.owner = firstparticipant
firstparticipant.gift = gifttoswap
print_and_save("\nThat's a wrap! Here's what everyone ended up with:\n", False)
for gift in gifts:
random.shuffle(reportlines)
print_and_save(reportlines[0] % (gift.owner.fullname, gift.name), False)
print_and_save("\n\n", False)
if should_save is '1':
save_file.close()
def greenify(string):
attr = []
attr.append('32')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
def print_and_save(string, should_greenify):
if should_greenify:
print greenify(string)
else:
print string
save_to_file(string)
def save_to_file(string):
global should_save
if should_save:
global save_document
save_document.write(string)
save_document.write("\n")
class Participant(object):
def __init__(self, name, gift):
self.fullname = name
self.gift = gift
class Gift(object):
def __init__(self, name, steals, owner):
self.name = name
self.steals = steals
self.owner = owner
should_save = False
save_document = None
if __name__ == "__main__":
main() |
"""Access to the base Slack Web API.
Attributes:
ALL (:py:class:`object`): Marker for cases where all child methods
should be deleted by :py:func:`api_subclass_factory`.
"""
from copy import deepcopy
import logging
import aiohttp
from .core import Service, UrlParamMixin
from .utils import FriendlyError, raise_for_status
logger = logging.getLogger(__name__)
ALL = object()
class SlackApiError(FriendlyError):
"""Wrapper exception for error messages in the response JSON."""
EXPECTED_ERRORS = {
'account_inactive': 'Authentication token is for a deleted user or '
'team.',
'invalid_auth': 'Invalid authentication token.',
'migration_in_progress': 'Team is being migrated between servers.',
'not_authed': "No authentication token provided.",
}
"""Friendly messages for expected Slack API errors."""
class SlackApi(UrlParamMixin, Service):
"""Class to handle interaction with Slack's API.
Attributes:
API_METHODS (:py:class:`dict`): The API methods defined by Slack.
"""
API_METHODS = {
'api': {'test': 'Checks API calling code.'},
'auth': {'test': 'Checks authentication & identity.'},
'channels': {
'archive': 'Archives a channel.',
'create': 'Creates a channel.',
'history': 'Fetches history of messages and events from a channel.',
'info': 'Gets information about a channel.',
'invite': 'Invites a user to a channel.',
'join': 'Joins a channel, creating it if needed.',
'kick': 'Removes a user from a channel.',
'leave': 'Leaves a channel.',
'list': 'Lists all channels in a Slack team.',
'mark': 'Sets the read cursor in a channel.',
'rename': 'Renames a channel.',
'setPurpose': 'Sets the purpose for a channel.',
'setTopic': 'Sets the topic for a channel.',
'unarchive': 'Unarchives a channel.',
},
'chat': {
'delete': 'Deletes a message.',
'postMessage': 'Sends a message to a channel.',
'update': 'Updates a message.'
},
'emoji': {'list': ' Lists custom emoji for a team.'},
'files': {
'delete': 'Deletes a file.',
'info': 'Gets information about a team file.',
'list': 'Lists & filters team files.',
'upload': 'Uploads or creates a file.'
},
'groups': {
'archive': 'Archives a private channel.',
'close': 'Closes a private channel.',
'create': 'Creates a private private channel.',
'createChild': 'Clones and archives a private channel.',
'history': 'Fetches history of messages and events from a private '
'channel.',
'info': 'Gets information about a private channel.',
'invite': 'Invites a user to a private channel.',
'kick': 'Removes a user from a private channel.',
'leave': 'Leaves a private channel.',
'list': 'Lists private channels that the calling user has access '
'to.',
'mark': 'Sets the read cursor in a private channel.',
'open': 'Opens a private channel.',
'rename': 'Renames a private channel.',
'setPurpose': 'Sets the purpose for a private channel.',
'setTopic': 'Sets the topic for a private channel.',
'unarchive': 'Unarchives a private channel.',
},
'im': {
'close': 'Close a direct message channel.',
'history': 'Fetches history of messages and events from direct '
'message channel.',
'list': 'Lists direct message channels for the calling user.',
'mark': 'Sets the read cursor in a direct message channel.',
'open': 'Opens a direct message channel.',
},
'mpim': {
'close': 'Closes a multiparty direct message channel.',
'history': 'Fetches history of messages and events from a '
'multiparty direct message.',
'list': 'Lists multiparty direct message channels for the calling '
'user.',
'mark': 'Sets the read cursor in a multiparty direct message '
'channel.',
'open': 'This method opens a multiparty direct message.',
},
'oauth': {
'access': 'Exchanges a temporary OAuth code for an API token.'
},
'pins': {
'add': 'Pins an item to a channel.',
'list': 'Lists items pinned to a channel.',
'remove': 'Un-pins an item from a channel.',
},
'reactions': {
'add': 'Adds a reaction to an item.',
'get': 'Gets reactions for an item.',
'list': 'Lists reactions made by a user.',
'remove': 'Removes a reaction from an item.',
},
'rtm': {'start': 'Starts a Real Time Messaging session.'},
'search': {
'all': 'Searches for messages and files matching a query.',
'files': 'Searches for files matching a query.',
'messages': 'Searches for messages matching a query.',
},
'stars': {
'add': 'Adds a star to an item.',
'list': 'Lists stars for a user.',
'remove': 'Removes a star from an item.',
},
'team': {
'accessLogs': 'Gets the access logs for the current team.',
'info': 'Gets information about the current team.',
'integrationLogs': 'Gets the integration logs for the current '
'team.',
},
'usergroups': {
'create': 'Create a user group.',
'disable': 'Disable an existing user group.',
'enable': 'Enable a user group.',
'list': 'List all user groups for a team.',
'update': 'Update an existing user group',
'users': {
'list': 'List all users in a user group',
'update': ' Update the list of users for a user group.',
},
},
'users': {
'getPresence': 'Gets user presence information.',
'info': 'Gets information about a user.',
'list': 'Lists all users in a Slack team.',
'setActive': 'Marks a user as active.',
'setPresence': 'Manually sets user presence.',
},
}
AUTH_PARAM = 'token'
REQUIRED = {'api_token'}
ROOT = 'https://slack.com/api/'
TOKEN_ENV_VAR = 'SLACK_API_TOKEN'
async def execute_method(self, method, **params):
"""Execute a specified Slack Web API method.
Arguments:
method (:py:class:`str`): The name of the method.
**params (:py:class:`dict`): Any additional parameters
required.
Returns:
:py:class:`dict`: The JSON data from the response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: If the HTTP
request returns a code other than 200 (OK).
SlackApiError: If the Slack API is reached but the response
contains an error message.
"""
url = self.url_builder(method, url_params=params)
logger.info('Executing method %r', method)
response = await aiohttp.get(url)
logger.info('Status: %r', response.status)
if response.status == 200:
json = await response.json()
logger.debug('...with JSON %r', json)
if json.get('ok'):
return json
raise SlackApiError(json['error'])
else:
raise_for_status(response)
@classmethod
def method_exists(cls, method):
"""Whether a given method exists in the known API.
Arguments:
method (:py:class:`str`): The name of the method.
Returns:
:py:class:`bool`: Whether the method is in the known API.
"""
methods = cls.API_METHODS
for key in method.split('.'):
methods = methods.get(key)
if methods is None:
break
if isinstance(methods, str):
logger.debug('%r: %r', method, methods)
return True
return False
def api_subclass_factory(name, docstring, remove_methods, base=SlackApi):
"""Create an API subclass with fewer methods than its base class.
Arguments:
name (:py:class:`str`): The name of the new class.
docstring (:py:class:`str`): The docstring for the new class.
remove_methods (:py:class:`dict`): The methods to remove from
the base class's :py:attr:`API_METHODS` for the subclass. The
key is the name of the root method (e.g. ``'auth'`` for
``'auth.test'``, the value is either a tuple of child method
names (e.g. ``('test',)``) or, if all children should be
removed, the special value :py:const:`ALL`.
base (:py:class:`type`, optional): The base class (defaults to
:py:class:`SlackApi`).
Returns:
:py:class:`type`: The new subclass.
Raises:
:py:class:`KeyError`: If the method wasn't in the superclass.
"""
methods = deepcopy(base.API_METHODS)
for parent, to_remove in remove_methods.items():
if to_remove is ALL:
del methods[parent]
else:
for method in to_remove:
del methods[parent][method]
return type(name, (base,), dict(API_METHODS=methods, __doc__=docstring))
SlackBotApi = api_subclass_factory( # pylint: disable=invalid-name
'SlackBotApi',
'API accessible to Slack custom bots.',
remove_methods=dict(
channels=('archive', 'create', 'invite', 'join', 'kick', 'leave',
'rename', 'unarchive'),
files=('info', 'list'),
groups=('archive', 'create', 'createChild', 'invite', 'kick', 'leave',
'rename', 'unarchive'),
pins=('list',),
search=ALL,
stars=('list',),
team=('accessLogs', 'integrationLogs'),
usergroups=ALL,
),
)
SlackAppBotApi = api_subclass_factory( # pylint: disable=invalid-name
'SlackAppBotApi',
'API accessible to Slack app bots.',
remove_methods=dict(
channels=('history', 'mark', 'setPurpose', 'setTopic'),
emoji=ALL,
groups=('close', 'history', 'mark', 'open', 'setPurpose', 'setTopic'),
team=ALL,
),
base=SlackBotApi,
)
|
import os
import random as rnd
import string
import pytest
from settings import valid_email, valid_pass, not_valid_email, not_valid_password,\
pet_id_valid, pet_id_novalid, pet_photo_valid, pet_photo_novalid
import API_PETFRIENDS
pf = API_PETFRIENDS.API()
_, key = pf.get_api_key(valid_email, valid_pass)
_, my_pets = pf.get_list_of_pets(key, "my_pets")
@pytest.fixture()
def get_pet_id():
pet_id = rnd.choice(my_pets['pets'])
return pet_id['id']
@pytest.fixture()
def get_pet_id_novalid():
return pet_id_novalid
@pytest.mark.skip
def gen_names():
name =[]
for i in range(1):
name.append(''.join(rnd.choice(string.ascii_letters) for x in range(10)))
return name[0]
@pytest.mark.skip
def get_rnd_pet_id():
pet_id = rnd.choice(my_pets['pets'])
return pet_id['id']
@pytest.mark.skip
def get_rnd_id_list():
id_list = []
for i in range(5):
pet_id = rnd.choice(my_pets['pets'])
id_list.append(pet_id['id'])
return id_list
@pytest.mark.api
def test_get_api_for_valid_user(email=valid_email, password=valid_<PASSWORD>):
status, result = pf.get_api_key(email, password)
assert status == 200
assert 'key' in result
@pytest.mark.parametrize("name, animal_type, age", argvalues=[('CODEGEASS','ERGO', 3)])
def test_post_creat_pet_with_novalid_key(name, animal_type, age):
auth_key = {"key": "novalidkey"}
status, result = pf.post_creat_pet(auth_key, name, animal_type, age)
assert status == 403
@pytest.mark.parametrize("pet_id, pet_photo", argvalues=[(pet_id_valid,pet_photo_valid)])
def test_post_set_photo_pet_with_valid_key(pet_id, pet_photo):
_, auth_key = pf.get_api_key(valid_email, valid_pass)
pet_photo=os.path.join(os.path.dirname(__file__), pet_photo)
status, result = pf.post_set_photo_pet(auth_key, pet_id, pet_photo)
assert status == 200
assert result['id'] == pet_id
@pytest.mark.skip
@pytest.mark.parametrize("pet_id, pet_photo", argvalues=[(pet_id_valid,pet_photo_valid)])
def test_post_set_photo_pet_with_novalid_data(pet_id, pet_photo):
_, auth_key = pf.get_api_key(valid_email, valid_pass)
pet_photo = os.path.join(os.path.dirname(__file__), pet_photo)
status, result = pf.post_set_photo_pet(auth_key, pet_id, pet_photo)
assert status == 400
assert status == 500
@pytest.mark.api
@pytest.mark.parametrize("pet_id, pet_photo", argvalues=[(pet_id_valid,pet_photo_valid)])
def test_post_set_photo_pet_with_novalid_key(pet_id, pet_photo):
auth_key = {"key": "novalidkey"}
pet_photo = os.path.join(os.path.dirname(__file__), pet_photo)
status, result = pf.post_set_photo_pet(auth_key, pet_id, pet_photo)
assert status == 403
@pytest.mark.skip(reason="Непонятная ошибка")
def test_get_all_pets_with_valid_key_novalid_filter(filter='kihkhk'):
_,auth_key = pf.get_api_key(valid_email, valid_pass)
status, result = pf.get_list_of_pets(auth_key, filter)
assert status == 400
@pytest.mark.api
@pytest.mark.parametrize("email, password", argvalues=[(not_valid_email,not_valid_password)])
def test_get_api_for_novalid_user(email, password):
status, result = pf.get_api_key(email, password)
assert status == 403
@pytest.mark.api
def test_get_all_pets_with_valid_key(filter=''):
_,auth_key = pf.get_api_key(valid_email, valid_pass)
status, result = pf.get_list_of_pets(auth_key, filter)
assert status == 200
assert len(result['pets']) > 0
@pytest.mark.api
def test_get_all_pets_with_novalid_key(filter=''):
auth_key = {"key": "novalidkey"}
status, result = pf.get_list_of_pets(auth_key, filter)
assert status == 403
@pytest.mark.api
@pytest.mark.parametrize("name, animal_type, age", argvalues=[(gen_names(),gen_names(), rnd.randint(0,100)),
(gen_names(),gen_names(), rnd.randint(0,100)),
(gen_names(),gen_names(), rnd.randint(0,100)),
(gen_names(),gen_names(), rnd.randint(0,100)),
(gen_names(),gen_names(), rnd.randint(0,100))])
def test_post_creat_pet_with_valid_key(name,
animal_type,
age):
_, auth_key = pf.get_api_key(valid_email, valid_pass)
status, result = pf.post_creat_pet(auth_key, name, animal_type, age)
assert status == 200
assert result['name'] == name
@pytest.mark.parametrize("name, animal_type, age", argvalues=[(gen_names(),'zzqweq', None), (gen_names(),'zzqweq', None) ,(gen_names(),'zzqweq', None),
(gen_names(),'zzqweq', None), (gen_names(),'zzqweq', None),(gen_names(),'zzqweq', None)])
def test_post_creat_pet_with_novalid_data(name,animal_type, age):
_, auth_key = pf.get_api_key(valid_email, valid_pass)
status, result = pf.post_creat_pet(auth_key, name, animal_type, age)
assert status == 400
@pytest.mark.parametrize("name, animal_type,age,pet_photo", argvalues=[('CODE','GEASS', str(rnd.randint(0,100)), pet_photo_valid)])
def test_post_new_pet_with_valid_data(name, animal_type,
age, pet_photo):
_,auth_key = pf.get_api_key(valid_email, valid_pass)
pet_photo = os.path.join(os.path.dirname(__file__), pet_photo)
status, result = pf.post_add_pet(auth_key, name, animal_type, age, pet_photo)
assert status == 200
assert result['name'] == name
@pytest.mark.parametrize("name, animal_type,age,pet_photo", argvalues=[('CODE','GEASS', str(rnd.randint(0,100)), pet_photo_valid)])
def test_post_new_pet_with_novalid_key(name, animal_type,
age, pet_photo):
auth_key = {"key": "novalidkey"}
pet_photo = os.path.join(os.path.dirname(__file__), pet_photo)
status, result = pf.post_add_pet(auth_key, name, animal_type, age, pet_photo)
assert status == 403
@pytest.mark.skip
@pytest.mark.parametrize("name, animal_type,age,pet_photo", argvalues=[('novalid','novalid', 'novalid', pet_photo_novalid)])
def test_post_new_pet_with_novalid_data(name, animal_type,
age, pet_photo):
_,auth_key = pf.get_api_key(valid_email, valid_pass)
pet_photo = os.path.join(os.path.dirname(__file__), pet_photo)
status, result = pf.post_add_pet(auth_key, name, animal_type, age, pet_photo)
assert status == 400
@pytest.mark.parametrize("pet_id", argvalues=[(get_rnd_pet_id())])
def test_delete_pet_with_valid_key(pet_id):
_,auth_key = pf.get_api_key(valid_email, valid_pass)
status, _ = pf.delete_pet(auth_key, pet_id)
_, my_pets = pf.get_list_of_pets(auth_key, "my_pets")
assert status == 200
assert pet_id not in my_pets.values()
@pytest.mark.foo
@pytest.mark.parametrize("pet_id", argvalues=[(get_rnd_pet_id())])
def test_delete_pet_with_novalid_key(pet_id):
auth_key = {"key": "novalidkey"}
status, result = pf.delete_pet(auth_key, pet_id)
assert status == 403
@pytest.mark.api
def test_put_pet_with_valid_key(pet_id=0,name='BERSERK', animal_type='Кот',
age = rnd.randint(0,100)):
_,auth_key = pf.get_api_key(valid_email, valid_pass)
_, my_pets = pf.get_list_of_pets(auth_key, "my_pets")
sum_pets = len(my_pets['pets'])
pet_id =rnd.choice(my_pets['pets'])
if sum_pets == 0:
raise Exception("Bаш список питомцев пуст")
else:
status, result = pf.put_pet(auth_key, pet_id['id'], name, animal_type, age)
assert status == 200
assert result['name'] == name
@pytest.mark.api
def test_put_pet_with_novalid_data(get_pet_id_novalid,name='novalid', animal_type='novalid',
age = rnd.randint(0,100)):
_,auth_key = pf.get_api_key(valid_email, valid_pass)
status, result = pf.put_pet(auth_key,get_pet_id_novalid, name, animal_type, age)
assert status == 400
@pytest.mark.foo
def test_put_pet_with_novalid_key(get_pet_id,name='novalid', animal_type='novalid',
age = rnd.randint(0,100)):
auth_key = {"key": "novalidkey"}
status, result = pf.put_pet(auth_key,get_pet_id, name, animal_type, age)
assert status == 403
|
<reponame>donalm/thrum
#!/usr/bin/env pypy
# -*- coding: utf-8 -*-
# Copyright (c) <NAME>
# See LICENSE for details.
import os
import sys
import socket
from . import binary
# Format code
FC_TEXT = 0
FC_BINARY = 1
# IP address family codes
PGSQL_AF_INET = 2 # IPv4
PGSQL_AF_INET6 = 3 # IPv6
# PG constants for numeric types
NUMERIC_POS = 0x0000
NUMERIC_NEG = 0x4000
NUMERIC_NAN = 0xC000
# Default protocol version
VERSION_MAJOR = 3
VERSION_MINOR = 0
DEFAULT_PROTOCOL_VERSION = (VERSION_MAJOR << 16) | VERSION_MINOR
# Message codes
NOTICE_RESPONSE = b'N'
AUTHENTICATION_REQUEST = b'R'
PARAMETER_STATUS = b'S'
BACKEND_KEY_DATA = b'K'
READY_FOR_QUERY = b'Z'
ROW_DESCRIPTION = b'T'
ERROR_RESPONSE = b'E'
DATA_ROW = b'D'
COMMAND_COMPLETE = b'C'
PARSE_COMPLETE = b'1'
BIND_COMPLETE = b'2'
CLOSE_COMPLETE = b'3'
PORTAL_SUSPENDED = b's'
NO_DATA = b'n'
PARAMETER_DESCRIPTION = b't'
NOTIFICATION_RESPONSE = b'A'
COPY_DONE = b'c'
COPY_DATA = b'd'
COPY_IN_RESPONSE = b'G'
COPY_OUT_RESPONSE = b'H'
EMPTY_QUERY_RESPONSE = b'I'
BIND = b'B'
PARSE = b'P'
EXECUTE = b'E'
FLUSH = b'H'
SYNC = b'S'
PASSWORD = b'p'
DESCRIBE = b'D'
TERMINATE = b'X'
CLOSE = b'C'
FLUSH_MSG = FLUSH + binary.i_pack(4)
SYNC_MSG = SYNC + binary.i_pack(4)
TERMINATE_MSG = TERMINATE + binary.i_pack(4)
COPY_DONE_MSG = COPY_DONE + binary.i_pack(4)
# DESCRIBE constants
STATEMENT = b'S'
PORTAL = b'P'
# ErrorResponse codes
RESPONSE_CODE = b'C' # always present
# READY FOR QUERY VALUES
IDLE = b'I'
IDLE_IN_TRANSACTION = b'T'
IDLE_IN_FAILED_TRANSACTION = b'E'
# typtype from pg_type table:
# https://www.postgresql.org/docs/9.6/static/catalog-pg-type.html
ENUM_TYPE = 'e'
BASE_TYPE = 'b'
COMPOSITE_TYPE = 'c'
DOMAIN_TYPE = 'd'
PSEUDO_TYPE = 'p'
RANGE_TYPE = 'r'
try:
HOSTNAME = socket.gethostname()
except Exception as e:
HOSTNAME = 'UNKNOWNHOST'
try:
PID = str(os.getpid())
except Exception as e:
PID = 'UNKNOWNPID'
try:
EXECUTABLE = os.path.basename(sys.executable)
except Exception as e:
EXECUTABLE = 'UNKNOWNEXECUTABLE'
APPLICATION_NAME = '%s_%s_%s' % (HOSTNAME, PID, EXECUTABLE,)
MIN_INT2 = -2 ** 15
MIN_INT4 = -2 ** 31
MIN_INT8 = -2 ** 63
MAX_INT2 = 2 ** 15 - 1
MAX_INT4 = 2 ** 31 - 1
MAX_INT8 = 2 ** 63 - 1
MIN_INT2U = 0
MIN_INT4U = 0
MIN_INT8U = 0
MAX_INT2U = 2 ** 16 - 1
MAX_INT4U = 2 ** 32 - 1
MAX_INT8U = 2 ** 64 - 1
BINARY_SPACE = b' '
DDL_COMMANDS = b'ALTER', b'CREATE'
NULL = binary.i_pack(-1)
NULL_BYTE = b'\x00'
BINARY = bytes
"""
Direct copy from pg8000
"""
pg_to_py = {
# Not supported:
'mule_internal': None,
'euc_tw': None,
# Name fine as-is:
# 'euc_jp',
# 'euc_jis_2004',
# 'euc_kr',
# 'gb18030',
# 'gbk',
# 'johab',
# 'sjis',
# 'shift_jis_2004',
# 'uhc',
# 'utf8',
# Different name:
'euc_cn': 'gb2312',
'iso_8859_5': 'is8859_5',
'iso_8859_6': 'is8859_6',
'iso_8859_7': 'is8859_7',
'iso_8859_8': 'is8859_8',
'koi8': 'koi8_r',
'latin1': 'iso8859-1',
'latin2': 'iso8859_2',
'latin3': 'iso8859_3',
'latin4': 'iso8859_4',
'latin5': 'iso8859_9',
'latin6': 'iso8859_10',
'latin7': 'iso8859_13',
'latin8': 'iso8859_14',
'latin9': 'iso8859_15',
'sql_ascii': 'ascii',
'win866': 'cp886',
'win874': 'cp874',
'win1250': 'cp1250',
'win1251': 'cp1251',
'win1252': 'cp1252',
'win1253': 'cp1253',
'win1254': 'cp1254',
'win1255': 'cp1255',
'win1256': 'cp1256',
'win1257': 'cp1257',
'win1258': 'cp1258',
'unicode': 'utf-8', # Needed for Amazon Redshift
}
|
import unittest
from src.core.pre.text.pre_inference import *
class UnitTests(unittest.TestCase):
# def test_all(self):
# example_text = "This is a test. And an other one.\nAnd a new line.\r\nAnd a line with \r.\n\nAnd a line with \n in it. This is a question? This is a error!"
# #example_text = read_text("examples/en/democritus.txt")
# conv = SymbolIdDict.init_from_symbols({"T", "h", "i", "s"})
# sents = add_text(example_text, Language.ENG, conv)
# print(sents)
# sents = sents_normalize(sents)
# print(sents)
# #sents = sents_map(sents, symbols_map=SymbolsMap.from_tuples([("o", "b"), ("a", ".")]))
# print(sents)
# sents = sents_convert_to_ipa(sents, ignore_tones=True, ignore_arcs=True)
# print(sents)
def test_add_text__chn__splits_sents(self):
_, sentences = add_text("暖耀着。旅行者。", lang=Language.CHN)
self.assertEqual(2, len(sentences))
def test_get_formatted_core(self):
symbols = list("this is a test!")
accent_ids = list("000016834864123")
accent_id_dict = AccentsDict.init_from_accents({f"a{i}" for i in range(10)})
sent_id = 1
max_pairs = 4
spacelength = 1
res = get_formatted_core(
sent_id,
symbols,
accent_ids,
max_pairs_per_line=max_pairs,
space_length=spacelength,
accent_id_dict=accent_id_dict
)
self.assertEqual(
'1: t h i s\n 0 0 0 0\n 0=a0\n \n i s \n 1 6 8 3\n 1=a1, 3=a3, 6=a6, 8=a8\n \n a t e\n 4 8 6 4\n 4=a4, 6=a6, 8=a8\n \n s t ! (15)\n 1 2 3\n 1=a1, 2=a2, 3=a3\n ', res)
def test_get_formatted(self):
sents = SentenceList([
Sentence(0, "", 0, "1,2", "2,1"),
Sentence(1, "", 0, "0", "0")
])
symbol_ids = SymbolIdDict.init_from_symbols({"a", "b", "c"})
accent_ids = AccentsDict.init_from_accents({"a1", "a2", "a3"})
res = sents.get_formatted(symbol_ids, accent_ids)
self.assertEqual('0: b c (2)\n 2 1\n 1=a2, 2=a3\n \n1: a (1)\n 0\n 0=a1\n ', res)
def test_sents_accent_template(self):
sents = SentenceList([
Sentence(0, "", 0, "1,2", "2,1"),
Sentence(0, "", 0, "0", "0")
])
symbol_ids = SymbolIdDict.init_from_symbols({"a", "b", "c"})
accent_ids = AccentsDict.init_from_accents({"a1", "a2", "a3"})
res = sents_accent_template(sents, symbol_ids, accent_ids)
self.assertEqual(3, len(res))
self.assertEqual("0-0", res.items()[0].position)
self.assertEqual("b", res.items()[0].symbol)
self.assertEqual("a3", res.items()[0].accent)
self.assertEqual("0-1", res.items()[1].position)
self.assertEqual("c", res.items()[1].symbol)
self.assertEqual("a2", res.items()[1].accent)
self.assertEqual("1-0", res.items()[2].position)
self.assertEqual("a", res.items()[2].symbol)
self.assertEqual("a1", res.items()[2].accent)
def test_sents_accent_apply(self):
sents = SentenceList([
Sentence(0, "", 0, "1,2", "2,1"),
Sentence(0, "", 0, "0", "0")
])
symbol_ids = SymbolIdDict.init_from_symbols({"a", "b", "c"})
accent_ids = AccentsDict.init_from_accents({"a1", "a2", "a3"})
acc_sents_template = sents_accent_template(sents, symbol_ids, accent_ids)
acc_sents_template.items()[0].accent = "a1"
acc_sents_template.items()[1].accent = "a3"
acc_sents_template.items()[2].accent = "a2"
res = sents_accent_apply(sents, acc_sents_template, accent_ids)
self.assertEqual(2, len(sents))
self.assertEqual("0,2", res.items()[0].serialized_accents)
self.assertEqual("1", res.items()[1].serialized_accents)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(UnitTests)
unittest.TextTestRunner(verbosity=2).run(suite)
|
"""
Generates setups for baroclinic MMS tests
"""
import sympy
import numbers
from sympy import init_printing
init_printing()
# coordinates
x, y, z = sympy.symbols('xyz[0] xyz[1] xyz[2]')
x_2d, y_2d = sympy.symbols('xy[0] xy[1]')
z_tilde = sympy.symbols('z_tilde')
# domain lenght, x in [0, Lx], y in [0, Ly]
lx, ly = sympy.symbols('lx ly')
# depth scale
depth = sympy.symbols('depth', positive=True)
# coriolis scale
f0 = sympy.symbols('f0', positive=True)
# viscosity scale
nu0 = sympy.symbols('nu0', positive=True)
# constant salinity
salt0 = sympy.symbols('salt_const', positive=True)
temp0 = sympy.symbols('temp_const', positive=True)
# gravitational acceleration
g = sympy.symbols('g_grav')
# time
t = sympy.symbols('t', positive=True)
T = sympy.symbols('T', positive=True)
eos_alpha, eos_beta, eos_t0, eos_s0 = sympy.symbols('eos_alpha eos_beta eos_t0 eos_s0')
rho0 = sympy.symbols('rho_0', positive=True)
# setup 1 -- temp only
# bath = depth
# elev = 0
# u = 0
# v = 0
# temp = 5*sympy.cos((2*x + y)/lx)*sympy.cos((z/depth)) + 15
# salt = salt0
# nu = nu0
# f = f0
# omit_int_pg = False
# setup 2 -- elevation only
# bath = depth
# elev = 5*sympy.cos((x + 5*y/2)/lx)
# u = 0
# v = 0
# temp = temp0
# salt = salt0
# nu = nu0
# f = f0
# #omit_int_pg = True
# omit_int_pg = False # setup2b
# setup 3 -- velocity only
# bath = depth
# elev = 0
# u = sympy.cos((2*x + y)/lx)
# v = 0
# temp = temp0
# salt = salt0
# nu = nu0
# f = f0
# omit_int_pg = True
# setup 4 -- velocity and temp
# bath = depth
# elev = 0
# u = sympy.cos((2*x + y)/lx)*sympy.cos(3*(z/depth))/2
# v = 0
# temp = 5*sympy.cos((x + 2*y)/lx)*sympy.cos((z/depth)) + 15
# salt = salt0
# nu = nu0
# f = f0
# omit_int_pg = False # setup4b
# setup 5 -- velocity and temp, symmetric
bath = depth
elev = 0
u = sympy.sin(2*sympy.pi*x/lx)*sympy.cos(3*(z/depth))/2
v = sympy.cos(sympy.pi*y/ly)*sympy.sin((z/depth/2))/3
temp = 15*sympy.sin(sympy.pi*x/lx)*sympy.sin(sympy.pi*y/ly)*sympy.cos(z/depth) + 15
salt = salt0
nu = nu0
f = f0
omit_int_pg = False
def split_velocity(u, v, eta, bath):
u_2d = sympy.integrate(u, (z, -bath, eta))/(eta+bath)
v_2d = sympy.integrate(v, (z, -bath, eta))/(eta+bath)
u_3d = u - u_2d
v_3d = v - v_2d
return u_3d, v_3d, u_2d, v_2d
def evaluate_w(eta, u, v, bath):
assert sympy.diff(bath, x) == 0 and sympy.diff(bath, y) == 0, 'bath source not implemented'
return sympy.integrate(-(sympy.diff(u, x) + sympy.diff(v, y)), (z, -bath, z))
def evaluate_baroclinicity(elev, temp, salt):
rho = - eos_alpha*(temp - eos_t0) + eos_beta*(salt - eos_s0)
baroc_head = sympy.integrate(rho/rho0, (z, elev, z))
return rho, baroc_head
def evaluate_tracer_source(eta, trac, u, v, w, bath, f, nu):
adv_t_uv = sympy.diff(trac, x)*u + sympy.diff(trac, y)*v
adv_t_w = sympy.diff(trac, z)*w
adv_t = adv_t_uv + adv_t_w
return adv_t, adv_t_uv, adv_t_w
def evaluate_mom_source(eta, baroc_head, u, v, w, u_3d, v_3d, bath, f, nu):
int_pg_x = -g*sympy.diff(baroc_head, x) # NOTE why the minus sign? BUG
int_pg_y = -g*sympy.diff(baroc_head, y)
adv_u = sympy.diff(u, x)*u + sympy.diff(u, y)*v
adv_v = sympy.diff(v, x)*u + sympy.diff(v, y)*v
adv_w_u = sympy.diff(u, z)*w
adv_w_v = sympy.diff(v, z)*w
cori_u = -f*v_3d
cori_v = f*u_3d
res_u = adv_u + adv_w_u + cori_u
res_v = adv_v + adv_w_v + cori_v
if not omit_int_pg:
res_u += int_pg_x
res_v += int_pg_y
return res_u, res_v, int_pg_x, int_pg_y, adv_u, adv_v, adv_w_u, adv_w_v, cori_u, cori_v
def evaluate_swe_source(eta, u, v, bath, f, nu, nonlin=True):
# evaluate shallow water equations
if nonlin:
tot_depth = eta + bath
else:
tot_depth = bath
div_hu = sympy.diff(tot_depth*u, x) + sympy.diff(tot_depth*v, y)
res_elev = sympy.diff(eta, t) + div_hu
cori_u = -f*v
cori_v = f*u
pg_u = g*sympy.diff(eta, x)
pg_v = g*sympy.diff(eta, y)
visc_u = -(2*sympy.diff(nu*sympy.diff(u, x), x) +
sympy.diff(nu*sympy.diff(u, y), y) +
sympy.diff(nu*sympy.diff(v, x), y))
visc_v = -(2*sympy.diff(nu*sympy.diff(v, y), y) +
sympy.diff(nu*sympy.diff(v, x), x) +
sympy.diff(nu*sympy.diff(u, y), x))
visc_u += -sympy.diff(tot_depth, x)/tot_depth * nu * 2 * sympy.diff(u, x)
visc_v += -sympy.diff(tot_depth, y)/tot_depth * nu * 2 * sympy.diff(v, y)
# NOTE in the coupled system 2d mom eq has no advection/diffusion terms
res_u = sympy.diff(u, t) + cori_u + pg_u
res_v = sympy.diff(v, t) + cori_v + pg_v
return res_elev, res_u, res_v, cori_u, cori_v
u_3d, v_3d, u_2d, v_2d = split_velocity(u, v, elev, bath)
w = evaluate_w(elev, u, v, bath)
rho, baroc_head = evaluate_baroclinicity(elev, temp, salt)
mom_source_x, mom_source_y, int_pg_x, int_pg_y, adv_u, adv_v, adv_w_u, adv_w_v, cori_u, cori_v = evaluate_mom_source(elev, baroc_head, u, v, w, u_3d, v_3d, bath, f, nu)
vol_source_2d, mom_source_2d_x, mom_source_2d_y, cori_u_2d, cori_v_2d = evaluate_swe_source(elev, u_2d, v_2d, bath, f, nu, nonlin=True)
temp_source_3d, adv_t_uv, adv_t_w = evaluate_tracer_source(elev, temp, u, v, w, bath, f, nu)
def expr2str(e):
if isinstance(e, (numbers.Number, sympy.numbers.Zero)):
return 'Constant({:})'.format(e)
return str(e)
def print_expr(name, *expr, dict_fmt=True):
if len(expr) == 1:
expr_str = expr2str(expr[0])
else:
if all(isinstance(e, numbers.Number) for e in expr):
comp_str = ', '.join([str(e) for e in expr])
expr_str = 'Constant((' + comp_str + '))'
else:
comp_str = ', '.join([expr2str(e) for e in expr])
expr_str = 'as_vector((' + comp_str + '))'
if dict_fmt:
print(" out['{:}'] = {:}".format(name, expr_str))
else:
print(" {:} = {:}".format(name, expr_str))
def to_2d_coords(expr):
if isinstance(expr, numbers.Number):
return expr
return expr.subs(x, x_2d).subs(y, y_2d)
def print_ufl_expressions():
"""
Print python expressions
"""
print_expr('elev_2d', to_2d_coords(elev))
print_expr('uv_full_3d', u, v, 0)
print_expr('uv_2d', to_2d_coords(u_2d), to_2d_coords(v_2d))
print_expr('uv_dav_3d', u_2d, v_2d, 0)
print_expr('uv_3d', u_3d, v_3d, 0)
print_expr('w_3d', 0, 0, w)
print_expr('temp_3d', temp)
print_expr('density_3d', rho)
print_expr('baroc_head_3d', baroc_head)
print_expr('int_pg_3d', int_pg_x, int_pg_y, 0)
print_expr('vol_source_2d', to_2d_coords(vol_source_2d))
print_expr('mom_source_2d', to_2d_coords(mom_source_2d_x), to_2d_coords(mom_source_2d_y))
print_expr('mom_source_3d', mom_source_x, mom_source_y, 0)
print_expr('temp_source_3d', temp_source_3d)
def print_latex_expressions():
"""
Print expressions in Latex for publications
"""
_x, _y, _z = sympy.symbols('x y z')
_lx, _ly = sympy.symbols('L_x L_y')
_depth = sympy.symbols('h')
_eos_alpha, _eos_t0, _eos_s0 = sympy.symbols('alpha T_0 S_0')
_eos_beta = 0
_rho0 = sympy.symbols('rho_0', positive=True)
_salt0 = sympy.symbols('S_a', positive=True)
_g = sympy.symbols('g', positive=True)
def for_latex(e):
o = e.subs([(x, _x), (y, _y), (z, _z), (lx, _lx), (ly, _ly), (depth, _depth), (g, _g)])
o = o.subs([(eos_alpha, _eos_alpha), (eos_beta, _eos_beta), (eos_t0, _eos_t0), (eos_s0, _eos_s0), (rho0, _rho0), (salt0, _salt0)])
return sympy.simplify(o)
print('\nAnalytical functions:\n')
print('T_a &= ' + sympy.latex(for_latex(temp)))
print('u_a &= ' + sympy.latex(for_latex(u)))
print('v_a &= ' + sympy.latex(for_latex(v)))
print('u_a\' &= ' + sympy.latex(for_latex(u_3d)))
print('v_a\' &= ' + sympy.latex(for_latex(v_3d)))
print('\\bar{u}_a &= ' + sympy.latex(for_latex(u_2d)))
print('\\bar{v}_a &= ' + sympy.latex(for_latex(v_2d)))
print('w_a &= ' + sympy.latex(for_latex(w)))
print('\\rho_a\' &= ' + sympy.latex(for_latex(rho)))
print('r_a &= ' + sympy.latex(for_latex(baroc_head)))
print('(\\IPG)_{x} &= ' + sympy.latex(for_latex(int_pg_x)))
print('(\\IPG)_{y} &= ' + sympy.latex(for_latex(int_pg_y)))
print('(\\bnabla_h \\cdot (\\bu \\bu))_{x} &= ' + sympy.latex(for_latex(adv_u)))
print('(\\bnabla_h \\cdot (\\bu \\bu))_{y} &= ' + sympy.latex(for_latex(adv_v)))
print('\\pd{\\left(w u \\right)}{z} &= ' + sympy.latex(for_latex(adv_w_u)))
print('\\pd{\\left(w v \\right)}{z} &= ' + sympy.latex(for_latex(adv_w_v)))
print('f\\bm{e}_z\\wedge\\baru &= ' + sympy.latex(for_latex(cori_u_2d)))
print('f\\bm{e}_z\\wedge\\baru &= ' + sympy.latex(for_latex(cori_v_2d)))
print('f\\bm{e}_z\\wedge u\' &= ' + sympy.latex(for_latex(cori_u)))
print('f\\bm{e}_z\\wedge v\' &= ' + sympy.latex(for_latex(cori_v)))
print('\\bnabla_h\\cdot\\left(H\\bbaru\\right) &= ' + sympy.latex(for_latex(vol_source_2d)))
print('\\bnabla_h \\cdot (\\bu T) &= ' + sympy.latex(for_latex(adv_t_uv)))
print('\\pd{\\left(w T \\right)}{z} &= ' + sympy.latex(for_latex(adv_t_w)))
print_ufl_expressions()
|
<reponame>lienching/nasbench_keras
# Copyright evgps
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# Code created based on https://github.com/google-research/nasbench
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import hashlib
import itertools
import numpy as np
# Graphviz is optional and only required for visualization.
try:
import graphviz # pylint: disable=g-import-not-at-top
except ImportError:
pass
def hash_module(matrix, labeling):
"""Computes a graph-invariance MD5 hash of the matrix and label pair.
Args:
matrix: np.ndarray square upper-triangular adjacency matrix.
labeling: list of int labels of length equal to both dimensions of
matrix.
Returns:
MD5 hash of the matrix and labeling.
"""
vertices = np.shape(matrix)[0]
in_edges = np.sum(matrix, axis=0).tolist()
out_edges = np.sum(matrix, axis=1).tolist()
assert len(in_edges) == len(out_edges) == len(labeling)
hashes = list(zip(out_edges, in_edges, labeling))
hashes = [hashlib.md5(str(h).encode('utf-8')).hexdigest() for h in hashes]
# Computing this up to the diameter is probably sufficient but since the
# operation is fast, it is okay to repeat more times.
for _ in range(vertices):
new_hashes = []
for v in range(vertices):
in_neighbors = [hashes[w] for w in range(vertices) if matrix[w, v]]
out_neighbors = [hashes[w] for w in range(vertices) if matrix[v, w]]
new_hashes.append(hashlib.md5(
(''.join(sorted(in_neighbors)) + '|' +
''.join(sorted(out_neighbors)) + '|' +
hashes[v]).encode('utf-8')).hexdigest())
hashes = new_hashes
fingerprint = hashlib.md5(str(sorted(hashes)).encode('utf-8')).hexdigest()
return fingerprint
class ModelSpec(object):
"""Model specification given adjacency matrix and labeling."""
def __init__(self, matrix, ops, data_format='channels_last'):
"""Initialize the module spec.
Args:
matrix: ndarray or nested list with shape [V, V] for the adjacency matrix.
ops: V-length list of labels for the base ops used. The first and last
elements are ignored because they are the input and output vertices
which have no operations. The elements are retained to keep consistent
indexing.
data_format: channels_last or channels_first.
Raises:
ValueError: invalid matrix or ops
"""
if not isinstance(matrix, np.ndarray):
matrix = np.array(matrix)
shape = np.shape(matrix)
if len(shape) != 2 or shape[0] != shape[1]:
raise ValueError('matrix must be square')
if shape[0] != len(ops):
raise ValueError('length of ops must match matrix dimensions')
if not is_upper_triangular(matrix):
raise ValueError('matrix must be upper triangular')
# Both the original and pruned matrices are deep copies of the matrix and
# ops so any changes to those after initialization are not recognized by the
# spec.
self.original_matrix = copy.deepcopy(matrix)
self.original_ops = copy.deepcopy(ops)
self.matrix = copy.deepcopy(matrix)
self.ops = copy.deepcopy(ops)
self.valid_spec = True
self._prune()
self.data_format = data_format
def _prune(self):
"""Prune the extraneous parts of the graph.
General procedure:
1) Remove parts of graph not connected to input.
2) Remove parts of graph not connected to output.
3) Reorder the vertices so that they are consecutive after steps 1 and 2.
These 3 steps can be combined by deleting the rows and columns of the
vertices that are not reachable from both the input and output (in reverse).
"""
num_vertices = np.shape(self.original_matrix)[0]
# DFS forward from input
visited_from_input = set([0])
frontier = [0]
while frontier:
top = frontier.pop()
for v in range(top + 1, num_vertices):
if self.original_matrix[top, v] and v not in visited_from_input:
visited_from_input.add(v)
frontier.append(v)
# DFS backward from output
visited_from_output = set([num_vertices - 1])
frontier = [num_vertices - 1]
while frontier:
top = frontier.pop()
for v in range(0, top):
if self.original_matrix[v, top] and v not in visited_from_output:
visited_from_output.add(v)
frontier.append(v)
# Any vertex that isn't connected to both input and output is extraneous to
# the computation graph.
extraneous = set(range(num_vertices)).difference(
visited_from_input.intersection(visited_from_output))
# If the non-extraneous graph is less than 2 vertices, the input is not
# connected to the output and the spec is invalid.
if len(extraneous) > num_vertices - 2:
self.matrix = None
self.ops = None
self.valid_spec = False
return
self.matrix = np.delete(self.matrix, list(extraneous), axis=0)
self.matrix = np.delete(self.matrix, list(extraneous), axis=1)
for index in sorted(extraneous, reverse=True):
del self.ops[index]
def hash_spec(self, canonical_ops):
"""Computes the isomorphism-invariant graph hash of this spec.
Args:
canonical_ops: list of operations in the canonical ordering which they
were assigned (i.e. the order provided in the config['available_ops']).
Returns:
MD5 hash of this spec which can be used to query the dataset.
"""
# Invert the operations back to integer label indices used in graph gen.
labeling = [-1] + [canonical_ops.index(op) for op in self.ops[1:-1]] + [-2]
return graph_util.hash_module(self.matrix, labeling)
def visualize(self):
"""Creates a dot graph. Can be visualized in colab directly."""
num_vertices = np.shape(self.matrix)[0]
g = graphviz.Digraph()
g.node(str(0), 'input')
for v in range(1, num_vertices - 1):
g.node(str(v), self.ops[v])
g.node(str(num_vertices - 1), 'output')
for src in range(num_vertices - 1):
for dst in range(src + 1, num_vertices):
if self.matrix[src, dst]:
g.edge(str(src), str(dst))
return g
def is_upper_triangular(matrix):
"""True if matrix is 0 on diagonal and below."""
for src in range(np.shape(matrix)[0]):
for dst in range(0, src + 1):
if matrix[src, dst] != 0:
return False
return True |
# import tensorflow as tf
# import numpy as np
import functools
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import math
from torch.nn.modules.linear import Linear
class ResBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, bn=False, stride=1):
super(ResBlock, self).__init__()
self.bn = bn
if bn:
self.bn0 = nn.BatchNorm2d(in_planes)
self.conv1 = nn.Conv2d(
in_planes, planes, kernel_size=3, stride=stride, padding=1)
if bn:
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
stride=1, padding=1)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != planes:
self.shortcut = nn.Sequential(
nn.Conv2d(in_planes, planes,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes)
)
def forward(self, x):
if self.bn:
out = F.relu(self.bn0(x))
else:
out = F.relu(x)
if self.bn:
out = F.relu(self.bn1(self.conv1(out)))
else:
out = F.relu(self.conv1(out))
out = self.conv2(out)
out += self.shortcut(x)
# out = F.relu(out)
return out
def resnet(input_shape, level):
# print(level)
net = []
net += [nn.Conv2d(input_shape[0], 64, 3, 1, 1)]
net += [nn.BatchNorm2d(64)]
net += [nn.ReLU()]
net += [nn.MaxPool2d(2)]
net += [ResBlock(64, 64)]
if level == 1:
return nn.Sequential(*net)
net += [ResBlock(64, 128, stride=2)]
if level == 2:
return nn.Sequential(*net)
net += [ResBlock(128, 128)]
if level == 3:
return nn.Sequential(*net)
net += [ResBlock(128, 256, stride=2)]
if level <= 4:
return nn.Sequential(*net)
else:
raise Exception('No level %d' % level)
def resnet_tail(level, num_class = 10):
print(level)
net = []
if level <= 1:
net += [ResBlock(64, 128, stride=2)]
if level <= 2:
net += [ResBlock(128, 128)]
if level <= 3:
net += [ResBlock(128, 256, stride=2)]
net += [ResBlock(256, 256, stride=1)]
net += [ResBlock(256, 512, stride=2)]
net += [ResBlock(512, 512, stride=1)]
net += [ResBlock(512, 1024, stride=2)]
net += [ResBlock(1024, 1024, stride=1)]
# net += [nn.AvgPool2d(2)]
net += [nn.Flatten()]
net += [nn.LazyLinear(num_class)]
return nn.Sequential(*net)
def pilot(input_shape, level):
net = []
act = None
#act = 'swish'
print("[PILOT] activation: ", act)
net += [nn.Conv2d(input_shape[0], 64, 3, 2, 1)]
if level == 1:
net += [nn.Conv2d(64, 64, 3, 1, 1)]
return nn.Sequential(*net)
net += [nn.Conv2d(64, 128, 3, 2, 1)]
if level <= 3:
net += [nn.Conv2d(128, 128, 3, 1, 1)]
return nn.Sequential(*net)
net += [nn.Conv2d(128, 256, 3, 2, 1)]
if level <= 4:
net += [nn.Conv2d(256, 256, 3, 1, 1)]
return nn.Sequential(*net)
else:
raise Exception('No level %d' % level)
class View(nn.Module):
def __init__(self, shape):
super(View, self).__init__()
self.shape = shape
def forward(self, x):
return x.view(*self.shape)
def make_generator(latent_size):
net = []
net += [torch.nn.Linear(latent_size, 8*8*256, bias = False)]
net += [torch.nn.BatchNorm1d(8*8*256)]
net += [torch.nn.LeakyReLU()]
net += [View((-1, 256, 8, 8))]
net += [torch.nn.ConvTranspose2d(256, 128, 3, 1, padding = 1, bias = False)]
net += [torch.nn.BatchNorm2d(128)]
net += [torch.nn.LeakyReLU()]
net += [torch.nn.ConvTranspose2d(128, 64, 3, 2, padding = 1, output_padding=1, bias = False)]
net += [torch.nn.BatchNorm2d(64)]
net += [torch.nn.LeakyReLU()]
net += [torch.nn.ConvTranspose2d(64, 3, 3, 2, padding = 1, output_padding=1, bias = False)]
net += [torch.nn.Tanh()]
# net += [torch.nn.Sigmoid()]
return nn.Sequential(*net)
def multihead_buffer(feature_size):
assert len(feature_size) == 4
net = []
net += [torch.nn.Conv2d(feature_size[1], feature_size[1], 3, 1, padding=1)]
net += [torch.nn.BatchNorm2d(feature_size[1])]
net += [torch.nn.ReLU()]
net += [torch.nn.Conv2d(feature_size[1], feature_size[1], 3, 1, padding=1)]
net += [torch.nn.BatchNorm2d(feature_size[1])]
net += [torch.nn.ReLU()]
net += [torch.nn.Conv2d(feature_size[1], feature_size[1], 3, 1, padding=1)]
net += [torch.nn.BatchNorm2d(feature_size[1])]
net += [torch.nn.ReLU()]
return nn.Sequential(*net)
def multihead_buffer_res(feature_size):
assert len(feature_size) == 4
net = []
net += [ResBlock(feature_size[1], feature_size[1])]
net += [ResBlock(feature_size[1], feature_size[1])]
# net += [ResBlock(feature_size[1], feature_size[1])]
return nn.Sequential(*net)
def cifar_pilot(output_dim, level):
net = []
act = None
#act = 'swish'
print("[PILOT] activation: ", act)
print(output_dim)
if output_dim[2] == 32:
net += [nn.Conv2d(3, 64, 3, 1, 1)]
return nn.Sequential(*net)
net += [nn.Conv2d(3, 64, 3, 2, 1)]
net += [nn.Conv2d(64, 64, 3, 1, 1)]
if output_dim[2] == 16:
net += [nn.Conv2d(64, output_dim[1], 3, 1, 1)]
return nn.Sequential(*net)
net += [nn.Conv2d(64, 128, 3, 2, 1)]
net += [nn.Conv2d(128, 128, 3, 1, 1)]
if output_dim[2] == 8:
net += [nn.Conv2d(128, output_dim[1], 3, 1, 1)]
return nn.Sequential(*net)
net += [nn.Conv2d(128, 256, 3, 2, 1)]
if output_dim[2] == 4:
net += [nn.Conv2d(256, output_dim[1], 3, 1, 1)]
return nn.Sequential(*net)
else:
raise Exception('No level %d' % level)
def decoder(input_shape, level, channels=3):
net = []
#act = "relu"
act = None
print("[DECODER] activation: ", act)
net += [nn.ConvTranspose2d(input_shape[0], 256, 3, 2, 1, output_padding=1)]
if level == 1:
net += [nn.Conv2d(256, channels, 3, 1, 1)]
net += [nn.Tanh()]
return nn.Sequential(*net)
net += [nn.ConvTranspose2d(256, 128, 3, 2, 1, output_padding=1)]
if level <= 3:
net += [nn.Conv2d(128, channels, 3, 1, 1)]
net += [nn.Tanh()]
return nn.Sequential(*net)
net += [nn.ConvTranspose2d(128, channels, 3, 2, 1, output_padding=1)]
net += [nn.Tanh()]
return nn.Sequential(*net)
def cifar_decoder(input_shape, channels=3):
net = []
#act = "relu"
act = None
print("[DECODER] activation: ", act)
# print(input_shape)
if input_shape[2] == 16:
net += [nn.Conv2d(input_shape[0], 64, 3, 1, 1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.Conv2d(64, 64, 3, 1, 1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.ConvTranspose2d(64, channels, 3, 2, 1, output_padding=1)]
net += [nn.Tanh()]
return nn.Sequential(*net)
elif input_shape[2] == 8:
net += [nn.Conv2d(input_shape[0], 128, 3, 1, 1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.Conv2d(128, 128, 3, 1, 1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.ConvTranspose2d(128, 64, 3, 2, 1, output_padding=1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.Conv2d(64, 64, 3, 1, 1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.ConvTranspose2d(64, channels, 3, 2, 1, output_padding=1)]
net += [nn.Tanh()]
return nn.Sequential(*net)
elif input_shape[2] == 4:
net += [nn.Conv2d(input_shape[0], 256, 3, 1, 1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.ConvTranspose2d(256, 128, 3, 2, 1, output_padding=1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.Conv2d(128, 128, 3, 1, 1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.ConvTranspose2d(128, 64, 3, 2, 1, output_padding=1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.Conv2d(64, 64, 3, 1, 1)]
if act == "relu":
net += [nn.ReLU()]
net += [nn.ConvTranspose2d(64, channels, 3, 2, 1, output_padding=1)]
net += [nn.Tanh()]
return nn.Sequential(*net)
else:
raise Exception('No Dim %d' % input_shape[2])
# def inference_model(input_shape):
# pass
class inference_model(nn.Module):
def __init__(self,num_classes):
self.num_classes=num_classes
super(inference_model, self).__init__()
self.features=nn.Sequential(
nn.Linear(num_classes,1024),
# nn.Linear(num_classes,256),
# nn.BatchNorm1d(1024),
nn.ReLU(),
nn.Linear(1024,512),
# nn.Linear(256,128),
# nn.BatchNorm1d(512),
nn.ReLU(),
nn.Linear(512,128),
# nn.Linear(128,64),
# nn.BatchNorm1d(64),
nn.ReLU(),
)
self.labels=nn.Sequential(
nn.Linear(num_classes,1024),
nn.ReLU(),
nn.Linear(1024,512),
# nn.BatchNorm1d(128),
nn.ReLU(),
nn.Linear(512,128),
# nn.BatchNorm1d(64),
nn.ReLU(),
)
self.combine=nn.Sequential(
nn.Linear(128*2,256),
# nn.BatchNorm1d(256),
nn.ReLU(),
nn.Linear(256,128),
# nn.BatchNorm1d(128),
nn.ReLU(),
nn.Linear(128,64),
# nn.BatchNorm1d(64),
nn.ReLU(),
nn.Linear(64,1),
)
# for key in self.state_dict():
# if key.split('.')[-1] == 'weight':
# nn.init.normal(self.state_dict()[key], std=0.01)
# elif key.split('.')[-1] == 'bias':
# self.state_dict()[key][...] = 0
self.output= nn.Sigmoid()
def forward(self,x,l):
out_x = self.features(x)
out_l = self.labels(l)
is_member =self.combine( torch.cat((out_x ,out_l),1))
return self.output(is_member)
def discriminator(input_shape, level):
net = []
if level == 1:
net += [nn.Conv2d(input_shape[0], 128, 3, 2, 1)]
net += [nn.ReLU()]
net += [nn.Conv2d(128, 256, 3, 2, 1)]
elif level <= 3:
net += [nn.Conv2d(input_shape[0], 256, 3, 2, 1)]
elif level <= 4:
net += [nn.Conv2d(input_shape[0], 256, 3, 1, 1)]
bn = False
net += [ResBlock(256, 256, bn=bn)]
net += [ResBlock(256, 256, bn=bn)]
net += [ResBlock(256, 256, bn=bn)]
net += [ResBlock(256, 256, bn=bn)]
net += [ResBlock(256, 256, bn=bn)]
net += [ResBlock(256, 256, bn=bn)]
net += [nn.Conv2d(256, 256, 3, 2, 1)]
net += [nn.Flatten()]
net += [nn.LazyLinear(1)]
return nn.Sequential(*net)
#==========================================================================================
class custom_AE_bn(nn.Module):
def __init__(self, input_nc=256, output_nc=3, input_dim=8, output_dim=32, activation = "sigmoid"):
super(custom_AE_bn, self).__init__()
upsampling_num = int(np.log2(output_dim // input_dim))
# get [b, 3, 8, 8]
model = []
nc = input_nc
for num in range(upsampling_num - 1):
model += [nn.Conv2d(nc, int(nc/2), kernel_size=3, stride=1, padding=1)]
model += [nn.BatchNorm2d(int(nc/2))]
model += [nn.ReLU()]
model += [nn.ConvTranspose2d(int(nc/2), int(nc/2), kernel_size=3, stride=2, padding=1, output_padding=1)]
model += [nn.BatchNorm2d(int(nc/2))]
model += [nn.ReLU()]
nc = int(nc/2)
if upsampling_num >= 1:
model += [nn.Conv2d(int(input_nc/(2 ** (upsampling_num - 1))), int(input_nc/(2 ** (upsampling_num - 1))), kernel_size=3, stride=1, padding=1)]
model += [nn.BatchNorm2d(int(input_nc/(2 ** (upsampling_num - 1))))]
model += [nn.ReLU()]
model += [nn.ConvTranspose2d(int(input_nc/(2 ** (upsampling_num - 1))), output_nc, kernel_size=3, stride=2, padding=1, output_padding=1)]
if activation == "sigmoid":
model += [nn.Sigmoid()]
elif activation == "tanh":
model += [nn.Tanh()]
else:
model += [nn.Conv2d(input_nc, input_nc, kernel_size=3, stride=1, padding=1)]
model += [nn.BatchNorm2d(input_nc)]
model += [nn.ReLU()]
model += [nn.Conv2d(input_nc, output_nc, kernel_size=3, stride=1, padding=1)]
if activation == "sigmoid":
model += [nn.Sigmoid()]
elif activation == "tanh":
model += [nn.Tanh()]
self.m = nn.Sequential(*model)
def forward(self, x):
output = self.m(x)
return output
class custom_AE(nn.Module):
def __init__(self, input_nc=256, output_nc=3, input_dim=8, output_dim=32, activation = "sigmoid"):
super(custom_AE, self).__init__()
upsampling_num = int(np.log2(output_dim // input_dim))
# get [b, 3, 8, 8]
model = []
nc = input_nc
for num in range(upsampling_num - 1):
#TODO: change to Conv2d
model += [nn.Conv2d(nc, int(nc/2), kernel_size=3, stride=1, padding=1)]
model += [nn.ReLU()]
model += [nn.ConvTranspose2d(int(nc/2), int(nc/2), kernel_size=3, stride=2, padding=1, output_padding=1)]
model += [nn.ReLU()]
nc = int(nc/2)
if upsampling_num >= 1:
model += [nn.Conv2d(int(input_nc/(2 ** (upsampling_num - 1))), int(input_nc/(2 ** (upsampling_num - 1))), kernel_size=3, stride=1, padding=1)]
model += [nn.ReLU()]
model += [nn.ConvTranspose2d(int(input_nc/(2 ** (upsampling_num - 1))), output_nc, kernel_size=3, stride=2, padding=1, output_padding=1)]
if activation == "sigmoid":
model += [nn.Sigmoid()]
elif activation == "tanh":
model += [nn.Tanh()]
else:
model += [nn.Conv2d(input_nc, input_nc, kernel_size=3, stride=1, padding=1)]
model += [nn.ReLU()]
model += [nn.Conv2d(input_nc, output_nc, kernel_size=3, stride=1, padding=1)]
if activation == "sigmoid":
model += [nn.Sigmoid()]
elif activation == "tanh":
model += [nn.Tanh()]
self.m = nn.Sequential(*model)
def forward(self, x):
output = self.m(x)
return output
class conv_normN_AE(nn.Module):
def __init__(self, N = 0, internal_nc = 64, input_nc=256, output_nc=3, input_dim=8, output_dim=32, activation = "sigmoid"):
super(conv_normN_AE, self).__init__()
if input_dim != 0:
upsampling_num = int(np.log2(output_dim // input_dim)) # input_dim =0 denotes confidensce score
self.confidence_score = False
else:
upsampling_num = int(np.log2(output_dim))
self.confidence_score = True
model = []
model += [nn.Conv2d(input_nc, internal_nc, kernel_size=3, stride=1, padding=1)] #first
model += [nn.BatchNorm2d(internal_nc)]
model += [nn.ReLU()]
for _ in range(N):
model += [nn.Conv2d(internal_nc, internal_nc, kernel_size=3, stride=1, padding=1)] #Middle-N
model += [nn.BatchNorm2d(internal_nc)]
model += [nn.ReLU()]
if upsampling_num >= 1:
model += [nn.ConvTranspose2d(internal_nc, internal_nc, kernel_size=3, stride=2, padding=1, output_padding=1)]
model += [nn.BatchNorm2d(internal_nc)]
else:
model += [nn.Conv2d(internal_nc, internal_nc, kernel_size=3, stride=1, padding=1)] #two required
model += [nn.BatchNorm2d(internal_nc)]
model += [nn.ReLU()]
if upsampling_num >= 2:
model += [nn.ConvTranspose2d(internal_nc, internal_nc, kernel_size=3, stride=2, padding=1, output_padding=1)]
model += [nn.BatchNorm2d(internal_nc)]
else:
model += [nn.Conv2d(internal_nc, internal_nc, kernel_size=3, stride=1, padding=1)] #two required
model += [nn.BatchNorm2d(internal_nc)]
model += [nn.ReLU()]
if upsampling_num >= 3:
for _ in range(upsampling_num - 2):
model += [nn.ConvTranspose2d(internal_nc, internal_nc, kernel_size=3, stride=2, padding=1, output_padding=1)]
model += [nn.BatchNorm2d(internal_nc)]
model += [nn.ReLU()]
model += [nn.Conv2d(internal_nc, output_nc, kernel_size=3, stride=1, padding=1)] #last
model += [nn.BatchNorm2d(output_nc)]
if activation == "sigmoid":
model += [nn.Sigmoid()]
elif activation == "tanh":
model += [nn.Tanh()]
self.m = nn.Sequential(*model)
def forward(self, x):
if self.confidence_score:
x = x.view(x.size(0), x.size(2), 1, 1)
output = self.m(x)
return output
class res_normN_AE(nn.Module):
def __init__(self, N = 0, internal_nc = 64, input_nc=256, output_nc=3, input_dim=8, output_dim=32, activation = "sigmoid"):
super(res_normN_AE, self).__init__()
if input_dim != 0:
upsampling_num = int(np.log2(output_dim // input_dim)) # input_dim =0 denotes confidensce score
self.confidence_score = False
else:
upsampling_num = int(np.log2(output_dim))
self.confidence_score = True
model = []
model += [ResBlock(input_nc, internal_nc, bn = True, stride=1)] #first
model += [nn.ReLU()]
for _ in range(N):
model += [ResBlock(internal_nc, internal_nc, bn = True, stride=1)]
model += [nn.ReLU()]
if upsampling_num >= 1:
model += [nn.ConvTranspose2d(internal_nc, internal_nc, kernel_size=3, stride=2, padding=1, output_padding=1)]
model += [nn.BatchNorm2d(internal_nc)]
else:
model += [ResBlock(internal_nc, internal_nc, bn = True, stride=1)] #second
model += [nn.ReLU()]
if upsampling_num >= 2:
model += [nn.ConvTranspose2d(internal_nc, internal_nc, kernel_size=3, stride=2, padding=1, output_padding=1)]
model += [nn.BatchNorm2d(internal_nc)]
else:
model += [ResBlock(internal_nc, internal_nc, bn = True, stride=1)]
model += [nn.ReLU()]
if upsampling_num >= 3:
for _ in range(upsampling_num - 2):
model += [nn.ConvTranspose2d(internal_nc, internal_nc, kernel_size=3, stride=2, padding=1, output_padding=1)]
model += [nn.BatchNorm2d(internal_nc)]
model += [nn.ReLU()]
model += [ResBlock(internal_nc, output_nc, bn = True, stride=1)]
if activation == "sigmoid":
model += [nn.Sigmoid()]
elif activation == "tanh":
model += [nn.Tanh()]
self.m = nn.Sequential(*model)
def forward(self, x):
if self.confidence_score:
x = x.view(x.size(0), x.size(2), 1, 1)
output = self.m(x)
return output
def classifier_binary(input_shape, class_num):
net = []
# xin = tf.keras.layers.Input(input_shape)
# net += [nn.ReLU()]
# net += [nn.Conv2d(input_shape[0], 128, 3, 1, 1)]
# net += [nn.ReLU()]
# net += [ResBlock(128, 128, bn=True)]
# net += [ResBlock(128, 128, bn=True)]
net += [nn.ReLU()]
net += [nn.Flatten()]
net += [nn.LazyLinear(256)]
net += [nn.ReLU()]
net += [nn.Linear(256, 128)]
net += [nn.ReLU()]
# if(class_num > 1):
# net += [nn.BatchNorm2d(np.prod([input_shape[0], 32, input_shape[2], input_shape[3]]))]
net += [nn.Linear(128, class_num)]
return nn.Sequential(*net)
def pilotClass(input_shape, level):
net = []
# xin = tf.keras.layers.Input(input_shape)
net += [nn.Conv2d(input_shape[0], 64, 3, 2, 1)]
net += [nn.SiLU]
if level == 1:
net += [nn.Conv2d(64, 64, 3, 1, 1)]
return nn.Sequential(*net)
net += [nn.Conv2d(64, 128, 3, 2, 1)]
net += [nn.SiLU]
if level <= 3:
net += [nn.Conv2d(128, 128, 3, 1, 1)]
return nn.Sequential(*net)
net += [nn.Conv2d(128, 256, 3, 2, 1)]
net += [nn.SiLU]
if level <= 4:
net += [nn.Conv2d(256, 256, 3, 1, 1)]
return nn.Sequential(*net)
else:
raise Exception('No level %d' % level)
SETUPS = [(functools.partial(resnet, level=i), functools.partial(pilot, level=i), functools.partial(decoder, level=i), functools.partial(discriminator, level=i), functools.partial(resnet_tail, level=i)) for i in range(1,6)]
# bin class
l = 4
SETUPS += [(functools.partial(resnet, level=l), functools.partial(pilot, level=l), classifier_binary, functools.partial(discriminator, level=l), functools.partial(resnet_tail, level=l))]
l = 3
SETUPS += [(functools.partial(resnet, level=l), functools.partial(pilot, level=l), classifier_binary, functools.partial(discriminator, level=l), functools.partial(resnet_tail, level=l))] |
import json
from pathlib import Path
from ..exceptions import TaskValidationError
def validate_task_options(task_name, required, **options):
"""
Validate that all options respect the task requirements.
Arguments:
task_name (string): Task name to output in possible error.
required (list): List of required option names .
**options (dict): Given task options.
Raises:
TaskValidationError: If required options are missing from given ``options``.
"""
fields = []
if required:
for name in set(required):
if name not in options:
fields.append(name)
if fields:
msg = "Task '{name}' require option(s): {fields}".format(
name=task_name,
fields=", ".join(sorted(fields)),
)
raise TaskValidationError(msg)
return True
def validate_job_file(filepath):
"""
Validate if a Job files exist, is valid JSON and have required parameters.
Arguments:
filepath (pathlib.Path): Path to a file to check.
Returns:
list: Error messages if any.
"""
errors = []
# Don't continue checking if file does not exists
if not filepath.exists():
errors.append("Configuration file does not exists: {}".format(filepath))
# Proceed to file checks
else:
# Don't continue checking if invalid JSON
try:
with filepath.open("r") as fp:
data = json.load(fp)
except json.decoder.JSONDecodeError as e:
errors.append(
"Configuration file is not a valid JSON file: {}\n{}".format(
filepath,
" {}".format(str(e)),
)
)
# Proceed to rules checking
else:
if "basepath" not in data:
errors.append(
(
"Configuration file is missing required 'basepath' item: {}"
).format(filepath)
)
# Validate if basepath exists and is a directory
else:
p = Path(data["basepath"])
if not p.is_absolute():
p = (filepath.parents[0] / p).resolve()
if not p.exists():
errors.append(
(
"Configuration file value for 'basepath' is not an "
"existing path: {}".format(p.resolve())
)
)
elif not p.is_dir():
errors.append(
(
"Configuration file value for 'basepath' is not a "
"directory: {}".format(p)
)
)
if "tasks" not in data:
# NOTE: Task can still be an empty list, this is a behavior to permit
# to run a job just for listing basepath.
errors.append(
(
"Configuration file miss required 'tasks' item: {}"
).format(filepath)
)
return errors
def validate_jobs(filepaths):
"""
Validate all jobs from given file paths.
Arguments:
filepaths (pathlib.Path): Path to a file to check.
Returns:
dict: All job errors where errors are indexed on their job files.
"""
errors = {}
for path in filepaths:
results = validate_job_file(path)
if results:
errors[str(path)] = results
return errors
def is_allowed_file(source, extensions=[]):
"""
Check if source path is a file and allowed against a set of file extensions.
A source file which does not exists on filesystem is not valid. Allowed extensions
are compared only to the last file extension since some file names can contain dots
as word divider but still recognized as extensions.
Also, the comparaison is case insensitive.
NOTE:
Double extension like "tar.gz" won't work because of how this have been
implemented. We match against extensions with the last suffix from Path object
and so can only be "gz", this was done to be compatible with
"dotted.file.names". But a new implementation may work correctly for double
extension if using string method "endswith" instead of "Path.suffixes[-1]".
Arguments:
source (pathlib.Path): Path to a file.
Keyword Arguments:
extensions (list): A list of extensions to check against. If empty, every
source filepaths are returned. Default to empty.
"""
if not source.is_file():
return False
# If no extensions, no further check
if not extensions:
return True
ext = source.suffixes[-1].lower()
if ext and ext.startswith("."):
ext = ext[1:]
if ext not in extensions:
return False
return True
|
<gh_stars>0
import io
import json
# import torchvision.transforms as transforms
from flask import Flask, jsonify, request
from PIL import Image
# from torchvision import datasets, models
# importing the libraries
#test
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms , models
from torch.autograd import Variable
import numpy as np
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
# version of pytorch
data_dir = 'ImageDataSet'
print(torch.__version__)
def load_split_train_test(datadir, valid_size = .2):
print("Model")
train_transforms = transforms.Compose([#transforms.RandomRotation(30), # data augmentations are great
#transforms.RandomResizedCrop(224), # but not in this case of map tiles
#transforms.RandomHorizontalFlip(),
transforms.Resize(224),
transforms.ToTensor(),
#transforms.Normalize([0.485, 0.456, 0.406], # PyTorch recommends these but in this
# [0.229, 0.224, 0.225]) # case I didn't get good results
])
test_transforms = transforms.Compose([transforms.Resize(224),
transforms.ToTensor(),
#transforms.Normalize([0.485, 0.456, 0.406],
# [0.229, 0.224, 0.225])
])
train_data = datasets.ImageFolder(datadir, transform=train_transforms)
test_data = datasets.ImageFolder(datadir, transform=test_transforms)
num_train = len(train_data)
indices = list(range(num_train))
split = int(np.floor(valid_size * num_train))
np.random.shuffle(indices)
from torch.utils.data.sampler import SubsetRandomSampler
train_idx, test_idx = indices[split:], indices[:split]
train_sampler = SubsetRandomSampler(train_idx)
test_sampler = SubsetRandomSampler(test_idx)
trainloader = torch.utils.data.DataLoader(train_data, sampler=train_sampler, batch_size=1)
testloader = torch.utils.data.DataLoader(test_data, sampler=test_sampler, batch_size=1)
return trainloader, testloader
trainloader, testloader = load_split_train_test(data_dir, .2)
print(trainloader.dataset.classes)
print("trainloader:=")
print(trainloader.dataset);
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = models.resnet50(pretrained=True)
model
for param in model.parameters():
param.requires_grad = False
model.fc = nn.Sequential(nn.Linear(2048, 512),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(512, 10),
nn.LogSoftmax(dim=1))
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.fc.parameters(), lr=0.003)
model.to(device)
epochs = 1
steps = 0
running_loss = 0
print_every = 10
train_losses, test_losses = [], []
for epoch in range(epochs):
for inputs, labels in trainloader:
steps += 1
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
logps = model.forward(inputs)
loss = criterion(logps, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if steps % print_every == 0:
test_loss = 0
accuracy = 0
model.eval()
with torch.no_grad():
for inputs, labels in testloader:
inputs, labels = inputs.to(device), labels.to(device)
logps = model.forward(inputs)
batch_loss = criterion(logps, labels)
test_loss += batch_loss.item()
ps = torch.exp(logps)
top_p, top_class = ps.topk(1, dim=1)
equals = top_class == labels.view(*top_class.shape)
accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
train_losses.append(running_loss/len(trainloader))
test_losses.append(test_loss/len(testloader))
print(f"Epoch {epoch+1}/{epochs}.. "
f"Train loss: {running_loss/print_every:.3f}.. "
f"Test loss: {test_loss/len(testloader):.3f}.. "
f"Test accuracy: {accuracy/len(testloader):.3f}")
running_loss = 0
model.train()
torch.save(model, 'aerialmodel.pth') # whatever is trained and saved like this ,
#that should be used to predict by loading same model.. like torch.load('')
# so see reference, and I think better use separate py file for prediction,
# where we will load saved model and prdict
|
#
#------------------------------------------------------------------------------
# Copyright (c) 2013-2014, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#------------------------------------------------------------------------------
#
# dnoise_int.py - This file is part of the PySptools package.
#
from __future__ import division
import os.path as osp
import numpy as np
from scipy.signal import fftconvolve
from math import factorial
from . import dnoise
from .inval import *
class SavitzkyGolay(object):
"""Apply a Savitzky Golay low pass filter."""
def __init__(self):
self.denoised = None
self.dbands = None
@DenoiseSpectraInputValidation('SavitzkyGolay')
def denoise_spectra(self, M, window_size, order, deriv=0, rate=1):
"""
Apply the Savitzky Golay filter on each spectrum.
Smooth (and optionally differentiate) data with a Savitzky-Golay filter.
The Savitzky-Golay filter removes high frequency noise from data.
It has the advantage of preserving the original shape and
features of the signal better than other types of filtering
approaches, such as moving averages techniques.
Parameters:
M: `numpy array`
A HSI cube (m x n x p).
window_size: `int`
the length of the window. Must be an odd integer number.
order: `int`
the order of the polynomial used in the filtering.
Must be less then `window_size` - 1.
deriv: `int [default 0]`
the order of the derivative to compute
(default = 0 means only smoothing).
Returns: `numpy array`
the smoothed signal (or it's n-th derivative) (m x n x p).
Code source:
The scipy Cookbook, SavitzkyGolay section. This class is not under the
copyright of this file.
"""
h, w, numBands = M.shape
M = np.reshape(M, (w*h, numBands))
self.denoised = self._denoise1d(M, window_size, order, deriv, rate)
self.denoised = np.reshape(self.denoised, (h, w, numBands))
return self.denoised
@DenoiseBandsInputValidation('SavitzkyGolay')
def denoise_bands(self, M, window_size, order, derivative=None):
"""
Apply the Savitzky Golay filter on each band.
Parameters:
M: `numpy array`
A HSI cube (m x n x p).
window_size: `int`
the length of the window. Must be an odd integer number.
order: `int`
the order of the polynomial used in the filtering.
Must be less then `window_size` - 1.
derivative: `string [default None]`
direction of the derivative to compute, can be None,
'col', 'row', 'both'.
Returns: `numpy array`
the smoothed signal (or it's n-th derivative) (m x n x p).
Code source:
The scipy Cookbook, SavitzkyGolay section. This class is not under the
copyright of this file.
"""
h, w, numBands = M.shape
self.dbands = np.ones((h, w, numBands), dtype=np.float)
for i in range(numBands):
self.dbands[:,:,i] = self._denoise2d(M[:,:,i], window_size, order, derivative)
return self.dbands
def _denoise1d(self, M, window_size, order, deriv, rate):
try:
window_size = np.abs(np.int(window_size))
order = np.abs(np.int(order))
except ValueError as msg:
raise ValueError("in SavitzkyGolay.denoise_spectra(), window_size and order have to be of type int")
if window_size % 2 != 1 or window_size < 1:
raise TypeError("in SavitzkyGolay.denoise_spectra(), window_size size must be a positive odd number")
if window_size < order + 2:
raise TypeError("in SavitzkyGolay.denoise_spectra(), window_size is too small for the polynomials order")
order_range = range(order+1)
half_window = (window_size -1) // 2
# precompute coefficients
b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
# pad the signal at the extremes with
# values taken from the signal itself
N, p = M.shape
dn = np.ones((N,p), dtype=np.float)
long_signal = np.ndarray(p+2, dtype=np.float)
for i in range(N):
y = M[i]
firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
long_signal = np.concatenate((firstvals, y, lastvals))
dn[i] = fftconvolve(long_signal, m, mode='valid')
return dn
def _denoise2d(self, z, window_size, order, derivative=None):
# number of terms in the polynomial expression
n_terms = ( order + 1 ) * ( order + 2) / 2.0
if window_size % 2 == 0:
raise ValueError('in SavitzkyGolay.denoise_bands(), window_size must be odd')
if window_size**2 < n_terms:
raise ValueError('in SavitzkyGolay.denoise_bands(), order is too high for the window size')
half_size = window_size // 2
# exponents of the polynomial.
# p(x,y) = a0 + a1*x + a2*y + a3*x^2 + a4*y^2 + a5*x*y + ...
# this line gives a list of two item tuple. Each tuple contains
# the exponents of the k-th term. First element of tuple is for x
# second element for y.
# Ex. exps = [(0,0), (1,0), (0,1), (2,0), (1,1), (0,2), ...]
exps = [ (k-n, n) for k in range(order+1) for n in range(k+1) ]
# coordinates of points
ind = np.arange(-half_size, half_size+1, dtype=np.float64)
dx = np.repeat( ind, window_size )
dy = np.tile( ind, [window_size, 1]).reshape(window_size**2, )
# build matrix of system of equation
A = np.empty( (window_size**2, len(exps)) )
for i, exp in enumerate( exps ):
A[:,i] = (dx**exp[0]) * (dy**exp[1])
# pad input array with appropriate values at the four borders
new_shape = z.shape[0] + 2*half_size, z.shape[1] + 2*half_size
Z = np.zeros( (new_shape) )
# top band
band = z[0, :]
Z[:half_size, half_size:-half_size] = band - np.abs( np.flipud( z[1:half_size+1, :] ) - band )
# bottom band
band = z[-1, :]
Z[-half_size:, half_size:-half_size] = band + np.abs( np.flipud( z[-half_size-1:-1, :] ) -band )
# left band
band = np.tile( z[:,0].reshape(-1,1), [1,half_size])
Z[half_size:-half_size, :half_size] = band - np.abs( np.fliplr( z[:, 1:half_size+1] ) - band )
# right band
band = np.tile( z[:,-1].reshape(-1,1), [1,half_size] )
Z[half_size:-half_size, -half_size:] = band + np.abs( np.fliplr( z[:, -half_size-1:-1] ) - band )
# central band
Z[half_size:-half_size, half_size:-half_size] = z
# top left corner
band = z[0,0]
Z[:half_size,:half_size] = band - np.abs( np.flipud(np.fliplr(z[1:half_size+1,1:half_size+1]) ) - band )
# bottom right corner
band = z[-1,-1]
Z[-half_size:,-half_size:] = band + np.abs( np.flipud(np.fliplr(z[-half_size-1:-1,-half_size-1:-1]) ) - band )
# top right corner
band = Z[half_size,-half_size:]
Z[:half_size,-half_size:] = band - np.abs( np.flipud(Z[half_size+1:2*half_size+1,-half_size:]) - band )
# bottom left corner
band = Z[-half_size:,half_size].reshape(-1,1)
Z[-half_size:,:half_size] = band - np.abs( np.fliplr(Z[-half_size:, half_size+1:2*half_size+1]) - band )
# solve system and convolve
if derivative == None:
m = np.linalg.pinv(A)[0].reshape((window_size, -1))
return fftconvolve(Z, m, mode='valid')
elif derivative == 'col':
c = np.linalg.pinv(A)[1].reshape((window_size, -1))
return fftconvolve(Z, -c, mode='valid')
elif derivative == 'row':
r = np.linalg.pinv(A)[2].reshape((window_size, -1))
return fftconvolve(Z, -r, mode='valid')
elif derivative == 'both':
c = np.linalg.pinv(A)[1].reshape((window_size, -1))
r = np.linalg.pinv(A)[2].reshape((window_size, -1))
return fftconvolve(Z, -r, mode='valid'), scipy.signal.fftconvolve(Z, -c, mode='valid')
def plot_spectrum_sample(self, M, path, x, y, suffix=None):
"""
Plot a spectrum sample with the original and the
filtered signal.
Parameters:
M: 'numpy array'
The original cube (m x n x p).
path: `string`
The path where to put the plot.
x: `int`
The x coordinate.
y: `int`
The y coordinate.
suffix: `string [default None]`
Add a suffix to the file name.
"""
import matplotlib.pyplot as plt
plt.ioff()
plt.plot(M[x,y])
plt.plot(self.denoised[x,y], color='r')
plt.xlabel('Wavelength')
plt.ylabel('Brightness')
if suffix == None:
fout = osp.join(path, 'SavitzkyGolay_x{0}_y{1}.png'.format(x,y))
else:
fout = osp.join(path, 'SavitzkyGolay_x{0}_y{1}_{2}.png'.format(x,y,suffix))
plt.savefig(fout)
plt.close()
def plot_bands_sample(self, path, band_no, suffix=None):
"""
Plot a filtered band.
Parameters:
path: `string`
The path where to put the plot.
band_no: `int or string`
The band index.
If band_no == 'all', plot all the bands.
suffix: `string [default None]`
Add a suffix to the file name.
"""
import matplotlib.pyplot as plt
plt.ioff()
if band_no == 'all':
for i in range(self.dbands.shape[2]):
plt.imshow(self.dbands[:,:,i], interpolation='none')
if suffix == None:
fout = osp.join(path, 'SavitzkyGolay_band_{0}.png'.format(i))
else:
fout = osp.join(path, 'SavitzkyGolay_band_{0}_{1}.png'.format(i, suffix))
plt.savefig(fout)
plt.close()
else:
plt.imshow(self.dbands[:,:,band_no], interpolation='none')
if suffix == None:
fout = osp.join(path, 'SavitzkyGolay_band_{0}.png'.format(band_no))
else:
fout = osp.join(path, 'SavitzkyGolay_band_{0}_{1}.png'.format(band_no, suffix))
plt.savefig(fout)
plt.close()
def display_spectrum_sample(self, M, x, y, suffix=None):
"""
Display a spectrum sample with the original and the
filtered signal.
Parameters:
M: 'numpy array'
The original cube (m x n x p).
x: `int`
The x coordinate.
y: `int`
The y coordinate.
suffix: `string [default None]`
Add a suffix to the title.
"""
import matplotlib.pyplot as plt
plt.plot(M[x,y])
plt.plot(self.denoised[x,y], color='r')
plt.xlabel('Wavelength')
plt.ylabel('Brightness')
if suffix == None:
plt.title('SG spectrum sample, x={0}, y={1}'.format(x,y))
else:
plt.title('SG spectrum sample, x={0}, y={1} - {2}'.format(x,y,suffix))
plt.show()
plt.close()
def display_bands_sample(self, band_no, suffix=None):
"""
Display a filtered band.
Parameters:
band_no: `int or string`
The band index.
If band_no == 'all', plot all the bands.
suffix: `string [default None]`
Add a suffix to the title.
"""
import matplotlib.pyplot as plt
if band_no == 'all':
for i in range(self.dbands.shape[2]):
plt.imshow(self.dbands[:,:,i], interpolation='none')
if suffix == None:
plt.title('SG band {0}'.format(i))
else:
plt.title('SG band {0} - {1}'.format(i, suffix))
plt.show()
plt.close()
else:
plt.imshow(self.dbands[:,:,band_no], interpolation='none')
if suffix == None:
plt.title('SG band {0}'.format(band_no))
else:
plt.title('SG band {0} - {1}'.format(band_no, suffix))
plt.show()
plt.close()
class Whiten(object):
"""Whiten the cube."""
def __init__(self):
self.dM = None
@ApplyInputValidation('Whiten')
def apply(self, M):
"""
Whitens a HSI cube. Use the noise covariance matrix to decorrelate
and rescale the noise in the data (noise whitening).
Results in transformed data in which the noise has unit variance
and no band-to-band correlations.
Parameters:
M: `numpy array`
A HSI cube (m x n x p).
Returns: `numpy array`
A whitened HSI cube (m x n x p).
"""
h, w, numBands = M.shape
M = np.reshape(M, (w*h, numBands))
dM = dnoise.whiten(M)
self.dM = np.reshape(dM, (h, w, numBands))
return self.dM
def get(self):
"""
Returns: `numpy array`
The whitened HSI cube (m x n x p).
"""
return self.dM
class MNF(object):
"""Transform a HSI cube."""
def __init__(self):
self.mnf = None
self.transform = None
self.wdata = None # temp
@ApplyInputValidation('MNF')
def apply(self, M):
"""
A linear transformation that consists of a noise whitening step
and one PCA rotation.
This process is designed to
* determine the inherent dimensionality of image data,
* segregate noise in the data,
* allow efficient elimination and/or reduction of noise, and
* reduce the computational requirements for subsequent processing.
Parameters:
M: `numpy array`
A HSI cube (m x n x p).
Returns: `numpy array`
A MNF transformed cube (m x n x p).
References:
C-I Change and Q Du, "Interference and Noise-Adjusted Principal
Components Analysis," IEEE TGRS, Vol 36, No 5, September 1999.
"""
from sklearn.decomposition import PCA
w = Whiten()
wdata = w.apply(M)
self.wdata = wdata #temp
h, w, numBands = wdata.shape
X = np.reshape(wdata, (w*h, numBands))
self.transform = PCA()
mnf = self.transform.fit_transform(X)
self.mnf = np.reshape(mnf, (h, w, numBands))
return self.mnf
@XInputValidation('MNF')
def inverse_transform(self, X):
"""
Inverse the PCA rotation step. The cube stay
whitened. Usefull if you want to denoise noisy
bands before the rotation.
X: `numpy array`
A transformed (MNF) cube (m x n x p).
Return: `numpy array`
A inverted cube (m x n x p).
"""
h, w, numBands = X.shape
X = np.reshape(X, (w*h, numBands))
M = self.transform.inverse_transform(X)
M = np.reshape(M, (h, w, numBands))
return M
def get_components(self, n):
"""
Return: `numpy array`
Return the first n bands (maximum variance bands).
"""
return self.mnf[:,:,:n]
def plot_components(self, path, n_first=None, colorMap='jet', suffix=None):
"""
Plot some bands.
Parameters:
path: `string`
The path where to put the plot.
n_first: `int [default None]`
Print the first n components.
colorMap: `string [default jet]`
A matplotlib color map.
suffix: `string [default None]`
Suffix to add to the title.
"""
import matplotlib.pyplot as plt
if n_first != None:
n = min(n_first, self.mnf.shape[2])
else:
n = self.mnf.shape[2]
plt.ioff()
for i in range(n):
plt.imshow(self.mnf[:,:,i], interpolation='none', cmap=colorMap)
if suffix == None:
fout = osp.join(path, 'MNF_bandno_{0}.png'.format(i+1))
else:
fout = osp.join(path, 'MNF_bandno_{0}_{1}.png'.format(i+1, suffix))
plt.savefig(fout)
plt.clf()
plt.close()
def display_components(self, n_first=None, colorMap='jet', suffix=None):
"""
Display some bands.
Parameters:
n_first: `int [default None]`
Display the first n components.
colorMap: `string [default jet]`
A matplotlib color map.
suffix: `string [default None]`
Suffix to add to the title.
"""
import matplotlib.pyplot as plt
if n_first != None:
n = min(n_first, self.mnf.shape[2])
else:
n = self.mnf.shape[2]
for i in range(n):
plt.imshow(self.mnf[:,:,i], interpolation='none', cmap=colorMap)
if suffix == None:
plt.title('MNF bandno {0}'.format(i+1))
else:
plt.title('MNF bandno {0} - {1}.png'.format(i+1, suffix))
plt.show()
plt.clf()
plt.close()
|
<gh_stars>10-100
# Copyright (c) 2018 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
GroupAction,
IncludeLaunchDescription,
SetEnvironmentVariable,
)
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, PythonExpression
from launch_ros.actions import PushRosNamespace
def generate_launch_description():
# Get the launch directory
sm_dance_bot_warehouse_2_dir = get_package_share_directory("sm_dance_bot_warehouse_2")
launch_dir = os.path.join(sm_dance_bot_warehouse_2_dir, "launch")
# Create the launch configuration variables
namespace = LaunchConfiguration("namespace")
use_namespace = LaunchConfiguration("use_namespace")
slam = LaunchConfiguration("slam")
map_yaml_file = LaunchConfiguration("map")
use_sim_time = LaunchConfiguration("use_sim_time")
params_file = LaunchConfiguration("params_file")
default_nav_to_pose_bt_xml = LaunchConfiguration("default_nav_to_pose_bt_xml")
autostart = LaunchConfiguration("autostart")
stdout_linebuf_envvar = SetEnvironmentVariable("RCUTILS_LOGGING_BUFFERED_STREAM", "1")
declare_namespace_cmd = DeclareLaunchArgument(
"namespace", default_value="", description="Top-level namespace"
)
declare_use_namespace_cmd = DeclareLaunchArgument(
"use_namespace",
default_value="false",
description="Whether to apply a namespace to the navigation stack",
)
declare_slam_cmd = DeclareLaunchArgument(
"slam", default_value="False", description="Whether run a SLAM"
)
declare_map_yaml_cmd = DeclareLaunchArgument(
"map", description="Full path to map yaml file to load"
)
declare_use_sim_time_cmd = DeclareLaunchArgument(
"use_sim_time", default_value="false", description="Use simulation (Gazebo) clock if true"
)
declare_params_file_cmd = DeclareLaunchArgument(
"params_file",
default_value=os.path.join(
sm_dance_bot_warehouse_2_dir, "params", "nav2z_client", "nav2_params.yaml"
),
description="Full path to the ROS2 parameters file to use for all launched nodes",
)
declare_bt_xml_cmd = DeclareLaunchArgument(
"default_nav_to_pose_bt_xml",
default_value=os.path.join(
sm_dance_bot_warehouse_2_dir, "params", "nav2z_client", "navigation_tree.xml"
),
description="Full path to the behavior tree xml file to use",
)
declare_autostart_cmd = DeclareLaunchArgument(
"autostart", default_value="true", description="Automatically startup the nav2 stack"
)
# Specify the actions
bringup_cmd_group = GroupAction(
[
PushRosNamespace(condition=IfCondition(use_namespace), namespace=namespace),
IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(launch_dir, "slam_launch.py")),
condition=IfCondition(slam),
launch_arguments={
"namespace": namespace,
"use_sim_time": use_sim_time,
"autostart": autostart,
"params_file": params_file,
}.items(),
),
IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(launch_dir, "localization_launch.py")),
condition=IfCondition(PythonExpression(["not ", slam])),
launch_arguments={
"namespace": namespace,
"map": map_yaml_file,
"use_sim_time": use_sim_time,
"autostart": autostart,
"params_file": params_file,
"use_lifecycle_mgr": "false",
}.items(),
),
IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(launch_dir, "navigation_launch.py")),
launch_arguments={
"namespace": namespace,
"use_sim_time": use_sim_time,
"autostart": autostart,
"params_file": params_file,
"default_nav_to_pose_bt_xml": default_nav_to_pose_bt_xml,
"use_lifecycle_mgr": "false",
"map_subscribe_transient_local": "true",
}.items(),
),
]
)
# Create the launch description and populate
ld = LaunchDescription()
# Set environment variables
ld.add_action(stdout_linebuf_envvar)
# Declare the launch options
ld.add_action(declare_namespace_cmd)
ld.add_action(declare_use_namespace_cmd)
ld.add_action(declare_slam_cmd)
ld.add_action(declare_map_yaml_cmd)
ld.add_action(declare_use_sim_time_cmd)
ld.add_action(declare_params_file_cmd)
ld.add_action(declare_autostart_cmd)
ld.add_action(declare_bt_xml_cmd)
# Add the actions to launch all of the navigation nodes
ld.add_action(bringup_cmd_group)
return ld
|
<filename>calx/diffractometer/diffractometer_swissfel.py
import numbers
import numpy as np
from numpy.linalg import norm
import warnings
import re
from xrayutilities import Experiment,QConversion
# package internal imports
from xrayutilities import math
# from xrayutilities import materials
# from xrayutilities import utilities
# from xrayutilities import cxrayutilities
from xrayutilities import config
from xrayutilities.exception import InputError
math.Transform
# python 2to3 compatibility
# try:
# basestring
# except NameError:
# basestring = str
# regular expression to check goniometer circle syntax
# directionSyntax = re.compile("[xyz][+-]")
# circleSyntaxDetector = re.compile("([xyz][+-])|(t[xyz])")
# circleSyntaxSample = re.compile("[xyzk][+-]")
class GID(Experiment):
"""
class describing grazing incidence x-ray diffraction experiments
the class helps with calculating the angles of Bragg reflections
as well as it helps with analyzing measured data
the class describes a four circle (alpha_i,azimuth,twotheta,beta)
goniometer to help with GID experiments at the ROTATING ANODE.
3D data can be treated with the use of linear and area detectors.
see help self.Ang2Q
Using this class the default sample surface orientation is determined by
the inner most sample rotation (which is usually the azimuth motor).
"""
def __init__(self, idir=[1,0,0], ndir=[0,0,1], **keyargs):
"""
initialization routine for a GID Experiment class fitting a Bernina
diffractometer a swissfel.
The normal convention is kept, which uses the sample z axis as the innermost rotation.
idir defines the inplane reference direction (idir points into the PB
direction at zero angles)
ndir defines the surface normal of your sample (ndir points along the
innermost sample rotation axis)
Parameters
----------
same as for the Experiment base class
"""
if 'sampleor' not in keyargs:
keyargs['sampleor'] = 'sam'
if "qconv" not in keyargs:
# 2S+2D goniometer
keyargs['qconv'] = QConversion(['z-', 'x+'], ['x+', 'z-'],
[0, 1, 0])
Experiment.__init__(self, idir, ndir, **keyargs)
def Q2Ang(self, Q, alpha_i=0, trans=True, deg=True, **kwargs):
"""
calculate the GID angles needed in the experiment
the inplane reference direction defines the direction were
the reference direction is parallel to the primary beam
(i.e. lattice planes perpendicular to the beam)
Parameters
----------
Q: a list or numpy array of shape (3) with
q-space vector components
optional keyword arguments:
trans: True/False apply coordinate transformation on Q
deg: True/Flase (default True) determines if the
angles are returned in radians or degrees
Returns
-------
a numpy array of shape (4) with the four GID scattering angles which
are [alpha_i, azimuth, twotheta, beta]
alpha_i: incidence angle to surface (at the moment always 0)
azimuth: sample rotation with respect to the inplane reference
direction
twotheta: scattering angle
beta: exit angle from surface (at the moment always 0)
"""
for k in kwargs.keys():
if k not in ['trans', 'deg']:
raise Exception("unknown keyword argument given: allowed are "
"'trans': coordinate transformation flag, "
"'deg': degree-flag")
if isinstance(Q, list):
q = np.array(Q, dtype=np.double)
elif isinstance(Q, np.ndarray):
q = Q
else:
raise TypeError("Q vector must be a list or numpy array")
if trans:
q = self.Transform(q)
if config.VERBOSITY >= config.INFO_ALL:
print("XU.GID.Q2Ang: q = %s" % repr(q))
if deg:
alpha_i = np.radians(alpha_i)
# print('converted alpha_i')
# set parameters for the calculation
z = self.Transform(self.ndir) # z
y = self.Transform(self.idir) # y
x = self.Transform(self.scatplane) # x
# check if reflection is inplane
# if np.abs(math.VecDot(q, z)) >= 0.001:
# raise InputError("Reflection not reachable in GID geometry (Q: %s)"
# % str(q))
#calculate perpendicular (z) and parallel components of Q
qz = math.VecDot(z, q)
qx = math.VecDot(x, q)
qy = math.VecDot(y, q)
qxy = np.sqrt(qx**2+qy**2)
# calculate angle to inplane reference direction,
# that is perpendicular to incoming beam projection on plane
aref = np.arctan2(qx, qy)
print(f'aref is {np.degrees(aref)} degrees')
# calculate scattering angle
qa = math.VecNorm(q)
tth = 2. * np.arcsin(qa / 2. / self.k0)
# calculate "phi" rotation that brings into ewald sphere
a_ewald = np.arcsin(
qa**2/self.k0/2/np.cos(alpha_i)/qxy + qz/qxy*np.tan(alpha_i)
)
# print(f'a_ewald is {np.degrees(a_ewald)} degrees')
# print(f'alpha_i is {np.degrees(alpha_i)} degrees')
azimuth = np.pi / 2 + aref + a_ewald
# print(f'az is {np.degrees(azimuth)} degrees')
q_lab = self.Ang2Q.transformSample2Lab(q,np.degrees(alpha_i),np.degrees(azimuth))
k_out = q_lab + self.k0*self.idir
# print('k out comparison',norm(self.k0*self.idir+q_lab),self.k0)
e_out = q_lab/self.k0 + self.idir
# print(f'ql is {q_lab} q is {q}')
assert len(self.Ang2Q.detectorAxis) == 2, "we need 2 detector axes for this"
ax0 = math.getVector(self.Ang2Q.detectorAxis[0])
ax1 = math.getVector(self.Ang2Q.detectorAxis[1])
a1 = np.pi/2 - np.arccos(math.VecDot(ax0,e_out))
# print(ax0,ax1,e_out)
ax1r = math.VecCross(e_out,ax0)
e_out0 = math.rotarb(e_out,ax1r,-a1,deg=False)
a0 = - np.arccos(math.VecDot(e_out0,self.idir))
if deg:
ang = [ np.degrees(azimuth), np.degrees(a0), np.degrees(a1)]
else:
ang = [azimuth, a0, a1]
if config.VERBOSITY >= config.INFO_ALL:
print("XU.GID.Q2Ang: [ai,azimuth,tth,beta] = %s \n difference to "
"inplane reference which is %5.2f" % (str(ang), aref))
return ang
def Ang2Q(self, ai, phi, tt, beta, **kwargs):
"""
angular to momentum space conversion for a point detector. Also see
help GID.Ang2Q for procedures which treat line and area detectors
Parameters
----------
ai,phi,tt,beta: sample and detector angles as numpy array, lists or
Scalars must be given. All arguments must have the
same shape or length. However, if one angle is always
the same its enough to give one scalar value.
**kwargs: optional keyword arguments
delta: giving delta angles to correct the given ones for
misalignment delta must be an numpy array or list of
length 4. Used angles are than ai,phi,tt,beta - delta
UB: matrix for conversion from (hkl) coordinates to Q of sample
used to determine not Q but (hkl)
(default: identity matrix)
wl: x-ray wavelength in angstroem (default: self._wl)
deg: flag to tell if angles are passed as degree (default: True)
Returns
-------
reciprocal space positions as numpy.ndarray with shape ( * , 3 )
where * corresponds to the number of points given in the input
"""
# dummy function to have some documentation string available
# the real function is generated dynamically in the __init__ routine
pass |
import httplib
import urllib
import random
import time
from PIL import Image
import os
from xml.etree import ElementTree
import logging
import StringIO
all_extras = ("description,license,date_upload,date_taken,owner_name,"
"icon_server,original_format,last_update,geo,tags,machine_tags,o_dims,"
"views,media,path_alias,url_sq,url_t,url_s,url_m,url_o")
keys = []
log = logging.getLogger("vision.flickr")
class Photo(object):
"""
A photo structure that represents a photo on Flickr.
A photo described here does not neccessarily exist on local storage. It can
be downloaded with the download() method, which returns an PIL image.
"""
def __init__(self, localpath, remoteurl, size, format, flickrid):
self.localpath = localpath
self.remoteurl = remoteurl
self.width, self.height = size
self.format = format
self.flickrid = int(flickrid)
def download(self):
"""
Downloads the Flickr image and returns the PIL image.
This does not write to local storage. To do so, use the save() method
on the returned image.
"""
data = urllib.urlopen(self.remoteurl).read()
s = StringIO.StringIO(data)
return Image.open(s)
def __hash__(self):
return self.flickrid
def __eq__(self, other):
return self.flickrid == other.flickrid
@classmethod
def fromapi(cls, attrib):
"""
Constructs a photo object from the Flickr API XML specification.
"""
if "url_o" in attrib:
url = attrib["url_o"]
size = attrib["width_o"], attrib["height_o"]
format = "original"
elif "url_l" in attrib:
url = attrib["url_l"]
size = attrib["width_l"], attrib["height_l"]
format = "large"
elif "url_m" in attrib:
url = attrib["url_m"]
size = attrib["width_m"], attrib["height_m"]
format = "medium"
elif "url_s" in attrib:
url = attrib["url_s"]
size = attrib["width_s"], attrib["height_s"]
format = "small"
else:
raise RuntimeError("Photo does not have URL")
return Photo(None, url, size, format, attrib["id"])
def request(method, parameters = {}):
"""
Generic request method to the Flickr API.
"""
if len(keys) == 0:
raise RuntimeError("No Flickr API keys defined")
apikey = random.choice(keys)
parameters = urllib.urlencode(parameters)
url = "/services/rest?method={0}&format=rest&api_key={1}&{2}"
url = url.format(method, apikey, parameters)
conn = httplib.HTTPConnection("api.flickr.com")
conn.request("GET", url)
response = conn.getresponse().read()
response = ElementTree.fromstring(response)
conn.close()
return response
def search(tags, perpage = 100):
"""
Builds an iterator for all the photos returned by a Flickr search. This
function automatically jumps to the next page when a page is exhausted.
"""
page, pages = 1, 2
while page < pages:
photos = request("flickr.photos.search", {
"tags": tags,
"page": page,
"per_page": perpage,
"extras": all_extras})
photos = photos.find("photos")
pages = int(photos.get("pages"))
page += 1
for photo in photos:
yield Photo.fromapi(photo.attrib)
def recent(perpage = 500):
"""
Builds an iterator for the most recent Flickr photos.
"""
photos = request("flickr.photos.getRecent", {
"per_page": perpage,
"extras": all_extras})
for photo in photos.getiterator("photo"):
yield Photo.fromapi(photo.attrib)
def pascal(tags, range = (2003, 2010)):
"""
Builds an iterator that queries images identical to the Pascal challenge.
"""
if isinstance(tags, str):
tags = tags.split(" ")
perpage = 10
while True:
start = int(time.mktime([range[0],1,1,0,0,0,0,0,-1]))
stop = int(time.mktime([range[1],12,31,23,59,59,0,0,-1]))
rtime = (time.localtime(random.randint(start, stop))[0:3] +
(0, 0, 0, 0, 0, -1))
rtime = time.mktime(rtime)
stm, etm = int(rtime), int(rtime + 86400)
tag = random.choice(tags)
r = request("flickr.photos.search", {
"text": tag,
"min_upload_date": stm,
"max_upload_date": etm,
"per_page": perpage,
"page": 1})
totpages = int(r.find("photos").get("pages"))
if totpages == 0:
continue
page = random.randint(1, totpages)
r = request("flickr.photos.search", {
"text": tag,
"min_upload_date": stm,
"max_upload_date": etm,
"per_page": perpage,
"page": page,
"extras": all_extras})
photos = [x.attrib for x in r.find("photos")]
if len(photos) > 0:
yield Photo.fromapi(photos[random.randint(0, len(photos) - 1)])
def filtersizes(iterator, size = "medium"):
"""
Filters sizes from the iterator and only returns images that are the
specified minimum size.
By default, it filters out all the small images. To download only
originals, pass "original". Valid sizes are:
- small
- medium
- large
- original
"""
sizes = {"small": 0, "medium": 1, "large": 2, "original": 3}
required = sizes[size]
for x in iterator:
if x.format in sizes and sizes[x.format] >= required:
yield x
def delay(iterator, wait = 1, every = 1):
"""
Delays between every n images for the specified time. Useful so that Flickr
doesn't disable your API key for excessive usage.
"""
for i, photo in enumerate(iterator):
if i > 0 and i % every == 0:
time.sleep(wait)
yield photo
def scrape(iterator, location, limit):
"""
Downloads up to the limit of all photos in an iterator.
"""
for photo in iterator:
filepath = "{0}/{1}/{2}.jpg".format(location,
photo.flickrid % 100,
photo.flickrid)
if os.path.exists(filepath):
log.info("Skipping duplicate {0}".format(photo.flickrid))
continue
try:
log.info("Downloading {0} ({1})".format(photo.flickrid,
photo.format))
image = photo.download()
try:
image.save(filepath)
except IOError:
os.makedirs(os.path.dirname(filepath))
image.save(filepath)
except KeyboardInterrupt:
raise
except:
pass
limit -= 1
if limit == 0:
break
|
<filename>morphling/copy.py
import re
import csv
class Copy:
def __init__(self, reader, writer):
self.reader = reader
self.writer = writer
self.data = list()
def __construct(self, data):
field = 0
message_tmps = list()
tmp_list = list()
check_datetime = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
check_datetime_message = '\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}[\]\n\w \d)]+'
index_check = [
'[\w\d_-]+',
'\w+',
check_datetime,
'\d+',
'\w+',
'[\d\w]+',
'.*\n{0,1}',
]
for string in data:
if field == 6 and string.find('\n') != -1:
words = string.split('\n')
tmp_list.append(words[0])
self.data.append(tmp_list)
tmp_list = [words[1]]
field = 1
elif field != 2 and re.search(index_check[field], string):
tmp_list.append(string)
field += 1
elif field == 2 and re.search(index_check[field], string) and not re.search(check_datetime_message, string):
tmp_list.append(''.join(message_tmps))
message_tmps = list()
tmp_list.append(string)
field += 1
elif field == 2:
message_tmps.append(string)
if field == 7:
self.data.append(tmp_list)
tmp_list = list()
field = 0
return tmp_list
def construct_csv(self, file_path):
reader = self.reader.read_line(file_path)
string = reader.readline()
new_list = re.split(',', string)
header = new_list[0:7]
tmp = new_list[7]
last_header, first_field = tmp.split('\n')
header.append(last_header)
self.data.append(header)
del new_list[0:8]
new_list.insert(0, first_field)
queue_list = list()
for string in reader:
new_list = re.split(',', string)
self._transform(new_list)
queue_list.extend(new_list)
if self._is_complete_row(queue_list):
self.__construct(queue_list)
queue_list = list()
reader.close()
def restruct_csv(self, source_path, destination_path):
with open(source_path, 'r') as reader, open(destination_path, 'w') as file_writer:
writer = csv.writer(file_writer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
string = reader.readline()
new_list = re.split(',', string)
header = new_list[0:7]
tmp = new_list[7]
last_header, first_field = tmp.split('\n')
header.append(last_header)
writer.writerow(header)
queue_list = list()
#To support case owner name is different line
post_queue = list()
complete_list = False
for line in reader:
#To support case owner name is different line
if (3 > len(queue_list) > 0) and (re.search('\n', queue_list[0]) or re.search('\n', queue_list[1])):
id_match = re.search('[\w\d_-]+', line)
if id_match:
post_queue[-1][-1] = post_queue[-1][-1] + '\n' + ','.join(queue_list).rstrip()
writer.writerow(post_queue[0])
complete_list = False
post_queue = list()
queue_list = list()
line_list = re.split(',', line)
self._transform(line_list)
queue_list.extend(line_list)
if self._is_complete_row(queue_list):
self.__construct(queue_list)
queue_list = list()
complete_list = True
if len(post_queue):
writer.writerow(post_queue[0])
post_queue = list()
queue_list = list()
if len(self.data):
post_queue.extend(self.data)
self.data = list()
if len(post_queue):
writer.writerow(post_queue[0])
post_queue = list()
queue_list = list()
def _is_complete_row(self, new_list):
"""Check whether the list including a competed row or not (already have all column)"""
field = 0
index_check = ['\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', '\d+', '\w+', '[\d\w]+', '.*\n{0,1}']
if len(new_list) < 8:
return False
for string in new_list:
match = re.search(index_check[field], string)
message_match = re.search('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}[\]\n\w \d)]+', string)
if field == 0 and match and not message_match:
field += 1
elif field != 0 and match:
field += 1
if field == 5:
break
return True if field == 5 else False
def _transform(self, new_list):
"""Concate string between line to create complete list (have all row)"""
index = None
for string in new_list:
datetime_match = re.search('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', string)
message_match = re.search('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}[\]\n\w \d)]+', string)
if datetime_match and not message_match:
index = new_list.index(string)
break
if index:
if index == 2:
tmps = new_list[:index]
del new_list[:index]
new_list.insert(0, ','.join(tmps))
elif len(new_list) > 3:
tmps = new_list[2:]
del new_list[2:]
new_list.append(','.join(tmps))
def construct(self, file_path):
"""Crate nested list to represent data"""
reader = self.reader.read_line(file_path)
queue_list = list()
for string in reader:
new_list = re.split(',', string)
#To support case owner name is different line
if (3 > len(queue_list) > 0) and (re.search('\n', queue_list[0]) or re.search('\n', queue_list[1])):
id_match = re.search('[\w\d_-]+', string)
if id_match:
self.data[-1][-1] = self.data[-1][-1] + '\n' + ','.join(queue_list)
queue_list = list()
self._transform(new_list)
queue_list.extend(new_list)
if self._is_complete_row(queue_list):
self.__construct(queue_list)
queue_list = list()
reader.close()
def to_csv(self, file_path):
self.writer.to_csv(self.data, file_path)
|
<reponame>xboix/FakeNews-Code
#! /usr/bin/env python
import tensorflow as tf
import numpy as np
np.set_printoptions(threshold=np.nan)
import os
import sys
import csv
import interpret
import data_helpers
from sklearn import metrics
from tensorflow.contrib import learn
#import yaml
import pickle
maxpool_x = 2;
maxpool_y = 128;
def matrix_multiply(a, b):
a=np.array(a)
b=np.array(b)
new_array = np.zeros((a.shape[0], b.shape[1]))
for row in range(a.shape[0]):
for col in range(b.shape[1]):
weights_x_activation = np.multiply(a[row],b[:,col])
element = sum(weights_x_activation)
new_array[row][col]=element
return new_array
def get_wi_ai(a,b):
a=np.array(a)
b=np.array(b)
new_array = np.zeros((a.shape[0], b.shape[1]))
batch_relevant=[]
for row in range(a.shape[0]):
relevant = np.zeros((maxpool_x, maxpool_y))
for col in range(b.shape[1]):
weights_x_activation = np.multiply(a[row],b[:,col])
relevant[col]=weights_x_activation
batch_relevant.append(relevant)
return np.array(batch_relevant)
def softmax(x):
"""Compute softmax values for each sets of scores in x"""
if x.ndim == 1:
x = x.reshape((1, -1))
max_x = np.max(x, axis=1).reshape((-1, 1))
exp_x = np.exp(x - max_x)
return exp_x / np.sum(exp_x, axis=1).reshape((-1, 1))
cfg = {'word_embeddings': {'default': 'word2vec', 'word2vec':
{'path': '/Users/sofia/Documents/src/fakenews1/GoogleNews-vectors-negative300.bin',
'dimension': 300, 'binary': True}, 'glove': {'path': '../../data/glove.6B.100d.txt', 'dimension': 100, 'length': 400000}},
'datasets': {'default': '20newsgroup', 'mrpolarity': {'positive_data_file': {'path': 'data/rt-polaritydata/rt-polarity.pos',
'info': 'Data source for the positive data'},
'negative_data_file': {'path': 'data/rt-polaritydata/rt-polarity.neg',
'info': 'Data source for the negative data'}},
'20newsgroup': {'categories': ['alt.atheism', 'comp.graphics', 'sci.med', 'soc.religion.christian'], 'shuffle': True, 'random_state': 42},
'20newsgroup': {'categories': ['alt.atheism', 'comp.graphics', 'sci.med', 'soc.religion.christian'], 'shuffle': True, 'random_state': 42},
'localdata': {'container_path': '../../data/input/SentenceCorpus', 'categories': None, 'shuffle': True, 'random_state': 42}}}
# Parameters
# ==================================================
# Data Parameters
# Eval Parameters
tf.flags.DEFINE_string("experiment", "all", "All subjects (all), Trump or Email.")
tf.flags.DEFINE_integer("batch_size", 256, "Batch Size (default: 64)")
# Misc Parameters
tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement")
tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices")
tf.flags.DEFINE_integer("y_test_special", 1, "The y value for the specific x raw if there is one.")
FLAGS = tf.flags.FLAGS
FLAGS(sys.argv)
print("\nParameters:")
for attr, value in sorted(FLAGS.__flags.items()):
print("{}={}".format(attr.upper(), value))
print("")
datasets = None
# Load data.
checkpoint_dir = os.getcwd() + '/runs/' + FLAGS.experiment + '/checkpoints/'
positive_data_file = os.getcwd() + '/data/clean/real.pkl'
negative_data_file = os.getcwd() + '/data/clean/fake.pkl'
dataset_name = cfg["datasets"]["default"]
x_origin, y_origin = data_helpers.load_data_and_labels(positive_data_file, negative_data_file)
#x_origin = x_origin[:1000]
#y_origin = y_origin[:1000]
y_test = np.argmax(y_origin, axis=1)
print("Total number of test examples: {}".format(len(y_test)))
import re
import string
def clean(text):
text = re.sub(r'\([^)]*\)', '', text)
text = ' '.join([s for s in text.split() if not any([c.isdigit() for c in s])])
text = ''.join(ch for ch in text if ch not in string.punctuation)
text = ' '.join([s for s in text.split() if not any([not c.isalpha() for c in s])])
text = re.sub(' +', ' ', text)
text = text.lower()
return text
x_raw = [" ".join(clean(x).split(" ")[:1000]) for x in x_origin]
# Map data into vocabulary
vocab_path = os.path.join(checkpoint_dir, "..", "vocab")
print(vocab_path)
vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)
x_test = np.array(list(vocab_processor.transform(x_raw)))
if FLAGS.experiment == 'all':
with open(os.getcwd() + '/data/clean/shuffle.pkl', 'rb') as fp:
shuffle_indices = pickle.load(fp)
x_test = x_test[shuffle_indices]
y_test = y_test[shuffle_indices]
#4000 testing articles
x_test = x_test[-4000:]
y_test = y_test[-4000:]
x_raw = np.array(x_raw)
x_raw = x_raw[shuffle_indices]
#4000 testing articles
x_raw = x_raw[-4000:]
elif FLAGS.experiment == 'Trump':
idx_trump = [idx for idx, article in enumerate(x_origin) if ((' trump ' in article) or (' Trump ' in article) or (' TRUMP ' in article))]
x_test = x_test[idx_trump]
y_test = y_test[idx_trump]
x_raw = np.array(x_raw)
x_raw = x_raw[idx_trump]
print("\nEvaluating...\n")
# Evaluation
# ==================================================
checkpoint_file = tf.train.latest_checkpoint(os.getcwd() + '/runs/' + FLAGS.experiment + '/checkpoints/')
print("checkpoint_file", checkpoint_file)
graph = tf.Graph()
print("0")
with tf.device('/gpu:1'):
with graph.as_default():
print("1")
session_conf = tf.ConfigProto(
allow_soft_placement=FLAGS.allow_soft_placement,
log_device_placement=FLAGS.log_device_placement)
print("2")
sess = tf.Session(config=session_conf)
with sess.as_default():
# Load the saved meta graph and restore variables
saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file))
saver.restore(sess, checkpoint_file)
# Get the placeholders from the graph by name
input_x = graph.get_operation_by_name("input_x").outputs[0]
# input_y = graph.get_operation_by_name("input_y").o utputs[0]
dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0]
# Tensors we want to evaluate
scores = graph.get_operation_by_name("output/scores").outputs[0]
# Tensors we want to evaluate
predictions = graph.get_operation_by_name("output/predictions").outputs[0]
conv_mp3 = graph.get_operation_by_name("conv-maxpool-3/conv").outputs[0]
relu_mp3 = graph.get_operation_by_name("conv-maxpool-3/relu").outputs[0]
before_predictions=graph.get_operation_by_name("W").outputs[0]
# Generate batches for one epoch
batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False)
b = graph.get_operation_by_name("output/b").outputs[0]
pool_mp3 = graph.get_operation_by_name("conv-maxpool-3/pool").outputs[0]
conv_lensequence = graph.get_operation_by_name("conv-maxpool-3/conv").outputs[0]
h_drop = graph.get_operation_by_name("dropout/dropout/mul").outputs[0]
embedding_W = graph.get_operation_by_name("embedding/W").outputs[0]
# Collect the predictions here
all_predictions = []
all_probabilities = None
all_x = []
all_w = []
all_wi_ai=np.zeros((0,maxpool_x,maxpool_y))
best_trigrams ={}
n=5
all_top_n_neurons=[]
ind=0
for i,x_test_batch in enumerate(batches):
batch_predictions_scores = sess.run([predictions, scores,conv_mp3,before_predictions,b,pool_mp3,h_drop,conv_lensequence,relu_mp3, embedding_W], {input_x: x_test_batch, dropout_keep_prob: 1.0})
predictions_result = batch_predictions_scores[0]
probabilities = softmax(batch_predictions_scores[1])
weights = batch_predictions_scores[3]
b_result=batch_predictions_scores[4]
pool_post_relu = batch_predictions_scores[5]
x_result = batch_predictions_scores[6]
conv=batch_predictions_scores[7]
relu_result = batch_predictions_scores[8]
all_predictions = np.concatenate([all_predictions, batch_predictions_scores[0]])
xW=np.matmul(x_result,weights)
batch_wi_ai = get_wi_ai(x_result, weights)
all_wi_ai = np.concatenate([all_wi_ai, batch_wi_ai])
embedding_W_result = batch_predictions_scores[9]
best_trigrams, top_n_neurons = interpret.interpret_many(x_raw[i * FLAGS.batch_size:i * FLAGS.batch_size + FLAGS.batch_size + 1], relu_result, pool_post_relu, batch_wi_ai, best_trigrams, n=n)
all_top_n_neurons+=top_n_neurons
if all_probabilities is not None:
all_probabilities = np.concatenate([all_probabilities, probabilities])
else:
all_probabilities = probabilities
# Print accuracy if y_test is defined
if y_test is not None:
correct_predictions = float(sum(all_predictions == y_test))
#for each thing in all predictions, if its equal to y_test you wanna print x_raw
wrong = [(x_raw[i],y_test[i]) for i in range(len(y_test)) if all_predictions[i]!=y_test[i]]
with open(checkpoint_dir+"false_pos.txt", 'w') as false_pos, open(checkpoint_dir+'false_neg.txt', 'w') as false_neg:
for headline, num in wrong:
if num==0:
# should be fake, but was real
false_pos.write(headline+"\n")
else:
#should be real, but was fake
false_neg.write(headline+"\n")
correct = [(x_raw[i],y_test[i]) for i in range(len(y_test)) if all_predictions[i]==y_test[i]]
with open(checkpoint_dir+"true_pos.txt", 'w') as true_pos, open(checkpoint_dir+'true_neg.txt', 'w') as true_neg:
for headline, num in correct:
if num==1:
true_pos.write(headline+"\n")
else:
true_neg.write(headline+"\n")
print("Total number of test examples: {}".format(len(y_test)))
print("Accuracy: {:g}".format(correct_predictions/float(len(y_test))))
print(metrics.confusion_matrix(y_test, all_predictions))
# Save the evaluation to a csv
predictions_human_readable = np.column_stack((np.array(x_raw),
[int(prediction) for prediction in all_predictions],
[ "{}".format(probability) for probability in all_probabilities]))
out_path = os.path.join(checkpoint_dir, "..", "prediction.csv")
print("Saving evaluation to {0}".format(out_path))
with open(out_path, 'w') as f:
csv.writer(f).writerows(predictions_human_readable)
def write_trigram_dict(filename, dictionary):
with open(filename, 'w') as f:
for k in dictionary.keys():
list_o_lists=dictionary[k]
best_trigrams_for_k=[]
for li in list_o_lists:
if len(li[1])>0:
trigram = ' '.join(li[1][0])
else:
trigram = ' '.join(li[1])
best_trigrams_for_k.append(trigram)
f.write("i: "+str(k)+'\n')
f.write("trigrams: ")
for trigram in best_trigrams_for_k:
f.write(trigram+",")
f.write('\n')
def first_element_from_tuples(tuple_list):
return [element[0] for element in tuple_list]
best_n_trigrams = interpret.get_best_n_for_each_neuron(best_trigrams, 15)
import pickle
with open(checkpoint_dir+"best_trigrams_pickle.txt", 'wb') as f2:
pickle.dump(best_trigrams, f2)
write_trigram_dict(checkpoint_dir+'best_trigrams.txt',best_trigrams)
write_trigram_dict(checkpoint_dir+'best_n_trigrams.txt',best_n_trigrams)
best_neurons_fake, best_neurons_real, worst_neurons_fake, worst_neurons_real = interpret.get_n_best_neurons(weights, 30)
best_fake_neurons = {key : best_n_trigrams[key] for key in first_element_from_tuples(best_neurons_fake)}
best_real_neurons = {key: best_n_trigrams[key] for key in first_element_from_tuples(best_neurons_real)}
worst_fake_neurons = {key: best_n_trigrams[key] for key in first_element_from_tuples(worst_neurons_fake)}
worst_real_neurons = {key: best_n_trigrams[key] for key in first_element_from_tuples(worst_neurons_real)}
write_trigram_dict(checkpoint_dir+'best_n_fake_neurons.txt',best_fake_neurons)
write_trigram_dict(checkpoint_dir+'worst_n_fake_neurons.txt', worst_fake_neurons)
write_trigram_dict(checkpoint_dir+'best_n_real_neurons.txt', best_real_neurons)
write_trigram_dict(checkpoint_dir+'worst_n_real_neurons.txt',worst_real_neurons)
with open(checkpoint_dir+"all_top_n_neurons.txt", 'wb') as f:
pickle.dump(all_top_n_neurons, f)
np.save(checkpoint_dir+"weights",weights)
np.save(checkpoint_dir+"all_wi_ai", all_wi_ai)
|
<gh_stars>0
import collections
import json
import re
class Writer:
def __init__(self, conn, debug):
self.conn = conn
self.debug = debug
self.schema_cache = {}
TYPE_MAPS = collections.defaultdict(lambda: lambda x: x)
TYPE_MAPS[list] = TYPE_MAPS[dict] = TYPE_MAPS[tuple] = TYPE_MAPS[collections.OrderedDict] = json.dumps
def set_schema(self, table, *schema):
old_schema = self._get_schema(table)
if not old_schema:
self._change_table(table, "CREATE TABLE %s (%s)" % (table, ",".join(schema)))
else:
for col in set(schema) - set(old_schema):
self._change_table(table, "ALTER TABLE %s ADD COLUMN %s" % (table, col))
def _change_table(self, table, sql):
self.execute(sql)
if table in self.schema_cache:
del self.schema_cache[table]
def _get_schema(self, table):
if table in self.schema_cache:
return self.schema_cache[table]
res = self.execute(
"SELECT sql FROM sqlite_master WHERE tbl_name = ? AND type = 'table'",
[table]
).fetchone()
if not res:
return None
sql = res[0]
typedef = [s.strip() for s in re.split(",", sql[sql.index('(')+1:sql.rindex(')')])]
self.schema_cache[table] = typedef
return typedef
def insert(self, table, **kwargs):
columns = kwargs.keys()
return self.execute(
"INSERT INTO %s (%s) VALUES (%s)" % (
table,
",".join(["\"" + k + "\"" for k in columns]),
",".join(["?" for _ in columns])
),
[self.TYPE_MAPS[type(kwargs[k])](kwargs[k]) for k in columns]
)
def execute(self, *args):
if self.debug:
print(args[0])
return self.conn.execute(*args)
def commit(self, *args):
return self.conn.commit(*args)
class GroupImport:
def __init__(self, key, writer, importer, length):
self.key = key
self.writer = writer
self.importer = importer
self.length = length
self.index = 0
self.writer.set_schema("imports", "key TEXT PRIMARY KEY", "count INTEGER DEFAULT 0")
self.writer.execute("INSERT OR IGNORE INTO imports (path) VALUES (?)", [self.key])
self.imported = self.writer.execute("SELECT count FROM imports WHERE key = ?", [self.key]).fetchone()[0]
def events(self, events):
if self.length > self.imported:
for event in events():
if self.index > self.imported:
self.importer.event(event)
self.index += 1
self.writer.execute("UPDATE imports SET count = ? WHERE key = ?", [self.index, self.key])
self.writer.commit()
return self.index - self.imported
return 0
class StructuredImport:
def __init__(self, writer):
self.writer = writer
DEFAULT_TYPES = {
str: 'TEXT',
int: 'INTEGER',
bool: 'BOOLEAN',
list: 'JSON',
float: 'REAL',
dict: 'JSON',
tuple: 'JSON',
collections.OrderedDict: 'JSON'
}
def event(self, event):
event_type = event['event']
del event['event']
self.writer.set_schema(
"events",
"id INTEGER PRIMARY KEY AUTOINCREMENT",
"timestamp TIMESTAMP",
"key TEXT",
"index_in_path INTEGER",
"type TEXT",
"event JSON",
)
event['event_id'] = self.writer.insert(
"events",
timestamp=event['timestamp'],
type=event_type,
event=event
).lastrowid
del event['timestamp']
custom_fn = getattr(self, event_type)
type_info = custom_fn(None)
type_overrides = constraints = None
if type_info:
type_overrides, constraints = type_info
def lookup_type(key):
if type_overrides and key in type_overrides:
return type_overrides[key]
return self.DEFAULT_TYPES[type(event[key])]
schema = []
if constraints:
schema.extend(constraints)
schema.extend(['"' + k + '"' + lookup_type(k) for k in event.keys()])
self.writer.set_schema(event_type, *schema)
value_overrides = custom_fn(event)
if value_overrides:
event = value_overrides
self.writer.insert(event_type, **event)
def ApproachSettlement(self, approachsettlement):
pass
def BackPack(self, backpack):
pass
def BackpackChange(self, backpackchange):
pass
def BookTaxi(self, booktaxi):
pass
def BuyAmmo(self, buyammo):
pass
def BuyDrones(self, buydrones):
pass
def BuyExplorationData(self, buyexplorationdata):
pass
def BuyTradeData(self, buytradedata):
pass
def CancelTaxi(self, canceltaxi):
pass
def Cargo(self, cargo):
pass
def CargoDepot(self, cargodepot):
pass
def CarrierJump(self, carrierjump):
pass
def CodexEntry(self, codexentry):
pass
def CollectCargo(self, collectcargo):
pass
def CommitCrime(self, commitcrime):
pass
def CommunityGoal(self, communitygoal):
pass
def CommunityGoalDiscard(self, communitygoaldiscard):
pass
def CommunityGoalJoin(self, communitygoaljoin):
pass
def CommunityGoalReward(self, communitygoalreward):
pass
def CrewHire(self, crewhire):
pass
def Died(self, died):
pass
def Docked(self, docked):
pass
def EjectCargo(self, ejectcargo):
pass
def EngineerContribution(self, engineercontribution):
pass
def EngineerCraft(self, engineercraft):
pass
def EngineerProgress(self, engineerprogress):
pass
def FSDJump(self, fsdjump):
pass
def FSDTarget(self, fsdtarget):
pass
def FSSAllBodiesFound(self, fssallbodiesfound):
pass
def FSSDiscoveryScan(self, fssdiscoveryscan):
pass
def FetchRemoteModule(self, fetchremotemodule):
pass
def Friends(self, friends):
pass
def Interdicted(self, interdicted):
pass
def Interdiction(self, interdiction):
pass
def JoinACrew(self, joinacrew):
pass
def LoadGame(self, loadgame):
pass
def Loadout(self, loadout):
pass
def Location(self, location):
pass
def MarketBuy(self, marketbuy):
pass
def MarketSell(self, marketsell):
pass
def MaterialCollected(self, materialcollected):
pass
def MaterialDiscarded(self, materialdiscarded):
pass
def MaterialTrade(self, materialtrade):
pass
def Materials(self, materials):
pass
def MiningRefined(self, miningrefined):
pass
def MissionAbandoned(self, missionabandoned):
pass
def MissionAccepted(self, missionaccepted):
pass
def MissionCompleted(self, missioncompleted):
pass
def MissionFailed(self, missionfailed):
pass
def MissionRedirected(self, missionredirected):
pass
def Missions(self, missions):
pass
def ModuleBuy(self, modulebuy):
pass
def ModuleRetrieve(self, moduleretrieve):
pass
def ModuleSell(self, modulesell):
pass
def ModuleSellRemote(self, modulesellremote):
pass
def MultiSellExplorationData(self, multisellexplorationdata):
pass
def NpcCrewPaidWage(self, npccrewpaidwage):
pass
def PayBounties(self, paybounties):
pass
def PayFines(self, payfines):
pass
def PayLegacyFines(self, paylegacyfines):
pass
def Powerplay(self, powerplay):
pass
def PowerplayCollect(self, powerplaycollect):
pass
def PowerplayDefect(self, powerplaydefect):
pass
def PowerplayDeliver(self, powerplaydeliver):
pass
def PowerplayFastTrack(self, powerplayfasttrack):
pass
def PowerplayJoin(self, powerplayjoin):
pass
def PowerplayLeave(self, powerplayleave):
pass
def PowerplaySalary(self, powerplaysalary):
pass
def Progress(self, progress):
pass
def Promotion(self, promotion):
pass
def QuitACrew(self, quitacrew):
pass
def Rank(self, rank):
pass
def RedeemVoucher(self, redeemvoucher):
pass
def RefuelAll(self, refuelall):
pass
def RefuelPartial(self, refuelpartial):
pass
def Repair(self, repair):
pass
def RepairAll(self, repairall):
pass
def Reputation(self, reputation):
pass
def RestockVehicle(self, restockvehicle):
pass
def Resurrect(self, resurrect):
pass
def SAASignalsFound(self, saascancomplete):
pass
def SAAScanComplete(self, saascancomplete):
pass
def Scan(self, scan):
pass
def ScientificResearch(self, scientificresearch):
pass
def SearchAndRescue(self, searchandrescue):
pass
def SelfDestruct(self, selfdestruct):
pass
def SellDrones(self, selldrones):
pass
def SellExplorationData(self, sellexplorationdata):
pass
def SellShipOnRebuy(self, sellshiponrebuy):
pass
def SetUserShipName(self, setusershipname):
pass
def ShipLocker(self, shiplocker):
pass
def ShipyardBuy(self, shipyardbuy):
pass
def ShipyardSell(self, shipyardsell):
pass
def ShipyardSwap(self, shipyardswap):
pass
def ShipyardTransfer(self, shipyardtransfer):
pass
def StartUp(self, startup):
pass
def Statistics(self, statistics):
pass
def StoredShips(self, storedships):
pass
def Synthesis(self, synthesis):
pass
def TechnologyBroker(self, technologybroker):
pass
def USSDrop(self, ussdrop):
pass
def Undocked(self, undocked):
pass
def AfmuRepairs(self, afmurepairs):
pass
def AppliedToSquadron(self, appliedtosquadron):
pass
def ApproachBody(self, approachbody):
pass
def AsteroidCracked(self, asteroidcracked):
pass
def BookDropship(self, bookdropship):
pass
def Bounty(self, bounty):
pass
def CancelDropship(self, canceldropship):
pass
def CapShipBond(self, capshipbond):
pass
def CargoTransfer(self, cargotransfer):
pass
def CarrierBankTransfer(self, carrierbanktransfer):
pass
def CarrierBuy(self, carrierbuy):
pass
def CarrierCrewServices(self, carriercrewservices):
pass
def CarrierDecommission(self, carrierdecommission):
pass
def CarrierDepositFuel(self, carrierdepositfuel):
pass
def CarrierDockingPermission(self, carrierdockingpermission):
pass
def CarrierFinance(self, carrierfinance):
pass
def CarrierJumpCancelled(self, carrierjumpcancelled):
pass
def CarrierJumpRequest(self, carrierjumprequest):
pass
def CarrierModulePack(self, carriermodulepack):
pass
def CarrierNameChange(self, carriernamechange):
pass
def CarrierStats(self, carrierstats):
pass
def CarrierTradeOrder(self, carriertradeorder):
pass
def ChangeCrewRole(self, changecrewrole):
pass
def ClearSavedGame(self, clearsavedgame):
pass
def CockpitBreached(self, cockpitbreached):
pass
def CollectItems(self, collectitems):
pass
def Commander(self, commander):
pass
def Continued(self, continued):
pass
def Coriolis(self, coriolis):
pass
def CrewAssign(self, crewassign):
pass
def CrewFire(self, crewfire):
pass
def CrewLaunchFighter(self, crewlaunchfighter):
pass
def CrewMemberJoins(self, crewmemberjoins):
pass
def CrewMemberQuits(self, crewmemberquits):
pass
def CrewMemberRoleChange(self, crewmemberrolechange):
pass
def CrimeVictim(self, crimevictim):
pass
def DataScanned(self, datascanned):
pass
def DatalinkScan(self, datalinkscan):
pass
def DatalinkVoucher(self, datalinkvoucher):
pass
def DisbandedSquadron(self, disbandedsquadron):
pass
def DiscoveryScan(self, discoveryscan):
pass
def DockFighter(self, dockfighter):
pass
def DockSRV(self, docksrv):
pass
def DockingCancelled(self, dockingcancelled):
pass
def DockingDenied(self, dockingdenied):
pass
def DockingGranted(self, dockinggranted):
pass
def DockingRequested(self, dockingrequested):
pass
def DockingTimeout(self, dockingtimeout):
pass
def DropItems(self, dropitems):
pass
def EDDCommodityPrices(self, eddcommodityprices):
pass
def EDDItemSet(self, edditemset):
pass
def EDShipyard(self, edshipyard):
pass
def Embark(self, embark):
pass
def EndCrewSession(self, endcrewsession):
pass
def EngineerApply(self, engineerapply):
pass
def EngineerLegacyConvert(self, engineerlegacyconvert):
pass
def EscapeInterdiction(self, escapeinterdiction):
pass
def FSSSignalDiscovered(self, fsssignaldiscovered):
pass
def FactionKillBond(self, factionkillbond):
pass
def FighterDestroyed(self, fighterdestroyed):
pass
def FighterRebuilt(self, fighterrebuilt):
pass
def Fileheader(self, fileheader):
pass
def FuelScoop(self, fuelscoop):
pass
def HeatDamage(self, heatdamage):
pass
def HeatWarning(self, heatwarning):
pass
def HullDamage(self, hulldamage):
pass
def InvitedToSquadron(self, invitedtosquadron):
pass
def JetConeBoost(self, jetconeboost):
pass
def JetConeDamage(self, jetconedamage):
pass
def JoinedSquadron(self, joinedsquadron):
pass
def KickCrewMember(self, kickcrewmember):
pass
def LaunchDrone(self, launchdrone):
pass
def LaunchFighter(self, launchfighter):
pass
def LaunchSRV(self, launchsrv):
pass
def LeaveBody(self, leavebody):
pass
def LeftSquadron(self, leftsquadron):
pass
def Liftoff(self, liftoff):
pass
def Market(self, market):
pass
def MassModuleStore(self, massmodulestore):
pass
def MaterialDiscovered(self, materialdiscovered):
pass
def ModuleArrived(self, modulearrived):
pass
def ModuleInfo(self, moduleinfo):
pass
def ModuleStore(self, modulestore):
pass
def ModuleSwap(self, moduleswap):
pass
def Music(self, music):
pass
def NavBeaconScan(self, navbeaconscan):
pass
def NavRoute(self, navroute):
pass
def NewCommander(self, newcommander):
pass
def NpcCrewRank(self, npccrewrank):
pass
def Outfitting(self, outfitting):
pass
def PVPKill(self, pvpkill):
pass
def Passengers(self, passengers):
pass
def PowerplayVote(self, powerplayvote):
pass
def PowerplayVoucher(self, powerplayvoucher):
pass
def ProspectedAsteroid(self, prospectedasteroid):
pass
def RebootRepair(self, rebootrepair):
pass
def ReceiveText(self, receivetext):
pass
def RepairDrone(self, repairdrone):
pass
def ReservoirReplenished(self, reservoirreplenished):
pass
def SRVDestroyed(self, srvdestroyed):
pass
def Scanned(self, scanned):
pass
def Screenshot(self, screenshot):
pass
def SendText(self, sendtext):
pass
def SharedBookmarkToSquadron(self, sharedbookmarktosquadron):
pass
def ShieldState(self, shieldstate):
pass
def ShipArrived(self, shiparrived):
pass
def ShipTargeted(self, shiptargeted):
pass
def Shipyard(self, shipyard):
pass
def ShipyardNew(self, shipyardnew):
pass
def ShutDown(self, shutdown):
pass
def Shutdown(self, shutdown):
if shutdown:
return {**shutdown, 'event': 'ShutDown'}
def SquadronCreated(self, squadroncreated):
pass
def SquadronStartup(self, squadronstartup):
pass
def StartJump(self, startjump):
pass
def Status(self, status):
pass
def StoredModules(self, storedmodules):
pass
def SupercruiseEntry(self, supercruiseentry):
pass
def SupercruiseExit(self, supercruiseexit):
pass
def SystemsShutdown(self, systemsshutdown):
pass
def Touchdown(self, touchdown):
pass
def UnderAttack(self, underattack):
pass
def VehicleSwitch(self, vehicleswitch):
pass
def WingAdd(self, wingadd):
pass
def WingInvite(self, winginvite):
pass
def WingJoin(self, wingjoin):
pass
def WingLeave(self, wingleave):
pass
def DetailedTrafficReport(self, detailedtrafficreport):
pass
def LocalFactionStatusSummary(self, localfactionstatussummary):
pass
def LocalFactionBounties(self, localfactionbounties):
pass
def LocalPowerBounties(self, localpowerbounties):
pass
def LocalPowerUpdate(self, localpowerupdate):
pass
def LocalTradeReport(self, localtradereport):
pass
def LocalCrimeReport(self, localcrimereport):
pass
def LocalBountyReport(self, localbountyreport):
pass
|
<filename>variation/tokenizers/tokenize_base.py
"""Module for commonly used tokenization methods."""
from typing import Tuple, Optional, Union
from variation.tokenizers.caches import NucleotideCache, AminoAcidCache
import re
class TokenizeBase:
"""Class for Tokenize methods."""
def __init__(self, amino_acid_cache: AminoAcidCache,
nucleotide_cache: NucleotideCache) -> None:
"""Initialize Token Base class.
:param AminoAcidCache amino_acid_cache: Valid amino acid codes
:param NucleotideCache nucleotide_cache: Valid nucleotides
"""
self.nucleotide_cache = nucleotide_cache
self.amino_acid_cache = amino_acid_cache
self.splitter_char_digit = re.compile("([a-zA-Z]+)([0-9]+)")
def get_amino_acid_and_pos(self, part, used_one_letter)\
-> Optional[Tuple[str, int, bool]]:
"""Return amino acid and position.
:param list part: Tokenized input string
:param bool used_one_letter: `True` if used 1 letter AA code.
`False` if used 3 letter AA code.
:return: Three letter AA code, position, and whether or not
one letter AA code was used
"""
try:
char_and_digits = self.splitter_char_digit.match(part).groups()
except AttributeError:
return None
if len(char_and_digits) != 2 or len(part) != \
(len(char_and_digits[0]) + len(char_and_digits[1])):
return None
aa = char_and_digits[0]
if len(aa) == 1:
if not used_one_letter:
used_one_letter = True
tmp_aa = \
self.amino_acid_cache.amino_acid_code_conversion[aa.upper()]
else:
tmp_aa = aa
pos = char_and_digits[1]
if not self.amino_acid_cache.__contains__(tmp_aa) \
or not pos.isdigit():
return None
return aa.upper(), pos, used_one_letter
def get_protein_inserted_sequence(self, parts, used_one_letter)\
-> Optional[str]:
"""Return inserted sequence for protein reference sequence.
:param list parts: Tokenized input string
:param bool used_one_letter: `True` if used 1 letter AA code.
`False` if used 3 letter AA code.
:return: Inserted sequence
"""
# Check inserted sequences
inserted_sequence = ""
if used_one_letter:
for i in range(len(parts[1])):
aa = parts[1][i:i + 1]
if len(aa) != 1:
return None
try:
self.amino_acid_cache.amino_acid_code_conversion[aa.upper()] # noqa: E501
except KeyError:
return None
else:
inserted_sequence += aa.upper()
else:
for i in range(0, len(parts[1]), 3):
aa = parts[1][i:i + 3]
if len(aa) != 3 or not self.amino_acid_cache.__contains__(aa):
if aa != 'ter':
return None
inserted_sequence += \
self.amino_acid_cache.convert_three_to_one(aa)
if inserted_sequence == '':
return None
return inserted_sequence
def get_aa_pos_range(self, parts)\
-> Optional[Tuple[str, str, str, int, bool]]:
"""Get amino acid(s) and positions(s) for protein reference sequence.
:param list parts: Tokenized input string
:return: Beginning AA, End AA, Beginning position, End position,
Whether or not one letter code was used
"""
aa_start = None
aa_end = None
pos_start = None
pos_end = None
used_one_letter = False
if '_' in parts[0] and parts[0].count('_') == 1:
aa_pos_range = parts[0].split('_')
if len(aa_pos_range) != 2 or \
not aa_pos_range[0] or not aa_pos_range[1]:
return None
start_aa_pos = \
self.get_amino_acid_and_pos(
aa_pos_range[0], used_one_letter
)
if start_aa_pos:
used_one_letter = start_aa_pos[2]
end_aa_pos = \
self.get_amino_acid_and_pos(
aa_pos_range[1], used_one_letter
)
if start_aa_pos and end_aa_pos:
aa_start = start_aa_pos[0]
pos_start = start_aa_pos[1]
aa_end = end_aa_pos[0]
pos_end = end_aa_pos[1]
used_one_letter = end_aa_pos[2]
else:
aa_and_pos = \
self.get_amino_acid_and_pos(
parts[0], used_one_letter
)
if aa_and_pos:
aa_start = aa_and_pos[0]
pos_start = aa_and_pos[1]
used_one_letter = aa_and_pos[2]
return aa_start, aa_end, pos_start, pos_end, used_one_letter
def get_positions_deleted(self, parts) -> Optional[Tuple[str, str]]:
"""Return position(s) deleted for transcript and genomic references.
:param list parts: Tokenized input string
:return: Start position deleted and end position deleted
"""
if '_' in parts[0] and parts[0].count('_') == 1:
positions = self.get_valid_digits(parts[0])
if not positions:
return None
start_pos_del, end_pos_del = positions
if start_pos_del > end_pos_del:
return None
else:
start_pos_del = parts[0]
end_pos_del = None
if not start_pos_del.isdigit():
return None
return start_pos_del, end_pos_del
def get_transcript_genomic_inserted_sequence(self, parts) -> \
Optional[Tuple[Union[str, int], Union[str, int]]]:
"""Return inserted sequence for transcript and genomic references.
:param list parts: Tokenized input string
:return: Start inserted sequence and end inserted sequence
"""
# Check inserted sequences
if '_' in parts[1] and parts[1].count('_') == 1:
# Replaced by sequence positions
inserted_sequences = self.get_valid_digits(parts[1])
if not inserted_sequences:
return None
inserted_sequence1, inserted_sequence2 = inserted_sequences
if inserted_sequence1 > inserted_sequence2:
return None
else:
# Replaced by nucleotides
inserted_sequence1 = self.get_sequence(parts[1])
inserted_sequence2 = None
return inserted_sequence1, inserted_sequence2
def get_sequence(self, part) -> Optional[str]:
"""Return validated sequence for transcript and genomic references.
:param str part: Sequence to validate
:return: Sequence of nucleotides
"""
for char in part:
if char.upper() not in self.nucleotide_cache.base_nucleotides:
return None
return part.upper()
def get_valid_digits(self, part) -> Optional[Tuple[str, str]]:
"""Return valid digits after splitting on `_`.
:param str part: Range of digits
:return: Digits represented as strings
"""
digits = part.split('_')
digit1 = digits[0]
digit2 = digits[1]
if not digit1.isdigit() or not digit2.isdigit():
return None
return digit1, digit2
|
<gh_stars>0
import time
# Third-party imports
import numpy
import scipy.stats
import matplotlib
from matplotlib import cm
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as pyplot
import cartopy
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
from cartopy.io import img_tiles
# PyCSEP imports
from csep.utils.constants import SECONDS_PER_DAY, CSEP_MW_BINS
from csep.utils.calc import bin1d_vec
from csep.utils.time_utils import datetime_to_utc_epoch
"""
This module contains plotting routines that generate figures for the stochastic event sets produced from
CSEP2 experiments.
Right now functions dont have consistent signatures. That means that some functions might have more functionality than others
while the routines are being developed.
TODO: Add annotations for other two plots.
TODO: Add ability to plot annotations from multiple catalogs. Esp, for plot_histogram()
IDEA: Same concept mentioned in evaluations might apply here. The plots could be a common class that might provide
more control to the end user.
IDEA: Since plotting functions are usable by these classes only that don't implement iter routines, maybe make them a class
method. like data.plot_thing()
"""
def plot_cumulative_events_versus_time_dev(xdata, ydata, obs_data, plot_args, show=False):
"""
Args:
xdata (ndarray): time bins for plotting shape (N,)
ydata (ndarray or list like): ydata for plotting; shape (N,5) in order 2.5%Per, 25%Per, 50%Per, 75%Per, 97.5%Per
obs_data (ndarry): same shape as xdata
plot_args:
show:
Returns:
"""
figsize = plot_args.get('figsize', None)
sim_label = plot_args.get('sim_label', 'Simulated')
obs_label = plot_args.get('obs_label', 'Observation')
legend_loc = plot_args.get('legend_loc', 'best')
title = plot_args.get('title', 'Cumulative Event Counts')
xlabel = plot_args.get('xlabel', 'Days')
fig, ax = pyplot.subplots(figsize=figsize)
try:
fifth_per = ydata[0,:]
first_quar = ydata[1,:]
med_counts = ydata[2,:]
second_quar = ydata[3,:]
nine_fifth = ydata[4,:]
except:
raise TypeError("ydata must be a [N,5] ndarray.")
# plotting
ax.plot(xdata, obs_data, color='black', label=obs_label)
ax.plot(xdata, med_counts, color='red', label=sim_label)
ax.fill_between(xdata, fifth_per, nine_fifth, color='red', alpha=0.2, label='5%-95%')
ax.fill_between(xdata, first_quar, second_quar, color='red', alpha=0.5, label='25%-75%')
ax.legend(loc=legend_loc)
ax.set_xlabel(xlabel)
ax.set_ylabel('Cumulative event count')
ax.set_title(title)
# pyplot.subplots_adjust(right=0.75)
# annotate the plot with information from data
# ax.annotate(str(observation), xycoords='axes fraction', xy=xycoords, fontsize=10, annotation_clip=False)
# save figure
filename = plot_args.get('filename', None)
if filename is not None:
fig.savefig(filename + '.pdf')
fig.savefig(filename + '.png', dpi=300)
# optionally show figure
if show:
pyplot.show()
return ax
def plot_cumulative_events_versus_time(stochastic_event_sets, observation, show=False, plot_args=None):
"""
Same as below but performs the statistics on numpy arrays without using pandas data frames.
Args:
stochastic_event_sets:
observation:
show:
plot_args:
Returns:
ax: matplotlib.Axes
"""
plot_args = plot_args or {}
print('Plotting cumulative event counts.')
figsize = plot_args.get('figsize', None)
fig, ax = pyplot.subplots(figsize=figsize)
# get global information from stochastic event set
t0 = time.time()
n_cat = len(stochastic_event_sets)
extreme_times = []
for ses in stochastic_event_sets:
start_epoch = datetime_to_utc_epoch(ses.start_time)
end_epoch = datetime_to_utc_epoch(ses.end_time)
if start_epoch == None or end_epoch == None:
continue
extreme_times.append((start_epoch, end_epoch))
# offsets to start at 0 time and converts from millis to hours
time_bins, dt = numpy.linspace(numpy.min(extreme_times), numpy.max(extreme_times), 100, endpoint=True, retstep=True)
n_bins = time_bins.shape[0]
binned_counts = numpy.zeros((n_cat, n_bins))
for i, ses in enumerate(stochastic_event_sets):
n_events = ses.data.shape[0]
ses_origin_time = ses.get_epoch_times()
inds = bin1d_vec(ses_origin_time, time_bins)
for j in range(n_events):
binned_counts[i, inds[j]] += 1
if (i+1) % 1500 == 0:
t1 = time.time()
print(f"Processed {i+1} catalogs in {t1-t0} seconds.")
t1 = time.time()
print(f'Collected binned counts in {t1-t0} seconds.')
summed_counts = numpy.cumsum(binned_counts, axis=1)
# compute summary statistics for plotting
fifth_per = numpy.percentile(summed_counts, 5, axis=0)
first_quar = numpy.percentile(summed_counts, 25, axis=0)
med_counts = numpy.percentile(summed_counts, 50, axis=0)
second_quar = numpy.percentile(summed_counts, 75, axis=0)
nine_fifth = numpy.percentile(summed_counts, 95, axis=0)
# compute median for comcat data
obs_binned_counts = numpy.zeros(n_bins)
inds = bin1d_vec(observation.get_epoch_times(), time_bins)
for j in range(observation.event_count):
obs_binned_counts[inds[j]] += 1
obs_summed_counts = numpy.cumsum(obs_binned_counts)
# update time_bins for plotting
millis_to_hours = 60*60*1000*24
time_bins = (time_bins - time_bins[0])/millis_to_hours
time_bins = time_bins + (dt/millis_to_hours)
# make all arrays start at zero
time_bins = numpy.insert(time_bins, 0, 0)
fifth_per = numpy.insert(fifth_per, 0, 0)
first_quar = numpy.insert(first_quar, 0, 0)
med_counts = numpy.insert(med_counts, 0, 0)
second_quar = numpy.insert(second_quar, 0, 0)
nine_fifth = numpy.insert(nine_fifth, 0, 0)
obs_summed_counts = numpy.insert(obs_summed_counts, 0, 0)
# get values from plotting args
sim_label = plot_args.get('sim_label', 'Simulated')
obs_label = plot_args.get('obs_label', 'Observation')
xycoords = plot_args.get('xycoords', (1.00, 0.40))
legend_loc = plot_args.get('legend_loc', 'best')
title = plot_args.get('title', 'Cumulative Event Counts')
# plotting
ax.plot(time_bins, obs_summed_counts, color='black', label=obs_label)
ax.plot(time_bins, med_counts, color='red', label=sim_label)
ax.fill_between(time_bins, fifth_per, nine_fifth, color='red', alpha=0.2, label='5%-95%')
ax.fill_between(time_bins, first_quar, second_quar, color='red', alpha=0.5, label='25%-75%')
ax.legend(loc=legend_loc)
ax.set_xlabel('Days since Mainshock')
ax.set_ylabel('Cumulative Event Count')
ax.set_title(title)
pyplot.subplots_adjust(right=0.75)
# annotate the plot with information from data
# ax.annotate(str(observation), xycoords='axes fraction', xy=xycoords, fontsize=10, annotation_clip=False)
# save figure
filename = plot_args.get('filename', None)
if filename is not None:
fig.savefig(filename + '.pdf')
fig.savefig(filename + '.png', dpi=300)
# optionally show figure
if show:
pyplot.show()
return ax
def plot_magnitude_versus_time(catalog, filename=None, show=False, reset_times=False, plot_args=None, **kwargs):
"""
Plots magnitude versus linear time for an earthquake data.
Catalog class must implement get_magnitudes() and get_datetimes() in order for this function to work correctly.
Args:
catalog (:class:`~csep.core.catalogs.AbstractBaseCatalog`): data to visualize
Returns:
(tuple): fig and axes handle
"""
# get values from plotting args
plot_args = plot_args or {}
title = plot_args.get('title', '')
marker_size = plot_args.get('marker_size', 10)
color = plot_args.get('color', 'blue')
c = plot_args.get('c', None)
clabel = plot_args.get('clabel', None)
print('Plotting magnitude versus time.')
fig = pyplot.figure(figsize=(8,3))
ax = fig.add_subplot(111)
# get time in days
# plotting timestamps for now, until I can format dates on axis properly
f = lambda x: numpy.array(x.timestamp()) / SECONDS_PER_DAY
# map returns a generator function which we collapse with list
days_elapsed = numpy.array(list(map(f, catalog.get_datetimes())))
if reset_times:
days_elapsed = days_elapsed - days_elapsed[0]
magnitudes = catalog.get_magnitudes()
# make plot
if c is not None:
h = ax.scatter(days_elapsed, magnitudes, marker='.', s=marker_size, c=c, cmap=cm.get_cmap('jet'), **kwargs)
cbar = fig.colorbar(h)
cbar.set_label(clabel)
else:
ax.scatter(days_elapsed, magnitudes, marker='.', s=marker_size, color=color, **kwargs)
# do some labeling of the figure
ax.set_title(title, fontsize=16, color='black')
ax.set_xlabel('Days Elapsed')
ax.set_ylabel('Magnitude')
fig.tight_layout()
# # annotate the plot with information from data
# if data is not None:
# try:
# ax.annotate(str(data), xycoords='axes fraction', xy=xycoords, fontsize=10, annotation_clip=False)
# except:
# pass
# handle displaying of figures
if filename is not None:
fig.savefig(filename + '.pdf')
fig.savefig(filename + '.png', dpi=300)
if show:
pyplot.show()
return ax
def plot_histogram(simulated, observation, bins='fd', percentile=None,
show=False, axes=None, catalog=None, plot_args=None):
"""
Plots histogram of single statistic for stochastic event sets and observations. The function will behave differently
depending on the inumpyuts.
Simulated should always be either a list or numpy.array where there would be one value per data in the stochastic event
set. Observation could either be a scalar or a numpy.array/list. If observation is a scale a vertical line would be
plotted, if observation is iterable a second histogram would be plotted.
This allows for comparisons to be made against catalogs where there are multiple values e.g., magnitude, and single values
e.g., event count.
If an axis handle is included, additional function calls will only addition extra simulations, observations will not be
plotted. Since this function returns an axes handle, any extra modifications to the figure can be made using that.
Args:
simulated (numpy.arrays): numpy.array like representation of statistics computed from catalogs.
observation(numpy.array or scalar): observation to plot against stochastic event set
filename (str): filename to save figure
show (bool): show interactive version of the figure
ax (axis object): axis object with interface defined by matplotlib
catalog (csep.AbstractBaseCatalog): used for annotating the figures
plot_args (dict): additional plotting commands. TODO: Documentation
Returns:
axis: matplolib axes handle
"""
# Plotting
plot_args = plot_args or {}
chained = False
figsize = plot_args.get('figsize', None)
if axes is not None:
chained = True
ax = axes
else:
if catalog:
fig, ax = pyplot.subplots(figsize=figsize)
else:
fig, ax = pyplot.subplots()
# parse plotting arguments
sim_label = plot_args.get('sim_label', 'Simulated')
obs_label = plot_args.get('obs_label', 'Observation')
xlabel = plot_args.get('xlabel', 'X')
ylabel = plot_args.get('ylabel', 'Frequency')
xycoords = plot_args.get('xycoords', (1.00, 0.40))
title = plot_args.get('title', None)
legend_loc = plot_args.get('legend_loc', 'best')
legend = plot_args.get('legend', True)
bins = plot_args.get('bins', bins)
color = plot_args.get('color', '')
filename = plot_args.get('filename', None)
xlim = plot_args.get('xlim', None)
# this could throw an error exposing bad implementation
observation = numpy.array(observation)
try:
n = len(observation)
except TypeError:
ax.axvline(x=observation, color='black', linestyle='--', label=obs_label)
else:
# remove any nan values
observation = observation[~numpy.isnan(observation)]
ax.hist(observation, bins=bins, label=obs_label, edgecolor=None, linewidth=0)
# remove any potential nans from arrays
simulated = numpy.array(simulated)
simulated = simulated[~numpy.isnan(simulated)]
if color:
n, bin_edges, patches = ax.hist(simulated, bins=bins, label=sim_label, color=color, edgecolor=None, linewidth=0)
else:
n, bin_edges, patches = ax.hist(simulated, bins=bins, label=sim_label, edgecolor=None, linewidth=0)
# color bars for rejection area
if percentile is not None:
inc = (100 - percentile) / 2
inc_high = 100 - inc
inc_low = inc
p_high = numpy.percentile(simulated, inc_high)
idx_high = numpy.digitize(p_high, bin_edges)
p_low = numpy.percentile(simulated, inc_low)
idx_low = numpy.digitize(p_low, bin_edges)
# show 99.5% of data
if xlim is None:
upper_xlim = numpy.percentile(simulated, 99.75)
upper_xlim = numpy.max([upper_xlim, numpy.max(observation)])
d_bin = bin_edges[1] - bin_edges[0]
upper_xlim = upper_xlim + 2*d_bin
lower_xlim = numpy.percentile(simulated, 0.25)
lower_xlim = numpy.min([lower_xlim, numpy.min(observation)])
lower_xlim = lower_xlim - 2*d_bin
try:
ax.set_xlim([lower_xlim, upper_xlim])
except ValueError:
print('Ignoring observation in axis scaling because inf or -inf')
upper_xlim = numpy.percentile(simulated, 99.75)
upper_xlim = upper_xlim + 2*d_bin
lower_xlim = numpy.percentile(simulated, 0.25)
lower_xlim = lower_xlim - 2*d_bin
ax.set_xlim([lower_xlim, upper_xlim])
else:
ax.set_xlim(xlim)
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if legend:
ax.legend(loc=legend_loc)
# hacky workaround for coloring legend, by calling after legend is drawn.
if percentile is not None:
for idx in range(idx_low):
patches[idx].set_fc('red')
for idx in range(idx_high, len(patches)):
patches[idx].set_fc('red')
if filename is not None:
ax.figure.savefig(filename + '.pdf')
ax.figure.savefig(filename + '.png', dpi=300)
if show:
pyplot.show()
return ax
def plot_ecdf(x, ecdf, axes=None, xv=None, show=False, plot_args = None):
""" Plots empirical cumulative distribution function. """
plot_args = plot_args or {}
# get values from plotting args
sim_label = plot_args.get('sim_label', 'Simulated')
obs_label = plot_args.get('obs_label', 'Observation')
xlabel = plot_args.get('xlabel', 'X')
ylabel = plot_args.get('ylabel', '$P(X \leq x)$')
xycoords = plot_args.get('xycoords', (1.00, 0.40))
legend_loc = plot_args.get('legend_loc', 'best')
filename = plot_args.get('filename', None)
# make figure
if axes == None:
fig, ax = pyplot.subplots()
else:
ax = axes
fig = axes.figure
ax.plot(x, ecdf, label=sim_label)
if xv:
ax.axvline(x=xv, color='black', linestyle='--', label=obs_label)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.legend(loc=legend_loc)
# if data is not None:
# ax.annotate(str(data), xycoords='axes fraction', xy=xycoords, fontsize=10, annotation_clip=False)
if filename is not None:
fig.savefig(filename + '.pdf')
fig.savefig(filename + '.png', dpi=300)
if show:
pyplot.show()
return ax
def plot_magnitude_histogram_dev(ses_data, obs, plot_args, show=False):
bin_edges, obs_hist = obs.magnitude_counts(retbins=True)
n_obs = numpy.sum(obs_hist)
event_counts = numpy.sum(ses_data, axis=1)
# normalize all histograms by counts in each
scale = n_obs / event_counts
# use broadcasting
ses_data = ses_data * scale.reshape(-1,1)
figsize = plot_args.get('figsize', None)
fig = pyplot.figure(figsize=figsize)
ax = fig.gca()
u3etas_median = numpy.median(ses_data, axis=0)
u3etas_low = numpy.percentile(ses_data, 2.5, axis=0)
u3etas_high = numpy.percentile(ses_data, 97.5, axis=0)
u3etas_min = numpy.min(ses_data, axis=0)
u3etas_max = numpy.max(ses_data, axis=0)
u3etas_emax = u3etas_max - u3etas_median
u3etas_emin = u3etas_median - u3etas_min
dmw = bin_edges[1] - bin_edges[0]
bin_edges_plot = bin_edges + dmw / 2
# u3etas_emax = u3etas_max
# plot 95% range as rectangles
rectangles = []
for i in range(len(bin_edges)):
width = dmw / 2
height = u3etas_high[i] - u3etas_low[i]
xi = bin_edges[i] + width / 2
yi = u3etas_low[i]
rect = matplotlib.patches.Rectangle((xi, yi), width, height)
rectangles.append(rect)
pc = matplotlib.collections.PatchCollection(rectangles, facecolor='blue', alpha=0.3, edgecolor='blue')
ax.add_collection(pc)
# plot whiskers
sim_label = plot_args.get('sim_label', 'Simulated Catalogs')
obs_label = plot_args.get('obs_label', 'Observed Catalog')
xlim = plot_args.get('xlim', None)
title = plot_args.get('title', "UCERF3-ETAS Histogram")
filename = plot_args.get('filename', None)
ax.errorbar(bin_edges_plot, u3etas_median, yerr=[u3etas_emin, u3etas_emax], xerr=0.8 * dmw / 2, fmt=' ',
label=sim_label, color='blue', alpha=0.7)
ax.plot(bin_edges_plot, obs_hist, '.k', markersize=10, label=obs_label)
ax.legend(loc='upper right')
ax.set_xlim(xlim)
ax.set_xlabel('Magnitude')
ax.set_ylabel('Event count per magnitude bin')
ax.set_title(title)
# ax.annotate(str(comcat), xycoords='axes fraction', xy=xycoords, fontsize=10, annotation_clip=False)
# pyplot.subplots_adjust(right=0.75)
if filename is not None:
fig.savefig(filename + '.pdf')
fig.savefig(filename + '.png', dpi=300)
if show:
pyplot.show()
return ax
def plot_magnitude_histogram(catalogs, comcat, show=True, plot_args=None):
""" Generates a magnitude histogram from a catalog-based forecast """
# get list of magnitudes list of ndarray
plot_args = plot_args or {}
catalogs_mws = list(map(lambda x: x.get_magnitudes(), catalogs))
obs_mw = comcat.get_magnitudes()
n_obs = comcat.get_number_of_events()
# get histogram at arbitrary values
mws = CSEP_MW_BINS
dmw = mws[1] - mws[0]
def get_hist(x, mws, normed=True):
n_temp = len(x)
if normed and n_temp != 0:
temp_scale = n_obs / n_temp
hist = numpy.histogram(x, bins=mws)[0] * temp_scale
else:
hist = numpy.histogram(x, bins=mws)[0]
return hist
# get hist values
u3etas_hist = numpy.array(list(map(lambda x: get_hist(x, mws), catalogs_mws)))
obs_hist, bin_edges = numpy.histogram(obs_mw, bins=mws)
bin_edges_plot = (bin_edges[1:] + bin_edges[:-1]) / 2
figsize = plot_args.get('figsize', None)
fig = pyplot.figure(figsize=figsize)
ax = fig.gca()
u3etas_median = numpy.median(u3etas_hist, axis=0)
u3etas_low = numpy.percentile(u3etas_hist, 2.5, axis=0)
u3etas_high = numpy.percentile(u3etas_hist, 97.5, axis=0)
u3etas_min = numpy.min(u3etas_hist, axis=0)
u3etas_max = numpy.max(u3etas_hist, axis=0)
u3etas_emax = u3etas_max - u3etas_median
u3etas_emin = u3etas_median - u3etas_min
# u3etas_emax = u3etas_max
# plot 95% range as rectangles
rectangles = []
for i in range(len(mws) - 1):
width = dmw / 2
height = u3etas_high[i] - u3etas_low[i]
xi = mws[i] + width / 2
yi = u3etas_low[i]
rect = matplotlib.patches.Rectangle((xi, yi), width, height)
rectangles.append(rect)
pc = matplotlib.collections.PatchCollection(rectangles, facecolor='blue', alpha=0.3, edgecolor='blue')
ax.add_collection(pc)
# plot whiskers
sim_label = plot_args.get('sim_label', 'Simulated Catalogs')
xlim = plot_args.get('xlim', None)
title=plot_args.get('title', "UCERF3-ETAS Histogram")
xycoords = plot_args.get('xycoords', (1.00, 0.40))
filename = plot_args.get('filename', None)
pyplot.errorbar(bin_edges_plot, u3etas_median, yerr=[u3etas_emin, u3etas_emax], xerr=0.8 * dmw / 2, fmt=' ',
label=sim_label, color='blue', alpha=0.7)
pyplot.plot(bin_edges_plot, obs_hist, '.k', markersize=10, label='Comcat')
pyplot.legend(loc='upper right')
pyplot.xlim(xlim)
pyplot.xlabel('Mw')
pyplot.ylabel('Count')
pyplot.title(title)
# ax.annotate(str(comcat), xycoords='axes fraction', xy=xycoords, fontsize=10, annotation_clip=False)
pyplot.subplots_adjust(right=0.75)
if filename is not None:
fig.savefig(filename + '.pdf')
fig.savefig(filename + '.png', dpi=300)
if show:
pyplot.show()
def plot_basemap(basemap, extent, ax=None, coastline=True, borders=False, linecolor='black', linewidth=True,
grid=False, grid_labels=False, set_global=False, show=False, projection=ccrs.PlateCarree(), apprx=False,
central_latitude=0.0):
""" Wrapper function for multiple cartopy base plots, including access to standard raster webservices
Args:
basemap (str): Possible values are: stock_img, stamen_terrain, stamen_terrain-background, google-satellite, ESRI_terrain, ESRI_imagery, ESRI_relief, ESRI_topo, ESRI_terrain, or webservice link (see examples in :func:`csep.utils.plots._get_basemap`. Default is None
extent (list): [lon_min, lon_max, lat_min, lat_max]
show (bool): Flag if the figure is displayed
set_global (bool): Display the complete globe as basemap
coastline (str): Flag to plot coastline. default True,
borders (bool): Flag to plot country borders. default False,
linewidth (float): Line width of borders and coast lines. default 1.5,
linecolor (str): Color of borders and coast lines. default 'black',
grid (bool): Draws a grid in the basemap
grid_labels (bool): Annotate grid values
apprx (bool): If true, approximates transformation by setting aspect ratio of axes based on middle latitude
central_latitude (float): average latitude from plotting region
Returns:
:class:`matplotlib.pyplot.ax` object
"""
if ax is None:
if apprx:
projection = ccrs.PlateCarree()
fig = pyplot.figure()
ax = fig.add_subplot(111, projection=projection)
# Set plot aspect according to local longitude-latitude ratio in metric units
# (only compatible with plain PlateCarree "projection")
LATKM = 110.574 # length of a ° of latitude [km]; constant --> ignores Earth's flattening
ax.set_aspect(LATKM / (111.320 * numpy.cos(numpy.deg2rad(central_latitude))))
else:
fig = pyplot.figure()
ax = fig.add_subplot(111, projection=projection)
if set_global:
ax.set_global()
else:
ax.set_extent(extents=extent, crs=ccrs.PlateCarree())
try:
# Set adaptive scaling
line_autoscaler = cartopy.feature.AdaptiveScaler('110m', (('50m', 50), ('10m', 5)))
tile_autoscaler = cartopy.feature.AdaptiveScaler(5, ((6, 50), (7, 15)))
tiles = None
# Set tile depth
tile_depth = 4 if set_global else tile_autoscaler.scale_from_extent(extent)
if coastline:
ax.coastlines(color=linecolor, linewidth=linewidth)
if borders:
borders = cartopy.feature.NaturalEarthFeature('cultural', 'admin_0_boundary_lines_land',
line_autoscaler, edgecolor=linecolor, facecolor='never')
ax.add_feature(borders, linewidth=linewidth)
if basemap == 'stock_img':
ax.stock_img()
elif basemap is not None:
tiles = _get_basemap(basemap)
if tiles:
ax.add_image(tiles, tile_depth)
except:
print("Unable to plot basemap. This might be due to no internet access, try pre-downloading the files.")
# Gridline options
if grid:
gl = ax.gridlines(draw_labels=grid_labels, alpha=0.5)
gl.right_labels = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
if show:
pyplot.show()
return ax
def plot_catalog(catalog, ax=None, show=False, extent=None, set_global=False, plot_args=None):
""" Plot catalog in a region
Args:
catalog (:class:`CSEPCatalog`): Catalog object to be plotted
ax (:class:`matplotlib.pyplot.ax`): Previously defined ax object (e.g from plot_spatial_dataset)
show (bool): Flag if the figure is displayed
extent (list): default 1.05-:func:`catalog.region.get_bbox()`
set_global (bool): Display the complete globe as basemap
plot_args (dict): matplotlib and cartopy plot arguments. The dictionary keys are str, whose items can be:
- :figsize: :class:`tuple`/:class:`list` - default [6.4, 4.8]
- :title: :class:`str` - default :class:`catalog.name`
- :title_size: :class:`int` - default 10
- :filename: :class:`str` - File to save figure. default None
- :projection: :class:`cartopy.crs.Projection` - default :class:`cartopy.crs.PlateCarree`. Note: this can be
'fast' to apply an approximate transformation of axes.
- :grid: :class:`bool` - default True
- :grid_labels: :class:`bool` - default True
- :marker: :class:`str` - Marker type
- :markersize: :class:`float` - Constant size for all earthquakes
- :markercolor: :class:`str` - Color for all earthquakes
- :basemap: :class:`str`/:class:`None`. Possible values are: stock_img, stamen_terrain, stamen_terrain-background, google-satellite, ESRI_terrain, ESRI_imagery, ESRI_relief, ESRI_topo, ESRI_terrain, or webservice link. Default is None
- :coastline: :class:`bool` - Flag to plot coastline. default True,
- :borders: :class:`bool` - Flag to plot country borders. default False,
- :linewidth: :class:`float` - Line width of borders and coast lines. default 1.5,
- :linecolor: :class:`str` - Color of borders and coast lines. default 'black',
- :alpha: :class:`float` - Transparency for the earthquakes scatter
- :mag_scale: :class:`float` - Scaling of the scatter
- :legend: :class:`bool` - Flag to display the legend box
- :legend_loc: :class:`int`/:class:`str` - Position of the legend
- :mag_ticks: :class:`list` - Ticks to display in the legend
- :labelspacing: :class:`int` - Separation between legend ticks
Returns:
:class:`matplotlib.pyplot.ax` object
"""
# Get spatial information for plotting
# Retrieve plot arguments
plot_args = plot_args or {}
# figure and axes properties
figsize = plot_args.get('figsize', None)
title = plot_args.get('title', catalog.name)
title_size = plot_args.get('title_size', None)
filename = plot_args.get('filename', None)
# scatter properties
markersize = plot_args.get('markersize', 2)
markercolor = plot_args.get('markercolor', 'blue')
alpha = plot_args.get('alpha', 1)
mag_scale = plot_args.get('mag_scale', 1)
legend = plot_args.get('legend', False)
legend_loc = plot_args.get('legend_loc', 1)
mag_ticks = plot_args.get('mag_ticks', False)
labelspacing = plot_args.get('labelspacing', 1)
region_border = plot_args.get('region_border', True)
# cartopy properties
projection = plot_args.get('projection', ccrs.PlateCarree(central_longitude=0.0))
grid = plot_args.get('grid', True)
grid_labels = plot_args.get('grid_labels', False)
basemap = plot_args.get('basemap', None)
coastline = plot_args.get('coastline', True)
borders = plot_args.get('borders', False)
linewidth = plot_args.get('linewidth', True)
linecolor = plot_args.get('linecolor', 'black')
bbox = catalog.get_bbox()
if region_border:
try:
bbox = catalog.region.get_bbox()
except AttributeError:
pass
if extent is None:
dh = (bbox[1] - bbox[0]) / 20.
dv = (bbox[3] - bbox[2]) / 20.
extent = [bbox[0] - dh, bbox[1]+dh, bbox[2] -dv, bbox[3] + dv]
apprx = False
central_latitude = 0.0
if projection == 'fast':
projection = ccrs.PlateCarree()
apprx = True
n_lats = len(catalog.region.ys) // 2
central_latitude = catalog.region.ys[n_lats]
# Instantiage GeoAxes object
if ax is None:
fig = pyplot.figure(figsize=figsize)
ax = fig.add_subplot(111, projection=projection)
if set_global:
ax.set_global()
else:
ax.set_extent(extents=extent, crs=ccrs.PlateCarree()) # Defined extent always in lat/lon
# Basemap plotting
ax = plot_basemap(basemap, extent, ax=ax, coastline=coastline, borders=borders,
linecolor=linecolor, linewidth=linewidth, projection=projection, apprx=apprx,
central_latitude=central_latitude)
# Scaling function
mw_range = [min(catalog.get_magnitudes()), max(catalog.get_magnitudes())]
def size_map(markersize, values, scale):
if isinstance(mag_scale, (int, float)):
return (markersize/(scale**mw_range[0]) * numpy.power(values, scale))
elif isinstance(scale, (numpy.ndarray, list)):
return scale
else:
raise ValueError('scale data type not supported')
## Plot catalog
scatter = ax.scatter(catalog.get_longitudes(), catalog.get_latitudes(),
s=size_map(markersize, catalog.get_magnitudes(), mag_scale),
transform=cartopy.crs.PlateCarree(),
color=markercolor,
alpha=alpha)
# Legend
if legend:
if not mag_ticks:
mag_ticks = numpy.round(numpy.linspace(mw_range[0], mw_range[1], 4), 1)
handles, labels = scatter.legend_elements(prop="sizes",
num=list(size_map(markersize, mag_ticks, mag_scale)),
alpha=0.3)
ax.legend(handles, mag_ticks,
loc=legend_loc, title=r"Magnitudes",title_fontsize=16,
labelspacing=labelspacing, handletextpad=5, framealpha=False)
if region_border:
try:
pts = catalog.region.tight_bbox()
ax.plot(pts[:, 0], pts[:, 1], lw=1, color='black')
except AttributeError:
print("unable to get tight bbox")
# Gridline options
if grid:
gl = ax.gridlines(draw_labels=grid_labels, alpha=0.5)
gl.right_labels = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
# Figure options
ax.set_title(title, fontsize=title_size, y=1.06)
if filename is not None:
ax.get_figure().savefig(filename + '.pdf')
ax.get_figure().savefig(filename + '.png', dpi=300)
if show:
pyplot.show()
return ax
def plot_spatial_dataset(gridded, region, ax=None, show=False, extent=None, set_global=False, plot_args=None):
""" Plot spatial dataset such as data from a gridded forecast
Args:
gridded (2D :class:`numpy.array`): Values according to `region`,
region (:class:`CartesianGrid2D`): Region in which gridded values are contained
show (bool): Flag if the figure is displayed
extent (list): default :func:`forecast.region.get_bbox()`
set_global (bool): Display the complete globe as basemap
plot_args (dict): matplotlib and cartopy plot arguments. Dict keys are str, whose values can be:
- :figsize: :class:`tuple`/:class:`list` - default [6.4, 4.8]
- :title: :class:`str` - default None
- :title_size: :class:`int` - default 10
- :filename: :class:`str` - default None
- :projection: :class:`cartopy.crs.Projection` - default :class:`cartopy.crs.PlateCarree`
- :grid: :class:`bool` - default True
- :grid_labels: :class:`bool` - default True
- :basemap: :class:`str`. Possible values are: stock_img, stamen_terrain, stamen_terrain-background, google-satellite, ESRI_terrain, ESRI_imagery, ESRI_relief, ESRI_topo, ESRI_terrain, or webservice link. Default is None
- :coastline: :class:`bool` - Flag to plot coastline. default True,
- :borders: :class:`bool` - Flag to plot country borders. default False,
- :linewidth: :class:`float` - Line width of borders and coast lines. default 1.5,
- :linecolor: :class:`str` - Color of borders and coast lines. default 'black',
- :cmap: :class:`str`/:class:`pyplot.colors.Colormap` - default 'viridis'
- :clabel: :class:`str` - default None
- :clim: :class:`list` - default None
- :alpha: :class:`float` - default 1
- :alpha_exp: :class:`float` - Exponent for the alpha func (recommended between 0.4 and 1). default 0
Returns:
:class:`matplotlib.pyplot.ax` object
"""
# Get spatial information for plotting
bbox = region.get_bbox()
if extent is None:
extent = [bbox[0], bbox[1], bbox[2] + region.dh, bbox[3] + region.dh]
# Retrieve plot arguments
plot_args = plot_args or {}
# figure and axes properties
figsize = plot_args.get('figsize', None)
title = plot_args.get('title', 'Spatial Dataset')
title_size = plot_args.get('title_size', None)
filename = plot_args.get('filename', None)
# cartopy properties
projection = plot_args.get('projection', ccrs.PlateCarree(central_longitude=0.0))
grid = plot_args.get('grid', True)
grid_labels = plot_args.get('grid_labels', False)
basemap = plot_args.get('basemap', None)
coastline = plot_args.get('coastline', True)
borders = plot_args.get('borders', False)
linewidth = plot_args.get('linewidth', True)
linecolor = plot_args.get('linecolor', 'black')
region_border = plot_args.get('region_border', True)
# color bar properties
cmap = plot_args.get('cmap', None)
clabel = plot_args.get('clabel', '')
clim = plot_args.get('clim', None)
alpha = plot_args.get('alpha', 1)
alpha_exp = plot_args.get('alpha_exp', 0)
apprx = False
central_latitude = 0.0
if projection == 'fast':
projection = ccrs.PlateCarree()
apprx = True
n_lats = len(region.ys) // 2
central_latitude = region.ys[n_lats]
# Instantiage GeoAxes object
if ax is None:
fig = pyplot.figure(figsize=figsize)
ax = fig.add_subplot(111, projection=projection)
else:
fig = ax.get_figure()
if set_global:
ax.set_global()
else:
ax.set_extent(extents=extent, crs=ccrs.PlateCarree()) # Defined extent always in lat/lon
# Basemap plotting
ax = plot_basemap(basemap, extent, ax=ax, coastline=coastline, borders=borders,
linecolor=linecolor, linewidth=linewidth, projection=projection, apprx=apprx,
central_latitude=central_latitude)
## Define colormap and transparency function
if isinstance(cmap, str) or not cmap:
cmap = pyplot.get_cmap(cmap)
cmap_tup = cmap(numpy.arange(cmap.N))
if isinstance(alpha_exp, (float,int)):
if alpha_exp != 0:
cmap_tup[:, -1] = numpy.linspace(0, 1, cmap.N) ** alpha_exp
alpha = None
cmap = matplotlib.colors.ListedColormap(cmap_tup)
## Plot spatial dataset
lons, lats = numpy.meshgrid(numpy.append(region.xs, region.xs[-1] + region.dh),
numpy.append(region.ys, region.ys[-1] + region.dh))
im = ax.pcolor(lons, lats, gridded, cmap=cmap, alpha=alpha, snap=True, transform=ccrs.PlateCarree())
im.set_clim(clim)
# Colorbar options
# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
cax = fig.add_axes([ax.get_position().x1 + 0.01, ax.get_position().y0, 0.025, ax.get_position().height],
label='Colorbar')
cbar = fig.colorbar(im, ax=ax, cax=cax)
cbar.set_label(clabel)
# Gridline options
if grid:
gl = ax.gridlines(draw_labels=grid_labels, alpha=0.5)
gl.right_labels = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
if region_border:
pts = region.tight_bbox()
ax.plot(pts[:,0], pts[:,1], lw=1, color='black', transform=ccrs.PlateCarree())
# matplotlib figure options
ax.set_title(title, y=1.06)
if filename is not None:
ax.get_figure().savefig(filename + '.pdf')
ax.get_figure().savefig(filename + '.png', dpi=300)
if show:
pyplot.show()
return ax
def plot_number_test(evaluation_result, axes=None, show=True, plot_args=None):
"""
Takes result from evaluation and generates a specific histogram plot to show the results of the statistical evaluation
for the n-test.
Args:
evaluation_result: object-like var that implements the interface of the above EvaluationResult
Returns:
ax (matplotlib.axes.Axes): can be used to modify the figure
"""
plot_args = plot_args or {}
# handle plotting
if axes:
chained = True
else:
chained = False
# supply fixed arguments to plots
# might want to add other defaults here
filename = plot_args.get('filename', None)
xlabel = plot_args.get('xlabel', 'Event count of catalog')
ylabel = plot_args.get('ylabel', 'Number of catalogs')
xy = plot_args.get('xy', (0.5, 0.3))
fixed_plot_args = {'obs_label': evaluation_result.obs_name,
'sim_label': evaluation_result.sim_name}
plot_args.update(fixed_plot_args)
bins = plot_args.get('mag_bins', 'auto')
percentile = plot_args.get('percentile', 95)
ax = plot_histogram(evaluation_result.test_distribution, evaluation_result.observed_statistic,
catalog=evaluation_result.obs_catalog_repr,
plot_args=plot_args,
bins=bins,
axes=axes,
percentile=percentile)
# annotate plot with p-values
if not chained:
try:
ax.annotate('$\delta_1 = P(X \geq x) = {:.2f}$\n$\delta_2 = P(X \leq x) = {:.2f}$\n$\omega = {:d}$'
.format(*evaluation_result.quantile, evaluation_result.observed_statistic),
xycoords='axes fraction',
xy=xy,
fontsize=14)
except:
ax.annotate('$\gamma = P(X \leq x) = {:.2f}$\n$\omega = {:.2f}$'
.format(evaluation_result.quantile, evaluation_result.observed_statistic),
xycoords='axes fraction',
xy=xy,
fontsize=14)
title = plot_args.get('title', evaluation_result.name)
ax.set_title(title, fontsize=14)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if filename is not None:
ax.figure.savefig(filename + '.pdf')
ax.figure.savefig(filename + '.png', dpi=300)
# func has different return types, before release refactor and remove plotting from evaluation.
# plotting should be separated from evaluation.
# evaluation should return some object that can be plotted maybe with verbose option.
if show:
pyplot.show()
return ax
def plot_magnitude_test(evaluation_result, axes=None, show=True, plot_args=None):
"""
Takes result from evaluation and generates a specific histogram plot to show the results of the statistical evaluation
for the M-test.
Args:
evaluation_result: object that implements the interface of EvaluationResult
Returns:
ax (matplotlib.axes.Axes): can be used to modify the figure
"""
plot_args = plot_args or {}
# handle plotting
if axes:
chained = True
else:
chained = False
# supply fixed arguments to plots
# might want to add other defaults here
filename = plot_args.get('filename', None)
xy = plot_args.get('xy', (0.55, 0.6))
fixed_plot_args = {'xlabel': 'D* Statistic',
'ylabel': 'Number of Catalogs',
'obs_label': evaluation_result.obs_name,
'sim_label': evaluation_result.sim_name}
plot_args.update(fixed_plot_args)
bins = plot_args.get('bins', 'auto')
percentile = plot_args.get('percentile', 95)
ax = plot_histogram(evaluation_result.test_distribution, evaluation_result.observed_statistic,
catalog=evaluation_result.obs_catalog_repr,
plot_args=plot_args,
bins=bins,
axes=axes,
percentile=percentile)
# annotate plot with quantile values
if not chained:
try:
ax.annotate('$\gamma = P(X \geq x) = {:.2f}$\n$\omega = {:.2f}$'
.format(evaluation_result.quantile, evaluation_result.observed_statistic),
xycoords='axes fraction',
xy=xy,
fontsize=14)
except TypeError:
# if both quantiles are provided, we want to plot the greater-equal quantile
ax.annotate('$\gamma = P(X \geq x) = {:.2f}$\n$\omega = {:.2f}$'
.format(evaluation_result.quantile[0], evaluation_result.observed_statistic),
xycoords='axes fraction',
xy=xy,
fontsize=14)
title = plot_args.get('title', 'Magnitude Test')
ax.set_title(title, fontsize=14)
if filename is not None:
ax.figure.savefig(filename + '.pdf')
ax.figure.savefig(filename + '.png', dpi=300)
# func has different return types, before release refactor and remove plotting from evaluation.
# plotting should be separated from evaluation.
# evaluation should return some object that can be plotted maybe with verbose option.
if show:
pyplot.show()
return ax
def plot_distribution_test(evaluation_result, axes=None, show=True, plot_args=None):
"""
Takes result from evaluation and generates a specific histogram plot to show the results of the statistical evaluation
for the M-test.
Args:
evaluation_result: object-like var that implements the interface of the above EvaluationResult
Returns:
ax (matplotlib.axes.Axes): can be used to modify the figure
"""
plot_args = plot_args or {}
# handle plotting
if axes:
chained = True
else:
chained = False
# supply fixed arguments to plots
# might want to add other defaults here
filename = plot_args.get('filename', None)
xlabel = plot_args.get('xlabel', '')
ylabel = plot_args.get('ylabel', '')
fixed_plot_args = {'obs_label': evaluation_result.obs_name,
'sim_label': evaluation_result.sim_name}
plot_args.update(fixed_plot_args)
bins = plot_args.get('bins', 'auto')
percentile = plot_args.get('percentile', 95)
ax = plot_histogram(evaluation_result.test_distribution, evaluation_result.observed_statistic,
catalog=evaluation_result.obs_catalog_repr,
plot_args=plot_args,
bins=bins,
axes=axes,
percentile=percentile)
# annotate plot with p-values
if not chained:
ax.annotate('$\gamma = P(X \leq x) = {:.3f}$\n$\omega$ = {:.3f}'
.format(evaluation_result.quantile, evaluation_result.observed_statistic),
xycoords='axes fraction',
xy=(0.5, 0.3),
fontsize=14)
title = plot_args.get('title', evaluation_result.name)
ax.set_title(title, fontsize=14)
ax.set_title(title, fontsize=14)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if filename is not None:
ax.figure.savefig(filename + '.pdf')
ax.figure.savefig(filename + '.png', dpi=300)
# func has different return types, before release refactor and remove plotting from evaluation.
# plotting should be separated from evaluation.
# evaluation should return some object that can be plotted maybe with verbose option.
if show:
pyplot.show()
return ax
def plot_likelihood_test(evaluation_result, axes=None, show=True, plot_args=None):
"""
Takes result from evaluation and generates a specific histogram plot to show the results of the statistical evaluation
for the L-test.
Args:
evaluation_result: object-like var that implements the interface of the above EvaluationResult
Returns:
ax (matplotlib.axes.Axes): can be used to modify the figure
"""
plot_args = plot_args or {}
# handle plotting
if axes:
chained = True
else:
chained = False
# supply fixed arguments to plots
# might want to add other defaults here
filename = plot_args.get('filename', None)
fixed_plot_args = {'xlabel': 'Pseudo likelihood',
'ylabel': 'Number of catalogs',
'obs_label': evaluation_result.obs_name,
'sim_label': evaluation_result.sim_name}
plot_args.update(fixed_plot_args)
bins = plot_args.get('bins', 'auto')
percentile = plot_args.get('percentile', 95)
ax = plot_histogram(evaluation_result.test_distribution, evaluation_result.observed_statistic,
catalog=evaluation_result.obs_catalog_repr,
plot_args=plot_args,
bins=bins,
axes=axes,
percentile=percentile)
# annotate plot with p-values
if not chained:
try:
ax.annotate('$\gamma = P(X \leq x) = {:.2f}$\n$\omega = {:.2f}$'
.format(evaluation_result.quantile, evaluation_result.observed_statistic),
xycoords='axes fraction',
xy=(0.55, 0.3),
fontsize=14)
except TypeError:
# if both quantiles are provided, we want to plot the greater-equal quantile
ax.annotate('$\gamma = P(X \leq x) = {:.2f}$\n$\omega = {:.2f}$'
.format(evaluation_result.quantile[1], evaluation_result.observed_statistic),
xycoords='axes fraction',
xy=(0.55, 0.3),
fontsize=14)
title = plot_args.get('title', 'Likelihood Test')
ax.set_title(title, fontsize=14)
if filename is not None:
ax.figure.savefig(filename + '.pdf')
ax.figure.savefig(filename + '.png', dpi=300)
# func has different return types, before release refactor and remove plotting from evaluation.
# plotting should be separated from evaluation.
# evaluation should return some object that can be plotted maybe with verbose option.
if show:
pyplot.show()
return ax
def plot_spatial_test(evaluation_result, axes=None, plot_args=None, show=True):
"""
Plot spatial test result from catalog based forecast
Args:
evaluation_result:
Returns:
"""
plot_args = plot_args or {}
# handle plotting
if axes:
chained = True
else:
chained = False
# supply fixed arguments to plots
# might want to add other defaults here
filename = plot_args.get('filename', None)
fixed_plot_args = {'obs_label': evaluation_result.obs_name,
'sim_label': evaluation_result.sim_name,
'xlabel': 'Normalized pseudo likelihood',
'ylabel': 'Number of catalogs'}
plot_args.update(fixed_plot_args)
title = plot_args.get('title', 'Spatial Test')
percentile = plot_args.get('percentile', 95)
ax = plot_histogram(evaluation_result.test_distribution, evaluation_result.observed_statistic,
catalog=evaluation_result.obs_catalog_repr,
plot_args=plot_args,
bins='fd',
axes=axes,
percentile=percentile)
# annotate plot with p-values
if not chained:
try:
ax.annotate('$\gamma = P(X \leq x) = {:.2f}$\n$\omega = {:.2f}$'
.format(evaluation_result.quantile, evaluation_result.observed_statistic),
xycoords='axes fraction',
xy=(0.2, 0.6),
fontsize=14)
except TypeError:
# if both quantiles are provided, we want to plot the greater-equal quantile
ax.annotate('$\gamma = P(X \leq x) = {:.2f}$\n$\omega = {:.2f}$'
.format(evaluation_result.quantile[1], evaluation_result.observed_statistic),
xycoords='axes fraction',
xy=(0.2, 0.6),
fontsize=14)
ax.set_title(title, fontsize=14)
if filename is not None:
ax.figure.savefig(filename + '.pdf')
ax.figure.savefig(filename + '.png', dpi=300)
# func has different return types, before release refactor and remove plotting from evaluation.
# plotting should be separated from evaluation.
# evaluation should return some object that can be plotted maybe with verbose option.
if show:
pyplot.show()
return ax
def _get_marker_style(obs_stat, p, one_sided_lower):
"""Returns matplotlib marker style as fmt string"""
if obs_stat < p[0] or obs_stat > p[1]:
# red circle
fmt = 'ro'
else:
# green square
fmt = 'gs'
if one_sided_lower:
if obs_stat < p[0]:
fmt = 'ro'
else:
fmt = 'gs'
return fmt
def plot_comparison_test(results, plot_args=None):
"""Plots list of T-Test or W-Test Results"""
if plot_args is None:
plot_args = {}
title = plot_args.get('title', 'CSEP1 Consistency Test')
xlabel = plot_args.get('xlabel', 'X')
ylabel = plot_args.get('ylabel', 'Y')
fig, ax = pyplot.subplots()
ax.axhline(y=0, linestyle='--', color='black')
for index, result in enumerate(results):
ylow = result.observed_statistic - result.test_distribution[0]
yhigh = result.test_distribution[1] - result.observed_statistic
ax.errorbar(index, result.observed_statistic, yerr=numpy.array([[ylow, yhigh]]).T, color='black', capsize=4)
ax.plot(index, result.observed_statistic, 'ok')
ax.set_xticklabels([res.sim_name[0] for res in results])
ax.set_xticks(numpy.arange(len(results)))
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_title(title)
fig.tight_layout()
return ax
def plot_poisson_consistency_test(eval_results, normalize=False, one_sided_lower=False, plot_args=None):
""" Plots results from CSEP1 tests following the CSEP1 convention.
Note: All of the evaluations should be from the same type of evaluation, otherwise the results will not be
comparable on the same figure.
Args:
results (list): Contains the tests results :class:`csep.core.evaluations.EvaluationResult` (see note above)
normalize (bool): select this if the forecast likelihood should be normalized by the observed likelihood. useful
for plotting simulation based simulation tests.
one_sided_lower (bool): select this if the plot should be for a one sided test
plot_args(dict): optional argument containing a dictionary of plotting arguments, with keys as strings and items as described below
Optional plotting arguments:
* figsize: (:class:`list`/:class:`tuple`) - default: [6.4, 4.8]
* title: (:class:`str`) - default: name of the first evaluation result type
* title_fontsize: (:class:`float`) Fontsize of the plot title - default: 10
* xlabel: (:class:`str`) - default: 'X'
* xlabel_fontsize: (:class:`float`) - default: 10
* xticks_fontsize: (:class:`float`) - default: 10
* ylabel_fontsize: (:class:`float`) - default: 10
* color: (:class:`float`/:class:`None`) If None, sets it to red/green according to :func:`_get_marker_style` - default: 'black'
* linewidth: (:class:`float`) - default: 1.5
* capsize: (:class:`float`) - default: 4
* hbars: (:class:`bool`) Flag to draw horizontal bars for each model - default: True
* tight_layout: (:class:`bool`) Set matplotlib.figure.tight_layout to remove excess blank space in the plot - default: True
Returns:
ax (:class:`matplotlib.pyplot.axes` object)
"""
try:
results = list(eval_results)
except TypeError:
results = [eval_results]
results.reverse()
# Parse plot arguments. More can be added here
if plot_args is None:
plot_args = {}
figsize= plot_args.get('figsize', None)
title = plot_args.get('title', results[0].name)
title_fontsize = plot_args.get('title_fontsize', None)
xlabel = plot_args.get('xlabel', 'X')
xlabel_fontsize = plot_args.get('xlabel_fontsize', None)
xticks_fontsize = plot_args.get('xticks_fontsize', None)
ylabel_fontsize = plot_args.get('ylabel_fontsize', None)
color = plot_args.get('color', 'black')
linewidth = plot_args.get('linewidth', None)
capsize = plot_args.get('capsize', 4)
hbars = plot_args.get('hbars', True)
tight_layout = plot_args.get('tight_layout', True)
fig, ax = pyplot.subplots(figsize=figsize)
xlims = []
for index, res in enumerate(results):
# handle analytical distributions first, they are all in the form ['name', parameters].
if res.test_distribution[0] == 'poisson':
plow = scipy.stats.poisson.ppf(0.025, res.test_distribution[1])
phigh = scipy.stats.poisson.ppf(0.975, res.test_distribution[1])
observed_statistic = res.observed_statistic
# empirical distributions
else:
if normalize:
test_distribution = numpy.array(res.test_distribution) - res.observed_statistic
observed_statistic = 0
else:
test_distribution = numpy.array(res.test_distribution)
observed_statistic = res.observed_statistic
# compute distribution depending on type of test
if one_sided_lower:
plow = numpy.percentile(test_distribution, 5)
phigh = numpy.percentile(test_distribution, 100)
else:
plow = numpy.percentile(test_distribution, 2.5)
phigh = numpy.percentile(test_distribution, 97.5)
if not numpy.isinf(observed_statistic): # Check if test result does not diverges
low = observed_statistic - plow
high = phigh - observed_statistic
ax.errorbar(observed_statistic, index, xerr=numpy.array([[low, high]]).T,
fmt=_get_marker_style(observed_statistic, (plow, phigh), one_sided_lower),
capsize=capsize, linewidth=linewidth, ecolor=color)
# determine the limits to use
xlims.append((plow, phigh, observed_statistic))
# we want to only extent the distribution where it falls outside of it in the acceptable tail
if one_sided_lower:
if observed_statistic >= plow and phigh < observed_statistic:
# draw dashed line to infinity
xt = numpy.linspace(phigh, 99999, 100)
yt = numpy.ones(100) * index
ax.plot(xt, yt, linestyle='--', linewidth=linewidth, color=color)
else:
print('Observed statistic diverges for forecast %s, index %i.'
' Check for zero-valued bins within the forecast'% (res.sim_name, index))
ax.barh(index, 99999, left=-10000, height=1, color=['red'], alpha=0.5)
try:
ax.set_xlim(*_get_axis_limits(xlims))
except ValueError:
raise ValueError('All EvaluationResults have infinite observed_statistics')
ax.set_yticks(numpy.arange(len(results)))
ax.set_yticklabels([res.sim_name for res in results], fontsize=ylabel_fontsize)
ax.set_ylim([-0.5, len(results)-0.5])
if hbars:
yTickPos = ax.get_yticks()
if len(yTickPos) >= 2:
ax.barh(yTickPos, numpy.array([99999] * len(yTickPos)), left=-10000,
height=(yTickPos[1] - yTickPos[0]), color=['w', 'gray'], alpha=0.2, zorder=0)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel(xlabel, fontsize=xlabel_fontsize)
ax.tick_params(axis='x', labelsize=xticks_fontsize)
if tight_layout:
ax.figure.tight_layout()
fig.tight_layout()
return ax
def _get_axis_limits(pnts, border=0.05):
"""Returns a tuple of x_min and x_max given points on plot."""
x_min = numpy.min(pnts)
x_max = numpy.max(pnts)
xd = (x_max - x_min)*border
return (x_min-xd, x_max+xd)
def _get_basemap(basemap):
if basemap == 'stamen_terrain':
tiles = img_tiles.Stamen('terrain')
elif basemap == 'stamen_terrain-background':
tiles = img_tiles.Stamen('terrain-background')
elif basemap == 'google-satellite':
tiles = img_tiles.GoogleTiles(style='satellite')
elif basemap == 'ESRI_terrain':
webservice = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/' \
'MapServer/tile/{z}/{y}/{x}.jpg'
tiles = img_tiles.GoogleTiles(url=webservice)
elif basemap == 'ESRI_imagery':
webservice = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/' \
'MapServer/tile/{z}/{y}/{x}.jpg'
tiles = img_tiles.GoogleTiles(url=webservice)
elif basemap == 'ESRI_relief':
webservice = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/' \
'MapServer/tile/{z}/{y}/{x}.jpg'
tiles = img_tiles.GoogleTiles(url=webservice)
elif basemap == 'ESRI_topo':
webservice = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/' \
'MapServer/tile/{z}/{y}/{x}.jpg'
tiles = img_tiles.GoogleTiles(url=webservice)
else:
try:
webservice = basemap
tiles = img_tiles.GoogleTiles(url=webservice)
except:
raise ValueError('Basemap type not valid or not implemented')
return tiles
def plot_calibration_test(evaluation_result, axes=None, plot_args=None, show=False):
# set up QQ plots and KS test
plot_args = plot_args or {}
n = len(evaluation_result.test_distribution)
k = numpy.arange(1, n + 1)
# plotting points for uniform quantiles
pp = k / (n + 1)
# compute confidence intervals for order statistics using beta distribution
ulow = scipy.stats.beta.ppf(0.025, k, n - k + 1)
uhigh = scipy.stats.beta.ppf(0.975, k, n - k + 1)
# get stuff from plot_args
label = plot_args.get('label', evaluation_result.sim_name)
xlim = plot_args.get('xlim', [0, 1.05])
ylim = plot_args.get('ylim', [0, 1.05])
xlabel = plot_args.get('xlabel', 'Quantile scores')
ylabel = plot_args.get('ylabel', 'Standard uniform quantiles')
color = plot_args.get('color', 'tab:blue')
marker = plot_args.get('marker', 'o')
size = plot_args.get('size', 5)
legend_loc = plot_args.get('legend_loc', 'best')
# quantiles should be sorted for plotting
sorted_td = numpy.sort(evaluation_result.test_distribution)
if axes is None:
fig, ax = pyplot.subplots()
else:
ax = axes
# plot qq plot
_ = ax.scatter(sorted_td, pp, label=label, c=color, marker=marker, s=size)
# plot uncertainty on uniform quantiles
ax.plot(pp, pp, '-k')
ax.plot(ulow, pp, ':k')
ax.plot(uhigh, pp, ':k')
ax.set_ylim(ylim)
ax.set_xlim(xlim)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.legend(loc=legend_loc)
if show:
pyplot.show()
return ax |
<gh_stars>1-10
#!/bin/python3;
a="""
This script will insert a row before the first row of the supplied CSV file.
Each field of this row will contain the numeric value of the ordinal position of the given field.
This script will also insert a column before the first column of the supplied CSV file.
The field of this column will contain the numeric value of the ordinal position of the record it is now part of.
pushd .;cd /local/data/development.minor/KAUST/BORG/try1;
export src_csv_dataset_file_name="../raw_data/2020-05-03/BORG_DDIEM__clinical_logs.2020-05-03.1213hrs.csv";
working_dir_file_name="/local/data/tmp/BORG_DDIEM/BORG_DDIEM__parse_clinical_logs_CSV.working_dir" \
&& count_of_workers=1 \
&& log_file_name="/local/data/tmp/BORG_DDIEM/logs/BORG_DDIEM__dataset.csv.log.`date +%Y-%m-%d.%H%M.%S.%N.%Z`" \
&& echo `date +%Y-%m-%d.%H%M.%S.%N.%Z`", log_file_name is:'${log_file_name}'" \
&& mkdir -p "$(dirname ${log_file_name})" \
&& pushd . && cd /local/data/development.minor/KAUST/BORG/try1 \
&& PYTHON_HOME="/local/data/apps/python/3.8.0" \
&& date && time "${PYTHON_HOME}"/bin/python3 src/py/clinical_logs_data_transformation/BORG_DDIEM__parse_clinical_logs_CSV.py \
-f"${src_csv_dataset_file_name}" \
-d"/local/data/development.minor/KAUST/BORG/raw_data" \
--count_of_workers=${count_of_workers} \
2>&1|tee "${log_file_name}" \
&& popd && date;
rm -rf /local/data/development.minor/KAUST/BORG/raw_data/2020-*/.~lock.*
""";
#from xml.sax import saxutils;
#import xml.sax;
import sys;
import os;
import getopt;
from optparse import OptionParser;
import errno;
import csv;
import re;
import time;
import json;
import logging;
import errno;
import sys, traceback;
import datetime;
import socket;
import multiprocessing;
LOG_FORMAT=('%(levelname) -5s processes_id:%(process)d time:%(asctime)s %(name) -10s [%(pathname)s %(module)s %(funcName) '
'-15s %(lineno) -5d]: %(message)s');
LOGGER = logging.getLogger(__name__);
def run_BORG_DDIEM__parse_clinical_logs_CSV(
w
,queue
,worker_id
):
try:
w.run();
queue.put(w._processing_outcome__dict);
except KeyboardInterrupt:
d.stop();
class BORG_DDIEM__parse_clinical_logs_CSV():
def __init__(
self
,hostname,ipAddress,ppid
,task_id
,task_formulation_timestamp
,worker_id
,worker_number
,working_dir_file_name
,_srcCSVFileName
,_destCSVDirFileName
):
doc="""
an object if this class performs the tranformation of XML to JSON.
""";
self.LOG_FORMAT=('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
'-35s %(lineno) -5d: %(message)s');
self.logging_level__value="INFO";
self.working_dir_file_name=working_dir_file_name;
self.hostname=hostname;
self.ipAddress=ipAddress;
self.ppid=os.getppid();
self.pid=os.getpid();
self.task_formulation_timestamp=task_formulation_timestamp;
self.task_id=task_id;
self.worker_id=worker_id;
self.worker_number=worker_number;
self._srcCSVFileName=_srcCSVFileName;
self._destCSVDirFileName=_destCSVDirFileName;
self._processing_outcome__dict=None;
try:
if(_srcCSVFileName==None or len(_srcCSVFileName.strip())<0):
pass;
raise ValueError("_srcCSVFileName is empty the supplied value is '%s'"%(_srcCSVFileName));
except ValueError as error:
#see "/local/data/BCL_FE_ABI3730_sequencer_plate_data_generator_jobs_data/2018/2018-09/2018-09-20/2018-09-20_171025_103.processing_outcome.json"
#LOGGER.info(" '%s', -------------- cmd is:'%s', row_cnt is:%d"%(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),cmd,row_cnt));
LOGGER.exception(error);
LOGGER.exception(traceback.format_exc());
raise error;
def run(self):
self._processing_outcome__dict=include_ordinal_position_fields(
self.hostname,self.ipAddress,self.ppid,self.pid
,self.working_dir_file_name
,self.task_id
,self.task_formulation_timestamp
,self.worker_id
,self.worker_number
,self._srcCSVFileName
,self._destCSVDirFileName
);
LOGGER.info("self._processing_outcome__dict is:'%s'"%(json.dumps(self._processing_outcome__dict,indent=4)));
def get_processing_outcome(self):
return self._processing_outcome__dict;
def include_ordinal_position_fields(
hostname,ipAddress,ppid,pid
,working_dir_file_name
,task_id
,task_formulation_timestamp
,worker_id
,worker_number
,_srcCSVFileName
,_destCSVDirFileName
):
pass;
processing_outcome__dict={};
task_commencement_time_obj=datetime.datetime.now();
task_commencement_time_str=task_commencement_time_obj.strftime('%Y-%m-%d %H:%M:%S.%f');
"""
""";
src_dataset_csv_file_name=_srcCSVFileName;
dest_dataset_csv_file_name=os.path.join(
_destCSVDirFileName
,os.path.basename(os.path.dirname(_srcCSVFileName))
,"%s.parsed.csv"%(os.path.splitext(os.path.basename(_srcCSVFileName))[0])
);
LOGGER.info("dest_dataset_csv_file_name is:'%s'"%(dest_dataset_csv_file_name));
mkdir_p(os.path.dirname(os.path.abspath(dest_dataset_csv_file_name)));
src_dataset_csv_fh=None;
src_dataset_csv_reader=None;
src_dataset_csv_fh=open(src_dataset_csv_file_name,"r");
src_dataset_csv_reader=csv.reader(
src_dataset_csv_fh
,delimiter=","
,quotechar='"'
,quoting=csv.QUOTE_MINIMAL
);
dest_dataset_csv_fh=None;
dest_dataset_csv_writer=None;
dest_dataset_csv_fh=open(dest_dataset_csv_file_name,"w");
dest_dataset_csv_writer=csv.writer(dest_dataset_csv_fh,delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL);
row2=[];
cnt_of_fields__max=0;
cnt_of_fields=0;
row_cnt=0;
src_dataset_csv_fh.seek(0);
for row in src_dataset_csv_reader:
row_cnt+=1;
if(len(row)>cnt_of_fields__max):
cnt_of_fields__max=len(row);
del row2[:];
for i, val in enumerate(row):
if(row[i]==None):
row[i]="";
else:
row[i]=row[i].strip();
if(row_cnt==1):
"""
We have the header record, lets generate and insert a row in the destination CSV, the fields of this row would contain the numeric ordinal position of the field.
"""
row2.append(0);
for i, val in enumerate(row):
row2.append(i+1);
dest_dataset_csv_writer.writerow(row2);
row2=[];
row2.append(row_cnt-1);
row2.extend(row[:]);
dest_dataset_csv_writer.writerow(row2);
dest_dataset_csv_fh.close();
src_dataset_csv_fh.close();
task_completion_time_obj=datetime.datetime.now();
task_completion_time_str="%s"%(task_completion_time_obj.strftime('%Y-%m-%d %H:%M:%S.%f'));
duration_obj=task_completion_time_obj-task_commencement_time_obj;
duration_ms=duration_obj.total_seconds()*1000;
processing_outcome__dict["task_commencement_time_str"]=task_commencement_time_str;
processing_outcome__dict["task_completion_time_str"]=task_completion_time_str;
processing_outcome__dict["duration_ms"]=duration_ms;
processing_outcome__dict["hostname"]=hostname;
processing_outcome__dict["ipAddress"]=ipAddress;
processing_outcome__dict["ppid"]=ppid;
processing_outcome__dict["pid"]=pid;
processing_outcome__dict["task_id"]=task_id;
processing_outcome__dict["task_formulation_timestamp_str"]=task_formulation_timestamp.strftime('%Y-%m-%d %H:%M:%S.%f');
processing_outcome__dict["worker_id"]=worker_id;
processing_outcome__dict["worker_number"]=worker_number;
processing_outcome__dict["src_dataset_csv_file_name"]=src_dataset_csv_file_name;
processing_outcome__dict["dest_dataset_csv_file_name"]=dest_dataset_csv_file_name;
processing_outcome__dict["cnt_of_fields__max"]=cnt_of_fields__max;
return processing_outcome__dict;
def getLocalIPAddress():
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM);
s.connect(('google.com',80));
return s.getsockname()[0];
def touch(file_name):
mkdir_p(os.path.abspath(os.path.join(file_name, os.pardir)));
with open(file_name,'a'):
os.utime(file_name,None);
import errno;
def mkdir_p(path):
if(not(os.path.exists(path) and os.path.isdir(path))):
try:
os.makedirs(path,exist_ok=True);
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def format_my_nanos(nanos):
dt = datetime.datetime.fromtimestamp(nanos / 1e9)
#return '{}.{:09.0f}'.format(dt.strftime('%Y-%m-%dT%H:%M:%S'), nanos % 1e9);
return '{}_{:09.0f}'.format(dt.strftime('%Y%m%d%H%M%S'), nanos % 1e9);
def timestamp_from_nano_seconds(nanos):
dt = datetime.datetime.fromtimestamp(nanos / 1e9)
#return '{}.{:09.0f}'.format(dt.strftime('%Y-%m-%dT%H:%M:%S'), nanos % 1e9);
return '{}_{:09.0f}'.format(dt.strftime('%Y/%m/%d %H:%M:%S'), nanos % 1e9);
class InfiniteTimer():#see https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds
"""A Timer class that does not stop, unless you want it to.""";
def __init__(self, seconds, target, countdown__upperbound):
self._should_continue = False;
self.is_running = False;
self.seconds = seconds;
self.target = target;
self.thread = None;
self.countdown__upperbound=countdown__upperbound;
def _handle_target(self):
self.is_running = True;
self.target();
self.is_running = False;
self._start_timer();
def _start_timer(self):
if self._should_continue: # Code could have been running when cancel was called.;
self.thread = threading.Timer(self.seconds, self._handle_target);
LOGGER.info("self.countdown__upperbound is:%d"%(self.countdown__upperbound));
if(self.countdown__upperbound>0):
self.thread.start();
self.countdown__upperbound-=1;
else:
self._should_continue=False;
def start(self):
if not self._should_continue and not self.is_running:
self._should_continue = True;
self._start_timer();
else:
print("Timer already started or running, please wait if you're restarting.");
def cancel(self):
if self.thread is not None:
self._should_continue = False # Just in case thread is running and cancel fails.;
self.thread.cancel();
else:
print("Timer never started or failed to initialize.");
from xml.sax import make_parser
from xml.sax.handler import feature_namespaces
if __name__ == '__main__':
task_formulation_timestamp=None;#datetime.datetime.strptime('20180910_135822_123456', '%Y%m%d_%H%M%S_%f');
task_formulation_timestamp_str=None;#'20180910_135822_123456';
working_dir_file_name=None;
src_csv_dataset_file_name=None;
dest_csv_dataset_dir_name=None;
count_of_workers=1;
usage="usage: %prog [options] arg1 [[arg2]..]"
version="version: 0.001"
import argparse;
parser=argparse.ArgumentParser();
try:
parser.add_argument("-t","--task_formulation_timestamp_str",action="append",type=str,dest="op__task_formulation_timestamp_str",help="""
This variable will contain the current timestamp in 'Ymd_HMS_f' format, for example '20180910_135822_123456'. This timestamp will be the bases of the task id of this job.
""");
parser.add_argument("-o","--working_dir_file_name",action="append",type=str,dest="op__working_dir_file_name",help="""
The full path to the directory where temporary data will be written.
""");
parser.add_argument("-f","--src_csv_dataset_file_name",action="append",type=str,dest="op__src_csv_dataset_file_name",help="The full path to the CSV file where the input dataset is to be found.")
parser.add_argument("-d","--dest_csv_dataset_dir_name",action="append",type=str,dest="op__dest_csv_dataset_dir_name",help="The full directory path where the resultant CSV file will be written.")
parser.add_argument("-w","--count_of_workers",action="append",type=int,dest="op__count_of_workers",help="""
The count of workers to launch (via multiprocessing).
""");
(options)=parser.parse_args(sys.argv[1:])
if len(sys.argv)<4:
parser.error("""
ERROR: Missing required arguments
-t, --task_formulation_timestamp_str
This variable will contain the current timestamp in 'Ymd_HMS_f' format, for example '20180910_135822_123456'. This timestamp will be the bases of the task id of this job.
-o, --working_dir_file_name
The full path to the directory where temporary data will be written.
-f, --src_csv_dataset_file_name
The full path to the CSV file where the input dataset is to be found.
-d, --dest_csv_dataset_dir_name
The full directory path where the resultant CSV file will be written.
-w, --count_of_workers
The count of workers to launch (via multiprocessing).
""");
if(options.op__task_formulation_timestamp_str):
task_formulation_timestamp_str=options.op__task_formulation_timestamp_str[0].strip();
if(options.op__working_dir_file_name):
working_dir_file_name=options.op__working_dir_file_name[0].strip();
if(options.op__src_csv_dataset_file_name):
src_csv_dataset_file_name=options.op__src_csv_dataset_file_name[0];
if(options.op__dest_csv_dataset_dir_name):
dest_csv_dataset_dir_name=options.op__dest_csv_dataset_dir_name[0];
mkdir_p(os.path.abspath(os.path.join(dest_csv_dataset_dir_name, os.pardir)));
mkdir_p(os.path.abspath(dest_csv_dataset_dir_name));
if(options.op__count_of_workers):
count_of_workers=int(options.op__count_of_workers[0]);
#parser.destroy()
except argparse.ArgumentError:
#print help infor and exit
usage()
sys.exit(2)
print("dest_csv_dataset_dir_name is:'%s'"%(dest_csv_dataset_dir_name));
#print("dest_ddl_file_name is:'%s'"%(dest_ddl_file_name));
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT);
task_formulation_timestamp=None;
if(task_formulation_timestamp_str!=None and len(task_formulation_timestamp_str)>0):
task_formulation_timestamp=datetime.datetime.strptime(task_formulation_timestamp_str, '%Y%m%d_%H%M%S_%f');
else:
task_formulation_timestamp=datetime.datetime.now();
task_id="%s"%(task_formulation_timestamp.strftime('%Y-%m-%d_%H%M%S_%f')[:-3]);#import datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-1]
hostname=socket.gethostname().strip();
ipAddress=getLocalIPAddress();
pid=os.getpid();
worker_id='%s_%s_%d'%(hostname,ipAddress,pid);
LOGGER.info(" '%s', -------------- hostname:'%s', ipAddress:'%s', pid:%d, worker_id:'%s', task_id:'%s'"%(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),hostname,ipAddress,pid,worker_id,task_id));
LOGGER.info(" '%s', -------------- src_csv_dataset_file_name is:'%s'"%(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),src_csv_dataset_file_name));
LOGGER.info(" '%s', -------------- dest_csv_dataset_dir_name is:'%s'"%(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),dest_csv_dataset_dir_name));
LOGGER.info(" '%s', -------------- count_of_workers is:'%s'"%(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),count_of_workers));
process_list=[];
queue_list=[];#this array will contain objects of multiprocessing.Queue (which is a near clone of queue.Queue)
worker_list=[];
try:
for i in range(count_of_workers):
#Instantiates the thread
#(i) dos not make a sequence, so we use (i,)
worker_id2='%s__%s__%d'%('BORG_DDIEM__parse_clinical_logs_CSV',worker_id,i);
LOGGER.info(">>>>>>>>>>worker_tag:'%s'"%(worker_id2));
worker_number=i;
w=BORG_DDIEM__parse_clinical_logs_CSV(
hostname,ipAddress,pid
,task_id
,task_formulation_timestamp
,worker_id2
,worker_number
,working_dir_file_name
,src_csv_dataset_file_name
,"%s"%(dest_csv_dataset_dir_name)
);
"""
t=threading.Thread(
target=run_BORG_DDIEM__parse_clinical_logs_CSV
,args=(
d
,worker_id2
)
);
thread_list.append(t);
worker_list.append(d);
"""
q=multiprocessing.Queue();
p=multiprocessing.Process(
target=run_BORG_DDIEM__parse_clinical_logs_CSV
,args=(
w
,q
,worker_id2
)
);
process_list.append(p);
queue_list.append(q);
worker_list.append(w);
for process in process_list:
process.start();
#block the current process till join() returns
#for process in process_list:
for i,process in enumerate(process_list):
cont=True;
while(cont):
#LOGGER.info("============Looping, i is:%d, process_list[%d].isAlive() is:'%s'"%(i,i,process_list[i].isAlive()));
process.join(60);#wait for 60 seconds.
if(process.is_alive()):
#timout occurred on process
cont=True;
#LOGGER.info("timeout occurred on process:'%s'."%(worker_list[i].worker_id));
#worker_list[i].stop();
#worker_list[i].some_function();
else:
cont=False;
#LOGGER.info("execution completes for process:'%s'."%(worker_list[i].consumer_tag));
for i,worker in enumerate(worker_list):
pass;
"""
""";
#processing_outcome__dict=worker_list[i]._processing_outcome__dict;
#processing_outcome__dict=worker_list[i].get_processing_outcome();
processing_outcome__dict=queue_list[i].get();
#LOGGER.info("[=]%s, %s"%(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),json.dumps(processing_outcome__dict,indent=4)));
LOGGER.info("processing_outcome__dict is:'%s'"%(json.dumps(processing_outcome__dict,indent=4)));
worker_list[i]=None;
worker=None;
except KeyboardInterrupt:
for i,worker in enumerate(worker_list):
pass;
"""
""";
#cleanup
#worker.cleanup();
if(worker_list[i]!=None):
worker_list[i].stop();
processing_outcome__dict=worker_list[i]._processing_outcome__dict;
worker_list[i]=None;
worker=None;
worker_list=None;
queue_list=None;
process_list=None;
"""
except Exception as error:
LOGGER.error("An error has been detected. Reason:'%s'"%(error));
worker_list=None;
thread_list=None;
"""
worker_list=None;
queue_list=None;
process_list=None;
|
<filename>scriptsForPreprocessing/crete_mask_manual.py
import os, json
import random
import cv2
import numpy as np
from PIL import Image, ImageDraw
def random_color():
levels = range(32, 256, 32)
return tuple(random.choice(levels) for _ in range(3))
points = []
cropping = False
def click_and_crop(event, x, y, flags, param):
global points, cropping
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being
# performed
if event == cv2.EVENT_LBUTTONDOWN:
cropping = True
# check to see if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
cropping = False
# record the ending (x, y) coordinates and indicate that
# the cropping operation is finished
refPt.append((x, y))
# import data
path_to_json = r'resources/fishial/train/via_region_data.json'
# path to augmented dataset
path_to_aug_dataset = r'resources/fishial/train'
json_tmp = json.load(open(path_to_json))
unique_img_array = []
while len(json_tmp) != 0:
keys = list(json_tmp.keys())
single_img = [json_tmp[keys[len(keys) - 1]]]
img_name = json_tmp[keys[len(keys) - 1]]['filename']
del json_tmp[keys[len(keys) - 1]]
for idx in range(len(json_tmp) - 1, -1, -1):
if json_tmp[keys[idx]]['filename'] == img_name:
single_img.append(json_tmp[keys[idx]])
del json_tmp[keys[idx]]
unique_img_array.append(single_img)
# create folder for augumented dataset !
os.makedirs(path_to_aug_dataset, exist_ok=True)
result_dict = {}
for leave, i in enumerate(unique_img_array):
print("Score: ", len(unique_img_array) - leave, len(result_dict))
img_main = os.path.join(path_to_aug_dataset, i[0]['filename'])
image = cv2.imread(img_main)
h, w, _ = image.shape
dst = image.copy()
mask_general = np.zeros((h, w))
print("Genreal: ", mask_general.shape)
for idx_, i_idx in enumerate(i):
color = random_color()
polygon_calc = []
for polygon_idx in range(len(i_idx['regions']['0']['shape_attributes']['all_points_x'])):
polygon_calc.append((i_idx['regions']['0']['shape_attributes']['all_points_x'][polygon_idx],
i_idx['regions']['0']['shape_attributes']['all_points_y'][polygon_idx]))
if len(polygon_calc) < 8: continue
img = Image.new('L', (w, h), 0)
ImageDraw.Draw(img).polygon(list(map(tuple, polygon_calc)), outline=1, fill=255)
tmp_mask = np.array(img)
mask_general = cv2.addWeighted(tmp_mask, 1, mask_general, 1, 0, dtype=cv2.CV_8UC1)
cv2.rectangle(dst, (min(i_idx['regions']['0']['shape_attributes']['all_points_x']),
min(i_idx['regions']['0']['shape_attributes']['all_points_y'])),
(max(i_idx['regions']['0']['shape_attributes']['all_points_x']),
max(i_idx['regions']['0']['shape_attributes']['all_points_y'])), color, 3)
mask_stack = np.dstack([mask_general] * 3)
mask_stack_arr = np.asarray(mask_stack)
dst = cv2.addWeighted(dst, 0.5, mask_stack_arr, 0.5, 0, dtype=cv2.CV_8UC3)
cv2.namedWindow("img")
cv2.setMouseCallback("img", click_and_crop)
points = []
# keep looping until the 'q' key is pressed
while True:
# display the image and wait for a keypress
cv2.imshow("img", dst)
key = cv2.waitKey(1) & 0xFF
# if the 'r' key is pressed, reset the cropping region
if key == ord("r"):
print("You press r")
elif key == 32:
break
# if the 'c' key is pressed, break from the loop
elif key == ord("c"):
break
if cropping:
if len(points)==1:
cv2.circle(dst, (int(points[0][0]), int(points[0][1])), 2, (0, 255, 0), -1)
elif len(points) > 1:
cv2.circle(dst, (int(points[len(points) - 1][0]),
int(points[len(points) - 1][1])), 2, (0, 255, 0), -1)
cv2.line(dst, (int(points[len(points) - 2][0]),
int(points[len(points) - 2][1])),
(int(points[len(points) - 1][0]),
int(points[len(points) - 1][1])), (0, 255, 0), thickness=2)
cv2.imshow("img", dst)
cropping = False
# if there are two reference points, then crop the region of interest
# from teh image and display it
if len(points) > 3:
print("Polygon: {} point: {}".format(len(points), points))
|
person_1 organizing case ; each had books . she had shelves ; she have total ?
person_1 halt momentum ; each halt momentum . she halt momentum ; she halt total ?
person_1 thick case ; each thick books . she thick shelves ; she have total ?
person_1 activated shield ; each had nothing . we activated shelves ; we activated total ?
person_1 conducting person_1 ; each conducting search . they conducting person_1 ; ships have total ?
person_1 organizing case ; each gotten books . ships had shelves ; she have total ?
person_1 enough case ; each outrun books . she talking shelves ; she outrun total ?
person_1 organizing case ; each had books . she had shelves ; starships standing total ?
person_1 period case ; each period books . spaceships period victory ; it have total ?
person_1 taking case ; each taking number_2 . she attack destroyer ; fighters have total ?
person_1 organizing case ; each near books . ships looks shelves ; that looks total ?
person_1 see case ; each see books . battlecruisers see largest ; she surround total ?
person_1 organizing scan ; each completed books . she completed scan ; it have total ?
person_1 organizing case ; each had books . she had shelves ; force you total ?
person_1 spot ships ; each had books . she spot shelves ; she spot total ?
person_1 appear display ; each had books . flashes had shelves ; flashes have total ?
person_1 organizing case ; each explodes books . she explodes shelves ; she explodes total ?
person_1 organizing han ; each leads books . chewie looks shelves ; chewie looks total ?
person_1 organizing case ; each had books . ship had shelves ; avenger aware total ?
person_1 coming 'em ; each charge 'em . she coming shelves ; she have total ?
person_1 organizing case ; each spots books . chewbacca spots shelves ; chewbacca spots total ?
person_1 have case ; each had ships . we have ships ; she have total ?
person_1 organizing case ; each pelt exteriors . number_1 explodes exteriors ; she have total ?
person_1 assemble case ; each had books . she leave shelves ; carriers leave total ?
person_1 gracing case ; each roll books . she gracing lips ; signalman directs total ?
person_1 count ships ; each evading books . she had ships ; we count total ?
person_1 organizing ships ; each had books . she had shelves ; she approaching total ?
person_1 organizing case ; each had books . she had shelves ; sir coming total ?
person_1 keep case ; each are distance . she are distance ; she are total ?
person_1 playing game ; she finds . she found treasures ; number_1 be what ?
person_1 halt momentum ; she finds . lights flashing momentum ; number_1 be what ?
person_1 thick game ; air finds . she thick treasures ; number_1 thick what ?
person_1 playing nothing ; she finds . she found nothing ; number_1 activated what ?
person_1 conducting game ; she finds . she found search ; number_1 estimate person_1 ?
person_1 path game ; you finds . you found treasures ; number_1 gotten what ?
person_1 outrun game ; she talking . she outrun starships ; number_1 talking what ?
person_1 standing game ; she standing . starships found treasures ; number_1 disappears what ?
person_1 playing victory ; she finds . she period victory ; number_1 won what ?
person_1 playing destroyer ; fighters taking . she taking destroyer ; number_1 taking number_2 ?
person_1 looks game ; ships looks . she near treasures ; number_1 looks what ?
person_1 see largest ; battleships finds . battlecruisers see largest ; number_1 see largest ?
person_1 side scan ; she completed . she completed scan ; number_1 be what ?
person_1 you game ; she you . force you treasures ; number_1 man ships ?
person_1 playing game ; she spot . she spot treasures ; number_1 spot ships ?
person_1 creating display ; flashes creating . flashes found display ; number_1 appear what ?
person_1 playing game ; she continue . she found treasures ; number_1 explodes what ?
person_1 face han ; chewie face . chewie face han ; number_1 face what ?
person_1 glides game ; ship aware . avenger found treasures ; number_1 aware what ?
person_1 charge game ; we finds . she found 'em ; number_1 be guns ?
person_1 spots game ; she spots . she found treasures ; number_1 spots what ?
person_1 playing game ; we have . we have treasures ; number_1 have ships ?
person_1 playing game ; she finds . number_1 explodes treasures ; number_1 explodes exteriors ?
person_1 leave game ; carriers leave . she found treasures ; number_1 be what ?
person_1 roll lips ; signalman finds . shields directs treasures ; number_1 directs what ?
person_1 playing game ; she count . they found turbo-lasers ; number_1 be ships ?
person_1 playing ships ; she finds . she approaching treasures ; number_1 be ships ?
person_1 playing game ; sir coming . she coming treasures ; number_1 be what ?
person_1 keep distance ; lot keep . she are treasures ; number_1 be distance ?
person_1 unboxing some . she found boxes ; mittens were . person_1 have total ?
person_1 unboxing momentum . lights flashing boxes ; lights halt . person_1 halt total ?
person_1 unboxing some . she found boxes ; mittens thick . person_1 have total ?
person_1 activated some . she found boxes ; mittens activated . person_1 activated total ?
person_1 reached search . ships found person_1 ; mittens conducting . person_1 conducting total ?
person_1 unboxing some . she gotten boxes ; you were . person_1 have total ?
person_1 outrun starships . she enough boxes ; i talking . person_1 have total ?
person_1 disappears some . all standing boxes ; all standing . person_1 have total ?
person_1 period some . spaceships found boxes ; it were . person_1 period total ?
person_1 unboxing some . she attack destroyer ; fighters attack . person_1 taking total ?
person_1 near some . ships near boxes ; mittens looks . person_1 looks total ?
person_1 unboxing some . battlecruisers found boxes ; battlecruisers fly . person_1 fly total ?
person_1 completed some . ships completed scan ; it side . person_1 have total ?
person_1 unboxing some . she found boxes ; force were . person_1 you total ?
person_1 spot ships . she found boxes ; mittens were . person_1 have total ?
person_1 creating star . she appear star ; flashes were . person_1 creating total ?
person_1 explodes some . ships found boxes ; mittens continue . person_1 explodes total ?
person_1 face some . which face threepio ; which were . person_1 have total ?
person_1 aware some . she aware boxes ; avenger were . person_1 aware total ?
person_1 charge 'em . she found boxes ; we coming . person_1 hold total ?
person_1 spots barks . she found boxes ; chewbacca spots . person_1 spots total ?
person_1 unboxing ships . she found boxes ; we have . person_1 have total ?
person_1 explodes some . she explodes exteriors ; mittens pelt . person_1 explodes total ?
person_1 unboxing some . she assemble boxes ; ships leave . person_1 assemble total ?
person_1 roll ships . shields directs ships ; signalman directs . person_1 gracing total ?
person_1 unboxing turbo-lasers . she count turbo-lasers ; they were . person_1 count total ?
person_1 unboxing ships . she found ships ; mittens approaching . person_1 approaching total ?
person_1 coming some . sir found boxes ; sir were . person_1 coming total ?
person_1 keep some . lot keep distance ; lot are . person_1 keep total ?
waiter had tables ; he waiting . customers total ; waiter have ?
lights had tables ; he flashing . customers total ; waiter have ?
waiter thick tables ; air thick . air total ; waiter have ?
waiter had nothing ; we activated . we total ; we activated ?
they conducting person_1 ; they estimate . they total ; waiter estimate ?
ships gotten tables ; he waiting . you total ; waiter have ?
waiter enough tables ; he waiting . i total ; i have ?
all disappears tables ; all standing . all total ; all standing ?
spaceships had victory ; spaceships waiting . customers total ; spaceships have ?
fighters had tables ; fighters waiting . fighters total ; waiter attack ?
waiter had tables ; he waiting . that total ; that have ?
battleships fly largest ; battleships see . eye total ; waiter see ?
it completed tables ; it completed . ships total ; ships side ?
force you tables ; force waiting . force total ; force man ?
waiter spot tables ; he spot . customers total ; waiter have ?
waiter appear star ; flashes leaving . flashes total ; flashes creating ?
ships explodes tables ; he waiting . customers total ; ships continue ?
chewie looks threepio ; chewie looks . customers total ; waiter face ?
vader glides tables ; ship moves . customers total ; ship glides ?
waiter charge guns ; i hold . we total ; i have ?
waiter spots tables ; he spots . customers total ; chewbacca have ?
waiter had ships ; we waiting . we total ; waiter have ?
waiter had exteriors ; number_1 waiting . customers total ; waiter have ?
waiter assemble tables ; carriers assemble . carriers total ; waiter leave ?
signalman gracing tables ; he roll . customers total ; shields directs ?
they evading tables ; he evading . they total ; they evading ?
waiter had ships ; he waiting . customers total ; waiter approaching ?
waiter had tables ; sir waiting . sir total ; waiter have ?
waiter had distance ; he waiting . customers total ; lot have ?
store has cages . cage has parakeets ; store have total ?
lights flashing momentum . cage flashing parakeets ; store halt total ?
store thick cages . cage has parakeets ; store have total ?
store has cages . cage has shield ; we had total ?
ships reached search . cage reached person_1 ; they estimate total ?
ships gotten cages . ships path parakeets ; you have total ?
store has starships . i enough starships ; store have total ?
starships standing cages . cage standing parakeets ; store have total ?
it has cages . cage period parakeets ; it won total ?
fighters attack cages . cage has number_2 ; fighters taking total ?
store near cages . cage looks parakeets ; that looks total ?
store has cages . battlecruisers fly parakeets ; battleships have total ?
store side cages . it completed scan ; it side total ?
force man cages . cage man parakeets ; store you total ?
store spot ships . cage spot parakeets ; store spot total ?
store appear star . cage creating display ; store leaving total ?
ships explodes cages . ships explodes parakeets ; store explodes total ?
store face threepio . chewie has han ; store have total ?
store glides cages . avenger glides parakeets ; avenger glides total ?
we hold cages . we hold parakeets ; store have total ?
chewbacca has cages . chewbacca spots barks ; chewbacca have total ?
store have cages . we have parakeets ; we have total ?
number_1 pelt cages . number_1 explodes parakeets ; store pelt total ?
ships assemble cages . ships leave parakeets ; carriers have total ?
signalman has lips . cage roll ships ; shields gracing total ?
we evading turbo-lasers . they evading parakeets ; we evading total ?
store has cages . cage has ships ; store have total ?
sir has cages . sir has parakeets ; store have total ?
store has cages . lot are parakeets ; lot keep total ?
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# #
# Copyright (c) 2002-2019 Prof. <NAME> (<EMAIL>), #
# Prof. <NAME> (<EMAIL>) and the RMG Team (<EMAIL>) #
# #
# Permission is hereby granted, free of charge, to any person obtaining a #
# copy of this software and associated documentation files (the 'Software'), #
# to deal in the Software without restriction, including without limitation #
# the rights to use, copy, modify, merge, publish, distribute, sublicense, #
# and/or sell copies of the Software, and to permit persons to whom the #
# Software is furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER #
# DEALINGS IN THE SOFTWARE. #
# #
###############################################################################
"""
This script contains unit tests of the :mod:`rmgpy.pdep.network` module.
"""
import unittest
from rmgpy.pdep.network import Network
from rmgpy.pdep.configuration import Configuration
from rmgpy.transport import TransportData
from rmgpy.statmech.translation import Translation, IdealGasTranslation
from rmgpy.statmech.rotation import Rotation, LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor
from rmgpy.statmech.vibration import Vibration, HarmonicOscillator
from rmgpy.statmech.torsion import Torsion, HinderedRotor
from rmgpy.statmech.conformer import Conformer
from rmgpy.species import Species, TransitionState
from rmgpy.reaction import Reaction
from rmgpy.pdep.collision import SingleExponentialDown
################################################################################
class TestNetwork(unittest.TestCase):
"""
Contains unit tests of the :class:`Network` class.
"""
def setUp(self):
"""
A function run before each unit test in this class.
"""
self.nC4H10O = Species(
label = 'n-C4H10O',
conformer = Conformer(
E0 = (-317.807,'kJ/mol'),
modes = [
IdealGasTranslation(mass=(74.07,"g/mol")),
NonlinearRotor(inertia=([41.5091,215.751,233.258],"amu*angstrom^2"), symmetry=1),
HarmonicOscillator(frequencies=([240.915,341.933,500.066,728.41,809.987,833.93,926.308,948.571,1009.3,1031.46,1076,1118.4,1184.66,1251.36,1314.36,1321.42,1381.17,1396.5,1400.54,1448.08,1480.18,1485.34,1492.24,1494.99,1586.16,2949.01,2963.03,2986.19,2988.1,2995.27,3026.03,3049.05,3053.47,3054.83,3778.88],"cm^-1")),
HinderedRotor(inertia=(0.854054,"amu*angstrom^2"), symmetry=1, fourier=([[0.25183,-1.37378,-2.8379,0.0305112,0.0028088], [0.458307,0.542121,-0.599366,-0.00283925,0.0398529]],"kJ/mol")),
HinderedRotor(inertia=(8.79408,"amu*angstrom^2"), symmetry=1, fourier=([[0.26871,-0.59533,-8.15002,-0.294325,-0.145357], [1.1884,0.99479,-0.940416,-0.186538,0.0309834]],"kJ/mol")),
HinderedRotor(inertia=(7.88153,"amu*angstrom^2"), symmetry=1, fourier=([[-4.67373,2.03735,-6.25993,-0.27325,-0.048748], [-0.982845,1.76637,-1.57619,0.474364,-0.000681718]],"kJ/mol")),
HinderedRotor(inertia=(2.81525,"amu*angstrom^2"), symmetry=3, barrier=(2.96807,"kcal/mol")),
],
spinMultiplicity = 1,
opticalIsomers = 1,
),
molecularWeight = (74.07,"g/mol"),
transportData=TransportData(sigma=(5.94, 'angstrom'), epsilon=(559, 'K')),
energyTransferModel = SingleExponentialDown(alpha0=(447.5*0.011962,"kJ/mol"), T0=(300,"K"), n=0.85),
)
self.nC4H8 = Species(
label = 'n-C4H8',
conformer = Conformer(
E0 = (-17.8832,'kJ/mol'),
modes = [
IdealGasTranslation(mass=(56.06,"g/mol")),
NonlinearRotor(inertia=([22.2748,122.4,125.198],"amu*angstrom^2"), symmetry=1),
HarmonicOscillator(frequencies=([308.537,418.67,636.246,788.665,848.906,936.762,979.97,1009.48,1024.22,1082.96,1186.38,1277.55,1307.65,1332.87,1396.67,1439.09,1469.71,1484.45,1493.19,1691.49,2972.12,2994.31,3018.48,3056.87,3062.76,3079.38,3093.54,3174.52],"cm^-1")),
HinderedRotor(inertia=(5.28338,"amu*angstrom^2"), symmetry=1, fourier=([[-0.579364,-0.28241,-4.46469,0.143368,0.126756], [1.01804,-0.494628,-0.00318651,-0.245289,0.193728]],"kJ/mol")),
HinderedRotor(inertia=(2.60818,"amu*angstrom^2"), symmetry=3, fourier=([[0.0400372,0.0301986,-6.4787,-0.0248675,-0.0324753], [0.0312541,0.0538,-0.493785,0.0965968,0.125292]],"kJ/mol")),
],
spinMultiplicity = 1,
opticalIsomers = 1,
),
)
self.H2O = Species(
label = 'H2O',
conformer = Conformer(
E0 = (-269.598,'kJ/mol'),
modes = [
IdealGasTranslation(mass=(18.01,"g/mol")),
NonlinearRotor(inertia=([0.630578,1.15529,1.78586],"amu*angstrom^2"), symmetry=2),
HarmonicOscillator(frequencies=([1622.09,3771.85,3867.85],"cm^-1")),
],
spinMultiplicity = 1,
opticalIsomers = 1,
),
)
self.N2 = Species(
label = 'N2',
molecularWeight = (28.04,"g/mol"),
transportData=TransportData(sigma=(3.41, "angstrom"), epsilon=(124, "K")),
energyTransferModel = None,
)
self.TS = TransitionState(
label = 'TS',
conformer = Conformer(
E0 = (-42.4373,"kJ/mol"),
modes = [
IdealGasTranslation(mass=(74.07,"g/mol")),
NonlinearRotor(inertia=([40.518,232.666,246.092],"u*angstrom**2"), symmetry=1, quantum=False),
HarmonicOscillator(frequencies=([134.289,302.326,351.792,407.986,443.419,583.988,699.001,766.1,777.969,829.671,949.753,994.731,1013.59,1073.98,1103.79,1171.89,1225.91,1280.67,1335.08,1373.9,1392.32,1417.43,1469.51,1481.61,1490.16,1503.73,1573.16,2972.85,2984.3,3003.67,3045.78,3051.77,3082.37,3090.44,3190.73,3708.52],"kayser")),
HinderedRotor(inertia=(2.68206,"amu*angstrom^2"), symmetry=3, barrier=(3.35244,"kcal/mol")),
HinderedRotor(inertia=(9.77669,"amu*angstrom^2"), symmetry=1, fourier=([[0.208938,-1.55291,-4.05398,-0.105798,-0.104752], [2.00518,-0.020767,-0.333595,0.137791,-0.274578]],"kJ/mol")),
],
spinMultiplicity = 1,
opticalIsomers = 1,
),
frequency=(-2038.34,'cm^-1'),
)
self.reaction = Reaction(
label = 'dehydration',
reactants = [self.nC4H10O],
products = [self.nC4H8, self.H2O],
transitionState = self.TS,
)
self.network = Network(
label = 'n-butanol',
isomers = [Configuration(self.nC4H10O)],
reactants = [],
products = [Configuration(self.nC4H8, self.H2O)],
pathReactions = [self.reaction],
bathGas = {self.N2: 1.0},
)
def test_label(self):
"""
Test that the network `label` property was properly set.
"""
self.assertEqual('n-butanol', self.network.label)
def test_isomers(self):
"""
Test that the network `isomers` property was properly set.
"""
self.assertEqual(1, len(self.network.isomers))
self.assertEqual(1, self.network.Nisom)
def test_reactants(self):
"""
Test that the network `reactants` property was properly set.
"""
self.assertEqual(0, len(self.network.reactants))
self.assertEqual(0, self.network.Nreac)
def test_products(self):
"""
Test that the network `products` property was properly set.
"""
self.assertEqual(1, len(self.network.products))
self.assertEqual(1, self.network.Nprod)
def test_pathReactions(self):
"""
Test that the network `pathReactions` property was properly set.
"""
self.assertEqual(1, len(self.network.pathReactions))
def test_bathGas(self):
"""
Test that the network `bathGas` property was properly set.
"""
self.assertEqual(1, len(self.network.bathGas))
self.assertTrue(self.N2 in self.network.bathGas)
def test_netReactions(self):
"""
Test that the network `netReactions` property was properly set.
"""
self.assertEqual(0, len(self.network.netReactions))
def test_repr(self):
"""
Test that the `repr` representation contains desired properties.
"""
output = repr(self.network)
# ensure species strings
labels = ['dehydration','H2O','N2','TS','n-C4H8','n-C4H10O']
for label in labels:
self.assertIn(label, output)
# ensure classes are used as well
attributes = ['Configuration','Network','Species','Conformer','NonlinearRotor',
'HarmonicOscillator','frequencies','TransportData',
'molecularWeight','SingleExponentialDown']
for label in attributes:
self.assertIn(label, output)
def test_str(self):
"""
Test that the string representation contains desired properties.
"""
output = str(self.network)
# ensure species strings
labels = ['dehydration','H2O','N2','n-C4H8','n-C4H10O']
for label in labels:
self.assertIn(label, output)
# ensure this extra fluff is not in Network string
attributes = ['Configuration','Species','Conformer','Molecule','NonlinearRotor',
'HarmonicOscillator','frequencies','spinMultiplicity','TransportData',
'molecularWeight','SingleExponentialDown']
for label in attributes:
self.assertNotIn(label, output)
def test_collisionMatrixMemoryHandling(self):
net = Network()
net.Elist = [1]*10000
net.E0 = 1.0
niso = 100000000
net.isomers = niso*[1]
try:
net.calculateCollisionModel()
except MemoryError:
raise AssertionError('Large collision matrix resulted in memory error, handling failed')
except:
pass
################################################################################
if __name__ == '__main__':
unittest.main(testRunner=unittest.TextTestRunner(verbosity=2))
|
<filename>src/py/test_day4_giant_squid.py
def part1(inp):
drawn_numbers = [int(x) for x in inp.pop(0).split(",")]
boards = []
for i in range(len(inp) // 6):
inp.pop(0)
board = [[int(x) for x in inp.pop(0).split()] for j in range(5)]
boards.append(board)
for num in drawn_numbers:
for board in boards:
mark_board(board, num)
if check_for_win(board):
return num * sum(
[sum(x for x in board[i][:] if x != -1) for i in range(len(board))]
)
def part2(inp):
drawn_numbers = [int(x) for x in inp.pop(0).split(",")]
boards = []
for i in range(len(inp) // 6):
inp.pop(0)
board = [[int(x) for x in inp.pop(0).split()] for j in range(5)]
boards.append(board)
boards_won = set()
for num in drawn_numbers:
for i, board in enumerate(boards):
if i in boards_won:
continue
mark_board(board, num)
if check_for_win(board):
boards_won.add(i)
if len(boards_won) == len(boards):
return num * sum(
[sum(x for x in board[i][:] if x != -1) for i in range(len(board))]
)
def mark_board(board, num):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == num:
board[i][j] = -1
def check_for_win(board):
for row in board:
if all(x == -1 for x in row):
return True
for col in range(len(board[0])):
if all(board[i][col] == -1 for i in range(len(board))):
return True
return False
# def part2(inp):
def test_check_for_win():
board = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[-1, -1, -1, -1],
[1, 2, 3, 4],
]
assert check_for_win(board) is True
board[2] = [1, 1, 1, 1]
assert check_for_win(board) is False
board[0][1] = -1
board[1][1] = -1
board[2][1] = -1
board[3][1] = -1
assert check_for_win(board) is True
def test_day4_sample():
with open("/Users/sep/CLionProjects/aoc-2021/src/test_files/day4_sample.txt") as f:
inp = [s.rstrip("\n").lstrip() for s in f.readlines()]
assert part1(inp) == 4512
def test_day4_submission():
with open(
"/Users/sep/CLionProjects/aoc-2021/src/test_files/day4_submission.txt"
) as f:
inp = [s.rstrip("\n") for s in f.readlines()]
assert part1(inp) == 16674
def test_day4_part2_sample():
with open("/Users/sep/CLionProjects/aoc-2021/src/test_files/day4_sample.txt") as f:
inp = [s.rstrip("\n") for s in f.readlines()]
assert part2(inp) == 1924
def test_day4_part2_submission():
with open(
"/Users/sep/CLionProjects/aoc-2021/src/test_files/day4_submission.txt"
) as f:
inp = [s.rstrip("\n") for s in f.readlines()]
assert part2(inp) == 7075
|
# Copyright 2020 ETH Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
:mod:`scionlab.scion.certs` --- SCION Issuer Certificate and AS certificate creation
====================================================================================
See https://scion.docs.anapaya.net/en/latest/cryptography/certificates.html
Permalink: https://github.com/scionproto/scion/blob/835b3683c6e6bdf2a98750ec3a04137053f7f142/doc/cryptography/certificates.rst
""" # noqa
from cryptography import x509
from cryptography.x509 import ExtensionType
from cryptography.x509.oid import NameOID, ObjectIdentifier
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import ec
from datetime import datetime
from tempfile import NamedTemporaryFile
from typing import List, Tuple, Optional, NamedTuple
from scionlab.scion.pkicommand import run_scion_pki
OID_ISD_AS = ObjectIdentifier('1.3.6.1.4.1.55324.1.2.1')
OID_SENSITIVE_KEY = ObjectIdentifier('1.3.6.1.4.1.55324.1.3.1')
OID_REGULAR_KEY = ObjectIdentifier('1.3.6.1.4.1.55324.1.3.2')
OID_ROOT_KEY = ObjectIdentifier('1.3.6.1.4.1.55324.1.3.3') # ca root key
CN_VOTING_SENSITIVE = 'Sensitive Voting Certificate'
CN_VOTING_REGULAR = 'Regular Voting Certificate'
CN_ISSUER_ROOT = 'High Security Root Certificate'
CN_ISSUER_CA = 'Secure CA Certificate'
CN_AS = 'AS Certificate'
class Extension(NamedTuple):
extension: ExtensionType
critical: bool
# some type aliases:
Name = List[Tuple[ObjectIdentifier, str]]
Extensions = List[Extension]
def encode_certificate(cert: x509.Certificate) -> str:
return cert.public_bytes(serialization.Encoding.PEM).decode("ascii")
def decode_certificate(pem: str) -> x509.Certificate:
return x509.load_pem_x509_certificate(pem.encode("ascii"))
def verify_certificate_valid(cert: str, cert_usage: str):
"""
Verifies that the certificate's fields are valid for that type.
The certificate is passed as a PEM string.
This function does not verify the trust chain
(see also verify_cp_as_chain).
"""
with NamedTemporaryFile('w', suffix=".crt") as f:
f.write(cert)
f.flush()
_run_scion_pki_certificate('validate', '--type', cert_usage, '--check-time', f.name)
def verify_cp_as_chain(cert: str, trc: bytes):
"""
Verify that the certificate is valid, using the last TRC as anchor.
The certificate is passed as a PEM string.
The TRC is passed as bytes, basee 64 format.
Raises ScionPkiError if the certificate is not valid.
"""
with NamedTemporaryFile(mode='wb', suffix=".trc") as trc_file,\
NamedTemporaryFile(mode='wt', suffix=".pem") as cert_file:
files = [trc_file, cert_file]
for f, value in zip(files, [trc, cert]):
f.write(value)
f.flush()
_run_scion_pki_certificate('verify', '--trc', trc_file.name, cert_file.name)
def generate_voting_sensitive_certificate(subject_id: str,
subject_key: ec.EllipticCurvePrivateKey,
not_before: datetime,
not_after: datetime) -> x509.Certificate:
subject = (subject_key, _create_name(subject_id, CN_VOTING_SENSITIVE))
return _build_certificate(subject=subject,
issuer=None,
not_before=not_before,
not_after=not_after,
extensions=_build_extensions_voting(subject_key, OID_SENSITIVE_KEY))
def generate_voting_regular_certificate(subject_id: str,
subject_key: ec.EllipticCurvePrivateKey,
not_before: datetime,
not_after: datetime) -> x509.Certificate:
subject = (subject_key, _create_name(subject_id, CN_VOTING_REGULAR))
return _build_certificate(subject=subject,
issuer=None,
not_before=not_before,
not_after=not_after,
extensions=_build_extensions_voting(subject_key, OID_REGULAR_KEY))
def generate_issuer_root_certificate(subject_id: str,
subject_key: ec.EllipticCurvePrivateKey,
not_before: datetime,
not_after: datetime) -> x509.Certificate:
"""
Generates an issuer root certificate. Issuer Root Certificates are used to sign CA certificates.
"""
subject = (subject_key, _create_name(subject_id, CN_ISSUER_ROOT))
return _build_certificate(subject=subject,
issuer=None,
not_before=not_before,
not_after=not_after,
extensions=_build_extensions_root(subject_key))
def generate_issuer_ca_certificate(subject_id: str,
subject_key: ec.EllipticCurvePrivateKey,
issuer_id: str,
issuer_key: ec.EllipticCurvePrivateKey,
not_before: datetime,
not_after: datetime) -> x509.Certificate:
"""
Generates an issuer CA certificate.
CA certificates are used to sign AS certificates.
CA certificates are signed by Root certificates.
"""
subject = (subject_key, _create_name(subject_id, CN_ISSUER_CA))
issuer = (issuer_key, _create_name(issuer_id, CN_ISSUER_ROOT))
return _build_certificate(subject=subject,
issuer=issuer,
not_before=not_before,
not_after=not_after,
extensions=_build_extensions_ca(subject_key, issuer_key))
def generate_as_certificate(subject_id: str,
subject_key: ec.EllipticCurvePrivateKey,
issuer_id: str,
issuer_key: ec.EllipticCurvePrivateKey,
not_before: datetime,
not_after: datetime) -> x509.Certificate:
subject = (subject_key, _create_name(subject_id, CN_AS))
issuer = (issuer_key, _create_name(issuer_id, CN_ISSUER_CA))
return _build_certificate(subject=subject,
issuer=issuer,
not_before=not_before,
not_after=not_after,
extensions=_build_extensions_as(subject_key, issuer_key))
def _create_name(as_id: str, common_name: str) -> Name:
return [(NameOID.COUNTRY_NAME, 'CH'),
(NameOID.STATE_OR_PROVINCE_NAME, 'ZH'),
(NameOID.LOCALITY_NAME, 'Zürich'),
(NameOID.ORGANIZATION_NAME, 'Netsec'),
(NameOID.ORGANIZATIONAL_UNIT_NAME, 'Netsec'),
(NameOID.COMMON_NAME, f'{as_id} {common_name}'),
(OID_ISD_AS, as_id)]
def _build_certificate(subject: Tuple[ec.EllipticCurvePrivateKey, Name],
issuer: Optional[Tuple[ec.EllipticCurvePrivateKey, Name]],
not_before: datetime,
not_after: datetime,
extensions: Extensions) -> x509.Certificate:
""" Builds a certificate from the parameters. The certificate is signed by the issuer. """
issuer = issuer or subject
subject_name = x509.Name([x509.NameAttribute(p[0], p[1]) for p in subject[1]])
issuer_name = x509.Name([x509.NameAttribute(p[0], p[1]) for p in issuer[1]])
# create certificate builder
cert_builder = x509.CertificateBuilder().subject_name(
subject_name
).issuer_name(
issuer_name
).public_key(
subject[0].public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
not_before
).not_valid_after(
not_after
)
for ext in extensions:
cert_builder = cert_builder.add_extension(ext.extension, ext.critical)
# use the issuer to sign a certificate
return cert_builder.sign(issuer[0], hashes.SHA512())
def _build_extensions_voting(key: ec.EllipticCurvePrivateKey,
issuer_key_type: ObjectIdentifier) -> Extensions:
return [Extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
critical=False),
Extension(x509.ExtendedKeyUsage([issuer_key_type,
x509.ExtendedKeyUsageOID.TIME_STAMPING]),
critical=False)]
def _build_extensions_root(key: ec.EllipticCurvePrivateKey) -> Extensions:
"""
Returns a list of Extension with the extension and its criticality
"""
return [Extension(x509.BasicConstraints(ca=True, path_length=1),
critical=True),
Extension(x509.KeyUsage(digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=True,
crl_sign=True,
encipher_only=False,
decipher_only=False),
critical=True),
Extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
critical=False),
Extension(x509.ExtendedKeyUsage([OID_ROOT_KEY,
x509.ExtendedKeyUsageOID.TIME_STAMPING]),
critical=False)]
def _build_extensions_ca(subject_key: ec.EllipticCurvePrivateKey,
issuer_key: ec.EllipticCurvePrivateKey) -> Extensions:
"""
Returns a list of Extension with the extension and its criticality
"""
return [Extension(x509.BasicConstraints(ca=True, path_length=0),
critical=True),
Extension(x509.KeyUsage(digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=True,
crl_sign=True,
encipher_only=False,
decipher_only=False),
critical=True),
Extension(x509.SubjectKeyIdentifier.from_public_key(subject_key.public_key()),
critical=False),
Extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(issuer_key.public_key()),
critical=False)]
def _build_extensions_as(subject_key: ec.EllipticCurvePrivateKey,
issuer_key: ec.EllipticCurvePrivateKey) -> Extensions:
"""
Returns a list of Extension with the extension and its criticality
"""
return [Extension(x509.KeyUsage(digital_signature=True,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False),
critical=True),
Extension(x509.SubjectKeyIdentifier.from_public_key(subject_key.public_key()),
critical=False),
Extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(issuer_key.public_key()),
critical=False),
Extension(x509.ExtendedKeyUsage([x509.ExtendedKeyUsageOID.SERVER_AUTH,
x509.ExtendedKeyUsageOID.CLIENT_AUTH,
x509.ExtendedKeyUsageOID.TIME_STAMPING]),
critical=False)]
def _run_scion_pki_certificate(*args, cwd=None, check=True):
return run_scion_pki('certificate', *args, cwd=cwd, check=check)
|
import json
import os
from dotenv import load_dotenv
from flask import Flask, render_template, request, redirect, url_for, flash, abort, session
from deta import Deta
from flask_qrcode import QRcode
import requests
app = Flask(__name__)
jdoodle_url = 'https://api.jdoodle.com/v1/execute'
load_dotenv()
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
deta = Deta(os.environ['TOKEN'])
codes = deta.Base("codes")
app.config['SECRET_KEY'] = os.environ['SECRET']
app.register_error_handler(404, page_not_found)
qrcode = QRcode(app)
JDOODLEID = os.environ['JDOODLEID']
JDOODLESECRET = os.environ['JDOODLESECRET']
@app.route('/', methods=["GET", "POST"])
def renderMainPage():
if request.method == 'GET':
return render_template('index.html', baseurl=request.base_url)
else:
codename = request.form['codename']
code = request.form['code']
language = request.form['language']
input = request.form['input']
output = request.form['output']
PIN = ''
pin_enabled = False
if 'customSwitch1' in request.form:
pin_enabled = request.form['customSwitch1'] == 'on'
PIN = request.form['PIN']
else:
pin_enabled = False
executable = False
if 'customSwitch2' in request.form:
executable = request.form['customSwitch2'] == 'on'
else:
executable = False
code_entry = codes.put({
"name": codename,
"code": code,
"pin": PIN,
"pin_enabled": pin_enabled,
"executable": executable,
"input": input,
"output": output,
"language": language,
})
return redirect(url_for('renderSharedCodes', code_id=code_entry['key']))
def updateCodeName(coderes):
if coderes['language'] == 'C':
coderes['name'] = coderes['name'] + '.c'
elif coderes['language'] == 'Java':
coderes['name'] = coderes['name'] + '.java'
elif coderes['language'] == 'C++':
coderes['name'] = coderes['name'] + '.cpp'
elif coderes['language'] == 'Python':
coderes['name'] = coderes['name'] + '.py'
return coderes
@app.route('/<code_id>', methods=['GET', 'POST'])
def renderSharedCodes(code_id):
if request.method == "GET":
print(code_id)
coderes = codes.get(code_id)
print('key' in session)
if coderes is None:
abort(404, description="Resource not found")
elif coderes['pin_enabled']:
if 'key' not in session:
return render_template('auth.html', code_id=code_id, create=True)
else:
session.pop('key', None)
coderes = updateCodeName(coderes)
return render_template('code.html', coderes=coderes, baseurl=request.base_url, create=True)
else:
print(coderes)
coderes = updateCodeName(coderes)
return render_template('code.html', coderes=coderes, baseurl=request.base_url, create=True)
else:
print(code_id)
coderes = codes.get(code_id)
if coderes is None:
abort(404, description="Resource not found")
elif request.form['PIN'] == coderes['pin']:
coderes = updateCodeName(coderes)
session['key'] = code_id
# return render_template('code.html', coderes=coderes, baseurl=request.base_url)
return redirect(url_for('renderSharedCodes', code_id=code_id))
else:
flash('Invalid PIN')
return render_template('auth.html', code_id=code_id, create=True)
# @app.route('/showAll', methods=['GET'])
# def showAllCodeFromDatabase():
# return {"codes": next(codes.fetch({}))}
#
#
# @app.route('/deleteAll', methods=['GET'])
# def deleteAllCodeFromDatabase():
# toDeleteCodes = next(codes.fetch({}))
# for i in toDeleteCodes:
# codes.delete(i['key'])
# return '{"STATUS":"DELETEDALL"}'
#
#
# @app.route('/deleteCode/<key>', methods=["DELETE"])
# def deleteCodeWithKey(key):
# print(key)
# print(codes.delete(key))
# return '{"STATUS":"DELETED"}'
def getExecLanguage(language):
if language == 'C':
return 'c'
elif language == 'Java':
return 'java'
elif language == 'Python':
return 'python3'
elif language == 'C++':
return 'cpp14'
@app.route('/about', methods=['GET'])
def about():
return render_template('about.html')
@app.route('/execute', methods=['POST'])
def execute():
print(request.form)
data = {}
language = getExecLanguage(request.form['language'])
debug = False
if JDOODLEID is None or JDOODLESECRET is None or debug:
return "Setup Proper API"
else:
try:
data['clientId'] = JDOODLEID
data['clientSecret'] = JDOODLESECRET
data['script'] = request.form['code']
data['stdin'] = request.form['input']
data['language'] = language
data['versionIndex'] = 0
output = requests.post(jdoodle_url, json=data).text
print(output)
return json.loads(output)['output'].replace('\n', ' \r\n ')
except:
return "Unknown error occured. Please try again later"
if __name__ == '__main__':
app.run()
|
<gh_stars>1-10
thickarrow_strings = ( # sized 24x24
"XX ",
"XXX ",
"XXXX ",
"XX.XX ",
"XX..XX ",
"XX...XX ",
"XX....XX ",
"XX.....XX ",
"XX......XX ",
"XX.......XX ",
"XX........XX ",
"XX........XXX ",
"XX......XXXXX ",
"XX.XXX..XX ",
"XXXX XX..XX ",
"XX XX..XX ",
" XX..XX ",
" XX..XX ",
" XX..XX ",
" XXXX ",
" XX ",
" ",
" ",
" ",
)
text_no = (" ",
" ",
" XXXXXX ",
" XX......XX ",
" X..........X ",
" X....XXXX....X ",
" X...XX XX...X ",
" X.....X X...X ",
" X..X...X X..X ",
" X...XX...X X...X ",
" X..X X...X X..X ",
" X..X X...X X..X ",
" X..X X.,.X X..X ",
" X..X X...X X..X ",
" X...X X...XX...X ",
" X..X X...X..X ",
" X...X X.....X ",
" X...XX X...X ",
" X....XXXXX...X ",
" X..........X ",
" XX......XX ",
" XXXXXX ",
" ",
" ",
)
text_arrow = ("xX ",
"X.X ",
"X..X ",
"X...X ",
"X....X ",
"X.....X ",
"X......X ",
"X.......X ",
"X........X ",
"X.........X ",
"X..........X ",
"X...X..X....X ",
"X..X X...X ",
"X.X X..X ",
"XX X.X ",
"X XX ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ")
def compile(strings, black='X', white='.', xor='o'):
size = len(strings[0]), len(strings)
if size[0] % 8 or size[1] % 8:
raise ValueError("cursor string sizes must be divisible by 8 %s" %
size)
for s in strings[1:]:
if len(s) != size[0]:
raise ValueError("Cursor strings are inconsistent lengths")
maskdata = []
filldata = []
maskitem = fillitem = 0
step = 8
for s in strings:
for c in s:
maskitem = maskitem << 1
fillitem = fillitem << 1
step = step - 1
if c == black:
maskitem = maskitem | 1
fillitem = fillitem | 1
elif c == white:
maskitem = maskitem | 1
elif c == xor:
fillitem = fillitem | 1
if not step:
maskdata.append(maskitem)
filldata.append(fillitem)
maskitem = fillitem = 0
step = 8
return tuple(filldata), tuple(maskdata)
def load_xbm(curs, mask):
def bitswap(num):
val = 0
for x in range(8):
b = num & (1 << x) != 0
val = val << 1 | b
return val
if type(curs) is type(''):
with open(curs) as cursor_f:
curs = cursor_f.readlines()
else:
curs = curs.readlines()
if type(mask) is type(''):
with open(mask) as mask_f:
mask = mask_f.readlines()
else:
mask = mask.readlines()
# avoid comments
for line in range(len(curs)):
if curs[line].startswith("#define"):
curs = curs[line:]
break
for line in range(len(mask)):
if mask[line].startswith("#define"):
mask = mask[line:]
break
width = int(curs[0].split()[-1])
height = int(curs[1].split()[-1])
if curs[2].startswith('#define'):
hotx = int(curs[2].split()[-1])
hoty = int(curs[3].split()[-1])
else:
hotx = hoty = 0
info = width, height, hotx, hoty
for line in range(len(curs)):
if curs[line].startswith('static char') or curs[line].startswith('static unsigned char'):
break
data = ' '.join(curs[line + 1:]).replace('};', '').replace(',', ' ')
cursdata = []
for x in data.split():
cursdata.append(bitswap(int(x, 16)))
cursdata = tuple(cursdata)
for line in range(len(mask)):
if mask[line].startswith('static char') or mask[line].startswith('static unsigned char'):
break
data = ' '.join(mask[line + 1:]).replace('};', '').replace(',', ' ')
maskdata = []
for x in data.split():
maskdata.append(bitswap(int(x, 16)))
maskdata = tuple(maskdata)
return info[:2], info[2:], cursdata, maskdata
|
import os
from PilotErrors import PilotErrors
from pUtil import tolog, readpar
class DBReleaseHandler:
"""
Methods for handling the DBRelease file and possibly skip it in the input file list
In the presence of $[VO_ATLAS_SW_DIR|OSG_APP]/database, the pilot will use these methods to:
1. Extract the requested DBRelease version from the job parameters string, if present
2. Scan the $[VO_ATLAS_SW_DIR|OSG_APP]/database dir for available DBRelease files
3. If the requested DBRelease file is available, continue [else, abort at this point]
4. Create a DBRelease setup file containing necessary environment variables
5. Create a new DBRelease file only containing the setup file in the input file directory
6. Update the job state file
7. Remove the DBRelease file from the input file list if all previous steps finished correctly
"""
# private data members
__error = PilotErrors() # PilotErrors object
__version = ""
__DBReleaseDir = ""
__filename = "DBRelease-%s.tar.gz"
__setupFilename = "setup.py"
__workdir = ""
def __init__(self, workdir=""):
""" Default initialization """
_path = self.getDBReleaseDir() # _path is a dummy variable
self.__workdir = workdir
def removeDBRelease(self, inputFiles, inFilesGuids, realDatasetsIn, dispatchDblock, dispatchDBlockToken, prodDBlockToken):
""" remove the given DBRelease files from the input file list """
# will only remove the DBRelease files that are already available locally
# identify all DBRelease files in the list (mark all for removal)
# note: multi-trf jobs tend to have the same DBRelease file listed twice
position = 0
positions_list = []
for f in inputFiles:
if "DBRelease" in f:
positions_list.append(position)
tolog("Will remove file %s from input file list" % (f))
position += 1
# remove the corresponding guids, datasets and tokens
for position in positions_list:
try:
del(inputFiles[position])
except Exception, e:
tolog("!!WARNING!!1990!! Could not delete object %d in inFiles: %s" % (position, str(e)))
else:
tolog("Removed item %d in inFiles" % (position))
try:
del(inFilesGuids[position])
except Exception, e:
tolog("!!WARNING!!1990!! Could not delete object %d in inFilesGuids: %s" % (position, str(e)))
else:
tolog("Removed item %d in inFilesGuids" % (position))
try:
del(realDatasetsIn[position])
except Exception, e:
tolog("!!WARNING!!1990!! Could not delete object %d in realDatasetsIn: %s" % (position, str(e)))
else:
tolog("Removed item %d in realDatasetsIn" % (position))
try:
del(dispatchDblock[position])
except Exception, e:
tolog("!!WARNING!!1990!! Could not delete object %d in dispatchDblock: %s" % (position, str(e)))
else:
tolog("Removed item %d in dispatchDblock" % (position))
try:
del(dispatchDBlockToken[position])
except Exception, e:
tolog("!!WARNING!!1990!! Could not delete object %d in dispatchDBlockToken: %s" % (position, str(e)))
else:
tolog("Removed item %d in dispatchDBlockToken" % (position))
try:
del(prodDBlockToken[position])
except Exception, e:
tolog("!!WARNING!!1990!! Could not delete object %d in prodDBlockToken: %s" % (position, str(e)))
else:
tolog("Removed item %d in prodDBlockToken" % (position))
return inputFiles, inFilesGuids, realDatasetsIn, dispatchDblock, dispatchDBlockToken, prodDBlockToken
def extractVersion(self, name):
""" Try to extract the version from the string name """
version = ""
import re
re_v = re.compile('DBRelease-(\d+\.\d+\.\d+)\.tar\.gz')
v = re_v.search(name)
if v:
version = v.group(1)
else:
re_v = re.compile('DBRelease-(\d+\.\d+\.\d+\.\d+)\.tar\.gz')
v = re_v.search(name)
if v:
version = v.group(1)
return version
def getDBReleaseVersion(self, jobPars=""):
""" Get the DBRelease version from the job parameters string """
version = ""
# get the version from the job parameters
if jobPars != "":
version = self.extractVersion(jobPars)
else:
# get the version from private data member (already set earlier)
version = self.__version
return version
def getDBReleaseDir(self):
""" Return the proper DBRelease directory """
if os.environ.has_key('VO_ATLAS_SW_DIR'):
path = os.path.expandvars('$VO_ATLAS_SW_DIR/database/DBRelease')
else:
path = os.path.expandvars('$OSG_APP/database/DBRelease')
if path == "" or path.startswith('OSG_APP'):
tolog("Note: The DBRelease database directory is not available (will not attempt to skip DBRelease stage-in)")
else:
if os.path.exists(path):
tolog("Local DBRelease path verified: %s (will attempt to skip DBRelease stage-in)" % (path))
self.__DBReleaseDir = path
else:
tolog("Note: Local DBRelease path does not exist: %s (will not attempt to skip DBRelease stage-in)" % (path))
path = ""
return path
def isDBReleaseAvailable(self, versionFromJobPars):
""" Check whether a given DBRelease file is already available """
status = False
self.__version = versionFromJobPars
# do not proceed if
if os.environ.has_key('ATLAS_DBREL_DWNLD'):
tolog("ATLAS_DBREL_DWNLD is set: do not skip DBRelease stage-in")
return status
# get the local path to the DBRelease directory
path = self.getDBReleaseDir()
if path != "":
if os.path.exists(path):
# get the list of available DBRelease directories
dir_list = os.listdir(path)
# is the required DBRelease version available?
if dir_list != []:
if self.__version != "":
if self.__version in dir_list:
tolog("Found version %s in path %s (%d releases found)" % (self.__version, path, len(dir_list)))
status = True
else:
tolog("Did not find version %s in path %s (%d releases found)" % (self.__version, path, len(dir_list)))
else:
tolog("Empty directory list: %s" % (path))
return status
def createSetupFile(self, version, path):
""" Create the DBRelease setup file """
status = False
# get the DBRelease directory
d = self.__DBReleaseDir
if d != "" and version != "":
# create the python code string to be written to file
txt = "import os\n"
txt += "os.environ['DBRELEASE'] = '%s'\n" % (version)
txt += "os.environ['DATAPATH'] = '%s/%s:' + os.environ['DATAPATH']\n" % (d, version)
txt += "os.environ['DBRELEASE_REQUIRED'] = '%s'\n" % (version)
txt += "os.environ['DBRELEASE_REQUESTED'] = '%s'\n" % (version)
txt += "os.environ['CORAL_DBLOOKUP_PATH'] = '%s/%s/XMLConfig'\n" % (d, version)
try:
f = open(os.path.join(path, self.__setupFilename), "w")
except OSError, e:
tolog("!!WARNING!!1990!! Failed to create DBRelease %s: %s" % (self.__setupFilename, str(e)))
else:
f.write(txt)
f.close()
tolog("Created setup file with the following content:.................................\n%s" % (txt))
tolog("...............................................................................")
status = True
return status
def mkdirs(self, path, d):
""" Create directory d in path """
status = False
try:
_dir = os.path.join(path, d)
os.makedirs(_dir)
except OSError, e:
tolog("!!WARNING!!1990!! Failed to create directories %s: %s" % (_dir, str(e)))
else:
status = True
return status
def rmdirs(self, path):
""" Remove directory in path """
status = False
try:
from shutil import rmtree
rmtree(path)
except OSError, e:
tolog("!!WARNING!!1990!! Failed to remove directories %s: %s" % (path, str(e)))
else:
status = True
return status
def createDBRelease(self, version, path):
""" Create the DBRelease file only containing a setup file """
status = False
# create the DBRelease and version directories
DBRelease_path = os.path.join(path, 'DBRelease')
if self.mkdirs(DBRelease_path, version):
# create the setup file in the DBRelease directory
version_path = os.path.join(DBRelease_path, version)
if self.createSetupFile(version, version_path):
tolog("Created DBRelease %s in new directory %s" % (self.__setupFilename, version_path))
# now create a new DBRelease tarball
filename = os.path.join(path, self.__filename % (version))
import tarfile
tolog("Attempting to create %s" % (filename))
try:
tar = tarfile.open(filename, "w:gz")
except Exception, e:
tolog("!!WARNING!!1990!! Could not create DBRelease tar file: %s" % str(e))
else:
if tar:
# add the setup file to the tar file
tar.add("%s/DBRelease/%s/%s" % (path, version, self.__setupFilename))
# create the symbolic link DBRelease/current -> 12.2.1
try:
_link = os.path.join(path, "DBRelease/current")
os.symlink(version, _link)
except Exception, e:
tolog("!!WARNING!!1990!! Failed to create symbolic link %s: %s" % (_link, str(e)))
else:
tolog("Created symbolic link %s" % (_link))
# add the symbolic link to the tar file
tar.add(_link)
# done with the tar archive
tar.close()
tolog("Created new DBRelease tar file: %s" % filename)
status = True
else:
tolog("!!WARNING!!1990!! Failed to create DBRelease tar file")
# clean up
if self.rmdirs(DBRelease_path):
tolog("Cleaned up directories in path %s" % (DBRelease_path))
else:
tolog("Failed to create DBRelease %s" % (self.__setupFilename))
if self.rmdirs(DBRelease_path):
tolog("Cleaned up directories in path %s" % (DBRelease_path))
return status
if __name__ == "__main__":
h = DBReleaseHandler()
jobPars="jobParametersInputEvgenFile=EVNT.162766._000363.pool.root.1 OutputHitsFile=6daee77d-1d29-4901-a04e-d532a5e1812f_1.HITS.pool.root MaxEvents=2 SkipEvents=0 RandomSeed=164832 GeometryVersion=ATLAS-GEO-16-00-00 PhysicsList=QGSP_BERT JobConfig=VertexFromCondDB.py,jobConfig.LooperKiller.py,CalHits.py,jobConfig.LucidOn.py DBRelease=DBRelease-12.2.1.tar.gz ConditionsTag=OFLCOND-SDR-BS7T-02 IgnoreConfigError=False AMITag=s932"
version = h.getDBReleaseVersion(jobPars=jobPars)
tolog("Version = %s" % (version))
if h.createDBRelease(version, os.getcwd()):
pass
|
#!/usr/bin/env python3
from argparse import ArgumentParser
from io import StringIO
from enum import Enum, auto
import os.path
import sys
class Cell:
def __init__(self, name, keep=False, port_attrs={}):
self.name = name
self.keep = keep
self.port_attrs = port_attrs
CELLS = [
# Design elements types listed in Xilinx UG953
Cell('BSCANE2', keep=True),
# Cell('BUFG', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFGCE', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFGCE_1', port_attrs={'O': ['clkbuf_driver']}),
#Cell('BUFGCTRL', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFGMUX', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFGMUX_1', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFGMUX_CTRL', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFH', port_attrs={'O': ['clkbuf_driver']}),
#Cell('BUFHCE', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFIO', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFMR', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFMRCE', port_attrs={'O': ['clkbuf_driver']}),
Cell('BUFR', port_attrs={'O': ['clkbuf_driver']}),
Cell('CAPTUREE2', keep=True),
# Cell('CARRY4'),
Cell('CFGLUT5', port_attrs={'CLK': ['clkbuf_sink']}),
Cell('DCIRESET', keep=True),
Cell('DNA_PORT'),
Cell('DSP48E1', port_attrs={'CLK': ['clkbuf_sink']}),
Cell('EFUSE_USR'),
# Cell('FDCE'),
# Cell('FDPE'),
# Cell('FDRE'),
# Cell('FDSE'),
Cell('FIFO18E1', port_attrs={'RDCLK': ['clkbuf_sink'], 'WRCLK': ['clkbuf_sink']}),
Cell('FIFO36E1', port_attrs={'RDCLK': ['clkbuf_sink'], 'WRCLK': ['clkbuf_sink']}),
Cell('FRAME_ECCE2'),
Cell('GTHE2_CHANNEL'),
Cell('GTHE2_COMMON'),
Cell('GTPE2_CHANNEL'),
Cell('GTPE2_COMMON'),
Cell('GTXE2_CHANNEL'),
Cell('GTXE2_COMMON'),
# Cell('IBUF', port_attrs={'I': ['iopad_external_pin']}),
Cell('IBUF_IBUFDISABLE', port_attrs={'I': ['iopad_external_pin']}),
Cell('IBUF_INTERMDISABLE', port_attrs={'I': ['iopad_external_pin']}),
Cell('IBUFDS', port_attrs={'I': ['iopad_external_pin'], 'IB': ['iopad_external_pin']}),
Cell('IBUFDS_DIFF_OUT', port_attrs={'I': ['iopad_external_pin'], 'IB': ['iopad_external_pin']}),
Cell('IBUFDS_DIFF_OUT_IBUFDISABLE', port_attrs={'I': ['iopad_external_pin'], 'IB': ['iopad_external_pin']}),
Cell('IBUFDS_DIFF_OUT_INTERMDISABLE', port_attrs={'I': ['iopad_external_pin'], 'IB': ['iopad_external_pin']}),
Cell('IBUFDS_GTE2', port_attrs={'I': ['iopad_external_pin'], 'IB': ['iopad_external_pin']}),
Cell('IBUFDS_IBUFDISABLE', port_attrs={'I': ['iopad_external_pin'], 'IB': ['iopad_external_pin']}),
Cell('IBUFDS_INTERMDISABLE', port_attrs={'I': ['iopad_external_pin'], 'IB': ['iopad_external_pin']}),
Cell('IBUFG', port_attrs={'I': ['iopad_external_pin']}),
Cell('IBUFGDS', port_attrs={'I': ['iopad_external_pin'], 'IB': ['iopad_external_pin']}),
Cell('IBUFGDS_DIFF_OUT', port_attrs={'I': ['iopad_external_pin'], 'IB': ['iopad_external_pin']}),
Cell('ICAPE2', keep=True),
Cell('IDDR', port_attrs={'C': ['clkbuf_sink']}),
Cell('IDDR_2CLK', port_attrs={'C': ['clkbuf_sink'], 'CB': ['clkbuf_sink']}),
Cell('IDELAYCTRL', keep=True, port_attrs={'REFCLK': ['clkbuf_sink']}),
Cell('IDELAYE2', port_attrs={'C': ['clkbuf_sink']}),
Cell('IN_FIFO', port_attrs={'RDCLK': ['clkbuf_sink'], 'WRCLK': ['clkbuf_sink']}),
Cell('IOBUF', port_attrs={'IO': ['iopad_external_pin']}),
Cell('IOBUF_DCIEN', port_attrs={'IO': ['iopad_external_pin']}),
Cell('IOBUF_INTERMDISABLE', port_attrs={'IO': ['iopad_external_pin']}),
Cell('IOBUFDS', port_attrs={'IO': ['iopad_external_pin']}),
Cell('IOBUFDS_DCIEN', port_attrs={'IO': ['iopad_external_pin'], 'IOB': ['iopad_external_pin']}),
Cell('IOBUFDS_DIFF_OUT', port_attrs={'IO': ['iopad_external_pin'], 'IOB': ['iopad_external_pin']}),
Cell('IOBUFDS_DIFF_OUT_DCIEN', port_attrs={'IO': ['iopad_external_pin'], 'IOB': ['iopad_external_pin']}),
Cell('IOBUFDS_DIFF_OUT_INTERMDISABLE', port_attrs={'IO': ['iopad_external_pin'], 'IOB': ['iopad_external_pin']}),
Cell('ISERDESE2', port_attrs={
'CLK': ['clkbuf_sink'],
'CLKB': ['clkbuf_sink'],
'OCLK': ['clkbuf_sink'],
'OCLKB': ['clkbuf_sink'],
'CLKDIV': ['clkbuf_sink'],
'CLKDIVP': ['clkbuf_sink'],
}),
Cell('KEEPER'),
Cell('LDCE'),
Cell('LDPE'),
# Cell('LUT1'),
# Cell('LUT2'),
# Cell('LUT3'),
# Cell('LUT4'),
# Cell('LUT5'),
# Cell('LUT6'),
#Cell('LUT6_2'),
Cell('MMCME2_ADV'),
Cell('MMCME2_BASE'),
# Cell('MUXF7'),
# Cell('MUXF8'),
# Cell('OBUF', port_attrs={'O': ['iopad_external_pin']}),
Cell('OBUFDS', port_attrs={'O': ['iopad_external_pin'], 'OB': ['iopad_external_pin']}),
Cell('OBUFT', port_attrs={'O': ['iopad_external_pin']}),
Cell('OBUFTDS', port_attrs={'O': ['iopad_external_pin'], 'OB': ['iopad_external_pin']}),
Cell('ODDR', port_attrs={'C': ['clkbuf_sink']}),
Cell('ODELAYE2', port_attrs={'C': ['clkbuf_sink']}),
Cell('OSERDESE2', port_attrs={'CLK': ['clkbuf_sink'], 'CLKDIV': ['clkbuf_sink']}),
Cell('OUT_FIFO', port_attrs={'RDCLK': ['clkbuf_sink'], 'WRCLK': ['clkbuf_sink']}),
Cell('PHASER_IN'),
Cell('PHASER_IN_PHY'),
Cell('PHASER_OUT'),
Cell('PHASER_OUT_PHY'),
Cell('PHASER_REF'),
Cell('PHY_CONTROL'),
Cell('PLLE2_ADV'),
Cell('PLLE2_BASE'),
Cell('PS7', keep=True),
Cell('PULLDOWN'),
Cell('PULLUP'),
#Cell('RAM128X1D', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM128X1S', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM256X1S', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM32M', port_attrs={'WCLK': ['clkbuf_sink']}),
#Cell('RAM32X1D', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM32X1S', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM32X1S_1', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM32X2S', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM64M', port_attrs={'WCLK': ['clkbuf_sink']}),
#Cell('RAM64X1D', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM64X1S', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM64X1S_1', port_attrs={'WCLK': ['clkbuf_sink']}),
Cell('RAM64X2S', port_attrs={'WCLK': ['clkbuf_sink']}),
# Cell('RAMB18E1', port_attrs={'CLKARDCLK': ['clkbuf_sink'], 'CLKBWRCLK': ['clkbuf_sink']}),
# Cell('RAMB36E1', port_attrs={'CLKARDCLK': ['clkbuf_sink'], 'CLKBWRCLK': ['clkbuf_sink']}),
Cell('ROM128X1'),
Cell('ROM256X1'),
Cell('ROM32X1'),
Cell('ROM64X1'),
#Cell('SRL16E', port_attrs={'CLK': ['clkbuf_sink']}),
#Cell('SRLC32E', port_attrs={'CLK': ['clkbuf_sink']}),
Cell('STARTUPE2', keep=True),
Cell('USR_ACCESSE2'),
Cell('XADC'),
]
class State(Enum):
OUTSIDE = auto()
IN_MODULE = auto()
IN_OTHER_MODULE = auto()
IN_FUNCTION = auto()
IN_TASK = auto()
def xtract_cell_decl(cell, dirs, outf):
for dir in dirs:
fname = os.path.join(dir, cell.name + '.v')
try:
with open(fname) as f:
state = State.OUTSIDE
found = False
# Probably the most horrible Verilog "parser" ever written.
for l in f:
l = l.partition('//')[0]
l = l.strip()
if l == 'module {}'.format(cell.name) or l.startswith('module {} '.format(cell.name)):
if found:
print('Multiple modules in {}.'.format(fname))
sys.exit(1)
elif state != State.OUTSIDE:
print('Nested modules in {}.'.format(fname))
sys.exit(1)
found = True
state = State.IN_MODULE
if cell.keep:
outf.write('(* keep *)\n')
outf.write('module {} (...);\n'.format(cell.name))
elif l.startswith('module '):
if state != State.OUTSIDE:
print('Nested modules in {}.'.format(fname))
sys.exit(1)
state = State.IN_OTHER_MODULE
elif l.startswith('task '):
if state == State.IN_MODULE:
state = State.IN_TASK
elif l.startswith('function '):
if state == State.IN_MODULE:
state = State.IN_FUNCTION
elif l == 'endtask':
if state == State.IN_TASK:
state = State.IN_MODULE
elif l == 'endfunction':
if state == State.IN_FUNCTION:
state = State.IN_MODULE
elif l == 'endmodule':
if state == State.IN_MODULE:
outf.write(l + '\n')
outf.write('\n')
elif state != State.IN_OTHER_MODULE:
print('endmodule in weird place in {}.'.format(cell.name, fname))
sys.exit(1)
state = State.OUTSIDE
elif l.startswith(('input ', 'output ', 'inout ')) and state == State.IN_MODULE:
if l.endswith((';', ',')):
l = l[:-1]
if ';' in l:
print('Weird port line in {} [{}].'.format(fname, l))
sys.exit(1)
kind, _, ports = l.partition(' ')
for port in ports.split(','):
port = port.strip()
for attr in cell.port_attrs.get(port, []):
outf.write(' (* {} *)\n'.format(attr))
outf.write(' {} {};\n'.format(kind, port))
elif l.startswith('parameter ') and state == State.IN_MODULE:
if 'UNPLACED' in l:
continue
if l.endswith((';', ',')):
l = l[:-1]
while ' ' in l:
l = l.replace(' ', ' ')
if ';' in l:
print('Weird parameter line in {} [{}].'.format(fname, l))
sys.exit(1)
outf.write(' {};\n'.format(l))
if state != State.OUTSIDE:
print('endmodule not found in {}.'.format(fname))
sys.exit(1)
if not found:
print('Cannot find module {} in {}.'.format(cell.name, fname))
sys.exit(1)
return
except FileNotFoundError:
continue
print('Cannot find {}.'.format(cell.name))
sys.exit(1)
if __name__ == '__main__':
parser = ArgumentParser(description='Extract Xilinx blackbox cell definitions from Vivado.')
parser.add_argument('vivado_dir', nargs='?', default='/opt/Xilinx/Vivado/2018.1')
args = parser.parse_args()
dirs = [
os.path.join(args.vivado_dir, 'data/verilog/src/xeclib'),
os.path.join(args.vivado_dir, 'data/verilog/src/retarget'),
]
for dir in dirs:
if not os.path.isdir(dir):
print('{} is not a directory'.format(dir))
out = StringIO()
for cell in CELLS:
xtract_cell_decl(cell, dirs, out)
with open('cells_xtra.v', 'w') as f:
f.write('// Created by cells_xtra.py from Xilinx models\n')
f.write('\n')
f.write(out.getvalue())
|
<reponame>jonnyns/sosi_files_importer
# -*- coding: utf-8 -*-
"""
Copyright © 2022 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This file is part of SosiImporter, an addon to import SOSI files containing
3D model data into Blender.
"""
import numpy as np
import math
import logging
from . import sosi_log_helper as sologhlp
from . import sosi_settings as soset
# -----------------------------------------------------------------------------
def coords2D(v):
return v[0], v[1]
# -----------------------------------------------------------------------------
def coords3D(v):
return v[0], v[1], v[2]
# -----------------------------------------------------------------------------
def printArray(a):
for row in range(len(a)):
for col in range (len(a[row])):
print("{:8.3f}".format(a[row][col]), end = " ")
print()
# -----------------------------------------------------------------------------
def rads_2_degrees(angls):
degs = []
for a in angls:
degs.append(math.degrees(a))
return degs
# -----------------------------------------------------------------------------
def arc_circle_center_2D(p1, p2, p3):
"""
For the 2D case: p1, p2, p3 are three points on the arc of a circle.
Return the x and y coordinates for the center of the circle.
"""
#print(p1, p2, p3)
x1, y1 = coords2D(p1)
x2, y2 = coords2D(p2)
x3, y3 = coords2D(p3)
n = (-x2 * x2 * y1 + x3 * x3 * y1 + x1 * x1 * y2 - x3 * x3 * y2 \
+ y1 * y1 * y2 - y1 * y2 * y2 - x1 * x1 * y3 + x2 * x2 * y3 \
- y1 * y1 * y3 + y2 * y2 * y3 + y1 * y3 * y3 - y2 * y3 * y3)
d = 2 * (x2 * y1 - x3 * y1 - x1 * y2 + x3 * y2 + x1 * y3 - x2 * y3)
if (d == 0.0):
return None
x = -(n/d)
n = -x1 * x1 * x2 + x1 * x2 * x2 + x1 * x1 * x3 - x2 * x2 * x3 \
- x1 * x3 * x3 + x2 * x3 * x3 - x2 * y1 * y1 + x3 * y1 * y1 \
+ x1 * y2 * y2 - x3 * y2 * y2 - x1 * y3 * y3 + x2 * y3 * y3
y = -(n/d)
return (x, y)
# -----------------------------------------------------------------------------
def rotate_pts_3D(mtx, pts):
"""
Rotate the 3D points in the pts list according to the 3x3
rotation matrix mtx.
Return the list of rotated points.
"""
tpts = []
for pt in pts:
p = mtx @ np.asarray(pt)
tpts.append(p)
return tpts
# -----------------------------------------------------------------------------
def transform_pts_3D(mtx, pts):
"""
Transform the 3D points in the pts list according to the 4x4
transformation matrix mtx.
Return the list of transformed points.
"""
tpts = []
for pt in pts:
if len(pt) < 4:
pt = (*pt, 1.0)
p = mtx @ np.asarray(pt)
pp = (p[0], p[1], p[2])
tpts.append(pp)
return tpts
# -----------------------------------------------------------------------------
def get_rotation_matrix(axis, theta):
"""
Find the rotation matrix associated with counterclockwise rotation
about the given axis by theta radians.
Credit: http://stackoverflow.com/users/190597/unutbu
Args:
axis (list): rotation axis of the form [x, y, z]
theta (float): rotational angle in radians
Returns:
array. Rotation matrix.
"""
axis = np.asarray(axis)
theta = np.asarray(theta)
axis = axis/math.sqrt(np.dot(axis, axis))
a = math.cos(theta/2.0)
b, c, d = -axis*math.sin(theta/2.0)
aa, bb, cc, dd = a*a, b*b, c*c, d*d
bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d
return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)],
[2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)],
[2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]])
# -----------------------------------------------------------------------------
def get_translation_matrix(t):
tm = [[1, 0, 0, t[0]], [0, 1, 0, t[1]], [0, 0, 1, t[2]], [0, 0, 0, 1]]
return np.asarray(tm)
# -----------------------------------------------------------------------------
def angles_interpolate(angls, angls_diff, num_splits):
angls_between = []
for i in range(len(angls)-1):
angl_step = angls_diff[i]/num_splits
a = angls[i]
angls_between.append(a)
for j in range(1, num_splits):
a += angl_step
angls_between.append(a)
angls_between.append(angls[-1])
return angls_between
# -----------------------------------------------------------------------------
# Angle between two vectors [radians]
def angle_vector_3D(v1, v2, acute):
"""
# v1 is first vector
# v2 is second vector
"""
angle = np.arccos(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
if (acute == True):
return angle
else:
return 2 * np.pi - angle
# -----------------------------------------------------------------------------
def angle_vector_2D(v1, v2):
"""
Return angle between two 2D vectors (i.e. use only x and y coordinate values)
Angle (from v1 to v2, positive angle of rotation) is in the range -pi < x < pi.
"""
dot = v1[0] * v2[0] + v1[1] * v2[1] # dot product
det = v1[0] * v2[1] - v1[1] * v2[0] # determinant
angl = math.atan2(det, dot)
return angl
# -----------------------------------------------------------------------------
def angles_circle_abs_2D(circle_pts, num=0):
"""
Assuming circle_pts contains 2D coordinates for a circle with center origin (0., 0.)
compute angle for all coordinates in range 0 <= angl < 2 * pi
"""
if (num == 0):
num = len(circle_pts)
angls = []
for i in range(0, num):
pt = circle_pts[i]
radius = math.sqrt(pt[0]**2 + pt[1]**2)
if (radius == 0.0):
angl = None
else:
angl = math.asin(pt[1]/radius)
#print(pt[0], pt[1], radius, angl, math.degrees(angl))
if (pt[0] < 0.):
angl = math.pi - angl
else:
if ((pt[1] < 0.)):
angl = 2 * math.pi + angl
#print(math.degrees(angl))
angls.append(angl)
return angls
# -----------------------------------------------------------------------------
def angles_circle_diff_2D(circle_pts):
"""
Assuming circle_pts contains 2D coordinates for pts on a circle as well as the circle center
The circle center is the very last of the coordinates
Compute angles between successive arc pts
"""
a = []
for i in range(1, len(circle_pts) - 1):
vb = circle_pts[i] - circle_pts[-1]
va = circle_pts[i-1] - circle_pts[-1]
a.append(angle_vector_2D(va, vb))
return a
# -----------------------------------------------------------------------------
def angle_num_splits(angl):
num_splits = (angl * soset.SOSI_ARC_SEGMENTS) / (2 * math.pi)
#print(math.degrees(angl), num_splits)
return num_splits
# -----------------------------------------------------------------------------
def is_arc_pos_or_neg(angls):
#print(math.degrees(angls[0]), math.degrees(angls[1]), math.degrees(angls[2]))
for i in range(len(angls)):
#print(i)
idx_nxt = i + 1
if (idx_nxt >= len(angls)):
idx_nxt = 0
if (angls[i] > angls[i-1]) and (angls[i] < angls[idx_nxt]):
return 1
elif (angls[i] < angls[i-1]) and (angls[i] > angls[idx_nxt]):
return -1
# -----------------------------------------------------------------------------
def arc_pts_interpolate_2D(cirpts_hor, num_splits):
"""
cirpts_hor contains 2D coordinates for pts on a circle (i.e. arcs) as well as the circle center.
The circle center is the very last of the coordinates.
num_splits is the number of segments required for each arc.
Return the coordinates for every point on the circle (including those in cirpts_hor)
"""
cirpts_hor = np.asarray(cirpts_hor) # To support vector operations
radius = math.sqrt((cirpts_hor[0][0] - cirpts_hor[-1][0])**2 + (cirpts_hor[0][1] - cirpts_hor[-1][1])**2)
angls = angles_circle_abs_2D(cirpts_hor, len(cirpts_hor)-1)
#print(math.degrees(angls[0]), math.degrees(angls[1]), math.degrees(angls[2]))
angls_diff = angles_circle_diff_2D(cirpts_hor)
#print(rads_2_degrees(angls_diff))
if num_splits == 0: # calculate number of splits
angl_less = angls_diff[0]
if abs(angls_diff[0]) > abs(angls_diff[1]):
angl_less = angls_diff[1] # lesser value
num_splits = math.ceil(abs(angle_num_splits(angl_less)))
#print(num_splits)
angls_interpolated = angles_interpolate(angls, angls_diff, num_splits)
#print(rads_2_degrees(angls_interpolated))
coords = []
for a in angls_interpolated:
coord = (math.cos(a) * radius, math.sin(a) * radius, cirpts_hor[0][2])
coords.append(coord)
#print(math.degrees(a), coord)
return coords
# -----------------------------------------------------------------------------
def arc_pts_segments_3D(arc_pts, num_splits):
"""
arc_pts contains 3 3D-coordinates assumed to lie on a circle (i.e. two arcs).
Each arc will be split into num_splits segments.
Return the 3D coordinates for all segment points (including the original coordinates)
as curve points. .
"""
arr = np.asarray(arc_pts) # To support vector operations
v1 = arr[0] - arr[1]
v2 = arr[2] - arr[1]
logging.debug(' Arc vectors:\n %s %s', v1, v2)
vn = np.cross(v1, v2) # Normal to vector plane
logging.debug(' Normal vector:\n %s', sologhlp.formatArray(vn))
vz = np.array([0.0, 0.0, 1.0])
# Rotation vector
vr = np.cross(vn, vz) # Between normal and z vector
logging.debug(' Rotation vector:\n%s', sologhlp.formatArray(vr))
# rotation angle
a = angle_vector_3D(vn, vz, True)
logging.debug(' Rotation angle:\n%s', math.degrees(a))
if (a != 0.0) and (a != math.pi):
rot_mtx = get_rotation_matrix(vr, a)
logging.debug(' Rotation matrix:\n%s', rot_mtx)
logging.debug(' Arc pts pre:\n%s', sologhlp.formatArray(arc_pts))
arc_pts_horz = rotate_pts_3D(rot_mtx, arc_pts)
logging.debug(' Arc pts post:\n%s', sologhlp.formatArray(arc_pts_horz))
else:
arc_pts_horz = arc_pts
#ctr2D = get_arc_center_2D(arc_pts_horz[0], arc_pts_horz[1], arc_pts_horz[2])
ctr2D = arc_circle_center_2D(arc_pts_horz[0], arc_pts_horz[1], arc_pts_horz[2])
ctr3D = [ctr2D[0], ctr2D[1], arc_pts_horz[2][2]] # Use z-value for one of the points
logging.debug(' Circle center:\n%s', ctr3D)
# Append the center point to the list
cir_pts_hor = [arc_pts_horz[0], arc_pts_horz[1], arc_pts_horz[2], np.array(ctr3D)]
logging.debug(' Circle points:\n%s', sologhlp.formatArray(cir_pts_hor))
# Translation to origo
trans_mtx1 = get_translation_matrix([-ctr3D[0], -ctr3D[1], 0]) # Translate circle center to origo
cir_pts_hor_origo = transform_pts_3D(trans_mtx1, cir_pts_hor)
logging.debug(' Circle points around origo:\n%s', sologhlp.formatArray(cir_pts_hor_origo))
# Interpolate into arc segment points
arc_pts_horz_origo = arc_pts_interpolate_2D(cir_pts_hor_origo, num_splits)
logging.debug(' Circle points around origo:\n%s', sologhlp.formatArray(arc_pts_horz_origo))
# Translation back
trans_mtx2 = get_translation_matrix([ctr3D[0], ctr3D[1], 0]) # Circle center back
arc_pts_horz = transform_pts_3D(trans_mtx2, arc_pts_horz_origo)
#printArray(arc_pts_horz)
# Rotate back to original position
if (a != 0.0) and (a != math.pi):
arc_pts_nonhorz = []
for ap in arc_pts_horz:
arc_pts_nonhorz.append(np.transpose(rot_mtx) @ ap)
else:
arc_pts_nonhorz = arc_pts_horz
return arc_pts_nonhorz |
<filename>one_fm/grd/doctype/moi_residency_jawazat/moi_residency_jawazat.py
# -*- coding: utf-8 -*-
# Copyright (c) 2020, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from datetime import date
from frappe.utils import today, add_days, get_url
from frappe.utils import get_datetime, add_to_date, getdate, get_link_to_form, now_datetime, nowdate, cstr
class MOIResidencyJawazat(Document):
def validate(self):
self.set_grd_values()
def set_grd_values(self):
if not self.grd_supervisor:
self.grd_supervisor = frappe.db.get_value('GRD Settings', None, 'default_grd_supervisor')
if not self.grd_operator:
self.grd_operator = frappe.db.get_value('GRD Settings', None, 'default_grd_operator')
def on_submit(self):
self.validate_mandatory_fields_on_submit()
self.set_residency_expiry_new_date_in_employee_doctype()
self.db_set('completed','Yes')
self.db_set('completed_on', today())
def validate_mandatory_fields_on_submit(self):
if self.apply_online == "No":
frappe.throw(_("Must Apply MOI To Submit"))
if not self.invoice_attachment:
frappe.throw(_("Attach The Invoice To Submit"))
if not self.residency_attachment:
frappe.throw(_("Attach Residency To Submit"))
if not self.new_residency_expiry_date:
frappe.throw(_("Add The New Residency Expiry Date To Submit"))
def set_residency_expiry_new_date_in_employee_doctype(self):
today = date.today()
employee = frappe.get_doc('Employee', self.employee)
employee.residency_expiry_date = self.new_residency_expiry_date # update the date of expiry
employee.append("one_fm_employee_documents", {
"attach": self.residency_attachment,
"document_name": "Residency Expiry Attachment",
"issued_on":today,
"valid_till":self.new_residency_expiry_date
})
employee.save()
#fetching the list of employee has Extend and renewal status from HR list. =====> to create moi record
def set_employee_list_for_moi(preparation_name):
# filter work permit records only take the non kuwaiti
employee_in_preparation = frappe.get_doc('Preparation',preparation_name)
if employee_in_preparation.preparation_record:
for employee in employee_in_preparation.preparation_record:
if employee.renewal_or_extend == 'Renewal' and employee.nationality != 'Kuwaiti':# For renewals
create_moi_record(frappe.get_doc('Employee',employee.employee),employee.renewal_or_extend,preparation_name)
if employee.renewal_or_extend != 'Renewal' and employee.nationality != 'Kuwaiti':# For extend
create_moi_record(frappe.get_doc('Employee',employee.employee),employee.renewal_or_extend,preparation_name)
#def create_mi_record(Insurance_status,work_permit_dic):
def create_moi_record(employee,Renewal_or_Extend,preparation_name):
start_day = add_days(employee.residency_expiry_date, -14)
new_moi = frappe.new_doc('MOI Residency Jawazat')
new_moi.employee = employee.name
new_moi.preparation = preparation_name
new_moi.renewal_or_extend = Renewal_or_Extend#employee_data.renewal_or_extend
new_moi.date_of_application = start_day
new_moi.insert()
# Run this method at 4 pm (cron)
def system_checks_grd_operator_apply_online():
filters = {'docstatus': 0,'apply_online':['=','No']}
moi_list = frappe.db.get_list('MOI Residency Jawazat', filters, ['name', 'grd_operator'])
if len(moi_list) > 0:
moi_notify_first_grd_operator()
# Notify GRD Operator at 9:00 am (cron)
def moi_notify_first_grd_operator():
moi_notify_grd_operator('yellow')
# Notify GRD Operator at 9:30 am (cron)
def moi_notify_again_grd_operator():
moi_notify_grd_operator('red')
def moi_notify_grd_operator(reminder_indicator):
# Get moi list
today = date.today()
filters = {'docstatus': 0,
'apply_online':['=','No'] ,'reminded_grd_operator': 0, 'reminded_grd_operator_again':0}
if reminder_indicator == 'red':
filters['reminded_grd_operator'] = 1
filters['reminded_grd_operator_again'] = 0
moi_list = frappe.db.get_list('MOI Residency Jawazat', filters, ['name', 'grd_operator'])
# send grd supervisor if reminder for second time (red)
cc = [moi_list[0].grd_supervisor] if reminder_indicator == 'red' else []
email_notification_to_grd_user('grd_operator', moi_list, reminder_indicator, 'Submit', cc)
def email_notification_to_grd_user(grd_user, moi_list, reminder_indicator, action, cc=[]):
recipients = {}
for moi in moi_list:
page_link = get_url("http://192.168.8.102/desk#Form/MOI Residency Jawazat/"+moi.name)
message = "<a href='{0}'>{1}</a>".format(page_link, moi.name)
if moi[grd_user] in recipients:
recipients[moi[grd_user]].append(message)#add the message in the empty list
else:
recipients[moi[grd_user]]=[message]
if recipients:
for recipient in recipients:
subject = 'MOI Residency Jawazat {0}'.format(moi.name)#added
message = "<p>Please {0} MOI Residency Jawazat listed below</p><ol>".format(action)
for msg in recipients[recipient]:
message += "<li>"+msg+"</li>"
message += "<ol>"
frappe.sendmail(
recipients=[recipient],
cc=cc,
subject=_('{0} MOI Residency Jawazat'.format(action)),
message=message,
header=['MOI Residency Jawazat Reminder', reminder_indicator],
)
to_do_to_grd_users(_('{0} MOI Residency Jawazat'.format(action)), message, recipient)
create_notification_log(subject, message, [moi.grd_user], moi)#added
def to_do_to_grd_users(subject, description, user):
frappe.get_doc({
"doctype": "ToDo",
"subject": subject,
"description": description,
"owner": user,
"date": today()
}).insert(ignore_permissions=True)
def create_notification_log(subject, message, for_users, reference_doc):
for user in for_users:
doc = frappe.new_doc('Notification Log')
doc.subject = subject
doc.email_content = message
doc.for_user = user
doc.document_type = reference_doc.doctype
doc.document_name = reference_doc.name
doc.from_user = reference_doc.modified_by
#doc.insert(ignore_permissions=True)
|
"""
test_click_jacking.py
Copyright 2012 <NAME>
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
import w3af.core.data.constants.severity as severity
from w3af.plugins.tests.helper import PluginTest, PluginConfig, MockResponse
class TestClickJackingVuln(PluginTest):
target_url = 'http://httpretty'
MOCK_RESPONSES = [MockResponse('http://httpretty/',
body='Hello world',
method='GET',
status=200)]
_run_configs = {
'cfg': {
'target': target_url,
'plugins': {
'grep': (PluginConfig('click_jacking'),),
'crawl': (
PluginConfig('web_spider',
('only_forward', True, PluginConfig.BOOL)),
)
}
}
}
def test_found_vuln(self):
cfg = self._run_configs['cfg']
self._scan(cfg['target'], cfg['plugins'])
vulns = self.kb.get('click_jacking', 'click_jacking')
self.assertEquals(1, len(vulns))
v = vulns[0]
self.assertEquals(severity.MEDIUM, v.get_severity())
self.assertEquals('Click-Jacking vulnerability', v.get_name())
self.assertEquals(len(v.get_id()), 1, v.get_id())
self.assertIn('The application has no protection', v.get_desc())
class TestClickJackingProtectedXFrameOptions(PluginTest):
target_url = 'http://httpretty'
MOCK_RESPONSES = [MockResponse('http://httpretty/',
body='Hello world',
method='GET',
headers={'x-frame-options': 'deny'},
status=200)]
_run_configs = {
'cfg': {
'target': target_url,
'plugins': {
'grep': (PluginConfig('click_jacking'),),
'crawl': (
PluginConfig('web_spider',
('only_forward', True, PluginConfig.BOOL)),
)
}
}
}
def test_no_vuln(self):
cfg = self._run_configs['cfg']
self._scan(cfg['target'], cfg['plugins'])
vulns = self.kb.get('click_jacking', 'click_jacking')
self.assertEquals(0, len(vulns))
class TestClickJackingCSPNone(PluginTest):
target_url = 'http://httpretty'
MOCK_RESPONSES = [MockResponse('http://httpretty/',
body='Hello world',
method='GET',
headers={'Content-Security-Policy': "frame-ancestors 'none';"},
status=200)]
_run_configs = {
'cfg': {
'target': target_url,
'plugins': {
'grep': (PluginConfig('click_jacking'),),
'crawl': (
PluginConfig('web_spider',
('only_forward', True, PluginConfig.BOOL)),
)
}
}
}
def test_no_vuln(self):
cfg = self._run_configs['cfg']
self._scan(cfg['target'], cfg['plugins'])
vulns = self.kb.get('click_jacking', 'click_jacking')
self.assertEquals(0, len(vulns))
class TestClickJackingCSPWildcard(PluginTest):
target_url = 'http://httpretty'
MOCK_RESPONSES = [MockResponse('http://httpretty/',
body='Hello world',
method='GET',
headers={'Content-Security-Policy': "frame-ancestors '*';"},
status=200)]
_run_configs = {
'cfg': {
'target': target_url,
'plugins': {
'grep': (PluginConfig('click_jacking'),),
'crawl': (
PluginConfig('web_spider',
('only_forward', True, PluginConfig.BOOL)),
)
}
}
}
def test_vuln(self):
cfg = self._run_configs['cfg']
self._scan(cfg['target'], cfg['plugins'])
vulns = self.kb.get('click_jacking', 'click_jacking')
self.assertEquals(1, len(vulns))
class TestClickJackingCSPSpecificDomain(PluginTest):
target_url = 'http://httpretty'
MOCK_RESPONSES = [MockResponse('http://httpretty/',
body='Hello world',
method='GET',
headers={'Content-Security-Policy': "frame-ancestors 'somesite.com';"},
status=200)]
_run_configs = {
'cfg': {
'target': target_url,
'plugins': {
'grep': (PluginConfig('click_jacking'),),
'crawl': (
PluginConfig('web_spider',
('only_forward', True, PluginConfig.BOOL)),
)
}
}
}
def test_vuln(self):
cfg = self._run_configs['cfg']
self._scan(cfg['target'], cfg['plugins'])
vulns = self.kb.get('click_jacking', 'click_jacking')
self.assertEquals(0, len(vulns))
class TestClickJackingCSPSelf(PluginTest):
target_url = 'http://httpretty'
MOCK_RESPONSES = [MockResponse('http://httpretty/',
body='Hello world',
method='GET',
headers={'Content-Security-Policy': "frame-ancestors 'self';"},
status=200)]
_run_configs = {
'cfg': {
'target': target_url,
'plugins': {
'grep': (PluginConfig('click_jacking'),),
'crawl': (
PluginConfig('web_spider',
('only_forward', True, PluginConfig.BOOL)),
)
}
}
}
def test_vuln(self):
cfg = self._run_configs['cfg']
self._scan(cfg['target'], cfg['plugins'])
vulns = self.kb.get('click_jacking', 'click_jacking')
self.assertEquals(0, len(vulns))
class TestClickJackingCSPSelfAndSpecificDomain(PluginTest):
target_url = 'http://httpretty'
MOCK_RESPONSES = [MockResponse('http://httpretty/',
body='Hello world',
method='GET',
headers={'Content-Security-Policy': "frame-ancestors self 'somesite.com';"},
status=200)]
_run_configs = {
'cfg': {
'target': target_url,
'plugins': {
'grep': (PluginConfig('click_jacking'),),
'crawl': (
PluginConfig('web_spider',
('only_forward', True, PluginConfig.BOOL)),
)
}
}
}
def test_vuln(self):
cfg = self._run_configs['cfg']
self._scan(cfg['target'], cfg['plugins'])
vulns = self.kb.get('click_jacking', 'click_jacking')
self.assertEquals(0, len(vulns))
|
<reponame>guanchaoguo/forsun
# -*- coding: utf-8 -*-
# 15/6/27
# create by: snower
import os
import configparser
from .utils import unicode_type, string_type, number_type, ensure_unicode
class ConfFileNotFoundError(Exception):
pass
__config = {}
DEFAULT_CONFIG = {
"LOG_FILE": "/var/log/forsun.log",
"LOG_LEVEL": "INFO",
"LOG_FORMAT": "%(asctime)s %(process)d %(levelname)s %(message)s",
"LOG_ROTATE": "",
"LOG_BACKUP_COUNT": 64,
"BIND_ADDRESS": "127.0.0.1",
"PORT": 6458,
"HTTP_BIND": "",
"STORE_DRIVER": "mem",
"STORE_STATUS_EXPRIED": 0,
"STORE_MEM_STORE_FILE": "",
"STORE_MEM_TIME_RATE": 1,
"STORE_REDIS_HOST": "127.0.0.1",
"STORE_REDIS_PORT": 6379,
"STORE_REDIS_DB": 0,
"STORE_REDIS_PASSWORD": "",
"STORE_REDIS_PREFIX": "forsun",
"STORE_REDIS_SERVER_ID": 0,
"STORE_REDIS_MAX_CONNECTIONS": 8,
"STORE_REDIS_CLIENT_TIMEOUT": 7200,
"STORE_REDIS_BULK_SIZE": 5,
"STORE_REDIS_CURRENTTIME_EXPRIED": 2592000,
"STORE_REDIS_PLAN_EXPRIED": 604800,
"STORE_REDIS_PLANTIME_EXPRIED": 604800,
"ACTION_RETRY_DELAY_SECONDS": 3,
"ACTION_RETRY_DELAY_RATE": 1,
"ACTION_RETRY_MAX_COUNT": 3,
"ACTION_POLL_IDLE_SECONDS": 120,
"ACTION_SHELL_CWD": "/tmp",
"ACTION_HTTP_MAX_CLIENTS": 64,
"ACTION_HTTP_CONNECT_TIMEOUT": 5,
"ACTION_HTTP_REQUEST_TIMEOUT": 120,
"ACTION_HTTP_USER_AGENT": "",
"ACTION_REDIS_MAX_CONNECTIONS": 8,
"ACTION_REDIS_CLIENT_TIMEOUT": 7200,
"ACTION_REDIS_BULK_SIZE": 5,
"ACTION_THRIFT_MAX_CONNECTIONS": 64,
"ACTION_MYSQL_USER": "root",
"ACTION_MYSQL_PASSWD": "",
"ACTION_MYSQL_MAX_CONNECTIONS": 8,
"ACTION_MYSQL_WAIT_CONNECTION_TIMEOUT": 7200,
"ACTION_MYSQL_IDLE_SECONDS": 120,
"EXTENSION_PATH": "",
"EXTENSIONS": [],
}
def get(name, default=None):
return __config.get(name, default)
def set(name, value):
old_value = __config[name]
__config[name] = value
return old_value
def update(config):
__config.update(config)
return __config
update(DEFAULT_CONFIG)
for key, value in DEFAULT_CONFIG.items():
env_value = os.environ.get(key)
if env_value is not None:
try:
if isinstance(value, number_type):
set(key, int(env_value))
elif isinstance(value, float):
set(key, float(env_value))
elif isinstance(value, string_type):
set(key, str(env_value))
except:pass
def load_conf(filename):
try:
with open(filename, "r") as fp:
conf_content = unicode_type("[global]\n") + ensure_unicode(fp.read())
cf = configparser.ConfigParser(allow_no_value=True)
cf.read_string(conf_content)
for key, value in DEFAULT_CONFIG.items():
try:
if key.startswith("STORE_"):
conf_value = cf.get("store", key[6:].lower())
elif key.startswith("ACTION_"):
conf_value = cf.get("action", key[7:].lower())
elif key.startswith("EXTENSION"):
if key == "EXTENSIONS":
conf_value = cf.get("extension", "extensions")
if isinstance(conf_value, string_type):
set(key, conf_value.split(";"))
continue
else:
conf_value = cf.get("extension", key[10:].lower())
else:
conf_value = cf.get("global", key.lower())
try:
if isinstance(value, number_type):
set(key, int(conf_value))
elif isinstance(value, float):
set(key, float(conf_value))
elif isinstance(value, string_type):
set(key, str(conf_value))
except:
pass
except (configparser.NoOptionError, configparser.NoSectionError):
continue
except IOError:
raise ConfFileNotFoundError()
|
# Author : <NAME>
from migtool import *
import subprocess,os
import multiprocessing
import getpass
def userinput():
global VCAUser, VCAPasswd, enttype, API_URL, VCAOrgName, PCCHost, PCCUser, PCCpass, SubRawURL
pullbanner = banner(text='vCloud Director to vCenter VM Cold Migration Tool')
endbanner = banner(text='***')
print("")
print(pullbanner)
print("")
print("Disclaimer:")
print("===========")
print(" 1. This application is developed to cold migrate vCloud director VMs to vCenter content Library")
print(" 2. Supported vCenters 6.0, 6.5, 6.7")
print(" 3. Input validation is performed after the last step, ensure all the information is entered correctly")
print(" 4. Don't close the Keep-alive/Migration window till all the migrations are complete")
print("")
print(endbanner)
print("")
print("Select the vCloud Director Environment type:")
print("1.vCloud Air (Legacy-depreciated)")
print("2.On-premise vCloud director")
enttype = int(input('Enter your choice [1-2]:'))
VCAUser = input('vCloud Director Username:')
VCAPasswd = getpass.getpass(prompt='vCloud Director Password:')
API_URL = input('vCloud Director API / GVR login URL:')
SubRawURL = API_URL[:API_URL.find('.com') + 4]
VCAOrgName = input('vCloud Director OrgName:')
PCCHost = input("vCenter Host_Name/IP,format(https://pcc-xxx-xxx-xxx-xxx.ovh.xx):")
PCCUser = input("vCenter UserName:")
PCCpass = getpass.getpass(prompt='vCenter Password:')
login()
def login():
global odxvchsauth,session_ID
if enttype == 1:
loginreq = login_ondemand(API_URL, VCAUser, VCAPasswd, VCAOrgName)
odxvchsauth = loginreq[0]
orgurl = loginreq[1]
session_ID = PCClogin(PCCHost, PCCUser, PCCpass)
subprocess.Popen(["start", "cmd", "/k", "python", "-c", "import migtoolPCC; migtoolPCC.keepalive('%s','%s','%s','%s')"%(PCCHost,session_ID,odxvchsauth,orgurl)], shell=True)
transferopt()
elif enttype == 2:
loginreq = login_subscription(SubRawURL,VCAUser,VCAPasswd,VCAOrgName)
odxvchsauth = loginreq[0]
orgurl = loginreq[1]
session_ID = PCClogin(PCCHost, PCCUser, PCCpass)
subprocess.Popen(["start", "cmd", "/k", "python", "-c", "import migtoolPCC; migtoolPCC.keepalive('%s','%s','%s','%s')"%(PCCHost,session_ID,odxvchsauth,orgurl)], shell=True)
transferopt()
def transferopt():
global objtype
print("")
print("Select the type of object to be transferred:")
print("1.vAPP (Cold Migration)")
print("2.vAPP Template")
print("3.Media / ISO")
objtype = int(input("Enter your choice [1-3]:"))
core()
def core():
if enttype == 1 and objtype == 1:
catalogid = PCCcreatecatalog(PCCHost,session_ID)
time.sleep(4)
source_item = vappmigrate_OD(API_URL, odxvchsauth)
time.sleep(4)
postURL = source_item[0]
vappname = source_item[1]
subprocess.Popen(["start", "cmd", "/k", "python", "-c", "import migtoolPCC; migtoolPCC.enabledownloadvapp('%s','%s','%s','%s','%s','%s')"%(postURL,PCCHost,odxvchsauth,vappname,session_ID,catalogid)], shell=True)
time.sleep(4)
transferopt()
elif enttype == 1 and objtype == 2:
catalogid = PCCcreatecatalog(PCCHost,session_ID)
time.sleep(4)
source_item = vapptempmigrate_OD(API_URL,odxvchsauth)
time.sleep(4)
postURL = source_item[0]
vappname = source_item[1]
catalogname = source_item[2]
CatName = source_item[3]
ObjName = source_item[4]
subprocess.Popen(["start", "cmd", "/k", "python", "-c", "import migtoolPCC; migtoolPCC.enabledownloadvapptemp('%s','%s','%s','%s','%s','%s')"%(postURL,PCCHost,vappname,odxvchsauth,session_ID,catalogid)], shell=True)
time.sleep(4)
transferopt()
elif enttype == 1 and objtype == 3:
catalogid = PCCcreatecatalog(PCCHost,session_ID)
sourceiso_size = Media_OD(API_URL, odxvchsauth)
download_iso_URL = sourceiso_size[1]
ObjNam = sourceiso_size[2]
source_size = sourceiso_size[0]
subprocess.Popen(["start", "cmd", "/k", "python", "-c", "import migtoolPCC; migtoolPCC.endownloadiso('%s','%s','%s','%s','%s','%s','%s')"%(odxvchsauth,session_ID,download_iso_URL,ObjNam,catalogid,PCCHost,source_size)], shell=True)
time.sleep(4)
transferopt()
elif enttype == 2 and objtype == 1:
catalogid = PCCcreatecatalog(PCCHost,session_ID)
time.sleep(4)
source_item = vappmigrate_OD(SubRawURL, odxvchsauth)
time.sleep(4)
postURL = source_item[0]
vappname = source_item[1]
subprocess.Popen(["start", "cmd", "/k", "python", "-c", "import migtoolPCC; migtoolPCC.enabledownloadvapp('%s','%s','%s','%s','%s','%s')"%(postURL,PCCHost,odxvchsauth,vappname,session_ID,catalogid)], shell=True)
time.sleep(5)
transferopt()
elif enttype == 2 and objtype == 2:
catalogid = PCCcreatecatalog(PCCHost,session_ID)
time.sleep(4)
source_item = vapptempmigrate_OD(SubRawURL, odxvchsauth)
time.sleep(4)
postURL = source_item[0]
vappname = source_item[1]
catalogname = source_item[2]
CatName = source_item[3]
ObjName = source_item[4]
subprocess.Popen(["start", "cmd", "/k", "python", "-c", "import migtoolPCC; migtoolPCC.enabledownloadvapptemp('%s','%s','%s','%s','%s','%s')"%(postURL,PCCHost,vappname,odxvchsauth,session_ID,catalogid)], shell=True)
time.sleep(4)
transferopt()
elif enttype == 2 and objtype == 3:
catalogid = PCCcreatecatalog(PCCHost,session_ID)
sourceiso_size = Media_OD(SubRawURL, odxvchsauth)
download_iso_URL = sourceiso_size[1]
ObjNam = sourceiso_size[2]
source_size = sourceiso_size[0]
subprocess.Popen(["start", "cmd", "/k", "python", "-c", "import migtoolPCC; migtoolPCC.endownloadiso('%s','%s','%s','%s','%s','%s','%s')"%(odxvchsauth,session_ID,download_iso_URL,ObjNam,catalogid,PCCHost,source_size)], shell=True)
time.sleep(4)
transferopt()
if __name__ == '__main__':
userinput()
|
<reponame>flaght/panther
# -*- coding: utf-8 -*-
import pdb,importlib,inspect,time,datetime,json
# from PyFin.api import advanceDateByCalendar
# from data.polymerize import DBPolymerize
from data.storage_engine import StorageEngine
import time
import pandas as pd
import numpy as np
from datetime import timedelta, datetime
from financial import factor_solvency
from data.model import BalanceMRQ, BalanceTTM
from data.model import CashFlowMRQ, CashFlowTTM
# from data.model import IndicatorTTM
from data.model import IncomeTTM
from vision.table.valuation import Valuation
from vision.db.signletion_engine import *
from data.sqlengine import sqlEngine
# pd.set_option('display.max_columns', None)
# pd.set_option('display.max_rows', None)
# from ultron.cluster.invoke.cache_data import cache_data
class CalcEngine(object):
def __init__(self, name, url, methods=[{'packet':'financial.factor_solvency','class':'FactorSolvency'},]):
self._name = name
self._methods = methods
self._url = url
def get_trade_date(self, trade_date, n, days=365):
"""
获取当前时间前n年的时间点,且为交易日,如果非交易日,则往前提取最近的一天。
:param days:
:param trade_date: 当前交易日
:param n:
:return:
"""
syn_util = SyncUtil()
trade_date_sets = syn_util.get_all_trades('001002', '19900101', trade_date)
trade_date_sets = trade_date_sets['TRADEDATE'].values
time_array = datetime.strptime(str(trade_date), "%Y%m%d")
time_array = time_array - timedelta(days=days) * n
date_time = int(datetime.strftime(time_array, "%Y%m%d"))
if str(date_time) < min(trade_date_sets):
# print('date_time %s is out of trade_date_sets' % date_time)
return str(date_time)
else:
while str(date_time) not in trade_date_sets:
date_time = date_time - 1
# print('trade_date pre %s year %s' % (n, date_time))
return str(date_time)
def _func_sets(self, method):
# 私有函数和保护函数过滤
return list(filter(lambda x: not x.startswith('_') and callable(getattr(method, x)), dir(method)))
def loading_data(self, trade_date):
"""
获取基础数据
按天获取当天交易日所有股票的基础数据
:param trade_date: 交易日
:return:
"""
# 转换时间格式
time_array = datetime.strptime(trade_date, "%Y-%m-%d")
trade_date = datetime.strftime(time_array, '%Y%m%d')
# 读取目前涉及到的因子
engine = sqlEngine()
columns = ['COMPCODE', 'PUBLISHDATE', 'ENDDATE', 'symbol', 'company_id', 'trade_date']
# MRQ data
balance_mrq_sets = engine.fetch_fundamentals_pit_extend_company_id(BalanceMRQ,
[BalanceMRQ.BDSPAYA,
BalanceMRQ.TOTASSET,
BalanceMRQ.TOTALNONCLIAB,
BalanceMRQ.TOTCURRASSET,
BalanceMRQ.TOTALCURRLIAB,
BalanceMRQ.TOTLIAB,
BalanceMRQ.FIXEDASSENET,
BalanceMRQ.PARESHARRIGH,
BalanceMRQ.SHORTTERMBORR,
BalanceMRQ.DUENONCLIAB,
BalanceMRQ.LONGBORR,
BalanceMRQ.BDSPAYA,
BalanceMRQ.INTEPAYA,
BalanceMRQ.RIGHAGGR,
BalanceMRQ.TOTALNONCASSETS,
BalanceMRQ.INVE,
BalanceMRQ.INTAASSET,
# BalanceMRQ.DEVEEXPE,
BalanceMRQ.GOODWILL,
BalanceMRQ.LOGPREPEXPE,
BalanceMRQ.DEFETAXASSET,
BalanceMRQ.CURFDS,
BalanceMRQ.TRADFINASSET,
BalanceMRQ.NOTESRECE,
BalanceMRQ.ACCORECE,
BalanceMRQ.OTHERRECE,
], dates=[trade_date])
for col in columns:
if col in list(balance_mrq_sets.keys()):
balance_mrq_sets = balance_mrq_sets.drop(col, axis=1)
balance_mrq_sets = balance_mrq_sets.rename(columns={
'TOTLIAB': 'total_liability', # 负债合计
'TOTASSET': 'total_assets', # 资产总计
'TOTALCURRLIAB': 'total_current_liability', # 流动负债合计
'TOTCURRASSET': 'total_current_assets', # 流动资产合计
'INVE': 'inventories', # 存货
'CURFDS': 'cash_equivalents', # 货币资金
'TRADFINASSET': 'trading_assets', # 交易性金融资产
'NOTESRECE': 'bill_receivable', # 应收票据
'ACCORECE': 'account_receivable', # 应收账款
'OTHERRECE': 'other_receivable', # 其他应收款
'PARESHARRIGH': 'equities_parent_company_owners', # 归属于母公司股东权益合计
'INTAASSET': 'intangible_assets', # 无形资产
# 'DEVEEXPE': 'development_expenditure', # 开发支出
'GOODWILL': 'good_will', # 商誉
'LOGPREPEXPE': 'long_deferred_expense', # 长期待摊费用
'DEFETAXASSET': 'deferred_tax_assets', # 递延所得税资产
'DUENONCLIAB': 'non_current_liability_in_one_year', # 一年内到期的非流动负债
'SHORTTERMBORR': 'shortterm_loan', # 短期借款
'LONGBORR': 'longterm_loan', # 长期借款
'BDSPAYA': 'bonds_payable', # 应付债券
'INTEPAYA': 'interest_payable', # 应付利息
'TOTALNONCLIAB': 'total_non_current_liability', # 非流动负债合计
'TOTALNONCASSETS': 'total_non_current_assets', # 非流动资产合计
'FIXEDASSENET': 'fixed_assets', # 固定资产
'RIGHAGGR': 'total_owner_equities', # 所有者权益(或股东权益)合计
'FINALCASHBALA': 'cash_and_equivalents_at_end', # 期末现金及现金等价物余额
})
cash_flow_mrq_sets = engine.fetch_fundamentals_pit_extend_company_id(CashFlowMRQ,
[CashFlowMRQ.MANANETR,
], dates=[trade_date])
for col in columns:
if col in list(cash_flow_mrq_sets.keys()):
cash_flow_mrq_sets = cash_flow_mrq_sets.drop(col, axis=1)
cash_flow_mrq_sets = cash_flow_mrq_sets.rename(columns={'MANANETR': 'net_operate_cash_flow_mrq', # 经营活动现金流量净额
})
mrq_solvency = pd.merge(cash_flow_mrq_sets, balance_mrq_sets, on='security_code')
# ttm data
income_ttm_sets = engine.fetch_fundamentals_pit_extend_company_id(IncomeTTM,
[IncomeTTM.TOTPROFIT,
IncomeTTM.FINEXPE,
# IncomeTTM.INTEINCO,
], dates=[trade_date])
for col in columns:
if col in list(income_ttm_sets.keys()):
income_ttm_sets = income_ttm_sets.drop(col, axis=1)
income_ttm_sets = income_ttm_sets.rename(columns={'TOTPROFIT': 'total_profit', # 利润总额
'FINEXPE': 'financial_expense', # 财务费用
# 'INTEINCO': 'interest_income', # 利息收入
})
balance_ttm_sets = engine.fetch_fundamentals_pit_extend_company_id(BalanceTTM,
[
BalanceTTM.TOTALCURRLIAB,
BalanceTTM.DUENONCLIAB,
], dates=[trade_date])
for col in columns:
if col in list(balance_ttm_sets.keys()):
balance_ttm_sets = balance_ttm_sets.drop(col, axis=1)
balance_ttm_sets = balance_ttm_sets.rename(columns={
'TOTALCURRLIAB': 'total_current_liability_ttm', # 流动负债合计
'DUENONCLIAB': 'non_current_liability_in_one_year_ttm', # 一年内到期的非流动负债
})
cash_flow_ttm_sets = engine.fetch_fundamentals_pit_extend_company_id(CashFlowTTM,
[CashFlowTTM.MANANETR, # 经营活动现金流量净额
CashFlowTTM.FINALCASHBALA, # 期末现金及现金等价物余额
], dates=[trade_date])
for col in columns:
if col in list(cash_flow_ttm_sets.keys()):
cash_flow_ttm_sets = cash_flow_ttm_sets.drop(col, axis=1)
cash_flow_ttm_sets = cash_flow_ttm_sets.rename(columns={
'MANANETR': 'net_operate_cash_flow', # 经营活动现金流量净额
'FINALCASHBALA': 'cash_and_equivalents_at_end', # 期末现金及现金等价物余额
})
indicator_ttm_sets = engine.fetch_fundamentals_pit_extend_company_id(IndicatorTTM,
[IndicatorTTM.NDEBT,
], dates=[trade_date])
for col in columns:
if col in list(indicator_ttm_sets.keys()):
indicator_ttm_sets = indicator_ttm_sets.drop(col, axis=1)
indicator_ttm_sets = indicator_ttm_sets.rename(columns={'NDEBT': 'net_liability', # 净负债
})
ttm_solvency = pd.merge(balance_ttm_sets, cash_flow_ttm_sets, how='outer', on="security_code")
ttm_solvency = pd.merge(ttm_solvency, income_ttm_sets, how='outer', on="security_code")
ttm_solvency = pd.merge(ttm_solvency, indicator_ttm_sets, how='outer', on="security_code")
column = ['trade_date']
valuation_sets = get_fundamentals(query(Valuation.security_code,
Valuation.trade_date,
Valuation.market_cap, )
.filter(Valuation.trade_date.in_([trade_date])))
for col in column:
if col in list(valuation_sets.keys()):
valuation_sets = valuation_sets.drop(col, axis=1)
tp_solvency = pd.merge(ttm_solvency, valuation_sets, how='outer', on='security_code')
tp_solvency = pd.merge(tp_solvency, mrq_solvency, how='outer', on='security_code')
return tp_solvency
def process_calc_factor(self, trade_date, tp_solvency):
tp_solvency = tp_solvency.set_index('security_code')
solvency = factor_solvency.FactorSolvency()
# 读取目前涉及到的因子
solvency_sets = pd.DataFrame()
solvency_sets['security_code'] = tp_solvency.index
solvency_sets = solvency_sets.set_index('security_code')
# MRQ计算
solvency_sets = solvency.BondsToAsset(tp_solvency, solvency_sets)
solvency_sets = solvency.BookLev(tp_solvency, solvency_sets)
solvency_sets = solvency.CurrentRatio(tp_solvency, solvency_sets)
solvency_sets = solvency.DA(tp_solvency, solvency_sets)
solvency_sets = solvency.DTE(tp_solvency, solvency_sets)
solvency_sets = solvency.EquityRatio(tp_solvency, solvency_sets)
solvency_sets = solvency.EquityPCToIBDebt(tp_solvency, solvency_sets)
solvency_sets = solvency.EquityPCToTCap(tp_solvency, solvency_sets)
solvency_sets = solvency.IntBDToCap(tp_solvency, solvency_sets)
solvency_sets = solvency.LDebtToWCap(tp_solvency, solvency_sets)
solvency_sets = solvency.MktLev(tp_solvency, solvency_sets)
solvency_sets = solvency.QuickRatio(tp_solvency, solvency_sets)
solvency_sets = solvency.SupQuickRatio(tp_solvency, solvency_sets)
# solvency_sets = solvency.TNWorthToIBDebt(tp_solvency, solvency_sets)
solvency_sets = solvency.TNWorthToNDebt(tp_solvency, solvency_sets)
solvency_sets = solvency.OPCToDebt(tp_solvency, solvency_sets)
solvency_sets = solvency.OptCFToCurrLiability(tp_solvency, solvency_sets)
# TTM计算
# solvency_sets = solvency.InterestCovTTM(tp_solvency, solvency_sets)
solvency_sets = solvency.OptCFToLiabilityTTM(tp_solvency, solvency_sets)
solvency_sets = solvency.OptCFToIBDTTM(tp_solvency, solvency_sets)
solvency_sets = solvency.OptCFToNetDebtTTM(tp_solvency, solvency_sets)
solvency_sets = solvency.OPCToDebtTTM(tp_solvency, solvency_sets)
solvency_sets = solvency.CashRatioTTM(tp_solvency, solvency_sets)
solvency_sets = solvency_sets.reset_index()
solvency_sets['trade_date'] = str(trade_date)
solvency_sets.replace([-np.inf, np.inf, None], np.nan, inplace=True)
return solvency_sets
def local_run(self, trade_date):
print('当前交易日: %s' % trade_date)
tic = time.time()
tp_solvency = self.loading_data(trade_date)
print('data load time %s' % (time.time()-tic))
storage_engine = StorageEngine(self._url)
result = self.process_calc_factor(trade_date, tp_solvency)
print('cal_time %s' % (time.time() - tic))
storage_engine.update_destdb(str(self._methods[-1]['packet'].split('.')[-1]), trade_date, result)
# storage_engine.update_destdb('factor_solvency', trade_date, result)
# def remote_run(self, trade_date):
# total_data = self.loading_data(trade_date)
# #存储数据
# session = str(int(time.time() * 1000000 + datetime.datetime.now().microsecond))
# cache_data.set_cache(session, 'alphax', total_data.to_json(orient='records'))
# distributed_factor.delay(session, json.dumps(self._methods), self._name)
#
# def distributed_factor(self, total_data):
# mkt_df = self.calc_factor_by_date(total_data,trade_date)
# result = self.calc_factor('alphax.alpha191','Alpha191',mkt_df,trade_date)
# @app.task
# def distributed_factor(session, trade_date, packet_sets, name):
# calc_engines = CalcEngine(name, packet_sets)
# content = cache_data.get_cache(session, factor_name)
# total_data = json_normalize(json.loads(content))
# calc_engines.distributed_factor(total_data)
#
# # @app.task()
# def factor_calculate(**kwargs):
# print("solvency_kwargs: {}".format(kwargs))
# date_index = kwargs['date_index']
# session = kwargs['session']
# content1 = cache_data.get_cache(session + str(date_index) + "1", date_index)
# tp_solvency = json_normalize(json.loads(str(content1, encoding='utf8')))
# tp_solvency.set_index('security_code', inplace=True)
# print("len_tp_cash_flow_data {}".format(len(tp_solvency)))
# calculate(date_index, tp_solvency)
|
<filename>parse_halos.py
#!/usr/bin/env python
"""
@file parse_halos.py
@brief Script to extract halos from binary simulation output file
@author <NAME> <<EMAIL>>
Usage: python parse_halos.py > halos.txt
Note: the infile halo.z=00.0000 must be in the same directory.
"""
import numpy as np
import struct
infile = "halo.z=00.0000"
fp = open(infile,"rb")
FileContent = fp.read()
# number of halos
nh, = struct.unpack('q',FileContent[0:8])
# halo ID
ID = np.zeros(nh)
# redshift (blank)
z = np.zeros(nh)
# distance [comoving Mpc/h] (blank)
d = np.zeros(nh)
# phi angle [deg] (blank)
phi = np.zeros(nh)
# theta angle [deg] (blank)
theta = np.zeros(nh)
# 3D position [comoving Mpc/h]
x_p = np.zeros(nh)
y_p = np.zeros(nh)
z_p = np.zeros(nh)
# 3D velocity [proper km/s]
x_v = np.zeros(nh)
y_v = np.zeros(nh)
z_v = np.zeros(nh)
# num of particles s.t. <density> = 200*cosmic density (a)
N200a = np.zeros(nh)
# mass [Msolar/h] corresponding to...
M200a = np.zeros(nh)
# ...radius [proper Mpc/h]
R200a = np.zeros(nh)
# velocity dispersion [proper km/s]
s200a = np.zeros(nh)
# num of particles s.t. <density> = 500*cosmic density (a)
N500a = np.zeros(nh)
M500a = np.zeros(nh)
R500a = np.zeros(nh)
s500a = np.zeros(nh)
# num of particles s.t. <density> = 200*critical density (c)
N200c = np.zeros(nh)
M200c = np.zeros(nh)
R200c = np.zeros(nh)
s200c = np.zeros(nh)
# num of particles s.t. <density> = 500*critical density (c)
N500c = np.zeros(nh)
M500c = np.zeros(nh)
R500c = np.zeros(nh)
s500c = np.zeros(nh)
# max circular velocity [proper km/s]
vcmax = np.zeros(nh)
# mass [Msolar/h] corresponding to vcmax
Mcmax = np.zeros(nh)
# radius [proper Mpc/h] corresponding to vcmax
rcmax = np.zeros(nh)
# 1(8) + 29(4)
halo_struct_size = 124
for i in range(nh):
first_byte = 8+i*halo_struct_size
"""
ID is allocated 8 bytes in the binary file, but you only need 4,
so bytes 4-8 of each struct are skipped. The halos are in numerical
order, so I output i+1 rather than this value.
"""
ID[i], = struct.unpack('i',FileContent[first_byte:first_byte+4])
z[i], = struct.unpack('f',FileContent[first_byte+8:first_byte+12])
d[i], = struct.unpack('f',FileContent[first_byte+12:first_byte+16])
phi[i], = struct.unpack('f',FileContent[first_byte+16:first_byte+20])
theta[i], = struct.unpack('f',FileContent[first_byte+20:first_byte+24])
x_p[i], = struct.unpack('f',FileContent[first_byte+24:first_byte+28])
y_p[i], = struct.unpack('f',FileContent[first_byte+28:first_byte+32])
z_p[i], = struct.unpack('f',FileContent[first_byte+32:first_byte+36])
x_v[i], = struct.unpack('f',FileContent[first_byte+36:first_byte+40])
y_v[i], = struct.unpack('f',FileContent[first_byte+40:first_byte+44])
z_v[i], = struct.unpack('f',FileContent[first_byte+44:first_byte+48])
N200a[i], = struct.unpack('i',FileContent[first_byte+48:first_byte+52])
M200a[i], = struct.unpack('f',FileContent[first_byte+52:first_byte+56])
R200a[i], = struct.unpack('f',FileContent[first_byte+56:first_byte+60])
s200a[i], = struct.unpack('f',FileContent[first_byte+60:first_byte+64])
N500a[i], = struct.unpack('i',FileContent[first_byte+64:first_byte+68])
M500a[i], = struct.unpack('f',FileContent[first_byte+68:first_byte+72])
R500a[i], = struct.unpack('f',FileContent[first_byte+72:first_byte+76])
s500a[i], = struct.unpack('f',FileContent[first_byte+76:first_byte+80])
N200c[i], = struct.unpack('i',FileContent[first_byte+80:first_byte+84])
M200c[i], = struct.unpack('f',FileContent[first_byte+84:first_byte+88])
R200c[i], = struct.unpack('f',FileContent[first_byte+88:first_byte+92])
s200c[i], = struct.unpack('f',FileContent[first_byte+92:first_byte+96])
N500c[i], = struct.unpack('i',FileContent[first_byte+96:first_byte+100])
M500c[i], = struct.unpack('f',FileContent[first_byte+100:first_byte+104])
R500c[i], = struct.unpack('f',FileContent[first_byte+104:first_byte+108])
s500c[i], = struct.unpack('f',FileContent[first_byte+108:first_byte+112])
vcmax[i], = struct.unpack('f',FileContent[first_byte+112:first_byte+116])
Mcmax[i], = struct.unpack('f',FileContent[first_byte+116:first_byte+120])
rcmax[i], = struct.unpack('f',FileContent[first_byte+120:first_byte+124])
# currently omitting blank properties z, d, phi, and theta:
# , '\t', z[i], '\t', d[i], '\t', phi[i], '\t', theta[i] \
print i+1 \
, '\t', x_p[i], '\t', y_p[i], '\t', z_p[i] \
, '\t', x_v[i], '\t', y_v[i], '\t', z_v[i] \
, '\t', N200a[i], '\t', M200a[i], '\t', R200a[i], '\t', s200a[i] \
, '\t', N500a[i], '\t', M500a[i], '\t', R500a[i], '\t', s500a[i] \
, '\t', N200c[i], '\t', M200c[i], '\t', R200c[i], '\t', s200c[i] \
, '\t', N500c[i], '\t', M500c[i], '\t', R500c[i], '\t', s500c[i] \
, '\t', vcmax[i], '\t', Mcmax[i], '\t', rcmax[i]
|
<reponame>saiakhil0034/SemanticSegmentation<filename>dataloader.py
from torch.utils.data import Dataset, DataLoader# For custom data-sets
import torchvision.transforms as transforms
import numpy as np
from PIL import Image, ImageOps
import torch
import pandas as pd
from collections import namedtuple
import matplotlib.pyplot as plt
import torchvision.transforms.functional as TF
import sys
n_class = 34
means = np.array([103.939, 116.779, 123.68]) / 255. # mean of three channels in the order of BGR
# a label and all meta information
Label = namedtuple( 'Label' , [
'name' , # The identifier of this label, e.g. 'car', 'person', ... .
# We use them to uniquely name a class
'id' , # An integer ID that is associated with this label.
# The IDs are used to represent the label in ground truth images
# An ID of -1 means that this label does not have an ID and thus
# is ignored when creating ground truth images (e.g. license plate).
'trainId' , # An integer ID that overwrites the ID above, when creating ground truth
# images for training.
# For training, multiple labels might have the same ID. Then, these labels
# are mapped to the same class in the ground truth images. For the inverse
# mapping, we use the label that is defined first in the list below.
# For example, mapping all void-type classes to the same ID in training,
# might make sense for some approaches.
'category' , # The name of the category that this label belongs to
'categoryId' , # The ID of this category. Used to create ground truth images
# on category level.
'hasInstances', # Whether this label distinguishes between single instances or not
'ignoreInEval', # Whether pixels having this class as ground truth label are ignored
# during evaluations or not
'color' , # The color of this label
] )
labels_classes = [
# name id trainId category catId hasInstances ignoreInEval color
Label( 'unlabeled' , 0 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),
Label( 'ego vehicle' , 1 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),
Label( 'rectification border' , 2 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),
Label( 'out of roi' , 3 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),
Label( 'static' , 4 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),
Label( 'dynamic' , 5 , 255 , 'void' , 0 , False , True , (111, 74, 0) ),
Label( 'ground' , 6 , 255 , 'void' , 0 , False , True , ( 81, 0, 81) ),
Label( 'road' , 7 , 0 , 'ground' , 1 , False , False , (128, 64,128) ),
Label( 'sidewalk' , 8 , 1 , 'ground' , 1 , False , False , (244, 35,232) ),
Label( 'parking' , 9 , 255 , 'ground' , 1 , False , True , (250,170,160) ),
Label( 'rail track' , 10 , 255 , 'ground' , 1 , False , True , (230,150,140) ),
Label( 'building' , 11 , 2 , 'construction' , 2 , False , False , ( 70, 70, 70) ),
Label( 'wall' , 12 , 3 , 'construction' , 2 , False , False , (102,102,156) ),
Label( 'fence' , 13 , 4 , 'construction' , 2 , False , False , (190,153,153) ),
Label( 'guard rail' , 14 , 255 , 'construction' , 2 , False , True , (180,165,180) ),
Label( 'bridge' , 15 , 255 , 'construction' , 2 , False , True , (150,100,100) ),
Label( 'tunnel' , 16 , 255 , 'construction' , 2 , False , True , (150,120, 90) ),
Label( 'pole' , 17 , 5 , 'object' , 3 , False , False , (153,153,153) ),
Label( 'polegroup' , 18 , 255 , 'object' , 3 , False , True , (153,153,153) ),
Label( 'traffic light' , 19 , 6 , 'object' , 3 , False , False , (250,170, 30) ),
Label( 'traffic sign' , 20 , 7 , 'object' , 3 , False , False , (220,220, 0) ),
Label( 'vegetation' , 21 , 8 , 'nature' , 4 , False , False , (107,142, 35) ),
Label( 'terrain' , 22 , 9 , 'nature' , 4 , False , False , (152,251,152) ),
Label( 'sky' , 23 , 10 , 'sky' , 5 , False , False , ( 70,130,180) ),
Label( 'person' , 24 , 11 , 'human' , 6 , True , False , (220, 20, 60) ),
Label( 'rider' , 25 , 12 , 'human' , 6 , True , False , (255, 0, 0) ),
Label( 'car' , 26 , 13 , 'vehicle' , 7 , True , False , ( 0, 0,142) ),
Label( 'truck' , 27 , 14 , 'vehicle' , 7 , True , False , ( 0, 0, 70) ),
Label( 'bus' , 28 , 15 , 'vehicle' , 7 , True , False , ( 0, 60,100) ),
Label( 'caravan' , 29 , 255 , 'vehicle' , 7 , True , True , ( 0, 0, 90) ),
Label( 'trailer' , 30 , 255 , 'vehicle' , 7 , True , True , ( 0, 0,110) ),
Label( 'train' , 31 , 16 , 'vehicle' , 7 , True , False , ( 0, 80,100) ),
Label( 'motorcycle' , 32 , 17 , 'vehicle' , 7 , True , False , ( 0, 0,230) ),
Label( 'bicycle' , 33 , 18 , 'vehicle' , 7 , True , False , (119, 11, 32) )
]
idsColor = dict((x.id,list(x.color)) for x in labels_classes)
idsNames = dict((x.id,x.name) for x in labels_classes)
a = list(filter(lambda x: x.trainId != 255, labels_classes))
useful_ids = [x.id for x in a]
class CityScapesDataset(Dataset):
def __init__(self, csv_file, n_class=n_class, transforms=None):
self.data = pd.read_csv(csv_file)
self.means = means
self.n_class = n_class
self.mode = csv_file
# Add any transformations here
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
img_name = self.data.iloc[idx, 0]
img_full = Image.open(img_name).convert('RGB')
label_name = self.data.iloc[idx, 1]
label_full = Image.open(label_name)
if('train' in self.mode or 'val' in self.mode):
if('train' in self.mode):
if(np.random.random() > 0.2):
if(np.random.random() > 0.5):
a = np.random.random()*5
img_full = TF.rotate(img_full, a)
label_full = TF.rotate(label_full, a)
else:
a = np.random.random()*5
img_full = TF.rotate(img_full, -1*a)
label_full = TF.rotate(label_full, -1*a)
#img, label = self.resize_image(img_full, label_full)
img, label = self.crop_image(img_full, label_full)
img, label = self.rhflip(img, label)
if('val' in self.mode):
img, label = self.crop_image(img_full, label_full)
else:
img, label = img_full, label_full
img = np.asarray(img)
label = np.asarray(label)
# reduce mean
img = img[:, :, ::-1] # switch to BGR
img = np.transpose(img, (2, 0, 1)) / 255.
img[0] -= self.means[0]
img[1] -= self.means[1]
img[2] -= self.means[2]
# convert to tensor
img = torch.from_numpy(img.copy()).float()
img_full = torch.from_numpy(np.array(img_full).copy()).float()
label = torch.from_numpy(label.copy()).long()
# create one-hot encoding
h, w = label.shape
target = torch.zeros(self.n_class, h, w)
for c in range(self.n_class):
target[c][label == c] = 1
return img, target, label
def rhflip(self,img,label,p=0.5):
if (np.random.random() > p):
return ImageOps.mirror(img), ImageOps.mirror(label)
else:
return img,label
def rvflip(self,img,label,p=0.5):
if (np.random.random() > p):
return ImageOps.flip(img), ImageOps.flip(label)
else:
return img,label
def resize_image(self, img, label, image_resize=(512,256)):
img = img.resize((image_resize[0], image_resize[1]))
label = label.resize((image_resize[0], image_resize[1]))
return img, label
def crop_image(self, img, label, image_size=(512, 256)):
i = np.random.randint(img.size[0] - image_size[0])
j = np.random.randint(img.size[1] - image_size[1])
img = img.crop([i, j, i+image_size[0], j+image_size[1]])
label = label.crop([i, j, i+image_size[0], j+image_size[1]])
return img, label
|
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Base class for gsutil commands.
In addition to base class code, this file contains helpers that depend on base
class state (such as GetAclCommandHelper, which depends on self.gsutil_bin_dir,
self.bucket_storage_uri_class, etc.) In general, functions that depend on class
state and that are used by multiple commands belong in this file. Functions that
don't depend on class state belong in util.py, and non-shared helpers belong in
individual subclasses.
"""
import boto
import getopt
import gslib
import logging
import multiprocessing
import os
import platform
import re
import sys
import wildcard_iterator
import xml.dom.minidom
from boto import handler
from boto.storage_uri import StorageUri
from getopt import GetoptError
from gslib import util
from gslib.exception import CommandException
from gslib.help_provider import HelpProvider
from gslib.name_expansion import NameExpansionIterator
from gslib.name_expansion import NameExpansionIteratorQueue
from gslib.project_id import ProjectIdHandler
from gslib.storage_uri_builder import StorageUriBuilder
from gslib.thread_pool import ThreadPool
from gslib.util import HAVE_OAUTH2
from gslib.util import NO_MAX
from gslib.wildcard_iterator import ContainsWildcard
def _ThreadedLogger():
"""Creates a logger that resembles 'print' output, but is thread safe.
The logger will display all messages logged with level INFO or above. Log
propagation is disabled.
Returns:
A logger object.
"""
log = logging.getLogger('threaded-logging')
log.propagate = False
log.setLevel(logging.INFO)
log_handler = logging.StreamHandler()
log_handler.setFormatter(logging.Formatter('%(message)s'))
log.addHandler(log_handler)
return log
# command_spec key constants.
COMMAND_NAME = 'command_name'
COMMAND_NAME_ALIASES = 'command_name_aliases'
MIN_ARGS = 'min_args'
MAX_ARGS = 'max_args'
SUPPORTED_SUB_ARGS = 'supported_sub_args'
FILE_URIS_OK = 'file_uri_ok'
PROVIDER_URIS_OK = 'provider_uri_ok'
URIS_START_ARG = 'uris_start_arg'
CONFIG_REQUIRED = 'config_required'
_EOF_NAME_EXPANSION_RESULT = ("EOF")
class Command(object):
# Global instance of a threaded logger object.
THREADED_LOGGER = _ThreadedLogger()
REQUIRED_SPEC_KEYS = [COMMAND_NAME]
# Each subclass must define the following map, minimally including the
# keys in REQUIRED_SPEC_KEYS; other values below will be used as defaults,
# although for readbility subclasses should specify the complete map.
command_spec = {
# Name of command.
COMMAND_NAME : None,
# List of command name aliases.
COMMAND_NAME_ALIASES : [],
# Min number of args required by this command.
MIN_ARGS : 0,
# Max number of args required by this command, or NO_MAX.
MAX_ARGS : NO_MAX,
# Getopt-style string specifying acceptable sub args.
SUPPORTED_SUB_ARGS : '',
# True if file URIs are acceptable for this command.
FILE_URIS_OK : False,
# True if provider-only URIs are acceptable for this command.
PROVIDER_URIS_OK : False,
# Index in args of first URI arg.
URIS_START_ARG : 0,
# True if must configure gsutil before running command.
CONFIG_REQUIRED : True,
}
_default_command_spec = command_spec
help_spec = HelpProvider.help_spec
"""Define an empty test specification, which derived classes must populate.
This is a list of tuples containing the following values:
step_name - mnemonic name for test, displayed when test is run
cmd_line - shell command line to run test
expect_ret or None - expected return code from test (None means ignore)
(result_file, expect_file) or None - tuple of result file and expected
file to diff for additional test
verification beyond the return code
(None means no diff requested)
Notes:
- Setting expected_ret to None means there is no expectation and,
hence, any returned value will pass.
- Any occurrences of the string 'gsutil' in the cmd_line parameter
are expanded to the full path to the gsutil command under test.
- The cmd_line, result_file and expect_file parameters may
contain the following special substrings:
$Bn - converted to one of 10 unique-for-testing bucket names (n=0..9)
$On - converted to one of 10 unique-for-testing object names (n=0..9)
$Fn - converted to one of 10 unique-for-testing file names (n=0..9)
$G - converted to the directory where gsutil is installed. Useful for
referencing test data.
- The generated file names are full pathnames, whereas the generated
bucket and object names are simple relative names.
- Tests with a non-None result_file and expect_file automatically
trigger an implicit diff of the two files.
- These test specifications, in combination with the conversion strings
allow tests to be constructed parametrically. For example, here's an
annotated subset of a test_steps for the cp command:
# Copy local file to object, verify 0 return code.
('simple cp', 'gsutil cp $F1 gs://$B1/$O1', 0, None, None),
# Copy uploaded object back to local file and diff vs. orig file.
('verify cp', 'gsutil cp gs://$B1/$O1 $F2', 0, '$F2', '$F1'),
- After pattern substitution, the specs are run sequentially, in the
order in which they appear in the test_steps list.
"""
test_steps = []
# Define a convenience property for command name, since it's used many places.
def _GetDefaultCommandName(self):
return self.command_spec[COMMAND_NAME]
command_name = property(_GetDefaultCommandName)
def __init__(self, command_runner, args, headers, debug, parallel_operations,
gsutil_bin_dir, boto_lib_dir, config_file_list, gsutil_ver,
bucket_storage_uri_class, test_method=None):
"""
Args:
command_runner: CommandRunner (for commands built atop other commands).
args: Command-line args (arg0 = actual arg, not command name ala bash).
headers: Dictionary containing optional HTTP headers to pass to boto.
debug: Debug level to pass in to boto connection (range 0..3).
parallel_operations: Should command operations be executed in parallel?
gsutil_bin_dir: Bin dir from which gsutil is running.
boto_lib_dir: Lib dir where boto runs.
config_file_list: Config file list returned by _GetBotoConfigFileList().
gsutil_ver: Version string of currently running gsutil command.
bucket_storage_uri_class: Class to instantiate for cloud StorageUris.
Settable for testing/mocking.
test_method: Optional general purpose method for testing purposes.
Application and semantics of this method will vary by
command and test type.
Implementation note: subclasses shouldn't need to define an __init__
method, and instead depend on the shared initialization that happens
here. If you do define an __init__ method in a subclass you'll need to
explicitly call super().__init__(). But you're encouraged not to do this,
because it will make changing the __init__ interface more painful.
"""
# Save class values from constructor params.
self.command_runner = command_runner
self.args = args
self.unparsed_args = args
self.headers = headers
self.debug = debug
self.parallel_operations = parallel_operations
self.gsutil_bin_dir = gsutil_bin_dir
self.boto_lib_dir = boto_lib_dir
self.config_file_list = config_file_list
self.gsutil_ver = gsutil_ver
self.bucket_storage_uri_class = bucket_storage_uri_class
self.test_method = test_method
self.exclude_symlinks = False
self.recursion_requested = False
self.all_versions = False
# Process sub-command instance specifications.
# First, ensure subclass implementation sets all required keys.
for k in self.REQUIRED_SPEC_KEYS:
if k not in self.command_spec or self.command_spec[k] is None:
raise CommandException('"%s" command implementation is missing %s '
'specification' % (self.command_name, k))
# Now override default command_spec with subclass-specified values.
tmp = self._default_command_spec
tmp.update(self.command_spec)
self.command_spec = tmp
del tmp
# Make sure command provides a test specification.
if not self.test_steps:
# TODO: Uncomment following lines when test feature is ready.
#raise CommandException('"%s" command implementation is missing test '
#'specification' % self.command_name)
pass
# Parse and validate args.
try:
(self.sub_opts, self.args) = getopt.getopt(
args, self.command_spec[SUPPORTED_SUB_ARGS])
except GetoptError, e:
raise CommandException('%s for "%s" command.' % (e.msg,
self.command_name))
if (len(self.args) < self.command_spec[MIN_ARGS]
or len(self.args) > self.command_spec[MAX_ARGS]):
raise CommandException('Wrong number of arguments for "%s" command.' %
self.command_name)
if (not self.command_spec[FILE_URIS_OK]
and self.HaveFileUris(self.args[self.command_spec[URIS_START_ARG]:])):
raise CommandException('"%s" command does not support "file://" URIs. '
'Did you mean to use a gs:// URI?' %
self.command_name)
if (not self.command_spec[PROVIDER_URIS_OK]
and self._HaveProviderUris(
self.args[self.command_spec[URIS_START_ARG]:])):
raise CommandException('"%s" command does not support provider-only '
'URIs.' % self.command_name)
if self.command_spec[CONFIG_REQUIRED]:
self._ConfigureNoOpAuthIfNeeded()
self.proj_id_handler = ProjectIdHandler()
self.suri_builder = StorageUriBuilder(debug, bucket_storage_uri_class)
# Cross-platform path to run gsutil binary.
self.gsutil_cmd = ''
# Cross-platform list containing gsutil path for use with subprocess.
self.gsutil_exec_list = []
# If running on Windows, invoke python interpreter explicitly.
if platform.system() == "Windows":
self.gsutil_cmd += 'python '
self.gsutil_exec_list += ['python']
# Add full path to gsutil to make sure we test the correct version.
self.gsutil_path = os.path.join(self.gsutil_bin_dir, 'gsutil')
self.gsutil_cmd += self.gsutil_path
self.gsutil_exec_list += [self.gsutil_path]
# We're treating recursion_requested like it's used by all commands, but
# only some of the commands accept the -R option.
if self.sub_opts:
for o, unused_a in self.sub_opts:
if o == '-r' or o == '-R':
self.recursion_requested = True
break
def WildcardIterator(self, uri_or_str, all_versions=False):
"""
Helper to instantiate gslib.WildcardIterator. Args are same as
gslib.WildcardIterator interface, but this method fills in most of the
values from instance state.
Args:
uri_or_str: StorageUri or URI string naming wildcard objects to iterate.
"""
return wildcard_iterator.wildcard_iterator(
uri_or_str, self.proj_id_handler,
bucket_storage_uri_class=self.bucket_storage_uri_class,
all_versions=all_versions,
headers=self.headers, debug=self.debug)
def RunCommand(self):
"""Abstract function in base class. Subclasses must implement this. The
return value of this function will be used as the exit status of the
process, so subclass commands should return an integer exit code (0 for
success, a value in [1,255] for failure).
"""
raise CommandException('Command %s is missing its RunCommand() '
'implementation' % self.command_name)
############################################################
# Shared helper functions that depend on base class state. #
############################################################
def UrisAreForSingleProvider(self, uri_args):
"""Tests whether the uris are all for a single provider.
Returns: a StorageUri for one of the uris on success, None on failure.
"""
provider = None
uri = None
for uri_str in uri_args:
# validate=False because we allow wildcard uris.
uri = boto.storage_uri(
uri_str, debug=self.debug, validate=False,
bucket_storage_uri_class=self.bucket_storage_uri_class)
if not provider:
provider = uri.scheme
elif uri.scheme != provider:
return None
return uri
def SetAclCommandHelper(self):
"""
Common logic for setting ACLs. Sets the standard ACL or the default
object ACL depending on self.command_name.
"""
acl_arg = self.args[0]
uri_args = self.args[1:]
# Disallow multi-provider setacl requests, because there are differences in
# the ACL models.
storage_uri = self.UrisAreForSingleProvider(uri_args)
if not storage_uri:
raise CommandException('"%s" command spanning providers not allowed.' %
self.command_name)
# Determine whether acl_arg names a file containing XML ACL text vs. the
# string name of a canned ACL.
if os.path.isfile(acl_arg):
acl_file = open(acl_arg, 'r')
acl_arg = acl_file.read()
# TODO: Remove this workaround when GCS allows
# whitespace in the Permission element on the server-side
acl_arg = re.sub(r'<Permission>\s*(\S+)\s*</Permission>',
r'<Permission>\1</Permission>', acl_arg)
acl_file.close()
self.canned = False
else:
# No file exists, so expect a canned ACL string.
canned_acls = storage_uri.canned_acls()
if acl_arg not in canned_acls:
raise CommandException('Invalid canned ACL "%s".' % acl_arg)
self.canned = True
# Used to track if any ACLs failed to be set.
self.everything_set_okay = True
def _SetAclExceptionHandler(e):
"""Simple exception handler to allow post-completion status."""
self.THREADED_LOGGER.error(str(e))
self.everything_set_okay = False
def _SetAclFunc(name_expansion_result):
exp_src_uri = self.suri_builder.StorageUri(
name_expansion_result.GetExpandedUriStr())
# We don't do bucket operations multi-threaded (see comment below).
assert self.command_name != 'setdefacl'
self.THREADED_LOGGER.info('Setting ACL on %s...' %
name_expansion_result.expanded_uri_str)
if self.canned:
exp_src_uri.set_acl(acl_arg, exp_src_uri.object_name, False,
self.headers)
else:
exp_src_uri.set_xml_acl(acl_arg, exp_src_uri.object_name, False,
self.headers)
# If user specified -R option, convert any bucket args to bucket wildcards
# (e.g., gs://bucket/*), to prevent the operation from being applied to
# the buckets themselves.
if self.recursion_requested:
for i in range(len(uri_args)):
uri = self.suri_builder.StorageUri(uri_args[i])
if uri.names_bucket():
uri_args[i] = uri.clone_replace_name('*').uri
else:
# Handle bucket ACL setting operations single-threaded, because
# our threading machinery currently assumes it's working with objects
# (name_expansion_iterator), and normally we wouldn't expect users to need
# to set ACLs on huge numbers of buckets at once anyway.
for i in range(len(uri_args)):
uri_str = uri_args[i]
if self.suri_builder.StorageUri(uri_str).names_bucket():
self._RunSingleThreadedSetAcl(acl_arg, uri_args)
return
name_expansion_iterator = NameExpansionIterator(
self.command_name, self.proj_id_handler, self.headers, self.debug,
self.bucket_storage_uri_class, uri_args, self.recursion_requested,
self.recursion_requested, all_versions=self.all_versions)
# Perform requests in parallel (-m) mode, if requested, using
# configured number of parallel processes and threads. Otherwise,
# perform requests with sequential function calls in current process.
self.Apply(_SetAclFunc, name_expansion_iterator, _SetAclExceptionHandler)
if not self.everything_set_okay:
raise CommandException('ACLs for some objects could not be set.')
def _RunSingleThreadedSetAcl(self, acl_arg, uri_args):
some_matched = False
for uri_str in uri_args:
for blr in self.WildcardIterator(uri_str):
if blr.HasPrefix():
continue
some_matched = True
uri = blr.GetUri()
if self.command_name == 'setdefacl':
print 'Setting default object ACL on %s...' % uri
if self.canned:
uri.set_def_acl(acl_arg, uri.object_name, False, self.headers)
else:
uri.set_def_xml_acl(acl_arg, False, self.headers)
else:
print 'Setting ACL on %s...' % uri
if self.canned:
uri.set_acl(acl_arg, uri.object_name, False, self.headers)
else:
uri.set_xml_acl(acl_arg, uri.object_name, False, self.headers)
if not some_matched:
raise CommandException('No URIs matched')
def GetAclCommandHelper(self):
"""Common logic for getting ACLs. Gets the standard ACL or the default
object ACL depending on self.command_name."""
# Resolve to just one object.
# Handle wildcard-less URI specially in case this is a version-specific
# URI, because WildcardIterator().IterUris() would lose the versioning info.
if not ContainsWildcard(self.args[0]):
uri = self.suri_builder.StorageUri(self.args[0])
else:
uris = list(self.WildcardIterator(self.args[0]).IterUris())
if len(uris) == 0:
raise CommandException('No URIs matched')
if len(uris) != 1:
raise CommandException('%s matched more than one URI, which is not '
'allowed by the %s command' % (self.args[0], self.command_name))
uri = uris[0]
if not uri.names_bucket() and not uri.names_object():
raise CommandException('"%s" command must specify a bucket or '
'object.' % self.command_name)
if self.command_name == 'getdefacl':
acl = uri.get_def_acl(False, self.headers)
else:
acl = uri.get_acl(False, self.headers)
# Pretty-print the XML to make it more easily human editable.
parsed_xml = xml.dom.minidom.parseString(acl.to_xml().encode('utf-8'))
print parsed_xml.toprettyxml(indent=' ')
def GetXmlSubresource(self, subresource, uri_arg):
"""Print an xml subresource, e.g. logging, for a bucket/object.
Args:
subresource: The subresource name.
uri_arg: URI for the bucket/object. Wildcards will be expanded.
Raises:
CommandException: if errors encountered.
"""
# Wildcarding is allowed but must resolve to just one bucket.
uris = list(self.WildcardIterator(uri_arg).IterUris())
if len(uris) != 1:
raise CommandException('Wildcards must resolve to exactly one item for '
'get %s' % subresource)
uri = uris[0]
xml_str = uri.get_subresource(subresource, False, self.headers)
# Pretty-print the XML to make it more easily human editable.
parsed_xml = xml.dom.minidom.parseString(xml_str.encode('utf-8'))
print parsed_xml.toprettyxml(indent=' ')
def Apply(self, func, name_expansion_iterator, thr_exc_handler,
shared_attrs=None):
"""Dispatch input URI assignments across a pool of parallel OS
processes and/or Python threads, based on options (-m or not)
and settings in the user's config file. If non-parallel mode
or only one OS process requested, execute requests sequentially
in the current OS process.
Args:
func: Function to call to process each URI.
name_expansion_iterator: Iterator of NameExpansionResult.
thr_exc_handler: Exception handler for ThreadPool class.
shared_attrs: List of attributes to manage across sub-processes.
Raises:
CommandException if invalid config encountered.
"""
# Set OS process and python thread count as a function of options
# and config.
if self.parallel_operations:
process_count = boto.config.getint(
'GSUtil', 'parallel_process_count',
gslib.commands.config.DEFAULT_PARALLEL_PROCESS_COUNT)
if process_count < 1:
raise CommandException('Invalid parallel_process_count "%d".' %
process_count)
thread_count = boto.config.getint(
'GSUtil', 'parallel_thread_count',
gslib.commands.config.DEFAULT_PARALLEL_THREAD_COUNT)
if thread_count < 1:
raise CommandException('Invalid parallel_thread_count "%d".' %
thread_count)
else:
# If -m not specified, then assume 1 OS process and 1 Python thread.
process_count = 1
thread_count = 1
if self.debug:
self.THREADED_LOGGER.info('process count: %d', process_count)
self.THREADED_LOGGER.info('thread count: %d', thread_count)
if self.parallel_operations and process_count > 1:
procs = []
# If any shared attributes passed by caller, create a dictionary of
# shared memory variables for every element in the list of shared
# attributes.
shared_vars = None
if shared_attrs:
for name in shared_attrs:
if not shared_vars:
shared_vars = {}
shared_vars[name] = multiprocessing.Value('i', 0)
# Construct work queue for parceling out work to multiprocessing workers,
# setting the max queue length of 50k so we will block if workers don't
# empty the queue as fast as we can continue iterating over the bucket
# listing. This number may need tuning; it should be large enough to
# keep workers busy (overlapping bucket list next-page retrieval with
# operations being fed from the queue) but small enough that we don't
# overfill memory when runing across a slow network link.
work_queue = multiprocessing.Queue(50000)
for shard in range(process_count):
# Spawn a separate OS process for each shard.
if self.debug:
self.THREADED_LOGGER.info('spawning process for shard %d', shard)
p = multiprocessing.Process(target=self._ApplyThreads,
args=(func, work_queue, shard,
thread_count, thr_exc_handler,
shared_vars))
procs.append(p)
p.start()
last_name_expansion_result = None
try:
# Feed all work into the queue being emptied by the workers.
for name_expansion_result in name_expansion_iterator:
last_name_expansion_result = name_expansion_result
work_queue.put(name_expansion_result)
except:
sys.stderr.write('Failed URI iteration. Last result (prior to '
'exception) was: %s\n'
% repr(last_name_expansion_result))
finally:
# We do all of the process cleanup in a finally cause in case the name
# expansion iterator throws an exception. This will send EOF to all the
# child processes and join them back into the parent process.
# Send an EOF per worker.
for shard in range(process_count):
work_queue.put(_EOF_NAME_EXPANSION_RESULT)
# Wait for all spawned OS processes to finish.
failed_process_count = 0
for p in procs:
p.join()
# Count number of procs that returned non-zero exit code.
if p.exitcode != 0:
failed_process_count += 1
# Propagate shared variables back to caller's attributes.
if shared_vars:
for (name, var) in shared_vars.items():
setattr(self, name, var.value)
# Abort main process if one or more sub-processes failed. Note that this
# is outside the finally clause, because we only want to raise a new
# exception if an exception wasn't already raised in the try clause above.
if failed_process_count:
plural_str = ''
if failed_process_count > 1:
plural_str = 'es'
raise Exception('unexpected failure in %d sub-process%s, '
'aborting...' % (failed_process_count, plural_str))
else:
# Using just 1 process, so funnel results to _ApplyThreads using facade
# that makes NameExpansionIterator look like a Multiprocessing.Queue
# that sends one EOF once the iterator empties.
work_queue = NameExpansionIteratorQueue(name_expansion_iterator,
_EOF_NAME_EXPANSION_RESULT)
self._ApplyThreads(func, work_queue, 0, thread_count, thr_exc_handler,
None)
def HaveFileUris(self, args_to_check):
"""Checks whether args_to_check contain any file URIs.
Args:
args_to_check: Command-line argument subset to check.
Returns:
True if args_to_check contains any file URIs.
"""
for uri_str in args_to_check:
if uri_str.lower().startswith('file://') or uri_str.find(':') == -1:
return True
return False
######################
# Private functions. #
######################
def _HaveProviderUris(self, args_to_check):
"""Checks whether args_to_check contains any provider URIs (like 'gs://').
Args:
args_to_check: Command-line argument subset to check.
Returns:
True if args_to_check contains any provider URIs.
"""
for uri_str in args_to_check:
if re.match('^[a-z]+://$', uri_str):
return True
return False
def _ConfigureNoOpAuthIfNeeded(self):
"""Sets up no-op auth handler if no boto credentials are configured."""
config = boto.config
if not util.HasConfiguredCredentials():
if self.config_file_list:
if (config.has_option('Credentials', 'gs_oauth2_refresh_token')
and not HAVE_OAUTH2):
raise CommandException(
'Your gsutil is configured with OAuth2 authentication '
'credentials.\nHowever, OAuth2 is only supported when running '
'under Python 2.6 or later\n(unless additional dependencies are '
'installed, see README for details); you are running Python %s.' %
sys.version)
raise CommandException('You have no storage service credentials in any '
'of the following boto config\nfiles. Please '
'add your credentials as described in the '
'gsutil README file, or else\nre-run '
'"gsutil config" to re-create a config '
'file:\n%s' % self.config_file_list)
else:
# With no boto config file the user can still access publicly readable
# buckets and objects.
from gslib import no_op_auth_plugin
def _ApplyThreads(self, func, work_queue, shard, num_threads,
thr_exc_handler=None, shared_vars=None):
"""
Perform subset of required requests across a caller specified
number of parallel Python threads, which may be one, in which
case the requests are processed in the current thread.
Args:
func: Function to call for each request.
work_queue: shared queue of NameExpansionResult to process.
shard: Assigned subset (shard number) for this function.
num_threads: Number of Python threads to spawn to process this shard.
thr_exc_handler: Exception handler for ThreadPool class.
shared_vars: Dict of shared memory variables to be managed.
(only relevant, and non-None, if this function is
run in a separate OS process).
"""
# Each OS process needs to establish its own set of connections to
# the server to avoid writes from different OS processes interleaving
# onto the same socket (and garbling the underlying SSL session).
# We ensure each process gets its own set of connections here by
# closing all connections in the storage provider connection pool.
connection_pool = StorageUri.provider_pool
if connection_pool:
for i in connection_pool:
connection_pool[i].connection.close()
if num_threads > 1:
thread_pool = ThreadPool(num_threads, thr_exc_handler)
try:
while True: # Loop until we hit EOF marker.
name_expansion_result = work_queue.get()
if name_expansion_result == _EOF_NAME_EXPANSION_RESULT:
break
exp_src_uri = self.suri_builder.StorageUri(
name_expansion_result.GetExpandedUriStr())
if self.debug:
self.THREADED_LOGGER.info('process %d shard %d is handling uri %s',
os.getpid(), shard, exp_src_uri)
if (self.exclude_symlinks and exp_src_uri.is_file_uri()
and os.path.islink(exp_src_uri.object_name)):
self.THREADED_LOGGER.info('Skipping symbolic link %s...', exp_src_uri)
elif num_threads > 1:
thread_pool.AddTask(func, name_expansion_result)
else:
func(name_expansion_result)
# If any Python threads created, wait here for them to finish.
if num_threads > 1:
thread_pool.WaitCompletion()
finally:
if num_threads > 1:
thread_pool.Shutdown()
# If any shared variables (which means we are running in a separate OS
# process), increment value for each shared variable.
if shared_vars:
for (name, var) in shared_vars.items():
var.value += getattr(self, name)
|
import os
import json
class SerialHelper:
path = 'input.json'
langs_dictionairy = {}
@staticmethod
def read():
if os.path.isfile(SerialHelper.path):
with open(SerialHelper.path, 'r') as json_file:
return json.load(json_file)
else:
raise FileNotFoundError('Missing input.json')
@staticmethod
def write(dir, name, json_data):
if not os.path.isdir(dir):
os.makedirs(dir)
path = '{dir}/{name}'.format(dir=dir, name=name) + '.json'
with open(path, 'w') as json_file:
json.dump(json_data, json_file, sort_keys=False, indent=2)
@staticmethod
def write_lang_file():
if not os.path.isdir('lang'):
os.mkdir('lang')
for key in SerialHelper.langs_dictionairy.keys():
path = 'lang/' + key + '.json'
with open(path, 'w') as json_file:
json.dump(SerialHelper.langs_dictionairy.get(
key), json_file, sort_keys=True, indent=2)
@staticmethod
def add_to_langs_dict(lang, lang_dict):
if SerialHelper.langs_dictionairy.get(lang):
SerialHelper.langs_dictionairy.get(lang).update(lang_dict)
else:
SerialHelper.langs_dictionairy.update({lang: lang_dict})
class Item(SerialHelper):
def __init__(self, modid, name, langs_dict):
self.modid = modid
self.name = name
self.langs_dict = langs_dict
self.write_item_model()
self.add_lang()
def write_item_model(self):
identifier = self.modid + ':items/' + self.name
json_data = {
'parent': 'item/generated',
'textures': {
'layer0': identifier
}
}
SerialHelper.write('models/item', self.name, json_data)
def add_lang(self):
identifier = 'item.' + self.modid + '.' + self.name
for lang in langs_dict:
lang_dict = {identifier: langs_dict[lang]}
self.add_to_langs_dict(lang, lang_dict)
class Block(SerialHelper):
def __init__(self, modid, name, langs_dict):
self.modid = modid
self.name = name
self.langs_dict = langs_dict
self.write_block_model()
self.write_blockstate()
self.write_blockitem()
self.write_loot_table()
self.add_lang()
def write_block_model(self):
identifier = self.modid + ':blocks/' + self.name
json_data = {
'parent': 'block/cube_all',
'textures': {
'all': identifier
}
}
self.write('models/block', self.name, json_data)
def write_blockstate(self):
identifier = self.modid + ':block/' + self.name
json_data = {
'variants': {
'': {'model': identifier}
}
}
SerialHelper.write('blockstates', self.name, json_data)
def write_blockitem(self):
identifier = self.modid + ':block/' + self.name
json_data = {
'parent': identifier
}
self.write('models/item', self.name, json_data)
def write_loot_table(self):
identifier = self.modid + ':' + self.name
json_data = {
'type': 'minecraft:block',
'pools': [
{
'rolls': 1,
'entries': [
{
'type': 'minecraft:item',
'name': identifier
}
],
'conditions': [
{
'condition': 'minecraft:survives_explosion'
}
]
}
]
}
self.write('loot_tables', self.name, json_data)
def add_lang(self):
identifier = 'block.' + self.modid + '.' + self.name
for lang in langs_dict:
lang_dict = {identifier: langs_dict[lang]}
self.add_to_langs_dict(lang, lang_dict)
class OrientableBlock(Block):
def write_block_model(self):
identifier = self.modid + ':blocks/' + self.name
json_data = {
'parent': 'block/orientable',
'textures': {
'front': identifier + '_front',
'side': identifier + '_side',
'top': identifier + '_top'
}
}
self.write('models/block', self.name, json_data)
def write_blockstate(self):
identifier = self.modid + ':block/' + self.name
json_data = {
'variants': {
'facing=north': {'model': identifier},
'facing=east': {'model': identifier, 'y': 90},
'facing=south': {'model': identifier, 'y': 180},
'facing=west': {'model': identifier, 'y': 270}
}
}
self.write('blockstates', self.name, json_data)
class StairsBlock(Block):
def __init__(self, modid, name, lang_dict, origin_block):
self.modid = modid
self.name = name
self.lang_dict = lang_dict
self.origin_block = origin_block
self.write_block_model()
self.write_blockstate()
self.write_blockitem()
self.write_loot_table()
self.add_lang()
def write_block_model(self):
identifier = self.modid + ':blocks/' + self.origin_block
json_data = {
'parent': 'minecraft:block/stairs',
'textures': {
'bottom': identifier,
'top': identifier,
'side': identifier
}
}
self.write('models/block', self.name, json_data)
json_data = {
'parent': 'minecraft:block/inner_stairs',
'textures': {
'bottom': identifier,
'top': identifier,
'side': identifier
}
}
self.write('models/block', self.name + '_inner', json_data)
json_data = {
'parent': 'minecraft:block/outer_stairs',
'textures': {
'bottom': identifier,
'top': identifier,
'side': identifier
}
}
self.write('models/block', self.name + '_outer', json_data)
def write_blockstate(self):
identifier = modid + ':block/' + self.name
identifier_inner = identifier + '_inner'
identifier_outer = identifier + '_outer'
json_data = {
'variants': {
'facing=east,half=bottom,shape=inner_left': {
'model': identifier_inner,
'y': 270,
'uvlock': True
},
'facing=east,half=bottom,shape=inner_right': {
'model': identifier_inner
},
'facing=east,half=bottom,shape=outer_left': {
'model': identifier_outer,
'y': 270,
'uvlock': True
},
'facing=east,half=bottom,shape=outer_right': {
'model': identifier_outer
},
'facing=east,half=bottom,shape=straight': {
'model': identifier
},
'facing=east,half=top,shape=inner_left': {
'model': identifier_inner,
'x': 180,
'uvlock': True
},
'facing=east,half=top,shape=inner_right': {
'model': identifier_inner,
'x': 180,
'y': 90,
'uvlock': True
},
'facing=east,half=top,shape=outer_left': {
'model': identifier_outer,
'x': 180,
'uvlock': True
},
'facing=east,half=top,shape=outer_right': {
'model': identifier_outer,
'x': 180,
'y': 90,
'uvlock': True
},
'facing=east,half=top,shape=straight': {
'model': identifier,
'x': 180,
'uvlock': True
},
'facing=north,half=bottom,shape=inner_left': {
'model': identifier_inner,
'y': 180,
'uvlock': True
},
'facing=north,half=bottom,shape=inner_right': {
'model': identifier_inner,
'y': 270,
'uvlock': True
},
'facing=north,half=bottom,shape=outer_left': {
'model': identifier_outer,
'y': 180,
'uvlock': True
},
'facing=north,half=bottom,shape=outer_right': {
'model': identifier_outer,
'y': 270,
'uvlock': True
},
'facing=north,half=bottom,shape=straight': {
'model': identifier,
'y': 270,
'uvlock': True
},
'facing=north,half=top,shape=inner_left': {
'model': identifier_inner,
'x': 180,
'y': 270,
'uvlock': True
},
'facing=north,half=top,shape=inner_right': {
'model': identifier_inner,
'x': 180,
'uvlock': True
},
'facing=north,half=top,shape=outer_left': {
'model': identifier_outer,
'x': 180,
'y': 270,
'uvlock': True
},
'facing=north,half=top,shape=outer_right': {
'model': identifier_outer,
'x': 180,
'uvlock': True
},
'facing=north,half=top,shape=straight': {
'model': identifier,
'x': 180,
'y': 270,
'uvlock': True
},
'facing=south,half=bottom,shape=inner_left': {
'model': identifier_inner
},
'facing=south,half=bottom,shape=inner_right': {
'model': identifier_inner,
'y': 90,
'uvlock': True
},
'facing=south,half=bottom,shape=outer_left': {
'model': identifier_outer
},
'facing=south,half=bottom,shape=outer_right': {
'model': identifier_outer,
'y': 90,
'uvlock': True
},
'facing=south,half=bottom,shape=straight': {
'model': identifier,
'y': 90,
'uvlock': True
},
'facing=south,half=top,shape=inner_left': {
'model': identifier_inner,
'x': 180,
'y': 90,
'uvlock': True
},
'facing=south,half=top,shape=inner_right': {
'model': identifier_inner,
'x': 180,
'y': 180,
'uvlock': True
},
'facing=south,half=top,shape=outer_left': {
'model': identifier_outer,
'x': 180,
'y': 90,
'uvlock': True
},
'facing=south,half=top,shape=outer_right': {
'model': identifier_outer,
'x': 180,
'y': 180,
'uvlock': True
},
'facing=south,half=top,shape=straight': {
'model': identifier,
'x': 180,
'y': 90,
'uvlock': True
},
'facing=west,half=bottom,shape=inner_left': {
'model': identifier_inner,
'y': 90,
'uvlock': True
},
'facing=west,half=bottom,shape=inner_right': {
'model': identifier_inner,
'y': 180,
'uvlock': True
},
'facing=west,half=bottom,shape=outer_left': {
'model': identifier_outer,
'y': 90,
'uvlock': True
},
'facing=west,half=bottom,shape=outer_right': {
'model': identifier_outer,
'y': 180,
'uvlock': True
},
'facing=west,half=bottom,shape=straight': {
'model': identifier,
'y': 180,
'uvlock': True
},
'facing=west,half=top,shape=inner_left': {
'model': identifier_inner,
'x': 180,
'y': 180,
'uvlock': True
},
'facing=west,half=top,shape=inner_right': {
'model': identifier_inner,
'x': 180,
'y': 270,
'uvlock': True
},
'facing=west,half=top,shape=outer_left': {
'model': identifier_outer,
'x': 180,
'y': 180,
'uvlock': True
},
'facing=west,half=top,shape=outer_right': {
'model': identifier_outer,
'x': 180,
'y': 270,
'uvlock': True
},
'facing=west,half=top,shape=straight': {
'model': identifier,
'x': 180,
'y': 180,
'uvlock': True
}
}
}
self.write('blockstates', self.name, json_data)
class SlabBlock(Block):
def __init__(self, modid, name, lang_dict, origin_block):
self.modid = modid
self.name = name
self.lang_dict = lang_dict
self.origin_block = origin_block
self.write_block_model()
self.write_blockstate()
self.write_blockitem()
self.write_loot_table()
self.add_lang()
def write_block_model(self):
identifier = self.modid + ':blocks/' + self.origin_block
json_data = {
'parent': 'minecraft:block/slab',
'textures': {
'bottom': identifier,
'top': identifier,
'side': identifier
}
}
self.write('models/block', self.name, json_data)
json_data = {
'parent': 'minecraft:block/slab_top',
'textures': {
'bottom': identifier,
'top': identifier,
'side': identifier
}
}
self.write('models/block', self.name + '_top', json_data)
def write_blockstate(self):
identifier = self.modid + ':block/' + self.name
identifier_top = identifier + '_top'
identifier_origin_block = self.modid + ':block/' + self.origin_block
json_data = {
'variants': {
'type=bottom': {
'model': identifier
},
'type=double': {
'model': identifier_origin_block
},
'type=top': {
'model': identifier_top
}
}
}
self.write('blockstates', self.name, json_data)
class WallBlock(Block):
def __init__(self, modid, name, lang_dict, origin_block):
self.modid = modid
self.name = name
self.lang_dict = lang_dict
self.origin_block = origin_block
self.write_block_model()
self.write_blockstate()
self.write_blockitem()
self.write_loot_table()
self.add_lang()
def write_block_model(self):
identifier = self.modid + ':blocks/' + self.origin_block
json_data = {
'parent': 'minecraft:block/template_inventory',
'textures': {
'wall': identifier
}
}
self.write('models/block', self.name + '_inventory', json_data)
json_data = {
'parent': 'minecraft:block/template_wall_post',
'textures': {
'wall': identifier
}
}
self.write('models/block', self.name + '_post', json_data)
json_data = {
'parent': 'minecraft:block/wall_side',
'textures': {
'wall': identifier
}
}
self.write('models/block', self.name + '_side', json_data)
json_data = {
'parent': 'minecraft:block/template_wall_side_tall',
'textures': {
'wall': identifier
}
}
self.write('models/block', self.name + '_side_tall', json_data)
def write_blockstate(self):
identifier = self.modid + ':block/' + self.name
identifier_post = identifier + '_post'
identifier_side = identifier + '_side'
identifier_side_tall = identifier_side + '_tall'
json_data = {
"multipart": [
{
"when": {
"up": "true"
},
"apply": {
"model": identifier_post
}
},
{
"when": {
"north": "low"
},
"apply": {
"model": identifier_side,
"uvlock": True
}
},
{
"when": {
"east": "low"
},
"apply": {
"model": identifier_side,
"y": 90,
"uvlock": True
}
},
{
"when": {
"south": "low"
},
"apply": {
"model": identifier_side,
"y": 180,
"uvlock": True
}
},
{
"when": {
"west": "low"
},
"apply": {
"model": identifier_side,
"y": 270,
"uvlock": True
}
},
{
"when": {
"north": "tall"
},
"apply": {
"model": identifier_side_tall,
"uvlock": True
}
},
{
"when": {
"east": "tall"
},
"apply": {
"model": identifier_side_tall,
"y": 90,
"uvlock": True
}
},
{
"when": {
"south": "tall"
},
"apply": {
"model": identifier_side_tall,
"y": 180,
"uvlock": True
}
},
{
"when": {
"west": "tall"
},
"apply": {
"model": identifier_side_tall,
"y": 270,
"uvlock": True
}
}
]
}
self.write('blockstates', self.name, json_data)
def write_blockitem(self):
identifier = self.modid + ':block/' + self.name + '_inventory'
json_data = {
'parent': identifier
}
self.write('models/item', self.name, json_data)
json_input = SerialHelper.read()
modid = json_input.get('modid')
types = {'block/cube_all': Block, 'item/generated': Item,
'block/orientable': OrientableBlock, 'block/stairs': StairsBlock, 'block/wall': WallBlock}
for entry in json_input.get('entries'):
parent = entry.get('parent')
name = entry.get('name')
langs_dict = entry.get('lang')
if entry.get('origin_block'):
types.get(parent)(modid, name, langs_dict, entry.get('origin_block'))
else:
types.get(parent)(modid, name, langs_dict)
print(langs_dict)
SerialHelper.write_lang_file()
|
import os
import sys
import onedrivesdk
REDIRECT_URL = 'http://localhost:8080/'
CLIENT_ID = '00000000401CDF7B'
CLIENT_SECRET = '<KEY>'
SCOPES=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
def get_client():
client = onedrivesdk.get_default_client(CLIENT_ID, SCOPES)
auth_url = client.auth_provider.get_auth_url(REDIRECT_URL)
from onedrivesdk.helpers import GetAuthCodeServer
code = GetAuthCodeServer.get_auth_code(auth_url, REDIRECT_URL)
client.auth_provider.authenticate(code, REDIRECT_URL, CLIENT_SECRET)
return client
def folders_by_path(client, path, debug = False):
try:
items = client.item(path=path).children.get()
except AttributeError:
print("Oops! Onedrive Client is wrong!")
return None
except onedrivesdk.error.OneDriveError:
print("Oops! Path is not in onedrive:", path)
return None
except:
print("Unexpected error:", sys.exc_info()[0])
return None
newitems = filter(lambda item: item.folder, items)
if debug:
for i in newitems:
print('--------------------')
print('folder name: %s'%i.name)
print('folder url : %s'%i.url)
return newitems
def files_by_path(client, path, debug = False):
try:
items = client.item(path=path).children.get()
except AttributeError:
print("Oops! Onedrive Client is wrong!")
return None
except onedrivesdk.error.OneDriveError:
print("Oops! Path is not in onedrive:", path)
return None
except:
print("Unexpected error:", sys.exc_info()[0])
return None
newitems = filter(lambda item: not item.folder, items)
if debug:
for i in newitems:
print('--------------------')
print('file name: %s'%i.name)
print('file url : %s'%i.url)
return newitems
def images_by_path(client, path, debug = False):
try:
items = client.item(path=path).children.get()
except AttributeError:
print("Oops! Onedrive Client is wrong!")
return None
except onedrivesdk.error.OneDriveError:
print("Oops! Path is not in onedrive:", path)
return None
except:
print("Unexpected error:", sys.exc_info()[0])
return None
newitems = filter(lambda item: item.image, items)
if debug:
for i in newitems:
print('--------------------')
print('image name: %s'%i.name)
print('image url : %s'%i.url)
return newitems
def imgurl_by_path(client, path, debug = False):
try:
items = client.item(path=path).children.get()
except AttributeError:
print("Oops! Onedrive Client is wrong!")
return None
except onedrivesdk.error.OneDriveError:
print("Oops! Path is not in onedrive:", path)
return None
except:
print("Unexpected error:", sys.exc_info()[0])
return None
newitems = filter(lambda item: item.image, items)
if debug:
for i in newitems:
print('--------------------')
print('imgurl name: %s'%i.name)
print('imgurl url : %s'%i.url)
for i in newitems:
yield i.url
def imgurls_by_path(client, path, debug = False):
try:
items = client.item(path=path).children.get()
except AttributeError:
print("Oops! Onedrive Client is wrong!")
return None
except onedrivesdk.error.OneDriveError:
print("Oops! Path is not in onedrive:", path)
return None
except:
print("Unexpected error:", sys.exc_info()[0])
return None
newitems = filter(lambda item: item.image, items)
urls = map(lambda item: item.url, newitems)
if debug:
for url in urls:
print('--------------------')
print('imgurls url : %s'% url)
return urls
if __name__=='__main__':
print(__file__)
item_id = "root"
folder_name = '/Pictures/family-shares'
c = get_client()
folders_by_path(c, folder_name,True)
files_by_path(c, folder_name,True)
images_by_path(c, folder_name,True)
for i in imgurl_by_path(c, folder_name,True):
pass
imgurls_by_path(c, folder_name,True)
exit(0) |
import pytest
import inspect
from ipaddress import IPv4Address, IPv4Network
from prettytable import PrettyTable
import numpy as np
from CybORG import CybORG
from CybORG.Shared.Actions import Remove
from CybORG.Shared.Enums import TrinaryEnum
from CybORG.Agents.SimpleAgents.B_line import B_lineAgent
from CybORG.Agents.Wrappers.BlueTableWrapper import BlueTableWrapper
from CybORG.Shared.Actions.AbstractActions import Monitor
from CybORG.Agents import BlueMonitorAgent
def get_table(rows):
table = PrettyTable([
'Subnet',
'IP Address',
'Hostname',
'Activity',
'Compromised',
])
for r in rows:
table.add_row(rows[r])
table.sortby = 'Hostname'
return table
def test_BlueTableWrapper():
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = BlueTableWrapper(env=CybORG(path, 'sim',agents={'Red': B_lineAgent}))
agent_name = 'Blue'
def get_ip(host):
ip_map = cyborg.env.env.environment_controller.state.ip_addresses
for ip in ip_map:
if ip_map[ip] == host:
return str(ip)
raise ValueError('Searched for host with no ip address. Probably invalid hostname.')
def get_subnet(subnet):
cidr_map = cyborg.env.env.environment_controller.state.subnet_name_to_cidr
return str(cidr_map[subnet])
def get_generic_rows():
generic_rows = {}
for i in range(5):
host = 'User' + str(i)
generic_rows[host] = [get_subnet('User'),get_ip(host),host,
'None', 'No']
for i in range(3):
host = 'Enterprise' + str(i)
generic_rows[host] = [get_subnet('Enterprise'),get_ip(host),host,
'None','No']
host = 'Defender'
generic_rows[host] = [get_subnet('Enterprise'), get_ip(host), host,
'None', 'No']
for i in range(3):
host = 'Op_Host' + str(i)
generic_rows[host] = [get_subnet('Operational'),get_ip(host),host,
'None','No']
host = 'Op_Server0'
generic_rows[host] = [get_subnet('Operational'),get_ip(host),host,
'None','No']
host = 'Defender'
generic_rows[host] = [get_subnet('Enterprise'),get_ip(host),host,
'None','No']
return generic_rows
# Test Initial Observation
results = cyborg.reset(agent=agent_name)
observation = results.observation
expected_rows = get_generic_rows()
expected_table = get_table(expected_rows)
# We compare strings instead of tables. See comments in get_table function.
assert observation.get_string() == expected_table.get_string()
# Test New Host Discovery
action = Monitor(agent='Blue',session=0)
results = cyborg.step(action=action,agent=agent_name)
observation = results.observation
expected_success = TrinaryEnum.TRUE
assert observation.success == expected_success
expected_rows = get_generic_rows()
expected_table = get_table(expected_rows)
assert observation.get_string() == expected_table.get_string()
# Test Port Scan
results = cyborg.step(action=action,agent=agent_name)
observation = results.observation
expected_success = TrinaryEnum.TRUE
assert observation.success == expected_success
expected_rows['User1'][3] = 'Scan'
expected_table = get_table(expected_rows)
assert observation.get_string() == expected_table.get_string()
# Test Remote Exploit
results = cyborg.step(action=action,agent=agent_name)
observation = results.observation
expected_success = TrinaryEnum.TRUE
assert observation.success == expected_success
expected_rows['User1'][3] = 'Exploit'
expected_rows['User1'][-1] = 'User'
expected_table = get_table(expected_rows)
assert observation.get_string() == expected_table.get_string()
# Test Privilege Escalate
results = cyborg.step(action=action,agent=agent_name)
observation = results.observation
expected_success = TrinaryEnum.TRUE
assert observation.success == expected_success
expected_rows['User1'][3] = 'None'
expected_table = get_table(expected_rows)
assert observation.get_string() == expected_table.get_string()
# Test Remove
action = Remove(hostname='User1',agent=agent_name,session=0)
results = cyborg.step(action=action,agent=agent_name)
observation = results.observation
expected_success = TrinaryEnum.TRUE
assert observation.success == expected_success
expected_rows['User1'][-1] = 'Unknown'
expected_rows['Enterprise1'][-2] = 'Scan'
expected_table = get_table(expected_rows)
assert observation.get_string() == expected_table.get_string()
# Test Remove on Non Compromised Host
action = Remove(hostname='User2', agent=agent_name, session=0)
results = cyborg.step(action=action,agent=agent_name)
observation = results.observation
expected_success = TrinaryEnum.TRUE
assert observation.success == expected_success
expected_rows['Enterprise1'][-2] = 'Exploit'
expected_rows['Enterprise1'][-1] = 'User'
expected_table = get_table(expected_rows)
assert observation.get_string() == expected_table.get_string()
def test_blue_vector():
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = BlueTableWrapper(env=CybORG(path, 'sim',agents = {'Red':B_lineAgent}), output_mode='vector')
agent_name = 'Blue'
results = cyborg.reset(agent=agent_name)
observation = results.observation
expected_vector = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0])
assert all(observation == expected_vector)
for i in range(10):
action = Monitor(session=0,agent='Blue')
results = cyborg.step(action=action,agent='Blue')
assert type(results.observation) == type(expected_vector)
assert len(results.observation) == len(expected_vector)
@pytest.fixture(params=['table','raw'])
def cyborg(request,agents = {'Blue':BlueMonitorAgent,'Red':B_lineAgent},seed = 1):
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = BlueTableWrapper(env=CybORG(path, 'sim', agents=agents),output_mode=request.param)
cyborg.set_seed(seed)
return cyborg
def test_get_attr(cyborg):
for attribute in ['get_observation','get_action_space','get_last_action','get_ip_map',
'get_rewards', 'get_agent_state']:
assert cyborg.get_attr(attribute) == cyborg.env.get_attr(attribute)
def test_get_observation(cyborg):
step_obs= cyborg.reset(agent='Red').observation
method_obs = cyborg.get_observation('Red')
assert step_obs == method_obs
step_obs= cyborg.step(agent='Red').observation
method_obs = cyborg.get_observation('Red')
assert step_obs == method_obs
step_obs = cyborg.reset(agent='Blue').observation
method_obs = cyborg.get_observation('Blue')
if type(step_obs) != dict:
step_obs = step_obs.get_string()
method_obs = method_obs.get_string()
assert step_obs == method_obs
step_obs = cyborg.step(agent='Blue').observation
method_obs = cyborg.get_observation('Blue')
if type(step_obs) != dict:
step_obs = step_obs.get_string()
method_obs = method_obs.get_string()
assert step_obs == method_obs
def test_get_agent_state(cyborg):
cyborg.reset()
cyborg.step()
assert cyborg.get_agent_state('True') == cyborg.get_attr('get_agent_state')('True')
assert cyborg.get_agent_state('Red') == cyborg.get_attr('get_agent_state')('Red')
assert cyborg.get_agent_state('Blue') == cyborg.get_attr('get_agent_state')('Blue')
def test_get_action_space(cyborg):
assert cyborg.get_action_space('Red') == cyborg.get_attr('get_action_space')('Red')
assert cyborg.get_action_space('Blue') == cyborg.get_attr('get_action_space')('Blue')
def test_get_last_action(cyborg):
cyborg.reset()
assert cyborg.get_last_action('Red') == cyborg.get_attr('get_last_action')('Red')
assert cyborg.get_last_action('Blue') == cyborg.get_attr('get_last_action')('Blue')
cyborg.step()
assert cyborg.get_last_action('Red') == cyborg.get_attr('get_last_action')('Red')
assert cyborg.get_last_action('Blue') == cyborg.get_attr('get_last_action')('Blue')
def test_get_ip_map(cyborg):
assert cyborg.get_ip_map() == cyborg.get_attr('get_ip_map')()
def test_get_rewards(cyborg):
assert cyborg.get_rewards() == cyborg.get_attr('get_rewards')()
|
import sys
import itertools
import Queue
def combine_interactions(a, b):
if a == 'fix' or b == 'fix':
return 'fix'
if a == 'break' or b == 'break':
return 'break'
return 'neutral'
class RTG:
def __init__(self, metal):
self.metal = metal
def broken(self, room):
return False
def interact(self, metal):
if metal == self.metal:
return 'fix'
return 'break'
def __repr__(self):
return "RTG('%s')" % self.metal
def __key(self):
return (self.metal,)
def __hash__(self):
return self.__key().__hash__()
def __eq__(self, other):
return isinstance(other, RTG) and self.__key() == other.__key()
class Chip:
def __init__(self, metal):
self.metal = metal
def broken(self, room):
breaking = 'neutral'
for obj in room.objs:
breaking = combine_interactions(breaking, obj.interact(self.metal))
return breaking == 'break'
def interact(self, metal):
return 'neutral'
def __repr__(self):
return "Chip('%s')" % self.metal
def __key(self):
return (self.metal,)
def __hash__(self):
return self.__key().__hash__()
def __eq__(self, other):
return isinstance(other, Chip) and self.__key() == other.__key()
class Room:
def __init__(self, objs):
self.objs = objs
def legal(self):
return not any(obj.broken(self) for obj in self.objs)
def add(self, objs):
return Room(self.objs + objs)
def remove(self, objs):
return Room(list(set(self.objs) - set(objs)))
def possible_removals(self):
return ([[x] for x in self.objs]
+ list(itertools.imap(list, itertools.combinations(self.objs, 2))))
def empty(self):
return not self.objs
def __repr__(self):
return "Room(%s)" % repr(self.objs)
def __key(self):
return tuple(sorted(self.objs))
def __hash__(self):
return self.__key().__hash__()
def __eq__(self, other):
return self.__key() == other.__key()
class Node:
def __init__(self, rooms, elevator):
self.rooms = rooms
self.elevator = elevator
def evaluate(self):
if not all(r.legal() for r in self.rooms):
return 'fail'
if all(r.empty() for r in self.rooms[:-1]):
return 'succeed'
return 'progress'
def goal_estimate(self):
return sum((len(self.rooms) - i - 1) * 2 * max(0, len(room.objs) - 1)
for i, room in enumerate(self.rooms))
def nexts(self):
i = self.elevator
r = self.rooms[i]
dests = []
if i != 0:
dests.append(i - 1)
if i < len(self.rooms) - 1:
dests.append(i + 1)
for removals in r.possible_removals():
new_room = self.rooms[i].remove(removals)
for dest in dests:
rooms = list(self.rooms)
rooms[i] = new_room
rooms[dest] = self.rooms[dest].add(removals)
yield (1,
Node(rooms, dest))
def __repr__(self):
return "Node(%s, %d)" % (repr(self.rooms), self.elevator)
def __key(self):
return (tuple(self.rooms), self.elevator)
def __hash__(self):
return self.__key().__hash__()
def __eq__(self, other):
return self.__key() == other.__key()
def search(root):
q = Queue.PriorityQueue()
visited = set([])
q.put((0 + root.goal_estimate(), 0, root))
iterations = 0
while not q.empty():
(estimated_cost, spent_cost, node) = q.get()
iterations = iterations + 1
if iterations % 1 == 5000:
print "Moved %d so far, about %d from goal" % (spent_cost, estimated_cost)
for (spend, next) in node.nexts():
if next in visited:
continue
kind = next.evaluate()
if kind == 'fail':
continue
new_cost = spent_cost + spend
if kind == 'succeed':
return (new_cost, next)
visited.add(next)
q.put_nowait((new_cost + next.goal_estimate(), new_cost, next))
# The first floor contains a thulium generator, a thulium-compatible microchip, a plutonium generator, and a strontium generator.
# The second floor contains a plutonium-compatible microchip and a strontium-compatible microchip.
# The third floor contains a promethium generator, a promethium-compatible microchip, a ruthenium generator, and a ruthenium-compatible microchip.
# The fourth floor contains nothing relevant.
root = Node([Room([RTG('thulium'), Chip('thulium'), RTG('plutonium'), RTG('strontium'),
RTG('elerium'), Chip('elerium'), RTG('dilithium'), Chip('dilithium')]),
Room([Chip('plutonium'), Chip('strontium')]),
Room([RTG('promethium'), Chip('promethium'), RTG('ruthenium'), Chip('ruthenium')]),
Room([])],
0)
if __name__ == '__main__':
print search(root)[0]
|
from typing import Optional, Dict, Union
import itertools
import json
from typing import Optional, Dict, Union
from nltk import sent_tokenize
import torch
from transformers import (
AutoModelForSeq2SeqLM,
AutoTokenizer,
PreTrainedModel,
PreTrainedTokenizer,
)
from transformers import (
AutoModelForSeq2SeqLM,
AutoTokenizer,
PreTrainedModel,
PreTrainedTokenizer,
)
# import docx2txt
def pipeline(
model: Optional = None,
tokenizer: Optional[Union[str, PreTrainedTokenizer]] = None,
qg_format: Optional[str] = "highlight",
ans_model: Optional = None,
ans_tokenizer: Optional[Union[str, PreTrainedTokenizer]] = None,
use_cuda: Optional[bool] = True,
**kwargs,
):
model = "valhalla/t5-small-qg-hl"
tokenizer = model
if isinstance(tokenizer, (str, tuple)):
if isinstance(tokenizer, tuple):
# For tuple we have (tokenizer name, {kwargs})
tokenizer = AutoTokenizer.from_pretrained(tokenizer[0], **tokenizer[1])
else:
tokenizer = AutoTokenizer.from_pretrained(tokenizer)
# Instantiate model if needed
if isinstance(model, str):
model = AutoModelForSeq2SeqLM.from_pretrained(model)
# load default ans model
ans_model = "valhalla/t5-small-qa-qg-hl"
ans_tokenizer = AutoTokenizer.from_pretrained(ans_model)
ans_model = AutoModelForSeq2SeqLM.from_pretrained(ans_model)
# Instantiate tokenizer if needed
if isinstance(ans_tokenizer, (str, tuple)):
if isinstance(ans_tokenizer, tuple):
# For tuple we have (tokenizer name, {kwargs})
ans_tokenizer = AutoTokenizer.from_pretrained(
ans_tokenizer[0], **ans_tokenizer[1]
)
else:
ans_tokenizer = AutoTokenizer.from_pretrained(ans_tokenizer)
if isinstance(ans_model, str):
ans_model = AutoModelForSeq2SeqLM.from_pretrained(ans_model)
return QuestionGenerator(
model=model,
tokenizer=tokenizer,
ans_model=ans_model,
ans_tokenizer=ans_tokenizer,
qg_format=qg_format,
use_cuda=use_cuda,
)
class QuestionGenerator:
def __init__(
self,
model: PreTrainedModel,
tokenizer: PreTrainedTokenizer,
ans_model: PreTrainedModel,
ans_tokenizer: PreTrainedTokenizer,
qg_format: str,
use_cuda: bool,
):
self.model = model
self.tokenizer = tokenizer
self.ans_model = ans_model
self.ans_tokenizer = ans_tokenizer
self.qg_format = qg_format
self.device = "cuda" if torch.cuda.is_available() and use_cuda else "cpu"
self.model.to(self.device)
if self.ans_model is not self.model:
self.ans_model.to(self.device)
assert self.model.__class__.__name__ in [
"T5ForConditionalGeneration",
"BartForConditionalGeneration",
]
if "T5ForConditionalGeneration" in self.model.__class__.__name__:
self.model_type = "t5"
else:
self.model_type = "bart"
def __call__(self, inputs: str):
inputs = " ".join(inputs.split())
sents, answers = self._extract_answers(inputs)
flat_answers = list(itertools.chain(*answers))
if len(flat_answers) == 0:
return []
qg_examples = self._prepare_inputs_for_qg_from_answers_hl(sents, answers)
qg_inputs = [example["source_text"] for example in qg_examples]
questions = self._generate_questions(qg_inputs)
output = []
for ctr, question in enumerate(questions):
temp_dict = {"question": question, "answer": qg_examples[ctr]["answer"]}
output.append(temp_dict)
return output
def _generate_questions(self, inputs):
inputs = self._tokenize(inputs, padding=True, truncation=True)
outs = self.model.generate(
input_ids=inputs["input_ids"].to(self.device),
attention_mask=inputs["attention_mask"].to(self.device),
max_length=32,
num_beams=4,
)
questions = [
self.tokenizer.decode(ids, skip_special_tokens=True) for ids in outs
]
return questions
def _extract_answers(self, context):
sents, inputs = self._prepare_inputs_for_ans_extraction(context)
inputs = self._tokenize(inputs, padding=True, truncation=True)
outs = self.ans_model.generate(
input_ids=inputs["input_ids"].to(self.device),
attention_mask=inputs["attention_mask"].to(self.device),
max_length=32,
)
dec = [
self.ans_tokenizer.decode(ids, skip_special_tokens=False) for ids in outs
]
answers = [item.split("<sep>") for item in dec]
answers = [i[:-1] for i in answers]
return sents, answers
def _tokenize(
self,
inputs,
padding=True,
truncation=True,
add_special_tokens=True,
max_length=512,
):
inputs = self.tokenizer.batch_encode_plus(
inputs,
max_length=max_length,
add_special_tokens=add_special_tokens,
truncation=truncation,
padding="max_length" if padding else False,
pad_to_max_length=padding,
return_tensors="pt",
)
return inputs
def _prepare_inputs_for_ans_extraction(self, text):
sents = sent_tokenize(text)
inputs = []
for i in range(len(sents)):
source_text = "extract answers:"
for j, sent in enumerate(sents):
if i == j:
sent = "<hl> %s <hl>" % sent
source_text = "%s %s" % (source_text, sent)
source_text = source_text.strip()
if self.model_type == "t5":
source_text = source_text + " </s>"
inputs.append(source_text)
return sents, inputs
def _prepare_inputs_for_qg_from_answers_hl(self, sents, answers):
inputs = []
for i, answer in enumerate(answers):
if len(answer) == 0:
continue
for answer_text in answer:
sent = sents[i]
sents_copy = sents[:]
answer_text = answer_text.strip()
answer_text = answer_text.replace("<pad> ", "")
try:
# ans_start_idx = sent.index(answer_text)
ans_start_idx = sent.replace(" ", "").index(
answer_text.replace(" ", "")
)
except Exception as e:
print(e, answer_text)
sent = f"{sent[:ans_start_idx]} <hl> {answer_text} <hl> {sent[ans_start_idx + len(answer_text): ]}"
sents_copy[i] = sent
source_text = " ".join(sents_copy)
source_text = f"generate question: {source_text}"
if self.model_type == "t5":
source_text = source_text + " </s>"
inputs.append({"answer": answer_text, "source_text": source_text})
return inputs
QG = pipeline()
|
"""Instruction module."""
# Official Libraries
# My Modules
from stobu.syss import messages as msg
from stobu.tools.translater import translate_tags_str
from stobu.types.action import ActDataType, ActionRecord, ActionsData, ActType
from stobu.types.action import NORMAL_ACTIONS
from stobu.utils.log import logger
__all__ = (
'actions_data_apply_instructions',
)
# Define Constants
PROC = 'INSTRUCTION'
INST_PARAGRAPH_START = ('P', 'pr')
INST_BREAK = ('B', 'BR', 'br')
INST_PARAGRAPH_END = ('PE', 'pend')
INST_ALIAS = ('A', 'alias')
INST_FORESHADOW = ('FS', 'FLAG', 'foreshadow')
INST_PAYOFF = ('PO', 'DISFLAG', 'payoff')
# Main
def actions_data_apply_instructions(actions_data: ActionsData, tags: dict) -> ActionsData:
assert isinstance(actions_data, ActionsData)
assert isinstance(tags, dict)
logger.debug(msg.PROC_START.format(proc=PROC))
tmp = []
alias = {}
# TODO: パラグラフはパラグラフのActDataTypeで制御し、インデントやBRはここでは命令分以外は入れない
for record in actions_data.get_data():
assert isinstance(record, ActionRecord)
if ActDataType.INSTRUCTION is record.subtype:
if record.subject in INST_PARAGRAPH_START:
tmp.append(_get_record_as_paragraph_start())
elif record.subject in INST_PARAGRAPH_END:
tmp.append(_get_record_as_paragraph_end())
elif record.subject in INST_BREAK:
tmp.append(_get_record_as_br())
elif record.subject in INST_ALIAS:
short, origin = record.outline.split('=')
alias[short] = origin
elif record.subject in INST_FORESHADOW:
tmp.append(_record_as_foreshadow_from(record, tags))
elif record.subject in INST_PAYOFF:
tmp.append(_record_as_payoff_from(record, tags))
else:
logger.warning(msg.ERR_FAIL_INVALID_DATA.format(data=f"instruction type in {PROC}"))
continue
elif ActDataType.SCENE_START is record.subtype:
alias = {}
tmp.append(record)
elif record.type in NORMAL_ACTIONS:
tmp.append(_conv_shorter_by_alias(record, alias))
else:
tmp.append(record)
logger.debug(msg.PROC_SUCCESS.format(proc=PROC))
return ActionsData(tmp)
# Private Functions
def _conv_shorter_by_alias(record: ActionRecord, alias: dict) -> ActionRecord:
assert isinstance(record, ActionRecord)
assert isinstance(alias, dict)
subject = record.subject
if record.subject in alias.keys():
subject = alias[record.subject]
return ActionRecord(
record.type,
record.subtype,
subject,
translate_tags_str(record.outline, alias),
translate_tags_str(record.desc, alias),
record.flags,
translate_tags_str(record.note, alias),
)
def _get_record_as_br() -> ActionRecord:
return ActionRecord(ActType.DATA, ActDataType.BR, '\n')
def _get_record_as_paragraph_end() -> ActionRecord:
return ActionRecord(ActType.DATA, ActDataType.PARAGRAPH_END, '')
def _get_record_as_paragraph_start() -> ActionRecord:
return ActionRecord(ActType.DATA, ActDataType.PARAGRAPH_START, '')
def _record_as_foreshadow_from(record: ActionRecord, tags: dict) -> ActionRecord:
assert isinstance(record, ActionRecord)
assert isinstance(tags, dict)
subject, flag = '', record.outline
if ':' in record.outline:
subject, flag = record.outline.split(':')
if subject:
subject = translate_tags_str(subject, tags, True, None)
return ActionRecord(
ActType.DATA,
ActDataType.FORESHADOW,
subject,
flag)
def _record_as_payoff_from(record: ActionRecord, tags: dict) -> ActionRecord:
assert isinstance(record, ActionRecord)
assert isinstance(tags, dict)
subject, flag = '', record.outline
if ':' in record.outline:
subject, flag = record.outline.split(':')
if subject:
subject = translate_tags_str(subject, tags, True, None)
return ActionRecord(
ActType.DATA,
ActDataType.PAYOFF,
subject,
flag)
|
<filename>points/viewsets.py
from .models import Payer, Transaction, Spend
from .serializers import PayerSerializer, TransactionSerializer, SpendSerializer
from rest_framework import viewsets, status
from rest_framework.response import Response
class PayerViewSet(viewsets.ModelViewSet):
queryset = Payer.objects.all()
serializer_class = PayerSerializer
def create(self, request, *args, **kwargs):
if len(request.data) == 2:
if request.data['total_points'] < 0:
return Response("Payer Points cannot be negative.", status=status.HTTP_400_BAD_REQUEST)
# check for repeat names
names = list(self.queryset.all().values_list('name', flat=True))
if request.data['name'].upper() in names:
return Response(f"{request.data['name'].upper()} name already exists. Choose a different name.", status=status.HTTP_400_BAD_REQUEST)
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
name = self.request.data['name'].upper()
serializer.save(name=name)
class TransactionViewSet(viewsets.ModelViewSet):
queryset = Transaction.objects.all().order_by("timestamp")
serializer_class = TransactionSerializer
# customize POST to add 'remaining_points' field
def create(self, request, *args, **kwargs):
name = request.data.get("payer")
name = name.upper()
payer = Payer.objects.get(name=name)
request.data["payer"] = payer.id
points = int(request.data.get("points"))
new_payer_total = payer.total_points + points
# checks if payer has enough points
if new_payer_total < 0:
text = f"Not enough points. {payer.name} only has {payer.total_points} points available."
return Response(text, status=status.HTTP_400_BAD_REQUEST)
# deducts negative transactions from payer balances and previous positive transactions
if points < 0:
qs = Transaction.objects.filter(payer=payer.id).order_by("timestamp")
points = points * -1
for t in qs:
if t.remaining_points != 0:
if t.remaining_points < points:
points -= t.remaining_points
payer.total_points -= t.remaining_points
t.remaining_points = 0
else:
t.remaining_points -= points
payer.total_points -= points
points = 0
t.save()
payer.total_points = new_payer_total
payer.save()
request.data["remaining_points"] = points
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
class SpendViewSet(viewsets.ModelViewSet):
queryset = Spend.objects.all()
serializer_class = SpendSerializer
# custom POST to add receipt to Spend
def create(self, request, *args, **kwargs):
spending = request.data.get("points")
total_transaction_points = sum(Transaction.objects.all().values_list("remaining_points", flat=True))
receipt = []
# checks to make sure we have enough spending power
if spending > total_transaction_points:
text = f"Not enough points. We only have {total_transaction_points} available."
return Response(text, status=status.HTTP_400_BAD_REQUEST)
for transaction in Transaction.objects.all().order_by("timestamp"):
payer = transaction.payer
r = {
"payer": payer.name,
"points": 0
}
# checks if player already exists in receipt
if len(receipt) != 0:
for item in receipt:
if item['payer'] == payer.name:
r = item
receipt.pop(receipt.index(item))
if transaction.remaining_points != 0:
if transaction.remaining_points <= spending:
r["points"] -= transaction.remaining_points
spending -= transaction.remaining_points
payer.total_points -= transaction.remaining_points
transaction.remaining_points = 0
elif transaction.remaining_points > spending:
r['points'] -= spending
payer.total_points -= spending
transaction.remaining_points -= spending
spending = 0
if r['points'] != 0:
receipt.append(r)
transaction.save()
payer.save()
if spending == 0:
break
request.data["receipt"] = receipt
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data['receipt'], status=status.HTTP_201_CREATED, headers=headers)
class BalanceViewSet(viewsets.ReadOnlyModelViewSet):
def list(self, request, *args, **kwargs):
balance = []
for payer in Payer.objects.all():
balance.append(payer.name)
balance.append(payer.total_points)
# turns list into a dictionary
balance_dict = {balance[i]: balance[i+1] for i in range(0, len(balance), 2)}
return Response(balance_dict)
|
<filename>tests/test_MesaFileAccess.py
import pytest
from typing import Tuple,List
from MesaHandler import MesaFileAccess
from MesaHandler.support import *
import shutil
testWritePath = "tests/playground/"
inlistpgstarParameters = [
"HR_win_flag",
"HR_logT_min",
"HR_logT_max",
"HR_logL_min",
"HR_logL_max",
"HR_win_width",
"HR_win_aspect_ratio",
"TRho_Profile_win_flag",
"show_TRho_Profile_legend",
"show_TRho_Profile_text_info",
"TRho_Profile_win_width",
"TRho_Profile_win_aspect_ratio",
]
inlistProjectParametersStarJob =[
"create_pre_main_sequence_model",
"save_model_when_terminate",
"save_model_filename",
"pgstar_flag",
"change_Y",
"new_Y",
]
inlistProjectParametersControl = [
"initial_mass",
"Lnuc_div_L_zams_limit",
"stop_near_zams",
"max_age",
"max_years_for_timestep",
"mixing_length_alpha",
"xa_central_lower_limit_species(1)",
"xa_central_lower_limit(1)",
]
@pytest.fixture(scope="function")
def defaultSetup(request):
with cd("tests"):
if "playground" not in os.listdir("."):
os.makedirs("playground/")
def cleanup():
print("Performing cleanup")
with cd(testWritePath):
for i in os.listdir("."):
os.remove(i)
with cd("tests"):
if "playground" in os.listdir("."):
os.rmdir("playground")
os.remove("inlist")
os.remove("inlist_pgstar")
os.remove("inlist_project")
shutil.copy2("tests/inlist","inlist")
shutil.copy2("tests/inlist_pgstar", "inlist_pgstar")
shutil.copy2("tests/inlist_project", "inlist_project")
request.addfinalizer(cleanup)
return MesaFileAccess()
def testObject(defaultSetup: MesaFileAccess):
object = defaultSetup
assert set(sections).issubset(object.dataDict.keys())
assert set(inlistpgstarParameters).issubset(object.dataDict["pgstar"]["inlist_pgstar"].keys())
assert set(inlistProjectParametersStarJob).issubset(object.dataDict["star_job"]["inlist_project"].keys())
assert set(inlistProjectParametersControl).issubset(object.dataDict["controls"]["inlist_project"].keys())
object["initial_mass"] = 5
assert object["controls"]["inlist_project"]["initial_mass"] == 5
object["initial_mass"] = 10
assert object["controls"]["inlist_project"]["initial_mass"] == 10
object.addValue("saved_model_for_merger_1","text")
assert object["star_job"]["inlist_project"]["saved_model_for_merger_1"] == "text"
object.removeValue("saved_model_for_merger_1")
with pytest.raises(KeyError):
object.addValue("dummy","dummy")
@pytest.mark.parametrize("value",[("firstFile","abcd"),("secondFile.txt","efgh"),("firstFile","jklmn")])
def testWriteFile(defaultSetup: MesaFileAccess,value:Tuple[str,str]):
defaultSetup.writeFile(testWritePath+value[0],value[1])
assert os.path.exists(testWritePath+value[0])
with open(testWritePath+value[0]) as f:
assert value[1] == f.read()
|
<reponame>Eo300/react_flask_pdb2pqr
import os, sys, time
import glob
import requests
import logging
from multiprocessing import Process
from pprint import pprint
from json import dumps
from flask import request
import kubernetes.client
from kubernetes import config
from kubernetes.client.rest import ApiException
from service import tesk_proxy_utils
from service.legacy.pdb2pqr_old_utils import redirector, setID
from service.legacy.weboptions import WebOptions, WebOptionsError
from service.legacy.src.pdb import readPDB
from service.legacy.src.aconf import (
# STYLESHEET,
# WEBSITE,
# PDB2PQR_OPAL_URL,
# HAVE_PDB2PQR_OPAL,
INSTALLDIR,
TMPDIR,
MAXATOMS,
PDB2PQR_VERSION)
class JobDirectoryExistsError(Exception):
def __init__(self, expression):
self.expression = expression
class Runner:
def __init__(self, form, files, storage_host, job_id=None):
# self.starttime = None
# self.job_id = None
self.weboptions = None
self.invoke_method = None
self.cli_params = None
# Load kubeconfig
# config.load_incluster_config()
# config.load_kube_config()
self.starttime = time.time()
if job_id is None:
self.job_id = setID(self.starttime)
else:
self.job_id = job_id
try:
# if 'invoke_method' in form and isinstance(form['invoke_method'], str):
if 'invoke_method' in form :
logging.info('invoke_method found, value: %s' % str(form['invoke_method']) )
if form['invoke_method'].lower() == 'v2' or form['invoke_method'].lower() == 'cli':
self.invoke_method = 'cli'
self.cli_params = {
'pdb_name' : form['pdb_name'],
'pqr_name' : form['pqr_name'],
'flags' : form['flags']
}
elif form['invoke_method'].lower() == 'v1' or form['invoke_method'].lower() == 'gui':
self.invoke_method = 'gui'
self.weboptions = WebOptions(form, files)
else:
logging.warning('invoke_method not found: %s' % str('invoke_method' in form))
if 'invoke_method' in form:
logging.debug("form['invoke_method']: "+str(form['invoke_method']))
logging.debug(type(form['invoke_method']))
self.invoke_method = 'gui'
self.weboptions = WebOptions(form, files)
except WebOptionsError:
raise
def prepare_job(self, job_id):
# os.makedirs('%s%s%s' % (INSTALLDIR, TMPDIR, job_id))
# job_id_exists = False
# try:
# os.makedirs('%s%s%s' % (INSTALLDIR, TMPDIR, job_id))
# except:
# job_id_exists = True
# pass
# if job_id_exists:
# raise JobDirectoryExistsError('Job directory exists for the id %s' % job_id)
try:
os.makedirs('%s%s%s' % (INSTALLDIR, TMPDIR, job_id))
except:
pass
#Some job parameters logging.
if self.invoke_method == 'gui':
apbsInputFile = open('%s%s%s/apbs_input' % (INSTALLDIR, TMPDIR, job_id),'w')
apbsInputFile.write(str(self.weboptions["apbs"]))
apbsInputFile.close()
typemapInputFile = open('%s%s%s/typemap' % (INSTALLDIR, TMPDIR, job_id),'w')
typemapInputFile.write(str(self.weboptions["typemap"]))
typemapInputFile.close()
# Recording CGI run information for PDB2PQR Opal
pdb2pqrLogFile = open('%s%s%s/pdb2pqr_log' % (INSTALLDIR, TMPDIR, job_id), 'w')
pdb2pqrLogFile.write(str(self.weboptions.getOptions())+'\n'+
str(self.weboptions.ff))
# str(weboptions.ff)+'\n'+
# str(os.environ["REMOTE_ADDR"]))
pdb2pqrLogFile.close()
elif self.invoke_method == 'cli':
pass
statusfile = open('%s%s%s/pdb2pqr_status' % (INSTALLDIR, TMPDIR, job_id), 'w')
statusfile.write('running')
statusfile.close()
def run_job(self, job_id, storage_host, tesk_host, image_pull_policy):
pqr_name = None
# print(self.weboptions.pdbfilestring)
# pdblist, errlist = readPDB(self.weboptions.pdbfile)
currentdir = os.getcwd()
os.chdir("/")
# os.setsid()
# os.umask(0)
os.chdir(currentdir)
# os.close(1) # not sure if these
# os.close(2) # two lines are necessary
# pqrpath = '%s%s%s/%s.pqr' % (INSTALLDIR, TMPDIR, job_id, job_id)
# orig_stdout = sys.stdout
# orig_stderr = sys.stderr
# sys.stdout = open('%s%s%s/pdb2pqr_stdout.txt' % (INSTALLDIR, TMPDIR, job_id), 'w')
# sys.stderr = open('%s%s%s/pdb2pqr_stderr.txt' % (INSTALLDIR, TMPDIR, job_id), 'w')
if self.invoke_method == 'gui' or self.invoke_method == 'v1':
run_arguements = self.weboptions.getRunArguments()
if self.weboptions.runoptions.get('ph_calc_method', '') == 'pdb2pka':
run_arguements['ph_calc_options']['output_dir']='%s%s%s/pdb2pka_output' % (INSTALLDIR, TMPDIR, job_id)
# Retrieve information about the PDB file and command line arguments
if self.weboptions.user_did_upload:
upload_list = ['pdb2pqr_status', 'pdb2pqr_start_time']
else:
if os.path.splitext(self.weboptions.pdbfilename)[1] != '.pdb':
self.weboptions.pdbfilename = self.weboptions.pdbfilename+'.pdb' # add pdb extension to pdbfilename
# Write the PDB file contents to disk
with open(os.path.join(INSTALLDIR, TMPDIR, job_id, self.weboptions.pdbfilename), 'w') as fout:
fout.write(self.weboptions.pdbfilestring)
upload_list = [self.weboptions.pdbfilename, 'pdb2pqr_status', 'pdb2pqr_start_time']
self.weboptions.pqrfilename = job_id+'.pqr' # make pqr name prefix the job_id
command_line_args = self.weboptions.getCommandLine()
if '--summary' in command_line_args:
command_line_args = command_line_args.replace('--summary', '')
logging.debug(command_line_args)
logging.debug(self.weboptions.pdbfilename)
if self.weboptions.user_did_upload:
upload_list = ['pdb2pqr_status', 'pdb2pqr_start_time']
else:
if os.path.splitext(self.weboptions.pdbfilename)[1] != '.pdb':
self.weboptions.pdbfilename = self.weboptions.pdbfilename+'.pdb' # add pdb extension to pdbfilename
logging.debug(self.weboptions.pdbfilename)
# Write the PDB file contents to disk
with open(os.path.join(INSTALLDIR, TMPDIR, job_id, self.weboptions.pdbfilename), 'w') as fout:
fout.write(self.weboptions.pdbfilestring)
upload_list = [self.weboptions.pdbfilename, 'pdb2pqr_status', 'pdb2pqr_start_time']
elif self.invoke_method == 'cli' or self.invoke_method == 'v2':
# construct command line argument string for when CLI is invoked
command_line_list = []
# get list of args from self.cli_params['flags']
for name in self.cli_params['flags']:
command_line_list.append( (name, self.cli_params['flags'][name]) )
command_line_args = ''
# append to command_line_str
for pair in command_line_list:
if isinstance(pair[1], bool):
cli_arg = '--%s' % (pair[0]) #add conditionals later to distinguish between data types
else:
cli_arg = '--%s=%s' % (pair[0], str(pair[1])) #add conditionals later to distinguish between data types
command_line_args = '%s %s' % (command_line_args, cli_arg)
# append self.cli_params['pdb_name'] and self.cli_params['pqr_name'] to command_line_str
pprint(self.cli_params)
command_line_args = '%s %s %s' % (command_line_args, self.cli_params['pdb_name'], self.cli_params['pqr_name'])
upload_list = ['pdb2pqr_status', 'pdb2pqr_start_time']
pqr_name = self.cli_params['pqr_name']
logging.info('pqr filename: %s', pqr_name)
# Write the start time to a file, before posting to TESK
with open(os.path.join(INSTALLDIR, TMPDIR, job_id, 'pdb2pqr_start_time'), 'w') as fout:
fout.write( str(time.time()) )
# set the PDB2PQR status to running, write to disk, upload
with open(os.path.join(INSTALLDIR, TMPDIR, job_id, 'pdb2pqr_status'), 'w') as fout:
fout.write('running\n')
tesk_proxy_utils.send_to_storage_service(storage_host, job_id, upload_list, os.path.join(INSTALLDIR, TMPDIR))
"""
# TESK request headers
headers = {}
headers['Content-Type'] = 'application/json'
headers['Accept'] = 'application/json'
pdb2pqr_json_dict = tesk_proxy_utils.pdb2pqr_json_config(job_id, command_line_args, storage_host, os.path.join(INSTALLDIR, TMPDIR), pqr_name=pqr_name)
url = tesk_host + '/v1/tasks/'
print(url)
# print( dumps(pdb2pqr_json_dict, indent=2) )
"""
# Set up job to send to Volcano.sh
volcano_namespace = os.environ.get('VOLCANO_NAMESPACE')
pdb2pqr_kube_dict = tesk_proxy_utils.pdb2pqr_yaml_config(job_id, volcano_namespace, image_pull_policy, command_line_args, storage_host, os.path.join(INSTALLDIR, TMPDIR), pqr_name=pqr_name)
# print( dumps(pdb2pqr_kube_dict, indent=2) )
# create an instance of the API class
configuration = kubernetes.client.Configuration()
api_instance = kubernetes.client.CustomObjectsApi(kubernetes.client.ApiClient(configuration))
group = 'batch.volcano.sh' # str | The custom resource's group name
version = 'v1alpha1' # str | The custom resource's version
namespace = volcano_namespace # str | The custom resource's namespace
plural = 'jobs' # str | The custom resource's plural name. For TPRs this would be lowercase plural kind.
# body = kubernetes.client.UNKNOWN_BASE_TYPE() # UNKNOWN_BASE_TYPE | The JSON schema of the Resource to create.
pretty = 'true' # str | If 'true', then the output is pretty printed. (optional)
body = pdb2pqr_kube_dict
try:
api_response = api_instance.create_namespaced_custom_object(group, version, namespace, plural, body, pretty=pretty)
# print('\n\n\n')
logging.debug( 'Response from Kube API server: %s', dumps(api_response, indent=2) )
# print(type(api_response))
except ApiException as e:
logging.error("Exception when calling CustomObjectsApi->create_namespaced_custom_object: %s\n", e)
raise
# #TODO: create handler in case of non-200 response
# response = requests.post(url, headers=headers, json=pdb2pqr_json_dict)
# print(response.content)
return
def start(self, storage_host, tesk_host, image_pull_policy, analytics_id, analytics_dim_index=None):
# Acquire job ID
self.starttime = time.time()
# job_id = setID(self.starttime)
job_id = self.job_id
# job_id = requests.get()
# Prepare job
self.prepare_job(job_id)
# Run PDB2PQR in separate process
# p = Process(target=self.run_job, args=(job_id, storage_host))
# p.start()
self.run_job(job_id, storage_host, tesk_host, image_pull_policy)
if 'X-Forwarded-For' in request.headers:
source_ip = request.headers['X-Forwarded-For']
else:
logging.warning("Unable to find 'X-Forwarded-For' header in request")
source_ip = None
if 'X-APBS-Client-ID' in request.headers:
client_id = request.headers['X-APBS-Client-ID']
else:
logging.warning("Unable to find 'X-APBS-Client-ID' header in request")
client_id = job_id
redirect = redirector(job_id, self.weboptions, 'pdb2pqr', source_ip, analytics_id, analytics_dim_index, client_id)
# Upload initial files to storage service
# file_list = [
# 'typemap',
# 'pdb2pqr_status',
# 'pdb2pqr_start_time',
# ]
# if isinstance(file_list, list):
# try:
# tesk_proxy_utils.send_to_storage_service(storage_host, job_id, file_list, os.path.join(INSTALLDIR, TMPDIR))
# except Exception as err:
# with open('storage_err', 'a+') as fin:
# fin.write(err)
return redirect
|
import unittest
from robot.utils.asserts import assert_equal, assert_true, assert_false
from robot import utils
from robot.model.tags import *
class TestTags(unittest.TestCase):
def test_empty_init(self):
assert_equal(list(Tags()), [])
def test_init_with_string(self):
assert_equal(list(Tags('string')), ['string'])
def test_init_with_iterable_and_normalization_and_sorting(self):
for inp in [['T 1', 't2', 't_3'],
('t2', 'T 1', 't_3'),
('t2', 'T 2', '__T__2__', 'T 1', 't1', 't_1', 't_3', 't3'),
('', 'T 1', '', 't2', 't_3', 'NONE')]:
assert_equal(list(Tags(inp)), ['T 1', 't2', 't_3'])
def test_add_string(self):
tags = Tags(['Y'])
tags.add('x')
assert_equal(list(tags), ['x', 'Y'])
def test_add_iterable(self):
tags = Tags(['A'])
tags.add(('b b', '', 'a', 'NONE'))
tags.add(Tags(['BB', 'C']))
assert_equal(list(tags), ['A', 'b b', 'C'])
def test_remove_string(self):
tags = Tags(['a', 'B B'])
tags.remove('a')
assert_equal(list(tags), ['B B'])
tags.remove('bb')
assert_equal(list(tags), [])
def test_remove_non_existing(self):
tags = Tags(['a'])
tags.remove('nonex')
assert_equal(list(tags), ['a'])
def test_remove_iterable(self):
tags = Tags(['a', 'B B'])
tags.remove(['nonex', '', 'A'])
tags.remove(Tags('__B_B__'))
assert_equal(list(tags), [])
def test_remove_using_pattern(self):
tags = Tags(['t1', 't2', '1', '1more'])
tags.remove('?2')
assert_equal(list(tags), ['1', '1more', 't1'])
tags.remove('*1*')
assert_equal(list(tags), [])
def test_add_and_remove_none(self):
tags = Tags(['t'])
tags.add(None)
tags.remove(None)
assert_equal(list(tags), ['t'])
def test_contains(self):
assert_true('a' in Tags(['a', 'b']))
assert_true('c' not in Tags(['a', 'b']))
assert_true('AA' in Tags(['a_a', 'b']))
def test_contains_pattern(self):
assert_true('a*' in Tags(['a', 'b']))
assert_true('a*' in Tags(['u2', 'abba']))
assert_true('a?' not in Tags(['a', 'abba']))
def test_length(self):
assert_equal(len(Tags()), 0)
assert_equal(len(Tags(['a', 'b'])), 2)
def test_truth(self):
assert_true(not Tags())
assert_true(Tags(['a']))
def test_unicode(self):
assert_equal(unicode(Tags()), '[]')
assert_equal(unicode(Tags(['y', "X'X", 'Y'])), "[X'X, y]")
assert_equal(unicode(Tags([u'\xe4', 'a'])), u'[a, \xe4]')
def test_str(self):
assert_equal(str(Tags()), '[]')
assert_equal(str(Tags(['y', "X'X"])), "[X'X, y]")
assert_equal(str(Tags([u'\xe4', 'a'])), '[a, \xc3\xa4]')
class TestTagPatterns(unittest.TestCase):
def test_match(self):
patterns = TagPatterns(['x', 'y', 'z*'])
assert_false(patterns.match([]))
assert_false(patterns.match(['no', 'match']))
assert_true(patterns.match(['x']))
assert_true(patterns.match(['xxx', 'zzz']))
def test_match_with_and(self):
patterns = TagPatterns(['xANDy', '???ANDz'])
assert_false(patterns.match([]))
assert_false(patterns.match(['x']))
assert_true(patterns.match(['x', 'y', 'z']))
assert_true(patterns.match(['123', 'y', 'z']))
def test_match_with_not(self):
patterns = TagPatterns(['xNOTy', '???NOT?'])
assert_false(patterns.match([]))
assert_false(patterns.match(['x', 'y']))
assert_false(patterns.match(['123', 'y', 'z']))
assert_true(patterns.match(['x']))
assert_true(patterns.match(['123', 'xx']))
def test_match_with_not_and_and(self):
patterns = TagPatterns(['xNOTyANDz', 'aANDbNOTc',
'1 AND 2? AND 3?? NOT 4* AND 5* AND 6*'])
assert_false(patterns.match([]))
assert_false(patterns.match(['x', 'y', 'z']))
assert_true(patterns.match(['x', 'y']))
assert_true(patterns.match(['x']))
assert_false(patterns.match(['a', 'b', 'c']))
assert_false(patterns.match(['a']))
assert_false(patterns.match(['b']))
assert_true(patterns.match(['a', 'b']))
assert_true(patterns.match(['a', 'b', 'xxxx']))
assert_false(patterns.match(['1', '22', '33']))
assert_false(patterns.match(['1', '22', '333', '4', '5', '6']))
assert_true(patterns.match(['1', '22', '333']))
assert_true(patterns.match(['1', '22', '333', '4', '5', '7']))
def test_match_with_multiple_nots(self):
patterns = TagPatterns(['xNOTyNOTz', '1 NOT 2 NOT 3 NOT 4'])
assert_true(patterns.match(['x']))
assert_false(patterns.match(['x', 'y']))
assert_false(patterns.match(['x', 'z']))
assert_false(patterns.match(['x', 'y', 'z']))
assert_false(patterns.match(['xxx']))
assert_true(patterns.match(['1']))
assert_false(patterns.match(['1', '3', '4']))
assert_false(patterns.match(['1', '2', '3']))
assert_false(patterns.match(['1', '2', '3', '4']))
def test_match_with_multiple_nots_with_ands(self):
patterns = TagPatterns('a AND b NOT c AND d NOT e AND f')
assert_true(patterns.match(['a', 'b']))
assert_true(patterns.match(['a', 'b', 'c']))
assert_true(patterns.match(['a', 'b', 'c', 'e']))
assert_false(patterns.match(['a', 'b', 'c', 'd']))
assert_false(patterns.match(['a', 'b', 'e', 'f']))
assert_false(patterns.match(['a', 'b', 'c', 'd', 'e', 'f']))
assert_false(patterns.match(['a', 'b', 'c', 'd', 'e']))
def test_seq2str(self):
patterns = TagPatterns([u'is\xe4', u'\xe4iti'])
assert_equal(utils.seq2str(patterns), u"'is\xe4' and '\xe4iti'")
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python3
#
# Copyright 2021 Venafi, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import platform
import re
import unittest
from assets import SSH_CERT_DATA, SSH_PRIVATE_KEY, SSH_PUBLIC_KEY
from test_env import TPP_TOKEN_URL, TPP_USER, TPP_PASSWORD, TPP_SSH_CADN, TPP_URL
from test_utils import timestamp
from vcert import (CommonConnection, SSHCertRequest, TPPTokenConnection, Authentication,
SCOPE_SSH, write_ssh_files, logger, venafi_connection, VenafiPlatform, TPPConnection)
from vcert.ssh_utils import SSHRetrieveResponse, SSHKeyPair, SSHCATemplateRequest
log = logger.get_child("test-ssh")
SERVICE_GENERATED_NO_KEY_ERROR = "{} key data is {} empty for Certificate {}" # type: str
SSH_CERT_DATA_ERROR = "Certificate data is empty for Certificate {}" # type: str
class TestTPPTokenSSHCertificate(unittest.TestCase):
def __init__(self, *args, **kwargs):
self.tpp_conn = TPPTokenConnection(url=TPP_TOKEN_URL, http_request_kwargs={'verify': "/tmp/chain.pem"})
auth = Authentication(user=TPP_USER, password=<PASSWORD>, scope=SCOPE_SSH)
self.tpp_conn.get_access_token(auth)
super(TestTPPTokenSSHCertificate, self).__init__(*args, **kwargs)
def test_enroll_local_generated_keypair(self):
keypair = SSHKeyPair()
keypair.generate(key_size=4096, passphrase="<PASSWORD>")
request = SSHCertRequest(cadn=TPP_SSH_CADN, key_id=_random_key_id())
request.validity_period = "4h"
request.source_addresses = ["test.com"]
request.set_public_key_data(keypair.public_key())
response = _enroll_ssh_cert(self.tpp_conn, request)
self.assertTrue(response.private_key_data is None,
SERVICE_GENERATED_NO_KEY_ERROR.format("Private", "not", request.key_id))
self.assertTrue(response.public_key_data, SERVICE_GENERATED_NO_KEY_ERROR.format("Public", "", request.key_id))
self.assertTrue(response.public_key_data == request.get_public_key_data(),
f"Public key on response does not match request."
f"\nExpected: {request.get_public_key_data()}"
f"\nGot: {response.public_key_data}")
self.assertTrue(response.certificate_data, SSH_CERT_DATA_ERROR.format(request.key_id))
def test_enroll_service_generated_keypair(self):
request = SSHCertRequest(cadn=TPP_SSH_CADN, key_id=_random_key_id())
request.validity_period = "4h"
request.source_addresses = ["test.com"]
response = _enroll_ssh_cert(self.tpp_conn, request)
self.assertTrue(response.private_key_data, SERVICE_GENERATED_NO_KEY_ERROR.format("Private", "", request.key_id))
self.assertTrue(response.public_key_data, SERVICE_GENERATED_NO_KEY_ERROR.format("Public", "", request.key_id))
self.assertTrue(response.certificate_data, SSH_CERT_DATA_ERROR.format(request.key_id))
def test_retrieve_ca_public_key(self):
tpp_connector = venafi_connection(platform=VenafiPlatform.TPP, url=TPP_TOKEN_URL,
http_request_kwargs={'verify': "/tmp/chain.pem"})
request = SSHCATemplateRequest(ca_template=TPP_SSH_CADN)
ssh_config = tpp_connector.retrieve_ssh_config(ca_request=request)
self.assertIsNotNone(ssh_config.ca_public_key, f"{TPP_SSH_CADN} Public Key data is empty")
self.assertIsNone(ssh_config.ca_principals, f"{TPP_SSH_CADN} default principals is not empty")
log.debug(f"{TPP_SSH_CADN} Public Key data:\n{ssh_config.ca_public_key}")
def test_retrieve_ca_public_key_and_principals(self):
ssh_config = _retrieve_ssh_config(self.tpp_conn)
self.assertIsNotNone(ssh_config.ca_public_key, f"{TPP_SSH_CADN} Public Key data is empty")
self.assertIsNotNone(ssh_config.ca_principals, f"{TPP_SSH_CADN} default principals is empty")
log.debug(f"{TPP_SSH_CADN} Public Key data: {ssh_config.ca_public_key}")
log.debug(f"{TPP_SSH_CADN} default principals: {ssh_config.ca_principals}")
class TestTPPSSHCertificate(unittest.TestCase):
def __init__(self, *args, **kwargs):
self.tpp_conn = TPPConnection(TPP_USER, TPP_PASSWORD, TPP_URL, http_request_kwargs={'verify': "/tmp/chain.pem"})
super(TestTPPSSHCertificate, self).__init__(*args, **kwargs)
def test_retrieve_ca_public_key_and_principals(self):
ssh_config = _retrieve_ssh_config(self.tpp_conn)
self.assertIsNotNone(ssh_config.ca_public_key, f"{TPP_SSH_CADN} Public Key data is empty")
self.assertIsNotNone(ssh_config.ca_principals, f"{TPP_SSH_CADN} default principals is empty")
log.debug(f"{TPP_SSH_CADN} Public Key data: {ssh_config.ca_public_key}")
log.debug(f"{TPP_SSH_CADN} default principals: {ssh_config.ca_principals}")
class TestSSHUtils(unittest.TestCase):
def test_write_ssh_files(self):
key_id = _random_key_id()
normalized_name = re.sub(r"[^A-Za-z0-9]+", "_", key_id)
full_path = f"./{normalized_name}"
write_ssh_files("./", key_id, SSH_CERT_DATA, SSH_PRIVATE_KEY, SSH_PUBLIC_KEY)
err_msg = "{} serialization does not match expected value"
with open(f"{full_path}-cert.pub", "r") as cert_file:
s_cert = cert_file.read()
self.assertTrue(SSH_CERT_DATA == s_cert, err_msg.format("SSH Certificate"))
with open(full_path, "r") as priv_key_file:
s_priv_key = priv_key_file.read()
expected_priv_key = SSH_PRIVATE_KEY
if platform.system() != "Windows":
expected_priv_key = expected_priv_key.replace("\r\n", "\n")
self.assertTrue(expected_priv_key == s_priv_key, err_msg.format("SSH Private Key"))
with open(f"{full_path}.pub", "r") as pub_key_file:
s_pub_key = pub_key_file.read()
self.assertTrue(SSH_PUBLIC_KEY == s_pub_key, err_msg.format("SSH Public Key"))
def _enroll_ssh_cert(connector, request):
"""
:param CommonConnection connector:
:param SSHCertRequest request:
:rtype: SSHRetrieveResponse
"""
success = connector.request_ssh_cert(request)
assert success
response = connector.retrieve_ssh_cert(request)
assert isinstance(response, SSHRetrieveResponse)
return response
def _retrieve_ssh_config(connection):
"""
:param vcert.AbstractTPPConnection connection:
:rtype: vcert.SSHConfig
"""
request = SSHCATemplateRequest(ca_template=TPP_SSH_CADN)
ssh_config = connection.retrieve_ssh_config(ca_request=request)
return ssh_config
def _random_key_id():
return f"vcert-python-ssh-{timestamp()}"
|
# -*- coding: utf-8 -*-
# Copyright (C) 2015 Mag. <NAME> All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>
# #*** <License> ************************************************************#
# This module is part of the package GTW.OMP.PAP.E164.
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# #*** </License> ***********************************************************#
#
#++
# Name
# GTW.OMP.PAP.E164.convert_numbering_plan_xls_rtr_at
#
# Purpose
# Convert the spreadsheet supplied by rtr.at for the Austrian Numbering Plan
#
# Revision Dates
# 23-Jul-2015 (CT) Creation
# ««revision-date»»···
#--
from _TFL import TFL
from _TFL import sos
from _TFL.defaultdict import defaultdict
from _TFL.formatted_repr import formatted_repr
from _TFL.portable_repr import portable_repr
from _TFL.predicate import identity
from _TFL.pyk import pyk
from _TFL.Regexp import Regexp, Re_Replacer, Multi_Re_Replacer, re
import _TFL.CAO
import _TFL._Meta.Object
import datetime
import xlrd
### 23-Jul-2015 10:43
### https://www.rtr.at/de/tk/E129/2312_Austrian_Numbering_Plan_2011-03-30.xls
_module_format = r"""
# -*- coding: utf-8 -*-
# Copyright (C) %(year)s Mag. <NAME> All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>@swing.co.at
# #*** <License> ************************************************************#
# This module is part of the package GTW.OMP.PAP.E164.
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# #*** </License> ***********************************************************#
#
# *** This file was generated automatically by
# *** %(generated_by)s
# *** DO NOT edit it manually !
#
from _GTW import GTW
from _TFL import TFL
from _TFL.defaultdict import defaultdict
import _GTW._OMP._PAP._E164.Country
class Country__43 (GTW.OMP.PAP.E164.Country_M) :
generated_from = %(generated_from)s
generation_date = %(generation_date)s
ndc_info_map = \
%(ndc_info_map)s
ndc_types_normal = %(ndc_types_normal)s
ndc_usage_map = \
%(ndc_usage_map)s
sn_max_length_map = defaultdict \
( lambda : %(max_len_default)s
, %(sn_max_length_map)s
)
sn_min_length_map = defaultdict \
( lambda : %(min_len_default)s
, %(sn_min_length_map)s
)
Country = Country__43 # end class
### __END__ GTW.OMP.PAP.E164._Country__43
"""
def _decoded (x) :
return pyk.decoded (x, "utf-8", "iso-8859-1")
# end def _decoded
def _str_int (x) :
return str (int (x))
# end def _str_int
class NDC (TFL.Meta.Object) :
### Want three integer columns, two string columns
_converters = (_str_int, int, int, _decoded, _decoded)
### DRY info
_info_cleaner = Re_Replacer ("^Area code for ", "")
_info_map = \
{ "650" : "Mobile (Telering)"
, "660" : "Mobile (Hutchison 3G/3)"
, "664" : "Mobile (A1)"
, "676" : "Mobile (T-Mobile Austria)"
, "677" : "Mobile (HoT)"
, "680" : "Mobile (BoB)"
, "681" : "Mobile (yesss!)"
, "688" : "Mobile (Previously Tele2)"
, "699" : "Mobile (Previously Orange, yesss!)"
}
### rtr.at specifies 67, 68, 69 as NDCs but these are not complete — the
### actual NDCs look like 676, 688, or 699
_ndc_add_digit = Regexp ("^6[789]$")
### Shorten usage to one word
_usage_map = \
{ "local network code" : "geographic"
, "mobile services" : "mobile"
, "service number" : "service"
, "routing number" : "routing"
}
def __init__ (self, ndc, max_len, min_len, usage, info) :
self.ndc = ndc
self.max_len = max_len
self.min_len = min_len
self.usage = usage
self.info = info
# end def __init__
@classmethod
def from_xls_row (cls, row) :
try :
ndc, max_len, min_len, usage, info = tuple \
(c (x.value) for c, x in zip (cls._converters, row))
except Exception :
pass
else :
if cls._ndc_add_digit.match (ndc) :
for i in range (10) :
ndc_x = ndc + str (i)
yield cls._from_row (ndc_x, max_len, min_len, usage, info)
else :
yield cls._from_row (ndc, max_len, min_len, usage, info)
# end def from_xls_row
@classmethod
def _from_row (cls, ndc, max_len, min_len, usage, info) :
ndc_len = len (ndc)
usage = cls._usage_map.get (usage, usage)
info = cls._info_cleaner (cls._info_map.get (ndc, info))
if not info :
info = usage.capitalize ()
return cls (ndc, max_len - ndc_len, min_len - ndc_len, usage, info)
# end def _from_row
def __repr__ (self) :
return "%s (%s, %s)" % (self, self.min_len, self.max_len)
# end def __repr__
def __str__ (self) :
return "%s [%s]" % (self.ndc, self.info)
# end def __str__
# end class NDC
def _convert_row (row) :
if len (row) == 5 :
yield from NDC.from_xls_row (row)
# end def _convert_row
def gen_records (xls_name) :
book = xlrd.open_workbook (xls_name, encoding_override = "iso-8859-1")
sheet = book.sheet_by_index (0)
for i in range (0, sheet.nrows) :
yield from _convert_row (sheet.row (i))
# end def gen_records
def _main (cmd) :
"""Convert the rtr.at spreadsheet for the Austrian Numbering Plan"""
ndcs = list (gen_records (cmd.xls_name))
info_map = {}
max_counts = defaultdict (int)
min_counts = defaultdict (int)
type_map = defaultdict (set)
usage_map = {}
for ndc in ndcs :
max_counts [ndc.max_len] +=1
min_counts [ndc.min_len] +=1
info_map [ndc.ndc] = ndc.info
usage_map [ndc.ndc] = ndc.usage
type_map [ndc.usage].add (ndc.ndc)
max_len_default = sorted \
((v, k) for k, v in pyk.iteritems (max_counts)) [-1] [1]
min_len_default = sorted \
((v, k) for k, v in pyk.iteritems (min_counts)) [-1] [1]
max_len = dict \
((r.ndc, r.max_len) for r in ndcs if r.max_len != max_len_default)
min_len = dict \
((r.ndc, r.min_len) for r in ndcs if r.min_len != min_len_default)
now = datetime.datetime.now ()
f_repr = formatted_repr
p_repr = portable_repr
print \
( ( _module_format
% dict
( generated_by = sos.path.basename (__file__)
, generated_from = p_repr (sos.path.basename (cmd.xls_name))
, generation_date = p_repr (str (now) [:16])
, max_len_default = max_len_default
, min_len_default = min_len_default
, ndc_types_normal = p_repr (set (("geographic", "mobile")))
, ndc_info_map = f_repr (info_map, level = 4).strip ()
, ndc_type_map = f_repr (type_map, level = 4).strip ()
, ndc_usage_map = f_repr (usage_map, level = 4).strip ()
, sn_max_length_map = f_repr (max_len, level = 5).strip ()
, sn_min_length_map = f_repr (min_len, level = 5).strip ()
, year = now.year
)
).strip ()
)
# end def _main
_Command = TFL.CAO.Cmd \
( handler = _main
, args =
( "xls_name:P"
"?Name of spreadsheet containing the Austrian Numbering Plan"
,
)
, opts =
()
, min_args = 1
, max_args = 1
)
r"""
Example usage:
python convert_numbering_plan_xls_rtr_at.py \
/tmp/2312_Austrian_Numbering_Plan_2011-03-30.xls > _Country__43.py
"""
if __name__ == "__main__" :
_Command ()
### __END__ GTW.OMP.PAP.E164.convert_numbering_plan_xls_rtr_at
|
import torch
import torch.nn as nn
from MHA import MultiHeadedAttention
from FeedForward import PositionwiseFeedForward
from PositionalEncoding import *
from Encoder import EncoderLayer, sequence_mask
from Decoder import DecoderLayer
class subclass(nn.Module):
def __init__(self,
d_model,
nhead,
d_ff,
self_attn_type,
dropout,
attention_dropout):
super().__init__()
self.enc = EncoderLayer(d_model,
nhead,
d_ff,
dropout,
attention_dropout)
self.dec = DecoderLayer(d_model,
nhead,
d_ff,
dropout,
attention_dropout,
self_attn_type=self_attn_type)
self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
def forward(self, src_out, src_mask, tgt_out, tgt_pad_mask, step=None):
# TODO LayerNorm?? Memory 여러개가 각기 다르게 변한다면, 업데이트마다 기존 Transformer보다 변동성이 크다
# 그러므로 반드시! LayerNorm을 해줘야 학습이 용이하다
# Encoder
src_out = self.enc(src_out, src_mask)
src_out = self.layer_norm(src_out)
# Decoder
tgt_out, attn = self.dec(tgt_out,
src_out,
src_mask, # (B, 1, src_len)
tgt_pad_mask,
step=step)
return src_out, tgt_out
class PEDec(nn.Module):
def __init__(self,
enc_num_layers,
dec_num_layers,
d_model,
nhead,
d_ff,
self_attn_type,
dropout,
attention_dropout,
enc_embeddings,
dec_embeddings):
super().__init__()
self.enc_embeddings = enc_embeddings
self.dec_embeddings = dec_embeddings
self.pre_tf = enc_num_layers > dec_num_layers
self.post_tf = enc_num_layers < dec_num_layers
if self.pre_tf:
self.pre_transformer = nn.ModuleList(
[EncoderLayer(d_model,
nhead,
d_ff,
dropout,
attention_dropout)
for i in range(enc_num_layers - dec_num_layers)])
enc_num_layers = dec_num_layers
self.transformer = nn.ModuleList(
[subclass(d_model,
nhead,
d_ff,
self_attn_type,
dropout,
attention_dropout)
for i in range(enc_num_layers)])
elif self.post_tf:
self.transformer = nn.ModuleList(
[subclass(d_model,
nhead,
d_ff,
self_attn_type,
dropout,
attention_dropout)
for i in range(enc_num_layers)])
self.post_transformer = nn.ModuleList(
[DecoderLayer(d_model,
nhead,
d_ff,
dropout,
attention_dropout,
self_attn_type=self_attn_type)
for i in range(dec_num_layers - enc_num_layers)])
else:
self.transformer = nn.ModuleList(
[subclass(d_model,
nhead,
d_ff,
self_attn_type,
dropout,
attention_dropout)
for i in range(enc_num_layers)])
self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
def forward(self, src, tgt, lengths=None, step=None):
src_emb = self.enc_embeddings(src) # (B, src_len, d_model)
# MHA에서 (B, 1, 1, T_src)로 바꿀 예정
src_mask = ~sequence_mask(lengths).unsqueeze(1) # (B, 1, src_len)
tgt_emb = self.dec_embeddings(tgt, step=step)
assert tgt_emb.dim() == 3 # (B, tgt_len, d_model)
pad_idx = self.dec_embeddings.pad_idx
## pad_idx와 같으면 True, 아니면 False
tgt_pad_mask = tgt.data.eq(pad_idx).unsqueeze(1) # (B, 1, tgt_len)
src_out, tgt_out = src_emb, tgt_emb
if self.pre_tf:
for pre_layer in self.pre_transformer:
src_out = pre_layer(src_out, src_mask)
for layer in self.transformer:
src_out, tgt_out = layer(src_out, src_mask, tgt_out, tgt_pad_mask, step)
if self.post_tf:
for post_layer in self.post_transformer:
tgt_out = post_layer(tgt_out,
src_out,
src_mask, # (B, 1, src_len)
tgt_pad_mask,
step=step)
out = self.layer_norm(tgt_out) # (B, src_len, d_model)
return out, lengths
def update_dropout(self, dropout, attention_dropout):
self.embeddings.update_dropout(dropout)
for layer in self.transformer:
layer.update_dropout(dropout, attention_dropout)
def _compute_dec_mask(self, tgt_pad_mask, future):
# tgt_pad_mask : (B, 1, tgt_len) // bool
## pad_idx만 True
tgt_len = tgt_pad_mask.size(-1)
if not future:
# future_mask : (tgt_len, tgt_len)
future_mask = torch.ones([tgt_len, tgt_len],
device=tgt_pad_mask.device,
dtype=torch.uint8)
future_mask = future_mask.triu_(1).view(1, tgt_len, tgt_len) # (1, tgt_len, tgt_len)
try:
## upper triangle만 True
future_mask = future_mask.bool()
except AttributeError:
pass
## torch.gt(A, 0) : A elements > 0 이면 True
## pad와 upper triangle은 True, 그 이외에는 False
dec_mask = torch.gt(tgt_pad_mask + future_mask, 0)
else:
dec_mask = tgt_pad_mask
return dec_mask
def _forward_self_attn(self, inputs_norm, dec_mask, step):
if isinstance(self.self_attn, MultiHeadedAttention):
return self.self_attn(inputs_norm,
inputs_norm,
inputs_norm,
mask=dec_mask,
attn_type='self')
|
<filename>CODE/dapt_task/controller.py
#! -*- encoding:utf-8 -*-
"""
@File : controller.py
@Author : <NAME>
@Contact : <EMAIL>
@Dscpt :
"""
import json
import logging
import os
from torch.utils.data import dataloader
logger = logging.getLogger("controller")
console = logging.StreamHandler();console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(name)s - %(message)s', datefmt = r"%y/%m/%d %H:%M")
console.setFormatter(formatter)
logger.addHandler(console)
import torch
from tqdm import tqdm
from utils.common import get_device, mkdir_if_notexist, result_dump
from dapt_task.trainer import Trainer
class DomainAdaptivePreTrain:
def __init__(self, args, model_kwargs={}) -> None:
self.config = args
self.model_kwargs = model_kwargs # args for model like cs_num
self.model = None
self.train_dataloader = None
self.deval_dataloader = None
self.test_dataloader = None
gpu_ids = list(map(int, self.config.gpu_ids.split()))
self.multi_gpu = (len(gpu_ids) > 1)
self.device = get_device(gpu_ids)
def load_model(self, ModelClass):
if self.config.mission == "train":
model_dir = self.config.PTM_model_vocab_dir
model = ModelClass.from_pretrained(model_dir, **self.model_kwargs)
else:
model_dir = self.config.saved_model_dir
if hasattr(ModelClass, 'from_pt'):
model = ModelClass.from_pt(model_dir, **self.model_kwargs)
else:
model = ModelClass.from_pretrained(model_dir, **self.model_kwargs)
if self.multi_gpu:
model = torch.nn.DataParallel(model, device_ids=self.gpu_ids)
self.trainer = Trainer(
model, self.multi_gpu, self.device,
self.config.print_step, self.config.eval_after_tacc,
self.config.fp16, self.config.clip_batch_off,
self.config.nsp,
self.config.result_dir,
exp_name=self.config.task_str)
self.model = model
def load_data(self, ProcessorClass, tokenizer):
if self.config.mission in ("train", 'conti-train'):
# processor = ProcessorClass(self.config, 'dev', tokenizer)
processor = ProcessorClass(self.config, 'train', tokenizer)
processor.load_data()
self.train_dataloader = processor.make_dataloader(shuffle=False)
# self.train_dataloader = processor.make_dataloader(self.tokenizer, self.config.train_batch_size, False, 128, shuffle=False)
logger.info("train dataset loaded")
processor = ProcessorClass(self.config, 'dev', tokenizer)
processor.load_data()
self.deval_dataloader = processor.make_dataloader(shuffle=False)
logger.info("dev dataset loaded")
elif self.config.mission == "eval":
processor = ProcessorClass(self.config, 'dev', tokenizer)
processor.load_data()
self.deval_dataloader = processor.make_dataloader(shuffle=False)
self.processor = processor
logger.info("dev dataset loaded")
elif self.config.mission == 'predict':
processor = ProcessorClass(self.config, 'test', tokenizer)
processor.load_data()
self.test_dataloader = processor.make_dataloader(shuffle=False)
self.processor = processor
logger.info("test dataset loaded")
def train(self):
train_dataloader = self.train_dataloader
deval_dataloader = self.deval_dataloader
train_step = len(train_dataloader)
total_training_step = train_step // self.config.gradient_accumulation_steps * self.config.num_train_epochs
warmup_proportion = self.config.warmup_proportion
# make and set optimizer & scheduler
optimizer = self.trainer.make_optimizer(self.config.weight_decay, self.config.learning_rate)
scheduler = self.trainer.make_scheduler(optimizer, warmup_proportion, total_training_step)
self.trainer.set_optimizer(optimizer)
self.trainer.set_scheduler(scheduler)
# 断点续训则先进行一次 Eval
if self.config.mission == 'conti-train':
right_num = self.evaluate()
self.trainer.set_best_acc(right_num)
self.trainer.load_train_info(self.config.saved_model_dir)
self.trainer.train(
self.config.num_train_epochs, self.config.gradient_accumulation_steps, train_dataloader, deval_dataloader, self.config.save_mode)
def evaluate(self):
pass
def run_dev(self):
pass
def predict_test(self):
pass
|
<reponame>bengentil/openshift-ansible-contrib
#!/usr/bin/env python
# vim: sw=2 ts=2
import click
import os
import sys
@click.command()
### Cluster options
@click.option('--console-port', default='443', type=click.IntRange(1,65535), help='OpenShift web console port',
show_default=True)
@click.option('--deployment-type', default='openshift-enterprise', help='OpenShift deployment type',
show_default=True)
@click.option('--openshift-sdn', default='redhat/openshift-ovs-multitenant', type=click.Choice(['redhat/openshift-ovs-subnet', 'redhat/openshift-ovs-multitenant']), help='OpenShift SDN',
show_default=True)
### AWS/EC2 options
@click.option('--glusterfs-stack-name', help='Specify a gluster stack name. Making the name unique will allow for multiple deployments',
show_default=True)
@click.option('--region', default='us-east-1', help='ec2 region',
show_default=True)
@click.option('--ami', default='ami-fbc89880', help='ec2 ami',
show_default=True)
@click.option('--node-instance-type', default='m4.2xlarge', help='ec2 instance type',
show_default=True)
@click.option('--use-cloudformation-facts', is_flag=True, help='Use cloudformation to populate facts. Requires Deployment >= OCP 3.5',
show_default=True)
@click.option('--keypair', help='ec2 keypair name',
show_default=True)
@click.option('--private-subnet-id1', help='Specify a Private subnet within the existing VPC',
show_default=True)
@click.option('--private-subnet-id2', help='Specify a Private subnet within the existing VPC',
show_default=True)
@click.option('--private-subnet-id3', help='Specify a Private subnet within the existing VPC',
show_default=True)
@click.option('--glusterfs-volume-size', default='500', help='Gluster volume size in GB',
show_default=True)
@click.option('--glusterfs-volume-type', default='st1', help='Gluster volume type',
show_default=True)
@click.option('--iops', help='Specfify the IOPS for a volume (used only with IO1)',
show_default=True)
### DNS options
@click.option('--public-hosted-zone', help='hosted zone for accessing the environment')
### Subscription and Software options
@click.option('--rhsm-user', help='Red Hat Subscription Management User')
@click.option('--rhsm-password', help='Red Hat Subscription Management Password',
hide_input=True,)
@click.option('--rhsm-pool', help='Red Hat Subscription Management Pool Name')
### Miscellaneous options
@click.option('--containerized', default='False', help='Containerized installation of OpenShift',
show_default=True)
@click.option('--iam-role', help='Specify the name of the existing IAM Instance profile',
show_default=True)
@click.option('--node-sg', help='Specify the already existing node security group id',
show_default=True)
@click.option('--existing-stack', help='Specify the name of the existing CloudFormation stack')
@click.option('--no-confirm', is_flag=True,
help='Skip confirmation prompt')
@click.help_option('--help', '-h')
@click.option('-v', '--verbose', count=True)
def launch_refarch_env(region=None,
ami=None,
no_confirm=False,
node_instance_type=None,
glusterfs_stack_name=None,
keypair=None,
public_hosted_zone=None,
deployment_type=None,
console_port=443,
rhsm_user=None,
rhsm_password=<PASSWORD>,
rhsm_pool=None,
containerized=None,
node_type=None,
private_subnet_id1=None,
private_subnet_id2=None,
private_subnet_id3=None,
glusterfs_volume_type=None,
glusterfs_volume_size=None,
openshift_sdn=None,
iops=None,
node_sg=None,
iam_role=None,
existing_stack=None,
use_cloudformation_facts=False,
verbose=0):
# Need to prompt for the R53 zone:
if public_hosted_zone is None:
public_hosted_zone = click.prompt('Hosted DNS zone for accessing the environment')
if existing_stack is None:
existing_stack = click.prompt('Specify the name of the existing CloudFormation stack')
if glusterfs_stack_name is None:
glusterfs_stack_name = click.prompt('Specify a unique name for the CNS CloudFormation stack')
# If no keypair is specified fail:
if keypair is None:
keypair = click.prompt('A SSH keypair must be specified or created')
# If the user already provided values, don't bother asking again
if deployment_type in ['openshift-enterprise'] and rhsm_user is None:
rhsm_user = click.prompt("RHSM username?")
if deployment_type in ['openshift-enterprise'] and rhsm_password is None:
rhsm_password = click.prompt("RHSM password?", hide_input=True)
if deployment_type in ['openshift-enterprise'] and rhsm_pool is None:
rhsm_pool = click.prompt("RHSM Pool ID or Subscription Name for OpenShift?")
# Prompt for vars if they are not defined
if use_cloudformation_facts and iam_role is None:
iam_role = "Computed by Cloudformations"
elif iam_role is None:
iam_role = click.prompt("Specify the IAM Role of the node?")
if use_cloudformation_facts and node_sg is None:
node_sg = "Computed by Cloudformations"
elif node_sg is None:
node_sg = click.prompt("Specify the Security Group for the nodes?")
if use_cloudformation_facts and private_subnet_id1 is None:
private_subnet_id1 = "Computed by Cloudformations"
elif private_subnet_id1 is None:
private_subnet_id1 = click.prompt("Specify the first private subnet for the nodes?")
if use_cloudformation_facts and private_subnet_id2 is None:
private_subnet_id2 = "Computed by Cloudformations"
elif private_subnet_id2 is None:
private_subnet_id2 = click.prompt("Specify the second private subnet for the nodes?")
if use_cloudformation_facts and private_subnet_id3 is None:
private_subnet_id3 = "Computed by Cloudformations"
elif private_subnet_id3 is None:
private_subnet_id3 = click.prompt("Specify the third private subnet for the nodes?")
if glusterfs_volume_type in ['io1']:
iops = click.prompt('Specify a numeric value for iops')
if iops is None:
iops = "NA"
# Hidden facts for infrastructure.yaml
create_key = "no"
create_vpc = "no"
add_node = "yes"
deploy_glusterfs = "true"
node_type = "glusterfs"
# Display information to the user about their choices
if use_cloudformation_facts:
click.echo('Configured values:')
click.echo('\tami: %s' % ami)
click.echo('\tregion: %s' % region)
click.echo('\tglusterfs_stack_name: %s' % glusterfs_stack_name)
click.echo('\tnode_instance_type: %s' % node_instance_type)
click.echo('\tglusterfs_volume_type: %s' % glusterfs_volume_type)
click.echo('\tglusterfs_volume_size: %s' % glusterfs_volume_size)
click.echo('\tiops: %s' % iops)
click.echo('\topenshift_sdn: %s' % openshift_sdn)
click.echo('\tkeypair: %s' % keypair)
click.echo('\tdeployment_type: %s' % deployment_type)
click.echo('\tpublic_hosted_zone: %s' % public_hosted_zone)
click.echo('\tconsole port: %s' % console_port)
click.echo('\trhsm_user: %s' % rhsm_user)
click.echo('\trhsm_password: *******')
click.echo('\trhsm_pool: %s' % rhsm_pool)
click.echo('\tcontainerized: %s' % containerized)
click.echo('\texisting_stack: %s' % existing_stack)
click.echo('\tSubnets, Security Groups, and IAM Roles will be gather from the CloudFormation')
click.echo("")
else:
click.echo('Configured values:')
click.echo('\tami: %s' % ami)
click.echo('\tregion: %s' % region)
click.echo('\tglusterfs_stack_name: %s' % glusterfs_stack_name)
click.echo('\tnode_instance_type: %s' % node_instance_type)
click.echo('\tprivate_subnet_id1: %s' % private_subnet_id1)
click.echo('\tprivate_subnet_id2: %s' % private_subnet_id2)
click.echo('\tprivate_subnet_id3: %s' % private_subnet_id3)
click.echo('\tglusterfs_volume_type: %s' % glusterfs_volume_type)
click.echo('\tglusterfs_volume_size: %s' % glusterfs_volume_size)
click.echo('\tiops: %s' % iops)
click.echo('\openshift_sdn: %s' % openshift_sdn)
click.echo('\tkeypair: %s' % keypair)
click.echo('\tkeypair: %s' % keypair)
click.echo('\tnode_sg: %s' % node_sg)
click.echo('\tdeployment_type: %s' % deployment_type)
click.echo('\tpublic_hosted_zone: %s' % public_hosted_zone)
click.echo('\tconsole port: %s' % console_port)
click.echo('\trhsm_user: %s' % rhsm_user)
click.echo('\trhsm_password: *******')
click.echo('\trhsm_pool: %s' % rhsm_pool)
click.echo('\tcontainerized: %s' % containerized)
click.echo('\tiam_role: %s' % iam_role)
click.echo('\texisting_stack: %s' % existing_stack)
click.echo("")
if not no_confirm:
click.confirm('Continue using these values?', abort=True)
playbooks = ['playbooks/infrastructure.yaml', 'playbooks/add-node.yaml']
for playbook in playbooks:
# hide cache output unless in verbose mode
devnull='> /dev/null'
if verbose > 0:
devnull=''
# refresh the inventory cache to prevent stale hosts from
# interferring with re-running
command='inventory/aws/hosts/ec2.py --refresh-cache %s' % (devnull)
os.system(command)
# remove any cached facts to prevent stale data during a re-run
command='rm -rf .ansible/cached_facts'
os.system(command)
if use_cloudformation_facts:
command='ansible-playbook -i inventory/aws/hosts -e \'region=%s \
ami=%s \
keypair=%s \
glusterfs_stack_name=%s \
add_node=yes \
node_instance_type=%s \
public_hosted_zone=%s \
deployment_type=%s \
console_port=%s \
rhsm_user=%s \
rhsm_password=%s \
rhsm_pool="%s" \
containerized=%s \
node_type=glusterfs \
key_path=/dev/null \
create_key=%s \
create_vpc=%s \
deploy_glusterfs=%s \
glusterfs_volume_type=%s \
glusterfs_volume_size=%s \
iops=%s \
openshift_sdn=%s \
stack_name=%s \' %s' % (region,
ami,
keypair,
glusterfs_stack_name,
node_instance_type,
public_hosted_zone,
deployment_type,
console_port,
rhsm_user,
rhsm_password,
rhsm_pool,
containerized,
create_key,
create_vpc,
deploy_glusterfs,
glusterfs_volume_type,
glusterfs_volume_size,
iops,
openshift_sdn,
existing_stack,
playbook)
else:
command='ansible-playbook -i inventory/aws/hosts -e \'region=%s \
ami=%s \
keypair=%s \
glusterfs_stack_name=%s \
add_node=yes \
node_sg=%s \
node_instance_type=%s \
private_subnet_id1=%s \
private_subnet_id2=%s \
private_subnet_id3=%s \
public_hosted_zone=%s \
deployment_type=%s \
console_port=%s \
rhsm_user=%s \
rhsm_password=%s \
rhsm_pool="%s" \
containerized=%s \
node_type=glusterfs \
iam_role=%s \
key_path=/dev/null \
create_key=%s \
create_vpc=%s \
deploy_glusterfs=%s \
glusterfs_volume_type=%s \
glusterfs_volume_size=%s \
iops=%s \
openshift_sdn=%s \
stack_name=%s \' %s' % (region,
ami,
keypair,
glusterfs_stack_name,
node_sg,
node_instance_type,
private_subnet_id1,
private_subnet_id2,
private_subnet_id3,
public_hosted_zone,
deployment_type,
console_port,
rhsm_user,
rhsm_password,
rhsm_pool,
containerized,
iam_role,
create_key,
create_vpc,
deploy_glusterfs,
glusterfs_volume_type,
glusterfs_volume_size,
iops,
openshift_sdn,
existing_stack,
playbook)
if verbose > 0:
command += " -" + "".join(['v']*verbose)
click.echo('We are running: %s' % command)
status = os.system(command)
if os.WIFEXITED(status) and os.WEXITSTATUS(status) != 0:
return os.WEXITSTATUS(status)
if __name__ == '__main__':
# check for AWS access info
if os.getenv('AWS_ACCESS_KEY_ID') is None or os.getenv('AWS_SECRET_ACCESS_KEY') is None:
print 'AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY **MUST** be exported as environment variables.'
sys.exit(1)
launch_refarch_env(auto_envvar_prefix='OSE_REFArch')
|
import logging
log = logging.getLogger(__name__)
import itertools
import numpy as np
from copy import deepcopy
import pycqed.measurement.waveform_control.sequence as sequence
from pycqed.utilities.general import add_suffix_to_dict_keys
import pycqed.measurement.randomized_benchmarking.randomized_benchmarking as rb
import pycqed.measurement.randomized_benchmarking.two_qubit_clifford_group as tqc
from pycqed.measurement.pulse_sequences.single_qubit_tek_seq_elts import \
get_pulse_dict_from_pars, add_preparation_pulses, pulse_list_list_seq, \
prepend_pulses, add_suffix, sweep_pulse_params
from pycqed.measurement.gate_set_tomography.gate_set_tomography import \
create_experiment_list_pyGSTi_qudev as get_exp_list
from pycqed.measurement.waveform_control import pulsar as ps
import pycqed.measurement.waveform_control.segment as segment
from pycqed.analysis_v2 import tomography_qudev as tomo
station = None
kernel_dir = 'kernels/'
# You need to explicitly set this before running any functions from this module
# I guess there are cleaner solutions :)
cached_kernels = {}
def n_qubit_off_on(pulse_pars_list, RO_pars_list, return_seq=False,
parallel_pulses=False, preselection=False, upload=True,
RO_spacing=2000e-9):
n = len(pulse_pars_list)
seq_name = '{}_qubit_OffOn_sequence'.format(n)
seq = sequence.Sequence(seq_name)
seg_list = []
RO_pars_list_presel = deepcopy(RO_pars_list)
for i, RO_pars in enumerate(RO_pars_list):
RO_pars['name'] = 'RO_{}'.format(i)
RO_pars['element_name'] = 'RO'
if i != 0:
RO_pars['ref_point'] = 'start'
for i, RO_pars_presel in enumerate(RO_pars_list_presel):
RO_pars_presel['ref_pulse'] = RO_pars_list[-1]['name']
RO_pars_presel['ref_point'] = 'start'
RO_pars_presel['element_name'] = 'RO_presel'
RO_pars_presel['pulse_delay'] = -RO_spacing
# Create a dict with the parameters for all the pulses
pulse_dict = dict()
for i, pulse_pars in enumerate(pulse_pars_list):
pars = pulse_pars.copy()
if i == 0 and parallel_pulses:
pars['ref_pulse'] = 'segment_start'
if i != 0 and parallel_pulses:
pars['ref_point'] = 'start'
pulses = add_suffix_to_dict_keys(
get_pulse_dict_from_pars(pars), ' {}'.format(i))
pulse_dict.update(pulses)
# Create a list of required pulses
pulse_combinations = []
for pulse_list in itertools.product(*(n*[['I', 'X180']])):
pulse_comb = (n)*['']
for i, pulse in enumerate(pulse_list):
pulse_comb[i] = pulse + ' {}'.format(i)
pulse_combinations.append(pulse_comb)
for i, pulse_comb in enumerate(pulse_combinations):
pulses = []
for j, p in enumerate(pulse_comb):
pulses += [pulse_dict[p]]
pulses += RO_pars_list
if preselection:
pulses = pulses + RO_pars_list_presel
seg = segment.Segment('segment_{}'.format(i), pulses)
seg_list.append(seg)
seq.add(seg)
repeat_dict = {}
repeat_pattern = ((1.0 + int(preselection))*len(pulse_combinations),1)
for i, RO_pars in enumerate(RO_pars_list):
repeat_dict = seq.repeat(RO_pars, None, repeat_pattern)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
if return_seq:
return seq, seg_list
else:
return seq_name
def two_qubit_randomized_benchmarking_seqs(
qb1n, qb2n, operation_dict, cliffords, nr_seeds=None,
max_clifford_idx=11520, cz_pulse_name=None, cal_points=None,
net_clifford=0, clifford_decomposition_name='HZ',
cl_sequence=None, sampling_seeds=None,
interleaved_gate=None, upload=True, prep_params=dict()):
"""
Args
qb1n (str): name of qb1
qb2n (str): name of qb2
operation_dict (dict): dict with all operations from both qubits and
with the multiplexed RO pulse pars
cliffords (array): array of ints specifying the number of random
Cliffords to generate in each sequence
nr_seeds (array): array of the form np.arange(nr_seeds_value)
max_clifford_idx (int): specifies up to which index of the elements in
the two-qubit Clifford group to include in the random generation.
See measurement/randomized_benchmarking/two_qubit_clifford_group.py.
CZ_pulse_name (str): pycqed name of the CZ pulse
cal_points (CalibrationPoints): instance of CalibrationPoints
net_clifford (int): 0 or 1; whether the recovery Clifford returns
qubits to ground statea (0) or puts them in the excited states (1)
clifford_decomp_name (str): the decomposition of Clifford gates
into primitives; can be "XY", "HZ", or "5Primitives"
cl_sequence (list): the Clifford sequence to use for all seeds. Can
also be lists of lists in which case the user must ensure that
len(nr seeds) % len(cl_sequence) == 0.
sampling_seeds (array of ints): ints that will be used as seeds for
the random generation of Cliffords. Should have the same length
as nr_seeds.
interleaved_gate (str): pycqed name for a gate
upload (bool): whether to upload sequence to AWGs
prep_params (dict): qubit preparation_params dict
"""
# This is used for checking that the recovery is correct
import qutip as qtp
standard_pulses = {
'I': qtp.qeye(2),
'Z0': qtp.qeye(2),
'X180': qtp.sigmax(),
'mX180': qtp.sigmax(),
'Y180': qtp.sigmay(),
'mY180': qtp.sigmay(),
'X90': qtp.rotation(qtp.sigmax(), np.pi / 2),
'mX90': qtp.rotation(qtp.sigmax(), -np.pi / 2),
'Y90': qtp.rotation(qtp.sigmay(), np.pi / 2),
'mY90': qtp.rotation(qtp.sigmay(), -np.pi / 2),
'Z90': qtp.rotation(qtp.sigmaz(), np.pi / 2),
'mZ90': qtp.rotation(qtp.sigmaz(), -np.pi / 2),
'Z180': qtp.sigmaz(),
'mZ180': qtp.sigmaz(),
'CZ': qtp.cphase(np.pi)
}
seq_name = '2Qb_RB_sequence'
if sampling_seeds is None:
if nr_seeds is None:
raise ValueError('Please provide either "sampling_seeds" or '
'"nr_seeds."')
sampling_seeds = [None] * len(nr_seeds)
else:
nr_seeds = np.arange(len(sampling_seeds))
# Set Clifford decomposition
tqc.gate_decomposition = rb.get_clifford_decomposition(
clifford_decomposition_name)
if cl_sequence is not None:
if isinstance(cl_sequence[0], list):
# if cl_sequence is a list of lists such that
# len(nr_seeds) != len(cl_sequence) but
# len(nr_seeds) % len(cl_sequence) == 0,
# then create as many copies of the lists in cl_sequence until
# len(cl_sequence) == len(nr_seeds).
assert len(nr_seeds) % len(cl_sequence) == 0
k = len(nr_seeds) // len(cl_sequence)
cl_seq_temp = k * cl_sequence
sequences = []
for nCl in cliffords:
pulse_list_list_all = []
for s in nr_seeds:
if cl_sequence is None:
cl_seq = rb.randomized_benchmarking_sequence_new(
nCl,
number_of_qubits=2,
max_clifford_idx=max_clifford_idx,
interleaving_cl=interleaved_gate,
desired_net_cl=net_clifford,
seed=sampling_seeds[s])
elif isinstance(cl_sequence[0], list):
cl_seq = cl_seq_temp[s]
else:
cl_seq = cl_sequence
pulse_list = []
pulsed_qubits = {qb1n, qb2n}
pulse_tuples_list_all = []
for idx in cl_seq:
pulse_tuples_list = tqc.TwoQubitClifford(idx).gate_decomposition
pulse_tuples_list_all += pulse_tuples_list
for j, pulse_tuple in enumerate(pulse_tuples_list):
if isinstance(pulse_tuple[1], list):
pulse_list += [operation_dict[cz_pulse_name]]
pulsed_qubits = {qb1n, qb2n}
else:
qb_name = qb1n if '0' in pulse_tuple[1] else qb2n
pulse_name = pulse_tuple[0]
if 'Z' not in pulse_name:
if qb_name not in pulsed_qubits:
pulse_name += 's'
else:
pulsed_qubits = set()
pulsed_qubits |= {qb_name}
pulse_list += [
operation_dict[pulse_name + ' ' + qb_name]]
# check recovery
gproduct = qtp.tensor(qtp.identity(2), qtp.identity(2))
for i, cl_tup in enumerate(pulse_tuples_list_all):
if cl_tup[0] == 'CZ':
gproduct = standard_pulses[cl_tup[0]] * gproduct
else:
eye_2qb = [qtp.identity(2), qtp.identity(2)]
eye_2qb[int(cl_tup[1][-1])] = standard_pulses[cl_tup[0]]
gproduct = qtp.tensor(eye_2qb) * gproduct
x = gproduct.full() / gproduct.full()[0][0]
assert (np.all((np.allclose(np.real(x), np.eye(4)),
np.allclose(np.imag(x), np.zeros(4)))))
pulse_list += generate_mux_ro_pulse_list(
[qb1n, qb2n], operation_dict)
pulse_list_w_prep = add_preparation_pulses(
pulse_list, operation_dict, [qb1n, qb2n], **prep_params)
pulse_list_list_all.append(pulse_list_w_prep)
seq = pulse_list_list_seq(pulse_list_list_all, seq_name+f'_{nCl}',
upload=False)
if cal_points is not None:
seq.extend(cal_points.create_segments(operation_dict,
**prep_params))
sequences.append(seq)
# reuse sequencer memory by repeating readout pattern
for s in sequences:
s.repeat_ro(f"RO {qb1n}", operation_dict)
s.repeat_ro(f"RO {qb2n}", operation_dict)
if upload:
ps.Pulsar.get_instance().program_awgs(sequences[0])
return sequences, np.arange(sequences[0].n_acq_elements()), \
np.arange(len(cliffords))
def n_qubit_simultaneous_randomized_benchmarking_seq(qubit_names_list,
operation_dict,
nr_cliffords_value, #scalar
nr_seeds, #array
net_clifford=0,
gate_decomposition='HZ',
interleaved_gate=None,
cal_points=False,
upload=True,
upload_all=True,
seq_name=None,
verbose=False,
return_seq=False):
"""
Args:
qubit_list (list): list of qubit names to perform RB on
operation_dict (dict): operation dictionary for all qubits
nr_cliffords_value (int): number of Cliffords in the sequence
nr_seeds (numpy.ndarray): numpy.arange(nr_seeds_int) where nr_seeds_int
is the number of times to repeat each Clifford sequence of
length nr_cliffords_value
net_clifford (int): 0 or 1; refers to the final state after the recovery
Clifford has been applied. 0->gnd state, 1->exc state.
gate_decomposition (str): 'HZ' or 'XY'
interleaved_gate (str): used for regular single qubit Clifford IRB
string referring to one of the gates in the single qubit
Clifford group
cal_points (bool): whether to use cal points
upload (bool): upload sequence to AWG or not
upload_all (bool): whether to upload to all AWGs
seq_name (str): name of this sequences
verbose (bool): print runtime info
return_seq (bool): if True, returns seq, element list;
if False, returns only seq_name
"""
raise NotImplementedError(
'n_qubit_simultaneous_randomized_benchmarking_seq has not been '
'converted to the latest waveform generation code and can not be used.')
# get number of qubits
n = len(qubit_names_list)
for qb_nr, qb_name in enumerate(qubit_names_list):
operation_dict['Z0 ' + qb_name] = \
deepcopy(operation_dict['Z180 ' + qb_name])
operation_dict['Z0 ' + qb_name]['basis_rotation'][qb_name] = 0
if seq_name is None:
seq_name = 'SRB_sequence'
seq = sequence.Sequence(seq_name)
el_list = []
if upload_all:
upload_AWGs = 'all'
else:
upload_AWGs = ['AWG1']
for qbn in qubit_names_list:
X90_pulse = deepcopy(operation_dict['X90 ' + qbn])
upload_AWGs += [station.pulsar.get(X90_pulse['I_channel'] + '_AWG'),
station.pulsar.get(X90_pulse['Q_channel'] + '_AWG')]
upload_AWGs = list(set(upload_AWGs))
for elt_idx, i in enumerate(nr_seeds):
if cal_points and (elt_idx == (len(nr_seeds)-2)):
pulse_keys = n*['I']
pulse_keys_w_suffix = []
for k, pk in enumerate(pulse_keys):
pk_name = pk if k == 0 else pk+'s'
pulse_keys_w_suffix.append(pk_name+' '+qubit_names_list[k % n])
pulse_list = []
for pkws in pulse_keys_w_suffix:
pulse_list.append(operation_dict[pkws])
elif cal_points and (elt_idx == (len(nr_seeds)-1)):
pulse_keys = n*['X180']
pulse_keys_w_suffix = []
for k, pk in enumerate(pulse_keys):
pk_name = pk if k == 0 else pk+'s'
pulse_keys_w_suffix.append(pk_name+' '+qubit_names_list[k % n])
pulse_list = []
for pkws in pulse_keys_w_suffix:
pulse_list.append(operation_dict[pkws])
else:
# if clifford_sequence_list is None:
clifford_sequence_list = []
for index in range(n):
clifford_sequence_list.append(
rb.randomized_benchmarking_sequence(
nr_cliffords_value, desired_net_cl=net_clifford,
interleaved_gate=interleaved_gate))
pulse_keys = rb.decompose_clifford_seq_n_qubits(
clifford_sequence_list,
gate_decomp=gate_decomposition)
# interleave pulses for each qubit to obtain [pulse0_qb0,
# pulse0_qb1,..pulse0_qbN,..,pulseN_qb0, pulseN_qb1,..,pulseN_qbN]
pulse_keys_w_suffix = []
for k, lst in enumerate(pulse_keys):
pulse_keys_w_suffix.append([x+' '+qubit_names_list[k % n]
for x in lst])
pulse_keys_by_qubit = []
for k in range(n):
pulse_keys_by_qubit.append([x for l in pulse_keys_w_suffix[k::n]
for x in l])
# # make all qb sequences the same length
# max_len = 0
# for pl in pulse_keys_by_qubit:
# if len(pl) > max_len:
# max_len = len(pl)
# for ii, pl in enumerate(pulse_keys_by_qubit):
# if len(pl) < max_len:
# pl += (max_len-len(pl))*['I ' + qubit_names_list[ii]]
pulse_list = []
max_len = max([len(pl) for pl in pulse_keys_by_qubit])
for j in range(max_len):
for k in range(n):
if j < len(pulse_keys_by_qubit[k]):
pulse_list.append(deepcopy(operation_dict[
pulse_keys_by_qubit[k][j]]))
# Make the correct pulses simultaneous
for p in pulse_list:
p['refpoint'] = 'end'
a = [iii for iii in pulse_list if
iii['pulse_type'] == 'SSB_DRAG_pulse']
a[0]['refpoint'] = 'end'
refpoint = [a[0]['target_qubit']]
for p in a[1:]:
if p['target_qubit'] not in refpoint:
p['refpoint'] = 'start'
refpoint.append(p['target_qubit'])
else:
p['refpoint'] = 'end'
refpoint = [p['target_qubit']]
# add RO pulse pars at the end
pulse_list += [operation_dict['RO mux']]
el = multi_pulse_elt(elt_idx, station, pulse_list)
el_list.append(el)
seq.append_element(el, trigger_wait=True)
if upload:
station.pulsar.program_awgs(seq, *el_list,
AWGs=upload_AWGs,
channels='all',
verbose=verbose)
if return_seq:
return seq, el_list
else:
return seq_name
def n_qubit_reset(qb_names, operation_dict, prep_params=dict(), upload=True,
states=('g','e',)):
"""
:param qb_names: list of qb_names to perform simultaneous reset upon
:param states (tuple): ('g','e',) for active reset e, ('g','f',) for active
reset f and ('g', 'e', 'f') for both.
:param prep_params (dict): preparation parameters. Note: should be
multi_qb_preparation_params, ie. threshold mapping should be of the
form: {qbi: thresh_map_qbi for qbi in qb_names}
:return:
"""
seq_name = '{}_reset_x{}_sequence'.format(qb_names,
prep_params.get('reset_reps',
'_default_n_reps'))
pulses = generate_mux_ro_pulse_list(qb_names, operation_dict)
reset_and_last_ro_pulses = \
add_preparation_pulses(pulses, operation_dict, qb_names, **prep_params)
swept_pulses = []
state_ops = dict(g=['I '], e=['X180 '], f=['X180 ', 'X180_ef '])
for s in states:
pulses = deepcopy(reset_and_last_ro_pulses)
state_pulses = []
segment_pulses = []
# generate one sub list for each qubit, with qb pulse naming
for qbn in qb_names:
qb_state_pulses = [deepcopy(operation_dict[op + qbn]) for op in
state_ops[s]]
for op, p in zip(state_ops[s], qb_state_pulses):
p['name'] = op + qbn
state_pulses += [qb_state_pulses]
# reference end of state pulse to start of first reset pulse,
# to effectively prepend the state pulse
for qb_state_pulses in state_pulses:
segment_pulses += prepend_pulses(pulses, qb_state_pulses)[
:len(qb_state_pulses)]
swept_pulses.append(segment_pulses + pulses)
seq = pulse_list_list_seq(swept_pulses, seq_name, upload=False)
# reuse sequencer memory by repeating readout pattern
# 1. get all readout pulse names (if they are on different uhf,
# they will be applied to different channels)
ro_pulse_names = [f"RO {qbn}" for qbn in qb_names]
# 2. repeat readout for each ro_pulse.
[seq.repeat_ro(pn, operation_dict) for pn in ro_pulse_names]
log.debug(seq)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
def parity_correction_seq(
qb1n, qb2n, qb3n, operation_dict, CZ_pulses, feedback_delay=900e-9,
prep_sequence=None, reset=True, nr_parity_measurements=1,
tomography_basis=tomo.DEFAULT_BASIS_ROTS,
parity_op='ZZ', upload=True, verbose=False, return_seq=False,
preselection=False, ro_spacing=1e-6, dd_scheme=None, nr_dd_pulses=4,
skip_n_initial_parity_checks=0, skip_elem='RO'):
"""
| elem 1 | elem 2 | (elem 3, 2) | elem 4
|q0> |======|---------*--------------------------( )-|======|
| prep | | ( repeat )| tomo |
|q1> | q0, |--mY90s--*--*--Y90--meas=Y180------( parity )| q0, |
| q2 | | || ( measurement )| q2 |
|q2> |======|------------*------------Y180-------( )-|======|
required elements:
elem_1:
contains everything up to the first readout including preparation
and first parity measurement
elem_2 (x2):
contains conditional Y180 on q1 and q2
elem_3:
additional parity measurements
elem_4 (x6**2):
tomography rotations for q0 and q2
Args:
parity_op: 'ZZ', 'XX', 'XX,ZZ' or 'ZZ,XX' specifies the type of parity
measurement
"""
raise NotImplementedError(
'parity_correction_seq has not been '
'converted to the latest waveform generation code and can not be used.')
if parity_op not in ['ZZ', 'XX', 'XX,ZZ', 'ZZ,XX']:
raise ValueError("Invalid parity operator '{}'".format(parity_op))
operation_dict['RO mux_presel'] = operation_dict['RO mux'].copy()
operation_dict['RO mux_presel']['pulse_delay'] = \
-ro_spacing - feedback_delay - operation_dict['RO mux']['length']
operation_dict['RO mux_presel']['refpoint'] = 'end'
operation_dict['RO mux_presel'].pop('basis_rotation', {})
operation_dict['RO presel_dummy'] = {
'pulse_type': 'SquarePulse',
'channel': operation_dict['RO mux']['acq_marker_channel'],
'amplitude': 0.0,
'length': ro_spacing + feedback_delay,
'pulse_delay': 0}
operation_dict['I rr_decay'] = {
'pulse_type': 'SquarePulse',
'channel': operation_dict['RO mux']['acq_marker_channel'],
'amplitude': 0.0,
'length': 400e-9,
'pulse_delay': 0}
operation_dict['RO skip'] = {
'pulse_type': 'SquarePulse',
'channel': operation_dict['RO mux']['acq_marker_channel'],
'amplitude': 0.0,
'length': operation_dict['RO mux']['length'],
'pulse_delay': 0
}
operation_dict['CZ1 skip'] = operation_dict[CZ_pulses[0]].copy()
operation_dict['CZ1 skip']['amplitude'] = 0
operation_dict['CZ2 skip'] = operation_dict[CZ_pulses[1]].copy()
operation_dict['CZ2 skip']['amplitude'] = 0
if dd_scheme is None:
dd_pulses = [{
'pulse_type': 'SquarePulse',
'channel': operation_dict['RO mux']['acq_marker_channel'],
'amplitude': 0.0,
'length': feedback_delay,
'pulse_delay': 0}]
else:
dd_pulses = get_dd_pulse_list(
operation_dict,
# [qb2n],
[qb1n, qb3n],
feedback_delay,
nr_pulses=nr_dd_pulses,
dd_scheme=dd_scheme,
init_buffer=0)
if prep_sequence is None:
if parity_op[0] == 'X':
prep_sequence = []
else:
prep_sequence = ['Y90 ' + qb1n, 'Y90s ' + qb3n]
elif prep_sequence == 'mixed':
prep_sequence = ['Y90 ' + qb1n, 'Y90s ' + qb3n, 'RO mux', 'I rr_decay']
xx_sequence_first = ['Y90 ' + qb1n, 'mY90s ' + qb2n, 'Y90s ' + qb3n,
CZ_pulses[0],
CZ_pulses[1],
# 'mY90 ' + qb1n,
'Y90 ' + qb2n,
'RO ' + qb2n]
xx_sequence_after_z = deepcopy(xx_sequence_first)
xx_sequence_after_x = ['mY90 ' + qb2n,
CZ_pulses[0],
CZ_pulses[1],
# 'mY90 ' + qb1n,
'Y90 ' + qb2n,
'RO ' + qb2n]
zz_sequence_first = ['mY90 ' + qb2n,
CZ_pulses[0],
CZ_pulses[1],
'Y90 ' + qb2n,
'RO ' + qb2n]
zz_sequence_after_z = deepcopy(zz_sequence_first)
zz_sequence_after_x = ['mY90 ' + qb2n, 'mY90s ' + qb3n, 'mY90s ' + qb1n,
CZ_pulses[0],
CZ_pulses[1],
'Y90 ' + qb2n,
'RO ' + qb2n]
pretomo_after_z = []
pretomo_after_x = ['mY90 ' + qb3n, 'mY90s ' + qb1n,]
# create the elements
el_list = []
# first element
if parity_op in ['XX', 'XX,ZZ']:
op_sequence = prep_sequence + xx_sequence_first
else:
op_sequence = prep_sequence + zz_sequence_first
def skip_parity_check(op_sequence, skip_elem, CZ_pulses, qb2n):
if skip_elem == 'RO':
op_sequence = ['RO skip' if op == ('RO ' + qb2n) else op
for op in op_sequence]
if skip_elem == 'CZ D1' or skip_elem == 'CZ both':
op_sequence = ['CZ1 skip' if op == CZ_pulses[0] else op
for op in op_sequence]
if skip_elem == 'CZ D2' or skip_elem == 'CZ both':
op_sequence = ['CZ2 skip' if op == CZ_pulses[1] else op
for op in op_sequence]
return op_sequence
if skip_n_initial_parity_checks > 0:
op_sequence = skip_parity_check(op_sequence, skip_elem, CZ_pulses, qb2n)
pulse_list = [operation_dict[pulse] for pulse in op_sequence]
pulse_list += dd_pulses
if preselection:
pulse_list.append(operation_dict['RO mux_presel'])
# RO presel dummy is referenced to end of RO mux presel => it happens
# before the preparation pulses!
pulse_list.append(operation_dict['RO presel_dummy'])
el_main = multi_pulse_elt(0, station, pulse_list, trigger=True,
name='m')
el_list.append(el_main)
# feedback elements
fb_sequence_0 = ['I ' + qb3n, 'Is ' + qb2n]
fb_sequence_1 = ['X180 ' + qb3n] if reset else ['I ' + qb3n]
fb_sequence_1 += ['X180s ' + qb2n]# if reset else ['Is ' + qb2n]
pulse_list = [operation_dict[pulse] for pulse in fb_sequence_0]
el_list.append(multi_pulse_elt(0, station, pulse_list, name='f0',
trigger=False, previous_element=el_main))
pulse_list = [operation_dict[pulse] for pulse in fb_sequence_1]
el_fb = multi_pulse_elt(1, station, pulse_list, name='f1',
trigger=False, previous_element=el_main)
el_list.append(el_fb)
# repeated parity measurement element(s). Phase errors need to be corrected
# for by careful selection of qubit drive IF-s.
if parity_op == 'ZZ':
pulse_list = [operation_dict[pulse] for pulse in zz_sequence_after_z]
pulse_list += dd_pulses
el_repeat = multi_pulse_elt(0, station, pulse_list, trigger=False,
name='rz', previous_element=el_fb)
el_list.append(el_repeat)
elif parity_op == 'XX':
pulse_list = [operation_dict[pulse] for pulse in xx_sequence_after_x]
pulse_list += dd_pulses
el_repeat = multi_pulse_elt(0, station, pulse_list, trigger=False,
name='rx', previous_element=el_fb)
el_list.append(el_repeat)
elif parity_op == 'ZZ,XX':
pulse_list = [operation_dict[pulse] for pulse in xx_sequence_after_z]
pulse_list += dd_pulses
el_repeat_x = multi_pulse_elt(0, station, pulse_list, trigger=False,
name='rx', previous_element=el_fb)
el_list.append(el_repeat_x)
pulse_list = [operation_dict[pulse] for pulse in zz_sequence_after_x]
pulse_list += dd_pulses
el_repeat_z = multi_pulse_elt(1, station, pulse_list, trigger=False,
name='rz', previous_element=el_fb)
el_list.append(el_repeat_z)
elif parity_op == 'XX,ZZ':
pulse_list = [operation_dict[pulse] for pulse in zz_sequence_after_x]
pulse_list += dd_pulses
el_repeat_z = multi_pulse_elt(0, station, pulse_list, trigger=False,
name='rz', previous_element=el_fb)
el_list.append(el_repeat_z)
pulse_list = [operation_dict[pulse] for pulse in xx_sequence_after_z]
pulse_list += dd_pulses
el_repeat_x = multi_pulse_elt(1, station, pulse_list, trigger=False,
name='rx', previous_element=el_fb)
el_list.append(el_repeat_x)
# repeated parity measurement element(s) with skipped parity check.
if skip_n_initial_parity_checks > 1:
if parity_op == 'ZZ':
op_sequence = skip_parity_check(zz_sequence_after_z,
skip_elem, CZ_pulses, qb2n)
pulse_list = [operation_dict[pulse] for pulse in op_sequence]
pulse_list += dd_pulses
el_repeat_skip = multi_pulse_elt(0, station, pulse_list,
trigger=False, name='rzs',
previous_element=el_fb)
el_list.append(el_repeat_skip)
elif parity_op == 'XX':
op_sequence = skip_parity_check(xx_sequence_after_x,
skip_elem, CZ_pulses, qb2n)
pulse_list = [operation_dict[pulse] for pulse in op_sequence]
pulse_list += dd_pulses
el_repeat_skip = multi_pulse_elt(0, station, pulse_list,
trigger=False, name='rxs',
previous_element=el_fb)
el_list.append(el_repeat_skip)
elif parity_op == 'ZZ,XX':
op_sequence = skip_parity_check(xx_sequence_after_z,
skip_elem, CZ_pulses, qb2n)
pulse_list = [operation_dict[pulse] for pulse in op_sequence]
pulse_list += dd_pulses
el_repeat_x_skip = multi_pulse_elt(0, station, pulse_list,
trigger=False, name='rxs',
previous_element=el_fb)
el_list.append(el_repeat_x_skip)
op_sequence = skip_parity_check(zz_sequence_after_x,
skip_elem, CZ_pulses, qb2n)
pulse_list = [operation_dict[pulse] for pulse in op_sequence]
pulse_list += dd_pulses
el_repeat_z_skip = multi_pulse_elt(0, station, pulse_list,
trigger=False, name='rzs',
previous_element=el_fb)
el_list.append(el_repeat_z_skip)
elif parity_op == 'XX,ZZ':
op_sequence = skip_parity_check(zz_sequence_after_x,
skip_elem, CZ_pulses, qb2n)
pulse_list = [operation_dict[pulse] for pulse in op_sequence]
pulse_list += dd_pulses
el_repeat_z_skip = multi_pulse_elt(0, station, pulse_list,
trigger=False, name='rzs',
previous_element=el_fb)
el_list.append(el_repeat_z_skip)
op_sequence = skip_parity_check(xx_sequence_after_z,
skip_elem, CZ_pulses, qb2n)
pulse_list = [operation_dict[pulse] for pulse in op_sequence]
pulse_list += dd_pulses
el_repeat_x_skip = multi_pulse_elt(0, station, pulse_list,
trigger=False, name='rxs',
previous_element=el_fb)
el_list.append(el_repeat_x_skip)
# check that the qubits do not acquire any phase over one round of parity
# correction
for qbn in [qb1n, qb2n, qb3n]:
ifreq = operation_dict['X180 ' + qbn]['mod_frequency']
if parity_op in ['XX', 'ZZ']:
elements_length = el_fb.ideal_length() + el_repeat.ideal_length()
dynamic_phase = el_repeat.drive_phase_offsets.get(qbn, 0)
else:
elements_length = el_fb.ideal_length() + el_repeat_x.ideal_length()
dynamic_phase = el_repeat_x.drive_phase_offsets.get(qbn, 0)
log.info('Length difference of XX and ZZ cycles: {} s'.format(
el_repeat_x.ideal_length() - el_repeat_z.ideal_length()
))
dynamic_phase -= el_main.drive_phase_offsets.get(qbn, 0)
phase_from_if = 360*ifreq*elements_length
total_phase = phase_from_if + dynamic_phase
total_mod_phase = (total_phase + 180) % 360 - 180
log.info(qbn + ' aquires a phase of {} ≡ {} (mod 360)'.format(
total_phase, total_mod_phase) + ' degrees each correction ' +
'cycle. You should reduce the intermediate frequency by {} Hz.'\
.format(total_mod_phase/elements_length/360))
# tomography elements
if parity_op in ['XX', ['XX,ZZ', 'ZZ,XX'][nr_parity_measurements % 2]]:
pretomo = pretomo_after_x
else:
pretomo = pretomo_after_z
tomography_sequences = get_tomography_pulses(qb1n, qb3n,
basis_pulses=tomography_basis)
for i, tomography_sequence in enumerate(tomography_sequences):
pulse_list = [operation_dict[pulse] for pulse in
pretomo + tomography_sequence + ['RO mux']]
el_list.append(multi_pulse_elt(i, station, pulse_list, trigger=False,
name='t{}'.format(i),
previous_element=el_fb))
# create the sequence
seq_name = 'Two qubit entanglement by parity measurement'
seq = sequence.Sequence(seq_name)
seq.codewords[0] = 'f0'
seq.codewords[1] = 'f1'
for i in range(len(tomography_basis)**2):
seq.append('m_{}'.format(i), 'm', trigger_wait=True)
seq.append('f_{}_0'.format(i), 'codeword', trigger_wait=False)
for j in range(1, nr_parity_measurements):
if parity_op in ['XX', ['XX,ZZ', 'ZZ,XX'][j % 2]]:
el_name = 'rx'
else:
el_name = 'rz'
if j < skip_n_initial_parity_checks:
el_name += 's'
seq.append('r_{}_{}'.format(i, j), el_name,
trigger_wait=False)
seq.append('f_{}_{}'.format(i, j), 'codeword',
trigger_wait=False)
seq.append('t_{}'.format(i), 't{}'.format(i),
trigger_wait=False)
if upload:
station.pulsar.program_awgs(seq, *el_list, verbose=verbose)
if return_seq:
return seq, el_list
else:
return seq_name
def parity_correction_no_reset_seq(
q0n, q1n, q2n, operation_dict, CZ_pulses, feedback_delay=900e-9,
prep_sequence=None, ro_spacing=1e-6, dd_scheme=None, nr_dd_pulses=0,
tomography_basis=tomo.DEFAULT_BASIS_ROTS,
upload=True, verbose=False, return_seq=False, preselection=False):
"""
| elem 1 | elem 2 | elem 3
|q0> |======|---------*------------------------|======|
| prep | | | tomo |
|q1> | q0, |--mY90s--*--*--Y90--meas===-------| q0, |
| q2 | | || | q2 |
|q2> |======|------------*------------X180-----|======|
required elements:
prep_sequence:
contains everything up to the first readout
Echo decoupling elements
contains nr_echo_pulses X180 equally-spaced pulses on q0n, q2n
FOR THIS TO WORK, ALL QUBITS MUST HAVE THE SAME PI-PULSE LENGTH
feedback x 2 (for the two readout results):
contains conditional Y80 on q1 and q2
tomography x 6**2:
measure all observables of the two qubits X/Y/Z
"""
raise NotImplementedError(
'parity_correction_no_reset_seq has not been '
'converted to the latest waveform generation code and can not be used.')
operation_dict['RO mux_presel'] = operation_dict['RO mux'].copy()
operation_dict['RO mux_presel']['pulse_delay'] = \
-ro_spacing - feedback_delay - operation_dict['RO mux']['length']
operation_dict['RO mux_presel']['refpoint'] = 'end'
operation_dict['RO presel_dummy'] = {
'pulse_type': 'SquarePulse',
'channel': operation_dict['RO mux']['acq_marker_channel'],
'amplitude': 0.0,
'length': ro_spacing+feedback_delay,
'pulse_delay': 0}
if dd_scheme is None:
dd_pulses = [{
'pulse_type': 'SquarePulse',
'channel': operation_dict['RO mux']['acq_marker_channel'],
'amplitude': 0.0,
'length': feedback_delay,
'pulse_delay': 0}]
else:
dd_pulses = get_dd_pulse_list(
operation_dict,
# [qb2n],
[q0n, q2n],
feedback_delay,
nr_pulses=nr_dd_pulses,
dd_scheme=dd_scheme,
init_buffer=0)
if prep_sequence is None:
prep_sequence = ['Y90 ' + q0n, 'Y90s ' + q2n,
'mY90 ' + q1n,
CZ_pulses[0], CZ_pulses[1],
'Y90 ' + q1n,
'RO ' + q1n]
pulse_list = [operation_dict[pulse] for pulse in prep_sequence] + dd_pulses
if preselection:
pulse_list.append(operation_dict['RO mux_presel'])
# RO presel dummy is referenced to end of RO mux presel => it happens
# before the preparation pulses!
pulse_list.append(operation_dict['RO presel_dummy'])
idle_length = operation_dict['X180 ' + q1n]['sigma']
idle_length *= operation_dict['X180 ' + q1n]['nr_sigma']
idle_length += 2*8/2.4e9
idle_pulse = {
'pulse_type': 'SquarePulse',
'channel': operation_dict['RO mux']['acq_marker_channel'],
'amplitude': 0.0,
'length': idle_length,
'pulse_delay': 0}
pulse_list.append(idle_pulse)
# tomography elements
tomography_sequences = get_tomography_pulses(q0n, q2n,
basis_pulses=tomography_basis)
# create the elements
el_list = []
for i, tomography_sequence in enumerate(tomography_sequences):
tomography_sequence.append('RO mux')
pulse_list_tomo = deepcopy(pulse_list) + \
[operation_dict[pulse] for pulse in
tomography_sequence]
el_list.append(multi_pulse_elt(i, station, pulse_list_tomo,
trigger=True,
name='tomography_{}'.format(i)))
# create the sequence
seq_name = 'Two qubit entanglement by parity measurement'
seq = sequence.Sequence(seq_name)
# for i in range(len(tomography_basis)**2):
for i, tomography_sequence in enumerate(tomography_sequences):
seq.append('tomography_{}'.format(i), 'tomography_{}'.format(i),
trigger_wait=True)
if upload:
station.pulsar.program_awgs(seq, *el_list, verbose=verbose)
if return_seq:
return seq, el_list
else:
return seq_name
def parity_single_round_seq(ancilla_qubit_name, data_qubit_names, CZ_map,
preps, cal_points, prep_params, operation_dict,
upload=True):
seq_name = 'Parity_1_round_sequence'
qb_names = [ancilla_qubit_name] + data_qubit_names
main_ops = ['Y90 ' + ancilla_qubit_name]
for i, dqn in enumerate(data_qubit_names):
op = 'CZ ' + ancilla_qubit_name + ' ' + dqn
main_ops += CZ_map.get(op, [op])
if i == len(data_qubit_names)/2 - 1:
main_ops += ['Y180 ' + ancilla_qubit_name]
# for dqnecho in enumerate(data_qubit_names):
# # main_ops += ['Y180s ' + dqnecho]
# if len(data_qubit_names)%2 == 0:
main_ops += ['Y90 ' + ancilla_qubit_name]
# else:
# main_ops += ['mY90 ' + ancilla_qubit_name]
all_opss = []
for prep in preps:
prep_ops = [{'g': 'I ', 'e': 'X180 ', '+': 'Y90 ', '-': 'mY90 '}[s] \
+ dqn for s, dqn in zip(prep, data_qubit_names)]
end_ops = [{'g': 'I ', 'e': 'I ', '+': 'Y90 ', '-': 'Y90 '}[s] \
+ dqn for s, dqn in zip(prep, data_qubit_names)]
all_opss.append(prep_ops + main_ops + end_ops)
all_pulsess = []
for all_ops, prep in zip(all_opss, preps):
all_pulses = []
for i, op in enumerate(all_ops):
all_pulses.append(deepcopy(operation_dict[op]))
# if i == 0:
# all_pulses[-1]['ref_pulse'] = 'segment_start'
# elif 0 < i <= len(data_qubit_names):
# all_pulses[-1]['ref_point'] = 'start'
if 'CZ' not in op:
all_pulses[-1]['element_name'] = f'drive_{prep}'
else:
all_pulses[-1]['element_name'] = f'flux_{prep}'
all_pulses += generate_mux_ro_pulse_list(qb_names, operation_dict)
all_pulsess.append(all_pulses)
# all_pulsess_with_prep = \
# [add_preparation_pulses(seg, operation_dict, qb_names, **prep_params)
# for seg in all_pulsess]
all_pulsess_with_prep = all_pulsess
seq = pulse_list_list_seq(all_pulsess_with_prep, seq_name, upload=False)
# add calibration segments
if cal_points is not None:
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
[seq.repeat_ro(f"RO {qbn}", operation_dict) for qbn in qb_names]
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
def parity_single_round__phases_seq(ancilla_qubit_name, data_qubit_names, CZ_map,
phases, prep_anc,
cal_points, prep_params,
operation_dict,
upload=True):
seq_name = 'Parity_1_round_sequence'
qb_names = [ancilla_qubit_name] + data_qubit_names
if prep_anc=='e':
main_ops = ['Y180 ' + ancilla_qubit_name]
else:
main_ops = ['I ' + ancilla_qubit_name]
for i, dqn in enumerate(data_qubit_names):
op = 'CZ ' + ancilla_qubit_name + ' ' + dqn
main_ops += CZ_map.get(op, [op])
if i == len(data_qubit_names)/2 - 1:
main_ops += ['Y180 ' + ancilla_qubit_name]
prep_ops = ['Y90' + (' ' if i==0 else 's ') + dqn for i,dqn in
enumerate(data_qubit_names)]
end_ops = ['mY90' + (' ' if i==0 else 's ') + dqn for i,dqn in
enumerate(data_qubit_names)]
all_pulsess = []
for n, phase in enumerate(phases):
all_pulses = []
for i, op in enumerate(prep_ops+main_ops):
all_pulses.append(deepcopy(operation_dict[op]))
if 'CZ' not in op:
all_pulses[-1]['element_name'] = f'drive_{n}'
else:
all_pulses[-1]['element_name'] = f'flux_{n}'
for i, op in enumerate(end_ops):
all_pulses.append(deepcopy(operation_dict[op]))
all_pulses[-1]['element_name'] = f'drive_{n}'
all_pulses[-1]['phase'] = phase/np.pi*180
all_pulses += generate_mux_ro_pulse_list(qb_names, operation_dict)
all_pulsess.append(all_pulses)
all_pulsess_with_prep = \
[add_preparation_pulses(seg, operation_dict, qb_names, **prep_params)
for seg in all_pulsess]
seq = pulse_list_list_seq(all_pulsess_with_prep, seq_name, upload=False)
# add calibration segments
if cal_points is not None:
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
def n_qubit_tomo_seq(
qubit_names, operation_dict, prep_sequence=None,
prep_name=None,
rots_basis=tomo.DEFAULT_BASIS_ROTS,
upload=True, return_seq=False,
preselection=False, ro_spacing=1e-6):
"""
"""
# create the sequence
if prep_name is None:
seq_name = 'N-qubit tomography'
else:
seq_name = prep_name + ' tomography'
seq = sequence.Sequence(seq_name)
seg_list = []
if prep_sequence is None:
prep_sequence = ['Y90 ' + qubit_names[0]]
# tomography elements
tomography_sequences = get_tomography_pulses(*qubit_names,
basis_pulses=rots_basis)
for i, tomography_sequence in enumerate(tomography_sequences):
pulse_list = [operation_dict[pulse] for pulse in prep_sequence]
# tomography_sequence.append('RO mux')
# if preselection:
# tomography_sequence.append('RO mux_presel')
# tomography_sequence.append('RO presel_dummy')
pulse_list.extend([operation_dict[pulse] for pulse in
tomography_sequence])
ro_pulses = generate_mux_ro_pulse_list(qubit_names, operation_dict)
pulse_list.extend(ro_pulses)
if preselection:
ro_pulses_presel = generate_mux_ro_pulse_list(
qubit_names, operation_dict, 'RO_presel', 'start', -ro_spacing)
pulse_list.extend(ro_pulses_presel)
seg = segment.Segment('tomography_{}'.format(i), pulse_list)
seg_list.append(seg)
seq.add(seg)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
if return_seq:
return seq, seg_list
else:
return seq_name
def get_tomography_pulses(*qubit_names, basis_pulses=('I', 'X180', 'Y90',
'mY90', 'X90', 'mX90')):
tomo_sequences = [[]]
for i, qb in enumerate(qubit_names):
if i == 0:
qb = ' ' + qb
else:
qb = 's ' + qb
tomo_sequences_new = []
for sequence in tomo_sequences:
for pulse in basis_pulses:
tomo_sequences_new.append(sequence + [pulse+qb])
tomo_sequences = tomo_sequences_new
return tomo_sequences
def get_decoupling_pulses(*qubit_names, nr_pulses=4):
if nr_pulses % 2 != 0:
logging.warning('Odd number of dynamical decoupling pulses')
echo_sequences = []
for pulse in nr_pulses*['X180']:
for i, qb in enumerate(qubit_names):
if i == 0:
qb = ' ' + qb
else:
qb = 's ' + qb
echo_sequences.append(pulse+qb)
return echo_sequences
def n_qubit_ref_seq(qubit_names, operation_dict, ref_desc, upload=True,
return_seq=False, preselection=False, ro_spacing=1e-6):
"""
Calibration points for arbitrary combinations
Arguments:
qubits: List of calibrated qubits for obtaining the pulse
dictionaries.
ref_desc: Description of the calibration sequence. Dictionary
name of the state as key, and list of pulses names as values.
"""
# create the elements
seq_name = 'Calibration'
seq = sequence.Sequence(seq_name)
seg_list = []
# calibration elements
# calibration_sequences = []
# for pulses in ref_desc:
# calibration_sequences.append(
# [pulse+' '+qb for qb, pulse in zip(qubit_names, pulses)])
calibration_sequences = []
for pulses in ref_desc:
calibration_sequence_new = []
for i, pulse in enumerate(pulses):
if i == 0:
qb = ' ' + qubit_names[i]
else:
qb = 's ' + qubit_names[i]
calibration_sequence_new.append(pulse+qb)
calibration_sequences.append(calibration_sequence_new)
for i, calibration_sequence in enumerate(calibration_sequences):
pulse_list = []
pulse_list.extend(
[operation_dict[pulse] for pulse in calibration_sequence])
ro_pulses = generate_mux_ro_pulse_list(qubit_names, operation_dict)
pulse_list.extend(ro_pulses)
if preselection:
ro_pulses_presel = generate_mux_ro_pulse_list(
qubit_names, operation_dict, 'RO_presel', 'start', -ro_spacing)
pulse_list.extend(ro_pulses_presel)
seg = segment.Segment('calibration_{}'.format(i), pulse_list)
seg_list.append(seg)
seq.add(seg)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
if return_seq:
return seq, seg_list
else:
return seq_name
def n_qubit_ref_all_seq(qubit_names, operation_dict, upload=True,
return_seq=False, preselection=False, ro_spacing=1e-6):
"""
Calibration points for all combinations
"""
return n_qubit_ref_seq(qubit_names, operation_dict,
ref_desc=itertools.product(["I", "X180"],
repeat=len(qubit_names)),
upload=upload, return_seq=return_seq,
preselection=preselection, ro_spacing=ro_spacing)
def Ramsey_add_pulse_seq(times, measured_qubit_name,
pulsed_qubit_name, operation_dict,
artificial_detuning=None,
cal_points=True,
verbose=False,
upload=True, return_seq=False):
raise NotImplementedError(
'Ramsey_add_pulse_seq has not been '
'converted to the latest waveform generation code and can not be used.')
if np.any(times > 1e-3):
logging.warning('The values in the times array might be too large.'
'The units should be seconds.')
seq_name = 'Ramsey_with_additional_pulse_sequence'
seq = sequence.Sequence(seq_name)
el_list = []
pulse_pars_x1 = deepcopy(operation_dict['X90 ' + measured_qubit_name])
pulse_pars_x1['refpoint'] = 'end'
pulse_pars_x2 = deepcopy(pulse_pars_x1)
pulse_pars_x2['refpoint'] = 'start'
RO_pars = operation_dict['RO ' + measured_qubit_name]
add_pulse_pars = deepcopy(operation_dict['X180 ' + pulsed_qubit_name])
for i, tau in enumerate(times):
if cal_points and (i == (len(times)-4) or i == (len(times)-3)):
el = multi_pulse_elt(i, station, [
operation_dict['I ' + measured_qubit_name], RO_pars])
elif cal_points and (i == (len(times)-2) or i == (len(times)-1)):
el = multi_pulse_elt(i, station, [
operation_dict['X180 ' + measured_qubit_name], RO_pars])
else:
pulse_pars_x2['pulse_delay'] = tau
if artificial_detuning is not None:
Dphase = ((tau-times[0]) * artificial_detuning * 360) % 360
pulse_pars_x2['phase'] = Dphase
if i % 2 == 0:
el = multi_pulse_elt(
i, station, [operation_dict['X90 ' + measured_qubit_name],
pulse_pars_x2, RO_pars])
else:
el = multi_pulse_elt(i, station,
[add_pulse_pars, pulse_pars_x1,
# [pulse_pars_x1, add_pulse_pars,
pulse_pars_x2, RO_pars])
el_list.append(el)
seq.append_element(el, trigger_wait=True)
if upload:
station.pulsar.program_awgs(seq, *el_list, verbose=verbose)
if return_seq:
return seq, el_list
else:
return seq_name
def ramsey_add_pulse_seq_active_reset(
times, measured_qubit_name, pulsed_qubit_name,
operation_dict, cal_points, n=1, artificial_detunings = 0,
upload=True, for_ef=False, last_ge_pulse=False, prep_params=dict()):
'''
Azz sequence: Ramsey on measured_qubit
pi-pulse on pulsed_qubit
Input pars:
times: array of delays (s)
n: number of pulses (1 is conventional Ramsey)
'''
seq_name = 'Ramsey_with_additional_pulse_sequence'
# Operations
if for_ef:
ramsey_ops_measured = ["X180"] + ["X90_ef"] * 2 * n
ramsey_ops_pulsed = ["X180"]
if last_ge_pulse:
ramsey_ops_measured += ["X180"]
else:
ramsey_ops_measured = ["X90"] * 2 * n
ramsey_ops_pulsed = ["X180"]
ramsey_ops_measured += ["RO"]
ramsey_ops_measured = add_suffix(ramsey_ops_measured, " " + measured_qubit_name)
ramsey_ops_pulsed = add_suffix(ramsey_ops_pulsed, " " + pulsed_qubit_name)
ramsey_ops_init = ramsey_ops_pulsed + ramsey_ops_measured
ramsey_ops_det = ramsey_ops_measured
# pulses
ramsey_pulses_init = [deepcopy(operation_dict[op]) for op in ramsey_ops_init]
ramsey_pulses_det = [deepcopy(operation_dict[op]) for op in ramsey_ops_det]
# name and reference swept pulse
for i in range(n):
idx = -2 #(2 if for_ef else 1) + i * 2 + 1
ramsey_pulses_init[idx]["name"] = f"Ramsey_x2_{i}"
ramsey_pulses_init[idx]['ref_point'] = 'start'
ramsey_pulses_det[idx]["name"] = f"Ramsey_x2_{i}"
ramsey_pulses_det[idx]['ref_point'] = 'start'
# compute dphase
a_d = artificial_detunings if np.ndim(artificial_detunings) == 1 \
else [artificial_detunings]
dphase = [((t - times[0]) * a_d[i % len(a_d)] * 360) % 360
for i, t in enumerate(times)]
# sweep pulses
params = {f'Ramsey_x2_{i}.pulse_delay': times for i in range(n)}
params.update({f'Ramsey_x2_{i}.phase': dphase for i in range(n)})
swept_pulses_init = sweep_pulse_params(ramsey_pulses_init, params)
swept_pulses_det = sweep_pulse_params(ramsey_pulses_det, params)
swept_pulses = np.ravel((swept_pulses_init,swept_pulses_det), order='F')
# add preparation pulses
swept_pulses_with_prep = \
[add_preparation_pulses(p, operation_dict,
[pulsed_qubit_name, measured_qubit_name],
**prep_params)
for p in swept_pulses]
seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)
# add calibration segments
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
# reuse sequencer memory by repeating readout pattern
seq.repeat_ro(f"RO {measured_qubit_name}", operation_dict)
log.debug(seq)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
def Ramsey_add_pulse_sweep_phase_seq(
phases, measured_qubit_name,
pulsed_qubit_name, operation_dict,
verbose=False,
upload=True, return_seq=False,
cal_points=True):
raise NotImplementedError(
'Ramsey_add_pulse_sweep_phase_seq has not been '
'converted to the latest waveform generation code and can not be used.')
seq_name = 'Ramsey_with_additional_pulse_sweep_phase_sequence'
seq = sequence.Sequence(seq_name)
el_list = []
X90_2 = deepcopy(operation_dict['X90 ' + measured_qubit_name])
for i, theta in enumerate(phases):
X90_2['phase'] = theta*180/np.pi
if cal_points and (theta == phases[-4] or theta == phases[-3]):
el = multi_pulse_elt(i, station,
[operation_dict['I ' + measured_qubit_name],
operation_dict['RO ' + measured_qubit_name]])
elif cal_points and (theta == phases[-2] or theta == phases[-1]):
el = multi_pulse_elt(i, station,
[operation_dict['X180 ' + measured_qubit_name],
operation_dict['RO ' + measured_qubit_name]])
else:
if i % 2 == 0:
el = multi_pulse_elt(
i, station, [operation_dict['X90 ' + measured_qubit_name],
X90_2,
operation_dict['RO ' + measured_qubit_name]])
else:
# X90_2['phase'] += 12
# VZ = deepcopy(operation_dict['Z180 '+measured_qubit_name])
# VZ['basis_rotation'][measured_qubit_name] = -12
el = multi_pulse_elt(
i, station, [operation_dict['X90 ' + measured_qubit_name],
operation_dict['X180s ' + pulsed_qubit_name],
# VZ,
X90_2,
operation_dict['RO ' + measured_qubit_name]])
el_list.append(el)
seq.append_element(el, trigger_wait=True)
if upload:
station.pulsar.program_awgs(seq, *el_list, verbose=verbose)
if return_seq:
return seq, el_list
else:
return seq_name
#### Multi-qubit time-domain
def general_multi_qubit_seq(
sweep_params,
sweep_points,
qb_names,
operation_dict, # of all qubits
qb_names_DD=None,
cal_points=True,
no_cal_points=4,
nr_echo_pulses=0,
idx_DD_start=-1,
UDD_scheme=True,
upload=True,
return_seq=False,
verbose=False):
"""
sweep_params = {
Pulse_type: (pulse_pars)
}
Ex:
# Rabi
sweep_params = (
('X180', {'pulse_pars': {'amplitude': (lambda sp: sp),
'repeat': 3}}), # for n-rabi; leave out if normal rabi
)
# Ramsey
sweep_params = (
('X90', {}),
('X90', {'pulse_pars': {'refpoint': 'start',
'pulse_delay': (lambda sp: sp),
'phase': (lambda sp:
( (sp-sweep_points[0]) *
art_det * 360) % 360)}}),
)
# T1
sweep_params = (
('X180', {}),
('RO_mux', {'pulse_pars': {'pulse_delay': (lambda sp: sp)}})
)
# Echo
sweep_params = (
('X90', {}),
('X180', {'pulse_pars': {'refpoint': 'start',
'pulse_delay': (lambda sp: sp/2)}}),
('X90', {'pulse_pars': {
'refpoint': 'start',
'pulse_delay': (lambda sp: sp/2),
'phase': (lambda sp:
((sp-sweep_points[0]) * artificial_detuning *
360) % 360)}})
)
# QScale
sweep_params = (
('X90', {'pulse_pars': {'motzoi': (lambda sp: sp)},
'condition': (lambda i: i%3==0)}),
('X180', {'pulse_pars': {'motzoi': (lambda sp: sp)},
'condition': (lambda i: i%3==0)}),
('X90', {'pulse_pars': {'motzoi': (lambda sp: sp)},
'condition': (lambda i: i%3==1)}),
('Y180', {'pulse_pars': {'motzoi': (lambda sp: sp)},
'condition': (lambda i: i%3==1)}),
('X90', {'pulse_pars': {'motzoi': (lambda sp: sp)},
'condition': (lambda i: i%3==2)}),
('mY180', {'pulse_pars': {'motzoi': (lambda sp: sp)},
'condition': (lambda i: i%3==2)}),
('RO', {})
)
"""
raise NotImplementedError(
'general_multi_qubit_seq has not been '
'converted to the latest waveform generation code and can not be used.')
seq_name = 'TD_sequence'
seq = sequence.Sequence(seq_name)
el_list = []
len_sweep_pts = len(sweep_points)
if (not isinstance(sweep_points, list) and
not isinstance(sweep_points, np.ndarray)):
if isinstance(sweep_points, dict):
len_sweep_pts = len(sweep_points[list(sweep_points)[0]])
assert (np.all([len_sweep_pts ==
len(sp) for sp in sweep_points.values()]))
else:
raise ValueError('Unrecognized type for "sweep_points".')
for i in np.arange(len_sweep_pts):
pulse_list = []
if cal_points and no_cal_points == 4 and \
(i == (len_sweep_pts-4) or i == (len_sweep_pts-3)):
for qb_name in qb_names:
qbn = ' ' + qb_name
if qb_name != qb_names[0]:
qbn = 's ' + qb_name
pulse_list += [operation_dict['I' + qbn]]
elif cal_points and no_cal_points == 4 and \
(i == (len_sweep_pts-2) or i == (len_sweep_pts-1)):
for qb_name in qb_names:
qbn = ' ' + qb_name
if qb_name != qb_names[0]:
qbn = 's ' + qb_name
pulse_list += [operation_dict['X180' + qbn]]
elif cal_points and no_cal_points == 2 and \
(i == (len_sweep_pts-2) or i == (len_sweep_pts-1)):
for qb_name in qb_names:
qbn = ' ' + qb_name
if qb_name != qb_names[0]:
qbn = 's ' + qb_name
pulse_list += [operation_dict['I' + qbn]]
else:
for sweep_tuple in sweep_params:
pulse_key = [x for x in sweep_tuple if isinstance(x, str)][0]
params_dict = [x for x in sweep_tuple if isinstance(x, dict)][0]
proceed = True
if 'condition' in params_dict:
if not params_dict['condition'](i):
proceed = False
if proceed:
if 'mux' in pulse_key:
pulse_pars_dict = deepcopy(operation_dict[pulse_key])
if 'pulse_pars' in params_dict:
for pulse_par_name, pulse_par in \
params_dict['pulse_pars'].items():
if hasattr(pulse_par, '__call__'):
if isinstance(sweep_points, dict):
if 'RO mux' in sweep_points.keys():
pulse_pars_dict[pulse_par_name] = \
pulse_par(sweep_points[
'RO mux'][i])
else:
pulse_pars_dict[pulse_par_name] = \
pulse_par(sweep_points[i])
else:
pulse_pars_dict[pulse_par_name] = \
pulse_par
pulse_list += [pulse_pars_dict]
else:
for qb_name in qb_names:
pulse_pars_dict = deepcopy(
operation_dict[pulse_key + ' ' + qb_name])
if 'pulse_pars' in params_dict:
for pulse_par_name, pulse_par in \
params_dict['pulse_pars'].items():
if hasattr(pulse_par, '__call__'):
if isinstance(sweep_points, dict):
pulse_pars_dict[pulse_par_name] = \
pulse_par(sweep_points[
qb_name][i])
else:
if pulse_par_name == \
'basis_rotation':
pulse_pars_dict[
pulse_par_name] = {}
pulse_pars_dict[pulse_par_name][
[qbn for qbn in qb_names if
qbn != qb_name][0]] = \
- pulse_par(sweep_points[i])
else:
pulse_pars_dict[
pulse_par_name] = \
pulse_par(sweep_points[i])
else:
pulse_pars_dict[pulse_par_name] = \
pulse_par
if qb_name != qb_names[0]:
pulse_pars_dict['refpoint'] = 'simultaneous'
pulse_list += [pulse_pars_dict]
if 'repeat' in params_dict:
n = params_dict['repeat']
pulse_list = n*pulse_list
if nr_echo_pulses != 0:
if qb_names_DD is None:
qb_names_DD = qb_names
pulse_list = get_DD_pulse_list(operation_dict, qb_names,
DD_time=sweep_points[i],
qb_names_DD=qb_names_DD,
pulse_dict_list=pulse_list,
nr_echo_pulses=nr_echo_pulses,
idx_DD_start=idx_DD_start,
UDD_scheme=UDD_scheme)
if not np.any([p['operation_type'] == 'RO' for p in pulse_list]):
pulse_list += [operation_dict['RO mux']]
el = multi_pulse_elt(i, station, pulse_list)
el_list.append(el)
seq.append_element(el, trigger_wait=True)
if upload:
station.pulsar.program_awgs(seq, *el_list, verbose=verbose)
if return_seq:
return seq, el_list
else:
return seq
def get_dd_pulse_list(operation_dict, qb_names, dd_time, nr_pulses=4,
dd_scheme='cpmg', init_buffer=0, refpoint='end'):
drag_pulse_length = (operation_dict['X180 ' + qb_names[-1]]['nr_sigma'] * \
operation_dict['X180 ' + qb_names[-1]]['sigma'])
pulse_list = []
def cpmg_delay(i, nr_pulses=nr_pulses):
if i == 0 or i == nr_pulses:
return 1/nr_pulses/2
else:
return 1/nr_pulses
def udd_delay(i, nr_pulses=nr_pulses):
delay = np.sin(0.5*np.pi*(i + 1)/(nr_pulses + 1))**2
delay -= np.sin(0.5*np.pi*i/(nr_pulses + 1))**2
return delay
if dd_scheme == 'cpmg':
delay_func = cpmg_delay
elif dd_scheme == 'udd':
delay_func = udd_delay
else:
raise ValueError('Unknown decoupling scheme "{}"'.format(dd_scheme))
for i in range(nr_pulses+1):
delay_pulse = {
'pulse_type': 'SquarePulse',
'channel': operation_dict['X180 ' + qb_names[0]]['I_channel'],
'amplitude': 0.0,
'length': dd_time*delay_func(i),
'pulse_delay': 0}
if i == 0:
delay_pulse['pulse_delay'] = init_buffer
delay_pulse['refpoint'] = refpoint
if i == 0 or i == nr_pulses:
delay_pulse['length'] -= drag_pulse_length/2
else:
delay_pulse['length'] -= drag_pulse_length
if delay_pulse['length'] > 0:
pulse_list.append(delay_pulse)
else:
raise Exception("Dynamical decoupling pulses don't fit in the "
"specified dynamical decoupling duration "
"{:.2f} ns".format(dd_time*1e9))
if i != nr_pulses:
for j, qbn in enumerate(qb_names):
pulse_name = 'X180 ' if j == 0 else 'X180s '
pulse_pulse = deepcopy(operation_dict[pulse_name + qbn])
pulse_list.append(pulse_pulse)
return pulse_list
def get_DD_pulse_list(operation_dict, qb_names, DD_time,
qb_names_DD=None,
pulse_dict_list=None, idx_DD_start=-1,
nr_echo_pulses=4, UDD_scheme=True):
n = len(qb_names)
if qb_names_DD is None:
qb_names_DD = qb_names
if pulse_dict_list is None:
pulse_dict_list = []
elif len(pulse_dict_list) < 2*n:
raise ValueError('The pulse_dict_list must have at least two entries.')
idx_DD_start *= n
pulse_dict_list_end = pulse_dict_list[idx_DD_start::]
pulse_dict_list = pulse_dict_list[0:idx_DD_start]
X180_pulse_dict = operation_dict['X180 ' + qb_names_DD[0]]
DRAG_length = X180_pulse_dict['nr_sigma']*X180_pulse_dict['sigma']
X90_separation = DD_time - DRAG_length
if UDD_scheme:
pulse_positions_func = \
lambda idx, N: np.sin(np.pi*idx/(2*N+2))**2
pulse_delays_func = (lambda idx, N: X90_separation*(
pulse_positions_func(idx, N) -
pulse_positions_func(idx-1, N)) -
((0.5 if idx == 1 else 1)*DRAG_length))
if nr_echo_pulses*DRAG_length > X90_separation:
pass
else:
for p_nr in range(nr_echo_pulses):
for qb_name in qb_names_DD:
if qb_name == qb_names_DD[0]:
DD_pulse_dict = deepcopy(operation_dict[
'X180 ' + qb_name])
DD_pulse_dict['refpoint'] = 'end'
DD_pulse_dict['pulse_delay'] = pulse_delays_func(
p_nr+1, nr_echo_pulses)
else:
DD_pulse_dict = deepcopy(operation_dict[
'X180s ' + qb_name])
pulse_dict_list.append(DD_pulse_dict)
for j in range(n):
if j == 0:
pulse_dict_list_end[j]['refpoint'] = 'end'
pulse_dict_list_end[j]['pulse_delay'] = pulse_delays_func(
1, nr_echo_pulses)
else:
pulse_dict_list_end[j]['pulse_delay'] = 0
else:
echo_pulse_delay = (X90_separation -
nr_echo_pulses*DRAG_length) / \
nr_echo_pulses
if echo_pulse_delay < 0:
pass
else:
start_end_delay = echo_pulse_delay/2
for p_nr in range(nr_echo_pulses):
for qb_name in qb_names_DD:
if qb_name == qb_names_DD[0]:
DD_pulse_dict = deepcopy(operation_dict[
'X180 ' + qb_name])
DD_pulse_dict['refpoint'] = 'end'
DD_pulse_dict['pulse_delay'] = \
(start_end_delay if p_nr == 0 else echo_pulse_delay)
else:
DD_pulse_dict = deepcopy(operation_dict[
'X180s ' + qb_name])
pulse_dict_list.append(DD_pulse_dict)
for j in range(n):
if j == 0:
pulse_dict_list_end[j]['refpoint'] = 'end'
pulse_dict_list_end[j]['pulse_delay'] = start_end_delay
else:
pulse_dict_list_end[j]['pulse_delay'] = 0
pulse_dict_list += pulse_dict_list_end
return pulse_dict_list
def pygsti_seq(qb_names, pygsti_listOfExperiments, operation_dict,
preselection=True, ro_spacing=1e-6,
seq_name=None, upload=True, upload_all=True,
return_seq=False, verbose=False):
raise NotImplementedError(
'pygsti_seq has not been '
'converted to the latest waveform generation code and can not be used.')
if seq_name is None:
seq_name = 'GST_sequence'
seq = sequence.Sequence(seq_name)
el_list = []
tup_lst = [g.tup for g in pygsti_listOfExperiments]
str_lst = []
for t1 in tup_lst:
s = ''
for t in t1:
s += str(t)
str_lst += [s]
experiment_lists = get_exp_list(filename='',
pygstiGateList=str_lst,
qb_names=qb_names)
if preselection:
RO_str = 'RO' if len(qb_names) == 1 else 'RO mux'
operation_dict[RO_str+'_presel'] = \
operation_dict[experiment_lists[0][-1]].copy()
operation_dict[RO_str+'_presel']['pulse_delay'] = -ro_spacing
operation_dict[RO_str+'_presel']['refpoint'] = 'start'
operation_dict[RO_str+'presel_dummy'] = {
'pulse_type': 'SquarePulse',
'channel': operation_dict[
experiment_lists[0][-1]]['acq_marker_channel'],
'amplitude': 0.0,
'length': ro_spacing,
'pulse_delay': 0}
if upload_all:
upload_AWGs = 'all'
else:
upload_AWGs = ['AWG1']
for qbn in qb_names:
X90_pulse = deepcopy(operation_dict['X90 ' + qbn])
upload_AWGs += [station.pulsar.get(X90_pulse['I_channel'] + '_AWG'),
station.pulsar.get(X90_pulse['Q_channel'] + '_AWG')]
if len(qb_names) > 1:
CZ_pulse_name = 'CZ {} {}'.format(qb_names[1], qb_names[0])
if len([i for i in experiment_lists if CZ_pulse_name in i]) > 0:
CZ_pulse = operation_dict[CZ_pulse_name]
upload_AWGs += [station.pulsar.get(CZ_pulse['channel'] + '_AWG')]
for ch in CZ_pulse['aux_channels_dict']:
upload_AWGs += [station.pulsar.get(ch + '_AWG')]
upload_AWGs = list(set(upload_AWGs))
for i, exp_lst in enumerate(experiment_lists):
pulse_lst = [operation_dict[p] for p in exp_lst]
if preselection:
pulse_lst.append(operation_dict[RO_str+'_presel'])
pulse_lst.append(operation_dict[RO_str+'presel_dummy'])
el = multi_pulse_elt(i, station, pulse_lst)
el_list.append(el)
seq.append_element(el, trigger_wait=True)
if upload:
station.pulsar.program_awgs(seq, *el_list,
AWGs=upload_AWGs,
channels='all',
verbose=verbose)
if return_seq:
return seq, el_list
else:
return seq_name
def generate_mux_ro_pulse_list(qubit_names, operation_dict, element_name='RO',
ref_point='end', pulse_delay=0.0):
ro_pulses = []
for j, qb_name in enumerate(qubit_names):
ro_pulse = deepcopy(operation_dict['RO ' + qb_name])
ro_pulse['pulse_name'] = '{}_{}'.format(element_name, j)
ro_pulse['element_name'] = element_name
if j == 0:
ro_pulse['pulse_delay'] = pulse_delay
ro_pulse['ref_point'] = ref_point
else:
ro_pulse['ref_point'] = 'start'
ro_pulses.append(ro_pulse)
return ro_pulses
def interleaved_pulse_list_equatorial_seg(
qubit_names, operation_dict, interleaved_pulse_list, phase,
pihalf_spacing=None, prep_params=None, segment_name='equatorial_segment'):
prep_params = {} if prep_params is None else prep_params
pulse_list = []
for notfirst, qbn in enumerate(qubit_names):
pulse_list.append(deepcopy(operation_dict['X90 ' + qbn]))
pulse_list[-1]['ref_point'] = 'start'
if not notfirst:
pulse_list[-1]['name'] = 'refpulse'
pulse_list += interleaved_pulse_list
for notfirst, qbn in enumerate(qubit_names):
pulse_list.append(deepcopy(operation_dict['X90 ' + qbn]))
pulse_list[-1]['phase'] = phase
if notfirst:
pulse_list[-1]['ref_point'] = 'start'
elif pihalf_spacing is not None:
pulse_list[-1]['ref_pulse'] = 'refpulse'
pulse_list[-1]['ref_point'] = 'start'
pulse_list[-1]['pulse_delay'] = pihalf_spacing
pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)
pulse_list = add_preparation_pulses(pulse_list, operation_dict, qubit_names, **prep_params)
return segment.Segment(segment_name, pulse_list)
def interleaved_pulse_list_list_equatorial_seq(
qubit_names, operation_dict, interleaved_pulse_list_list, phases,
pihalf_spacing=None, prep_params=None, cal_points=None,
sequence_name='equatorial_sequence', upload=True):
prep_params = {} if prep_params is None else prep_params
seq = sequence.Sequence(sequence_name)
for i, interleaved_pulse_list in enumerate(interleaved_pulse_list_list):
for j, phase in enumerate(phases):
seg = interleaved_pulse_list_equatorial_seg(
qubit_names, operation_dict, interleaved_pulse_list, phase,
pihalf_spacing=pihalf_spacing, prep_params=prep_params, segment_name=f'segment_{i}_{j}')
seq.add(seg)
if cal_points is not None:
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
def measurement_induced_dephasing_seq(
measured_qubit_names, dephased_qubit_names, operation_dict,
ro_amp_scales, phases, pihalf_spacing=None, prep_params=None,
cal_points=None, upload=True, sequence_name='measurement_induced_dephasing_seq'):
interleaved_pulse_list_list = []
for i, ro_amp_scale in enumerate(ro_amp_scales):
interleaved_pulse_list = generate_mux_ro_pulse_list(
measured_qubit_names, operation_dict,
element_name=f'interleaved_readout_{i}')
for pulse in interleaved_pulse_list:
pulse['amplitude'] *= ro_amp_scale
pulse['operation_type'] = None
interleaved_pulse_list_list.append(interleaved_pulse_list)
return interleaved_pulse_list_list_equatorial_seq(
dephased_qubit_names, operation_dict, interleaved_pulse_list_list,
phases, pihalf_spacing=pihalf_spacing, prep_params=prep_params,
cal_points=cal_points, sequence_name=sequence_name, upload=upload)
def drive_cancellation_seq(
drive_op_code, ramsey_qubit_names, operation_dict,
sweep_points, n_pulses=1, pihalf_spacing=None, prep_params=None,
cal_points=None, upload=True, sequence_name='drive_cancellation_seq'):
"""
Sweep pulse cancellation parameters and measure Ramsey on qubits the
cancellation is for.
Args:
drive_op_code: Operation code for the pulse to be cancelled, including
the qubit name.
ramsey_qubit_names: A list of qubit names corresponding to the
undesired targets of the pulse that is being cancelled.
sweep_points: A SweepPoints object that describes the pulse
parameters to sweep. The sweep point keys should be of the form
`qb.param`, where `qb` is the name of the qubit the cancellation
is for and `param` is a parameter in the pulses
cancellation_params dict. For example to sweep the amplitude of
the cancellation pulse on qb1, you could configure the sweep
points as `SweepPoints('qb1.amplitude', np.linspace(0, 1, 21))`.
The Ramsey phases must be given in the second sweep dimension with
sweep name 'phases'.
n_pulses: Number of pulse repetitions done between the Ramsey
pulses. Useful for amplification of small errors. Defaults to 1.
Rest of the arguments are passed down to
interleaved_pulse_list_list_equatorial_seq
"""
len_sweep = len(list(sweep_points[0].values())[0][0])
# create len_sweep instances of n pulses, where the n references correspond
# to the same dictionary instance
interleaved_pulse_list_list = \
[n_pulses*[deepcopy(operation_dict[drive_op_code])]
for _ in range(len_sweep)]
for key, (values, unit, label) in sweep_points[0].items():
assert len(values) == len_sweep
tqb, param = key.split('.')
iq = operation_dict[f'X180 {tqb}']['I_channel'], \
operation_dict[f'X180 {tqb}']['Q_channel']
for pulse_list, value in zip(interleaved_pulse_list_list, values):
# since all n pulses in pulse_list are the same dict. we only need
# to modify the first element.
pulse_list[0]['cancellation_params'][iq][param] = value
# make last segment a calibration segment
interleaved_pulse_list_list[-1][0]['amplitude'] = 0
return interleaved_pulse_list_list_equatorial_seq(
ramsey_qubit_names, operation_dict, interleaved_pulse_list_list,
sweep_points[1]['phase'][0], pihalf_spacing=pihalf_spacing,
prep_params=prep_params, cal_points=cal_points,
sequence_name=sequence_name, upload=upload)
def fluxline_crosstalk_seq(target_qubit_name, crosstalk_qubits_names,
crosstalk_qubits_amplitudes, sweep_points,
operation_dict, crosstalk_fluxpulse_length,
target_fluxpulse_length, prep_params,
cal_points, upload=True,
sequence_name='fluxline_crosstalk_seq'):
"""
Applies a flux pulse on the target qubit with various amplitudes.
Measure the phase shift due to these pulses on the crosstalk qubits which
are measured in a Ramsey setting and fluxed to a more sensitive frequency.
Args:
target_qubit_name: the qubit to which a fluxpulse with varying amplitude
is applied
crosstalk_qubits_names: a list of qubits to do a Ramsey on.
crosstalk_qubits_amplitudes: A dictionary from crosstalk qubit names
to flux pulse amplitudes that are applied to them to increase their
flux sensitivity. Missing amplitudes are set to 0.
sweep_points: A SweepPoints object, where the first sweep dimension is
over Ramsey phases and must be called 'phase' and the second sweep
dimenstion is over the target qubit pulse amplitudes and must be
called 'target_amp'.
operation_dict: A dictionary of pulse dictionaries corresponding to the
various operations that can be done.
target_fluxpulse_length: length of the flux pulse on the target qubit.
crosstalk_fluxpulse_length: length of the flux pulses on the crosstalk
qubits
prep_params: Perparation parameters dictionary specifying the type
of state preparation.
cal_points: CalibrationPoints object determining the used calibration
points
upload: Whether the experimental sequence should be uploaded.
Defaults to True.
sequence_name: Overwrite the sequence name. Defaults to
'fluxline_crosstalk_seq'.
"""
interleaved_pulse_list_list = []
buffer_start = 0
buffer_end = 0
pi_len = 0
for qbn in crosstalk_qubits_names:
buffer_start = max(buffer_start,
operation_dict[f'FP {qbn}']['buffer_length_start'])
buffer_end = max(buffer_end,
operation_dict[f'FP {qbn}']['buffer_length_end'])
pi_len = max(pi_len, operation_dict[f'X180 {qbn}']['nr_sigma'] *
operation_dict[f'X180 {qbn}']['sigma'])
for amp in sweep_points[1]['target_amp'][0]:
interleaved_pulse_list = []
for i, qbn in enumerate(crosstalk_qubits_names):
pulse = deepcopy(operation_dict[f'FP {qbn}'])
if i > 0:
pulse['ref_point'] = 'middle'
pulse['ref_point_new'] = 'middle'
pulse['amplitude'] = crosstalk_qubits_amplitudes.get(qbn, 0)
pulse['pulse_length'] = crosstalk_fluxpulse_length
pulse['buffer_length_start'] = buffer_start
pulse['buffer_length_end'] = buffer_end
interleaved_pulse_list += [pulse]
pulse = deepcopy(operation_dict[f'FP {target_qubit_name}'])
pulse['amplitude'] = amp
pulse['pulse_length'] = target_fluxpulse_length
pulse['ref_point'] = 'middle'
pulse['ref_point_new'] = 'middle'
interleaved_pulse_list += [pulse]
interleaved_pulse_list_list += [interleaved_pulse_list]
pihalf_spacing = buffer_start + crosstalk_fluxpulse_length + buffer_end + \
pi_len
return interleaved_pulse_list_list_equatorial_seq(
crosstalk_qubits_names, operation_dict, interleaved_pulse_list_list,
sweep_points[0]['phase'][0], pihalf_spacing=pihalf_spacing,
prep_params=prep_params, cal_points=cal_points,
sequence_name=sequence_name, upload=upload)
def multi_parity_multi_round_seq(ancilla_qubit_names,
data_qubit_names,
parity_map,
CZ_map,
prep,
operation_dict,
mode='tomo',
parity_seperation=800e-9,
rots_basis=('I', 'Y90', 'X90'),
parity_loops=1,
cal_points=None,
prep_params=None,
upload=True,
max_acq_length=1e-6,
):
seq_name = 'Multi_Parity_{}_round_sequence'.format(parity_loops)
qb_names = ancilla_qubit_names + data_qubit_names
# Dummy pulses are used to make sure that all UHFs are triggered even if
# only part of the qubits are read out.
# First get all RO pulses, then throw away all except one per channel pair.
dummy_pulses = [deepcopy(operation_dict['RO ' + qbn]) for qbn in qb_names]
dummy_pulses = {(p['I_channel'], p['Q_channel']): p for p in dummy_pulses}
for p in dummy_pulses.values():
p.update({'amplitude': 0.00001,
'pulse_length': 50e-09,
'pulse_delay': 0,
'mod_frequency': 900.0e6,
'op_code': ''})
echo_pulses = [('Y180' + 's ' + dqb)
for n, dqb in enumerate(data_qubit_names)]
parity_ops_list = []
echoed_round = {}
for i in range(len(parity_map)):
echoed_round[parity_map[i]['round']] = False
for i in range(len(parity_map)):
parity_ops = []
anc_name = parity_map[i]['ancilla']
basis_op = 'I'
if parity_map[i]['type'] == 'Z':
basis_op = 'I'
elif parity_map[i]['type'] == 'X':
basis_op = 'Y90'
elif parity_map[i]['type'] == 'Y':
basis_op = 'X90'
for n, dqb in enumerate(parity_map[i]['data']):
if dqb in data_qubit_names:
op = basis_op + ('' if n==0 else 's') + ' ' + dqb
parity_ops.append(op)
parity_ops.append('Y90 ' + anc_name)
for n, dqb in enumerate(parity_map[i]['data']):
op = 'CZ ' + anc_name + ' ' + dqb
op = CZ_map.get(op, [op])
ops = parity_ops+op
if n==1 and parity_map[i]['type'] == 'X':
ops.append('Y180 ' + anc_name)
ops.append('Z180 ' + parity_map[i]['data'][-1])
ops.append('Z180 ' + parity_map[i]['data'][-2])
print('ECHO')
elif n==0 and parity_map[i]['type'] == 'Z':
ops.append('Y180 ' + anc_name)
ops.append('Z180 ' + parity_map[i]['data'][-1])
print('ECHO')
parity_ops = ops
parity_ops.append('I ' + anc_name)
parity_ops.append('Y90s ' + anc_name)
print('ECHO')
for n, dqb in enumerate(parity_map[i]['data']):
if dqb in data_qubit_names:
op = ('m' if basis_op is not 'I' else '') + basis_op + ('' if n==0
else
's') + ' ' + dqb
# op = basis_op + ('' if n==0 else 's') + ' ' + dqb
parity_ops.append(op)
parity_ops.append('I ' + parity_map[i]['data'][-1])
parity_ops.append('RO ' + anc_name)
parity_ops_list.append(parity_ops)
prep_ops = [{'g': 'I ', 'e': 'X180 ', '+': 'Y90 ', '-': 'mY90 '}[s] \
+ dqn for s, dqn in zip(prep, data_qubit_names)]
prep_mode = False
end_sequence = []
if mode=='tomo':
end_sequences = get_tomography_pulses(*data_qubit_names,
basis_pulses=rots_basis)
elif mode=='onoff':
end_sequences = [[rot + ('s ' if i==0 else ' ') + dqb
for i, dqb in enumerate(data_qubit_names)]
for rot in rots_basis]
elif mode=='preps':
prep_ops = [[{'g': 'I ', 'e': 'X180 ', '+': 'Y90 ', '-': 'mY90 '}[s] \
+ dqn for s, dqn in zip(preps, data_qubit_names)]
for preps in rots_basis]
end_sequences = [['I ' + data_qubit_names[0]] for preps in rots_basis]
prep_mode = True
else:
end_sequences = ['I ' + data_qubit_names[0]]
first_readout = dict()
rounds = 0
for k in range(len(parity_map)):
first_readout[parity_map[k]['round']] = True
if parity_map[k]['round'] > rounds:
rounds = parity_map[k]['round']
all_pulsess = []
for t, end_sequence in enumerate(end_sequences):
all_pulses = []
if prep_mode:
prep_pulses = [deepcopy(operation_dict[op]) for op in
prep_ops[t]]
else:
prep_pulses = [deepcopy(operation_dict[op]) for op in
prep_ops]
for pulse in prep_pulses:
# pulse['element_name'] = f'prep_tomo_{t}'
pulse['element_name'] = f'drive_tomo_{t}'
pulse['ref_pulse'] = 'segment_start'
pulse['pulse_delay'] = -pulse['sigma']*pulse['nr_sigma']
all_pulses += prep_pulses
for m in range(parity_loops):
for round in first_readout.keys():
first_readout[round] = True
for k in range(len(parity_map)):
round = parity_map[k]['round']
anc_name = parity_map[k]['ancilla']
for i, op in enumerate(parity_ops_list[k]):
all_pulses.append(deepcopy(operation_dict[op]))
if op == 'I '+anc_name:
all_pulses[-1]['basis_rotation'] = parity_map[k][
'phases']
if i == 0:
all_pulses[-1]['ref_pulse'] = 'segment_start'
all_pulses[-1]['pulse_delay'] = np.sum(
parity_seperation[:round])+m*np.sum(parity_seperation)
if 'CZ' not in op and 'RO' not in op:
all_pulses[-1]['element_name'] = f'drive_tomo_{t}'
# all_pulses[-1]['element_name'] = f'drive_{round}_loop' + \
# f'_{m}_tomo_{t}'
elif 'CZ' in op:
all_pulses[-1]['element_name'] = f'flux_tomo_{t}'
if 'RO' in op:
all_pulses[-1]['element_name'] = f'ro_{round}_loop' + \
f'_{m}_tomo_{t}'
if first_readout[round] is True:
all_pulses[-1]['name'] = f'first_ro_{round}_loop' + \
f'_{m}_tomo_{t}'
else:
all_pulses[-1]['ref_pulse'] = f'first_ro_{round}' + \
f'_loop_{m}_tomo_{t}'
all_pulses[-1]['ref_point'] = 'start'
first_readout[round] = False
# Add dummy pulses for all UHFs
for p in dummy_pulses.values():
all_pulses.append(deepcopy(p))
all_pulses[-1]['element_name'] = f'ro_{round}_loop' + \
f'_{m}_tomo_{t}'
all_pulses[-1]['ref_pulse'] = f'first_ro_{round}' + \
f'_loop_{m}_tomo_{t}'
all_pulses[-1]['ref_point'] = 'start'
# if (m!=parity_loops-1) or ( (parity_loops%2==0)
# and m==parity_loops-1):
if m != parity_loops - 1:
# print('Logical Echo')
for i, op in enumerate(echo_pulses):
all_pulses.append(deepcopy(operation_dict[op]))
all_pulses[-1]['element_name'] = f'drive_tomo_{t}'
# all_pulses[-1]['pulse_delay'] = -50e-9
end_pulses = [deepcopy(operation_dict[op]) for op in end_sequence]
for pulse in end_pulses:
pulse['element_name'] = f'drive_tomo_{t}'
pulse['ref_pulse'] = f'first_ro_{rounds}' + \
f'_loop_{parity_loops-1}_tomo_{t}'
pulse['pulse_delay'] = max_acq_length + 5e-9 # account for UHF deadtime
pulse['ref_point'] = 'start'
all_pulses += end_pulses
all_pulses += generate_mux_ro_pulse_list(qb_names, operation_dict)
all_pulsess.append(all_pulses)
if prep_params is not None:
all_pulsess_with_prep = \
[add_preparation_pulses(seg, operation_dict, qb_names, **prep_params)
for seg in all_pulsess]
else:
all_pulsess_with_prep = all_pulsess
seq = pulse_list_list_seq(all_pulsess_with_prep, seq_name, upload=False)
# add calibration segments
if cal_points is not None:
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
# This will currently only work with pre-selection
ROs = (rounds+1)
repeat_patern = (len(end_sequences), 1, (parity_loops, ROs), 1)
for qbn in qb_names:
pulse = 'RO ' + qbn
repeat_dict = seq.repeat(pulse, operation_dict, repeat_patern)
log.debug(repeat_dict)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
log.debug('sweep_points: ', seq.n_acq_elements())
return seq, np.arange(seq.n_acq_elements())
def ro_dynamic_phase_seq(hard_sweep_dict, qbp_name, qbr_names,
operation_dict, pulse_separation, init_state,
cal_points=None, prep_params=dict(), upload=True):
"""
RO cross-dephasing measurement sequence. Measures the dynamic phase induced
on qbr by a measurement tone on the pulsed qubit (qbp).
Args:
qbp_name: pulsed qubit name; RO pulse is applied on this qubit
qbr_names: ramsey (measured) qubits
phases: array of phases for the second piHalf pulse on qbr
operation_dict: contains operation dicts from both qubits;
!!! Must contain 'RO mux' which is the mux RO pulse only for
the measured_qubits (qbr_names) !!!
pulse_separation: separation between the two pi-half pulses, shouls be
equal to integration length
cal_points: use cal points
"""
seq_name = 'ro_dynamic_phase_sequence'
dummy_ro_1 = {'pulse_type': 'GaussFilteredCosIQPulse',
'I_channel': 'UHF1_ch1',
'Q_channel': 'UHF1_ch2',
'amplitude': 0.00001,
'pulse_length': 50e-09,
'pulse_delay': 0,
'mod_frequency': 900.0e6,
'phase': 0,
'phi_skew': 0,
'alpha': 1,
'gaussian_filter_sigma': 1e-09,
'nr_sigma': 2,
'phase_lock': True,
'basis_rotation': {},
'operation_type': 'RO'}
dummy_ro_2 = {'pulse_type': 'GaussFilteredCosIQPulse',
'I_channel': 'UHF2_ch1',
'Q_channel': 'UHF2_ch2',
'amplitude': 0.00001,
'pulse_length': 50e-09,
'pulse_delay': 0,
'mod_frequency': 900.0e6,
'phase': 0,
'phi_skew': 0,
'alpha': 1,
'gaussian_filter_sigma': 1e-09,
'nr_sigma': 2,
'phase_lock': True,
'basis_rotation': {},
'operation_type': 'RO'}
# put together n-qubit calibration point pulse lists
# put together n-qubit ramsey pulse lists
pulse_list = []
for j, qbr_name in enumerate(qbr_names):
pulse_list.append(deepcopy(operation_dict['X90 ' + qbr_name]))
pulse_list[-1]['name'] = f'x1_{qbr_name}'
pulse_list[-1]['ref_pulse'] = 'segment_start'
pulse_list[-1]['refpoint'] = 'start'
ro_probe = deepcopy(operation_dict['RO ' + qbp_name])
pulse_list.append(ro_probe)
pulse_list[-1]['name'] = f'ro_probe'
pulse_list[-1]['element_name'] = f'ro_probe'
pulse_list.append(dummy_ro_1)
pulse_list[-1]['refpoint'] = 'start'
pulse_list[-1]['element_name'] = f'ro_probe'
pulse_list.append(dummy_ro_2)
pulse_list[-1]['refpoint'] = 'start'
pulse_list[-1]['element_name'] = f'ro_probe'
for j, qbr_name in enumerate(qbr_names):
pulse_list.append(deepcopy(operation_dict['X90 ' + qbr_name]))
pulse_list[-1]['name'] = f'x2_{qbr_name}'
pulse_list[-1]['ref_pulse'] = 'segment_start'
pulse_list[-1]['refpoint'] = 'start'
pulse_list[-1]['pulse_delay'] = pulse_separation
ro_list = generate_mux_ro_pulse_list(qbr_names+[qbp_name], operation_dict)
pulse_list += ro_list
if init_state == 'e':
pulse_list.append(deepcopy(operation_dict['X180 ' + qbp_name]))
pulse_list[-1]['ref_pulse'] = 'segment_start'
pulse_list[-1]['refpoint'] = 'start'
pulse_list[-1]['pulse_delay'] = -100e-9
params = {f'x2_{qbr_name}.{k}': v['values']
for k, v in hard_sweep_dict.items() for qbr_name in qbr_names}
hsl = len(list(hard_sweep_dict.values())[0]['values'])
params.update({f'ro_probe.amplitude': np.concatenate(
[ro_probe['amplitude'] * np.ones(hsl // 2), np.zeros(hsl // 2)])})
swept_pulses = sweep_pulse_params(pulse_list, params)
swept_pulses_with_prep = \
[add_preparation_pulses(p, operation_dict, [qbp_name], **prep_params)
for p in swept_pulses]
seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)
if cal_points is not None:
# add calibration segments
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
log.debug(seq)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
## Multi-qubit time-domain sequences ##
def n_qubit_rabi_seq(qubit_names, operation_dict, sweep_points, cal_points,
upload=True, n=1, for_ef=False,
last_ge_pulse=False, prep_params=dict()):
'''
Rabi sequence for n qubits.
Args:
qubit_names: list of qubit names
operation_dict: operation_dict for all qubit in qubit_names
sweep_points: instance of SweepPoints class
cal_points: instance of CalibrationPoints class
upload: whether to upload sequence to instrument or not
n: number of pulses (1 is conventional Rabi)
for_ef: whether to do rabi between ef transition
last_ge_pulse: whether to use a ge pulse at the end of each segment
for a rabi between ef transition
prep_params: qubit preparation params
Returns:
sequence (Sequence): sequence object
segment_indices (list): array of range of n_segments including
calibration_segments. To be used as sweep_points for the MC.
'''
seq_name = 'n_qubit_Rabi_sequence'
pulse_list = []
# add Rabi amplitudes segments
for qbn in qubit_names:
rabi_ops = ["X180_ef " + qbn if for_ef else "X180 " + qbn] * n
if for_ef:
rabi_ops = ["X180 " + qbn] + rabi_ops # prepend ge pulse
if last_ge_pulse:
rabi_ops += ["X180 " + qbn] # append ge pulse
rabi_pulses = [deepcopy(operation_dict[op]) for op in rabi_ops]
rabi_pulses[0]['ref_pulse'] = 'segment_start'
for i in np.arange(1 if for_ef else 0, n + 1 if for_ef else n):
rabi_pulses[i]["name"] = f"Rabi_{i-1 if for_ef else i}_{qbn}"
pulse_list += rabi_pulses
pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)
params_to_sweep = {
f'Rabi_{i}_{qbn}.amplitude': list(sweep_points[0].values())[j][0]
for i in range(n) for j, qbn in enumerate(qubit_names)}
swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)
swept_pulses_with_prep = \
[add_preparation_pulses(p, operation_dict, qubit_names, **prep_params)
for p in swept_pulses]
seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)
# add calibration segments
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
# reuse sequencer memory by repeating readout pattern
[seq.repeat_ro(f"RO {qbn}", operation_dict) for qbn in qubit_names]
log.debug(seq)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
def n_qubit_ramsey_seq(qubit_names, operation_dict, sweep_points, cal_points,
artificial_detuning=0, upload=True, for_ef=False,
last_ge_pulse=False, prep_params=dict()):
'''
Ramsey sequence for n qubits.
Args:
qubit_names: list of qubit names
operation_dict: operation_dict for all qubit in qubit_names
sweep_points: instance of SweepPoints class
cal_points: instance of CalibrationPoints class
artificial_detunings: Detuning of second pi-half pulse.
upload: whether to upload sequence to instrument or not
n: number of pulses (1 is conventional Rabi)
for_ef: whether to do rabi between ef transition
last_ge_pulse: whether to use a ge pulse at the end of each segment
for a rabi between ef transition
prep_params: qubit preparation params
Returns:
sequence (Sequence): sequence object
segment_indices (list): array of range of n_segments including
calibration_segments. To be used as sweep_points for the MC.
'''
seq_name = 'n_qubit_Ramsey_sequence'
pulse_list = []
# add Ramsey segments
for qbn in qubit_names:
ramsey_ops = ["X90_ef " + qbn if for_ef else "X90 " + qbn] * 2
if for_ef:
ramsey_ops = ["X180 " + qbn] + ramsey_ops # prepend ge pulse
if last_ge_pulse:
ramsey_ops += ["X180 " + qbn] # append ge pulse
ramsey_pulses = [deepcopy(operation_dict[op]) for op in ramsey_ops]
ramsey_pulses[0]['ref_pulse'] = 'segment_start'
ramsey_pulses[2 if for_ef else 1]["name"] = f"Ramsey_{qbn}"
ramsey_pulses[2 if for_ef else 1]["ref_point"] = 'start'
pulse_list += ramsey_pulses
pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)
params_to_sweep = {}
for j, qbn in enumerate(qubit_names):
times = list(sweep_points[0].values())[j][0]
params_to_sweep.update({f'Ramsey_{qbn}.pulse_delay': times})
params_to_sweep.update({
f'Ramsey_{qbn}.phase':
((times-times[0])*artificial_detuning*360) % 360})
swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)
swept_pulses_with_prep = \
[add_preparation_pulses(p, operation_dict, qubit_names, **prep_params)
for p in swept_pulses]
seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)
# add calibration segments
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
# reuse sequencer memory by repeating readout pattern
[seq.repeat_ro(f"RO {qbn}", operation_dict) for qbn in qubit_names]
log.debug(seq)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
def n_qubit_qscale_seq(qubit_names, operation_dict, sweep_points, cal_points,
upload=True, for_ef=False,
last_ge_pulse=False, prep_params=dict()):
'''
DRAG pulse calibration sequence for n qubits.
Args:
qubit_names: list of qubit names
operation_dict: operation_dict for all qubit in qubit_names
sweep_points: instance of SweepPoints class
cal_points: instance of CalibrationPoints class
upload: whether to upload sequence to instrument or not
n: number of pulses (1 is conventional Rabi)
for_ef: whether to do rabi between ef transition
last_ge_pulse: whether to use a ge pulse at the end of each segment
for a rabi between ef transition
prep_params: qubit preparation params
Returns:
sequence (Sequence): sequence object
segment_indices (list): array of range of n_segments including
calibration_segments. To be used as sweep_points for the MC.
'''
seq_name = 'n_qubit_qscale_sequence'
# Operations
qscale_base_ops = [['X90', 'X180'], ['X90', 'Y180'], ['X90', 'mY180']]
# add DRAG calibration segments
final_pulses = []
for base_ops in qscale_base_ops:
pulse_list = []
for qbn in qubit_names:
qscale_ops = add_suffix(base_ops, "_ef" if for_ef else "")
if for_ef:
qscale_ops = ['X180'] + qscale_ops
if last_ge_pulse:
qscale_ops += ["X180"]
qscale_ops = add_suffix(qscale_ops, " " + qbn)
qscale_pulses = [deepcopy(operation_dict[op]) for op in qscale_ops]
qscale_pulses[0]['ref_pulse'] = 'segment_start'
# name and reference swept pulse
for i in range(len(base_ops)):
idx = (1 if for_ef else 0) + i
qscale_pulses[idx]["name"] = f"Qscale_{i}_{qbn}"
pulse_list += qscale_pulses
pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)
params_to_sweep = {
f'Qscale_*_{qbn}.motzoi': list(sweep_points[0].values())[j][0]
for j, qbn in enumerate(qubit_names)}
swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)
swept_pulses_with_prep = \
[add_preparation_pulses(p, operation_dict, qubit_names,
**prep_params)
for p in swept_pulses]
final_pulses.append(swept_pulses_with_prep)
# intertwine pulses in same order as base_ops
# 1. get one list of list from the 3 lists of list
f_p = np.array(final_pulses)
reordered_pulses = [[X90X180, X90Y180, X90mY180]
for X90X180, X90Y180, X90mY180
in zip(f_p[0], f_p[1], f_p[2])]
# 2. reshape to list of list
len_swp_pts = len(list(sweep_points[0].values())[0][0])
final_pulses = np.squeeze(np.reshape(reordered_pulses,
(3*len_swp_pts, -1))).tolist()
seq = pulse_list_list_seq(final_pulses, seq_name, upload=False)
# add calibration segments
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
# reuse sequencer memory by repeating readout pattern
[seq.repeat_ro(f"RO {qbn}", operation_dict) for qbn in qubit_names]
log.debug(seq)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
def n_qubit_t1_seq(qubit_names, operation_dict, sweep_points, cal_points,
upload=True, for_ef=False, last_ge_pulse=False,
prep_params=dict()):
'''
T1 sequence for n qubits.
Args:
qubit_names: list of qubit names
operation_dict: operation_dict for all qubit in qubit_names
sweep_points: instance of SweepPoints class
cal_points: instance of CalibrationPoints class
upload: whether to upload sequence to instrument or not
for_ef: whether to do rabi between ef transition
last_ge_pulse: whether to use a ge pulse at the end of each segment
for a rabi between ef transition
prep_params: qubit preparation params
Returns:
sequence (Sequence): sequence object
segment_indices (list): array of range of n_segments including
calibration_segments. To be used as sweep_points for the MC.
'''
seq_name = 'n_qubit_T1_sequence'
pulse_list = []
# add delays segments
for j, qbn in enumerate(qubit_names):
t1_ops = ["X180_ef " + qbn if for_ef else "X180 " + qbn]
if for_ef:
t1_ops = ["X180 " + qbn] + t1_ops # prepend ge pulse
if last_ge_pulse:
t1_ops += ["X180 " + qbn] # append ge pulse
t1_pulses = [deepcopy(operation_dict[op]) for op in t1_ops]
t1_pulses[0]['ref_pulse'] = 'segment_start'
if for_ef and last_ge_pulse:
t1_pulses[-1]['name'] = f"delayed_pulse_{qbn}"
pulse_list += t1_pulses
pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)
if not (for_ef and last_ge_pulse):
pulse_list[-len(qubit_names)]["name"] = f"delayed_pulse"
params_to_sweep = {}
for j, qbn in enumerate(qubit_names):
delay_times = list(sweep_points[0].values())[j][0]
if for_ef and last_ge_pulse:
delays = np.array(delay_times)
params_to_sweep.update({f'delayed_pulse_{qbn}.pulse_delay': delays})
else:
delays = np.array(delay_times) + pulse_list[-1]["pulse_delay"]
params_to_sweep.update({f'delayed_pulse.pulse_delay': delays})
swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)
swept_pulses_with_prep = \
[add_preparation_pulses(p, operation_dict, qubit_names, **prep_params)
for p in swept_pulses]
seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)
# add calibration segments
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
# reuse sequencer memory by repeating readout pattern
[seq.repeat_ro(f"RO {qbn}", operation_dict) for qbn in qubit_names]
log.debug(seq)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
def n_qubit_echo_seq(qubit_names, operation_dict, sweep_points, cal_points,
artificial_detuning=0, upload=True, for_ef=False,
last_ge_pulse=False, prep_params=dict()):
'''
Echo sequence for n qubits.
Args:
qubit_names: list of qubit names
operation_dict: operation_dict for all qubit in qubit_names
sweep_points: instance of SweepPoints class
cal_points: instance of CalibrationPoints class
artificial_detunings: Detuning of second pi-half pulse.
upload: whether to upload sequence to instrument or not
n: number of pulses (1 is conventional Rabi)
for_ef: whether to do rabi between ef transition
last_ge_pulse: whether to use a ge pulse at the end of each segment
for a rabi between ef transition
prep_params: qubit preparation params
Returns:
sequence (Sequence): sequence object
segment_indices (list): array of range of n_segments including
calibration_segments. To be used as sweep_points for the MC.
'''
seq_name = 'n_qubit_Ramsey_sequence'
pulse_list = []
# add Echo segments
for qbn in qubit_names:
echo_ops = ["X90_ef " + qbn if for_ef else "X90 " + qbn]
echo_ops = echo_ops + \
["X180_ef " + qbn if for_ef else "X180 " + qbn] + \
echo_ops
if for_ef:
echo_ops = ["X180 " + qbn] + echo_ops # prepend ge pulse
if last_ge_pulse:
echo_ops += ["X180 " + qbn] # append ge pulse
echo_ops = [deepcopy(operation_dict[op]) for op in echo_ops]
echo_ops[0]['ref_pulse'] = 'segment_start'
echo_ops[2 if for_ef else 1]["name"] = f"Echo_pi_{qbn}"
echo_ops[2 if for_ef else 1]["ref_point"] = 'start'
echo_ops[3 if for_ef else 2]["name"] = f"Echo_pihalf_{qbn}"
echo_ops[3 if for_ef else 2]["ref_point"] = 'start'
pulse_list += echo_ops
pulse_list += generate_mux_ro_pulse_list(qubit_names, operation_dict)
params_to_sweep = {}
for j, qbn in enumerate(qubit_names):
times = list(sweep_points[0].values())[j][0]
params_to_sweep.update({f'Echo_pi_{qbn}.pulse_delay': times/2})
params_to_sweep.update({f'Echo_pihalf_{qbn}.pulse_delay': times/2})
params_to_sweep.update({
f'Echo_pihalf_{qbn}.phase':
((times-times[0])*artificial_detuning*360) % 360})
swept_pulses = sweep_pulse_params(pulse_list, params_to_sweep)
swept_pulses_with_prep = \
[add_preparation_pulses(p, operation_dict, qubit_names, **prep_params)
for p in swept_pulses]
seq = pulse_list_list_seq(swept_pulses_with_prep, seq_name, upload=False)
# add calibration segments
seq.extend(cal_points.create_segments(operation_dict, **prep_params))
# reuse sequencer memory by repeating readout pattern
[seq.repeat_ro(f"RO {qbn}", operation_dict) for qbn in qubit_names]
log.debug(seq)
if upload:
ps.Pulsar.get_instance().program_awgs(seq)
return seq, np.arange(seq.n_acq_elements())
|
# -*- coding: utf-8 -*-
"""
/dms/faqitem/help_form.py
.. enthaelt die kompletten Kontext-Hilfetexte fuer FAQ-Beitraege
Django content Management System
<NAME>
<EMAIL>
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 01.10.2007 Beginn der Arbeit
"""
from django.utils.translation import ugettext as _
from dms.help_form_base import get_help_form
help_form = get_help_form()
# ----------------------------------------------------------------
help_form['string_1'] = {
'title' : _(u'Mein Name'),
'help' : _(u"""<p>
Falls Sie eingeloggt sind, werden Ihre bekannten Daten übernommen, ansonsten tragen Sie hier bitte Ihren Vor- und Nachnamen ein. Anonyme Beiträge sind nicht erwünscht.
</p>""") }
# ----------------------------------------------------------------
help_form['string_2'] = {
'title' : _(u'Meine E-Mail-Adresse'),
'help' : _(u"""<p>
Falls Sie eingeloggt sind, wird Ihre bekannte Adresse übernommen, ansonsten geben Sie bitte für Rückfragen oder direkte Reaktionen Ihre E-Mail-Adresse an.
</p>""") }
# ----------------------------------------------------------------
help_form['title'] = {
'title' : _(u'Betreff'),
'help' : _(u"""<p>
Tragen Sie hier den Betreff Ihres FAQ-Beitrags ein.
</p>
<p>
Hinweis: Bei einem kürzen Betreff können Sie eher davon ausgehen,
dass Ihr Beitrag gelesen wird.
</p>""") }
# ----------------------------------------------------------------
help_form['text'] = {
'title' : _(u'Frage'),
'help' : _(u"""<p>
Geben Sie hier bitte Ihre Frage ein. Ihnen stehen dabei die wichtigsten
Möglichkeiten eines Editors zur Verfügung. Wenn Sie die Maus
längere Zeit über die Symbole halten, werden in kleinen
Fenstern erläuternde Informationen angezeigt.
</p>""") }
# ----------------------------------------------------------------
help_form['text_more'] = {
'title' : _(u'Antwort'),
'help' : _(u"""<p>
Geben Sie hier bitte die Antwort ein.
</p>
<p>
Ihnen stehen dabei die wichtigsten
Möglichkeiten eines Editors zur Verfügung. Wenn Sie die Maus
längere Zeit über die Symbole halten, werden in kleinen
Fenstern erläuternde Informationen angezeigt.
</p>""") }
# ----------------------------------------------------------------
help_form['moderated_text'] = {
'title': _(u'Moderierte FAQ-Liste'),
'info' : _(u"""<p>
<b>Diese FAQ-Liste ist moderiert. Ihr neuer Beitrag wird erst
angezeigt, nachdem ihn die zuständige Person freigegeben hat.</b>
</p>""") }
# ----------------------------------------------------------------
help_form['tab_base'] = {
'title' : _(u'Basisdaten'),
'info' : _(u"""<p>
Mit diesem Formular legen Sie Ihren Beitrag fest.
</p>""") }
# ----------------------------------------------------------------
help_form['section'] = {
'title' : _(u'Zuordnung in der FAQ-Liste'),
'help' : _(u"""<p>
Hier legen Sie fest, unter welchem Zwischentitel Ihr FAQ-Beitrag in der
<b>übergeordneten</b> FAQ-Liste angezeigt wird. Bei Bedarf können
Sie später mit der Aktion "umordnen" Ihren FAQ-Beitrag weiter nach oben
oder nach unten verschieben.
</p>""") }
|
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common import exceptions
from selenium.webdriver.chrome.options import Options
from pdlearn import user_agent
import os
import itchat
class Mydriver:
def __init__(self, noimg=True, nohead=True):
try:
self.options = Options()
if os.path.exists("./chrome/chrome.exe"): # win
self.options.binary_location = "./chrome/chrome.exe"
elif os.path.exists("/opt/google/chrome/chrome"): # linux
self.options.binary_location = "/opt/google/chrome/chrome"
if noimg:
self.options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度
if nohead:
self.options.add_argument('--headless')
self.options.add_argument('--disable-extensions')
self.options.add_argument('--disable-gpu')
self.options.add_argument('--no-sandbox')
self.options.add_argument('--mute-audio') # 关闭声音
self.options.add_argument('--window-size=400,500')
self.options.add_argument('--window-position=800,0')
self.options.add_argument('--log-level=3')
self.options.add_argument('--user-agent={}'.format(user_agent.getheaders()))
self.options.add_experimental_option('excludeSwitches', ['enable-automation']) # 绕过js检测
self.webdriver = webdriver
if os.path.exists("./chrome/chromedriver.exe"): # win
self.driver = self.webdriver.Chrome(executable_path="./chrome/chromedriver.exe",
chrome_options=self.options)
elif os.path.exists("./chromedriver"): # linux
self.driver = self.webdriver.Chrome(executable_path="./chromedriver",
chrome_options=self.options)
elif os.path.exists("/usr/lib64/chromium-browser/chromedriver"): # linux 包安装chromedriver
self.driver = self.webdriver.Chrome(executable_path="/usr/lib64/chromium-browser/chromedriver",
chrome_options=self.options)
elif os.path.exists("/usr/local/bin/chromedriver"): # linux 包安装chromedriver
self.driver = self.webdriver.Chrome(executable_path="/usr/local/bin/chromedriver",
chrome_options=self.options)
else:
self.driver = self.webdriver.Chrome(chrome_options=self.options)
except:
print("=" * 120)
print("Mydriver初始化失败")
print("=" * 120)
raise
def login(self):
print("正在打开二维码登陆界面,请稍后")
self.driver.get("https://pc.xuexi.cn/points/login.html")
try:
remover = WebDriverWait(self.driver, 30, 0.2).until(
lambda driver: driver.find_element_by_class_name("redflagbox"))
except exceptions.TimeoutException:
print("网络缓慢,请重试")
else:
self.driver.execute_script('arguments[0].remove()', remover)
try:
remover = WebDriverWait(self.driver, 30, 0.2).until(
lambda driver: driver.find_element_by_class_name("header"))
except exceptions.TimeoutException:
print("当前网络缓慢...")
else:
self.driver.execute_script('arguments[0].remove()', remover)
try:
remover = WebDriverWait(self.driver, 30, 0.2).until(
lambda driver: driver.find_element_by_class_name("footer"))
except exceptions.TimeoutException:
print("当前网络缓慢...")
else:
self.driver.execute_script('arguments[0].remove()', remover)
self.driver.execute_script('window.scrollTo(document.body.scrollWidth/2 - 200 , 0)')
itchat.auto_login(hotReload=True)
f = "d:/test.png" # 图片地址
self.driver.get_screenshot_as_file(f);
users = itchat.search_friends(name=u'喻珊')
itchat.send("这是一条系统自动发送的消息,请扫描二维码登录学习强国", toUserName=users[0]["UserName"]);
itchat.send_image(f, toUserName=users[0]["UserName"])
try:
WebDriverWait(self.driver, 270).until(EC.title_is(u"我的学习"))
cookies = self.get_cookies()
return cookies
except:
print("扫描二维码超时")
def dd_login(self, d_name, pwd):
__login_status = False
self.driver.get(
"https://login.dingtalk.com/login/index.htm?"
"goto=https%3A%2F%2Foapi.dingtalk.com%2Fconnect%2Foauth2%2Fsns_authorize"
"%3Fappid%3Ddingoankubyrfkttorhpou%26response_type%3Dcode%26scope%3Dsnsapi"
"_login%26redirect_uri%3Dhttps%3A%2F%2Fpc-api.xuexi.cn%2Fopen%2Fapi%2Fsns%2Fcallback"
)
self.driver.find_elements_by_id("mobilePlaceholder")[0].click()
self.driver.find_element_by_id("mobile").send_keys(d_name)
self.driver.find_elements_by_id("mobilePlaceholder")[1].click()
self.driver.find_element_by_id("pwd").send_keys(<PASSWORD>)
self.driver.find_element_by_id("loginBtn").click()
try:
print("登陆中...")
WebDriverWait(self.driver, 2, 0.1).until(lambda driver: driver.find_element_by_class_name("modal"))
print(self.driver.find_element_by_class_name("modal").find_elements_by_tag_name("div")[0].text)
self.driver.quit()
__login_status = False
except:
__login_status = True
return __login_status
def get_cookies(self):
cookies = self.driver.get_cookies()
return cookies
def set_cookies(self, cookies):
for cookie in cookies:
self.driver.add_cookie({k: cookie[k] for k in cookie.keys()})
def get_url(self, url):
self.driver.get(url)
def go_js(self, js):
self.driver.execute_script(js)
def quit(self):
self.driver.quit() |
<filename>env/lib/python3.5/site-packages/mne/viz/backends/base_renderer.py
"""Core visualization operations."""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: Simplified BSD
from abc import ABCMeta, abstractclassmethod
class _BaseRenderer(metaclass=ABCMeta):
@abstractclassmethod
def __init__(self, fig=None, size=(600, 600), bgcolor=(0., 0., 0.),
name=None, show=False, shape=(1, 1)):
"""Set up the scene."""
pass
@abstractclassmethod
def subplot(self, x, y):
"""Set the active subplot."""
pass
@abstractclassmethod
def scene(self):
"""Return scene handle."""
pass
@abstractclassmethod
def set_interactive(self):
"""Enable interactive mode."""
pass
@abstractclassmethod
def mesh(self, x, y, z, triangles, color, opacity=1.0, shading=False,
backface_culling=False, **kwargs):
"""Add a mesh in the scene.
Parameters
----------
x: array, shape (n_vertices,)
The array containing the X component of the vertices.
y: array, shape (n_vertices,)
The array containing the Y component of the vertices.
z: array, shape (n_vertices,)
The array containing the Z component of the vertices.
triangles: array, shape (n_polygons, 3)
The array containing the indices of the polygons.
color: tuple | str
The color of the mesh as a tuple (red, green, blue) of float
values between 0 and 1 or a valid color name (i.e. 'white'
or 'w').
opacity: float
The opacity of the mesh.
shading: bool
If True, enable the mesh shading.
backface_culling: bool
If True, enable backface culling on the mesh.
kwargs: args
The arguments to pass to triangular_mesh
Returns
-------
surface:
Handle of the mesh in the scene.
"""
pass
@abstractclassmethod
def contour(self, surface, scalars, contours, width=1.0, opacity=1.0,
vmin=None, vmax=None, colormap=None,
normalized_colormap=False, kind='line', color=None):
"""Add a contour in the scene.
Parameters
----------
surface: surface object
The mesh to use as support for contour.
scalars: ndarray, shape (n_vertices,)
The scalar valued associated to the vertices.
contours: int | list
Specifying a list of values will only give the requested contours.
width: float
The width of the lines or radius of the tubes.
opacity: float
The opacity of the contour.
vmin: float | None
vmin is used to scale the colormap.
If None, the min of the data will be used
vmax: float | None
vmax is used to scale the colormap.
If None, the max of the data will be used
colormap:
The colormap to use.
normalized_colormap: bool
Specify if the values of the colormap are between 0 and 1.
kind: 'line' | 'tube'
The type of the primitives to use to display the contours.
color:
The color of the mesh as a tuple (red, green, blue) of float
values between 0 and 1 or a valid color name (i.e. 'white'
or 'w').
"""
pass
@abstractclassmethod
def surface(self, surface, color=None, opacity=1.0,
vmin=None, vmax=None, colormap=None, scalars=None,
backface_culling=False):
"""Add a surface in the scene.
Parameters
----------
surface: surface object
The information describing the surface.
color: tuple | str
The color of the surface as a tuple (red, green, blue) of float
values between 0 and 1 or a valid color name (i.e. 'white'
or 'w').
opacity: float
The opacity of the surface.
vmin: float | None
vmin is used to scale the colormap.
If None, the min of the data will be used
vmax: float | None
vmax is used to scale the colormap.
If None, the max of the data will be used
colormap:
The colormap to use.
scalars: ndarray, shape (n_vertices,)
The scalar valued associated to the vertices.
backface_culling: bool
If True, enable backface culling on the surface.
"""
pass
@abstractclassmethod
def sphere(self, center, color, scale, opacity=1.0,
resolution=8, backface_culling=False,
radius=None):
"""Add sphere in the scene.
Parameters
----------
center: ndarray, shape(n_center, 3)
The list of centers to use for the sphere(s).
color: tuple | str
The color of the sphere as a tuple (red, green, blue) of float
values between 0 and 1 or a valid color name (i.e. 'white'
or 'w').
scale: float
The scaling applied to the spheres. The given value specifies
the maximum size in drawing units.
opacity: float
The opacity of the sphere(s).
resolution: int
The resolution of the sphere created. This is the number
of divisions along theta and phi.
backface_culling: bool
If True, enable backface culling on the sphere(s).
radius: float | None
Replace the glyph scaling by a fixed radius value for each
sphere (not supported by mayavi).
"""
pass
@abstractclassmethod
def tube(self, origin, destination, radius=0.001, color='white',
scalars=None, vmin=None, vmax=None, colormap='RdBu',
normalized_colormap=False, reverse_lut=False):
"""Add tube in the scene.
Parameters
----------
origin: array, shape(n_lines, 3)
The coordinates of the first end of the tube(s).
destination: array, shape(n_lines, 3)
The coordinates of the other end of the tube(s).
radius: float
The radius of the tube(s).
color: tuple | str
The color of the tube as a tuple (red, green, blue) of float
values between 0 and 1 or a valid color name (i.e. 'white'
or 'w').
scalars: array, shape (n_quivers,) | None
The optional scalar data to use.
vmin: float | None
vmin is used to scale the colormap.
If None, the min of the data will be used
vmax: float | None
vmax is used to scale the colormap.
If None, the max of the data will be used
colormap:
The colormap to use.
opacity: float
The opacity of the tube(s).
backface_culling: bool
If True, enable backface culling on the tube(s).
reverse_lut: bool
If True, reverse the lookup table.
Returns
-------
surface:
Handle of the tube in the scene.
"""
pass
@abstractclassmethod
def quiver3d(self, x, y, z, u, v, w, color, scale, mode, resolution=8,
glyph_height=None, glyph_center=None, glyph_resolution=None,
opacity=1.0, scale_mode='none', scalars=None,
backface_culling=False, colormap=None, vmin=None, vmax=None,
line_width=2., name=None):
"""Add quiver3d in the scene.
Parameters
----------
x: array, shape (n_quivers,)
The X component of the position of the quiver.
y: array, shape (n_quivers,)
The Y component of the position of the quiver.
z: array, shape (n_quivers,)
The Z component of the position of the quiver.
u: array, shape (n_quivers,)
The last X component of the quiver.
v: array, shape (n_quivers,)
The last Y component of the quiver.
w: array, shape (n_quivers,)
The last Z component of the quiver.
color: tuple | str
The color of the quiver as a tuple (red, green, blue) of float
values between 0 and 1 or a valid color name (i.e. 'white'
or 'w').
scale: float
The scaling applied to the glyphs. The size of the glyph
is by default calculated from the inter-glyph spacing.
The given value specifies the maximum glyph size in drawing units.
mode: 'arrow', 'cone' or 'cylinder'
The type of the quiver.
resolution: int
The resolution of the glyph created. Depending on the type of
glyph, it represents the number of divisions in its geometric
representation.
glyph_height: float
The height of the glyph used with the quiver.
glyph_center: tuple
The center of the glyph used with the quiver: (x, y, z).
glyph_resolution: float
The resolution of the glyph used with the quiver.
opacity: float
The opacity of the quiver.
scale_mode: 'vector', 'scalar' or 'none'
The scaling mode for the glyph.
scalars: array, shape (n_quivers,) | None
The optional scalar data to use.
backface_culling: bool
If True, enable backface culling on the quiver.
colormap:
The colormap to use.
vmin: float | None
vmin is used to scale the colormap.
If None, the min of the data will be used
vmax: float | None
vmax is used to scale the colormap.
If None, the max of the data will be used
line_width: float
The width of the 2d arrows.
"""
pass
@abstractclassmethod
def text2d(self, x_window, y_window, text, size=14, color='white'):
"""Add 2d text in the scene.
Parameters
----------
x: float
The X component to use as position of the text in the
window coordinates system (window_width, window_height).
y: float
The Y component to use as position of the text in the
window coordinates system (window_width, window_height).
text: str
The content of the text.
size: int
The size of the font.
color: tuple | str
The color of the text as a tuple (red, green, blue) of float
values between 0 and 1 or a valid color name (i.e. 'white'
or 'w').
"""
pass
@abstractclassmethod
def text3d(self, x, y, z, text, width, color='white'):
"""Add 2d text in the scene.
Parameters
----------
x: float
The X component to use as position of the text.
y: float
The Y component to use as position of the text.
z: float
The Z component to use as position of the text.
text: str
The content of the text.
width: float
The width of the text.
color: tuple | str
The color of the text as a tuple (red, green, blue) of float
values between 0 and 1 or a valid color name (i.e. 'white'
or 'w').
"""
pass
@abstractclassmethod
def scalarbar(self, source, title=None, n_labels=4):
"""Add a scalar bar in the scene.
Parameters
----------
source:
The object of the scene used for the colormap.
title: str | None
The title of the scalar bar.
n_labels: int | None
The number of labels to display on the scalar bar.
"""
pass
@abstractclassmethod
def show(self):
"""Render the scene."""
pass
@abstractclassmethod
def close(self):
"""Close the scene."""
pass
@abstractclassmethod
def set_camera(self, azimuth=None, elevation=None, distance=None,
focalpoint=None):
"""Configure the camera of the scene.
Parameters
----------
azimuth: float
The azimuthal angle of the camera.
elevation: float
The zenith angle of the camera.
distance: float
The distance to the focal point.
focalpoint: tuple
The focal point of the camera: (x, y, z).
"""
pass
@abstractclassmethod
def reset_camera(self):
"""Reset the camera properties."""
pass
@abstractclassmethod
def screenshot(self, mode='rgb', filename=None):
"""Take a screenshot of the scene.
Parameters
----------
mode: str
Either 'rgb' or 'rgba' for values to return.
Default is 'rgb'.
filename: str | None
If not None, save the figure to the disk.
"""
pass
@abstractclassmethod
def project(self, xyz, ch_names):
"""Convert 3d points to a 2d perspective.
Parameters
----------
xyz: array, shape(n_points, 3)
The points to project.
ch_names: array, shape(_n_points,)
Names of the channels.
"""
pass
|
<gh_stars>1-10
"""
@author: 代码医生工作室
@公众号:xiangyuejiqiren (内有更多优秀文章及学习资料)
@来源: <PyTorch深度学习和图神经网络(卷 1)——基础知识>配套代码
@配套代码技术支持:bbs.aianaconda.com
Created on Tue Mar 19 22:24:58 2019
"""
import torch
import torchvision
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import transforms
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
img_transform = transforms.Compose([ transforms.ToTensor() ])
def to_img(x):
x = 0.5 * (x + 1)
x = x.clamp(0, 1)
x = x.reshape(x.size(0), 1, 28, 28)
return x
def imshow(img):
npimg = img.numpy()
plt.axis('off')
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
data_dir = './fashion_mnist/'
train_dataset = torchvision.datasets.FashionMNIST(data_dir, train=True,
transform=img_transform,download=True)
train_loader = DataLoader(train_dataset,batch_size=128, shuffle=True)
val_dataset = torchvision.datasets.FashionMNIST(data_dir, train=False,
transform=img_transform)
test_loader = DataLoader(val_dataset, batch_size=10, shuffle=False)
#指定设备
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
class VAE(nn.Module):
def __init__(self,hidden_1=256,hidden_2=256,
in_decode_dim=2,hidden_3=256):
super(VAE, self).__init__()
self.fc1 = nn.Linear(784, hidden_1)
self.fc21 = nn.Linear(hidden_2, 2)
self.fc22 = nn.Linear(hidden_2, 2)
self.fc3 = nn.Linear(in_decode_dim, hidden_3)
self.fc4 = nn.Linear(hidden_3, 784)
def encode(self, x):
h1 = F.relu(self.fc1(x))
return self.fc21(h1), self.fc22(h1)
def reparametrize(self, mean, lg_var):
std = lg_var.exp().sqrt()
eps = torch.FloatTensor(std.size()).normal_().to(device)
eps = torch.FloatTensor(std.size()).normal_().to(device)
return eps.mul(std).add_(mean)
def decode(self, z):
h3 = F.relu(self.fc3(z))
return self.fc4(h3)
def forward(self, x,*arg):
mean, lg_var = self.encode(x)
z = self.reparametrize(mean, lg_var)
return self.decode(z), mean, lg_var
reconstruction_function = nn.MSELoss(size_average=False)
def loss_function(recon_x, x, mean, lg_var):
MSEloss = reconstruction_function(recon_x, x) # mse loss
# loss = 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
# KLD_element = mean.pow(2).add_(lg_var.exp()).mul_(-1).add_(1).add_(lg_var)
# KLD = torch.sum(KLD_element).mul_(-0.5)
KLD = -0.5 * torch.sum(1 + lg_var - mean.pow(2) - lg_var.exp())
return MSEloss*0.5 + KLD
def train(model,num_epochs = 50):
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
display_step = 5
for epoch in range(num_epochs):
model.train()
train_loss = 0
for batch_idx, data in enumerate(train_loader):
img, label = data
img = img.view(img.size(0), -1).to(device)
y_one_hot = torch.zeros(label.shape[0],10).scatter_(1,
label.view(label.shape[0],1),1).to(device)
optimizer.zero_grad()
recon_batch, mean, lg_var = model(img,y_one_hot)
loss = loss_function(recon_batch, img, mean, lg_var)
loss.backward()
train_loss += loss.data
optimizer.step()
if epoch % display_step == 0:
print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(loss.data))
print("完成! cost=",loss.data)
if __name__ == '__main__':
model = VAE().to(device)
train(model,50)
# 可视化结果
sample = iter(test_loader)
images, labels = sample.next()
images2 = images.view(images.size(0), -1)
with torch.no_grad():
pred, mean, lg_var = model(images2.to(device))
pred =to_img( pred.cpu().detach())
rel = torch.cat([images,pred],axis = 0)
imshow(torchvision.utils.make_grid(rel,nrow=10))
test_loader = DataLoader(val_dataset, batch_size=len(val_dataset), shuffle=False)
sample = iter(test_loader)
images, labels = sample.next()
with torch.no_grad():
mean, lg_var = model.encode(images.view(images.size(0), -1).to(device))
z = model.reparametrize(mean, lg_var)
z =z.cpu().detach().numpy()
plt.figure(figsize=(6, 6))
plt.scatter(z[:, 0], z[:, 1], c=labels)
plt.colorbar()
plt.show()
# display a 2D manifold of the digits
n = 15 # figure with 15x15 digits
digit_size = 28
figure = np.zeros((digit_size * n, digit_size * n))
grid_x = norm.ppf(np.linspace(0.05, 0.95, n))
grid_y = norm.ppf(np.linspace(0.05, 0.95, n))
for i, yi in enumerate(grid_x):
for j, xi in enumerate(grid_y):
z_sample= torch.FloatTensor([[xi, yi]]).reshape([1,2]).to(device)
x_decoded = model.decode(z_sample).cpu().detach().numpy()
digit = x_decoded[0].reshape(digit_size, digit_size)
figure[i * digit_size: (i + 1) * digit_size,
j * digit_size: (j + 1) * digit_size] = digit
plt.figure(figsize=(10, 10))
plt.imshow(figure, cmap='Greys_r')
plt.show()
# a =torch.FloatTensor(2,1,2).normal_()
|
#pylint: disable=invalid-name,no-self-use
"""The tests for DrawWrite."""
# Imports {{{
import datetime
import logging
from unittest import mock
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.files.storage import Storage
from django.test import TestCase
from django.utils import timezone
from .models import Chain, DrawLink, Game, Player, WriteLink
from .forms import IndexForm
from . import services
# }}}
logging.disable(logging.CRITICAL)
# GameTests {{{
class GameTests(TestCase):
"""Tests for manipulation of Games."""
def test_game_creation_is_successful(self):
"""
Creating a game should work.
"""
game = services.new_game(name='test')
self.assertIsInstance(game, Game)
def test_game_creation_repeated_name_is_unsuccessful(self):
"""
Creating a game with the same name as one already created should
raise an exception.
"""
name = 'test'
services.new_game(name=name)
second_game = services.new_game(name=name)
self.assertIs(second_game, None)
def test_game_creation_has_not_started(self):
"""
Games should be created in the 'not started' state.
"""
game = services.new_game(name='test')
self.assertIs(game.started, False)
def test_default_time_created_is_valid_time(self):
"""
Creating a game with no specified 'created time' should yield a
game with a valid 'created time' anyway.
"""
game = services.new_game(name='test')
self.assertIsInstance(game.time_created, datetime.datetime)
def test_default_num_players_is_zero(self):
"""
Creating a game should set the default numPlayers to zero.
"""
game = services.new_game(name='test')
self.assertEqual(game.num_players, 0)
def test_cannot_create_player_for_started_game(self):
"""
Creating a player for a started game should throw a
GameAlreadyStarted exception.
"""
game = services.new_game(name='test')
game.started = True
with self.assertRaises(services.GameAlreadyStarted):
services.new_player(game, 'test player', True)
def test_create_new_player_returns_valid_player(self):
"""
Creating a player in a game should return a valid player.
"""
game = services.new_game(name='test')
player = services.new_player(game, '<NAME>', True)
self.assertIsInstance(player, Player)
def test_create_new_player_increases_num_players(self):
"""
Creating a new player should increase numPlayers by one.
"""
game = services.new_game(name='test')
old = game.num_players
services.new_player(game, 'test player', True)
self.assertEqual(old + 1, game.num_players)
def test_create_new_player_sets_name_correctly(self):
"""
Creating a new player should return a player with the correct name.
"""
name = '<NAME>'
game = services.new_game(name='test')
player = services.new_player(game, name, True)
self.assertEqual(name, player.name)
def test_create_new_player_inserts_foreign_key_correctly(self):
"""
Creating a player should return a player with the 'game' field
set to the game on which newPlayer was called.
"""
game = services.new_game(name='test')
player = services.new_player(game, '<NAME>', True)
self.assertEqual(player.game, game)
def test_create_new_player_sets_position_correctly(self):
"""
Creating a player should return a player with the 'position' field
set correctly.
"""
game = services.new_game(name='test')
pos = game.num_players
player = services.new_player(game, '<NAME>', True)
self.assertEqual(player.position, pos)
def test_create_multiple_players_sets_position_correctly(self):
"""
Creating multiple players should return players with increasing
'position' fields.
"""
game = services.new_game(name='test')
num = 5
player = None
for i in range(num):
player = services.new_player(game, 'test player {0}'.format(i), True)
self.assertEqual(player.position, i)
self.assertEqual(game.num_players, num)
def test_create_two_players_with_same_name_in_same_game_errors(self):
"""
Creating two players with the same name in the same game should
cause an exception.
"""
game = services.new_game(name='test')
name = 'test player'
services.new_player(game, name, True)
self.assertIs(services.new_player(game, name, True), None)
# }}}
# ChainTests {{{
class ChainTests(TestCase):
"""Tests for manipulating chains."""
def get_mocked_file(self):
"""
Get a mocked file to read from.
"""
return SimpleUploadedFile('test.jpg', 'file contents!'.encode('utf-8'))
def get_mocked_storage(self):
"""
Get a mocked storage system.
"""
return mock.MagicMock(spec=Storage, name='StorageMock')
def test_chain_creation_is_successful(self):
"""
Creating a chain should work.
"""
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
self.assertIsInstance(chain, Chain)
def test_default_time_created_is_valid_time(self):
"""
Creating a Chain with no arguments should yield a valid
datetime.datetime in timeCreated.
"""
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
self.assertIsInstance(chain.time_created, datetime.datetime)
def test_default_time_created_is_recent(self):
"""
Creating a Chain with no arguments should yield a chain with
timeCreated being in the very recent past.
"""
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
pre_creation = timezone.now()
chain = services.new_chain(player)
post_creation = timezone.now()
self.assertIs(pre_creation < chain.time_created, True)
self.assertIs(post_creation > chain.time_created, True)
def test_default_next_link_position_is_zero(self):
"""
Creating a Chain with no arguments should yield a chain with
nextLinkPosition of zero.
"""
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
self.assertEqual(chain.next_link_position, 0)
def test_new_draw_link_with_even_next_link_position_returns_none(self):
"""
Calling newDrawLink() should return None when the chain's
nextLinkPosition is an even number.
"""
with mock.patch('django.core.files.storage.default_storage._wrapped',
self.get_mocked_storage()):
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
self.assertIs(services.new_draw_link(chain, self.get_mocked_file(), player), None)
chain.next_link_position = 26
self.assertIs(services.new_draw_link(chain, self.get_mocked_file(), player), None)
def test_new_draw_link_with_odd_next_link_position_returns_draw_link(self):
"""
Calling newDrawLink() should return a new DrawLink object when
nextLinkPosition is an even number.
"""
with mock.patch('django.core.files.storage.default_storage._wrapped',
self.get_mocked_storage()):
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
chain.next_link_position = 1
self.assertIsInstance(services.new_draw_link(chain, self.get_mocked_file(), player),
DrawLink)
chain.next_link_position = 27
self.assertIsInstance(services.new_draw_link(chain, self.get_mocked_file(), player),
DrawLink)
def test_new_draw_link_with_even_next_link_position_does_not_increase_next_link_position(self):
"""
Calling newDrawLink() should not increase nextLinkPosition if
nextLinkPosition is even.
"""
with mock.patch('django.core.files.storage.default_storage._wrapped',
self.get_mocked_storage()):
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
services.new_draw_link(chain, self.get_mocked_file(), player)
self.assertEqual(chain.next_link_position, 0)
chain.next_link_position = 26
services.new_draw_link(chain, self.get_mocked_file(), player)
self.assertEqual(chain.next_link_position, 26)
def test_new_draw_link_with_odd_next_link_position_inceases_next_link_position(self):
"""
Calling newDrawLink() should increase nextLinkPosition if
nextLinkPosition is odd.
"""
with mock.patch('django.core.files.storage.default_storage._wrapped',
self.get_mocked_storage()):
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
chain.next_link_position = 1
services.new_draw_link(chain, self.get_mocked_file(), player)
self.assertEqual(chain.next_link_position, 2)
chain.next_link_position = 27
services.new_draw_link(chain, self.get_mocked_file(), player)
self.assertEqual(chain.next_link_position, 28)
def test_new_draw_link_creates_draw_link_with_correct_link_position(self):
"""
Calling newDrawLink() when nextLinkPosition is odd should create
a DrawLink with the previous value of nextLinkPosition.
"""
with mock.patch('django.core.files.storage.default_storage._wrapped',
self.get_mocked_storage()):
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
chain.next_link_position = 1
expect = chain.next_link_position
draw_link = services.new_draw_link(chain, self.get_mocked_file(), player)
self.assertEqual(expect, draw_link.link_position)
chain.next_link_position = 27
expect = chain.next_link_position
draw_link = services.new_draw_link(chain, self.get_mocked_file(), player)
self.assertEqual(expect, draw_link.link_position)
def test_new_write_link_with_even_next_link_position_returns_write_link(self):
"""
Calling newWriteLink() should return a WriteLink if nextLinkPosition
is an even number.
"""
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
self.assertIsInstance(services.new_write_link(chain, 'fake text', player), WriteLink)
chain.next_link_position = 26
self.assertIsInstance(services.new_write_link(chain, 'fake text', player), WriteLink)
def test_new_write_link_with_odd_next_link_position_returns_none(self):
"""
Calling newWriteLink() should return None if nextLinkPosition is an
odd number.
"""
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
chain.next_link_position = 1
self.assertIs(services.new_write_link(chain, 'fake text', player), None)
chain.next_link_position = 27
self.assertIs(services.new_write_link(chain, 'fake text', player), None)
def test_new_write_link_with_even_next_link_position_increases_next_link_position(self):
"""
Calling newWriteLink() should increase nextLinkPosition if nextLinkPosition
is even.
"""
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
services.new_write_link(chain, 'fake text', player)
self.assertEqual(chain.next_link_position, 1)
chain.next_link_position = 26
services.new_write_link(chain, 'fake text', player)
self.assertEqual(chain.next_link_position, 27)
def test_new_write_link_with_odd_next_link_position_does_not_increase_next_link_position(self):
"""
Calling newWriteLink() should not increase nextLinkPosition if nextLinkPosition
is odd.
"""
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
chain.next_link_position = 1
services.new_write_link(chain, 'fake text', player)
self.assertEqual(chain.next_link_position, 1)
chain.next_link_position = 27
services.new_write_link(chain, 'fake text', player)
self.assertEqual(chain.next_link_position, 27)
def test_new_write_link_creates_write_link_with_correct_link_position(self):
"""
Calling newWriteLink() when nextLinePosition is even should create a
WriteLink with the previous value of nextLinePosition.
"""
game = services.new_game(name='test')
player = services.new_player(game, 'test player', True)
chain = services.new_chain(player)
expect = chain.next_link_position
write_link = services.new_write_link(chain, 'fake text', player)
self.assertEqual(expect, write_link.link_position)
chain.next_link_position = 26
expect = chain.next_link_position
write_link = services.new_write_link(chain, 'fake text', player)
self.assertEqual(expect, write_link.link_position)
# }}}
# IndexFormTests {{{
class IndexFormTests(TestCase):
"""Tests for the form that collects initial player data."""
valid_data = ['lower', 'UPPER', 'miXEDcaSE',
'abcdefghijklmnopqrstuvwxyz1234567890_-',
'-_0987654321zyxwvutsrqponmlkjihgfedcba',
]
invalid_data = ['simple*', 'this$is*bad', '`', '\'', '"', '=+',
'<script>alert("hi!");</script>',
]
def test_form_accepts_valid_input(self):
"""
Forms with data that contains only letters, numbers, and spaces
should be valid.
"""
for test_case in self.valid_data:
form = IndexForm(data={
'gamename': test_case,
'username': test_case,
})
try:
self.assertIs(form.is_valid(), True)
except AssertionError:
raise Exception('input: {0}'.format(test_case))
def test_form_discards_invalid_input(self):
"""
Forms with data that contains anything other then letters, numbers,
and spaces shouldn't be valid.
"""
for test_case in self.invalid_data:
form = IndexForm(data={
'gamename': test_case,
'username': test_case,
})
try:
self.assertIs(form.is_valid(), False)
except AssertionError:
raise Exception('input: {0}'.format(test_case))
# }}}
|
#!/usr/bin/env python3
import argparse
import random
import serial
from datetime import datetime, timedelta
from tests.testmtrreader import MtrDataBytesBuilder
def create_argparser():
argparser = argparse.ArgumentParser(
description=(
"Mock MTR supporting spool-all command ('/SA'). "
"Responds with data messages in binary file to serial port."))
argparser.add_argument('port', help='Serial port identifier')
argparser.add_argument(
'-n', type=int, default=100, help='Number of messages to generate')
argparser.add_argument(
'-f', '--file',
help=(
"Don't generate messages, but read from file. "
'(File can be created with devutil-recordmtrdata.py.)'))
argparser.add_argument(
'-v', '--verbose', action='store_true', help='Verbose output')
return argparser
def is_command(cmd_bytes):
return cmd_bytes == b'/ST' or cmd_bytes == b'/SA'
def listen(serial_port):
command_buffer = bytearray()
COMMAND_LENGTH = 3
print("Listening for command on {} ...".format(serial_port.name))
while not is_command(command_buffer):
if len(command_buffer) == COMMAND_LENGTH:
# make room for incoming byte by removing oldest
command_buffer.pop(0)
command_buffer.extend(serial_port.read())
print("Received command {}".format(command_buffer))
return command_buffer
def respond_status(serial_port, mtr_id):
now = datetime.now()
data = bytearray()
data.extend(b'\xFF\xFF\xFF\xFF') # preamble
data.append(55) # status message length
data.append(ord('S')) # status message type
data.extend(mtr_id.to_bytes(2, 'little'))
data.append(now.year % 100)
data.append(now.month)
data.append(now.day)
data.append(now.hour)
data.append(now.minute)
data.append(now.second)
data.extend(b'\x00\x00') # ms
data.append(0) # battery status (0=ok, 1=low)
data.extend(b'\x00\x00\x00\x00') # recent pkgnum
data.extend(b'\x00\x00\x00\x00') # oldest pkgnum
data.extend(b'\x00\x00\x00\x00') # curr sess start
data.extend(b'\x00\x00\x00\x00') # prev1 sess start
data.extend(b'\x00\x00\x00\x00') # prev2 sess start
data.extend(b'\x00\x00\x00\x00') # prev3 sess start
data.extend(b'\x00\x00\x00\x00') # prev4 sess start
data.extend(b'\x00\x00\x00\x00') # prev5 sess start
data.extend(b'\x00\x00\x00\x00') # prev6 sess start
data.extend(b'\x00\x00\x00\x00') # prev7 sess start
data.append(sum(data) % 256)
data.append(0)
num_bytes_written = serial_port.write(data)
print("Wrote {} bytes".format(num_bytes_written))
def respond_with_file(serial_port, source_filename):
with open(source_filename, 'rb') as source_file:
print("Opened file {}".format(source_filename))
data = source_file.read()
print("Read {} bytes".format(len(data)))
num_bytes_written = serial_port.write(data)
print("Wrote {} bytes".format(num_bytes_written))
def respond_with_generated(serial_port, mtr_id, n):
print("Generating {} messages".format(n, serial_port))
now = datetime.now()
course_a = [0, 31, 32, 33, 34, 35, 102, 103, 104, 249]
course_b = [0, 31, 32, 33, 35, 103, 104, 249]
course_c = [0, 65, 66, 67, 60, 61, 62, 249]
courses = [course_a, course_b, course_c]
for i in range(1, n+1):
card_id = random.randint(
1, int.from_bytes(bytes(b'\xFF\xFF\xFF'), 'little'))
splits = random_splits_for_course(random.choice(courses))
datetime_read = now - timedelta(minutes=(n - i)*2)
message_bytes = mtr_bytes(mtr_id, card_id, splits, datetime_read, i)
if is_verbose:
print(message_bytes.hex())
num_bytes_written = serial_port.write(message_bytes)
if is_verbose:
print("{} bytes sent".format(num_bytes_written))
def mtr_bytes(mtr_id, card_id, splits, datetime_read, package_num):
return MtrDataBytesBuilder(
mtr_id, card_id, splits, datetime_read, package_num
).to_bytes()
def random_splits_for_course(course):
split_times = [0]
for j in range(1, len(course)):
split_times.append(split_times[j-1] + random.randint(60, 900))
return list(zip(course, split_times))
args = create_argparser().parse_args()
is_verbose = args.verbose
test_serial = serial.Serial(port=args.port, baudrate=9600)
while True:
cmd = listen(test_serial)
mtr_id = random.randint(1, int.from_bytes(bytes(b'\xFF\xFF'), 'little'))
if cmd == b'/ST':
respond_status(test_serial, mtr_id)
elif cmd == b'/SA':
if args.file:
respond_with_file(test_serial, args.file)
else:
respond_with_generated(test_serial, mtr_id, args.n)
|
import torch
import pyro
import pyro.distributions as dist
from torch.distributions import constraints
from pyro import poutine
from pyro.infer import SVI, Trace_ELBO, TraceEnum_ELBO, config_enumerate, infer_discrete
from pyro.infer.autoguide import AutoDiagonalNormal
from pyro.ops.indexing import Vindex
import pyro.poutine as poutine
from pyro.infer import MCMC, NUTS
'''
Implements Animal Crossing: New Horizons turnip pricing as a model
in Pyro.
Based primarily on the data mining by
https://gist.github.com/Treeki/85be14d297c80c8b3c0a76375743325b
and the writeup at
https://tinyurl.com/y76p2zzk.
'''
pattern_index_to_name = [
"Random",
"Large Spike",
"Decreasing",
"Small Spike"
]
pattern_transition_matrix = torch.tensor(
[[0.2, 0.3, 0.15, 0.35],
[0.5, 0.05, 0.2, 0.25],
[0.25, 0.45, 0.05, 0.25],
[0.45, 0.25, 0.15, 0.15]]).T
def calculate_turnip_prices():
# Random integer base price on [90, 110]
basePrice = pyro.sample(
"basePrice",
dist.Uniform(90, 110))
# The prior over patterns is the steady state of
# the transition matrix
out = torch.eig(pattern_transition_matrix, eigenvectors=True)
assert(torch.isclose(out.eigenvalues[0, 0], torch.tensor([1.])))
prior_over_patterns = out.eigenvectors[:, 0]
prior_over_patterns = prior_over_patterns / torch.sum(prior_over_patterns)
# Select previous pattern from the steady-state prior
prevPattern = pyro.sample(
"prevPattern",
dist.Categorical(prior_over_patterns),
infer={"enumerate": "sequential"})
# And select next pattern based on the transition probabilities
nextPattern = pyro.sample(
"nextPattern",
dist.Categorical(pattern_transition_matrix[prevPattern, :]),
infer={"enumerate": "sequential"},
obs=torch.tensor([0]))
print("basePrice: ", basePrice)
print("prevPattern: ", prevPattern)
print("nextPattern: ", nextPattern)
# Now observe the 12 half-day prices based on the pattern.
if nextPattern == 0:
### Random: high, decreasing, high, decreasing, high
random_decPhaseLen1 = pyro.sample("random_decPhase1Len",
dist.Categorical(torch.tensor([0.5, 0.5])),
infer={"enumerate": "sequential"}) + 2
random_decPhaseLen2 = 5 - random_decPhaseLen1
random_hiPhaseLen1 = pyro.sample("random_hiPhase1Len",
dist.Categorical(torch.ones(7)),
infer={"enumerate": "sequential"})
random_hiPhaseLen2and3 = 7 - random_hiPhaseLen1
random_hiPhaseLen3 = pyro.sample("random_hiPhaseLen3",
dist.Categorical(torch.ones(random_hiPhaseLen2and3)),
infer={"enumerate": "sequential"})
sellprices = []
for k in range(random_hiPhaseLen1):
rate = pyro.sample("random_hiPhase1_rate_%d" % k, dist.Uniform(0.9, 1.4))
sellprices.append(rate * basePrice)
rate = pyro.sample("random_decPhase1_initial_rate",
dist.Uniform(0.6, 0.8))
for k in range(random_decPhaseLen1):
sellprices.append(rate * basePrice)
rate -= 0.04
rate -= pyro.sample("random_decPhase1_dec_%d" % k, dist.Uniform(0.0, 0.06))
for k in range(random_hiPhaseLen2and3 - random_hiPhaseLen3):
rate = pyro.sample("random_hiPhase2_rate_%d" % k, dist.Uniform(0.9, 1.4))
sellprices.append(rate * basePrice)
rate = pyro.sample("random_decPhase2_initial_rate",
dist.Uniform(0.6, 0.8))
for k in range(random_decPhaseLen2):
sellprices.append(rate * basePrice)
rate -= 0.04
rate -= pyro.sample("random_decPhase2_dec_%d" % k, dist.Uniform(0.0, 0.06))
for k in range(random_hiPhaseLen3):
rate = pyro.sample("random_hiPhase3_rate_%d" % k, dist.Uniform(0.9, 1.4))
sellprices.append(rate * basePrice)
if len(sellprices[0].shape) >= 1:
sellprices = torch.stack(sellprices, dim=1)
else:
sellprices = torch.stack(sellprices).reshape(1, 12)
sellprices = torch.ceil(sellprices)
print("Random sellprices: ", sellprices)
elif nextPattern == 1:
### Pattern 1: Large Spike
sellprices = []
large_spike_peakStart = pyro.sample("large_spike_peakStart",
dist.Categorical(torch.ones(7))) + 1
rate = pyro.sample("large_spike_initial_rate",
dist.Uniform(0.85, 0.9))
for k in range(large_spike_peakStart):
sellprices.append(rate * basePrice)
rate -= 0.03
rate -= pyro.sample("large_spike_dec_%d" % k, dist.Uniform(0., 0.02))
sellprices.append(pyro.sample("large_spike_rate_1", dist.Uniform(0.9, 1.4)) * basePrice)
sellprices.append(pyro.sample("large_spike_rate_2", dist.Uniform(1.4, 2.0)) * basePrice)
sellprices.append(pyro.sample("large_spike_rate_3", dist.Uniform(2.0, 6.0)) * basePrice)
sellprices.append(pyro.sample("large_spike_rate_4", dist.Uniform(1.4, 2.0)) * basePrice)
sellprices.append(pyro.sample("large_spike_rate_5", dist.Uniform(0.9, 1.4)) * basePrice)
for k in range(12 - large_spike_peakStart - 5):
sellprices.append(pyro.sample("large_spike_fin_rate_%d" % k, dist.Uniform(0.4, 0.9)) * basePrice)
sellprices = torch.ceil(torch.stack(sellprices))
print("Large spike sellprices: ", sellprices)
elif nextPattern == 2:
### Pattern 2: Decreasing
sellprices = []
rate = 0.9
rate -= pyro.sample("decreasing_dec_init", dist.Uniform(0.0, 0.05))
for k in range(12):
sellprices.append(rate * basePrice)
rate -= 0.03
rate -= pyro.sample("decreasing_dec_%d" % k, dist.Uniform(0.0, 0.02))
sellprices = torch.ceil(torch.stack(sellprices))
print("Decreasing sellprices: ", sellprices)
elif nextPattern == 3:
### Pattern 3: Small Spike
sellprices = []
small_spike_peakStart = pyro.sample("small_spike_peakStart",
dist.Categorical(torch.ones(8)))
rate = pyro.sample("small_spike_initial_rate",
dist.Uniform(0.4, 0.9))
for k in range(small_spike_peakStart):
sellprices.append(rate * basePrice)
rate -= 0.03
rate -= pyro.sample("small_spike_dec", dist.Uniform(0., 0.02))
sellprices.append(pyro.sample("small_spike_rate_1", dist.Uniform(0.9, 1.4)) * basePrice)
sellprices.append(pyro.sample("small_spike_rate_2", dist.Uniform(0.9, 1.4)) * basePrice)
rate = pyro.sample("small_spike_rate_spike_ub", dist.Uniform(1.4, 2.0))
sellprices.append(pyro.sample("small_spike_rate_spike_pre", dist.Uniform(1.4, rate)) * basePrice - 1)
sellprices.append(rate * basePrice)
sellprices.append(pyro.sample("small_spike_rate_spike_post", dist.Uniform(1.4, rate)) * basePrice - 1)
rate = pyro.sample("small_spike_rate_post_spike", dist.Uniform(0.4, 0.9))
for k in range(12 - small_spike_peakStart - 5):
sellprices.append(rate * basePrice)
rate -= 0.03
rate -= pyro.sample("small_spike_final_dec_%d" % k, dist.Uniform(0., 0.02))
sellprices = torch.ceil(torch.stack(sellprices))
print("Small spike sellprices: ", sellprices)
else:
raise ValueError("Invalid nextPattern %d" % nextPattern)
pyro.sample("obs", dist.Delta(sellprices).to_event(1))
if __name__ == "__main__":
calculate_turnip_prices()
conditioned_model = poutine.condition(
calculate_turnip_prices,
data={"obs": torch.tensor([87., 83., 79., 75., 72., 68., 64., 106., 115., 144., 185., 138.])})
nuts_kernel = NUTS(conditioned_model)
mcmc = MCMC(nuts_kernel,
num_samples=1000,
warmup_steps=100,
num_chains=1)
mcmc.run()
mcmc.summary(prob=0.5)
|
from django.test import TestCase
from dcim.models import Site
class NaturalOrderByManagerTest(TestCase):
"""
Ensure consistent natural ordering given myriad sample data. We use dcim.Site as our guinea pig because it's simple.
"""
def setUp(self):
return
def evaluate_ordering(self, names):
# Create the Sites
Site.objects.bulk_create(
Site(name=name, slug=name.lower()) for name in names
)
# Validate forward ordering
self.assertEqual(
names,
list(Site.objects.values_list('name', flat=True))
)
# Validate reverse ordering
self.assertEqual(
list(reversed(names)),
list(Site.objects.reverse().values_list('name', flat=True))
)
def test_leading_digits(self):
self.evaluate_ordering([
'1Alpha',
'1Bravo',
'1Charlie',
'9Alpha',
'9Bravo',
'9Charlie',
'10Alpha',
'10Bravo',
'10Charlie',
'99Alpha',
'99Bravo',
'99Charlie',
'100Alpha',
'100Bravo',
'100Charlie',
'999Alpha',
'999Bravo',
'999Charlie',
])
def test_trailing_digits(self):
self.evaluate_ordering([
'Alpha1',
'Alpha9',
'Alpha10',
'Alpha99',
'Alpha100',
'Alpha999',
'Bravo1',
'Bravo9',
'Bravo10',
'Bravo99',
'Bravo100',
'Bravo999',
'Charlie1',
'Charlie9',
'Charlie10',
'Charlie99',
'Charlie100',
'Charlie999',
])
def test_leading_and_trailing_digits(self):
self.evaluate_ordering([
'1Alpha1',
'1Alpha9',
'1Alpha10',
'1Alpha99',
'1Alpha100',
'1Alpha999',
'1Bravo1',
'1Bravo9',
'1Bravo10',
'1Bravo99',
'1Bravo100',
'1Bravo999',
'1Charlie1',
'1Charlie9',
'1Charlie10',
'1Charlie99',
'1Charlie100',
'1Charlie999',
'9Alpha1',
'9Alpha9',
'9Alpha10',
'9Alpha99',
'9Alpha100',
'9Alpha999',
'9Bravo1',
'9Bravo9',
'9Bravo10',
'9Bravo99',
'9Bravo100',
'9Bravo999',
'9Charlie1',
'9Charlie9',
'9Charlie10',
'9Charlie99',
'9Charlie100',
'9Charlie999',
'10Alpha1',
'10Alpha9',
'10Alpha10',
'10Alpha99',
'10Alpha100',
'10Alpha999',
'10Bravo1',
'10Bravo9',
'10Bravo10',
'10Bravo99',
'10Bravo100',
'10Bravo999',
'10Charlie1',
'10Charlie9',
'10Charlie10',
'10Charlie99',
'10Charlie100',
'10Charlie999',
'99Alpha1',
'99Alpha9',
'99Alpha10',
'99Alpha99',
'99Alpha100',
'99Alpha999',
'99Bravo1',
'99Bravo9',
'99Bravo10',
'99Bravo99',
'99Bravo100',
'99Bravo999',
'99Charlie1',
'99Charlie9',
'99Charlie10',
'99Charlie99',
'99Charlie100',
'99Charlie999',
'100Alpha1',
'100Alpha9',
'100Alpha10',
'100Alpha99',
'100Alpha100',
'100Alpha999',
'100Bravo1',
'100Bravo9',
'100Bravo10',
'100Bravo99',
'100Bravo100',
'100Bravo999',
'100Charlie1',
'100Charlie9',
'100Charlie10',
'100Charlie99',
'100Charlie100',
'100Charlie999',
'999Alpha1',
'999Alpha9',
'999Alpha10',
'999Alpha99',
'999Alpha100',
'999Alpha999',
'999Bravo1',
'999Bravo9',
'999Bravo10',
'999Bravo99',
'999Bravo100',
'999Bravo999',
'999Charlie1',
'999Charlie9',
'999Charlie10',
'999Charlie99',
'999Charlie100',
'999Charlie999',
])
|
<reponame>cdeck3r/3DScanner<gh_stars>1-10
#
# Testinfra testcases to validate the autosetup run.
#
# Author: cdeck3r
#
import pytest
#####################################################
# Tests
#####################################################
@pytest.mark.usefixtures("camnode_ssh_config")
class TestAutosetupCamnode:
@pytest.mark.parametrize('nodetype', ['camnode'])
def test_hostname(self, pytestconfig, host, nodetype):
hostname = pytestconfig.getini(nodetype.lower())
assert host.run("hostname").stdout.rstrip() == hostname
def test_booter_done(self, host):
assert host.file('/boot/booter.done').exists
def test_ssh_avahi_service(self, host):
assert host.file('/etc/avahi/services/ssh.service').exists
assert host.file('/etc/avahi/services/ssh.service').mode == 0o644
@pytest.mark.parametrize('nodetype', ['camnode'])
def test_autosetup_nodetype(self, host, nodetype):
assert host.file('/boot/autosetup/NODETYPE').exists
assert host.file('/boot/autosetup/NODETYPE').contains(nodetype.upper())
def test_autosetup_git_installed(self, host):
pkg = host.package('git')
assert pkg.is_installed
assert pkg.version.startswith('1:2.20')
def test_autosetup_repo_exists(self, host):
assert host.file('/boot/autosetup/3DScanner/.git').is_directory
def test_autosetup_install_scripts_exists(self, host):
assert host.file('/boot/autosetup/3DScanner/src/raspi-autosetup').is_directory
assert host.file(
'/boot/autosetup/3DScanner/src/raspi-autosetup/install_commons.sh'
).exists
assert host.file(
'/boot/autosetup/3DScanner/src/raspi-autosetup/install_camnode.sh'
).exists
assert host.file(
'/boot/autosetup/3DScanner/src/raspi-autosetup/install_centralnode.sh'
).exists
def test_repo_branch(self, host):
"""Test the branch the repository's head points to.
If there is a `/boot/BRANCH` file, the repo head is
equal the branch from this file. Allowed values are `dev` or `master`.
Otherwise the repo's head points to the master branch.
"""
git_head = '/boot/autosetup/3DScanner/.git/HEAD'
if host.file('/boot/BRANCH').exists:
branch = host.run('head -1 /boot/BRANCH').stdout.rstrip()
if branch == 'dev':
assert (
host.run('head -1 ' + git_head).stdout.rstrip()
== 'ref: refs/heads/dev'
)
elif branch == 'master':
assert (
host.run('head -1 ' + git_head).stdout.rstrip()
== 'ref: refs/heads/master'
)
else:
assert False, 'No valid branch: ' + branch
else:
assert (
host.run('head -1 ' + git_head).stdout.rstrip()
== 'ref: refs/heads/master'
)
def test_autosetup_python_installed(self, host):
pkg = host.package('python3')
assert pkg.is_installed
assert pkg.version.startswith('3.7')
def test_autosetup_pip3_installed(self, host):
pkg = host.package('python3-pip')
assert pkg.is_installed
def test_autosetup_raspistill_installed(self, host):
exec_file = '/usr/bin/raspistill'
if host.file(exec_file).is_symlink:
exec_file = host.file('/usr/bin/raspistill').linked_to
assert host.file(exec_file).exists
assert host.file(exec_file).mode == 0o755
def test_autosetup_mosquittoclients_installed(self, host):
pkg = host.package('mosquitto-clients')
assert pkg.is_installed
def test_autosetup_homie4_installed(self, host):
assert (
host.run('pip3 freeze | grep Homie4').stdout.rstrip().startswith('Homie4')
)
def test_autosetup_camera(self, host):
assert host.run('sudo raspi-config nonint get_camera').stdout.rstrip() == '0'
def test_avahi_resolve_name_conflict_cronjob(self, host):
jobfile = 'avahi-resolve-name-conflict.sh'
assert host.run('sudo ls -l /root/' + jobfile).succeeded
assert (
host.run('sudo ls /root/' + jobfile).stdout.rstrip() == '/root/' + jobfile
)
assert (
host.run('sudo crontab -l | grep ' + jobfile)
.stdout.rstrip()
.startswith('@reboot sleep 60 && /root/' + jobfile)
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.