id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7 values |
|---|---|---|
/EasyDeL-0.0.29-py3-none-any.whl/EasyDel/trainer/fsdp_train.py | import dataclasses
import functools
import os
import time
import typing
import IPython.display
from fjutils.easylm import blockwise_cross_entropy, cross_entropy_loss_and_accuracy
import wandb
from datasets import Dataset
from EasyDel.trainer.config import TrainArguments
import jax
import flax
import optax
from transformers import FlaxAutoModelForCausalLM, AutoConfig
from IPython.display import clear_output
from tqdm import tqdm
from EasyDel.utils.utils import Timers
from EasyDel.smi import initialise_tracking, get_mem
from jax.experimental.pjit import pjit, with_sharding_constraint
from jax.sharding import PartitionSpec
from flax.training import train_state
from jax import numpy as jnp
from torch.utils.data import DataLoader
from fjutils import match_partition_rules, make_shard_and_gather_fns, StreamingCheckpointer, count_params
from EasyDel.utils.utils import prefix_print
def calculate_accuracy(predictions: jax.Array, targets: jax.Array):
predicted_classes = jnp.argmax(predictions, axis=-1)
correct_predictions = (predicted_classes == targets).sum()
total_predictions = targets.shape[0]
accuracy = correct_predictions / total_predictions
return accuracy
def fsdp_train_step(state, batch):
batch = with_sharding_constraint(batch, PartitionSpec(('dp', 'fsdp')))
def calculate_loss(params):
labels = batch.pop('labels')
logits = state.apply_fn(params=params, **batch,
return_dict=True).logits
loss, accuracy = cross_entropy_loss_and_accuracy(
logits[:, :-1, :], labels, batch['attention_mask'].astype(jnp.float32)[:, 1:]
)
return loss, accuracy
grad_fn = jax.value_and_grad(calculate_loss, has_aux=True)
(loss__, accuracy__), grad = grad_fn(state.params)
state = state.apply_gradients(grads=grad)
return state, loss__, accuracy__
def fsdp_eval_step(state, batch_eval):
batch_eval = with_sharding_constraint(
batch_eval,
PartitionSpec(
('dp', 'fsdp'))
)
def calculate_loss(params):
labels = batch_eval.pop('labels')
logits = state.apply_fn(params=params, **batch_eval,
return_dict=True).logits
loss, accuracy = cross_entropy_loss_and_accuracy(
logits[:, :-1, :], labels, batch_eval['attention_mask'].astype(jnp.float32)[:, 1:]
)
return loss, accuracy
loss__, accuracy__ = calculate_loss(state.params)
return loss__, accuracy__
def predict(state, input_ids):
input_ids = with_sharding_constraint(input_ids, PartitionSpec(('dp', 'fsdp')))
pred = state.apply_fn(params=state.params, input_ids=input_ids, return_dict=True)
token = jnp.argmax(jax.nn.softmax(pred.logits)[:, -1, :])
input_ids = jnp.concatenate([input_ids, token.reshape(1, -1)], axis=-1)
return input_ids
@dataclasses.dataclass
class OutputFineTuner:
train_state: typing.Any
predict_fun: typing.Any
mesh: typing.Any
ckpt_stream: typing.Any
gather_fns: typing.Any
shard_fns: typing.Any
last_save_file_name: str
class CausalLMTrainer:
def __init__(self,
arguments: TrainArguments,
dataset_train: Dataset,
dataset_eval: Dataset = None,
finetune: bool = True,
ckpt_path: typing.Union[str, os.PathLike] = None,
_do_init_fns: bool = True
):
self.timer = None
self.dataloader_train = None
self.dataloader_eval = None
self.model = None
self.wandb_runtime = None
self.max_steps_train = None
self.max_steps_eval = None
self.config = None
self.scheduler = None
self.tx = None
self.sharded_create_from_params_fn = None
self.sharded_train_step_fn = None
self.sharded_predict = None
self.mesh = None
self.ckpt_streamer = None
self.init_fn = None
self.train_state_shape = None
self.train_state_partition_spec = None
self.arguments = arguments
self.dataset_train = dataset_train
self.dataset_eval = dataset_eval
self.finetune = finetune
self.ckpt_path = ckpt_path
self.dtype = arguments.dtype
self.param_dtype = arguments.param_dtype
if finetune:
if ckpt_path is None:
prefix_print(
'Warning',
'In case of using finetune = True and Passing ckpt_path = None you should pass parameters'
'in train function'
)
if _do_init_fns:
self.init_functions()
else:
prefix_print('Warning', 'you have set _do_init_fns to False so function will not me initialized you have '
f'to do in manually (simply with trainer.init_functions() )')
def __str__(self):
string = f'CausalLMTrainer('
for k, v in self.__dict__.items():
if isinstance(v, typing.Callable):
def string_func(it_self):
string_ = f'{it_self.__class__.__name__}(\n'
for k_, v_ in it_self.__dict__.items():
string_ += f'\t\t{k_} : {v_}\n'
string_ += '\t)'
return string_
try:
v.__str__ = string_func
v = v.__str__(v)
except RuntimeError:
pass
string += f'\n\t{k} : {v}'
string += ')'
return string
def __repr__(self):
return self.__str__()
@staticmethod
def finish():
wandb.finish()
def init_functions(self):
self.wandb_runtime = self.arguments.get_wandb_init() if self.arguments.use_wandb else None
self.timer = Timers(
use_wandb=False,
tensorboard_writer=self.arguments.get_board()
)
self.timer(
'configure dataloaders'
).start()
self.dataloader_train, self.max_steps_train, \
self.dataloader_eval, self.max_steps_eval = self.configure_dataloader()
self.timer(
'configure dataloaders'
).stop()
self.timer.log(['configure dataloaders'])
self.timer(
'configure Model ,Optimizer ,Scheduler and Config'
).start()
self.model, self.tx, self.scheduler, self.config = self.configure_model()
self.timer(
'configure Model ,Optimizer ,Scheduler and Config'
).stop()
self.timer.log(['configure Model ,Optimizer ,Scheduler and Config'])
self.timer(
'configure functions and sharding them'
).start()
funcs = self.configure_functions()
self.sharded_create_from_params_fn = funcs[0]
self.sharded_train_step_fn = funcs[1]
self.sharded_predict = funcs[2]
self.mesh = funcs[3]
self.ckpt_streamer = funcs[4]
self.init_fn = funcs[5]
self.timer(
'configure functions and sharding them'
).stop()
self.timer.log(['configure functions and sharding them'])
def configure_dataloader(self):
def collate_fn(batch):
rs = {}
for key in batch[0].keys():
ssp = [jnp.array(f[key])[..., -self.arguments.max_length:] for f in batch]
rs[key] = jnp.stack(ssp).reshape(-1, ssp[0].shape[-1])
return rs
dataloader_train = DataLoader(self.dataset_train, collate_fn=collate_fn,
batch_size=self.arguments.total_batch_size, drop_last=True)
max_steps_train = self.arguments.num_train_epochs * len(
dataloader_train) if self.arguments.max_steps is None else self.arguments.max_steps
if self.dataset_eval is not None and self.arguments.do_eval:
dataloader_eval = DataLoader(self.dataset_eval, collate_fn=collate_fn,
batch_size=self.arguments.total_batch_size, drop_last=True)
max_steps_eval = len(
dataloader_eval) if self.arguments.max_steps is None else self.arguments.max_steps
else:
dataloader_eval, max_steps_eval = None, 0
return dataloader_train, max_steps_train, dataloader_eval, max_steps_eval
def configure_model(self):
extra_configs = {} if self.arguments.extra_configs is None else self.arguments.extra_configs
if self.arguments.model_class is None:
config = AutoConfig.from_pretrained(self.arguments.model_id, trust_remote_code=True
, gradient_checkpointing=self.arguments.gradient_checkpointing,
use_pjit_attention_force=self.arguments.use_pjit_attention_force,
**extra_configs
)
assert hasattr(config, 'get_partition_rules')
model = FlaxAutoModelForCausalLM.from_config(config, trust_remote_code=True, dtype=self.arguments.dtype,
param_dtype=self.arguments.param_dtype,
_do_init=False)
else:
assert self.arguments.custom_rule is not None, 'if you are using custom model to init you must' \
' pass custom_rule for partition rules '
self.arguments.configs_to_init_model_class[
'config'].use_pjit_attention_force = self.arguments.use_pjit_attention_force
model = self.arguments.model_class(
**self.arguments.configs_to_init_model_class,
_do_init=False
)
config = self.arguments.configs_to_init_model_class['config']
tx, scheduler = self.arguments.get_optimizer_and_scheduler(self.max_steps_train)
return model, tx, scheduler, config
def configure_functions(self):
def init_fn():
params__ = self.model.init_weights(jax.random.PRNGKey(0), (1, self.arguments.max_length))
if self.arguments.dtype == jnp.bfloat16:
params__ = self.model.to_bf16(params__)
elif self.arguments.dtype == jnp.float16:
params__ = self.model.to_fp16(params__)
return train_state.TrainState.create(
tx=self.tx,
params=flax.core.freeze({'params': params__}),
apply_fn=self.model.__call__
)
def create_train_state_from_params(params_):
return train_state.TrainState.create(
tx=self.tx,
apply_fn=self.model.__call__,
params=params_
)
if self.arguments.loss_remat != '':
blockwise_cross = functools.partial(
blockwise_cross_entropy,
chunk_size=self.arguments.loss_chunk,
policy=self.arguments.loss_remat
)
loss_fn = blockwise_cross
else:
loss_fn = cross_entropy_loss_and_accuracy
def fsdp_train_step_(state, batch):
batch = with_sharding_constraint(batch, PartitionSpec(('dp', 'fsdp')))
def calculate_loss(params):
labels = batch.pop('labels')
logits = state.apply_fn(params=params, **batch,
return_dict=True).logits[:, :-1, :]
loss, accuracy = loss_fn(
logits, labels, batch['attention_mask'].astype(jnp.float32)[:, 1:]
)
return loss, accuracy
grad_fn = jax.value_and_grad(calculate_loss, has_aux=True)
(loss__, accuracy__), grad = grad_fn(state.params)
state = state.apply_gradients(grads=grad)
return state, loss__, accuracy__
train_state_shape = jax.eval_shape(init_fn)
train_state_partition_spec = match_partition_rules(
self.config.get_partition_rules(
fully_fsdp=self.arguments.fully_fsdp) if self.arguments.custom_rule is None else self.arguments.custom_rule,
train_state_shape)
sharded_create_from_params_fn = pjit(
create_train_state_from_params,
in_shardings=(train_state_partition_spec.params,),
out_shardings=train_state_partition_spec,
donate_argnums=(0,)
)
sharded_train_step_fn = pjit(
fsdp_train_step_,
in_shardings=(train_state_partition_spec, PartitionSpec()),
out_shardings=(train_state_partition_spec, PartitionSpec(), PartitionSpec()),
donate_argnums=(0, 0),
)
sharded_predict = pjit(predict, out_shardings=PartitionSpec(),
in_shardings=(train_state_partition_spec, PartitionSpec()))
mesh = self.arguments.get_mesh()
self.arguments.ckpt_path_exists()
ckpt_streamer = self.arguments.get_streaming_checkpointer()
self.train_state_partition_spec = train_state_partition_spec
self.train_state_shape = train_state_shape
return sharded_create_from_params_fn, sharded_train_step_fn, sharded_predict, mesh, ckpt_streamer, init_fn
def train(self, model_parameters: flax.core.FrozenDict = None) -> OutputFineTuner:
dir_prefix: str = '/dev/shm'
if self.arguments.track_memory:
initialise_tracking(dir_prefix=dir_prefix)
with self.mesh:
if self.finetune:
shard_fns, gather_fns = make_shard_and_gather_fns(self.train_state_partition_spec,
dtype_specs=self.dtype)
if model_parameters is None:
prefix_print(
'Action', f'Loading Model From {self.ckpt_path}'
)
_, params = StreamingCheckpointer.load_trainstate_checkpoint(
f'params::{self.ckpt_path}', self.train_state_shape, shard_fns
)
if self.arguments.remove_ckpt_after_load:
os.remove(self.ckpt_path)
else:
prefix_print(
'Action', f'Sharding Passed Parameters'
)
from flax.core import unfreeze
if not isinstance(model_parameters, flax.core.FrozenDict):
prefix_print(
'Warning', 'Model Parameters should be like FrozenDict({"params" : params}) make sure to '
'pass as type FrozenDict in case of not getting UnExcepted Errors '
)
params = model_parameters if not self.arguments.do_shard_fns else jax.tree_util.tree_map(
lambda f, x: f(x), shard_fns.params,
model_parameters)
sharded_train_state_ = self.sharded_create_from_params_fn(params)
count_params(sharded_train_state_.params)
else:
sharded_train_state_ = self.init_fn()
count_params(sharded_train_state_.params)
pbar = tqdm(total=self.max_steps_train)
i = sharded_train_state_.step.tolist()
losses = []
accuracies = []
pbar.update(sharded_train_state_.step.tolist())
learning_rates = []
if self.arguments.use_wandb:
self.wandb_runtime.log(
{
'model billion parameters': sum(
i.size for i in
jax.tree_util.tree_flatten(flax.core.unfreeze(sharded_train_state_.params))[0]) / 1e9
}
)
try:
for ep in range(self.arguments.num_train_epochs):
for batch in self.dataloader_train:
i += 1
if i < self.max_steps_train:
batch['labels'] = batch['input_ids'][..., 1:]
for ssb in self.arguments.ids_to_pop_from_dataset:
_ = batch.pop(ssb, None)
time_s = time.time()
sharded_train_state_, loss, accuracy = self.sharded_train_step_fn(sharded_train_state_,
batch
)
ttl_time = time.time() - time_s
losses.append(loss)
learning_rates.append(self.scheduler(i).tolist())
accuracies.append(accuracy)
if self.arguments.track_memory:
mem_res = get_mem(dir_prefix=dir_prefix)
else:
mem_res = 'Tracking Option is OFF'
pbar.update(1)
if self.arguments.use_wandb:
self.wandb_runtime.log(
{
'loss': loss.tolist(),
'learning_rate': self.scheduler(sharded_train_state_.step.tolist()).tolist(),
'step': sharded_train_state_.step.tolist(),
'step time': ttl_time,
'perplexity': jnp.exp(loss).tolist(),
'accuracy': accuracy.tolist(),
'avg_accuracy': (sum(accuracies) / len(accuracies)).tolist(),
'mem_res': mem_res
}
)
if self.arguments.track_memory:
IPython.display.clear_output(True)
pbar.display(mem_res)
pbar.set_postfix(loss=loss,
learning_rate=self.scheduler(sharded_train_state_.step.tolist()).tolist(),
step=sharded_train_state_.step.tolist(),
perplexity=jnp.exp(loss).tolist(),
accuracy=accuracy,
)
else:
break
if self.arguments.save_steps is not None and i % self.arguments.save_steps == 0:
filename = f'{self.arguments.model_name}-{sum(losses) / len(losses)}-{i}'
print(f'Saving Model to \033[1;30m{filename}\033[1;0m')
self.ckpt_streamer.save_checkpoint(sharded_train_state_.params['params'],
filename,
gather_fns=gather_fns.params['params'])
except KeyboardInterrupt:
print(
'\033[1;30m KeyboardInterrupt At training model Will return current state of the model * \033[1;0m')
if self.arguments.do_eval:
if self.dataset_eval is not None:
pbar_eval = tqdm(total=self.max_steps_eval)
for i_eval, batch_eval in enumerate(self.dataloader_eval):
_ = batch_eval.pop('token_type_ids', None)
batch['labels'] = batch['input_ids'][..., 1:]
for i in self.arguments.ids_to_pop_from_dataset:
_ = batch_eval.pop(i, None)
loss_eval, accuracy = fsdp_eval_step(sharded_train_state_, batch_eval)
pbar_eval.update(1)
if self.arguments.use_wandb:
self.wandb_runtime.log(
{'loss_eval': loss_eval.tolist(),
'accuracy': accuracy.tolist()}
)
pbar_eval.set_postfix(loss_eval=loss_eval.tolist())
if self.arguments.save_steps is None and self.arguments.do_last_save:
filename = f'{self.arguments.model_name}-{sum(losses) / len(losses)}-{i}'
print(f'Saving Model to \033[1;30m{filename}\033[1;0m')
self.ckpt_streamer.save_checkpoint(sharded_train_state_.params['params'],
filename,
gather_fns=gather_fns.params['params'])
else:
filename = 'not_saved | None'
output = OutputFineTuner(
last_save_file_name=filename,
predict_fun=self.sharded_predict,
train_state=sharded_train_state_,
mesh=self.mesh,
shard_fns=shard_fns,
gather_fns=gather_fns,
ckpt_stream=self.ckpt_streamer
)
wandb.finish()
return output | PypiClean |
/DEODR-0.2.1-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl/deodr/opengl/pyrender.py | from typing import Optional, Tuple
import numpy as np
import pyrender
import trimesh
from deodr.differentiable_renderer import Camera, Scene3D
from deodr.triangulated_mesh import ColoredTriMesh
def arcsinc(x: float) -> float:
return np.arcsin(x) / x if abs(x) > 1e-6 else 1
def min_rotation(vec1: np.ndarray, vec2: np.ndarray) -> np.ndarray:
"""Find the rotation matrix that aligns vec1 to vec2
:param vec1: A 3d "source" vector
:param vec2: A 3d "destination" vector
:return mat: A transform matrix (3x3) which when applied to vec1,
aligns it with vec2.
"""
assert vec1.shape == (3,)
assert vec2.shape == (3,)
a, b = (
(vec1 / np.linalg.norm(vec1)).reshape(3),
(vec2 / np.linalg.norm(vec2)).reshape(3),
)
v = np.cross(a, b)
c = np.dot(a, b)
s = np.linalg.norm(v)
kmat = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
d = (1 - c) / (s**2) if s > 1e-6 else 0.5
return np.eye(3) + kmat + kmat.dot(kmat) * d
def deodr_directional_light_to_pyrender(
deodr_directional_light: np.ndarray,
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
assert deodr_directional_light.shape == (3,)
directional_light_intensity = np.linalg.norm(deodr_directional_light)
if directional_light_intensity > 0:
directional_light_direction = (
deodr_directional_light / directional_light_intensity
)
directional_light_rotation = min_rotation(
np.array([0, 0, -1]), directional_light_direction
)
pose = np.zeros((4, 4))
pose[:3, :3] = directional_light_rotation
pose[3, 3] = 1
directional_light = pyrender.light.DirectionalLight(
intensity=directional_light_intensity
)
else:
directional_light = None
pose = None
return directional_light, pose
def deodr_mesh_to_pyrender(deodr_mesh: ColoredTriMesh) -> pyrender.Mesh:
assert deodr_mesh.uv is not None
assert deodr_mesh.texture is not None
# trimesh and pyrender do to handle faces indices for texture
# that are different from face indices for the 3d vertices
# we need to duplicate vertices
faces, mask_v, mask_vt = trimesh.visual.texture.unmerge_faces(
deodr_mesh.faces, deodr_mesh.faces_uv
)
vertices = deodr_mesh.vertices[mask_v]
deodr_mesh.compute_vertex_normals()
vertex_normals = deodr_mesh.vertex_normals[mask_v]
uv = deodr_mesh.uv[mask_vt]
pyrender_uv = np.column_stack(
(
(uv[:, 0]) / deodr_mesh.texture.shape[0],
(1 - uv[:, 1] / deodr_mesh.texture.shape[1]),
)
)
material = None
poses = None
color_0 = None
if material is None:
base_color_texture = pyrender.texture.Texture(
source=deodr_mesh.texture, source_channels="RGB"
)
material = pyrender.MetallicRoughnessMaterial(
alphaMode="BLEND",
baseColorFactor=[1, 1, 1, 1.0],
metallicFactor=0,
roughnessFactor=1,
baseColorTexture=base_color_texture,
)
material.wireframe = False
primitive = pyrender.Primitive(
positions=vertices,
normals=vertex_normals,
texcoord_0=pyrender_uv,
color_0=color_0,
indices=faces,
material=material,
mode=pyrender.constants.GLTF.TRIANGLES,
poses=poses,
)
return pyrender.Mesh(primitives=[primitive])
def render(deodr_scene: Scene3D, camera: Camera) -> Tuple[np.ndarray, np.ndarray]:
assert (
deodr_scene.mesh is not None
), "You need a mesh in the scene you want to render"
"""Render a deodr scene using pyrender"""
if deodr_scene.background_image is not None:
bg_color = deodr_scene.background_image[0, 0]
if not (np.all(deodr_scene.background_image == bg_color[None, None, :])):
raise (
BaseException(
"pyrender does not support background image, please provide a"
" background image that correspond to a uniform color"
)
)
else:
bg_color = deodr_scene.background_color
pyrender_scene = pyrender.Scene(
ambient_light=deodr_scene.light_ambient * np.ones((3)), bg_color=bg_color
)
if camera.distortion is not None:
raise (BaseException("cameras with distortion not handled yet with pyrender"))
# cam = pyrender.PerspectiveCamera(yfov=np.pi / 3.0, aspectRatio=1.414)
cam = pyrender.IntrinsicsCamera(
fx=camera.intrinsic[0, 0],
fy=camera.intrinsic[1, 1],
cx=camera.intrinsic[0, 2],
cy=camera.intrinsic[1, 2],
)
# convert to pyrender directional light parameterization
assert deodr_scene.light_directional is not None
directional_light, directional_light_pose = deodr_directional_light_to_pyrender(
deodr_scene.light_directional
)
if directional_light is not None:
pyrender_scene.add(directional_light, pose=directional_light_pose)
# convert the mesh
pyrender_mesh = deodr_mesh_to_pyrender(deodr_scene.mesh)
pyrender_scene.add(pyrender_mesh, pose=np.eye(4))
# convert the camera
m = camera.camera_to_world_mtx_4x4()
pose_camera = m.dot(np.diag([1, -1, -1, 1]))
pyrender_scene.add(cam, pose=pose_camera)
# render
width = camera.width
height = camera.height
r = pyrender.offscreen.OffscreenRenderer(width, height, point_size=1.0)
image_pyrender, depth = r.render(pyrender_scene)
return image_pyrender, depth | PypiClean |
/HttpMax-1.2.tar.gz/HttpMax-1.2/README.md | # HttpMax
**HttpMax** is a simple, asynchronous, fast and beautiful HTTP library.
```python
import HttpMax
import asyncio
async def main():
r = await HttpMax.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
r.status_code
>>>200
r.headers['content-type']
>>>'application/json; charset=utf8'
r.encoding
>>>'utf-8'
r.text
>>>'{"authenticated": true, ...'
r.json()
>>> {'authenticated': True, ...}
asyncio.run(main())
```
HttpMax allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode your `PUT` & `POST` data — but nowadays, just use the `json` method! | PypiClean |
/AccessControl-5.5.tar.gz/AccessControl-5.5/docs/requestmethod.rst | Request method decorators
=========================
Using request method decorators, you can limit functions or methods to only
be callable when the HTTP request was made using a particular method.
To limit access to a function or method to POST requests, use the
`requestmethod` decorator factory::
>>> from AccessControl.requestmethod import requestmethod
>>> @requestmethod('POST')
... def foo(bar, REQUEST):
... return bar
When this method is accessed through a request that does not use POST, the
Forbidden exception will be raised::
>>> foo('spam', GET)
Traceback (most recent call last):
...
Forbidden: Request must be POST
Only when the request was made using POST, will the call succeed::
>>> foo('spam', POST)
'spam'
The `REQUEST` can be is a positional or a keyword parameter.
*Not* passing an optional `REQUEST` always succeeds.
Note that the `REQUEST` parameter is a requirement for the decorator to
operate, not including it in the callable signature results in an error.
You can pass in multiple request methods allow access by any of them.
| PypiClean |
/ClueDojo-1.4.3-1.tar.gz/ClueDojo-1.4.3-1/src/cluedojo/static/dojo/nls/zh/colors.js | ({"lightsteelblue":"浅钢蓝色","orangered":"橙红色","midnightblue":"深蓝色","cadetblue":"灰蓝色","seashell":"海贝色","slategrey":"灰石色","coral":"珊瑚色","darkturquoise":"深粉蓝","antiquewhite":"古董白","mediumspringgreen":"间春绿色","salmon":"橙红","darkgrey":"深灰色","ivory":"象牙色","greenyellow":"绿黄色","mistyrose":"浅玫瑰色","lightsalmon":"淡橙色","silver":"银白色","dimgrey":"暗灰色","orange":"橙色","white":"白色","navajowhite":"纳瓦白","royalblue":"品蓝","deeppink":"深粉红色","lime":"淡黄绿色","oldlace":"老白色","chartreuse":"黄绿色","darkcyan":"深青绿","yellow":"黄色","linen":"亚麻色","olive":"橄榄绿","gold":"金黄色","lawngreen":"草绿色","lightyellow":"浅黄色","tan":"棕褐色","darkviolet":"深紫色","lightslategrey":"浅青灰","grey":"灰色","darkkhaki":"深卡其色","green":"绿色","deepskyblue":"深天蓝色","aqua":"浅绿色","sienna":"赭色","mintcream":"薄荷色","rosybrown":"褐玫瑰红","mediumslateblue":"间暗蓝色","magenta":"洋红色","lightseagreen":"浅海藻绿","cyan":"青蓝色","olivedrab":"草绿色","darkgoldenrod":"深金黄","slateblue":"石蓝色","mediumaquamarine":"间绿色","lavender":"淡紫色","mediumseagreen":"间海蓝色","maroon":"栗色","darkslategray":"深青灰","mediumturquoise":"间绿宝石色","ghostwhite":"苍白","darkblue":"深蓝","mediumvioletred":"间紫罗兰色","brown":"棕色","lightgray":"浅灰色","sandybrown":"沙褐色","pink":"粉红色","firebrick":"砖红","indigo":"靛青","snow":"雪白色","darkorchid":"深紫色","turquoise":"绿宝石色","chocolate":"巧克力色","springgreen":"春绿色","moccasin":"鹿皮色","navy":"藏青色","lemonchiffon":"柠檬绸色","teal":"水鸭色","floralwhite":"花白色","cornflowerblue":"浅蓝色","paleturquoise":"苍绿色","purple":"紫色","gainsboro":"淡灰色","plum":"杨李色","red":"红色","blue":"蓝色","forestgreen":"森林绿","darkgreen":"深绿色","honeydew":"蜜汁色","darkseagreen":"深海藻绿","lightcoral":"浅珊瑚色","palevioletred":"苍紫罗兰色","mediumpurple":"间紫色","saddlebrown":"重褐色","darkmagenta":"深洋红色","thistle":"蓟色","whitesmoke":"烟白色","wheat":"浅黄色","violet":"紫色","lightskyblue":"浅天蓝色","goldenrod":"金麒麟色","mediumblue":"间蓝色","skyblue":"天蓝色","crimson":"绯红色","darksalmon":"深橙红","darkred":"深红色","darkslategrey":"深青灰","peru":"秘鲁色","lightgrey":"浅灰色","lightgoldenrodyellow":"浅金黄色","blanchedalmond":"白杏色","aliceblue":"爱丽丝蓝","bisque":"桔黄色","slategray":"灰石色","palegoldenrod":"淡金黄色","darkorange":"深橙色","aquamarine":"碧绿色","lightgreen":"浅绿色","burlywood":"实木色","dodgerblue":"闪蓝色","darkgray":"深灰色","lightcyan":"浅青色","powderblue":"铁蓝","blueviolet":"蓝紫色","orchid":"紫色","dimgray":"暗灰色","beige":"米色","fuchsia":"紫红色","lavenderblush":"淡紫红","hotpink":"深粉红","steelblue":"钢蓝色","tomato":"西红柿色","lightpink":"浅粉红色","limegreen":"橙绿色","indianred":"印度红","papayawhip":"木瓜色","lightslategray":"浅青灰","gray":"灰色","mediumorchid":"间紫色","cornsilk":"米绸色","black":"黑色","seagreen":"海绿色","darkslateblue":"深青蓝","khaki":"卡其色","lightblue":"淡蓝色","palegreen":"淡绿色","azure":"天蓝色","peachpuff":"桃色","darkolivegreen":"深橄榄绿","yellowgreen":"黄绿色"}) | PypiClean |
/IRT-AI-0.0.1a0.tar.gz/IRT-AI-0.0.1a0/src/tiai/mediapip/hand.py | import cv2
import mediapipe as mp
def read_infrared_data(file):
lines = open(file, "r", encoding='utf-8')
data = []
for line in lines:
vs = line.strip().split(",")
row = [float(v) for v in vs]
data.append(row)
return data
def find_temp(csv_matrix,image_x,image_y,image_width,image_height):
m_width=len(csv_matrix[0])
m_height=len(csv_matrix)
rate1=m_width*1.0/image_width
rate2=m_height*1.0/image_height
c_x=int(image_x*rate1)-1
c_y=int(image_y*rate2)-1
if c_x<0:
c_x=0
if c_y<0:
c_y=0
if c_x>m_width-1:
c_x=m_width-1
if c_y > m_height-1:
c_y=m_height-1
print(f"cx={c_x},cy={c_y}")
return csv_matrix[c_y][c_x],c_x,c_y
def props_with_(obj):
pr={}
for name in dir(obj):
value=getattr(obj,name)
if not name.startswith('__') and not callable(value):
pr[name]=value
return pr
def detect_hand(image_path,save_detected_path=None,show=False,ext=".png",min_detection_confidence=0.5):
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
# For static images:
IMAGE_FILES = [image_path]
annotated_image=None
list_model=[]
list_connections=[]
count=0
with mp_hands.Hands(
static_image_mode=True,
max_num_hands=2,
min_detection_confidence=min_detection_confidence) as hands:
for idx, file in enumerate(IMAGE_FILES):
img_matrix = read_infrared_data(file.replace(ext,".csv"))
print("matrix: ",len(img_matrix[0]),len(img_matrix))
# Read an image, flip it around y-axis for correct handedness output (see
# above).
image = cv2.flip(cv2.imread(file), 1)
#print("shape: ",image.shape)
image_height,image_width,_=image.shape
print("shape: ", image_width,image_height)
# Convert the BGR image to RGB before processing.
results = hands.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
# Print handedness and draw hand landmarks on the image.
print('Handedness:', results.multi_handedness)
cls=results.multi_handedness[0]
import re
xx=re.findall(r'score: ([\d\.]+) ', str(cls).replace("\n"," "))
score=float(xx[0].strip())
print("score: ",xx[0])
if not results.multi_hand_landmarks:
continue
image_height, image_width, _ = image.shape
annotated_image = image.copy()
for hand_landmarks in results.multi_hand_landmarks:
# print(f'hand_landmarks:', hand_landmarks)
print("hand_landmarks: ")
for idx1,hand_lanmark in enumerate(hand_landmarks.landmark):
print(idx1)
x=hand_lanmark.x * image_width
y=hand_lanmark.y * image_height
z=hand_lanmark.z
temp,c_x,c_y=find_temp(img_matrix,x,y,image_width,image_height)
print(x,y,z)
print("temp = "+str(temp))
print()
list_model.append({
"id":f"hand-{count}-"+str(idx1),
"x":c_x,
"y":c_y,
"z":z,
"temp":temp
})
print(
f'Index finger tip coordinates: (',
f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].x * image_width}, '
f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].y * image_height})'
)
for model in mp_hands.HAND_CONNECTIONS:
list_connections.append({
"id": f"hand-{count}-" + str(idx1),
"start":model[0],
"end":model[1]
})
mp_drawing.draw_landmarks(
annotated_image,
hand_landmarks,
mp_hands.HAND_CONNECTIONS,
mp_drawing_styles.get_default_hand_landmarks_style(),
mp_drawing_styles.get_default_hand_connections_style())
count += 1
if save_detected_path!=None:
cv2.imwrite(save_detected_path, cv2.flip(annotated_image, 1))
if show:
cv2.imshow("annotated image",annotated_image)
cv2.waitKey()
'''
# Draw hand world landmarks.
if not results.multi_hand_world_landmarks:
continue
for hand_world_landmarks in results.multi_hand_world_landmarks:
mp_drawing.plot_landmarks(
hand_world_landmarks, mp_hands.HAND_CONNECTIONS, azimuth=5)
'''
return annotated_image,list_model,list_connections,score | PypiClean |
/FreePyBX-1.0-RC1.tar.gz/FreePyBX-1.0-RC1/freepybx/public/js/dojox/string/sprintf.js | define("dojox/string/sprintf",["dojo/_base/kernel","dojo/_base/lang","dojo/_base/sniff","./tokenize"],function(_1,_2,_3,_4){
var _5=_2.getObject("string",true,dojox);
_5.sprintf=function(_6,_7){
for(var _8=[],i=1;i<arguments.length;i++){
_8.push(arguments[i]);
}
var _9=new _5.sprintf.Formatter(_6);
return _9.format.apply(_9,_8);
};
_5.sprintf.Formatter=function(_a){
var _b=[];
this._mapped=false;
this._format=_a;
this._tokens=_4(_a,this._re,this._parseDelim,this);
};
_2.extend(_5.sprintf.Formatter,{_re:/\%(?:\(([\w_]+)\)|([1-9]\d*)\$)?([0 +\-\#]*)(\*|\d+)?(\.)?(\*|\d+)?[hlL]?([\%scdeEfFgGiouxX])/g,_parseDelim:function(_c,_d,_e,_f,_10,_11,_12){
if(_c){
this._mapped=true;
}
return {mapping:_c,intmapping:_d,flags:_e,_minWidth:_f,period:_10,_precision:_11,specifier:_12};
},_specifiers:{b:{base:2,isInt:true},o:{base:8,isInt:true},x:{base:16,isInt:true},X:{extend:["x"],toUpper:true},d:{base:10,isInt:true},i:{extend:["d"]},u:{extend:["d"],isUnsigned:true},c:{setArg:function(_13){
if(!isNaN(_13.arg)){
var num=parseInt(_13.arg);
if(num<0||num>127){
throw new Error("invalid character code passed to %c in sprintf");
}
_13.arg=isNaN(num)?""+num:String.fromCharCode(num);
}
}},s:{setMaxWidth:function(_14){
_14.maxWidth=(_14.period==".")?_14.precision:-1;
}},e:{isDouble:true,doubleNotation:"e"},E:{extend:["e"],toUpper:true},f:{isDouble:true,doubleNotation:"f"},F:{extend:["f"]},g:{isDouble:true,doubleNotation:"g"},G:{extend:["g"],toUpper:true}},format:function(_15){
if(this._mapped&&typeof _15!="object"){
throw new Error("format requires a mapping");
}
var str="";
var _16=0;
for(var i=0,_17;i<this._tokens.length;i++){
_17=this._tokens[i];
if(typeof _17=="string"){
str+=_17;
}else{
if(this._mapped){
if(typeof _15[_17.mapping]=="undefined"){
throw new Error("missing key "+_17.mapping);
}
_17.arg=_15[_17.mapping];
}else{
if(_17.intmapping){
var _16=parseInt(_17.intmapping)-1;
}
if(_16>=arguments.length){
throw new Error("got "+arguments.length+" printf arguments, insufficient for '"+this._format+"'");
}
_17.arg=arguments[_16++];
}
if(!_17.compiled){
_17.compiled=true;
_17.sign="";
_17.zeroPad=false;
_17.rightJustify=false;
_17.alternative=false;
var _18={};
for(var fi=_17.flags.length;fi--;){
var _19=_17.flags.charAt(fi);
_18[_19]=true;
switch(_19){
case " ":
_17.sign=" ";
break;
case "+":
_17.sign="+";
break;
case "0":
_17.zeroPad=(_18["-"])?false:true;
break;
case "-":
_17.rightJustify=true;
_17.zeroPad=false;
break;
case "#":
_17.alternative=true;
break;
default:
throw Error("bad formatting flag '"+_17.flags.charAt(fi)+"'");
}
}
_17.minWidth=(_17._minWidth)?parseInt(_17._minWidth):0;
_17.maxWidth=-1;
_17.toUpper=false;
_17.isUnsigned=false;
_17.isInt=false;
_17.isDouble=false;
_17.precision=1;
if(_17.period=="."){
if(_17._precision){
_17.precision=parseInt(_17._precision);
}else{
_17.precision=0;
}
}
var _1a=this._specifiers[_17.specifier];
if(typeof _1a=="undefined"){
throw new Error("unexpected specifier '"+_17.specifier+"'");
}
if(_1a.extend){
_2.mixin(_1a,this._specifiers[_1a.extend]);
delete _1a.extend;
}
_2.mixin(_17,_1a);
}
if(typeof _17.setArg=="function"){
_17.setArg(_17);
}
if(typeof _17.setMaxWidth=="function"){
_17.setMaxWidth(_17);
}
if(_17._minWidth=="*"){
if(this._mapped){
throw new Error("* width not supported in mapped formats");
}
_17.minWidth=parseInt(arguments[_16++]);
if(isNaN(_17.minWidth)){
throw new Error("the argument for * width at position "+_16+" is not a number in "+this._format);
}
if(_17.minWidth<0){
_17.rightJustify=true;
_17.minWidth=-_17.minWidth;
}
}
if(_17._precision=="*"&&_17.period=="."){
if(this._mapped){
throw new Error("* precision not supported in mapped formats");
}
_17.precision=parseInt(arguments[_16++]);
if(isNaN(_17.precision)){
throw Error("the argument for * precision at position "+_16+" is not a number in "+this._format);
}
if(_17.precision<0){
_17.precision=1;
_17.period="";
}
}
if(_17.isInt){
if(_17.period=="."){
_17.zeroPad=false;
}
this.formatInt(_17);
}else{
if(_17.isDouble){
if(_17.period!="."){
_17.precision=6;
}
this.formatDouble(_17);
}
}
this.fitField(_17);
str+=""+_17.arg;
}
}
return str;
},_zeros10:"0000000000",_spaces10:" ",formatInt:function(_1b){
var i=parseInt(_1b.arg);
if(!isFinite(i)){
if(typeof _1b.arg!="number"){
throw new Error("format argument '"+_1b.arg+"' not an integer; parseInt returned "+i);
}
i=0;
}
if(i<0&&(_1b.isUnsigned||_1b.base!=10)){
i=4294967295+i+1;
}
if(i<0){
_1b.arg=(-i).toString(_1b.base);
this.zeroPad(_1b);
_1b.arg="-"+_1b.arg;
}else{
_1b.arg=i.toString(_1b.base);
if(!i&&!_1b.precision){
_1b.arg="";
}else{
this.zeroPad(_1b);
}
if(_1b.sign){
_1b.arg=_1b.sign+_1b.arg;
}
}
if(_1b.base==16){
if(_1b.alternative){
_1b.arg="0x"+_1b.arg;
}
_1b.arg=_1b.toUpper?_1b.arg.toUpperCase():_1b.arg.toLowerCase();
}
if(_1b.base==8){
if(_1b.alternative&&_1b.arg.charAt(0)!="0"){
_1b.arg="0"+_1b.arg;
}
}
},formatDouble:function(_1c){
var f=parseFloat(_1c.arg);
if(!isFinite(f)){
if(typeof _1c.arg!="number"){
throw new Error("format argument '"+_1c.arg+"' not a float; parseFloat returned "+f);
}
f=0;
}
switch(_1c.doubleNotation){
case "e":
_1c.arg=f.toExponential(_1c.precision);
break;
case "f":
_1c.arg=f.toFixed(_1c.precision);
break;
case "g":
if(Math.abs(f)<0.0001){
_1c.arg=f.toExponential(_1c.precision>0?_1c.precision-1:_1c.precision);
}else{
_1c.arg=f.toPrecision(_1c.precision);
}
if(!_1c.alternative){
_1c.arg=_1c.arg.replace(/(\..*[^0])0*/,"$1");
_1c.arg=_1c.arg.replace(/\.0*e/,"e").replace(/\.0$/,"");
}
break;
default:
throw new Error("unexpected double notation '"+_1c.doubleNotation+"'");
}
_1c.arg=_1c.arg.replace(/e\+(\d)$/,"e+0$1").replace(/e\-(\d)$/,"e-0$1");
if(_3("opera")){
_1c.arg=_1c.arg.replace(/^\./,"0.");
}
if(_1c.alternative){
_1c.arg=_1c.arg.replace(/^(\d+)$/,"$1.");
_1c.arg=_1c.arg.replace(/^(\d+)e/,"$1.e");
}
if(f>=0&&_1c.sign){
_1c.arg=_1c.sign+_1c.arg;
}
_1c.arg=_1c.toUpper?_1c.arg.toUpperCase():_1c.arg.toLowerCase();
},zeroPad:function(_1d,_1e){
_1e=(arguments.length==2)?_1e:_1d.precision;
if(typeof _1d.arg!="string"){
_1d.arg=""+_1d.arg;
}
var _1f=_1e-10;
while(_1d.arg.length<_1f){
_1d.arg=(_1d.rightJustify)?_1d.arg+this._zeros10:this._zeros10+_1d.arg;
}
var pad=_1e-_1d.arg.length;
_1d.arg=(_1d.rightJustify)?_1d.arg+this._zeros10.substring(0,pad):this._zeros10.substring(0,pad)+_1d.arg;
},fitField:function(_20){
if(_20.maxWidth>=0&&_20.arg.length>_20.maxWidth){
return _20.arg.substring(0,_20.maxWidth);
}
if(_20.zeroPad){
this.zeroPad(_20,_20.minWidth);
return;
}
this.spacePad(_20);
},spacePad:function(_21,_22){
_22=(arguments.length==2)?_22:_21.minWidth;
if(typeof _21.arg!="string"){
_21.arg=""+_21.arg;
}
var _23=_22-10;
while(_21.arg.length<_23){
_21.arg=(_21.rightJustify)?_21.arg+this._spaces10:this._spaces10+_21.arg;
}
var pad=_22-_21.arg.length;
_21.arg=(_21.rightJustify)?_21.arg+this._spaces10.substring(0,pad):this._spaces10.substring(0,pad)+_21.arg;
}});
return _5.sprintf;
}); | PypiClean |
/Flask-AdminLTE2-1.0.0.tar.gz/Flask-AdminLTE2-1.0.0/flask_adminlte2/static/plugins/jQuery/core.js |
define( [
"./var/arr",
"./var/document",
"./var/getProto",
"./var/slice",
"./var/concat",
"./var/push",
"./var/indexOf",
"./var/class2type",
"./var/toString",
"./var/hasOwn",
"./var/fnToString",
"./var/ObjectFunctionString",
"./var/support",
"./var/isFunction",
"./var/isWindow",
"./core/DOMEval",
"./core/toType"
], function( arr, document, getProto, slice, concat, push, indexOf,
class2type, toString, hasOwn, fnToString, ObjectFunctionString,
support, isFunction, isWindow, DOMEval, toType ) {
"use strict";
var
version = "3.4.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
// Return all the elements in a clean array
if ( num == null ) {
return slice.call( this );
}
// Return just the one element from the set
return num < 0 ? this[ num + this.length ] : this[ num ];
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
each: function( callback ) {
return jQuery.each( this, callback );
},
map: function( callback ) {
return this.pushStack( jQuery.map( this, function( elem, i ) {
return callback.call( elem, i, elem );
} ) );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
},
end: function() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
copy = options[ name ];
// Prevent Object.prototype pollution
// Prevent never-ending loop
if ( name === "__proto__" || target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = Array.isArray( copy ) ) ) ) {
src = target[ name ];
// Ensure proper type for the source value
if ( copyIsArray && !Array.isArray( src ) ) {
clone = [];
} else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {
clone = {};
} else {
clone = src;
}
copyIsArray = false;
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend( {
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
isPlainObject: function( obj ) {
var proto, Ctor;
// Detect obvious negatives
// Use toString instead of jQuery.type to catch host objects
if ( !obj || toString.call( obj ) !== "[object Object]" ) {
return false;
}
proto = getProto( obj );
// Objects with no prototype (e.g., `Object.create( null )`) are plain
if ( !proto ) {
return true;
}
// Objects with prototype are plain iff they were constructed by a global Object function
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
// Evaluates a script in a global context
globalEval: function( code, options ) {
DOMEval( code, { nonce: options && options.nonce } );
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android <=4.0 only
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArrayLike( Object( arr ) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: real iOS 8.2 only (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = toType( obj );
if ( isFunction( obj ) || isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
return jQuery;
} ); | PypiClean |
/FairDynamicRec-0.0.123-py3-none-any.whl/fair_dynamic_rec/core/rankers/ea_linear_upper_confidence_bound.py | import numpy as np
from .ea_linear_submodular_bandit import EALSB
class EALinUCB(EALSB):
def __init__(self, config, dataObj, parameters=None):
super(EALinUCB, self).__init__(config, dataObj, parameters)
self.dim = self.dataObj.feature_data['train_item_latent_features'].shape[1]
# parameters
self.ill_matrix_counter = 0
self.theta = np.ones((self.dataObj.n_users, self.dim)) # d-dimensional
self.b = np.zeros((self.dataObj.n_users, self.dim)) # d
self.M = np.zeros((self.dataObj.n_users, self.dim, self.dim)) # d by d
self.MInv = np.zeros((self.dataObj.n_users, self.dim, self.dim)) # for fast matrix inverse computation, d by d
for i in range(self.dataObj.n_users):
self.M[i] = np.eye(self.dim)
self.MInv[i] = np.eye(self.dim)
# for ill inverse
self.b_tmp = np.zeros((self.dataObj.n_users, self.dim))
self.MInv_tmp = np.zeros((self.dataObj.n_users, self.dim, self.dim))
self.gamma = float(parameters["gamma"]["value"])
self.window = int(parameters['window']['value'])
self.click_history = np.zeros((self.dataObj.n_users, self.dim))
def get_ranking(self, batch_users, sampled_item=None, round=None):
"""
:param x: features
:param k: number of positions
:return: ranking: the ranked item id.
"""
# assert x.shape[0] >= k
rankings = np.zeros((len(batch_users), self.config.list_size), dtype=int)
self.batch_features = np.zeros((len(batch_users), self.config.list_size, self.dim))
tie_breaker = self.prng.rand(len(self.dataObj.feature_data['train_item_latent_features']))
for i in range(len(batch_users)):
user = batch_users[i]
cb = self.alpha * np.sqrt(np.multiply(np.dot(self.dataObj.feature_data['train_item_latent_features'], self.MInv[user]), self.dataObj.feature_data['train_item_latent_features']).sum(axis=1))
score = np.dot(self.dataObj.feature_data['train_item_latent_features'], self.theta[user])
ucb = score + cb
rankings[i] = np.lexsort((tie_breaker, -ucb))[:self.config.list_size]
self.batch_features[i] = self.dataObj.feature_data['train_item_latent_features'][rankings[i]]
return rankings | PypiClean |
/Oasys-Canvas-Core-1.0.7.tar.gz/Oasys-Canvas-Core-1.0.7/orangecanvas/scheme/readwrite.py | import sys
import warnings
import base64
import itertools
from xml.etree.ElementTree import TreeBuilder, Element, ElementTree, parse
from collections import defaultdict, namedtuple
from itertools import chain, count
import pickle
import json
import pprint
import ast
from ast import literal_eval
import logging
import six
from . import SchemeNode, SchemeLink
from .annotations import SchemeTextAnnotation, SchemeArrowAnnotation
from .errors import IncompatibleChannelTypeError
from ..registry import global_registry
log = logging.getLogger(__name__)
class UnknownWidgetDefinition(Exception):
pass
def string_eval(source):
"""
Evaluate a python string literal `source`. Raise ValueError if
`source` is not a string literal.
>>> string_eval("'a string'")
a string
"""
node = ast.parse(source, "<source>", mode="eval")
if not isinstance(node.body, ast.Str):
raise ValueError("%r is not a string literal" % source)
return node.body.s
def tuple_eval(source):
"""
Evaluate a python tuple literal `source` where the elements are
constrained to be int, float or string. Raise ValueError if not
a tuple literal.
>>> tuple_eval("(1, 2, "3")")
(1, 2, '3')
"""
node = ast.parse(source, "<source>", mode="eval")
if not isinstance(node.body, ast.Tuple):
raise ValueError("%r is not a tuple literal" % source)
if not all(isinstance(el, (ast.Str, ast.Num)) or
# allow signed number literals in Python3 (i.e. -1|+1|-1.0)
(isinstance(el, ast.UnaryOp) and
isinstance(el.op, (ast.UAdd, ast.USub)) and
isinstance(el.operand, ast.Num))
for el in node.body.elts):
raise ValueError("Can only contain numbers or strings")
return literal_eval(source)
def terminal_eval(source):
"""
Evaluate a python 'constant' (string, number, None, True, False)
`source`. Raise ValueError is not a terminal literal.
>>> terminal_eval("True")
True
"""
node = ast.parse(source, "<source>", mode="eval")
try:
return _terminal_value(node.body)
except ValueError:
raise
def _terminal_value(node):
if isinstance(node, ast.Str):
return node.s
elif sys.version_info >= (3,) and isinstance(node, ast.Bytes):
return node.s
elif isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.Name) and \
node.id in ["True", "False", "None"]:
return __builtins__[node.id]
elif sys.version_info >= (3, 4) and isinstance(node, ast.NameConstant):
return node.value
raise ValueError("Not a terminal")
def sniff_version(stream):
"""
Parse a scheme stream and return the scheme's serialization
version string.
"""
doc = parse(stream)
scheme_el = doc.getroot()
version = scheme_el.attrib.get("version", None)
# Fallback: check for "widgets" tag.
if scheme_el.find("widgets") is not None:
version = "1.0"
else:
version = "2.0"
return version
def parse_scheme(scheme, stream, error_handler=None,
allow_pickle_data=False):
"""
Parse a saved scheme from `stream` and populate a `scheme`
instance (:class:`Scheme`).
`error_handler` if given will be called with an exception when
a 'recoverable' error occurs. By default the exception is simply
raised.
Parameters
----------
scheme : :class:`.Scheme`
A scheme instance to populate with the contents of `stream`.
stream : file-like object
A file like object opened for reading.
error_hander : function, optional
A function to call with an exception instance when a `recoverable`
error occurs.
allow_picked_data : bool, optional
Specifically allow parsing of picked data streams.
"""
warnings.warn("Use 'scheme_load' instead", DeprecationWarning,
stacklevel=2)
doc = parse(stream)
scheme_el = doc.getroot()
version = scheme_el.attrib.get("version", None)
if version is None:
# Fallback: check for "widgets" tag.
if scheme_el.find("widgets") is not None:
version = "1.0"
else:
version = "2.0"
if error_handler is None:
def error_handler(exc):
raise exc
if version == "1.0":
parse_scheme_v_1_0(doc, scheme, error_handler=error_handler,
allow_pickle_data=allow_pickle_data)
return scheme
else:
parse_scheme_v_2_0(doc, scheme, error_handler=error_handler,
allow_pickle_data=allow_pickle_data)
return scheme
def scheme_node_from_element(node_el, registry):
"""
Create a SchemeNode from an `Element` instance.
"""
try:
widget_desc = registry.widget(node_el.get("qualified_name"))
except KeyError as ex:
raise UnknownWidgetDefinition(*ex.args)
title = node_el.get("title")
pos = node_el.get("position")
if pos is not None:
pos = tuple_eval(pos)
return SchemeNode(widget_desc, title=title, position=pos)
def parse_scheme_v_2_0(etree, scheme, error_handler, widget_registry=None,
allow_pickle_data=False):
"""
Parse an `ElementTree` instance.
"""
if widget_registry is None:
widget_registry = global_registry()
nodes_not_found = []
nodes = []
links = []
id_to_node = {}
scheme_node = etree.getroot()
scheme.title = scheme_node.attrib.get("title", "")
scheme.description = scheme_node.attrib.get("description", "")
# Load and create scheme nodes.
for node_el in etree.findall("nodes/node"):
try:
node = scheme_node_from_element(node_el, widget_registry)
except UnknownWidgetDefinition as ex:
# description was not found
error_handler(ex)
node = None
except Exception:
raise
if node is not None:
nodes.append(node)
id_to_node[node_el.get("id")] = node
else:
nodes_not_found.append(node_el.get("id"))
# Load and create scheme links.
for link_el in etree.findall("links/link"):
source_id = link_el.get("source_node_id")
sink_id = link_el.get("sink_node_id")
if source_id in nodes_not_found or sink_id in nodes_not_found:
continue
source = id_to_node.get(source_id)
sink = id_to_node.get(sink_id)
source_channel = link_el.get("source_channel")
sink_channel = link_el.get("sink_channel")
enabled = link_el.get("enabled") == "true"
try:
link = SchemeLink(source, source_channel, sink, sink_channel,
enabled=enabled)
except (ValueError, IncompatibleChannelTypeError) as ex:
error_handler(ex)
else:
links.append(link)
# Load node properties
for property_el in etree.findall("node_properties/properties"):
node_id = property_el.attrib.get("node_id")
if node_id in nodes_not_found:
continue
node = id_to_node[node_id]
format = property_el.attrib.get("format", "pickle")
if "data" in property_el.attrib:
# data string is 'encoded' with 'repr' i.e. unicode and
# nonprintable characters are \u or \x escaped.
# Could use 'codecs' module?
data = string_eval(property_el.attrib.get("data"))
else:
data = property_el.text
properties = None
if format != "pickle" or allow_pickle_data:
try:
properties = loads(data, format)
except Exception:
log.error("Could not load properties for %r.", node.title,
exc_info=True)
if properties is not None:
node.properties = properties
annotations = []
for annot_el in etree.findall("annotations/*"):
if annot_el.tag == "text":
rect = annot_el.attrib.get("rect", "(0, 0, 20, 20)")
rect = tuple_eval(rect)
font_family = annot_el.attrib.get("font-family", "").strip()
font_size = annot_el.attrib.get("font-size", "").strip()
font = {}
if font_family:
font["family"] = font_family
if font_size:
font["size"] = int(font_size)
annot = SchemeTextAnnotation(rect, annot_el.text or "", font=font)
elif annot_el.tag == "arrow":
start = annot_el.attrib.get("start", "(0, 0)")
end = annot_el.attrib.get("end", "(0, 0)")
start, end = map(tuple_eval, (start, end))
color = annot_el.attrib.get("fill", "red")
annot = SchemeArrowAnnotation(start, end, color=color)
annotations.append(annot)
for node in nodes:
scheme.add_node(node)
for link in links:
scheme.add_link(link)
for annot in annotations:
scheme.add_annotation(annot)
def parse_scheme_v_1_0(etree, scheme, error_handler, widget_registry=None,
allow_pickle_data=False):
"""
ElementTree Instance of an old .ows scheme format.
"""
if widget_registry is None:
widget_registry = global_registry()
widgets_not_found = []
widgets = widget_registry.widgets()
widgets_by_name = [(d.qualified_name.rsplit(".", 1)[-1], d)
for d in widgets]
widgets_by_name = dict(widgets_by_name)
nodes_by_caption = {}
nodes = []
links = []
for widget_el in etree.findall("widgets/widget"):
caption = widget_el.get("caption")
name = widget_el.get("widgetName")
x_pos = widget_el.get("xPos")
y_pos = widget_el.get("yPos")
if name in widgets_by_name:
desc = widgets_by_name[name]
else:
error_handler(UnknownWidgetDefinition(name))
widgets_not_found.append(caption)
continue
node = SchemeNode(desc, title=caption,
position=(int(x_pos), int(y_pos)))
nodes_by_caption[caption] = node
nodes.append(node)
for channel_el in etree.findall("channels/channel"):
in_caption = channel_el.get("inWidgetCaption")
out_caption = channel_el.get("outWidgetCaption")
if in_caption in widgets_not_found or \
out_caption in widgets_not_found:
continue
source = nodes_by_caption[out_caption]
sink = nodes_by_caption[in_caption]
enabled = channel_el.get("enabled") == "1"
signals = literal_eval(channel_el.get("signals"))
for source_channel, sink_channel in signals:
try:
link = SchemeLink(source, source_channel, sink, sink_channel,
enabled=enabled)
except (ValueError, IncompatibleChannelTypeError) as ex:
error_handler(ex)
else:
links.append(link)
settings = etree.find("settings")
properties = {}
if settings is not None:
data = settings.attrib.get("settingsDictionary", None)
if data and allow_pickle_data:
try:
properties = literal_eval(data)
except Exception:
log.error("Could not load properties for the scheme.",
exc_info=True)
for node in nodes:
if node.title in properties:
try:
node.properties = pickle.loads(properties[node.title])
except Exception:
log.error("Could not unpickle properties for the node %r.",
node.title, exc_info=True)
scheme.add_node(node)
for link in links:
scheme.add_link(link)
# Intermediate scheme representation
_scheme = namedtuple(
"_scheme",
["title", "version", "description", "nodes", "links", "annotations"])
_node = namedtuple(
"_node",
["id", "title", "name", "position", "project_name", "qualified_name",
"version", "data"])
_data = namedtuple(
"_data",
["format", "data"])
_link = namedtuple(
"_link",
["id", "source_node_id", "sink_node_id", "source_channel", "sink_channel",
"enabled"])
_annotation = namedtuple(
"_annotation",
["id", "type", "params"])
_text_params = namedtuple(
"_text_params",
["geometry", "text", "font"])
_arrow_params = namedtuple(
"_arrow_params",
["geometry", "color"])
def parse_ows_etree_v_2_0(tree):
scheme = tree.getroot()
nodes, links, annotations = [], [], []
# First collect all properties
properties = {}
for property in tree.findall("node_properties/properties"):
node_id = property.get("node_id")
format = property.get("format")
if "data" in property.attrib:
data = property.get("data")
else:
data = property.text
properties[node_id] = _data(format, data)
# Collect all nodes
for node in tree.findall("nodes/node"):
node_id = node.get("id")
node = _node(
id=node_id,
title=node.get("title"),
name=node.get("name"),
position=tuple_eval(node.get("position")),
project_name=node.get("project_name"),
qualified_name=node.get("qualified_name"),
version=node.get("version", ""),
data=properties.get(node_id, None)
)
nodes.append(node)
for link in tree.findall("links/link"):
params = _link(
id=link.get("id"),
source_node_id=link.get("source_node_id"),
sink_node_id=link.get("sink_node_id"),
source_channel=link.get("source_channel"),
sink_channel=link.get("sink_channel"),
enabled=link.get("enabled") == "true",
)
links.append(params)
for annot in tree.findall("annotations/*"):
if annot.tag == "text":
rect = tuple_eval(annot.get("rect", "(0.0, 0.0, 20.0, 20.0)"))
font_family = annot.get("font-family", "").strip()
font_size = annot.get("font-size", "").strip()
font = {}
if font_family:
font["family"] = font_family
if font_size:
font["size"] = int(font_size)
annotation = _annotation(
id=annot.get("id"),
type="text",
params=_text_params(rect, annot.text or "", font),
)
elif annot.tag == "arrow":
start = tuple_eval(annot.get("start", "(0, 0)"))
end = tuple_eval(annot.get("end", "(0, 0)"))
color = annot.get("fill", "red")
annotation = _annotation(
id=annot.get("id"),
type="arrow",
params=_arrow_params((start, end), color)
)
annotations.append(annotation)
return _scheme(
version=scheme.get("version"),
title=scheme.get("title", ""),
description=scheme.get("description"),
nodes=nodes,
links=links,
annotations=annotations
)
def parse_ows_etree_v_1_0(tree):
nodes, links = [], []
id_gen = count()
settings = tree.find("settings")
properties = {}
if settings is not None:
data = settings.get("settingsDictionary", None)
if data:
try:
properties = literal_eval(data)
except Exception:
log.error("Could not decode properties data.",
exc_info=True)
for widget in tree.findall("widgets/widget"):
title = widget.get("caption")
data = properties.get(title, None)
node = _node(
id=next(id_gen),
title=widget.get("caption"),
name=None,
position=(float(widget.get("xPos")),
float(widget.get("yPos"))),
project_name=None,
qualified_name=widget.get("widgetName"),
version="",
data=_data("pickle", data)
)
nodes.append(node)
nodes_by_title = dict((node.title, node) for node in nodes)
for channel in tree.findall("channels/channel"):
in_title = channel.get("inWidgetCaption")
out_title = channel.get("outWidgetCaption")
source = nodes_by_title[out_title]
sink = nodes_by_title[in_title]
enabled = channel.get("enabled") == "1"
# repr list of (source_name, sink_name) tuples.
signals = literal_eval(channel.get("signals"))
for source_channel, sink_channel in signals:
links.append(
_link(id=next(id_gen),
source_node_id=source.id,
sink_node_id=sink.id,
source_channel=source_channel,
sink_channel=sink_channel,
enabled=enabled)
)
return _scheme(title="", description="", version="1.0",
nodes=nodes, links=links, annotations=[])
def parse_ows_stream(stream):
doc = parse(stream)
scheme_el = doc.getroot()
version = scheme_el.get("version", None)
if version is None:
# Fallback: check for "widgets" tag.
if scheme_el.find("widgets") is not None:
version = "1.0"
else:
log.warning("<scheme> tag does not have a 'version' attribute")
version = "2.0"
if version == "1.0":
return parse_ows_etree_v_1_0(doc)
elif version == "2.0":
return parse_ows_etree_v_2_0(doc)
else:
raise ValueError()
def resolve_1_0(scheme_desc, registry):
widgets = registry.widgets()
widgets_by_name = dict((d.qualified_name.rsplit(".", 1)[-1], d)
for d in widgets)
nodes = scheme_desc.nodes
for i, node in list(enumerate(nodes)):
# 1.0's qualified name is the class name only, need to replace it
# with the full qualified import name
qname = node.qualified_name
if qname in widgets_by_name:
desc = widgets_by_name[qname]
nodes[i] = node._replace(qualified_name=desc.qualified_name,
project_name=desc.project_name)
return scheme_desc._replace(nodes=nodes)
def resolve_replaced(scheme_desc, registry):
widgets = registry.widgets()
replacements = {}
for desc in widgets:
if desc.replaces:
for repl_qname in desc.replaces:
replacements[repl_qname] = desc.qualified_name
nodes = scheme_desc.nodes
for i, node in list(enumerate(nodes)):
if not registry.has_widget(node.qualified_name) and \
node.qualified_name in replacements:
qname = replacements[node.qualified_name]
desc = registry.widget(qname)
nodes[i] = node._replace(qualified_name=desc.qualified_name,
project_name=desc.project_name)
return scheme_desc._replace(nodes=nodes)
def scheme_load(scheme, stream, registry=None, error_handler=None):
desc = parse_ows_stream(stream)
if registry is None:
registry = global_registry()
if error_handler is None:
def error_handler(exc):
raise exc
if desc.version == "1.0":
desc = resolve_1_0(desc, registry)
desc = resolve_replaced(desc, registry)
nodes_not_found = []
nodes = []
nodes_by_id = {}
links = []
annotations = []
scheme.title = desc.title
scheme.description = desc.description
for node_d in desc.nodes:
try:
w_desc = registry.widget(node_d.qualified_name)
except KeyError as ex:
error_handler(UnknownWidgetDefinition(*ex.args))
nodes_not_found.append(node_d.id)
else:
node = SchemeNode(
w_desc, title=node_d.title, position=node_d.position)
data = node_d.data
if data:
try:
properties = loads(data.data, data.format)
except Exception:
log.error("Could not load properties for %r.", node.title,
exc_info=True)
else:
node.properties = properties
nodes.append(node)
nodes_by_id[node_d.id] = node
for link_d in desc.links:
source_id = link_d.source_node_id
sink_id = link_d.sink_node_id
if source_id in nodes_not_found or sink_id in nodes_not_found:
continue
source = nodes_by_id[source_id]
sink = nodes_by_id[sink_id]
try:
link = SchemeLink(source, link_d.source_channel,
sink, link_d.sink_channel,
enabled=link_d.enabled)
except (ValueError, IncompatibleChannelTypeError) as ex:
error_handler(ex)
else:
links.append(link)
for annot_d in desc.annotations:
params = annot_d.params
if annot_d.type == "text":
annot = SchemeTextAnnotation(params.geometry, params.text,
params.font)
elif annot_d.type == "arrow":
start, end = params.geometry
annot = SchemeArrowAnnotation(start, end, params.color)
else:
log.warning("Ignoring unknown annotation type: %r", annot_d.type)
annotations.append(annot)
for node in nodes:
scheme.add_node(node)
for link in links:
scheme.add_link(link)
for annot in annotations:
scheme.add_annotation(annot)
return scheme
def scheme_to_etree(scheme, data_format="literal", pickle_fallback=False):
"""
Return an `xml.etree.ElementTree` representation of the `scheme`.
"""
builder = TreeBuilder(element_factory=Element)
builder.start("scheme", {"version": "2.0",
"title": scheme.title or "",
"description": scheme.description or ""})
## Nodes
node_ids = defaultdict(lambda c=itertools.count(): next(c))
builder.start("nodes", {})
for node in scheme.nodes:
desc = node.description
attrs = {"id": str(node_ids[node]),
"name": desc.name,
"qualified_name": desc.qualified_name,
"project_name": desc.project_name or "",
"version": desc.version or "",
"title": node.title,
}
if node.position is not None:
attrs["position"] = str(node.position)
if type(node) is not SchemeNode:
attrs["scheme_node_type"] = "%s.%s" % (type(node).__name__,
type(node).__module__)
builder.start("node", attrs)
builder.end("node")
builder.end("nodes")
## Links
link_ids = defaultdict(lambda c=itertools.count(): next(c))
builder.start("links", {})
for link in scheme.links:
source = link.source_node
sink = link.sink_node
source_id = node_ids[source]
sink_id = node_ids[sink]
attrs = {"id": str(link_ids[link]),
"source_node_id": str(source_id),
"sink_node_id": str(sink_id),
"source_channel": link.source_channel.name,
"sink_channel": link.sink_channel.name,
"enabled": "true" if link.enabled else "false",
}
builder.start("link", attrs)
builder.end("link")
builder.end("links")
## Annotations
annotation_ids = defaultdict(lambda c=itertools.count(): next(c))
builder.start("annotations", {})
for annotation in scheme.annotations:
annot_id = annotation_ids[annotation]
attrs = {"id": str(annot_id)}
data = None
if isinstance(annotation, SchemeTextAnnotation):
tag = "text"
attrs.update({"rect": repr(annotation.rect)})
# Save the font attributes
font = annotation.font
attrs.update({"font-family": font.get("family", None),
"font-size": font.get("size", None)})
attrs = [(key, value) for key, value in attrs.items()
if value is not None]
attrs = dict((key, six.text_type(value)) for key, value in attrs)
data = annotation.text
elif isinstance(annotation, SchemeArrowAnnotation):
tag = "arrow"
attrs.update({"start": repr(annotation.start_pos),
"end": repr(annotation.end_pos)})
# Save the arrow color
try:
color = annotation.color
attrs.update({"fill": color})
except AttributeError:
pass
data = None
else:
log.warning("Can't save %r", annotation)
continue
builder.start(tag, attrs)
if data is not None:
builder.data(data)
builder.end(tag)
builder.end("annotations")
builder.start("thumbnail", {})
builder.end("thumbnail")
# Node properties/settings
builder.start("node_properties", {})
for node in scheme.nodes:
data = None
if node.properties:
try:
data, format = dumps(node.properties, format=data_format,
pickle_fallback=pickle_fallback)
except Exception:
log.error("Error serializing properties for node %r",
node.title, exc_info=True)
if data is not None:
builder.start("properties",
{"node_id": str(node_ids[node]),
"format": format})
builder.data(data)
builder.end("properties")
builder.end("node_properties")
builder.end("scheme")
root = builder.close()
tree = ElementTree(root)
return tree
def scheme_to_ows_stream(scheme, stream, pretty=False, pickle_fallback=False):
"""
Write scheme to a a stream in Orange Scheme .ows (v 2.0) format.
Parameters
----------
scheme : :class:`.Scheme`
A :class:`.Scheme` instance to serialize.
stream : file-like object
A file-like object opened for writing.
pretty : bool, optional
If `True` the output xml will be pretty printed (indented).
pickle_fallback : bool, optional
If `True` allow scheme node properties to be saves using pickle
protocol if properties cannot be saved using the default
notation.
"""
tree = scheme_to_etree(scheme, data_format="literal",
pickle_fallback=pickle_fallback)
if pretty:
indent(tree.getroot(), 0)
if sys.version_info < (2, 7):
# in Python 2.6 the write does not have xml_declaration parameter.
tree.write(stream, encoding="utf-8")
else:
tree.write(stream, encoding="utf-8", xml_declaration=True)
def indent(element, level=0, indent="\t"):
"""
Indent an instance of a :class:`Element`. Based on
(http://effbot.org/zone/element-lib.htm#prettyprint).
"""
def empty(text):
return not text or not text.strip()
def indent_(element, level, last):
child_count = len(element)
if child_count:
if empty(element.text):
element.text = "\n" + indent * (level + 1)
if empty(element.tail):
element.tail = "\n" + indent * (level + (-1 if last else 0))
for i, child in enumerate(element):
indent_(child, level + 1, i == child_count - 1)
else:
if empty(element.tail):
element.tail = "\n" + indent * (level + (-1 if last else 0))
return indent_(element, level, True)
if six.PY3:
_encodebytes = base64.encodebytes
_decodebytes = base64.decodebytes
else:
_encodebytes = base64.encodestring
_decodebytes = base64.decodestring
def dumps(obj, format="literal", prettyprint=False, pickle_fallback=False):
"""
Serialize `obj` using `format` ('json' or 'literal') and return its
string representation and the used serialization format ('literal',
'json' or 'pickle').
If `pickle_fallback` is True and the serialization with `format`
fails object's pickle representation will be returned
"""
if format == "literal":
try:
return (literal_dumps(obj, prettyprint=prettyprint, indent=1),
"literal")
except (ValueError, TypeError) as ex:
if not pickle_fallback:
raise
log.warning("Could not serialize to a literal string",
exc_info=True)
elif format == "json":
try:
return (json.dumps(obj, indent=1 if prettyprint else None),
"json")
except (ValueError, TypeError):
if not pickle_fallback:
raise
log.warning("Could not serialize to a json string",
exc_info=True)
elif format == "pickle":
return _encodebytes(pickle.dumps(obj)).decode('ascii'), "pickle"
else:
raise ValueError("Unsupported format %r" % format)
if pickle_fallback:
log.warning("Using pickle fallback")
return _encodebytes(pickle.dumps(obj)).decode('ascii'), "pickle"
else:
raise Exception("Something strange happened.")
def loads(string, format):
if format == "literal":
return literal_eval(string)
elif format == "json":
return json.loads(string)
elif format == "pickle":
original_value = _decodebytes(string.encode('ascii'))
fixed_value = original_value.replace("PyQt4".encode("ascii"), "PyQt5".encode("ascii"))
return pickle.loads(fixed_value)
else:
raise ValueError("Unknown format")
# This is a subset of PyON serialization.
def literal_dumps(obj, prettyprint=False, indent=4):
"""
Write obj into a string as a python literal.
"""
memo = {}
NoneType = type(None)
def check(obj):
if type(obj) in [int, float, bool, NoneType, bytes, six.text_type]:
return True
if id(obj) in memo:
raise ValueError("{0} is a recursive structure".format(obj))
memo[id(obj)] = obj
if type(obj) in [list, tuple]:
return all(map(check, obj))
elif type(obj) is dict:
return all(map(check, chain(obj.keys(), obj.values())))
else:
raise TypeError("{0} can not be serialized as a python "
"literal".format(type(obj)))
check(obj)
if prettyprint:
return pprint.pformat(obj, indent=indent)
else:
return repr(obj)
literal_loads = literal_eval | PypiClean |
/NetComp-0.2.3.tar.gz/NetComp-0.2.3/netcomp/distance/exact.py | import numpy as np
from numpy import linalg as la
import networkx as nx
from netcomp.linalg import (renormalized_res_mat,resistance_matrix,
fast_bp,laplacian_matrix,normalized_laplacian_eig,
_flat,_pad,_eigs)
from netcomp.distance import get_features,aggregate_features
from netcomp.exception import InputError
######################
## Helper Functions ##
######################
def _canberra_dist(v1,v2):
"""The canberra distance between two vectors. We need to carefully handle
the case in which both v1 and v2 are zero in a certain dimension."""
eps = 10**(-15)
v1,v2 = [_flat(v) for v in [v1,v2]]
d_can = 0
for u,w in zip(v1,v2):
if np.abs(u)<eps and np.abs(w)<eps:
d_update = 1
else:
d_update = np.abs(u-w) / (np.abs(u)+np.abs(w))
d_can += d_update
return d_can
#############################
## Distance Between Graphs ##
#############################
def edit_distance(A1,A2):
"""The edit distance between graphs, defined as the number of changes one
needs to make to put the edge lists in correspondence.
Parameters
----------
A1, A2 : NumPy matrices
Adjacency matrices of graphs to be compared
Returns
-------
dist : float
The edit distance between the two graphs
"""
dist = np.abs((A1-A2)).sum() / 2
return dist
def vertex_edge_overlap(A1,A2):
"""Vertex-edge overlap. Basically a souped-up edit distance, but in similarity
form. The VEO similarity is defined as
VEO(G1,G2) = (|V1&V2| + |E1&E2|) / (|V1|+|V2|+|E1|+|E2|)
where |S| is the size of a set S and U&T is the union of U and T.
Parameters
----------
A1, A2 : NumPy matrices
Adjacency matrices of graphs to be compared
Returns
-------
sim : float
The similarity between the two graphs
References
----------
"""
try:
[G1,G2] = [nx.from_scipy_sparse_matrix(A) for A in [A1,A2]]
except AttributeError:
[G1,G2] = [nx.from_numpy_matrix(A) for A in [A1,A2]]
V1,V2 = [set(G.nodes()) for G in [G1,G2]]
E1,E2 = [set(G.edges()) for G in [G1,G2]]
V_overlap = len(V1|V2) # set union
E_overlap = len(E1|E2)
sim = (V_overlap + E_overlap) / (len(V1)+len(V2)+len(E1)+len(E2))
return sim
def vertex_edge_distance(A1,A2):
"""Vertex-edge overlap transformed into a distance via
D = (1-VEO)/VEO
which is the inversion of the common distance-to-similarity function
sim = 1/(1+D).
Parameters
----------
A1, A2 : NumPy matrices
Adjacency matrices of graphs to be compared
Returns
-------
dist : float
The distance between the two graphs
"""
sim = vertex_edge_overlap(A1,A2)
dist = (1-sim)/sim
return dist
def lambda_dist(A1,A2,k=None,p=2,kind='laplacian'):
"""The lambda distance between graphs, which is defined as
d(G1,G2) = norm(L_1 - L_2)
where L_1 is a vector of the top k eigenvalues of the appropriate matrix
associated with G1, and L2 is defined similarly.
Parameters
----------
A1, A2 : NumPy matrices
Adjacency matrices of graphs to be compared
k : Integer
The number of eigenvalues to be compared
p : non-zero Float
The p-norm is used to compare the resulting vector of eigenvalues.
kind : String , in {'laplacian','laplacian_norm','adjacency'}
The matrix for which eigenvalues will be calculated.
Returns
-------
dist : float
The distance between the two graphs
Notes
-----
The norm can be any p-norm; by default we use p=2. If p<0 is used, the
result is not a mathematical norm, but may still be interesting and/or
useful.
If k is provided, then we use the k SMALLEST eigenvalues for the Laplacian
distances, and we use the k LARGEST eigenvalues for the adjacency
distance. This is because the corresponding order flips, as L = D-A.
References
----------
See Also
--------
netcomp.linalg._eigs
normalized_laplacian_eigs
"""
# ensure valid k
n1,n2 = [A.shape[0] for A in [A1,A2]]
N = min(n1,n2) # minimum size between the two graphs
if k is None or k > N:
k = N
if kind is 'laplacian':
# form matrices
L1,L2 = [laplacian_matrix(A) for A in [A1,A2]]
# get eigenvalues, ignore eigenvectors
evals1,evals2 = [_eigs(L)[0] for L in [L1,L2]]
elif kind is 'laplacian_norm':
# use our function to graph evals of normalized laplacian
evals1,evals2 = [normalized_laplacian_eig(A)[0] for A in [A1,A2]]
elif kind is 'adjacency':
evals1,evals2 = [_eigs(A)[0] for A in [A1,A2]]
# reverse, so that we are sorted from large to small, since we care
# about the k LARGEST eigenvalues for the adjacency distance
evals1,evals2 = [evals[::-1] for evals in [evals1,evals2]]
else:
raise InputError("Invalid type, choose from 'laplacian', "
"'laplacian_norm', and 'adjacency'.")
dist = la.norm(evals1[:k]-evals2[:k],ord=p)
return dist
def netsimile(A1,A2):
"""NetSimile distance between two graphs.
Parameters
----------
A1, A2 : SciPy sparse array
Adjacency matrices of the graphs in question.
Returns
-------
d_can : Float
The distance between the two graphs.
Notes
-----
NetSimile works on graphs without node correspondence. Graphs to not need to
be the same size.
See Also
--------
References
----------
"""
feat_A1,feat_A2 = [get_features(A) for A in [A1,A2]]
agg_A1,agg_A2 = [aggregate_features(feat) for feat in [feat_A1,feat_A2]]
# calculate Canberra distance between two aggregate vectors
d_can = _canberra_dist(agg_A1,agg_A2)
return d_can
def resistance_distance(A1,A2,p=2,renormalized=False,attributed=False,
check_connected=True,beta=1):
"""Compare two graphs using resistance distance (possibly renormalized).
Parameters
----------
A1, A2 : NumPy Matrices
Adjacency matrices of graphs to be compared.
p : float
Function returns the p-norm of the flattened matrices.
renormalized : Boolean, optional (default = False)
If true, then renormalized resistance distance is computed.
attributed : Boolean, optional (default=False)
If true, then the resistance distance PER NODE is returned.
check_connected : Boolean, optional (default=True)
If false, then no check on connectivity is performed. See Notes of
resistance_matrix for more information.
beta : float, optional (default=1)
A parameter used in the calculation of the renormalized resistance
matrix. If using regular resistance, this is irrelevant.
Returns
-------
dist : float of numpy array
The RR distance between the two graphs. If attributed is True, then
vector distance per node is returned.
Notes
-----
The distance is calculated by assuming the nodes are in correspondence, and
any nodes not present are treated as isolated by renormalized resistance.
References
----------
See Also
--------
resistance_matrix
"""
# Calculate resistance matricies and compare
if renormalized:
# pad smaller adj. mat. so they're the same size
n1,n2 = [A.shape[0] for A in [A1,A2]]
N = max(n1,n2)
A1,A2 = [_pad(A,N) for A in [A1,A2]]
R1,R2 = [renormalized_res_mat(A,beta=beta) for A in [A1,A2]]
else:
R1,R2 = [resistance_matrix(A,check_connected=check_connected)
for A in [A1,A2]]
try:
distance_vector = np.sum((R1-R2)**p,axis=1)
except ValueError:
raise InputError('Input matrices are different sizes. Please use '
'renormalized resistance distance.')
if attributed:
return distance_vector**(1/p)
else:
return np.sum(distance_vector)**(1/p)
def deltacon0(A1,A2,eps=None):
"""DeltaCon0 distance between two graphs. The distance is the Frobenius norm
of the element-wise square root of the fast belief propogation matrix.
Parameters
----------
A1, A2 : NumPy Matrices
Adjacency matrices of graphs to be compared.
Returns
-------
dist : float
DeltaCon0 distance between graphs.
References
----------
See Also
--------
fast_bp
"""
# pad smaller adj. mat. so they're the same size
n1,n2 = [A.shape[0] for A in [A1,A2]]
N = max(n1,n2)
A1,A2 = [_pad(A,N) for A in [A1,A2]]
S1,S2 = [fast_bp(A,eps=eps) for A in [A1,A2]]
dist = np.abs(np.sqrt(S1)-np.sqrt(S2)).sum()
return dist | PypiClean |
/B9gemyaeix-4.14.1.tar.gz/B9gemyaeix-4.14.1/weblate/fonts/views.py |
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied, ValidationError
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.utils.translation import gettext as _
from django.views.generic import DetailView, ListView
from weblate.fonts.forms import FontForm, FontGroupForm, FontOverrideForm
from weblate.fonts.models import Font, FontGroup
from weblate.utils import messages
from weblate.utils.views import ProjectViewMixin
@method_decorator(login_required, name="dispatch")
class FontListView(ProjectViewMixin, ListView):
model = Font
_font_form = None
_group_form = None
def get_queryset(self):
return self.project.font_set.order_by("family", "style")
def get_context_data(self, **kwargs):
result = super().get_context_data(**kwargs)
result["object"] = self.project
result["font_list"] = result["object_list"]
result["group_list"] = self.project.fontgroup_set.order()
result["font_form"] = self._font_form or FontForm()
result["group_form"] = self._group_form or FontGroupForm(
auto_id="id_group_%s", project=self.project
)
result["can_edit"] = self.request.user.has_perm("project.edit", self.project)
return result
def post(self, request, **kwargs):
if not request.user.has_perm("project.edit", self.project):
raise PermissionDenied()
if request.FILES:
form = self._font_form = FontForm(request.POST, request.FILES)
else:
form = self._group_form = FontGroupForm(
request.POST, auto_id="id_group_%s", project=self.project
)
if form.is_valid():
instance = form.save(commit=False)
instance.project = self.project
instance.user = self.request.user
try:
instance.validate_unique()
instance.save()
return redirect(instance)
except ValidationError:
messages.error(request, _("Font with the same name already exists."))
else:
messages.error(request, _("Creation failed, please fix the errors below."))
return self.get(request, **kwargs)
@method_decorator(login_required, name="dispatch")
class FontDetailView(ProjectViewMixin, DetailView):
model = Font
def get_queryset(self):
return self.project.font_set.all()
def get_context_data(self, **kwargs):
result = super().get_context_data(**kwargs)
result["can_edit"] = self.request.user.has_perm("project.edit", self.project)
return result
def post(self, request, **kwargs):
self.object = self.get_object()
if not request.user.has_perm("project.edit", self.project):
raise PermissionDenied()
self.object.delete()
messages.error(request, _("Font deleted."))
return redirect("fonts", project=self.project.slug)
@method_decorator(login_required, name="dispatch")
class FontGroupDetailView(ProjectViewMixin, DetailView):
model = FontGroup
_form = None
_override_form = None
def get_queryset(self):
return self.project.fontgroup_set.all()
def get_context_data(self, **kwargs):
result = super().get_context_data(**kwargs)
result["form"] = self._form or FontGroupForm(
instance=self.object, project=self.project
)
result["override_form"] = self._override_form or FontOverrideForm()
result["can_edit"] = self.request.user.has_perm("project.edit", self.project)
return result
def post(self, request, **kwargs):
self.object = self.get_object()
if not request.user.has_perm("project.edit", self.project):
raise PermissionDenied()
if "name" in request.POST:
form = self._form = FontGroupForm(
request.POST, instance=self.object, project=self.project
)
if form.is_valid():
instance = form.save(commit=False)
try:
instance.validate_unique()
instance.save()
return redirect(self.object)
except ValidationError:
messages.error(
request, _("Font group with the same name already exists.")
)
return self.get(request, **kwargs)
if "language" in request.POST:
form = self._form = FontOverrideForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.group = self.object
try:
instance.validate_unique()
instance.save()
return redirect(self.object)
except ValidationError:
messages.error(
request, _("Font group with the same name already exists.")
)
return self.get(request, **kwargs)
if "override" in request.POST:
try:
self.object.fontoverride_set.filter(
pk=int(request.POST["override"])
).delete()
return redirect(self.object)
except (ValueError, ObjectDoesNotExist):
messages.error(request, _("No override found."))
self.object.delete()
messages.error(request, _("Font group deleted."))
return redirect("fonts", project=self.project.slug) | PypiClean |
/FreePyBX-1.0-RC1.tar.gz/FreePyBX-1.0-RC1/freepybx/public/js/dojox/charting/themes/Tom.js.uncompressed.js | define("dojox/charting/themes/Tom", ["../Theme", "dojox/gfx/gradutils", "./common"], function(Theme, gradutils, themes){
// created by Tom Trenka
var g = Theme.generateGradient,
defaultFill = {type: "linear", space: "shape", x1: 0, y1: 0, x2: 0, y2: 100};
themes.Tom = new Theme({
chart: {
fill: "#181818",
stroke: {color: "#181818"},
pageStyle: {backgroundColor: "#181818", backgroundImage: "none", color: "#eaf2cb"}
},
plotarea: {
fill: "#181818"
},
axis:{
stroke: { // the axis itself
color: "#a0a68b",
width: 1
},
tick: { // used as a foundation for all ticks
color: "#888c76",
position: "center",
font: "normal normal normal 7pt Helvetica, Arial, sans-serif", // labels on axis
fontColor: "#888c76" // color of labels
}
},
series: {
stroke: {width: 2.5, color: "#eaf2cb"},
outline: null,
font: "normal normal normal 8pt Helvetica, Arial, sans-serif",
fontColor: "#eaf2cb"
},
marker: {
stroke: {width: 1.25, color: "#eaf2cb"},
outline: {width: 1.25, color: "#eaf2cb"},
font: "normal normal normal 8pt Helvetica, Arial, sans-serif",
fontColor: "#eaf2cb"
},
seriesThemes: [
{fill: g(defaultFill, "#bf9e0a", "#ecc20c")},
{fill: g(defaultFill, "#73b086", "#95e5af")},
{fill: g(defaultFill, "#c7212d", "#ed2835")},
{fill: g(defaultFill, "#87ab41", "#b6e557")},
{fill: g(defaultFill, "#b86c25", "#d37d2a")}
],
markerThemes: [
{fill: "#bf9e0a", stroke: {color: "#ecc20c"}},
{fill: "#73b086", stroke: {color: "#95e5af"}},
{fill: "#c7212d", stroke: {color: "#ed2835"}},
{fill: "#87ab41", stroke: {color: "#b6e557"}},
{fill: "#b86c25", stroke: {color: "#d37d2a"}}
]
});
themes.Tom.next = function(elementType, mixin, doPost){
var isLine = elementType == "line";
if(isLine || elementType == "area"){
// custom processing for lines: substitute colors
var s = this.seriesThemes[this._current % this.seriesThemes.length];
s.fill.space = "plot";
if(isLine){
s.stroke = { width: 4, color: s.fill.colors[0].color};
}
var theme = Theme.prototype.next.apply(this, arguments);
// cleanup
delete s.outline;
delete s.stroke;
s.fill.space = "shape";
return theme;
}
return Theme.prototype.next.apply(this, arguments);
};
themes.Tom.post = function(theme, elementType){
theme = Theme.prototype.post.apply(this, arguments);
if((elementType == "slice" || elementType == "circle") && theme.series.fill && theme.series.fill.type == "radial"){
theme.series.fill = gradutils.reverse(theme.series.fill);
}
return theme;
};
return themes.Tom;
}); | PypiClean |
/B9gemyaeix-4.14.1.tar.gz/B9gemyaeix-4.14.1/weblate/addons/models.py |
from appconf import AppConf
from django.db import Error as DjangoDatabaseError
from django.db import models
from django.db.models import Q
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.urls import reverse
from django.utils.functional import cached_property
from weblate.addons.events import (
EVENT_CHOICES,
EVENT_COMPONENT_UPDATE,
EVENT_POST_ADD,
EVENT_POST_COMMIT,
EVENT_POST_PUSH,
EVENT_POST_UPDATE,
EVENT_PRE_COMMIT,
EVENT_PRE_PUSH,
EVENT_PRE_UPDATE,
EVENT_STORE_POST_LOAD,
EVENT_UNIT_POST_SAVE,
EVENT_UNIT_PRE_CREATE,
)
from weblate.trans.models import Change, Component, Unit
from weblate.trans.signals import (
component_post_update,
store_post_load,
translation_post_add,
unit_pre_create,
vcs_post_commit,
vcs_post_push,
vcs_post_update,
vcs_pre_commit,
vcs_pre_push,
vcs_pre_update,
)
from weblate.utils.classloader import ClassLoader
from weblate.utils.decorators import disable_for_loaddata
from weblate.utils.errors import report_error
from weblate.utils.fields import JSONField
# Initialize addons registry
ADDONS = ClassLoader("WEBLATE_ADDONS", False)
class AddonQuerySet(models.QuerySet):
def filter_component(self, component):
return self.prefetch_related("event_set").filter(
(Q(component=component) & Q(project_scope=False))
| (Q(component__project=component.project) & Q(project_scope=True))
| (Q(component__linked_component=component) & Q(repo_scope=True))
| (Q(component=component.linked_component) & Q(repo_scope=True))
)
def filter_event(self, component, event):
return component.addons_cache[event]
class Addon(models.Model):
component = models.ForeignKey(Component, on_delete=models.deletion.CASCADE)
name = models.CharField(max_length=100)
configuration = JSONField()
state = JSONField()
project_scope = models.BooleanField(default=False, db_index=True)
repo_scope = models.BooleanField(default=False, db_index=True)
objects = AddonQuerySet.as_manager()
class Meta:
verbose_name = "add-on"
verbose_name_plural = "add-ons"
def __str__(self):
return f"{self.addon.verbose}: {self.component}"
def save(
self, force_insert=False, force_update=False, using=None, update_fields=None
):
cls = self.addon_class
self.project_scope = cls.project_scope
self.repo_scope = cls.repo_scope
# Reallocate to repository
if self.repo_scope and self.component.linked_component:
self.component = self.component.linked_component
# Clear add-on cache
self.component.drop_addons_cache()
# Store history (if not updating state only)
if update_fields != ["state"]:
self.store_change(
Change.ACTION_ADDON_CREATE
if self.pk or force_insert
else Change.ACTION_ADDON_CHANGE
)
return super().save(
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields,
)
def get_absolute_url(self):
return reverse(
"addon-detail",
kwargs={
"project": self.component.project.slug,
"component": self.component.slug,
"pk": self.pk,
},
)
def store_change(self, action):
Change.objects.create(
action=action,
user=self.component.acting_user,
component=self.component,
target=self.name,
details=self.configuration,
)
def configure_events(self, events):
for event in events:
Event.objects.get_or_create(addon=self, event=event)
self.event_set.exclude(event__in=events).delete()
@cached_property
def addon_class(self):
return ADDONS[self.name]
@cached_property
def addon(self):
return self.addon_class(self)
def delete(self, using=None, keep_parents=False):
# Store history
self.store_change(Change.ACTION_ADDON_REMOVE)
# Delete any addon alerts
if self.addon.alert:
self.component.delete_alert(self.addon.alert)
result = super().delete(using=using, keep_parents=keep_parents)
# Trigger post uninstall action
self.addon.post_uninstall()
return result
def disable(self):
self.component.log_warning(
"disabling no longer compatible add-on: %s", self.name
)
self.delete()
class Event(models.Model):
addon = models.ForeignKey(Addon, on_delete=models.deletion.CASCADE)
event = models.IntegerField(choices=EVENT_CHOICES)
class Meta:
unique_together = [("addon", "event")]
verbose_name = "add-on event"
verbose_name_plural = "add-on events"
def __str__(self):
return f"{self.addon}: {self.get_event_display()}"
class AddonsConf(AppConf):
WEBLATE_ADDONS = (
"weblate.addons.gettext.GenerateMoAddon",
"weblate.addons.gettext.UpdateLinguasAddon",
"weblate.addons.gettext.UpdateConfigureAddon",
"weblate.addons.gettext.MsgmergeAddon",
"weblate.addons.gettext.GettextCustomizeAddon",
"weblate.addons.gettext.GettextAuthorComments",
"weblate.addons.cleanup.CleanupAddon",
"weblate.addons.cleanup.RemoveBlankAddon",
"weblate.addons.consistency.LangaugeConsistencyAddon",
"weblate.addons.discovery.DiscoveryAddon",
"weblate.addons.autotranslate.AutoTranslateAddon",
"weblate.addons.flags.SourceEditAddon",
"weblate.addons.flags.TargetEditAddon",
"weblate.addons.flags.SameEditAddon",
"weblate.addons.flags.BulkEditAddon",
"weblate.addons.generate.GenerateFileAddon",
"weblate.addons.generate.PseudolocaleAddon",
"weblate.addons.generate.PrefillAddon",
"weblate.addons.json.JSONCustomizeAddon",
"weblate.addons.properties.PropertiesSortAddon",
"weblate.addons.git.GitSquashAddon",
"weblate.addons.removal.RemoveComments",
"weblate.addons.removal.RemoveSuggestions",
"weblate.addons.resx.ResxUpdateAddon",
"weblate.addons.yaml.YAMLCustomizeAddon",
"weblate.addons.cdn.CDNJSAddon",
)
LOCALIZE_CDN_URL = None
LOCALIZE_CDN_PATH = None
class Meta:
prefix = ""
def handle_addon_error(addon, component):
report_error(cause="add-on error")
# Uninstall no longer compatible add-ons
if not addon.addon.can_install(component, None):
addon.disable()
@receiver(vcs_pre_push)
def pre_push(sender, component, **kwargs):
for addon in Addon.objects.filter_event(component, EVENT_PRE_PUSH):
component.log_debug("running pre_push add-on: %s", addon.name)
try:
addon.addon.pre_push(component)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, component)
@receiver(vcs_post_push)
def post_push(sender, component, **kwargs):
for addon in Addon.objects.filter_event(component, EVENT_POST_PUSH):
component.log_debug("running post_push add-on: %s", addon.name)
try:
addon.addon.post_push(component)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, component)
@receiver(vcs_post_update)
def post_update(
sender,
component,
previous_head: str,
child: bool = False,
skip_push: bool = False,
**kwargs,
):
for addon in Addon.objects.filter_event(component, EVENT_POST_UPDATE):
if child and addon.repo_scope:
continue
component.log_debug("running post_update add-on: %s", addon.name)
try:
addon.addon.post_update(component, previous_head, skip_push)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, component)
@receiver(component_post_update)
def component_update(sender, component, **kwargs):
for addon in Addon.objects.filter_event(component, EVENT_COMPONENT_UPDATE):
component.log_debug("running component_update add-on: %s", addon.name)
try:
addon.addon.component_update(component)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, component)
@receiver(vcs_pre_update)
def pre_update(sender, component, **kwargs):
for addon in Addon.objects.filter_event(component, EVENT_PRE_UPDATE):
component.log_debug("running pre_update add-on: %s", addon.name)
try:
addon.addon.pre_update(component)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, component)
@receiver(vcs_pre_commit)
def pre_commit(sender, translation, author, **kwargs):
addons = Addon.objects.filter_event(translation.component, EVENT_PRE_COMMIT)
for addon in addons:
translation.log_debug("running pre_commit add-on: %s", addon.name)
try:
addon.addon.pre_commit(translation, author)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, translation.component)
@receiver(vcs_post_commit)
def post_commit(sender, component, **kwargs):
addons = Addon.objects.filter_event(component, EVENT_POST_COMMIT)
for addon in addons:
component.log_debug("running post_commit add-on: %s", addon.name)
try:
addon.addon.post_commit(component)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, component)
@receiver(translation_post_add)
def post_add(sender, translation, **kwargs):
addons = Addon.objects.filter_event(translation.component, EVENT_POST_ADD)
for addon in addons:
translation.log_debug("running post_add add-on: %s", addon.name)
try:
addon.addon.post_add(translation)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, translation.component)
@receiver(unit_pre_create)
def unit_pre_create_handler(sender, unit, **kwargs):
addons = Addon.objects.filter_event(
unit.translation.component, EVENT_UNIT_PRE_CREATE
)
for addon in addons:
unit.translation.log_debug("running unit_pre_create add-on: %s", addon.name)
try:
addon.addon.unit_pre_create(unit)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, unit.translation.component)
@receiver(post_save, sender=Unit)
@disable_for_loaddata
def unit_post_save_handler(sender, instance, created, **kwargs):
addons = Addon.objects.filter_event(
instance.translation.component, EVENT_UNIT_POST_SAVE
)
for addon in addons:
instance.translation.log_debug("running unit_post_save add-on: %s", addon.name)
try:
addon.addon.unit_post_save(instance, created)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, instance.translation.component)
@receiver(store_post_load)
def store_post_load_handler(sender, translation, store, **kwargs):
addons = Addon.objects.filter_event(translation.component, EVENT_STORE_POST_LOAD)
for addon in addons:
translation.log_debug("running store_post_load add-on: %s", addon.name)
try:
addon.addon.store_post_load(translation, store)
except DjangoDatabaseError:
raise
except Exception:
handle_addon_error(addon, translation.component) | PypiClean |
/GSAS-II-WONDER_osx-1.0.4.tar.gz/GSAS-II-WONDER_osx-1.0.4/GSAS-II-WONDER/CifFile/YappsStarParser_1_1.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from .StarFile import StarBlock,StarFile,StarList,StarDict
from io import StringIO
# An alternative specification for the Cif Parser, based on Yapps2
# by Amit Patel (http://theory.stanford.edu/~amitp/Yapps)
#
# helper code: we define our match tokens
lastval = ''
def monitor(location,value):
global lastval
#print 'At %s: %s' % (location,repr(value))
lastval = repr(value)
return value
# Strip extras gets rid of leading and trailing whitespace, and
# semicolons.
def stripextras(value):
from .StarFile import remove_line_folding, remove_line_prefix
# we get rid of semicolons and leading/trailing terminators etc.
import re
jj = re.compile("[\n\r\f \t\v]*")
semis = re.compile("[\n\r\f \t\v]*[\n\r\f]\n*;")
cut = semis.match(value)
if cut: #we have a semicolon-delimited string
nv = value[cut.end():len(value)-2]
try:
if nv[-1]=='\r': nv = nv[:-1]
except IndexError: #empty data value
pass
# apply protocols
nv = remove_line_prefix(nv)
nv = remove_line_folding(nv)
return nv
else:
cut = jj.match(value)
if cut:
return stripstring(value[cut.end():])
return value
# helper function to get rid of inverted commas etc.
def stripstring(value):
if value:
if value[0]== '\'' and value[-1]=='\'':
return value[1:-1]
if value[0]=='"' and value[-1]=='"':
return value[1:-1]
return value
# helper function to get rid of triple quotes
def striptriple(value):
if value:
if value[:3] == '"""' and value[-3:] == '"""':
return value[3:-3]
if value[:3] == "'''" and value[-3:] == "'''":
return value[3:-3]
return value
# helper function to populate a StarBlock given a list of names
# and values .
#
# Note that there may be an empty list at the very end of our itemlists,
# so we remove that if necessary.
#
def makeloop(target_block,loopdata):
loop_seq,itemlists = loopdata
if itemlists[-1] == []: itemlists.pop(-1)
# print 'Making loop with %s' % repr(itemlists)
step_size = len(loop_seq)
for col_no in range(step_size):
target_block.AddItem(loop_seq[col_no], itemlists[col_no::step_size],precheck=True)
# print 'Makeloop constructed %s' % repr(loopstructure)
# now construct the loop
try:
target_block.CreateLoop(loop_seq) #will raise ValueError on problem
except ValueError:
error_string = 'Incorrect number of loop values for loop containing %s' % repr(loop_seq)
print(error_string, file=sys.stderr)
raise ValueError(error_string)
# return an object with the appropriate amount of nesting
def make_empty(nestlevel):
gd = []
for i in range(1,nestlevel):
gd = [gd]
return gd
# this function updates a dictionary first checking for name collisions,
# which imply that the CIF is invalid. We need case insensitivity for
# names.
# Unfortunately we cannot check loop item contents against non-loop contents
# in a non-messy way during parsing, as we may not have easy access to previous
# key value pairs in the context of our call (unlike our built-in access to all
# previous loops).
# For this reason, we don't waste time checking looped items against non-looped
# names during parsing of a data block. This would only match a subset of the
# final items. We do check against ordinary items, however.
#
# Note the following situations:
# (1) new_dict is empty -> we have just added a loop; do no checking
# (2) new_dict is not empty -> we have some new key-value pairs
#
def cif_update(old_dict,new_dict,loops):
old_keys = map(lambda a:a.lower(),old_dict.keys())
if new_dict != {}: # otherwise we have a new loop
#print 'Comparing %s to %s' % (repr(old_keys),repr(new_dict.keys()))
for new_key in new_dict.keys():
if new_key.lower() in old_keys:
raise CifError("Duplicate dataname or blockname %s in input file" % new_key)
old_dict[new_key] = new_dict[new_key]
#
# this takes two lines, so we couldn't fit it into a one line execution statement...
def order_update(order_array,new_name):
order_array.append(new_name)
return new_name
# and finally...turn a sequence into a python dict (thanks to Stackoverflow)
def pairwise(iterable):
it = iter(iterable)
while 1:
yield next(it), next(it)
# Begin -- grammar generated by Yapps
import sys, re
from . import yapps3_compiled_rt as yappsrt
class StarParserScanner(yappsrt.Scanner):
def __init__(self, *args,**kwargs):
patterns = [
('([ \t\n\r](?!;))|[ \t]', '([ \t\n\r](?!;))|[ \t]'),
('(#.*[\n\r](?!;))|(#.*)', '(#.*[\n\r](?!;))|(#.*)'),
('LBLOCK', '(L|l)(O|o)(O|o)(P|p)_'),
('GLOBAL', '(G|g)(L|l)(O|o)(B|b)(A|a)(L|l)_'),
('STOP', '(S|s)(T|t)(O|o)(P|p)_'),
('save_heading', '(S|s)(A|a)(V|v)(E|e)_[][!%&\\(\\)*+,./:<=>?@0-9A-Za-z\\\\^`{}\\|~"#$\';_-]+'),
('save_end', '(S|s)(A|a)(V|v)(E|e)_'),
('data_name', '_[][!%&\\(\\)*+,./:<=>?@0-9A-Za-z\\\\^`{}\\|~"#$\';_-]+'),
('data_heading', '(D|d)(A|a)(T|t)(A|a)_[][!%&\\(\\)*+,./:<=>?@0-9A-Za-z\\\\^`{}\\|~"#$\';_-]+'),
('start_sc_line', '(\n|\r\n);([^\n\r])*(\r\n|\r|\n)+'),
('sc_line_of_text', '[^;\r\n]([^\r\n])*(\r\n|\r|\n)+'),
('end_sc_line', ';'),
('data_value_1', '((?!(((S|s)(A|a)(V|v)(E|e)_[^\\s]*)|((G|g)(L|l)(O|o)(B|b)(A|a)(L|l)_[^\\s]*)|((S|s)(T|t)(O|o)(P|p)_[^\\s]*)|((D|d)(A|a)(T|t)(A|a)_[^\\s]*)))[^\\s"#$\'_\\(\\{\\[\\]][^\\s]*)|\'((\'(?=\\S))|([^\n\r\x0c\']))*\'+|"(("(?=\\S))|([^\n\r"]))*"+'),
('END', '$'),
]
yappsrt.Scanner.__init__(self,patterns,['([ \t\n\r](?!;))|[ \t]', '(#.*[\n\r](?!;))|(#.*)'],*args,**kwargs)
class StarParser(yappsrt.Parser):
Context = yappsrt.Context
def input(self, prepared, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'input', [prepared])
_token = self._peek('END', 'data_heading')
if _token == 'data_heading':
dblock = self.dblock(prepared, _context)
allblocks = prepared;allblocks.merge_fast(dblock)
while self._peek('END', 'data_heading') == 'data_heading':
dblock = self.dblock(prepared, _context)
allblocks.merge_fast(dblock)
if self._peek() not in ['END', 'data_heading']:
raise yappsrt.SyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['END', 'data_heading']))
END = self._scan('END')
else: # == 'END'
END = self._scan('END')
allblocks = prepared
return allblocks
def dblock(self, prepared, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'dblock', [prepared])
data_heading = self._scan('data_heading')
heading = data_heading[5:];thisbc=StarFile(characterset='unicode',standard=prepared.standard);newname = thisbc.NewBlock(heading,StarBlock(overwrite=False));act_block=thisbc[newname]
while self._peek('save_heading', 'LBLOCK', 'data_name', 'save_end', 'END', 'data_heading') in ['save_heading', 'LBLOCK', 'data_name']:
_token = self._peek('save_heading', 'LBLOCK', 'data_name')
if _token != 'save_heading':
dataseq = self.dataseq(thisbc[heading], _context)
else: # == 'save_heading'
save_frame = self.save_frame(_context)
thisbc.merge_fast(save_frame,parent=act_block)
if self._peek() not in ['save_heading', 'LBLOCK', 'data_name', 'save_end', 'END', 'data_heading']:
raise yappsrt.SyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['save_heading', 'LBLOCK', 'data_name', 'save_end', 'END', 'data_heading']))
thisbc[heading].setmaxnamelength(thisbc[heading].maxnamelength);return (monitor('dblock',thisbc))
def dataseq(self, starblock, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'dataseq', [starblock])
data = self.data(starblock, _context)
while self._peek('LBLOCK', 'data_name', 'save_heading', 'save_end', 'END', 'data_heading') in ['LBLOCK', 'data_name']:
data = self.data(starblock, _context)
if self._peek() not in ['LBLOCK', 'data_name', 'save_heading', 'save_end', 'END', 'data_heading']:
raise yappsrt.SyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['LBLOCK', 'data_name', 'save_heading', 'save_end', 'END', 'data_heading']))
def data(self, currentblock, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'data', [currentblock])
_token = self._peek('LBLOCK', 'data_name')
if _token == 'LBLOCK':
top_loop = self.top_loop(_context)
makeloop(currentblock,top_loop)
else: # == 'data_name'
datakvpair = self.datakvpair(_context)
currentblock.AddItem(datakvpair[0],datakvpair[1],precheck=True)
def datakvpair(self, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'datakvpair', [])
data_name = self._scan('data_name')
data_value = self.data_value(_context)
return [data_name,data_value]
def data_value(self, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'data_value', [])
_token = self._peek('data_value_1', 'start_sc_line')
if _token == 'data_value_1':
data_value_1 = self._scan('data_value_1')
thisval = stripstring(data_value_1)
else: # == 'start_sc_line'
sc_lines_of_text = self.sc_lines_of_text(_context)
thisval = stripextras(sc_lines_of_text)
return monitor('data_value',thisval)
def sc_lines_of_text(self, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'sc_lines_of_text', [])
start_sc_line = self._scan('start_sc_line')
lines = StringIO();lines.write(start_sc_line)
while self._peek('end_sc_line', 'sc_line_of_text') == 'sc_line_of_text':
sc_line_of_text = self._scan('sc_line_of_text')
lines.write(sc_line_of_text)
if self._peek() not in ['end_sc_line', 'sc_line_of_text']:
raise yappsrt.SyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['sc_line_of_text', 'end_sc_line']))
end_sc_line = self._scan('end_sc_line')
lines.write(end_sc_line);return monitor('sc_line_of_text',lines.getvalue())
def top_loop(self, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'top_loop', [])
LBLOCK = self._scan('LBLOCK')
loopfield = self.loopfield(_context)
loopvalues = self.loopvalues(_context)
return loopfield,loopvalues
def loopfield(self, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'loopfield', [])
toploop=[]
while self._peek('data_name', 'data_value_1', 'start_sc_line') == 'data_name':
data_name = self._scan('data_name')
toploop.append(data_name)
if self._peek() not in ['data_name', 'data_value_1', 'start_sc_line']:
raise yappsrt.SyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['data_name', 'data_value_1', 'start_sc_line']))
return toploop
def loopvalues(self, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'loopvalues', [])
data_value = self.data_value(_context)
dataloop=[data_value]
while self._peek('data_value_1', 'start_sc_line', 'LBLOCK', 'data_name', 'save_heading', 'save_end', 'END', 'data_heading') in ['data_value_1', 'start_sc_line']:
data_value = self.data_value(_context)
dataloop.append(monitor('loopval',data_value))
if self._peek() not in ['data_value_1', 'start_sc_line', 'LBLOCK', 'data_name', 'save_heading', 'save_end', 'END', 'data_heading']:
raise yappsrt.SyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['data_value_1', 'start_sc_line', 'LBLOCK', 'data_name', 'save_heading', 'save_end', 'END', 'data_heading']))
return dataloop
def save_frame(self, _parent=None):
_context = self.Context(_parent, self._scanner, self._pos, 'save_frame', [])
save_heading = self._scan('save_heading')
savehead = save_heading[5:];savebc = StarFile();newname=savebc.NewBlock(savehead,StarBlock(overwrite=False));act_block=savebc[newname]
while self._peek('save_end', 'save_heading', 'LBLOCK', 'data_name', 'END', 'data_heading') in ['save_heading', 'LBLOCK', 'data_name']:
_token = self._peek('save_heading', 'LBLOCK', 'data_name')
if _token != 'save_heading':
dataseq = self.dataseq(savebc[savehead], _context)
else: # == 'save_heading'
save_frame = self.save_frame(_context)
savebc.merge_fast(save_frame,parent=act_block)
if self._peek() not in ['save_end', 'save_heading', 'LBLOCK', 'data_name', 'END', 'data_heading']:
raise yappsrt.SyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['save_end', 'save_heading', 'LBLOCK', 'data_name', 'END', 'data_heading']))
save_end = self._scan('save_end')
return monitor('save_frame',savebc)
def parse(rule, text):
P = StarParser(StarParserScanner(text))
return yappsrt.wrap_error_reporter(P, rule)
# End -- grammar generated by Yapps | PypiClean |
/MLTSA-0.0.7.tar.gz/MLTSA-0.0.7/README.rst |
*****
MLTSA
*****
Info
#####
This is a Python module to apply the MLTSA approach for relevant CV identification on Molecular Dynamics data using both Sklearn and TensorFlow modules.
> examples : Contains files with the easy to call 1D/2D/MD examples to generate data or play around with it as tests for the approach.
> MLTSA_sklearn : Contains the Scikit-Learn integrated functions to apply MLTSA on data.
> MLTSA_tensorflow: Contains the set of functions and different models built on TensorFlow to apply MLTSA on data.
Usage
######
Installation
##############
To use MLTSA, first install it using pip:
.. code-block:: console
(.venv) $ pip install MLTSA
| PypiClean |
/CLOVER_GUI-1.0.0a1-py3-none-any.whl/clover_gui/details/storage.py |
import tkinter as tk
from typing import Callable
import ttkbootstrap as ttk
from clover.impact.finance import COST, COST_DECREASE, OM
from clover.impact.ghgs import GHGS, GHG_DECREASE, OM_GHGS
from clover.simulation.storage_utils import Battery
from ttkbootstrap.constants import *
from ttkbootstrap.scrolled import *
from ..__utils__ import COSTS, EMISSIONS
__all__ = ("StorageFrame",)
class BatteryFrame(ttk.Frame):
"""
Represents the Battery frame.
Contains settings for the battery units.
TODO: Update attributes.
"""
def __init__(self, parent):
super().__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.scrollable_frame = ScrolledFrame(self)
self.scrollable_frame.grid(row=0, column=0, padx=10, pady=5, sticky="news")
self.scrollable_frame.rowconfigure(0, weight=1)
self.scrollable_frame.rowconfigure(1, weight=1)
self.scrollable_frame.rowconfigure(2, weight=1)
self.scrollable_frame.rowconfigure(3, weight=1)
self.scrollable_frame.rowconfigure(4, weight=1)
self.scrollable_frame.rowconfigure(5, weight=1)
self.scrollable_frame.rowconfigure(6, weight=1)
self.scrollable_frame.rowconfigure(7, weight=1)
self.scrollable_frame.rowconfigure(8, weight=1)
self.scrollable_frame.rowconfigure(9, weight=1)
self.scrollable_frame.rowconfigure(10, weight=1)
self.scrollable_frame.rowconfigure(11, weight=1)
self.scrollable_frame.rowconfigure(12, weight=1)
self.scrollable_frame.rowconfigure(13, weight=1)
self.scrollable_frame.rowconfigure(14, weight=1)
self.scrollable_frame.rowconfigure(15, weight=1)
self.scrollable_frame.rowconfigure(16, weight=1)
self.scrollable_frame.columnconfigure(0, weight=10)
self.scrollable_frame.columnconfigure(1, weight=10)
self.scrollable_frame.columnconfigure(2, weight=1)
self.scrollable_frame.columnconfigure(3, weight=1)
self.add_battery_to_system_frame: Callable | None = None
self.set_batteries_on_system_frame: Callable | None = None
# Battery being selected
self.battery_selected_label = ttk.Label(
self.scrollable_frame, text="Battery to configure"
)
self.battery_selected_label.grid(row=0, column=0, padx=10, pady=5, sticky="w")
self.battery_selected = ttk.StringVar(self, "Li-Ion", "battery_selected")
self.battery_name_values = {
"Li-Ion": self.battery_selected,
(battery_name := "Pb-Acid"): ttk.StringVar(self, battery_name),
(battery_name := "New Pb-Acid"): ttk.StringVar(self, battery_name),
}
self.battery_selected_combobox = ttk.Combobox(
self.scrollable_frame, bootstyle=WARNING, textvariable=self.battery_selected
)
self.battery_selected_combobox.grid(
row=0, column=1, padx=10, pady=5, sticky="w", ipadx=60
)
self.battery_selected_combobox.bind("<<ComboboxSelected>>", self.select_battery)
self.populate_available_batteries()
# New battery
self.new_battery_button = ttk.Button(
self.scrollable_frame,
bootstyle=f"{WARNING}-{OUTLINE}",
command=self.add_battery,
text="New battery",
)
self.new_battery_button.grid(row=0, column=2, padx=10, pady=5, ipadx=80)
# Battery name
self.battery_name_label = ttk.Label(self.scrollable_frame, text="Battery name")
self.battery_name_label.grid(row=1, column=0, padx=10, pady=5, sticky="w")
self.battery_name_entry = ttk.Entry(
self.scrollable_frame, bootstyle=WARNING, textvariable=self.battery_selected
)
self.battery_name_entry.grid(
row=1, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.battery_name_entry.bind("<Return>", self.enter_battery_name)
# Battery capacity
self.battery_capacity_label = ttk.Label(self.scrollable_frame, text="Capacity")
self.battery_capacity_label.grid(row=2, column=0, padx=10, pady=5, sticky="w")
self.battery_capacities: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 1, f"{battery_name}_battery_capacity")
for battery_name in self.battery_name_values
}
self.battery_capacity_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.battery_capacities[self.battery_selected.get()],
)
self.battery_capacity_entry.grid(
row=2, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.battery_capacity_unit = ttk.Label(self.scrollable_frame, text="kWh")
self.battery_capacity_unit.grid(row=2, column=2, padx=10, pady=5, sticky="w")
# Maximum charge
self.maximum_charge_label = ttk.Label(
self.scrollable_frame, text="Maximum state of charge"
)
self.maximum_charge_label.grid(row=3, column=0, padx=10, pady=5, sticky="w")
self.maximum_charge: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 90, f"{battery_name}_maximum_charge")
for battery_name in self.battery_name_values
}
def scalar_maximum_charge(_):
self.minimum_charge[self.battery_selected.get()].set(
round(
min(
self.maximum_charge[self.battery_selected.get()].get(),
self.minimum_charge[self.battery_selected.get()].get(),
),
0,
)
)
self.maximum_charge_entry.update()
self.maximum_charge_slider = ttk.Scale(
self.scrollable_frame,
from_=0,
to=100,
orient=tk.HORIZONTAL,
length=320,
command=scalar_maximum_charge,
bootstyle=WARNING,
variable=self.maximum_charge[self.battery_selected.get()],
# state=DISABLED
)
self.maximum_charge_slider.grid(row=3, column=1, padx=10, pady=5, sticky="ew")
def enter_maximum_charge(_):
self.minimum_charge[self.battery_selected.get()].set(
round(
min(
self.maximum_charge[self.battery_selected.get()].get(),
self.minimum_charge[self.battery_selected.get()].get(),
),
2,
)
)
self.maximum_charge[self.battery_selected.get()].set(
round(self.maximum_charge_entry.get(), 2)
)
self.maximum_charge_slider.set(
round(self.maximum_charge[self.battery_selected.get()].get(), 2)
)
self.maximum_charge_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.maximum_charge[self.battery_selected.get()],
)
self.maximum_charge_entry.grid(row=3, column=2, padx=10, pady=5, sticky="ew")
self.maximum_charge_entry.bind("<Return>", enter_maximum_charge)
self.maximum_charge_unit = ttk.Label(self.scrollable_frame, text=f"%")
self.maximum_charge_unit.grid(row=3, column=3, padx=10, pady=5, sticky="ew")
# Minimum charge
self.minimum_charge_label = ttk.Label(
self.scrollable_frame, text="Minimum state of charge"
)
self.minimum_charge_label.grid(row=4, column=0, padx=10, pady=5, sticky="w")
self.minimum_charge: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 20, f"{battery_name}_minimum_charge")
for battery_name in self.battery_name_values
}
def scalar_minimum_charge(_):
self.maximum_charge[self.battery_selected.get()].set(
round(
max(
self.maximum_charge[self.battery_selected.get()].get(),
self.minimum_charge[self.battery_selected.get()].get(),
),
0,
)
)
self.minimum_charge_entry.update()
self.minimum_charge_slider = ttk.Scale(
self.scrollable_frame,
from_=0,
to=100,
orient=tk.HORIZONTAL,
length=320,
command=scalar_minimum_charge,
bootstyle=WARNING,
variable=self.minimum_charge[self.battery_selected.get()],
# state=DISABLED
)
self.minimum_charge_slider.grid(row=4, column=1, padx=10, pady=5, sticky="ew")
def enter_minimum_charge(_):
self.minimum_charge[self.battery_selected.get()].set(
round(self.minimum_charge_entry.get(), 2)
)
self.maximum_charge.set(
round(
max(
self.maximum_charge[self.battery_selected.get()].get(),
self.minimum_charge[self.battery_selected.get()].get(),
),
2,
)
)
self.minimum_charge_slider.set(
self.minimum_charge[self.battery_selected.get()].get()
)
self.minimum_charge_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.minimum_charge[self.battery_selected.get()],
)
self.minimum_charge_entry.grid(row=4, column=2, padx=10, pady=5, sticky="ew")
self.minimum_charge_entry.bind("<Return>", enter_minimum_charge)
self.minimum_charge_unit = ttk.Label(self.scrollable_frame, text=f"%")
self.minimum_charge_unit.grid(row=4, column=3, padx=10, pady=5, sticky="ew")
# Leakage
self.leakage_label = ttk.Label(self.scrollable_frame, text="Leakage")
self.leakage_label.grid(row=5, column=0, padx=10, pady=5, sticky="w")
self.leakage: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 30, f"{battery_name}_leakage")
for battery_name in self.battery_name_values
}
self.leakage_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.leakage[self.battery_selected.get()],
)
self.leakage_entry.grid(row=5, column=1, padx=10, pady=5, sticky="ew", ipadx=80)
self.leakage_unit = ttk.Label(self.scrollable_frame, text="% / hour")
self.leakage_unit.grid(row=5, column=2, padx=10, pady=5, sticky="w")
# Conversion efficiency in
self.conversion_efficiency_in_label = ttk.Label(
self.scrollable_frame, text="Conversion efficiency in"
)
self.conversion_efficiency_in_label.grid(
row=6, column=0, padx=10, pady=5, sticky="w"
)
self.conversion_efficiency_in: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(
self, 97, f"{battery_name}_conversion_efficiency_in"
)
for battery_name in self.battery_name_values
}
def scalar_conversion_efficiency_in(_):
self.conversion_efficiency_in[self.battery_selected.get()].set(
round(self.conversion_efficiency_in_slider.get(), 0)
)
self.conversion_efficiency_in_entry.update()
self.conversion_efficiency_in_slider = ttk.Scale(
self.scrollable_frame,
from_=0,
to=100,
orient=tk.HORIZONTAL,
length=320,
command=scalar_conversion_efficiency_in,
bootstyle=WARNING,
variable=self.conversion_efficiency_in[self.battery_selected.get()],
)
self.conversion_efficiency_in_slider.grid(
row=6, column=1, padx=10, pady=5, sticky="ew"
)
def enter_conversion_efficiency_in(_):
self.conversion_efficiency_in[self.battery_selected.get()].set(
round(self.conversion_efficiency_in_entry.get(), 2)
)
self.conversion_efficiency_in_slider.set(
round(
self.conversion_efficiency_in[self.battery_selected.get()].get(), 2
)
)
self.conversion_efficiency_in_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.conversion_efficiency_in[self.battery_selected.get()],
)
self.conversion_efficiency_in_entry.grid(
row=6, column=2, padx=10, pady=5, sticky="ew"
)
self.conversion_efficiency_in_entry.bind(
"<Return>", enter_conversion_efficiency_in
)
self.conversion_efficiency_in_unit = ttk.Label(self.scrollable_frame, text=f"%")
self.conversion_efficiency_in_unit.grid(
row=6, column=3, padx=10, pady=5, sticky="ew"
)
# Conversion Efficiency (Output)
self.conversion_efficiency_out_label = ttk.Label(
self.scrollable_frame, text="Conversion efficiency out"
)
self.conversion_efficiency_out_label.grid(
row=7, column=0, padx=10, pady=5, sticky="w"
)
self.conversion_efficiency_out: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(
self, 95, f"{battery_name}_conversion_efficiency_out"
)
for battery_name in self.battery_name_values
}
def scalar_conversion_efficiency_out(_):
self.conversion_efficiency_out[self.battery_selected.get()].set(
round(self.conversion_efficiency_out_slider.get(), 0)
)
self.conversion_efficiency_out_entry.update()
self.conversion_efficiency_out_slider = ttk.Scale(
self.scrollable_frame,
from_=0,
to=100,
orient=tk.HORIZONTAL,
length=320,
command=scalar_conversion_efficiency_out,
bootstyle=WARNING,
variable=self.conversion_efficiency_out[self.battery_selected.get()],
)
self.conversion_efficiency_out_slider.grid(
row=7, column=1, padx=10, pady=5, sticky="ew"
)
def enter_conversion_efficiency_out(_):
self.conversion_efficiency_out[self.battery_selected.get()].set(
round(self.conversion_efficiency_out_entry.get(), 2)
)
self.conversion_efficiency_out_slider.set(
round(
self.conversion_efficiency_out[self.battery_selected.get()].get(), 2
)
)
self.conversion_efficiency_out_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.conversion_efficiency_out[self.battery_selected.get()],
)
self.conversion_efficiency_out_entry.grid(
row=7, column=2, padx=10, pady=5, sticky="ew"
)
self.conversion_efficiency_out_entry.bind(
"<Return>", enter_conversion_efficiency_out
)
self.conversion_efficiency_out_unit = ttk.Label(
self.scrollable_frame, text=f"%"
)
self.conversion_efficiency_out_unit.grid(
row=7, column=3, padx=10, pady=5, sticky="ew"
)
# Cycle lifetime
self.cycle_lifetime_label = ttk.Label(
self.scrollable_frame, text="Cycle lifetime"
)
self.cycle_lifetime_label.grid(row=8, column=0, padx=10, pady=5, sticky="w")
self.cycle_lifetime: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 2000, f"{battery_name}_cycle_lifetime")
for battery_name in self.battery_name_values
}
self.cycle_lifetime_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.cycle_lifetime[self.battery_selected.get()],
)
self.cycle_lifetime_entry.grid(
row=8, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.cycle_lifetime_unit = ttk.Label(self.scrollable_frame, text="cycles")
self.cycle_lifetime_unit.grid(row=8, column=2, padx=10, pady=5, sticky="w")
# Lifetime capacity loss
self.lifetime_capacity_loss_label = ttk.Label(
self.scrollable_frame, text="Lifetime capacity loss"
)
self.lifetime_capacity_loss_label.grid(
row=9, column=0, padx=10, pady=5, sticky="w"
)
self.lifetime_capacity_loss: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(
self, 0, f"{battery_name}_lifetime_capacity_loss"
)
for battery_name in self.battery_name_values
}
def scalar_lifetime_capacity_loss(_):
self.lifetime_capacity_loss[self.battery_selected.get()].set(
round(self.lifetime_capacity_loss_slider.get(), 0)
)
# self.lifetime_capacity_loss_entry.configure(str(self.lifetime_capacity_loss.get()))
self.lifetime_capacity_loss_entry.update()
self.lifetime_capacity_loss_slider = ttk.Scale(
self.scrollable_frame,
from_=0,
to=100,
orient=tk.HORIZONTAL,
length=320,
command=scalar_lifetime_capacity_loss,
bootstyle=WARNING,
variable=self.lifetime_capacity_loss[self.battery_selected.get()],
# state=DISABLED
)
self.lifetime_capacity_loss_slider.grid(
row=9, column=1, padx=10, pady=5, sticky="ew"
)
def enter_lifetime_capacity_loss(_):
self.lifetime_capacity_loss[self.battery_selected.get()].set(
round(self.lifetime_capacity_loss_entry.get(), 2)
)
self.lifetime_capacity_loss_slider.set(
round(self.lifetime_capacity_loss[self.battery_selected.get()].get(), 2)
)
self.lifetime_capacity_loss_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.lifetime_capacity_loss[self.battery_selected.get()],
)
self.lifetime_capacity_loss_entry.grid(
row=9, column=2, padx=10, pady=5, sticky="ew"
)
self.lifetime_capacity_loss_entry.bind("<Return>", enter_lifetime_capacity_loss)
self.lifetime_capacity_loss_unit = ttk.Label(self.scrollable_frame, text=f"%")
self.lifetime_capacity_loss_unit.grid(
row=9, column=3, padx=10, pady=5, sticky="ew"
)
# C-rate discharging
self.c_rate_discharging_label = ttk.Label(
self.scrollable_frame, text="C-rate discharging"
)
self.c_rate_discharging_label.grid(
row=10, column=0, padx=10, pady=5, sticky="w"
)
self.c_rate_discharging: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(
self, 0.33, f"{battery_name}_c_rate_discharging"
)
for battery_name in self.battery_name_values
}
self.c_rate_discharging_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.c_rate_discharging[self.battery_selected.get()],
)
self.c_rate_discharging_entry.grid(
row=10, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.c_rate_discharging_unit = ttk.Label(
self.scrollable_frame, text="fraction of capacity / hour"
)
self.c_rate_discharging_unit.grid(row=10, column=2, padx=10, pady=5, sticky="w")
# C-rate charging
self.c_rate_charging_label = ttk.Label(
self.scrollable_frame, text="C-rate charging"
)
self.c_rate_charging_label.grid(row=11, column=0, padx=10, pady=5, sticky="w")
self.c_rate_charging: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 0.33, f"{battery_name}_c_rate_charging")
for battery_name in self.battery_name_values
}
self.c_rate_charging_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.c_rate_charging[self.battery_selected.get()],
)
self.c_rate_charging_entry.grid(
row=11, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.c_rate_charging_unit = ttk.Label(
self.scrollable_frame, text="fraction of capacity / hour"
)
self.c_rate_charging_unit.grid(row=11, column=2, padx=10, pady=5, sticky="w")
# Cost
self.cost_label = ttk.Label(self.scrollable_frame, text="Cost")
self.cost_label.grid(row=12, column=0, padx=10, pady=5, sticky="w")
self.costs: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 0, f"{battery_name}_cost")
for battery_name in self.battery_name_values
}
self.cost_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.costs[self.battery_selected.get()],
)
self.cost_entry.grid(row=12, column=1, padx=10, pady=5, sticky="ew", ipadx=80)
self.cost_unit = ttk.Label(self.scrollable_frame, text="USD ($)")
self.cost_unit.grid(row=12, column=2, padx=10, pady=5, sticky="w")
# Cost decrease
self.cost_decrease_label = ttk.Label(
self.scrollable_frame, text="Cost decrease"
)
self.cost_decrease_label.grid(row=13, column=0, padx=10, pady=5, sticky="w")
self.cost_decrease: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 0, f"{battery_name}_cost_decrease")
for battery_name in self.battery_name_values
}
self.cost_decrease_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.cost_decrease[self.battery_selected.get()],
)
self.cost_decrease_entry.grid(
row=13, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.cost_decrease_unit = ttk.Label(
self.scrollable_frame, text="% decrease / year"
)
self.cost_decrease_unit.grid(row=13, column=2, padx=10, pady=5, sticky="w")
# OPEX costs
self.opex_costs_label = ttk.Label(
self.scrollable_frame, text="OPEX (O&M) costs"
)
self.opex_costs_label.grid(row=14, column=0, padx=10, pady=5, sticky="w")
self.o_and_m_costs: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 0, f"{battery_name}_o_and_m_costs")
for battery_name in self.battery_name_values
}
self.o_and_m_costs_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.o_and_m_costs[self.battery_selected.get()],
)
self.o_and_m_costs_entry.grid(
row=14, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.o_and_m_costs_unit = ttk.Label(self.scrollable_frame, text="USD ($)")
self.o_and_m_costs_unit.grid(row=14, column=2, padx=10, pady=5, sticky="w")
# Embedded emissions
self.embedded_emissions_label = ttk.Label(
self.scrollable_frame, text="Embedded emissions"
)
self.embedded_emissions_label.grid(
row=15, column=0, padx=10, pady=5, sticky="w"
)
self.embedded_emissions: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 0, f"{battery_name}_ghgs")
for battery_name in self.battery_name_values
}
self.embedded_emissions_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.embedded_emissions[self.battery_selected.get()],
)
self.embedded_emissions_entry.grid(
row=15, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.embedded_emissions_unit = ttk.Label(
self.scrollable_frame, text="kgCO2eq / unit"
)
self.embedded_emissions_unit.grid(row=15, column=2, padx=10, pady=5, sticky="w")
# O&M emissions
self.om_emissions_label = ttk.Label(self.scrollable_frame, text="O&M emissions")
self.om_emissions_label.grid(row=16, column=0, padx=10, pady=5, sticky="w")
self.om_emissions: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 0, f"{battery_name}_o_and_m_ghgs")
for battery_name in self.battery_name_values
}
self.om_emissions_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.om_emissions[self.battery_selected.get()],
)
self.om_emissions_entry.grid(
row=16, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.om_emissions_unit = ttk.Label(self.scrollable_frame, text="kgCO2eq / year")
self.om_emissions_unit.grid(row=16, column=2, padx=10, pady=5, sticky="w")
# Annual emissions decrease
self.annual_emissions_decrease_label = ttk.Label(
self.scrollable_frame, text="Annual emissions decrease"
)
self.annual_emissions_decrease_label.grid(
row=17, column=0, padx=10, pady=5, sticky="w"
)
self.annual_emissions_decrease: dict[str, ttk.DoubleVar] = {
battery_name: ttk.DoubleVar(self, 0, f"{battery_name}_ghgs_decrease")
for battery_name in self.battery_name_values
}
self.annual_emissions_decrease_entry = ttk.Entry(
self.scrollable_frame,
bootstyle=WARNING,
textvariable=self.annual_emissions_decrease[self.battery_selected.get()],
)
self.annual_emissions_decrease_entry.grid(
row=17, column=1, padx=10, pady=5, sticky="ew", ipadx=80
)
self.annual_emissions_decrease_unit = ttk.Label(
self.scrollable_frame, text="% / year"
)
self.annual_emissions_decrease_unit.grid(
row=17, column=2, padx=10, pady=5, sticky="w"
)
# TODO: Add configuration frame widgets and layout
def add_battery(self) -> None:
"""Called when a user presses the new battery button."""
# Determine the new name
new_name = "New{suffix}"
index = 0
suffix = ""
while new_name.format(suffix=suffix) in self.battery_name_values:
index += 1
suffix = f"_{index}"
new_name = new_name.format(suffix=suffix)
self.battery_name_values[new_name] = ttk.StringVar(self, new_name)
self.populate_available_batteries()
# Update all the mappings stored
self.battery_capacities[new_name] = ttk.DoubleVar(self, 0)
self.maximum_charge[new_name] = ttk.DoubleVar(self, 100)
self.minimum_charge[new_name] = ttk.DoubleVar(self, 0)
self.leakage[new_name] = ttk.DoubleVar(self, 0)
self.conversion_efficiency_in[new_name] = ttk.DoubleVar(self, 100)
self.conversion_efficiency_out[new_name] = ttk.DoubleVar(self, 100)
self.cycle_lifetime[new_name] = ttk.DoubleVar(self, 0)
self.lifetime_capacity_loss[new_name] = ttk.DoubleVar(self, 100)
self.c_rate_discharging[new_name] = ttk.DoubleVar(self, 1)
self.c_rate_charging[new_name] = ttk.DoubleVar(self, 1)
self.costs[new_name] = ttk.DoubleVar(self, 0)
self.cost_decrease[new_name] = ttk.DoubleVar(self, 0)
self.o_and_m_costs[new_name] = ttk.DoubleVar(self, 0)
self.embedded_emissions[new_name] = ttk.DoubleVar(self, 0)
self.om_emissions[new_name] = ttk.DoubleVar(self, 0)
self.annual_emissions_decrease[new_name] = ttk.DoubleVar(self, 0)
# Select the new battery and update the screen
self.battery_selected = self.battery_name_values[new_name]
self.battery_selected_combobox.configure(textvariable=self.battery_selected)
self.battery_name_entry.configure(textvariable=self.battery_selected)
self.update_battery_frame()
# Add the battery to the system frame
self.add_battery_to_system_frame(new_name)
@property
def batteries(self) -> list[dict[str, float | dict[str, float]]]:
"""
Return a list of batteries based on the information provided in the frame.
:return:
The batteries based on the frame's information.
"""
batteries: list[dict[str, float | dict[str, float]]] = []
for battery_name in self.battery_name_values:
battery_dict = Battery(
self.battery_capacities[battery_name].get(),
self.cycle_lifetime[battery_name].get(),
self.leakage[battery_name].get() / 100,
self.maximum_charge[battery_name].get() / 100,
self.minimum_charge[battery_name].get() / 100,
battery_name,
self.c_rate_charging[battery_name].get(),
self.conversion_efficiency_in[battery_name].get() / 100,
self.conversion_efficiency_out[battery_name].get() / 100,
self.c_rate_discharging[battery_name].get(),
self.lifetime_capacity_loss[battery_name].get() / 100,
self.battery_capacities[battery_name].get(),
True,
).as_dict
# Append cost and emissions information
battery_dict[COSTS] = {
COST: self.costs[battery_name].get(),
COST_DECREASE: self.cost_decrease[battery_name].get(),
OM: self.o_and_m_costs[battery_name].get(),
}
battery_dict[EMISSIONS] = {
GHGS: self.embedded_emissions[battery_name].get(),
GHG_DECREASE: self.annual_emissions_decrease[battery_name].get(),
OM_GHGS: self.om_emissions[battery_name].get(),
}
batteries.append(battery_dict)
return batteries
def enter_battery_name(self, _) -> None:
"""Called when someone enters a new battery name."""
self.populate_available_batteries()
# Update all the mappings stored
self.battery_capacities = {
self.battery_name_values[key].get(): value
for key, value in self.battery_capacities.items()
}
self.maximum_charge = {
self.battery_name_values[key].get(): value
for key, value in self.maximum_charge.items()
}
self.minimum_charge = {
self.battery_name_values[key].get(): value
for key, value in self.minimum_charge.items()
}
self.leakage = {
self.battery_name_values[key].get(): value
for key, value in self.leakage.items()
}
self.conversion_efficiency_in = {
self.battery_name_values[key].get(): value
for key, value in self.conversion_efficiency_in.items()
}
self.conversion_efficiency_out = {
self.battery_name_values[key].get(): value
for key, value in self.conversion_efficiency_out.items()
}
self.cycle_lifetime = {
self.battery_name_values[key].get(): value
for key, value in self.cycle_lifetime.items()
}
self.lifetime_capacity_loss = {
self.battery_name_values[key].get(): value
for key, value in self.lifetime_capacity_loss.items()
}
self.c_rate_discharging = {
self.battery_name_values[key].get(): value
for key, value in self.c_rate_discharging.items()
}
self.c_rate_charging = {
self.battery_name_values[key].get(): value
for key, value in self.c_rate_charging.items()
}
self.costs = {
self.battery_name_values[key].get(): value
for key, value in self.costs.items()
}
self.cost_decrease = {
self.battery_name_values[key].get(): value
for key, value in self.cost_decrease.items()
}
self.o_and_m_costs = {
self.battery_name_values[key].get(): value
for key, value in self.o_and_m_costs.items()
}
self.embedded_emissions = {
self.battery_name_values[key].get(): value
for key, value in self.embedded_emissions.items()
}
self.om_emissions = {
self.battery_name_values[key].get(): value
for key, value in self.om_emissions.items()
}
self.annual_emissions_decrease = {
self.battery_name_values[key].get(): value
for key, value in self.annual_emissions_decrease.items()
}
# Update the battery-name values.
self.battery_name_values = {
entry.get(): entry for entry in self.battery_name_values.values()
}
# Update the battery names on the sysetm frame
self.set_batteries_on_system_frame(list(self.battery_name_values.keys()))
def populate_available_batteries(self) -> None:
"""Populate the combo box with the set of avialable batteries."""
self.battery_selected_combobox["values"] = [
entry.get() for entry in self.battery_name_values.values()
]
def select_battery(self, _) -> None:
# Determine the battery name pre- and post-selection
previous_battery_name: str = {
(entry == self.battery_selected): key
for key, entry in self.battery_name_values.items()
}[True]
selected_battery_name: str = self.battery_selected_combobox.get()
# Reset the value of the old variable
self.battery_name_values[previous_battery_name].set(previous_battery_name)
# Set the variable to be the new selected variable
self.battery_selected = self.battery_name_values[selected_battery_name]
self.battery_selected_combobox.configure(textvariable=self.battery_selected)
self.battery_name_entry.configure(textvariable=self.battery_selected)
# Update the variables being displayed.
self.update_battery_frame()
def set_batteries(
self,
batteries: list[Battery],
battery_costs: dict[str, dict[str, float]],
battery_emissions: dict[str, dict[str, float]],
) -> None:
"""
Set the battery information for the frame based on the inputs provided.
:param: batteries
The `list` of :class:`storage_utils.Battery` instances defined;
:param: battery_costs
The battery cost information
:param: battery_emissions
The battery emissions information;
"""
self.battery_name_values: dict[str, ttk.StringVar] = {}
self.battery_capacities = {}
self.maximum_charge = {}
self.minimum_charge = {}
self.leakage = {}
self.conversion_efficiency_in = {}
self.conversion_efficiency_out = {}
self.cycle_lifetime = {}
self.lifetime_capacity_loss = {}
self.c_rate_charging = {}
self.c_rate_discharging = {}
self.costs = {}
self.cost_decrease = {}
self.o_and_m_costs = {}
self.embedded_emissions = {}
self.om_emissions = {}
self.annual_emissions_decrease = {}
for battery in batteries:
self.battery_name_values[battery.name] = ttk.StringVar(self, battery.name)
# Performance characteristics
self.battery_capacities[battery.name] = ttk.DoubleVar(
self, battery.capacity
)
self.maximum_charge[battery.name] = ttk.DoubleVar(
self, 100 * battery.maximum_charge
)
self.minimum_charge[battery.name] = ttk.DoubleVar(
self, 100 * battery.minimum_charge
)
self.leakage[battery.name] = ttk.DoubleVar(self, 100 * battery.leakage)
self.conversion_efficiency_in[battery.name] = ttk.DoubleVar(
self, 100 * battery.conversion_in
)
self.conversion_efficiency_out[battery.name] = ttk.DoubleVar(
self, 100 * battery.conversion_out
)
self.cycle_lifetime[battery.name] = ttk.DoubleVar(
self, battery.cycle_lifetime
)
self.lifetime_capacity_loss[battery.name] = ttk.DoubleVar(
self, 100 * battery.lifetime_loss
)
self.c_rate_discharging[battery.name] = ttk.DoubleVar(
self, battery.discharge_rate
)
self.c_rate_charging[battery.name] = ttk.DoubleVar(
self, battery.charge_rate
)
# Costs
self.costs[battery.name] = ttk.DoubleVar(
self, (this_battery_costs := battery_costs[battery.name]).get(COST, 0)
)
self.cost_decrease[battery.name] = ttk.DoubleVar(
self, this_battery_costs.get(COST_DECREASE, 0)
)
self.o_and_m_costs[battery.name] = ttk.DoubleVar(
self, this_battery_costs.get(OM, 0)
)
# Emissions
self.embedded_emissions[battery.name] = ttk.DoubleVar(
self,
(this_battery_emissions := battery_emissions[battery.name]).get(
GHGS, 0
),
)
self.om_emissions[battery.name] = ttk.DoubleVar(
self, this_battery_emissions.get(GHG_DECREASE, 0)
)
self.annual_emissions_decrease[battery.name] = ttk.DoubleVar(
self, this_battery_emissions.get(OM_GHGS, 0)
)
self.battery_selected = self.battery_name_values[batteries[0].name]
self.battery_selected_combobox["values"] = [
battery.name for battery in batteries
]
self.battery_selected_combobox.set(self.battery_selected.get())
self.select_battery(self.battery_selected.get())
def update_battery_frame(self) -> None:
"""
Updates the entries so that the correct variables are displayed on the screen.
"""
self.battery_capacity_entry.configure(
textvariable=self.battery_capacities[self.battery_selected.get()]
)
self.maximum_charge_entry.configure(
textvariable=self.maximum_charge[self.battery_selected.get()]
)
self.maximum_charge_slider.configure(
variable=self.maximum_charge[self.battery_selected.get()]
)
self.minimum_charge_entry.configure(
textvariable=self.minimum_charge[self.battery_selected.get()]
)
self.minimum_charge_slider.configure(
variable=self.minimum_charge[self.battery_selected.get()]
)
self.leakage_entry.configure(
textvariable=self.leakage[self.battery_selected.get()]
)
self.conversion_efficiency_in_slider.configure(
variable=self.conversion_efficiency_in[self.battery_selected.get()]
)
self.conversion_efficiency_in_entry.configure(
textvariable=self.conversion_efficiency_in[self.battery_selected.get()]
)
self.conversion_efficiency_out_slider.configure(
variable=self.conversion_efficiency_out[self.battery_selected.get()]
)
self.conversion_efficiency_out_entry.configure(
textvariable=self.conversion_efficiency_out[self.battery_selected.get()]
)
self.cycle_lifetime_entry.configure(
textvariable=self.cycle_lifetime[self.battery_selected.get()]
)
self.lifetime_capacity_loss_slider.configure(
variable=self.lifetime_capacity_loss[self.battery_selected.get()]
)
self.lifetime_capacity_loss_entry.configure(
textvariable=self.lifetime_capacity_loss[self.battery_selected.get()]
)
self.c_rate_discharging_entry.configure(
textvariable=self.c_rate_discharging[self.battery_selected.get()]
)
self.c_rate_charging_entry.configure(
textvariable=self.c_rate_charging[self.battery_selected.get()]
)
self.cost_entry.configure(textvariable=self.costs[self.battery_selected.get()])
self.cost_decrease_entry.configure(
textvariable=self.cost_decrease[self.battery_selected.get()]
)
self.o_and_m_costs_entry.configure(
textvariable=self.o_and_m_costs[self.battery_selected.get()]
)
self.embedded_emissions_entry.configure(
textvariable=self.embedded_emissions[self.battery_selected.get()]
)
self.annual_emissions_decrease_entry.configure(
textvariable=self.annual_emissions_decrease[self.battery_selected.get()]
)
self.om_emissions_entry.configure(
textvariable=self.om_emissions[self.battery_selected.get()]
)
# Update the entries
self.battery_capacity_entry.update()
self.maximum_charge_entry.update()
self.minimum_charge_entry.update()
self.maximum_charge_slider.update()
self.minimum_charge_slider.update()
self.leakage_entry.update()
self.conversion_efficiency_in_slider.update()
self.conversion_efficiency_in_entry.update()
self.conversion_efficiency_out_slider.update()
self.conversion_efficiency_out_entry.update()
self.cycle_lifetime_entry.update()
self.lifetime_capacity_loss_slider.update()
self.lifetime_capacity_loss_entry.update()
self.c_rate_discharging_entry.update()
self.c_rate_charging_entry.update()
self.cost_entry.update()
self.cost_decrease_entry.update()
self.o_and_m_costs_entry.update()
self.embedded_emissions_entry.update()
self.annual_emissions_decrease_entry.update()
self.om_emissions_entry.update()
class TankFrame(ttk.Frame):
"""
Represents the Tank frame.
Contains settings for the tank units.
TODO: Update attributes.
"""
def __init__(self, parent):
super().__init__(parent)
self.label = ttk.Label(self, text="Tank frame")
self.label.grid(row=0, column=0)
# TODO: Add configuration frame widgets and layout
class StorageFrame(ttk.Frame):
"""
Represents the Storage frame.
Contains settings for storage units.
TODO: Update attributes.
"""
def __init__(self, parent):
super().__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.storage_notebook = ttk.Notebook(self, bootstyle=WARNING)
self.storage_notebook.grid(row=0, column=0, padx=20, pady=10, sticky="news")
self.battery_frame = BatteryFrame(self)
self.storage_notebook.add(self.battery_frame, text="Batteries", sticky="news")
self.tank_frame = TankFrame(self)
# self.storage_notebook.add(
# self.tank_frame, text="Water tanks", sticky="news", state=DISABLED
# )
# TODO: Add configuration frame widgets and layout | PypiClean |
/CryptoDigital-0.0.2.tar.gz/CryptoDigital-0.0.2/README.md | # Example Package
[GetHub Project](https://github.com/DrSudoSaeed/)
This is a library to get the online price of digital currencies
This library is very easy and convenient to use !
**Follow the steps below to use:**
```
from CryptoDigital import *
# Use the following function to get the dollar price:
print(dolar())
# Use the following function to get the price of digital currencies:
print(crypto())
```
For criticisms and suggestions,<br>contact the author of this libraryon Telegram and Instagram :)
telegram --> [SudoSaeed](https://t.me/sudosaeed/)<br>
instagram --> [SudoSaeed](https://www.instagram.com/sudosaeed/) | PypiClean |
/ADDPIO-1.0.3b1.tar.gz/ADDPIO-1.0.3b1/README.rst | ADDPIO project
==================
This project allows the Raspberry Pi* to access the sensors (accelerometer, gyroscope, ...)
and other IO of an Android* device, similar to the GPIO library. There is a corresponding
Android app (ADDPIO on the Google Play Store) to run on the Android device(s). The Raspberry
Pi and all Android devices must be connected to the same network. This uses UDP port 6297 to
communicate. Create a new ADDPIO object passing the ip address (this is displayed on the
Android app). The object has an input and output function that takes a type number and value.
See below for the standard type number symbols or use the number displayed on the Android app.
The Android sensors return an array of values (e.g. x,y,z). For ADDPIO sensor input the value
parameter represents the index into the array of values returned by the sensor. For other input,
the value is ignored.
The Android app has several widgets for IO:
buttons, LEDs, a touchpad, alarm, notification, and text.
Read the ip address and available sensors from the Android app.
from ADDPIO import ADDPIO
myHost = ADDPIO("192.168.0.0")
myValue = myHost.input(ADDPIO.SENSOR_ACCELEROMETER,1)
myValue = myHost.input(12345,47)
myHost.output(ADDPIO.ALARM,1)
myHost.output(ADDPIO.ALARM,0)
See the testADDPIO.py program for an example.
# Android sensors
SENSOR_ACCELEROMETER
SENSOR_AMBIENT_TEMPERATURE
SENSOR_GAME_ROTATION_VECTOR
SENSOR_GEOMAGNETIC_ROTATION_VECTOR
SENSOR_GRAVITY
SENSOR_GYROSCOPE
SENSOR_GYROSCOPE_UNCALIBRATED
SENSOR_HEART_BEAT
SENSOR_HEART_RATE
SENSOR_LIGHT
SENSOR_LINEAR_ACCELERATION
SENSOR_MAGNETIC_FIELD
SENSOR_MAGNETIC_FIELD_UNCALIBRATED
SENSOR_MOTION_DETECT
SENSOR_ORIENTATION
SENSOR_POSE_6DOF
SENSOR_PRESSURE
SENSOR_PROXIMITY
SENSOR_RELATIVE_HUMIDITY
SENSOR_ROTATION_VECTOR
SENSOR_SIGNIFICANT_MOTION
SENSOR_STATIONARY_DETECT
SENSOR_STEP_COUNTER
SENSOR_STEP_DETECTOR
SENSOR_TEMPERATURE
# Android input/output
BUTTON_1 input 0/1
BUTTON_2 input 0/1
LED_RED output 0/1
LED_GREEN output 0/1
LED_BLUE output 0/1
ALARM output 0/1
NOTIFICATION output any number
TEXT output any number
TOUCH_PAD_X_IN input 0-255
TOUCH_PAD_Y_IN input 0-255
TOUCH_PAD_X_OUT output 0-255
TOUCH_PAD_Y_OUT output 0-255
* Raspberry Pi is a trademark of the Raspberry Pi Foundation - http://www.raspberrypi.org
* Android is a trademark of Google Inc.
| PypiClean |
/Electrum-CHI-3.3.8.tar.gz/Electrum-CHI-3.3.8/packages/aiohttp_socks/proto.py | import asyncio
import socket
import struct
from .errors import (
SocksConnectionError, InvalidServerReply, SocksError,
InvalidServerVersion, NoAcceptableAuthMethods,
LoginAuthenticationFailed, UnknownAuthMethod
)
RSV = NULL = 0x00
SOCKS_VER4 = 0x04
SOCKS_VER5 = 0x05
SOCKS_CMD_CONNECT = 0x01
SOCKS_CMD_BIND = 0x02
SOCKS_CMD_UDP_ASSOCIATE = 0x03
SOCKS4_GRANTED = 0x5A
SOCKS5_GRANTED = 0x00
SOCKS5_AUTH_ANONYMOUS = 0x00
SOCKS5_AUTH_UNAME_PWD = 0x02
SOCKS5_AUTH_NO_ACCEPTABLE_METHODS = 0xFF
SOCKS5_ATYP_IPv4 = 0x01
SOCKS5_ATYP_DOMAIN = 0x03
SOCKS5_ATYP_IPv6 = 0x04
SOCKS4_ERRORS = {
0x5B: 'Request rejected or failed',
0x5C: 'Request rejected because SOCKS server '
'cannot connect to identd on the client',
0x5D: 'Request rejected because the client program '
'and identd report different user-ids'
}
SOCKS5_ERRORS = {
0x01: 'General SOCKS server failure',
0x02: 'Connection not allowed by ruleset',
0x03: 'Network unreachable',
0x04: 'Host unreachable',
0x05: 'Connection refused',
0x06: 'TTL expired',
0x07: 'Command not supported, or protocol error',
0x08: 'Address type not supported'
}
def _is_proactor(loop): # pragma: no cover
try:
from asyncio import ProactorEventLoop
except ImportError:
return False
return isinstance(loop, ProactorEventLoop)
def _is_uvloop(loop): # pragma: no cover
try:
# noinspection PyPackageRequirements
from uvloop import Loop
except ImportError:
return False
return isinstance(loop, Loop)
class SocksVer(object):
SOCKS4 = 1
SOCKS5 = 2
class BaseSocketWrapper(object):
def __init__(self, loop, host, port,
family=socket.AF_INET):
self._loop = loop
self._socks_host = host
self._socks_port = port
self._dest_host = None
self._dest_port = None
self._family = family
self._socket = None
async def _send(self, request):
data = bytearray()
for item in request:
if isinstance(item, int):
data.append(item)
elif isinstance(item, (bytearray, bytes)):
data += item
else:
raise ValueError('Unsupported item')
await self._loop.sock_sendall(self._socket, data)
async def _receive(self, n):
data = b''
while len(data) < n:
packet = await self._loop.sock_recv(self._socket, n - len(data))
if not packet:
raise InvalidServerReply('Not all data available')
data += packet
return bytearray(data)
async def _resolve_addr(self, host, port):
addresses = await self._loop.getaddrinfo(
host=host, port=port, family=socket.AF_UNSPEC,
type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP,
flags=socket.AI_ADDRCONFIG)
if not addresses:
raise OSError('Can`t resolve address %s:%s' % (host, port))
family = addresses[0][0]
addr = addresses[0][4][0]
return family, addr
async def negotiate(self):
raise NotImplementedError
async def connect(self, address):
self._dest_host = address[0]
self._dest_port = address[1]
self._socket = socket.socket(
family=self._family,
type=socket.SOCK_STREAM
)
self._socket.setblocking(False)
try:
await self._loop.sock_connect(
sock=self._socket,
address=(self._socks_host, self._socks_port)
)
except OSError as e:
self.close()
raise SocksConnectionError(
e.errno,
'Can not connect to proxy %s:%d [%s]' %
(self._socks_host, self._socks_port, e.strerror)) from e
except asyncio.CancelledError: # pragma: no cover
self.close()
raise
try:
await self.negotiate()
except SocksError:
self.close()
raise
except asyncio.CancelledError: # pragma: no cover
if _is_proactor(self._loop) or _is_uvloop(self._loop):
self.close()
raise
def close(self):
self._socket.close()
async def sendall(self, data):
await self._loop.sock_sendall(self._socket, data)
async def recv(self, nbytes):
return await self._loop.sock_recv(self._socket, nbytes)
@property
def socket(self):
return self._socket
class Socks4SocketWrapper(BaseSocketWrapper):
def __init__(self, loop, host, port,
user_id=None, rdns=False):
super().__init__(
loop=loop,
host=host,
port=port,
family=socket.AF_INET
)
self._user_id = user_id
self._rdns = rdns
async def _socks_connect(self):
host, port = self._dest_host, self._dest_port
port_bytes = struct.pack(b'>H', port)
include_hostname = False
try:
# destination address provided is an IP address
host_bytes = socket.inet_aton(host)
except socket.error:
# not IP address, probably a DNS name
if self._rdns:
# remote resolve (SOCKS4a)
host_bytes = bytes([NULL, NULL, NULL, 0x01])
include_hostname = True
else:
# resolve locally
family, host = await self._resolve_addr(host, port)
host_bytes = socket.inet_aton(host)
# build and send connect command
req = [SOCKS_VER4, SOCKS_CMD_CONNECT, port_bytes, host_bytes]
if self._user_id:
req.append(self._user_id.encode())
req.append(NULL)
if include_hostname:
req += [host.encode('idna'), NULL]
await self._send(req)
res = await self._receive(8)
if res[0] != NULL:
raise InvalidServerReply('SOCKS4 proxy server sent invalid data')
if res[1] != SOCKS4_GRANTED:
error = SOCKS4_ERRORS.get(res[1], 'Unknown error')
raise SocksError('[Errno {0:#04x}]: {1}'.format(res[1], error))
binded_addr = (
socket.inet_ntoa(res[4:]),
struct.unpack('>H', res[2:4])[0]
)
return (host, port), binded_addr
async def negotiate(self):
await self._socks_connect()
class Socks5SocketWrapper(BaseSocketWrapper):
def __init__(self, loop, host, port, username=None,
password=None, rdns=True, family=socket.AF_INET):
super().__init__(
loop=loop,
host=host,
port=port,
family=family
)
self._username = username
self._password = password
self._rdns = rdns
async def _socks_auth(self):
# send auth methods
if self._username and self._password:
auth_methods = [SOCKS5_AUTH_UNAME_PWD, SOCKS5_AUTH_ANONYMOUS]
else:
auth_methods = [SOCKS5_AUTH_ANONYMOUS]
req = [SOCKS_VER5, len(auth_methods)] + auth_methods
await self._send(req)
res = await self._receive(2)
ver, auth_method = res[0], res[1]
if ver != SOCKS_VER5:
raise InvalidServerVersion(
'Unexpected SOCKS version number: %s' % ver
)
if auth_method == SOCKS5_AUTH_NO_ACCEPTABLE_METHODS:
raise NoAcceptableAuthMethods(
'No acceptable authentication methods were offered'
)
if auth_method not in auth_methods:
raise UnknownAuthMethod(
'Unexpected SOCKS authentication method: %s' % auth_method
)
# authenticate
if auth_method == SOCKS5_AUTH_UNAME_PWD:
req = [0x01,
chr(len(self._username)).encode(),
self._username.encode(),
chr(len(self._password)).encode(),
self._password.encode()]
await self._send(req)
res = await self._receive(2)
ver, status = res[0], res[1]
if ver != 0x01:
raise InvalidServerReply('Invalid authentication response')
if status != SOCKS5_GRANTED:
raise LoginAuthenticationFailed(
'Username and password authentication failure'
)
async def _socks_connect(self):
req_addr, resolved_addr = await self._build_dest_address()
req = [SOCKS_VER5, SOCKS_CMD_CONNECT, RSV] + req_addr
await self._send(req)
res = await self._receive(3)
ver, err_code, reserved = res[0], res[1], res[2]
if ver != SOCKS_VER5:
raise InvalidServerVersion(
'Unexpected SOCKS version number: %s' % ver
)
if err_code != 0x00:
raise SocksError(SOCKS5_ERRORS.get(err_code, 'Unknown error'))
if reserved != 0x00:
raise InvalidServerReply('The reserved byte must be 0x00')
binded_addr = await self._read_binded_address()
return resolved_addr, binded_addr
async def _build_dest_address(self):
host = self._dest_host
port = self._dest_port
family_to_byte = {socket.AF_INET: SOCKS5_ATYP_IPv4,
socket.AF_INET6: SOCKS5_ATYP_IPv6}
port_bytes = struct.pack('>H', port)
# destination address provided is an IPv4 or IPv6 address
for family in (socket.AF_INET, socket.AF_INET6):
try:
host_bytes = socket.inet_pton(family, host)
req = [family_to_byte[family], host_bytes, port_bytes]
return req, (host, port)
except socket.error:
pass
# not IP address, probably a DNS name
if self._rdns:
# resolve remotely
host_bytes = host.encode('idna')
req = [SOCKS5_ATYP_DOMAIN, chr(len(host_bytes)).encode(),
host_bytes, port_bytes]
else:
# resolve locally
family, addr = await self._resolve_addr(host=host, port=port)
host_bytes = socket.inet_pton(family, addr)
req = [family_to_byte[family], host_bytes, port_bytes]
host = socket.inet_ntop(family, host_bytes)
return req, (host, port)
async def _read_binded_address(self):
atype = (await self._receive(1))[0]
if atype == SOCKS5_ATYP_IPv4:
addr = await self._receive(4)
addr = socket.inet_ntoa(addr)
elif atype == SOCKS5_ATYP_DOMAIN:
length = await self._receive(1)
addr = await self._receive(ord(length))
elif atype == SOCKS5_ATYP_IPv6:
addr = await self._receive(16)
addr = socket.inet_ntop(socket.AF_INET6, addr)
else:
raise InvalidServerReply('SOCKS5 proxy server sent invalid data')
port = await self._receive(2)
port = struct.unpack('>H', port)[0]
return addr, port
async def negotiate(self):
await self._socks_auth()
await self._socks_connect() | PypiClean |
/CoolAMQP-1.2.15.tar.gz/CoolAMQP-1.2.15/coolamqp/attaches/declarer.py | from __future__ import print_function, absolute_import, division
import collections
import logging
from concurrent.futures import Future
from coolamqp.attaches.channeler import Channeler, ST_ONLINE
from coolamqp.attaches.utils import Synchronized
from coolamqp.exceptions import AMQPError, ConnectionDead
from coolamqp.framing.definitions import ChannelOpenOk, ExchangeDeclare, \
ExchangeDeclareOk, QueueDeclare, \
QueueDeclareOk, ChannelClose, QueueDelete, QueueDeleteOk, QueueBind, QueueBindOk
from coolamqp.objects import Exchange, Queue, Callable, QueueBind as CommandQueueBind
logger = logging.getLogger(__name__)
class Operation(object):
"""
An abstract operation.
This class possesses the means to carry itself out and report back status.
Represents the op currently carried out.
This will register it's own callback. Please, call on_connection_dead when connection is broken
to fail futures with ConnectionDead, since this object does not watch for Fails
"""
__slots__ = ('done', 'fut', 'declarer', 'obj', 'on_done', 'parent_span', 'enqueued_span',
'processing_span')
def __init__(self, declarer, obj, fut=None, span_parent=None, span_enqueued=None):
self.done = False
self.fut = fut
self.parent_span = span_parent
self.enqueued_span = span_enqueued
self.processing_span = None
self.declarer = declarer
self.obj = obj
self.on_done = Callable() # callable/0
def span_exception(self, exception):
if self.parent_span is not None:
if self.enqueued_span is None:
from opentracing import tags, logs
self.enqueued_span.set_tag(tags.ERROR, True)
self.enqueued_span.log_kv({logs.EVENT: tags.ERROR,
logs.ERROR_KIND: exception,
logs.ERROR_OBJECT: exception})
self.enqueued_span.finish()
self.enqueued_span = None
if self.processing_span is not None:
from opentracing import tags, logs
self.processing_span.set_tag(tags.ERROR, True)
self.processing_span.log_kv({logs.EVENT: tags.ERROR,
logs.ERROR_KIND: exception,
logs.ERROR_OBJECT: exception})
self.processing_span.finish()
self.processing_span = None
if self.enqueued_span is not None:
self.enqueued_span.finish()
self.enqueued_span = None
self.parent_span.finish()
def on_connection_dead(self):
"""To be called by declarer when our link fails"""
if self.fut is not None:
err = ConnectionDead()
self.span_exception(err)
self.fut.set_exception(err)
self.fut = None
def span_starting(self):
if self.enqueued_span is not None:
self.enqueued_span.finish()
from opentracing import follows_from
self.processing_span = self.declarer.cluster.tracer.start_span('Declaring',
child_of=self.parent_span,
references=follows_from(self.enqueued_span))
self.enqueued_span = None
def span_finished(self):
if self.processing_span is not None:
self.processing_span.finish()
self.processing_span = None
def span_begin(self):
if self.enqueued_span is not None:
self.enqueued_span.finish()
from opentracing import follows_from
self.processing_span = self.declarer.cluster.tracer.start_span('Declaring',
child_of=self.parent_span,
references=follows_from(self.enqueued_span))
self.enqueued_span = None
def perform(self):
"""Attempt to perform this op."""
self.span_begin()
obj = self.obj
if isinstance(obj, Exchange):
self.declarer.method_and_watch(
ExchangeDeclare(self.obj.name.encode('utf8'), obj.type, False,
obj.durable,
obj.auto_delete, False, False, []),
(ExchangeDeclareOk, ChannelClose),
self._callback)
elif isinstance(obj, Queue):
self.declarer.method_and_watch(
QueueDeclare(obj.name, False, obj.durable, obj.exclusive,
obj.auto_delete, False, []),
(QueueDeclareOk, ChannelClose),
self._callback)
elif isinstance(obj, CommandQueueBind):
self.declarer.method_and_watch(
QueueBind(obj.queue, obj.exchange, obj.routing_key, False, []),
(QueueBindOk, ChannelClose),
self._callback
)
def _callback(self, payload):
assert not self.done
self.done = True
if isinstance(payload, ChannelClose):
err = AMQPError(payload)
self.span_exception(err)
if self.fut is not None:
self.fut.set_exception(err)
self.fut = None
else:
# something that had no Future failed. Is it in declared?
if self.obj in self.declarer.declared:
self.declarer.declared.remove(
self.obj) # todo access not threadsafe
self.declarer.on_discard(self.obj)
else:
if isinstance(payload, QueueDeclareOk) and self.obj.anonymous:
self.obj.name = payload.queue
self.obj.anonymous = False
self.span_finished()
if self.fut is not None:
self.fut.set_result(None)
self.fut = None
self.declarer.on_operation_done()
class DeleteQueue(Operation):
def __init__(self, declarer, queue, fut, span_parent=None, span_enqueued=None):
super(DeleteQueue, self).__init__(declarer, queue, fut=fut, span_parent=span_parent,
span_enqueued=span_enqueued)
def perform(self):
queue = self.obj
self.declarer.method_and_watch(
QueueDelete(queue.name, False, False, False),
(QueueDeleteOk, ChannelClose),
self._callback)
def _callback(self, payload):
assert not self.done
self.done = True
if isinstance(payload, ChannelClose):
err = AMQPError(payload)
self.span_exception(err)
self.fut.set_exception(err)
else: # Queue.DeleteOk
self.span_finished()
self.fut.set_result(None)
self.declarer.on_operation_done()
class Declarer(Channeler, Synchronized):
"""
Doing other things, such as declaring, deleting and other stuff.
This also maintains a list of declared queues/exchanges, and redeclares them on each reconnect.
"""
def __init__(self, cluster):
"""
Create a new declarer.
"""
Channeler.__init__(self)
Synchronized.__init__(self)
self.cluster = cluster
self.declared = set() # since Queues and Exchanges are hashable...
# anonymous queues aren't, but we reject those
# persistent
self.left_to_declare = collections.deque() # since last disconnect. persistent+transient
# deque of Operation objects
self.on_discard = Callable() # callable/1, with discarded elements
self.in_process = None # Operation instance that is being progressed right now
def on_close(self, payload=None):
# we are interested in ChannelClose during order execution,
# because that means that operation was illegal, and must
# be discarded/exceptioned on future
if payload is None:
if self.in_process is not None:
self.in_process.on_connection_dead()
self.in_process = None
# connection down, panic mode engaged.
while len(self.left_to_declare) > 0:
self.left_to_declare.pop().on_connection_dead()
# recast current declarations as new operations
for dec in self.declared:
self.left_to_declare.append(Operation(self, dec))
super(Declarer, self).on_close()
return
elif isinstance(payload, ChannelClose):
# Looks like a soft fail - we may try to survive that
old_con = self.connection
super(Declarer, self).on_close()
# But, we are super optimists. If we are not cancelled, and connection is ok,
# we must reestablish
if old_con.state == ST_ONLINE and not self.cancelled:
self.attach(old_con)
else:
super(Declarer, self).on_close(payload)
def on_operation_done(self):
"""
Called by operation, when it's complete (whether success or fail).
Not called when operation fails due to DC
"""
self.in_process = None
self._do_operations()
def delete_queue(self, queue, span=None):
"""
Delete a queue.
Future is returned, so that user knows when it happens. This may fail.
Returned Future is already running, and so cannot be cancelled.
If the queue is in declared consumer list, it will not be removed.
:param queue: Queue instance
:param span: optional span, if opentracing is installed
:return: a Future
"""
fut = Future()
fut.set_running_or_notify_cancel()
self.left_to_declare.append(DeleteQueue(self, queue, fut))
self._do_operations()
return fut
def declare(self, obj, persistent=False, span=None):
"""
Schedule to have an object declared.
Future is returned, so that user knows when it happens.
Returned Future is already running, and so cannot be cancelled.
Exchange declarations never fail.
Of course they do, but you will be told that it succeeded. This is by design,
and due to how AMQP works.
Queue declarations CAN fail.
Note that if re-declaring these fails, they will be silently discarded.
You can subscribe an on_discard(Exchange | Queue) here.
:param obj: Exchange or Queue instance
:param persistent: will be redeclared upon disconnect. To remove, use "undeclare"
:param span: span if opentracing is installed
:return: a Future instance
:raise ValueError: tried to declare anonymous queue
"""
if span is not None:
enqueued_span = self.cluster.tracer.start_span('Enqueued', child_of=span)
else:
span = None
enqueued_span = None
fut = Future()
fut.set_running_or_notify_cancel()
if persistent:
if obj not in self.declared:
self.declared.add(obj) # todo access not threadsafe
self.left_to_declare.append(Operation(self, obj, fut, span, enqueued_span))
self._do_operations()
return fut
@Synchronized.synchronized
def _do_operations(self):
"""
Attempt to execute something.
To be called when it's possible that something can be done
"""
if (self.state != ST_ONLINE) or len(self.left_to_declare) == 0 or (
self.in_process is not None):
return
self.in_process = self.left_to_declare.popleft()
self.in_process.perform()
def on_setup(self, payload):
if isinstance(payload, ChannelOpenOk):
assert self.in_process is None
self.state = ST_ONLINE
self._do_operations() | PypiClean |
/Flask_RESTful_DRY-0.3.1-py3-none-any.whl/flask_dry/api/allow.py |
r'''Allow/deny objects.
All of these objects are intended to be immutable.
'''
__all__ = ('Allow', 'Deny')
class base:
def __init__(self, *names):
self._names = frozenset(names)
def __repr__(self):
return "<{}: {}>".format(self.__class__.__name__, sorted(self._names))
def intersection(self, other):
r'''Returns the intersection of self and other.
Returns a new Allowed object.
'''
if isinstance(other, Deny):
return self.denying(*other._names)
return self.intersection_allowed(other._names)
def test(self, allowed, denied):
a, d = self.allowed_denied(allowed)
assert a == frozenset(allowed)
assert not d
a, d = self.allowed_denied(denied)
assert not a
assert d == frozenset(denied)
class Allow(base):
r'''Allows a specific set of names.
These actually work for any hashable type.
>>> a = Allow('a', 'b', None)
>>> a.allow('a')
True
>>> a.allow(None)
True
>>> a.allow('d')
False
>>> a.test(('b', None), 'cd')
'''
def intersection_allowed(self, allowed):
r'''Returns intersection with allowed set.
>>> a = Allow('a', 'b')
>>> b = Allow('b', 'c')
>>> c = a.intersection(b)
>>> c.test('b', 'acd')
>>> b = Deny('b', 'c')
>>> c = a.intersection(b)
>>> c.test('a', 'bcd')
'''
return Allow(*self._names.intersection(allowed))
def allowing(self, *allow):
r'''Create a copy allowing additional names.
>>> a = Allow('a')
>>> b = a.allowing('b', 'c')
>>> a.test('a', 'bcd')
>>> b.test('abc', 'd')
'''
return Allow(*self._names.union(allow))
def denying(self, *denied):
r'''Create a copy denying specified names.
>>> a = Allow('a', 'b')
>>> b = a.denying('b')
>>> a.test('ab', 'c')
>>> b.test('a', 'bc')
'''
return Allow(*self._names.difference(denied))
def allow(self, name):
r'''Return True iff `name` is allowed.
>>> a = Allow('a', 'b')
>>> a.allow('a')
True
>>> a.allow('c')
False
'''
return name in self._names
def allowed_denied(self, names):
r'''Determines the allowed and denied names from `names`.
Returns two frozensets of names: allowed_names, denied_names.
>>> a = Allow('a', 'b')
>>> a.allowed_denied('ac')
(frozenset({'a'}), frozenset({'c'}))
'''
names = frozenset(names)
allowed = self._names.intersection(names)
return allowed, names.difference(allowed)
class Deny(base):
r'''Denies a specific set of names.
>>> d = Deny('a', 'b', None)
>>> d.allow('a')
False
>>> d.allow(None)
False
>>> d.allow('d')
True
>>> d.test('cd', ('b', None))
'''
def intersection_allowed(self, allowed):
r'''Returns intersection with allowed set.
>>> a = Deny('a', 'b')
>>> b = Deny('b', 'c')
>>> c = a.intersection(b)
>>> c.test('d', 'abc')
>>> b = Allow('b', 'c')
>>> c = a.intersection(b)
>>> c.test('c', 'abd')
'''
return Allow(*allowed.difference(self._names))
def allowing(self, *allowed):
r'''Create a copy allowing additional names.
>>> a = Deny('a', 'b')
>>> b = a.allowing('b', 'c')
>>> a.test('cd', 'ab')
>>> b.test('bcd', 'a')
'''
return Deny(*self._names.difference(allowed))
def denying(self, *denied):
r'''Create a copy denying specified names.
>>> a = Deny('a', 'b')
>>> b = a.denying('b', 'c')
>>> a.test('cd', 'ab')
>>> b.test('d', 'abc')
'''
return Deny(*self._names.union(denied))
def allow(self, name):
r'''Return True iff `name` is allowed.
>>> d = Deny('a', 'b')
>>> d.allow('a')
False
>>> d.allow('c')
True
'''
return name not in self._names
def allowed_denied(self, names):
r'''Determines the allowed and denied names from `names`.
Returns two frozensets of names: allowed_names, denied_names.
>>> d = Deny('a', 'b')
>>> d.allowed_denied('ac')
(frozenset({'c'}), frozenset({'a'}))
'''
names = frozenset(names)
denied = self._names.intersection(names)
return names.difference(denied), denied | PypiClean |
/Django-Pizza-16.10.1.tar.gz/Django-Pizza-16.10.1/pizza/kitchen_sink/static/ks/ckeditor/plugins/specialchar/dialogs/lang/pt-br.js | /*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar","pt-br",{euro:"Euro",lsquo:"Aspas simples esquerda",rsquo:"Aspas simples direita",ldquo:"Aspas duplas esquerda",rdquo:"Aspas duplas direita",ndash:"Traço",mdash:"Travessão",iexcl:"Ponto de exclamação invertido",cent:"Cent",pound:"Cerquilha",curren:"Dinheiro",yen:"Yen",brvbar:"Bara interrompida",sect:"Símbolo de Parágrafo",uml:"Trema",copy:"Direito de Cópia",ordf:"Indicador ordinal feminino",laquo:"Aspas duplas angulares esquerda",not:"Negação",reg:"Marca Registrada",
macr:"Mácron",deg:"Grau",sup2:"2 Superscrito",sup3:"3 Superscrito",acute:"Acento agudo",micro:"Micro",para:"Pé de mosca",middot:"Ponto mediano",cedil:"Cedilha",sup1:"1 Superscrito",ordm:"Indicador ordinal masculino",raquo:"Aspas duplas angulares direita",frac14:"Um quarto",frac12:"Um meio",frac34:"Três quartos",iquest:"Interrogação invertida",Agrave:"A maiúsculo com acento grave",Aacute:"A maiúsculo com acento agudo",Acirc:"A maiúsculo com acento circunflexo",Atilde:"A maiúsculo com til",Auml:"A maiúsculo com trema",
Aring:"A maiúsculo com anel acima",AElig:"Æ maiúsculo",Ccedil:"Ç maiúlculo",Egrave:"E maiúsculo com acento grave",Eacute:"E maiúsculo com acento agudo",Ecirc:"E maiúsculo com acento circumflexo",Euml:"E maiúsculo com trema",Igrave:"I maiúsculo com acento grave",Iacute:"I maiúsculo com acento agudo",Icirc:"I maiúsculo com acento circunflexo",Iuml:"I maiúsculo com crase",ETH:"Eth maiúsculo",Ntilde:"N maiúsculo com til",Ograve:"O maiúsculo com acento grave",Oacute:"O maiúsculo com acento agudo",Ocirc:"O maiúsculo com acento circunflexo",
Otilde:"O maiúsculo com til",Ouml:"O maiúsculo com trema",times:"Multiplicação",Oslash:"Diâmetro",Ugrave:"U maiúsculo com acento grave",Uacute:"U maiúsculo com acento agudo",Ucirc:"U maiúsculo com acento circunflexo",Uuml:"U maiúsculo com trema",Yacute:"Y maiúsculo com acento agudo",THORN:"Thorn maiúsculo",szlig:"Eszett minúsculo",agrave:"a minúsculo com acento grave",aacute:"a minúsculo com acento agudo",acirc:"a minúsculo com acento circunflexo",atilde:"a minúsculo com til",auml:"a minúsculo com trema",
aring:"a minúsculo com anel acima",aelig:"æ minúsculo",ccedil:"ç minúsculo",egrave:"e minúsculo com acento grave",eacute:"e minúsculo com acento agudo",ecirc:"e minúsculo com acento circunflexo",euml:"e minúsculo com trema",igrave:"i minúsculo com acento grave",iacute:"i minúsculo com acento agudo",icirc:"i minúsculo com acento circunflexo",iuml:"i minúsculo com trema",eth:"eth minúsculo",ntilde:"n minúsculo com til",ograve:"o minúsculo com acento grave",oacute:"o minúsculo com acento agudo",ocirc:"o minúsculo com acento circunflexo",
otilde:"o minúsculo com til",ouml:"o minúsculo com trema",divide:"Divisão",oslash:"o minúsculo com cortado ou diâmetro",ugrave:"u minúsculo com acento grave",uacute:"u minúsculo com acento agudo",ucirc:"u minúsculo com acento circunflexo",uuml:"u minúsculo com trema",yacute:"y minúsculo com acento agudo",thorn:"thorn minúsculo",yuml:"y minúsculo com trema",OElig:"Ligação tipográfica OE maiúscula",oelig:"Ligação tipográfica oe minúscula",372:"W maiúsculo com acento circunflexo",374:"Y maiúsculo com acento circunflexo",
373:"w minúsculo com acento circunflexo",375:"y minúsculo com acento circunflexo",sbquo:"Aspas simples inferior direita",8219:"Aspas simples superior esquerda",bdquo:"Aspas duplas inferior direita",hellip:"Reticências",trade:"Trade mark",9658:"Ponta de seta preta para direita",bull:"Ponto lista",rarr:"Seta para direita",rArr:"Seta dupla para direita",hArr:"Seta dupla direita e esquerda",diams:"Ouros",asymp:"Aproximadamente"}); | PypiClean |
/AirStrip-2.0.2.tar.gz/AirStrip-2.0.2/airstrip/air.py | from puke import *
import json
import os
import re
from distutils import version
from verlib import NormalizedVersion
from distutils.version import StrictVersion, LooseVersion
AIRSTRIP_ROOT = os.path.dirname(os.path.realpath(__file__))
NORMALIZE_VERSION = re.compile(r'([^\d]*)')
# System-wide yawns path
AIRSTRIP_YAWN_PATH = os.path.join(AIRSTRIP_ROOT, 'airs')
# Project user-defined yawns path
PROJECT_YAWN_PATH = './airs'
EMPTY_GLOBAL = """
"description": "",
"keywords": [],
"author": [],
"licenses": [],
"category": "library",
"homepage": "http://",
"tools": [],
"depends": {},
"strict": true,
"git": "",
"versions": {
"master": {
"package": "",
"resources": {
},
"build": [],
"productions": {
}
}
}
}"""
EMPTY_LOCAL_VERSION = """{
"versions": {
"version.name": {
"package": "",
"resources": {
},
"build": [],
"productions": {
}
}
}
}"""
class Air():
def __init__(self, name):
self.name = name
self.hasGlobal = False
self.yawn = json.loads("""{
"name": "%s",
%s""" % (name, EMPTY_GLOBAL))
systemPath = FileSystem.join(AIRSTRIP_YAWN_PATH, '%s.json' % name)
if FileSystem.exists(systemPath):
try:
self.yawn = json.loads(FileSystem.readfile(systemPath))
self.hasGlobal = True
except:
console.error('The system yawn descriptor for %s is borked!' % name)
self.hasLocal = False
self.local = json.loads('{}')
localPath = FileSystem.join(PROJECT_YAWN_PATH, '%s.json' % name)
if FileSystem.exists(localPath):
try:
self.local = json.loads(FileSystem.readfile(localPath))
self.hasLocal = True
except:
console.error('The yawn descriptor for %s in your project is borked!' % name)
@staticmethod
def exists(name):
systemPath = FileSystem.join(AIRSTRIP_YAWN_PATH, '%s.json' % name)
localPath = FileSystem.join(PROJECT_YAWN_PATH, '%s.json' % name)
if not FileSystem.exists(localPath) and not FileSystem.exists(systemPath):
return False
return True
def edit(self, globally = False):
# Global edition, just go
if globally:
p = FileSystem.join(AIRSTRIP_YAWN_PATH, '%s.json' % self.name)
c = self.yawn
else:
p = FileSystem.join(PROJECT_YAWN_PATH, '%s.json' % self.name)
# No local data yet
if not self.hasLocal:
# if no global data either, populate with yawn
if not self.hasGlobal:
self.local = json.loads("""{
"name": "%s",
%s""" % (self.name, EMPTY_GLOBAL))
# if has global data, should start empty instead, as a version specialization
else:
self.local = json.loads(EMPTY_LOCAL_VERSION)
c = self.local
if not FileSystem.exists(p):
FileSystem.writefile(p, json.dumps(c, indent=4))
sh('open "%s"' % p)
self.__init__(self.name)
def get(self, version, key = False):
if key == "safename":
return self.name
keys = ['name', 'homepage', 'git', 'description', 'author', 'keywords', 'strict', 'licenses', 'category', 'tools', 'depends', 'package', 'resources', 'build', 'productions']
#, 'versions']
# if key and not key in keys:
# console.error('There is no such thing as %s' % key)
if self.hasGlobal and (version in self.yawn["versions"]):
ref = self.yawn['versions'][version]
if "package.json" in ref and "component.json" in ref:
for i in ref["component.json"]:
ref["package.json"][i] = ref["component.json"][i]
parent = self.yawn
elif self.hasLocal and (version in self.local["versions"]):
ref = self.local['versions'][version]
if "package.json" in ref and "component.json" in ref:
for i in ref["component.json"]:
ref["package.json"][i] = ref["component.json"][i]
parent = self.local
else:
console.error('The requested version (%s) does not exist' % version)
raise Exception("FAIL")
if not key:
return ref
if key in ref:
return ref[key]
if "package.json" in ref and key in ref["package.json"]:
return ref["package.json"][key]
if not key in parent:
if "branch" in ref:
return self.get(ref["branch"], key)
else:
console.warn('No such key (%s)' % key)
return False
return parent[key]
def versions(self):
r = re.compile(r'([^\d]*)')
versions = {}
result = []
dates = {}
if self.hasGlobal:
self._parseVersions(self.yawn["versions"], versions)
# print(self.yawn["versions"])
if self.hasLocal:
self._parseVersions(self.local["versions"], versions)
hasMaster = versions.pop('master', False)
sortedVersions = versions.keys()
sortedVersions.sort(key=LooseVersion)
for key in sortedVersions:
result.append(versions[key])
if hasMaster:
result.append(hasMaster)
return result
def _parseVersions(self, entries, result):
for version in entries:
date = False
content = entries[version]
if 'date' in content and 'commited' in content['date']:
date = content['date']['commited']
if not date:
date = None
if version == 'master':
normalized = 'master'
else:
normalized = NORMALIZE_VERSION.sub('', version, 1)
result[normalized] = (version, date)
# def latest(self):
# v = self.versions()
# for i in v:
# v = i.lstrip("v")
# better = re.sub(r"([0-9]+)[.]([0-9]+)[.]([0-9]+)(.*)$", r"\1 \2 \3 \4", v).split(" ")
# print better
# try:
# print NormalizedVersion(v)
# except:
# print v.split('.')
# print "WRONG version"
# http://www.python.org/dev/peps/pep-0386/#normalizedversion
# version.StrictVersion('1.0.5') < version.StrictVersion('1.0.8')
# print version.StrictVersion(i)
# print better
# if self.hasGlobal:
# if key in self.yawn:
# ref = self.yawn[key]
# if self.hasGlobal:
# ref =
# return self.yawn[key]
# if self.hasLocal:
# return self.local[key]
# idx = keys.index(key)
# types = ['', '', [], [], '', [], {}, '', {}, [], {}]
# return types[idx] | PypiClean |
/Mathics3-6.0.2.tar.gz/Mathics3-6.0.2/mathics/builtin/numbers/numbertheory.py | import mpmath
import sympy
from mathics.builtin.base import Builtin, SympyFunction
from mathics.core.atoms import Integer, Integer0, Integer10, Rational, Real
from mathics.core.attributes import (
A_LISTABLE,
A_NUMERIC_FUNCTION,
A_ORDERLESS,
A_PROTECTED,
A_READ_PROTECTED,
)
from mathics.core.convert.expression import to_mathics_list
from mathics.core.convert.python import from_bool, from_python
from mathics.core.convert.sympy import SympyPrime, from_sympy
from mathics.core.evaluation import Evaluation
from mathics.core.expression import Expression
from mathics.core.list import ListExpression
from mathics.core.symbols import Symbol, SymbolDivide, SymbolFalse
from mathics.core.systemsymbols import (
SymbolCeiling,
SymbolComplex,
SymbolFloor,
SymbolIm,
SymbolRe,
)
from mathics.eval.nevaluator import eval_N
SymbolFractionalPart = Symbol("System`FractionalPart")
SymbolMantissaExponent = Symbol("System`MantissaExponent")
class ContinuedFraction(SympyFunction):
"""
<url>:Continued fraction:
https://en.wikipedia.org/wiki/Continued_fraction</url> (<url>
:SymPy: https://docs.sympy.org/latest/modules/ntheory.html#module-sympy.ntheory.continued_fraction</url>, <url>
:WMA: https://reference.wolfram.com/language/ref/ContinuedFraction.html</url>)
<dl>
<dt>'ContinuedFraction[$x$, $n$]'
<dd>generate the first $n$ terms in the continued fraction representation of $x$.
<dt>'ContinuedFraction[$x$]'
<dd>the complete continued fraction representation for a rational or quadradic irrational number.
</dl>
>> ContinuedFraction[Pi, 10]
= {3, 7, 15, 1, 292, 1, 1, 1, 2, 1}
>> ContinuedFraction[(1 + 2 Sqrt[3])/5]
= {0, 1, {8, 3, 34, 3}}
>> ContinuedFraction[Sqrt[70]]
= {8, {2, 1, 2, 1, 2, 16}}
"""
attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_PROTECTED
summary_text = "continued fraction expansion"
sympy_name = "continued_fraction"
def eval(self, x, evaluation: Evaluation):
"%(name)s[x_]"
return super().eval(x, evaluation)
def eval_with_n(self, x, n: Integer, evaluation: Evaluation):
"%(name)s[x_, n_Integer]"
py_n = n.value
sympy_x = x.to_sympy()
it = sympy.continued_fraction_iterator(sympy_x)
return from_sympy([next(it) for _ in range(py_n)])
class Divisors(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Divisors.html</url>
<dl>
<dt>'Divisors[$n$]'
<dd>returns a list of the integers that divide $n$.
</dl>
>> Divisors[96]
= {1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 96}
>> Divisors[704]
= {1, 2, 4, 8, 11, 16, 22, 32, 44, 64, 88, 176, 352, 704}
>> Divisors[{87, 106, 202, 305}]
= {{1, 3, 29, 87}, {1, 2, 53, 106}, {1, 2, 101, 202}, {1, 5, 61, 305}}
#> Divisors[0]
= Divisors[0]
#> Divisors[{-206, -502, -1702, 9}]
= {{1, 2, 103, 206}, {1, 2, 251, 502}, {1, 2, 23, 37, 46, 74, 851, 1702}, {1, 3, 9}}
#> Length[Divisors[1000*369]]
= 96
#> Length[Divisors[305*176*369*100]]
= 672
"""
# TODO: support GaussianIntegers
# e.g. Divisors[2, GaussianIntegers -> True]
attributes = A_LISTABLE | A_PROTECTED
summary_text = "integer divisors"
def eval(self, n: Integer, evaluation: Evaluation):
"Divisors[n_Integer]"
if n == Integer0:
return None
return to_mathics_list(*sympy.divisors(n.value), elements_conversion_fn=Integer)
# FIXME: Previously this used gmpy's gcdext. sympy's gcdex is not as powerful
# class ExtendedGCD(Builtin):
# """
# >> ExtendedGCD[10, 15]
# = {5, {-1, 1}}
#
# 'ExtendedGCD' works with any number of arguments:
# >> ExtendedGCD[10, 15, 7]
# = {1, {-3, 3, -2}}
#
# Compute the greated common divisor and check the result:
# >> numbers = {10, 20, 14};
# >> {gcd, factors} = ExtendedGCD[Sequence @@ numbers]
# = {2, {3, 0, -2}}
# >> Plus @@ (numbers * factors)
# = 2
#
# 'ExtendedGCD' does not work for rational numbers and Gaussian integers yet
# """
#
# attributes = A_LISTABLE | A_PROTECTED
#
# def eval(self, ns, evaluation: Evaluation):
# 'ExtendedGCD[ns___Integer]'
#
# ns = ns.get_sequence()
# result = 0
# coeff = []
# for n in ns:
# value = n.value
# if value is None:
# return
# new_result, c1, c2 = sympy.gcdex(result, value)
# result = new_result
# coeff = [c * c1 for c in coeff] + [c2]
# return ListExpression(Integer(result), ListExpression(
# *(Integer(c) for c in coeff)))
class EulerPhi(SympyFunction):
"""
<url>:Euler's totient function: https://en.wikipedia.org/wiki/Euler%27s_totient_function</url> (<url>:SymPy: https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.factor_.totient</url>, <url>:WMA: https://reference.wolfram.com/language/ref/EulerPhi.html</url>)
This function counts positive integers up to $n$ that are relatively prime to $n$.
It is typically used in cryptography and in many applications in elementary number theory.
<dl>
<dt>'EulerPhi[$n$]'
<dd>returns the Euler totient function .
</dl>
Compute the Euler totient function:
>> EulerPhi[9]
= 6
'EulerPhi' of a negative integer is same as its positive counterpart:
>> EulerPhi[-11] == EulerPhi[11]
= True
Large arguments are computed quickly:
>> EulerPhi[40!]
= 121343746763281707274905415180804423680000000000
'EulerPhi' threads over lists:
>> EulerPhi[Range[1, 17, 2]]
= {1, 2, 4, 6, 6, 10, 12, 8, 16}
Above, we get consecutive even numbers when the input is prime.
Compare the results above with:
>> EulerPhi[Range[1, 17]]
= {1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16}
"""
attributes = A_LISTABLE | A_PROTECTED
summary_text = "Euler totient function"
sympy_name = "totient"
def eval(self, n: Integer, evaluation: Evaluation):
"EulerPhi[n_Integer]"
return super().eval(abs(n), evaluation)
class FactorInteger(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/FactorInteger.html</url>
<dl>
<dt>'FactorInteger[$n$]'
<dd>returns the factorization of $n$ as a list of factors and exponents.
</dl>
>> factors = FactorInteger[2010]
= {{2, 1}, {3, 1}, {5, 1}, {67, 1}}
To get back the original number:
>> Times @@ Power @@@ factors
= 2010
'FactorInteger' factors rationals using negative exponents:
>> FactorInteger[2010 / 2011]
= {{2, 1}, {3, 1}, {5, 1}, {67, 1}, {2011, -1}}
"""
attributes = A_LISTABLE | A_PROTECTED
summary_text = "list of prime factors and exponents"
# TODO: GausianIntegers option
# e.g. FactorInteger[5, GaussianIntegers -> True]
def eval(self, n, evaluation: Evaluation):
"FactorInteger[n_]"
if isinstance(n, Integer):
factors = sympy.factorint(n.value)
factors = sorted(factors.items())
return ListExpression(
*(to_mathics_list(factor, exp) for factor, exp in factors)
)
elif isinstance(n, Rational):
factors, factors_denom = list(
map(sympy.factorint, n.value.as_numer_denom())
)
for factor, exp in factors_denom.items():
factors[factor] = factors.get(factor, 0) - exp
factors = sorted(factors.items())
return ListExpression(
*(to_mathics_list(factor, exp) for factor, exp in factors)
)
else:
evaluation.message("FactorInteger", "exact", n)
def _fractional_part(self, n, expr, evaluation: Evaluation):
n_sympy = n.to_sympy()
if n_sympy.is_constant():
if n_sympy >= 0:
positive_integer_part = (
Expression(SymbolFloor, n).evaluate(evaluation).to_python()
)
result = n - Integer(positive_integer_part)
else:
negative_integer_part = (
Expression(SymbolCeiling, n).evaluate(evaluation).to_python()
)
result = n - Integer(negative_integer_part)
else:
return expr
return from_python(result)
class FractionalPart(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/FractionalPart.html</url>
<dl>
<dt>'FractionalPart[$n$]'
<dd>finds the fractional part of $n$.
</dl>
>> FractionalPart[4.1]
= 0.1
>> FractionalPart[-5.25]
= -0.25
#> FractionalPart[b]
= FractionalPart[b]
#> FractionalPart[{-2.4, -2.5, -3.0}]
= {-0.4, -0.5, 0.}
#> FractionalPart[14/32]
= 7 / 16
#> FractionalPart[4/(1 + 3 I)]
= 2 / 5 - I / 5
#> FractionalPart[Pi^20]
= -8769956796 + Pi ^ 20
"""
attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_READ_PROTECTED | A_PROTECTED
summary_text = "fractional part of a number"
def eval(self, n, evaluation: Evaluation):
"FractionalPart[n_]"
expr = Expression(SymbolFractionalPart, n)
return _fractional_part(self.__class__.__name__, n, expr, evaluation)
def eval_complex_n(self, n, evaluation: Evaluation):
"FractionalPart[n_Complex]"
expr = Expression(SymbolFractionalPart, n)
n_real = Expression(SymbolRe, n).evaluate(evaluation)
n_image = Expression(SymbolIm, n).evaluate(evaluation)
real_fractional_part = _fractional_part(
self.__class__.__name__, n_real, expr, evaluation
)
image_fractional_part = _fractional_part(
self.__class__.__name__, n_image, expr, evaluation
)
return Expression(SymbolComplex, real_fractional_part, image_fractional_part)
class FromContinuedFraction(SympyFunction):
"""
<url>
:WMA link:
https://reference.wolfram.com/language/ref/FromContinuedFraction.html</url>
<dl>
<dt>'FromContinuedFraction[$list$]'
<dd>reconstructs a number from the list of its continued fraction terms.
</dl>
>> FromContinuedFraction[{3, 7, 15, 1, 292, 1, 1, 1, 2, 1}]
= 1146408 / 364913
>> FromContinuedFraction[Range[5]]
= 225 / 157
"""
attributes = A_NUMERIC_FUNCTION | A_PROTECTED
summary_text = "reconstructs a number from its continued fraction representation"
sympy_name = "continued_fraction_reduce"
def eval(self, expr, evaluation: Evaluation):
"%(name)s[expr_List]"
nums = expr.to_python()
if all(isinstance(i, int) for i in nums):
return from_sympy(sympy.continued_fraction_reduce(nums))
class MantissaExponent(Builtin):
"""
<url>
:WMA link:
https://reference.wolfram.com/language/ref/MantissaExponent.html</url>
<dl>
<dt>'MantissaExponent[$n$]'
<dd>finds a list containing the mantissa and exponent of a given number $n$.
<dt>'MantissaExponent[$n$, $b$]'
<dd>finds the base b mantissa and exponent of $n$.
</dl>
>> MantissaExponent[2.5*10^20]
= {0.25, 21}
>> MantissaExponent[125.24]
= {0.12524, 3}
>> MantissaExponent[125., 2]
= {0.976563, 7}
>> MantissaExponent[10, b]
= MantissaExponent[10, b]
#> MantissaExponent[E, Pi]
= {E / Pi, 1}
#> MantissaExponent[Pi, Pi]
= {1 / Pi, 2}
#> MantissaExponent[5/2 + 3, Pi]
= {11 / (2 Pi ^ 2), 2}
#> MantissaExponent[b]
= MantissaExponent[b]
#> MantissaExponent[17, E]
= {17 / E ^ 3, 3}
#> MantissaExponent[17., E]
= {0.84638, 3}
#> MantissaExponent[Exp[Pi], 2]
= {E ^ Pi / 32, 5}
#> MantissaExponent[3 + 2 I, 2]
: The value 3 + 2 I is not a real number
= MantissaExponent[3 + 2 I, 2]
#> MantissaExponent[25, 0.4]
: Base 0.4 is not a real number greater than 1.
= MantissaExponent[25, 0.4]
#> MantissaExponent[0.0000124]
= {0.124, -4}
#> MantissaExponent[0.0000124, 2]
= {0.812646, -16}
#> MantissaExponent[0]
= {0, 0}
#> MantissaExponent[0, 2]
= {0, 0}
"""
attributes = A_LISTABLE | A_PROTECTED
messages = {
"realx": "The value `1` is not a real number",
"rbase": "Base `1` is not a real number greater than 1.",
}
rules = {
"MantissaExponent[0]": "{0, 0}",
"MantissaExponent[0, n_]": "{0, 0}",
}
summary_text = "decomposes numbers as mantissa and exponent"
def eval(self, n, evaluation: Evaluation):
"MantissaExponent[n_]"
n_sympy = n.to_sympy()
expr = Expression(SymbolMantissaExponent, n)
if isinstance(n.to_python(), complex):
evaluation.message("MantissaExponent", "realx", n)
return expr
# Handle Input with special cases such as PI and E
if n_sympy.is_constant():
temp_n = eval_N(n, evaluation)
py_n = temp_n.to_python()
else:
return expr
base_exp = int(mpmath.log10(py_n))
exp = Integer((base_exp + 1) if base_exp >= 0 else base_exp)
return ListExpression(Expression(SymbolDivide, n, Integer10**exp), exp)
def eval_with_b(self, n, b, evaluation: Evaluation):
"MantissaExponent[n_, b_]"
# Handle Input with special cases such as PI and E
n_sympy, b_sympy = n.to_sympy(), b.to_sympy()
expr = Expression(SymbolMantissaExponent, n, b)
if isinstance(n.to_python(), complex):
evaluation.message("MantissaExponent", "realx", n)
return expr
if n_sympy.is_constant():
temp_n = eval_N(n, evaluation)
py_n = temp_n.to_python()
else:
return expr
if b_sympy.is_constant():
temp_b = eval_N(b, evaluation)
py_b = temp_b.to_python()
else:
return expr
if not py_b > 1:
evaluation.message("MantissaExponent", "rbase", b)
return expr
base_exp = int(mpmath.log(py_n, py_b))
exp = Integer((base_exp + 1) if base_exp >= 0 else base_exp)
return ListExpression(Expression(SymbolDivide, n, b**exp), exp)
class NextPrime(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/NextPrime.html</url>
<dl>
<dt>'NextPrime[$n$]'
<dd>gives the next prime after $n$.
<dt>'NextPrime[$n$,$k$]'
<dd>gives the $k$th prime after $n$.
</dl>
>> NextPrime[10000]
= 10007
>> NextPrime[100, -5]
= 73
>> NextPrime[10, -5]
= -2
>> NextPrime[100, 5]
= 113
>> NextPrime[5.5, 100]
= 563
>> NextPrime[5, 10.5]
= NextPrime[5, 10.5]
"""
rules = {
"NextPrime[n_]": "NextPrime[n, 1]",
}
summary_text = "closest, smallest prime number"
def eval(self, n, k: Integer, evaluation: Evaluation):
"NextPrime[n_?NumberQ, k_Integer]"
def to_int_value(x):
if isinstance(x, Integer):
return x.value
x = eval_N(x, evaluation)
if isinstance(x, Integer):
return x.value
elif isinstance(x, Real):
return round(x.value)
else:
return None
py_k = to_int_value(k)
if py_k is None:
return None
py_n = n.value
if py_k >= 0:
return Integer(sympy.ntheory.nextprime(py_n, py_k))
# Hack to get earlier primes
result = n.to_python()
for i in range(-py_k):
try:
result = sympy.ntheory.prevprime(result)
except ValueError:
# No earlier primes
return Integer(-1 * sympy.ntheory.nextprime(0, py_k - i))
return Integer(result)
class PartitionsP(SympyFunction):
"""
<url>:WMA link:
https://reference.wolfram.com/language/ref/PartitionsP.html</url>
<dl>
<dt>'PartitionsP[$n$]'
<dd>return the number $p$($n$) of unrestricted partitions of the integer $n$.
</dl>
>> Table[PartitionsP[k], {k, -2, 12}]
= {0, 0, 1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77}
"""
attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_ORDERLESS | A_PROTECTED
summary_text = "number of unrestricted partitions"
sympy_name = "npartitions"
def eval(self, n, evaluation: Evaluation):
"PartitionsP[n_Integer]"
return super().eval(n, evaluation)
class Prime(SympyFunction):
"""
<url>:WMA link:
https://reference.wolfram.com/language/ref/Prime.html</url>
<dl>
<dt>'Prime[$n$]'
<dt>'Prime'[{$n0$, $n1$, ...}]
<dd>returns the $n$th prime number where $n$ is an positive Integer.
If given a list of integers, the return value is a list with 'Prime' applied to each.
</dl>
Note that the first prime is 2, not 1:
>> Prime[1]
= 2
>> Prime[167]
= 991
When given a list of integers, a list is returned:
>> Prime[{5, 10, 15}]
= {11, 29, 47}
1.2 isn't an integer
>> Prime[1.2]
= Prime[1.2]
Since 0 is less than 1, like 1.2 it is invalid.
>> Prime[{0, 1, 1.2, 3}]
= {Prime[0], 2, Prime[1.2], 5}
"""
attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_PROTECTED
summary_text = "n-esim prime number"
def eval(self, n, evaluation: Evaluation):
"Prime[n_]"
return from_sympy(SympyPrime(n.to_sympy()))
def to_sympy(self, expr, **kwargs):
if expr.has_form("Prime", 1):
return SympyPrime(expr.elements[0].to_sympy(**kwargs))
class PrimePi(SympyFunction):
"""
<url>:Prime numbers:https://reference.wolfram.com/language/ref/PrimePi.html</url>
<dl>
<dt>'PrimePi[$x$]'
<dd>gives the number of primes less than or equal to $x$.
</dl>
PrimePi is the inverse of Prime:
>> PrimePi[2]
= 1
>> PrimePi[100]
= 25
>> PrimePi[-1]
= 0
>> PrimePi[3.5]
= 2
>> PrimePi[E]
= 1
"""
attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_PROTECTED
mpmath_name = "primepi"
summary_text = "amount of prime numbers less than or equal"
sympy_name = "ntheory.primepi"
# TODO: Traditional Form
def eval(self, n, evaluation: Evaluation):
"PrimePi[n_?NumericQ]"
result = sympy.ntheory.primepi(eval_N(n, evaluation).to_python())
return Integer(result)
class PrimePowerQ(Builtin):
"""
<url>:Prime numbers:https://reference.wolfram.com/language/ref/PrimePowerQ.html</url>
<dl>
<dt>'PrimePowerQ[$n$]'
<dd>returns 'True' if $n$ is a power of a prime number.
</dl>
>> PrimePowerQ[9]
= True
>> PrimePowerQ[52142]
= False
>> PrimePowerQ[-8]
= True
>> PrimePowerQ[371293]
= True
#> PrimePowerQ[1]
= False
"""
attributes = A_LISTABLE | A_PROTECTED | A_READ_PROTECTED
rules = {
"PrimePowerQ[1]": "False",
}
summary_text = "test if a number is a power of a prime number"
# TODO: GaussianIntegers option
"""
#> PrimePowerQ[5, GaussianIntegers -> True]
= False
"""
# TODO: Complex args
"""
#> PrimePowerQ[{3 + I, 3 - 2 I, 3 + 4 I, 9 + 7 I}]
= {False, True, True, False}
"""
# TODO: Gaussian rationals
"""
#> PrimePowerQ[2/125 - 11 I/125]
= True
"""
def eval(self, n, evaluation: Evaluation):
"PrimePowerQ[n_]"
n = n.get_int_value()
if n is None:
return SymbolFalse
n = abs(n)
return from_bool(len(sympy.factorint(n)) == 1)
class RandomPrime(Builtin):
"""
<url>:Prime numbers:https://reference.wolfram.com/language/ref/RandomPrime.html</url>
<dl>
<dt>'RandomPrime[{$imin$, $imax}]'
<dd>gives a random prime between $imin$ and $imax$.
<dt>'RandomPrime[$imax$]'
<dd>gives a random prime between 2 and $imax$.
<dt>'RandomPrime[$range$, $n$]'
<dd>gives a list of $n$ random primes in $range$.
</dl>
>> RandomPrime[{14, 17}]
= 17
>> RandomPrime[{14, 16}, 1]
: There are no primes in the specified interval.
= RandomPrime[{14, 16}, 1]
>> RandomPrime[{8,12}, 3]
= {11, 11, 11}
>> RandomPrime[{10,30}, {2,5}]
= ...
#> RandomPrime[{10,12}, {2,2}]
= {{11, 11}, {11, 11}}
#> RandomPrime[2, {3,2}]
= {{2, 2}, {2, 2}, {2, 2}}
"""
messages = {
"posdim": (
"The dimensions parameter `1` is expected to be a positive "
"integer or a list of positive integers."
),
"noprime": "There are no primes in the specified interval.",
"prmrng": (
"First argument `1` is not a positive integer or a list "
"of two positive integers."
),
"posint": (
"The paramater `1` describing the interval is expected to "
"be a positive integer."
),
}
rules = {
"RandomPrime[imax_?NotListQ]": "RandomPrime[{1, imax}, 1]",
"RandomPrime[int_List]": "RandomPrime[int, 1]",
"RandomPrime[imax_List, n_?ArrayQ]": ("ConstantArray[RandomPrime[imax, 1], n]"),
"RandomPrime[imax_?NotListQ, n_?ArrayQ]": (
"ConstantArray[RandomPrime[{1, imax}, 1], n]"
),
}
summary_text = "picks a random prime in an interval"
# TODO: Use random state as in other randomised methods within mathics
def eval(self, interval, n, evaluation: Evaluation):
"RandomPrime[interval_List, n_]"
if not isinstance(n, Integer):
evaluation.message("RandomPrime", "posdim", n)
return
py_n = n.to_python()
py_int = interval.to_python()
if not (isinstance(py_int, list) and len(py_int) == 2):
evaluation.message("RandomPrime", "prmrng", interval)
imin, imax = min(py_int), max(py_int)
if imin <= 0 or not isinstance(imin, int):
evaluation.message("RandomPrime", "posint", interval.elements[0])
return
if imax <= 0 or not isinstance(imax, int):
evaluation.message("RandomPrime", "posint", interval.elements[1])
return
try:
if py_n == 1:
return Integer(sympy.ntheory.randprime(imin, imax + 1))
return from_python(
[sympy.ntheory.randprime(imin, imax + 1) for i in range(py_n)]
)
except ValueError:
evaluation.message("RandomPrime", "noprime")
return | PypiClean |
/DobbyStockSimulation-0.1.1.tar.gz/DobbyStockSimulation-0.1.1/.history/main_package/Stock_main_20221223162516.py | import numpy as np
import random
class SizeError(Exception):
def __init__(self):
self.message = "Error: size must be a positive integer"
class Stock(object):
def __init__(self):
try:
size = int(input("How many round do you want to play with?"))
if size <= 0:
raise SizeError
self.n = int(size)
print("You are going to play {} round, get ready!!!!!!!!\n".format(self.n))
self.high_price_list = [random.randint(201, 500) for i in range(int(self.n))]
self.low_price_list = [random.randint(50, 200) for i in range(int(self.n))]
self.volume_list = [random.randint(1, 200) for i in range(int(self.n))]
except TypeError:
print("Error: size must be a numeric value")
except ValueError:
print("Error: size must be a positive integer")
except ZeroDivisionError:
print("Error: size cannot be zero")
except Exception:
print("An unknown error occurred")
def get_high_price(self):
try:
return self.high_price_list
except AttributeError:
print("Error: high_price_list is not initialized")
except Exception:
print("An unknown error occurred")
def get_low_price(self):
try:
return self.low_price_list
except AttributeError:
print("Error: low_price_list is not initialized")
except Exception:
print("An unknown error occurred")
def get_volume(self):
try:
return self.volume_list
except AttributeError:
print("Error: volume_list is not initialized")
except Exception:
print("An unknown error occurred")
def get_size(self):
try:
return int(self.n)
except AttributeError:
print("Error: n is not initialized")
except Exception:
print("An unknown error occurred")
def __str__(self):
try:
print('high price list: {}','\nlow price list: {}','\nvolume list:{}'.format(self.high_price_list, self.low_price_list, self.volume_list))
# return f'high price list: {self.high_price_list}\nlow price list: {self.low_price_list}\nvolume list: {self.volume_list}'
except AttributeError:
print("Error: high_price_list, low_price_list, or volume_list is not initialized")
except TypeError:
print("Error: high_price_list, low_price_list, and volume_list must be lists")
except ValueError:
print("Error: high_price_list, low_price_list, and volume_list must contain only integers")
except Exception:
print("An unknown error occurred") | PypiClean |
/Nuitka_fixed-1.1.2-cp310-cp310-win_amd64.whl/nuitka/plugins/standard/TkinterPlugin.py | """ Details see below in class definition.
"""
import os
import sys
from nuitka import Options
from nuitka.plugins.PluginBase import NuitkaPluginBase
from nuitka.utils.FileOperations import listDllFilesFromDirectory, relpath
from nuitka.utils.Utils import isWin32Windows
def _isTkInterModule(module):
full_name = module.getFullName()
return full_name in ("Tkinter", "tkinter", "PySimpleGUI", "PySimpleGUI27")
class NuitkaPluginTkinter(NuitkaPluginBase):
"""This class represents the main logic of the TkInter plugin.
This is a plug-in to make programs work well in standalone mode which are using tkinter.
These programs require the presence of certain libraries written in the TCL language.
On Windows platforms, and even on Linux, the existence of these libraries cannot be
assumed. We therefore
1. Copy the TCL libraries as sub-folders to the program's dist folder
2. Redirect the program's tkinter requests to these library copies. This is
done by setting appropriate variables in the os.environ dictionary.
Tkinter will use these variable value to locate the library locations.
Each time before the program issues an import to a tkinter module, we make
sure, that the TCL environment variables are correctly set.
Notes:
You can enforce using a specific TCL folder by using TCL_LIBRARY
and a Tk folder by using TK_LIBRARY, but that ought to normally
not be necessary.
"""
plugin_name = "tk-inter" # Nuitka knows us by this name
plugin_desc = "Required by Python's Tk modules"
def __init__(self, tcl_library_dir, tk_library_dir):
self.tcl_library_dir = tcl_library_dir
self.tk_library_dir = tk_library_dir
self.files_copied = False # ensure one-time action
return None
@classmethod
def isRelevant(cls):
"""This method is called one time only to check, whether the plugin might make sense at all.
Returns:
True if this is a standalone, else False.
"""
return Options.isStandaloneMode()
@staticmethod
def createPreModuleLoadCode(module):
"""This method is called with a module that will be imported.
Notes:
If the word "tkinter" occurs in its full name, we know that the correct
setting of the TCL environment must be ensured before this happens.
Args:
module: the module object
Returns:
Code to insert and None (tuple)
"""
# only insert code for tkinter related modules
if _isTkInterModule(module):
# The following code will be executed before importing the module.
# If required we set the respective environment values.
code = r"""
import os
os.environ["TCL_LIBRARY"] = os.path.join(__nuitka_binary_dir, "tcl")
os.environ["TK_LIBRARY"] = os.path.join(__nuitka_binary_dir, "tk")"""
return code, "Need to make sure we set environment variables for TCL."
@classmethod
def addPluginCommandLineOptions(cls, group):
group.add_option(
"--tk-library-dir",
action="store",
dest="tk_library_dir",
default=None,
help="""\
The Tk library dir. Nuitka is supposed to automatically detect it, but you can
override it here. Default is automatic detection.""",
)
group.add_option(
"--tcl-library-dir",
action="store",
dest="tcl_library_dir",
default=None,
help="""\
The Tcl library dir. See comments for Tk library dir.""",
)
@staticmethod
def _getTkinterDnDPlatformDirectory():
# From their code:
import platform
if platform.system() == "Darwin":
return "osx64"
elif platform.system() == "Linux":
return "linux64"
elif platform.system() == "Windows":
return "win64"
else:
return None
def _considerDataFilesTkinterDnD(self, module):
platform_rep = self._getTkinterDnDPlatformDirectory()
if platform_rep is None:
return
yield self.makeIncludedPackageDataFiles(
package_name="tkinterdnd2",
package_directory=module.getCompileTimeDirectory(),
pattern=os.path.join("tkdnd", platform_rep, "**"),
reason="Tcl needed for 'tkinterdnd2' usage",
tags="tcl",
)
def considerDataFiles(self, module):
"""Provide TCL libraries to the dist folder.
Notes:
We will provide the copy the TCL/TK directories to the program's root directory,
that might be shiftable with some work.
Args:
module: the module in question, maybe ours
Yields:
IncludedDataFile objects.
"""
# Extra TCL providing module go here:
if module.getFullName() == "tkinterdnd2.TkinterDnD":
yield self._considerDataFilesTkinterDnD(module)
return
if not _isTkInterModule(module):
return
# Check typical locations of the dirs
candidates_tcl = (
os.environ.get("TCL_LIBRARY"),
"/usr/share/tcltk/tcl8.6",
"/usr/share/tcltk/tcl8.5",
"/usr/share/tcl8.6",
"/usr/share/tcl8.5",
"/usr/lib64/tcl/tcl8.5",
"/usr/lib64/tcl/tcl8.6",
os.path.join(sys.prefix, "tcl", "tcl8.5"),
os.path.join(sys.prefix, "tcl", "tcl8.6"),
os.path.join(sys.prefix, "lib", "tcl8.5"),
os.path.join(sys.prefix, "lib", "tcl8.6"),
)
candidates_tk = (
os.environ.get("TK_LIBRARY"),
"/usr/share/tcltk/tk8.6",
"/usr/share/tcltk/tk8.5",
"/usr/share/tk8.6",
"/usr/share/tk8.5",
"/usr/lib64/tcl/tk8.5",
"/usr/lib64/tcl/tk8.6",
os.path.join(sys.prefix, "tcl", "tk8.5"),
os.path.join(sys.prefix, "tcl", "tk8.6"),
os.path.join(sys.prefix, "lib", "tk8.5"),
os.path.join(sys.prefix, "lib", "tk8.6"),
)
tcl = self.tcl_library_dir
if tcl is None:
for tcl in candidates_tcl:
if tcl is not None and os.path.exists(tcl):
break
if tcl is None or not os.path.exists(tcl):
self.sysexit(
"Could not find Tcl, you might need to set 'TCL_LIBRARY' and if that works, report a bug."
)
tk = self.tk_library_dir
if tk is None:
for tk in candidates_tk:
if tk is not None and os.path.exists(tk):
break
if tk is None or not os.path.exists(tk):
self.sysexit(
"Could not find Tk, you might need to set 'TK_LIBRARY' and if that works, report a bug."
)
# survived the above, now do provide the locations
yield self.makeIncludedDataDirectory(
source_path=tk,
dest_path="tk",
reason="Tk copy needed for standalone Tcl",
ignore_dirs=("demos",),
tags="tk",
)
yield self.makeIncludedDataDirectory(
source_path=tcl,
dest_path="tcl",
reason="Tcl needed for tkinter usage",
tags="tcl",
)
if isWin32Windows():
yield self.makeIncludedDataDirectory(
source_path=os.path.join(tcl, "..", "tcl8"),
dest_path="tcl8",
reason="Tcl needed for tkinter usage",
tags="tcl",
)
def getExtraDlls(self, module):
if module.getFullName() == "tkinterdnd2.TkinterDnD":
platform_rep = self._getTkinterDnDPlatformDirectory()
if platform_rep is None:
return
module_directory = module.getCompileTimeDirectory()
for filename, _dll_filename in listDllFilesFromDirectory(
os.path.join(module_directory, "tkdnd", platform_rep)
):
dest_path = relpath(filename, module_directory)
yield self.makeDllEntryPoint(
source_path=filename,
dest_path=os.path.join("tkinterdnd2", dest_path),
package_name="tkinterdnd2",
reason="tkinterdnd2 package DLL",
)
class NuitkaPluginDetectorTkinter(NuitkaPluginBase):
"""Used only if plugin is not activated.
Notes:
We are given the chance to issue a warning if we think we may be required.
"""
detector_for = NuitkaPluginTkinter
@classmethod
def isRelevant(cls):
"""This method is called one time only to check, whether the plugin might make sense at all.
Returns:
True if this is a standalone compilation on Windows, else False.
"""
return Options.isStandaloneMode()
def checkModuleSourceCode(self, module_name, source_code):
"""This method checks the source code
Notes:
We only use it to check whether this is the main module, and whether
it contains the keyword "tkinter".
We assume that the main program determines whether tkinter is used.
References by dependent or imported modules are assumed irrelevant.
Args:
module_name: the name of the module
source_code: the module's source code
Returns:
None
"""
if module_name == "__main__":
for line in source_code.splitlines():
# Ignore comments.
if "#" in line:
line = line[: line.find("#")]
if "tkinter" in line or "Tkinter" in line:
self.warnUnusedPlugin("Tkinter needs TCL included.")
break | PypiClean |
/Bootcampspot-python-0.0.3.tar.gz/Bootcampspot-python-0.0.3/bcs/bootcampspot.py | import json
import os
from datetime import datetime
from typing import Dict, List
import requests
from io import StringIO
from .errors import CourseError, EnrollmentError
class Bootcampspot:
def __init__(self, email: str, password: str):
'''Get Auth and call `/me` endpoint for course info.'''
self.__creds = {"email": email,
"password": password}
self.__bcs_root = "https://bootcampspot.com/api/instructor/v1"
self.__login = requests.post(
f"{self.__bcs_root}/login", json=self.__creds)
self.__auth = self.__login.json()['authenticationInfo']['authToken']
self.__head = {
'Content-Type': 'application/json',
'authToken': self.__auth
}
# Get relevent values
self.__me = requests.get(
self.__bcs_root + "/me", headers=self.__head).json()
self.user = self.__me['userInfo']
self.class_details = [{'courseName': enrollment['course']['name'], 'courseId': enrollment['courseId'], 'enrollmentId': enrollment['id']}
for enrollment in self.__me['Enrollments']]
self.my_courses = [course['courseId']
for course in self.class_details]
self.my_enrollments = [course['enrollmentId']
for course in self.class_details]
self.my_cohorts = [course['courseName']
for course in self.class_details]
self.__course = None
self.__enrollment = None
def __repr__(self):
'''Return course details on print'''
rows = len(self.my_courses)
max_name = max([len(str(x)) for x in self.my_cohorts])
if os.isatty(0):
console_width, console_height = os.get_terminal_size()
if rows+1 <= console_height and console_width >= max_name+40:
name_fill = ' '*(max_name-11)
def _repr_row_gen() -> Generator:
for idx, value in enumerate(reversed(self.class_details)):
course_pad = ' '*(9-len(str(value['courseId'])))
enroll_pad = ' '*(13-len(str(value['enrollmentId'])))
name_pad = ' ' * \
(max_name-len(str(value['courseName'])))
output_string = f"{idx}| {name_pad}{value['courseName']} |{course_pad}{value['courseId']} |{enroll_pad}{value['enrollmentId']} |\n"
yield output_string
header = f" |{name_fill} Class Name | courseID | enrollmentId |\n"
output = StringIO("")
output.write(header)
output.write(f" {'-'*(len(header)-2)}\n")
for row in _repr_row_gen():
output.write(row)
return output.getvalue()
else:
return json.dumps(self.class_details)
else:
# @TODO: Make it pretty too
return json.dumps(self.class_details)
@property
def enrollment(self):
return self.__enrollment
@enrollment.setter
def enrollment(self, enrollmentId: int):
if enrollmentId not in self.my_enrollments:
msg = f'Invalid enrollmentId: {enrollmentId} not in your enrollments. Try one of these: {self.my_enrollments}'
raise EnrollmentError(msg)
elif not self._course == None:
enroll_match = [
enrollment for enrollment in self.class_details if course['courseId'] == self.__course][0]
if not enrollmentId == enroll_match['enrollmentId']:
msg = f"Invalid courseId: {enrollmentId} did not match enrollmentId for set courseId. Did you mean {enroll_match['enrollmentId']}"
raise EnrollmentError(msg)
else:
self.__enrollment = enrollmentId
@property
def course(self):
return self.__course
@course.setter
def course(self, courseId=int):
if courseId not in self.my_courses:
msg = f'Invalid courseId: {courseId} not in your courses. Try one of these: {self.my_courses}'
raise CourseError(msg)
elif not self.__enrollment == None:
course_match = [
course for course in self.class_details if course['enrollmentId'] == self.__enrollment][0]
if not courseId == course_match['courseId']:
msg = f"Invalid courseId: {courseId} did not match courseId for set enrollmentId. Did you mean {course_match['courseId']}"
raise CourseError(msg)
else:
self.__course = courseId
self.__enrollment = [course['enrollmentId']
for course in self.class_details if course['courseId'] == self.__course][0]
def __course_check(self, course):
# Set courseId if not set
if not course == None:
if course not in self.my_courses:
msg = f'Invalid courseId: {course} not in your courses. Try one of these: {self.my_courses}'
raise CourseError(msg)
else:
enroll_match = [course['enrollmentId']
for course in self.class_details if course['courseId'] == self.__course][0]
return course, enroll_match
else:
return self.__course, self.__enrollment
def __enrollment_check(self, enrollment):
# Set enrollmentId if not set
if not enrollment == None:
if enrollment not in self.my_enrollments:
msg = f"Invalid enrollmentId: {enrollment} not in your enrollments. Try one of these: {self.my_enrollments}"
raise EnrollmentError(msg)
else:
return enrollment
else:
return self.__enrollment
def __call(self, endpoint=str, body=dict):
'''Grab response from endpoint'''
response = requests.post(
f"{self.__bcs_root}/{endpoint}", headers=self.__head, json=body)
if response.status_code == 200:
return response.json()
def grades(self, course_id=None, milestones=False, return_null=False) -> Dict:
"""Fetches grades for a courseId.
Calls the sessions endpoint to retrieve details about a session
Args:
courseId (int): takes an integer corresponding to a courseId
milestones (bool): takes a boolean determining whether milestones will be included in the output
return_null (bool): takes boolean determining whether assignments with all None values are returned **i.e.** assignments yet to be assigned.
Returns:
dict: The grades, by assignment, for each student
"""
course_id, enrollment_id = self.__course_check(course_id)
body = {'courseId': course_id}
response = self.__call('grades', body)
grades = {}
def _value_check(grade):
# if grade == None:
# return "Not Submitted"
# else:
# return grade
return grade
for assignment in response:
if not milestones and 'Milestone' in assignment['assignmentTitle']:
pass
else:
try:
grades[assignment['assignmentTitle']
][assignment['studentName']] = _value_check(assignment['grade'])
except:
grades[assignment['assignmentTitle']] = {
assignment['studentName']: _value_check(assignment['grade'])}
if not return_null:
null_assignments = []
null_students = []
for assignment in grades.keys():
if all(grade == None for grade in grades[assignment].values()):
null_assignments.append(assignment)
for assignment in null_assignments:
del grades[assignment]
return grades
def sessions(self, course_id=None, enrollment_id=None, career_ok=False, orientation_ok=False) -> Dict:
"""Fetches session for course corresponding to courseId.
Calls the sessions endpoint to retrieve details about a session
Args:
courseId (int): takes an integer corresponding to a courseId
enrollmentId (int): takes an integer corresponding to an enrollmentId
career_ok (bool): takes in a boolean to limit results to academic sessions.
Returns:
dict: The session details for the session matching session_id
"""
if enrollment_id == None:
course_id, enrollment_id = self.__course_check(course_id)
else:
enrollment_id = self.__enrollment_check(enrollment_id)
body = {'enrollmentId': enrollment_id}
# Perform API call
sessions = self.__call('sessions', body=body)
sessions_list = []
def session_append(session):
sessions_list.append({'id': session_info['id'],
'name': session_info['name'],
'short_description': session_info['shortDescription'],
'long_description': session_info['longDescription'],
'start_time': session_info['startTime'][:-1],
'end_time': session_info['endTime'][:-1],
'chapter': session_info['chapter'],
'context': session_type,
'classroom': session['classroom'],
'video_url_list': session['videoUrlList']
})
def mask_check(session_type):
if session_type == 'career':
if career_ok:
return True
else:
return False
elif session_type == 'orientation':
if orientation_ok:
return True
else:
return False
elif not course_id == None:
if session_info['courseId'] == course_id:
return True
else:
return False
else:
return True
# Loop through current week sessions
for session in sessions['calendarSessions']:
session_info = session['session']
session_type = session['context']['contextCode']
# Filter on courseId and session code (to remove career entries)
# Pull out session name, start time (ISO 8601 with UTC TZ removed)
if mask_check(session_type):
session_append(session)
return sessions_list
def attendance(self, course_id=None, by='student') -> Dict:
"""Fetches attendance for each student/course.
Calls the attendance uri and encodes the attendance value as a category.
Args:
course_id (int): takes an integer corresponding to a course_id
Returns:
dict: The student name, session name and attendance value.
"""
course_id, enrollment_id = self.__course_check(course_id)
body = {'courseId': course_id}
response = self.__call(endpoint='attendance', body=body)
def switch(session):
if session['present'] == True and session['remote'] == False:
return 'present'
elif session['remote'] == True:
return 'remote'
elif session['excused'] == True and not session['excused'] == None:
return 'excused'
elif session['present'] == False and session['excused'] == False:
return 'absent'
attendance = {}
if by == 'student':
by_not = 'session'
else:
by_not = 'student'
for session in response:
try:
attendance[session[by+'Name']][session[by_not+'Name']] = switch(
session)
except:
attendance[session[by+'Name']] = {
session[by_not+'Name']: switch(session)}
null_sessions = []
for k in attendance.keys():
if all(att == None for att in attendance[k].values()):
null_sessions.append(k)
for session in null_sessions:
del attendance[session]
return attendance
def session_details(self, session_id: int) -> Dict:
"""Fetches session details for session matching session_id.
Calls the sessionDetail endpoint to retrieve details about a session
Args:
session_id (int): takes an integer corresponding to a session_id
Returns:
dict: The session details for the session matching session_id
"""
body = {'sessionId': session_id}
session_detail_response = self.__call('sessionDetail', body)
return session_detail_response['session']
def session_closest(self, course_id=None) -> Dict:
"""Fetches sessions list and returns nearest class to now.
Based on the courseId and enrollmentId, it will call the sessions
endpoint, find the closest session['startTime'] to datetime.utcnow()
and call the sessionDetail endpoint using session['id'] corresponding
to that session['startTime']
Args:
enrollment_id (int): takes an integer for the enrollmentId to pass
course_id (int): courseId for the session you'd like to retrieve.
Returns:
dict: The course details for soonest class before or after current time.
"""
course_id, enrollment_id = self.__course_check(course_id)
now = datetime.utcnow()
session_list = self.sessions(
course_id=course_id)
def closest_date(session_list: list, now):
return min(session_list, key=lambda x: abs(datetime.fromisoformat(x['start_time']) - now))
closest_session_id = closest_date(session_list, now)['id']
body = {'sessionId': closest_session_id}
session_detail_response = self.__call('sessionDetail', body)
return session_detail_response['session']['session']
def feedback(self, course_id=None) -> Dict:
"""Fetches weekly feedback."""
course_id, enrollment_id = self.__course_check(course_id)
body = {'courseId': course_id}
response = self.__call(endpoint='weeklyFeedback', body=body)
q_text = response['surveyDefinition']['steps']
feedback_struct = {question['stepNumber']: question['text'].split(
'(')[0][:-1] for question in q_text}
def process(inp):
try:
ignore_list = ['n/a', 'na', 'none', 'no']
answer = student['answers'][inp]['answer']['value']
if answer.lower() == any(ignore_list):
return None
else:
return answer
except TypeError:
return None
feedback = {}
for student in response['submissions']:
feedback[student['username']] = {
'timestamp': datetime.fromisoformat(student['date'].split('T')[0])
}
for idx, question in enumerate(feedback_struct):
feedback[student['username']
][feedback_struct[str(idx+1)]] = process(idx)
return feedback
@property
def feedback_chapter(self, course_id=None) -> str:
"""Fetches week of feedback"""
course_id, _ = self.__course_check(course_id)
body = {'courseId': course_id}
response = self.__call(endpoint='weeklyFeedback', body=body)
session_list = self.sessions(
course_id=course_id)
def closest_date(session_list: list, time):
return min(session_list, key=lambda x: abs(datetime.fromisoformat(x['start_time']) - time))
feedback_date = datetime.fromisoformat(
response['submissions'][0]['date'][:-1].split('T')[0])
feedback_chapter = closest_date(session_list, feedback_date)[
'chapter'].split('.')[0]
return feedback_chapter | PypiClean |
/NavAdd-0.1.1.tar.gz/NavAdd-0.1.1/navadd/navadd.py | from StringIO import StringIO
from trac import mimeview
from trac import resource
from trac import wiki
from trac.core import *
from trac.web.api import IRequestFilter
from trac.web.chrome import INavigationContributor
from trac.util import Markup
from genshi.builder import tag, Element
class NavAdd(Component):
""" Allows to add items to main and meta navigation bar"""
implements(INavigationContributor, IRequestFilter)
# INavigationContributor methods
def get_active_navigation_item(self, req):
return ''
def get_navigation_items(self, req):
add = self.env.config.getlist('navadd', 'add_items', [])
for a in add:
title = self.env.config.get('navadd', '%s.title' % a)
url = self.env.config.get('navadd', '%s.url' % a)
perm = self.env.config.get('navadd', '%s.perm' % a)
target = self.env.config.get('navadd', '%s.target' % a)
forusers = self.env.config.getlist('navadd', '%s.forusers' % a, [])
if perm and not req.perm.has_permission(perm):
continue
if forusers and req.authname not in forusers:
continue
if target not in ('mainnav', 'metanav'):
target = 'mainnav'
ctx = mimeview.Context.from_request(req)
link = wiki.formatter.extract_link(self.env, ctx, "[%s %s]" % (url, title))
yield (target, a, link)
# IRequestFilter methods
def pre_process_request(self, req, handler):
add = self.env.config.getlist('navadd', 'add_items', [])
for a in add:
url = self.env.config.get('navadd', '%s.url' % a)
perm = self.env.config.get('navadd', '%s.perm' % a)
target = self.env.config.get('navadd', '%s.target' % a)
forusers = self.env.config.getlist('navadd', '%s.forusers' % a, [])
setactive = self.env.config.getbool('navadd', '%s.setactive' % a, True)
if perm and not req.perm.has_permission(perm):
continue
if forusers and req.authname not in forusers:
continue
try:
if not req.environ['PATH_INFO'].startswith(url):
continue
except UnicodeDecodeError:
continue
if target not in ('mainnav', 'metanav'):
target = 'mainnav'
items = req.chrome.get('nav', {}).get(target, [])
if not items:
continue
for i in items:
if i.get('name', '') == a:
# We first disable all items
for j in items:
j['active'] = False
# We enable our item
i['active'] = True
break
break
return handler
def post_process_request(req, template, content_type):
return (template, content_type)
def post_process_request(req, template, data, content_type):
return (template, data, content_type) | PypiClean |
/mysmile-0.7.2.tar.gz/mysmile-0.7.2/apps/preferences/views.py | from django.shortcuts import render
from django.http import HttpResponseNotFound
from django.template import RequestContext, loader, Template, TemplateDoesNotExist
from django.views.decorators.csrf import requires_csrf_token
import logging
logger = logging.getLogger(__name__) # Get an instance of a logger
from apps.pages.models import Page, Page_translation
@requires_csrf_token
def e404(request, template_name='404.html'):
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
template = Template(
'<h1>Not Found</h1>'
'<p>The requested URL {{ request_path }} was not found on this server.</p>')
try:
slug = request.path.split('/')[-1].split('.html')[0] # get slug from path request
# Verify the existence of the slug
slug = Page.objects.filter(slug=slug,
status=Page.STATUS_PUBLISHED,
ptype__in=[Page.PTYPE_MENU, Page.PTYPE_MENU_API, Page.PTYPE_INNER]).values_list('slug', flat=True)[0]
except IndexError as err:
slug = None
logger.error(str(err))
langs = Page_translation.objects.filter(page__slug=slug).values_list('lang', flat=True) if slug else ''
return HttpResponseNotFound(template.render(RequestContext(request, {'request_host': request.get_host, 'request_path': request.path, 'slug': slug, 'langs': langs})))
@requires_csrf_token
def e500(request, template_name='500.html'):
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
template = Template(
'<h1>Not Found</h1>'
'<p>The requested URL {{ request_path }} was not found on this server.</p>')
return HttpResponseNotFound(template.render(RequestContext(request, {'request_path': request.path, })))
# like e403
def csrf_failure(request, reason=""):
template_name = '403.html'
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
template = Template(
'<b>HTTP Forbidden</b>'
'<p>The requested URL {{ request_path }} forbidden.</p>')
logger.error('error 403: ' + str(request))
return HttpResponseNotFound(template.render(RequestContext(request, {'request_path': request.path, }))) | PypiClean |
/6D657461666C6F77-0.0.17.tar.gz/6D657461666C6F77-0.0.17/metaflow/metaflow_version.py | # This file is imported from https://github.com/aebrahim/python-git-version
from __future__ import print_function
from subprocess import check_output, CalledProcessError
from os import path, name, devnull, environ, listdir
__all__ = ("get_version",)
CURRENT_DIRECTORY = path.dirname(path.abspath(__file__))
VERSION_FILE = path.join(CURRENT_DIRECTORY, "VERSION")
GIT_COMMAND = "git"
if name == "nt":
def find_git_on_windows():
"""find the path to the git executable on windows"""
# first see if git is in the path
try:
check_output(["where", "/Q", "git"])
# if this command succeeded, git is in the path
return "git"
# catch the exception thrown if git was not found
except CalledProcessError:
pass
# There are several locations git.exe may be hiding
possible_locations = []
# look in program files for msysgit
if "PROGRAMFILES(X86)" in environ:
possible_locations.append("%s/Git/cmd/git.exe" %
environ["PROGRAMFILES(X86)"])
if "PROGRAMFILES" in environ:
possible_locations.append("%s/Git/cmd/git.exe" %
environ["PROGRAMFILES"])
# look for the github version of git
if "LOCALAPPDATA" in environ:
github_dir = "%s/GitHub" % environ["LOCALAPPDATA"]
if path.isdir(github_dir):
for subdir in listdir(github_dir):
if not subdir.startswith("PortableGit"):
continue
possible_locations.append("%s/%s/bin/git.exe" %
(github_dir, subdir))
for possible_location in possible_locations:
if path.isfile(possible_location):
return possible_location
# git was not found
return "git"
GIT_COMMAND = find_git_on_windows()
def call_git_describe(abbrev=7):
"""return the string output of git desribe"""
try:
# first, make sure we are actually in a Metaflow repo,
# not some other repo
with open(devnull, 'w') as fnull:
arguments = [GIT_COMMAND, "rev-parse", "--show-toplevel"]
reponame = check_output(arguments, cwd=CURRENT_DIRECTORY,
stderr=fnull).decode("ascii").strip()
if path.basename(reponame) != 'metaflow':
return None
with open(devnull, "w") as fnull:
arguments = [GIT_COMMAND, "describe", "--tags",
"--abbrev=%d" % abbrev]
return check_output(arguments, cwd=CURRENT_DIRECTORY,
stderr=fnull).decode("ascii").strip()
except (OSError, CalledProcessError):
return None
def format_git_describe(git_str, pep440=False):
"""format the result of calling 'git describe' as a python version"""
if git_str is None:
return None
if "-" not in git_str: # currently at a tag
return git_str
else:
# formatted as version-N-githash
# want to convert to version.postN-githash
git_str = git_str.replace("-", ".post", 1)
if pep440: # does not allow git hash afterwards
return git_str.split("-")[0]
else:
return git_str.replace("-g", "+git")
def read_release_version():
"""Read version information from VERSION file"""
try:
with open(VERSION_FILE, "r") as infile:
version = str(infile.read().strip())
if len(version) == 0:
version = None
return version
except IOError:
return None
def update_release_version():
"""Update VERSION file"""
version = get_version(pep440=True)
with open(VERSION_FILE, "w") as outfile:
outfile.write(version)
outfile.write("\n")
def get_version(pep440=False):
"""Tracks the version number.
pep440: bool
When True, this function returns a version string suitable for
a release as defined by PEP 440. When False, the githash (if
available) will be appended to the version string.
The file VERSION holds the version information. If this is not a git
repository, then it is reasonable to assume that the version is not
being incremented and the version returned will be the release version as
read from the file.
However, if the script is located within an active git repository,
git-describe is used to get the version information.
The file VERSION will need to be changed by manually. This should be done
before running git tag (set to the same as the version in the tag).
"""
git_version = format_git_describe(call_git_describe(), pep440=pep440)
if git_version is None: # not a git repository
import metaflow
return metaflow.__version__
else:
return git_version | PypiClean |
/MOM-Tapyr-1.6.2.tar.gz/MOM-Tapyr-1.6.2/_Meta/M_Link.py |
from _MOM import MOM
from _TFL import TFL
import _MOM._Meta.M_Entity
import _MOM.E_Type_Manager
from _TFL.I18N import _, _T, _Tn
from _TFL.predicate import cartesian, filtered_join, paired, plural_of, uniq
from _TFL.pyk import pyk
from _TFL.Regexp import Regexp, re
import _TFL.multimap
import _TFL.Undef
import itertools
class M_Link (MOM.Meta.M_Id_Entity) :
"""Meta class of link-types of MOM meta object model.
`MOM.Meta.M_Link` provides the meta machinery for defining
essential association types and link instances. It is based on
:class:`~_MOM._Meta.M_Entity.M_Entity`.
`M_Link` is the common base class for the arity-specific subclasses.
`M_Link` provides the attribute:
.. attribute:: Roles
The tuple of role objects (contains as many role objects as the arity
of the association specifies).
"""
auto_derive_np_kw = TFL.mm_dict_mm_dict ()
_orn = {}
def __init__ (cls, name, bases, dct) :
cls.__m_super.__init__ (name, bases, dct)
if "_role_children_to_add" not in dct :
cls._role_children_to_add = []
# end def __init__
def m_create_role_children (cls, role) :
if not isinstance (role, pyk.string_types) :
role = role.name
cls._role_children_to_add.append (role)
# end def m_create_role_children
def other_role_name (cls, role_name) :
raise TypeError \
( "%s.%s.other_role_name needs to be explicitly defined"
% (cls.type_name, role_name)
)
# end def other_role_name
def _m_create_auto_children (cls) :
adrs = tuple \
( tuple
( (r.name, c)
for c in sorted
( pyk.itervalues (r.E_Type.children_np)
, key = TFL.Getter.i_rank
)
if not
( cls.type_name in c.refuse_links
or c.type_name in r.refuse_e_types
)
)
for r in cls.Roles
if r.auto_derive_np and r.E_Type.children_np
)
if adrs :
for adr in cartesian (* adrs) :
cls._m_create_role_child (* adr)
# end def _m_create_auto_children
def _m_create_link_ref_attr (cls, role, role_type, plural) :
name = cls._m_link_ref_attr_name (role, plural)
Attr_Type = MOM.Attr.A_Link_Ref_List if plural else MOM.Attr.A_Link_Ref
return cls._m_create_rev_ref_attr \
( Attr_Type, name, role, role_type, cls
, assoc = cls ### XXX remove after auto_cache_roles are removed
, description =
( _Tn ( "`%s` link", "`%s` links", 7 if plural else 1)
% (_T (cls.ui_name), )
)
, hidden =
cls.rev_ref_attr_hidden or (plural and role.max_links == 1)
, hidden_nested = 1
)
# end def _m_create_link_ref_attr
def _m_create_role_child (cls, * role_etype_s) :
"""Create derived link classes for the (role, e_type) combinations
specified.
"""
rkw = {}
rets = []
tn = cls.type_name
tbn = cls.type_base_name
for role_name, etype in role_etype_s :
role = getattr (cls._Attributes, role_name)
rET = role.E_Type
tbn = tbn.replace (rET.type_base_name, etype.type_base_name)
tn = tn.replace (rET.type_base_name, etype.type_base_name)
if tn == cls.type_name :
raise NameError \
( "Cannot auto-derive from %s for role `%s` from %s to %s"
% ( cls.type_name, role_name
, rET.type_base_name, etype.type_base_name
)
)
if cls.type_name in etype.refuse_links :
return
rets.append ((role, etype))
if any ((cls.type_name in etype.refuse_links) for role, etype in rets):
return
elif tn not in cls._type_names :
if tn in cls.auto_derive_np_kw :
auto_kw = cls.auto_derive_np_kw [tn]
else :
auto_kw = cls.auto_derive_np_kw [tbn]
auto_kw = auto_kw.__class__ (auto_kw)
for role, etype in rets :
for rtn in (etype.type_name, etype.type_base_name) :
ra_kw = cls.auto_derive_np_kw [rtn, role.name]
auto_kw.update (ra_kw)
for auto_kw_updater in pyk.itervalues (auto_kw ["_update_auto_kw"]):
auto_kw_updater (auto_kw)
for role, etype in rets :
r_rkw = dict \
( auto_kw [role.name]
, auto_rev_ref = role.auto_rev_ref_np
, auto_derive_np = role.auto_derive_npt
, role_type = etype
, __module__ = cls.__module__
)
rkw [role.name] = role.__class__ (role.name, (role, ), r_rkw)
### reset cache
role._children_np = role._children_np_transitive = None
is_partial = \
( any (r.role_type.is_partial for r in pyk.itervalues (rkw))
or any
( (not r.role_type) or r.role_type.is_partial
for r in cls.Role_Attrs if r.name not in rkw
)
)
result = cls.__class__ \
( tbn
, (cls, )
, dict
( auto_kw ["properties"]
, _Attributes = cls._Attributes.__class__
( "_Attributes"
, (cls._Attributes, )
, dict
( auto_kw ["extra_attributes"]
, __module__ = cls.__module__
, ** rkw
)
)
, auto_derived_p = True
, auto_derived_root = cls.auto_derived_root or cls
, is_partial = is_partial
, PNS = cls.PNS
, __module__ = cls.__module__
)
)
### reset cache
cls._children_np = cls._children_np_transitive = None
result._m_setup_etype_auto_props ()
return result
# end def _m_create_role_child
def _m_create_role_children (cls) :
for role in uniq (cls._role_children_to_add) :
role = getattr (cls._Attributes, role)
children = sorted \
( pyk.itervalues (role.E_Type.children_np)
, key = TFL.Getter.i_rank
)
for c in children :
cls._m_create_role_child ((role.name, c))
# end def _m_create_role_children
def _m_create_role_ref_attr (cls, name, role, role_type) :
orn = cls.other_role_name (role.name)
other_role = getattr (cls._Attributes, orn)
plural = other_role.max_links != 1
Attr_Type = MOM.Attr.A_Role_Ref
if plural :
if not role.rev_ref_singular :
name = plural_of (name)
Attr_Type = MOM.Attr.A_Role_Ref_Set
if other_role.role_type :
result = cls._m_create_rev_ref_attr \
( Attr_Type, name, other_role, other_role.role_type, role_type
, description = _T ("`%s` linked to `%s`") %
(_T (role_type.ui_name), _T (other_role.role_type.ui_name))
, other_role_name = role.name
)
return result
# end def _m_create_role_ref_attr
def _m_init_prop_specs (cls, name, bases, dct) :
result = cls.__m_super._m_init_prop_specs (name, bases, dct)
cls._Attributes.m_setup_names (cls)
def _gen_roles (cls) :
for a in sorted \
( pyk.itervalues (cls._Attributes._names)
, key = TFL.Sorted_By ("rank", "name")
) :
if a is not None and issubclass (a, MOM.Attr.A_Link_Role) :
yield a
cls.Role_Attrs = tuple (_gen_roles (cls))
return result
# end def _m_init_prop_specs
def _m_link_ref_attr_name (cls, role, plural = True) :
result = role.link_ref_attr_name or cls.link_ref_attr_name_p (role)
suffix = role.link_ref_suffix
if isinstance (suffix, TFL.Undef) :
suffix = cls.link_ref_attr_name_s
if suffix is not None :
result += suffix
if plural :
result = plural_of (result)
elif not plural :
result += "_1"
return result
# end def _m_link_ref_attr_name
def _m_new_e_type_dict (cls, app_type, etypes, bases, ** kw) :
result = cls.__m_super._m_new_e_type_dict \
( app_type, etypes, bases
, child_np_map = {}
, other_role_name = cls._orn
, ** kw
)
return result
# end def _m_new_e_type_dict
def _m_setup_roles (cls) :
cls.__m_super._m_setup_roles ()
cls.Partial_Roles = PRs = []
cls.Roles = Rs = []
cls.acr_map = acr_map = dict (getattr (cls, "acr_map", {}))
for a in cls.Role_Attrs :
Rs.append (a)
if a.role_type :
if a.role_type.is_partial :
PRs.append (a)
else :
cls.is_partial = True
for role in Rs :
r_type = role.role_type
if r_type and not isinstance (role.link_ref_attr_name, TFL.Undef) :
if role.link_ref_singular :
if role.max_links != 1 :
raise TypeError \
( "%s.%s: inconsistent `max_links` %s "
"for link_ref_singular"
% (cls, role.name, role.max_links)
)
else :
cls._m_create_link_ref_attr (role, r_type, plural = True)
if role.max_links == 1 :
cls._m_create_link_ref_attr (role, r_type, plural = False)
rran = role.rev_ref_attr_name or role.auto_rev_ref
if rran and len (cls.Role_Attrs) == 2 :
if rran == True :
rran = role.role_name
cls._m_create_role_ref_attr (rran, role, r_type)
cls.auto_cache_roles = ()
# end def _m_setup_roles
# end class M_Link
class M_Link1 (M_Link) :
"""Meta class of unary link-types of MOM meta object model.
`MOM.Meta.M_Link1` provides the meta machinery for
:class:`unary links<_MOM.Link.Link1>`.
"""
link_ref_attr_name_s = ""
rev_ref_attr_hidden = False
def link_ref_attr_name_p (cls, role) :
return cls.type_base_name.lower ()
# end def link_ref_attr_name_p
def other_role_name (cls, role_name) :
raise TypeError \
( "%s: There is no other role than %s"
% (cls.type_name, role_name)
)
# end def other_role_name
# end class M_Link1
class M_Link_n (M_Link) :
"""Meta class of link-types with more than 1 role."""
link_ref_attr_name_s = "_link"
rev_ref_attr_hidden = True
def link_ref_attr_name_p (cls, role) :
return "__".join \
(r.role_name for r in cls.Roles if r.name != role.name)
# end def link_ref_attr_name_p
# end class M_Link_n
class M_Link2 (M_Link_n) :
"""Meta class of binary entity-based link-types of MOM meta object model.
`MOM.Meta.M_Link2` provides the meta machinery for
:class:`binary links<_MOM.Link.Link2>`.
"""
_orn = dict (left = "right", right = "left")
def other_role_name (cls, role_name) :
return cls._orn [role_name]
# end def other_role_name
# end class M_Link2
class M_Link3 (M_Link_n) :
"""Meta class of ternary link-types of MOM meta object model.
`MOM.Meta.M_Link3` provides the meta machinery for
:class:`ternary links<_MOM.Link.Link3>`.
"""
# end class M_Link3
@TFL.Add_To_Class ("M_E_Type", M_Link)
class M_E_Type_Link (MOM.Meta.M_E_Type_Id) :
"""Meta class for essence of MOM.Link."""
Manager = MOM.E_Type_Manager.Link
### `Alias_Property` makes `destroy_dependency` usable as class and as
### instance method
### - called as class method it refers to `destroy_links`
### - called as instance method it refers to `destroy_dependency` defined
### in `Link` (or one of its ancestors)
destroy_dependency = TFL.Meta.Alias_Property ("destroy_links")
def child_np (cls, roles) :
"""Return non-partial descendent for e-types of `roles`, if any."""
### `roles` can contain `_Reload` instances --> need to use
### `.E_Type`, because `.__class__` would be wrong
etypes = tuple (r.E_Type for r in roles)
etns = tuple (et.type_name for et in etypes)
try :
result = cls.child_np_map [etns]
except KeyError :
for cnp in pyk.itervalues (cls.children_np) :
if etypes == tuple (r.role_type for r in cnp.Roles) :
result = cls.child_np_map [etns] = cnp
break
else :
### cache non-existence, too
result = cls.child_np_map [etns] = None
return result
# end def child_np
def destroy_links (cls, obj) :
"""Destroy all links where `obj` participates."""
scope = obj.home_scope
etm = getattr (scope, cls.type_name)
for l in etm.links_of (obj) :
scope.remove (l)
# end def destroy_links
def _m_default_ui_name (cls, base_name) :
result = base_name
Roles = getattr (cls, "Roles", [])
if Roles and all (R.E_Type for R in Roles) :
rn_pat = Regexp \
( "^"
+ "_(.+)_".join (R.E_Type.type_base_name for R in Roles)
+ "$"
)
if rn_pat.match (base_name) :
cs = rn_pat.groups ()
ns = tuple (R.E_Type.ui_name for R in Roles)
result = filtered_join \
(" ", itertools.chain (* paired (ns, cs)))
return result
# end def _m_default_ui_name
def _m_fix_doc (cls) :
cls.set_ui_name (cls.__name__)
cls.__m_super._m_fix_doc ()
# end def _m_fix_doc
def _m_setup_ref_maps (cls) :
cls._m_setup_roles ()
cls.__m_super._m_setup_ref_maps ()
# end def _m_setup_ref_maps
def _m_setup_roles (cls) :
cls.Roles = Roles = tuple \
(p for p in cls.primary if isinstance (p, MOM.Attr.Link_Role))
role_types = tuple \
(r.role_type for r in Roles if r.role_type is not None)
rns = set ()
cls.number_of_roles = len (Roles)
if len (role_types) == len (Roles) :
type_base_names = [rt.type_base_name for rt in role_types]
cls.role_map = role_map = {}
for i, r in enumerate (Roles) :
if r.role_name in rns :
crs = tuple (s for s in Roles if s.role_name == r.role_name)
raise TypeError \
( "%s: role name `%s` cannot be used for %s roles %s"
% ( cls.type_name, r.role_name, len (crs)
, ", ".join
("`%s`" % r.generic_role_name for r in crs)
)
)
rns.add (r.role_name)
if r.attr.name in cls._Attributes._own_names :
### Replace by app-type specific e-type
r.attr.assoc = r.assoc = cls
r.attr.role_type = r.attr.P_Type = rt = \
cls.app_type.entity_type (r.role_type)
r.attr.typ = rt.type_base_name
ac = cls.acr_map.get (r.attr.name)
cr_attr = ac and ac.cr_attr
if cr_attr and cr_attr.P_Type :
cr_attr.P_Type = cls.app_type.entity_type \
(cr_attr.P_Type)
if r.role_name != r.generic_role_name :
setattr \
( cls, r.role_name
, TFL.Meta.Alias_Property (r.generic_role_name)
)
cls.attributes.add_alias (r.role_name, r.generic_role_name)
r.role_index = i
for key in set \
(( r.default_role_name, r.generic_role_name
, r.role_name, r.role_type.type_name
, r.role_type.type_base_name
)) :
role_map [key] = r.role_index
# end def _m_setup_roles
# end class M_E_Type_Link
@TFL.Add_To_Class ("M_E_Type", M_Link1)
class M_E_Type_Link1 (M_E_Type_Link) :
"""Meta class for essence of MOM.Link1."""
Manager = MOM.E_Type_Manager.Link1
# end class M_E_Type_Link1
@TFL.Add_To_Class ("M_E_Type", M_Link2)
class M_E_Type_Link2 (M_E_Type_Link) :
"""Meta class for essence of MOM.Link2."""
Manager = MOM.E_Type_Manager.Link2
# end class M_E_Type_Link2
@TFL.Add_To_Class ("M_E_Type", M_Link3)
class M_E_Type_Link3 (M_E_Type_Link2) :
"""Meta class for essence of MOM.Link2."""
Manager = MOM.E_Type_Manager.Link3
# end class M_E_Type_Link3
class M_E_Type_Link1_Destroyed (MOM.Meta.M_E_Type_Id_Destroyed, M_E_Type_Link1) :
"""Meta class for `_Destroyed` classes of descendents of MOM.Link1."""
# end class M_E_Type_Link1_Destroyed
class M_E_Type_Link2_Destroyed (MOM.Meta.M_E_Type_Id_Destroyed, M_E_Type_Link2) :
"""Meta class for `_Destroyed` classes of descendents of MOM.Link2."""
# end class M_E_Type_Link2_Destroyed
class M_E_Type_Link3_Destroyed (MOM.Meta.M_E_Type_Id_Destroyed, M_E_Type_Link3) :
"""Meta class for `_Destroyed` classes of descendents of MOM.Link3."""
# end class M_E_Type_Link3_Destroyed
class M_E_Type_Link1_Reload (MOM.Meta.M_E_Type_Id_Reload, M_E_Type_Link1) :
"""Meta class for `_Reload` classes of descendents of MOM.Link1."""
# end class M_E_Type_Link1_Reload
class M_E_Type_Link2_Reload (MOM.Meta.M_E_Type_Id_Reload, M_E_Type_Link2) :
"""Meta class for `_Reload` classes of descendents of MOM.Link2."""
# end class M_E_Type_Link2_Reload
class M_E_Type_Link3_Reload (MOM.Meta.M_E_Type_Id_Reload, M_E_Type_Link3) :
"""Meta class for `_Reload` classes of descendents of MOM.Link3."""
# end class M_E_Type_Link3_Reload
### «text» ### start of documentation
__doc__ = """
"""
if __name__ != "__main__" :
MOM.Meta._Export ("*")
### __END__ MOM.Meta.M_Link | PypiClean |
/Electrum-CHI-3.3.8.tar.gz/Electrum-CHI-3.3.8/electrum_chi/electrum/verifier.py |
import asyncio
from typing import Sequence, Optional, TYPE_CHECKING
import aiorpcx
from .util import bh2u, TxMinedInfo, NetworkJobOnDefaultServer
from .crypto import sha256d
from .bitcoin import hash_decode, hash_encode
from .transaction import Transaction
from .blockchain import hash_header
from .interface import GracefulDisconnect
from .network import UntrustedServerReturnedError
from . import constants
if TYPE_CHECKING:
from .network import Network
from .address_synchronizer import AddressSynchronizer
class MerkleVerificationFailure(Exception): pass
class MissingBlockHeader(MerkleVerificationFailure): pass
class MerkleRootMismatch(MerkleVerificationFailure): pass
class InnerNodeOfSpvProofIsValidTx(MerkleVerificationFailure): pass
class SPV(NetworkJobOnDefaultServer):
""" Simple Payment Verification """
def __init__(self, network: 'Network', wallet: 'AddressSynchronizer'):
self.wallet = wallet
NetworkJobOnDefaultServer.__init__(self, network)
def _reset(self):
super()._reset()
self.merkle_roots = {} # txid -> merkle root (once it has been verified)
self.requested_merkle = set() # txid set of pending requests
async def _start_tasks(self):
async with self.group as group:
await group.spawn(self.main)
def diagnostic_name(self):
return self.wallet.diagnostic_name()
async def main(self):
self.blockchain = self.network.blockchain()
while True:
await self._maybe_undo_verifications()
await self._request_proofs()
await asyncio.sleep(0.1)
async def _request_proofs(self):
local_height = self.blockchain.height()
unverified = self.wallet.get_unverified_txs()
for tx_hash, tx_height in unverified.items():
# do not request merkle branch if we already requested it
if tx_hash in self.requested_merkle or tx_hash in self.merkle_roots:
continue
# or before headers are available
if tx_height <= 0 or tx_height > local_height:
continue
# if it's in the checkpoint region, we still might not have the header
header = self.blockchain.read_header(tx_height)
if header is None:
if tx_height < constants.net.max_checkpoint():
await self.group.spawn(self.network.request_chunk(tx_height, None, can_return_early=True))
continue
# request now
self.logger.info(f'requested merkle {tx_hash}')
self.requested_merkle.add(tx_hash)
await self.group.spawn(self._request_and_verify_single_proof, tx_hash, tx_height)
async def _request_and_verify_single_proof(self, tx_hash, tx_height):
try:
merkle = await self.network.get_merkle_for_transaction(tx_hash, tx_height)
except UntrustedServerReturnedError as e:
if not isinstance(e.original_exception, aiorpcx.jsonrpc.RPCError):
raise
self.logger.info(f'tx {tx_hash} not at height {tx_height}')
self.wallet.remove_unverified_tx(tx_hash, tx_height)
self.requested_merkle.discard(tx_hash)
return
# Verify the hash of the server-provided merkle branch to a
# transaction matches the merkle root of its block
if tx_height != merkle.get('block_height'):
self.logger.info('requested tx_height {} differs from received tx_height {} for txid {}'
.format(tx_height, merkle.get('block_height'), tx_hash))
tx_height = merkle.get('block_height')
pos = merkle.get('pos')
merkle_branch = merkle.get('merkle')
# we need to wait if header sync/reorg is still ongoing, hence lock:
async with self.network.bhi_lock:
header = self.network.blockchain().read_header(tx_height)
try:
verify_tx_is_in_block(tx_hash, merkle_branch, pos, header, tx_height)
except MerkleVerificationFailure as e:
if self.network.config.get("skipmerklecheck"):
self.logger.info(f"skipping merkle proof check {tx_hash}")
else:
self.logger.info(repr(e))
raise GracefulDisconnect(e)
# we passed all the tests
self.merkle_roots[tx_hash] = header.get('merkle_root')
self.requested_merkle.discard(tx_hash)
self.logger.info(f"verified {tx_hash}")
header_hash = hash_header(header)
tx_info = TxMinedInfo(height=tx_height,
timestamp=header.get('timestamp'),
txpos=pos,
header_hash=header_hash)
self.wallet.add_verified_tx(tx_hash, tx_info)
#if self.is_up_to_date() and self.wallet.is_up_to_date():
# self.wallet.save_verified_tx(write=True)
@classmethod
def hash_merkle_root(cls, merkle_branch: Sequence[str], tx_hash: str, leaf_pos_in_tree: int):
"""Return calculated merkle root."""
try:
h = hash_decode(tx_hash)
merkle_branch_bytes = [hash_decode(item) for item in merkle_branch]
leaf_pos_in_tree = int(leaf_pos_in_tree) # raise if invalid
except Exception as e:
raise MerkleVerificationFailure(e)
if leaf_pos_in_tree < 0:
raise MerkleVerificationFailure('leaf_pos_in_tree must be non-negative')
index = leaf_pos_in_tree
for item in merkle_branch_bytes:
if len(item) != 32:
raise MerkleVerificationFailure('all merkle branch items have to 32 bytes long')
h = sha256d(item + h) if (index & 1) else sha256d(h + item)
index >>= 1
cls._raise_if_valid_tx(bh2u(h))
if index != 0:
raise MerkleVerificationFailure(f'leaf_pos_in_tree too large for branch')
return hash_encode(h)
@classmethod
def _raise_if_valid_tx(cls, raw_tx: str):
# If an inner node of the merkle proof is also a valid tx, chances are, this is an attack.
# https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-June/016105.html
# https://lists.linuxfoundation.org/pipermail/bitcoin-dev/attachments/20180609/9f4f5b1f/attachment-0001.pdf
# https://bitcoin.stackexchange.com/questions/76121/how-is-the-leaf-node-weakness-in-merkle-trees-exploitable/76122#76122
tx = Transaction(raw_tx)
try:
tx.deserialize()
except:
pass
else:
raise InnerNodeOfSpvProofIsValidTx()
async def _maybe_undo_verifications(self):
old_chain = self.blockchain
cur_chain = self.network.blockchain()
if cur_chain != old_chain:
self.blockchain = cur_chain
above_height = cur_chain.get_height_of_last_common_block_with_chain(old_chain)
self.logger.info(f"undoing verifications above height {above_height}")
tx_hashes = self.wallet.undo_verifications(self.blockchain, above_height)
for tx_hash in tx_hashes:
self.logger.info(f"redoing {tx_hash}")
self.remove_spv_proof_for_tx(tx_hash)
def remove_spv_proof_for_tx(self, tx_hash):
self.merkle_roots.pop(tx_hash, None)
self.requested_merkle.discard(tx_hash)
def is_up_to_date(self):
return not self.requested_merkle
def verify_tx_is_in_block(tx_hash: str, merkle_branch: Sequence[str],
leaf_pos_in_tree: int, block_header: Optional[dict],
block_height: int) -> None:
"""Raise MerkleVerificationFailure if verification fails."""
if not block_header:
raise MissingBlockHeader("merkle verification failed for {} (missing header {})"
.format(tx_hash, block_height))
if len(merkle_branch) > 30:
raise MerkleVerificationFailure(f"merkle branch too long: {len(merkle_branch)}")
calc_merkle_root = SPV.hash_merkle_root(merkle_branch, tx_hash, leaf_pos_in_tree)
if block_header.get('merkle_root') != calc_merkle_root:
raise MerkleRootMismatch("merkle verification failed for {} ({} != {})".format(
tx_hash, block_header.get('merkle_root'), calc_merkle_root)) | PypiClean |
/BioTEMPy-2.1.0a0-py3-none-any.whl/TEMPy/maps/em_map.py |
import datetime
import math
from random import randrange
import sys
import numpy as np
from scipy.ndimage.interpolation import (
affine_transform,
map_coordinates,
shift,
spline_filter,
)
from scipy.ndimage import (
generic_filter,
laplace,
minimum_filter,
uniform_filter,
)
from scipy.ndimage.filters import sobel
from scipy.fftpack import (
fftn,
fftshift,
)
from scipy.signal import resample
from scipy.spatial import KDTree
from scipy.ndimage.morphology import binary_opening
from scipy.ndimage import measurements
import struct as binary
import TEMPy.math.vector as Vector
from TEMPy.protein.prot_rep_biopy import (
BioPyAtom,
BioPy_Structure,
)
import mrcfile
class Map:
"""A class representing information from a density map file.
Args:
fullMap: 3D Numpy array containing the EM density
origin: Origin of the EM map, in [x, y, z] format.
apix: Pixel size (Å) of the EM map.
filename: Filename of the parsed map.
header: Python array, containing the header information, ordered based
on the
`mrc header format <https://www.ccpem.ac.uk/mrc_format/mrc2014.php>`_.
ext_header: Information present in the extended header, as per the
`mrc header format <https://www.ccpem.ac.uk/mrc_format/mrc2014.php>`_
, if present.
Returns:
Map Instance.
:ivar Map.fullMap: 3D Numpy array containing the EM density
:ivar Map.origin: Origin of the EM map, in [x, y, z] format.
:ivar Map.apix: Pixel size (Å) of the EM map.
:ivar Map.filename: Filename of the parsed map.
:ivar Map.header: Python array, containing the header information, ordered
based on the
`mrc header format <https://www.ccpem.ac.uk/mrc_format/mrc2014.php>`_.
:ivar Map.ext_header: Information present in the extended header, as per
the
`mrc header format <https://www.ccpem.ac.uk/mrc_format/mrc2014.php>`_
, if present.
"""
def __init__(
self,
fullMap,
origin,
apix,
filename,
header=[],
ext_header=[]
):
self.header = header
self.origin = origin
self.apix = apix
self.filename = filename
self.fullMap = fullMap
self.ext_header = ext_header
def __repr__(self):
box_size = list(self.box_size())
box_size.reverse()
string1 = 'Obtained from ' + self.filename + '\n'
string2 = 'Origin: [{:.3f} {:.3f} {:.3f}]\n'.format(
self.origin[0], self.origin[1], self.origin[2]
)
string3 = 'Box size (x,y,z): ' + str(box_size) + '\n'
string4 = 'Grid spacing: [{:.3f} {:.3f} {:.3f}]\n'.format(
self.apix[0], self.apix[1], self.apix[2])
string5 = (
'Min, max, mean, std: %.3f, %.3f, %.3f, %.3f\n' %
(
self.min(),
self.max(),
self.mean(),
self.std()
)
)
return string1 + string2 + string3 + string4 + string5
def x_origin(self):
"""
Returns:
x-coordinate of the origin."""
return self.origin[0]
def y_origin(self):
"""
Returns:
y-coordinate of the origin."""
return self.origin[1]
def z_origin(self):
"""
Returns:
z-coordinate of the origin."""
return self.origin[2]
def copy(self):
"""
Returns:
copy of the Map Instance.
"""
copy = Map(
self.fullMap.copy(),
self.origin[:],
self.apix,
self.filename,
self.header[:],
self.ext_header[:]
)
return copy
def getMap(self):
"""
Returns:
Numpy array containing the map density data.
"""
return self.fullMap
def box_size(self):
"""
Returns:
Size of the map array, in Numpy (Z, Y, X) format. """
return self.fullMap.shape
def x_size(self):
"""
Returns:
Size of the map array in x direction.
"""
return self.fullMap.shape[2]
def y_size(self):
"""
Returns:
Size of the map array in y direction."""
return self.fullMap.shape[1]
def z_size(self):
"""
Returns:
Size of the map array in z direction.
"""
return self.fullMap.shape[0]
def map_size(self):
"""
Returns:
Number of voxels in the fullMap array. """
return self.fullMap.size
def __getitem__(self, index):
"""
Allows direct indexing of the map array from the Map instance.
ie. map[2][2][1] instead of map.fullMap[2][2][1]
"""
return self.fullMap[index]
def _shift_density(self, offset):
self.fullMap = self.fullMap + float(offset)
def scale_map(self, scaling):
""" Scaling Map by scaling factor
Returns:
new Map instance
"""
sc = 1. / scaling
c_sh = self.pixel_centre() * (1 - sc)
newMap = self.copy()
newMap.fullMap = affine_transform(
self.fullMap,
np.diag([sc, sc, sc]),
offset=[c_sh.z, c_sh.y, c_sh.x]
)
return newMap
def _crop_box(self, c, f):
"""
Crop a map in place based on a threshold
Arguments:
*c*
map threshold
*f*
factor to relax threshold
Returns:
"""
minval = float(c) - (float(f) * self.std())
axis_diff = []
for i in range(3):
ct1 = 0
try:
while (self.fullMap[0] < minval).all():
self.fullMap = np.delete(self.fullMap, 0, 0)
ct1 += 1
except (IndexError, ValueError):
pass
axis_diff.append(ct1)
ct2 = 0
try:
while (self.fullMap[self.fullMap.shape[0] - 1] < minval).all():
self.fullMap = np.delete(self.fullMap, -1, 0)
ct2 += 1
except (IndexError, ValueError):
pass
self.fullMap = np.transpose(self.fullMap, (2, 0, 1))
ox = self.origin[0] + axis_diff[1] * self.apix[0]
oy = self.origin[1] + axis_diff[2] * self.apix[1]
oz = self.origin[2] + axis_diff[0] * self.apix[2]
self.origin = (ox, oy, oz)
def _alignment_box(self, map2, s):
(ox, oy, oz) = (
self.origin[0],
self.origin[1],
self.origin[2]
)
(o1x, o1y, o1z) = (
map2.origin[0],
map2.origin[1],
map2.origin[2]
)
offset = (
o1x - ox,
o1y - oy,
o1z - oz
)
(m1x, m1y, m1z) = (
ox + self.fullMap.shape[2] * self.apix[2],
oy + self.fullMap.shape[1] * self.apix[1],
oz + self.fullMap.shape[0] * self.apix[0]
)
(m2x, m2y, m2z) = (
o1x + map2.fullMap.shape[2] * map2.apix[2],
o1y + map2.fullMap.shape[1] * map2.apix[1],
o1z + map2.fullMap.shape[0] * map2.apix[0]
)
(nx, ny, nz) = (o1x, o1y, o1z)
if offset[0] > 0:
nx = ox
if offset[1] > 0:
ny = oy
if offset[2] > 0:
nz = oz
(lz, ly, lx) = (
(m2z-nz) / float(s[2]),
(m2y-ny) / float(s[1]),
(m2x-nx) / float(s[0])
)
if m2x < m1x:
lx = (m1x - nx) / float(s[0])
if m2y < m1y:
ly = (m1y - ny) / float(s[1])
if m2z < m1z:
lz = (m1z - nz) / float(s[2])
gridshape = (int(lz), int(ly), int(lx))
new_origin = (nx, ny, nz)
return gridshape, new_origin
def _interpolate_to_grid(self, grid, s, ori):
new_map = self.copy()
(ox, oy, oz) = (
self.origin[0],
self.origin[1],
self.origin[2],
)
(o1x, o1y, o1z) = (
float(ori[0]),
float(ori[1]),
float(ori[2])
)
scale = s / self.apix
offset = (
o1x - ox,
o1y - oy,
o1z - oz
)
gridshape = grid
new_map.origin = (o1x, o1y, o1z)
grid_indices = np.indices(gridshape)
z_ind = grid_indices[0]
z_ind.ravel()
y_ind = grid_indices[1]
y_ind.ravel()
x_ind = grid_indices[2]
x_ind.ravel()
z_ind = ((offset[2]) / self.apix[2]) + scale[2] * z_ind
y_ind = ((offset[1]) / self.apix[1]) + scale[1] * y_ind
x_ind = ((offset[0]) / self.apix[0]) + scale[0] * x_ind
new_array = map_coordinates(
self.fullMap,
[z_ind, y_ind, x_ind],
cval=self.min(),
)
new_map.fullMap = new_array.reshape(gridshape)
new_map.origin = (o1x, o1y, o1z)
new_map.apix = s
return new_map
def _downsample_apix(self, spacing):
apix_ratio = (
round(self.header[10] / self.header[7], 2) / spacing,
round(self.header[11] / self.header[8], 2) / spacing,
round(self.header[12] / self.header[9], 2) / spacing
)
grid_shape = (
int(round(self.z_size() * apix_ratio[2])),
int(round(self.y_size() * apix_ratio[1])),
int(round(self.x_size() * apix_ratio[0]))
)
try:
newmap = self._interpolate_to_grid1(
grid_shape,
spacing,
self.origin
)
except: # noqa:E722
newmap = self._interpolate_to_grid(
grid_shape,
spacing,
self.origin
)
return newmap
def downsample_map(self, spacing, grid_shape=None):
apix_ratio = self.apix / spacing
if grid_shape is None:
grid_shape = (
int(round(self.z_size() * apix_ratio[2])),
int(round(self.y_size() * apix_ratio[1])),
int(round(self.x_size() * apix_ratio[0]))
)
emmap_1 = self._interpolate_to_grid(
grid_shape,
spacing,
self.origin
)
return emmap_1
def _peak_density(self):
"""
Find background peak and sigma (for values beyond the peak)
Returns:
peak, average and sigma (beyond peak)
"""
freq, bins = np.histogram(self.fullMap, 1000)
ind = np.nonzero(freq == np.amax(freq))[0]
peak = None
ave = np.mean(self.fullMap)
sigma = np.std(self.fullMap)
for i in ind:
val = (bins[i] + bins[i + 1]) / 2.
if val < float(ave) + float(sigma):
peak = val
if peak is None:
peak = ave
sigma1 = None
if peak is not None:
mask_array = self.fullMap[self.fullMap > peak]
sigma1 = np.sqrt(
np.mean(
np.square(mask_array - peak)
)
)
return peak, ave, sigma1
def _sobel_surface_mask(self, c):
""" Apply sobel filter on binned density maps
Args:
c: Threshold that defines the maps surface.
Returns:
Sobel filtered Map instance
"""
newmap = self.copy()
binmap = newmap.fullMap > float(c)
sx = sobel(binmap, 0, mode='constant')
sy = sobel(binmap, 1, mode='constant')
sz = sobel(binmap, 2, mode='constant')
newmap.fullMap = np.sqrt(sx * sx + sy * sy + sz * sz)
newmap.fullMap = binmap * newmap.fullMap
return newmap
def _sobel_filter_contour(self, c):
"""Apply sobel filter on density maps above contour
Args:
c: Threshold that defines the maps surface.
Returns:
Sobel filtered Map instance
"""
newmap = self.copy()
binmap = newmap.fullMap > c
newmap.fullMap = binmap * newmap.fullMap
sx = sobel(newmap.fullMap, 0, mode='constant')
sy = sobel(newmap.fullMap, 1, mode='constant')
sz = sobel(newmap.fullMap, 2, mode='constant')
newmap.fullMap = np.sqrt(sx * sx + sy * sy + sz * sz)
return newmap
def _sobel_filter_map_all(self):
""" Apply sobel filter on self
Returns:
Sobel filtered Map instance
"""
newmap = self.copy()
sx = sobel(newmap.fullMap, 0, mode='constant')
sy = sobel(newmap.fullMap, 1, mode='constant')
sz = sobel(newmap.fullMap, 2, mode='constant')
newmap.fullMap = np.sqrt(sx * sx + sy * sy + sz * sz)
return newmap
def _laplace_filtered_contour(self, c):
"""
Apply Laplacian filter on density maps above contour
Returns:
new Map instance
"""
newmap = self.copy()
binmap = newmap.fullMap > float(c)
newmap.fullMap = binmap * newmap.fullMap
newmap.fullMap = laplace(newmap.fullMap)
return newmap
def _surface_minimum_filter(self, c):
"""
contour the map
get the footprint array corresponding to 6 neighbors of a voxel
apply minimum filter to return surface voxels with zeros in
select those voxels with zeros filled in after applying minimum filter
"""
binmap = self.fullMap > float(c)
fp = self._grid_footprint()
binmap_surface = minimum_filter(
binmap * 1,
footprint=fp,
mode='constant',
cval=0.0
)
binmap_surface = ((binmap * 1 - binmap_surface) == 1) * 1
return binmap_surface
def _surface_features(
self,
c,
window=21,
itern=1
):
newmap = self.copy()
binmap = self.fullMap > float(c)
newmap.fullMap = binmap * 1.0
for i in range(itern):
newmap.fullMap = uniform_filter(
newmap.fullMap,
size=window,
mode='constant',
cval=0.0
)
newmap.fullMap = newmap.fullMap*binmap
binmap = newmap.fullMap > 0.0
minval = newmap.fullMap[binmap].min()
newmap.fullMap = newmap.fullMap - minval + (0.001 * minval)
newmap.fullMap = newmap.fullMap * binmap
newmap.fullMap = newmap.fullMap / float(newmap.fullMap.max())
return newmap
def _soft_mask(
self,
c=None,
window=5,
itern=3
):
newmap = self.copy()
if c is not None:
newmap.fullMap = newmap.fullMap * (newmap.fullMap > float(c))
binmap = newmap.fullMap != 0
footprint_sph = self._make_spherical_footprint(window)
for i in range(itern):
newmap.fullMap = generic_filter(
newmap.fullMap,
np.mean,
footprint=footprint_sph,
mode='constant',
cval=0.0
)
newmap.fullMap[binmap] = self.fullMap[binmap]
return newmap.fullMap
def _std_neigh(self, c=None, window=6):
newmap = self.copy()
if c is not None:
newmap.fullMap = newmap.fullMap * (newmap.fullMap > float(c))
footprint_sph = self._make_spherical_footprint(window)
newmap.fullMap = generic_filter(
newmap.fullMap,
np.std,
footprint=footprint_sph,
mode='constant',
cval=0.0
)
return newmap
def _mean_neigh(
self,
c=None,
window=6,
itr=1
):
newmap = self.copy()
if c is not None:
newmap.fullMap = newmap.fullMap * (newmap.fullMap > float(c))
footprint_sph = self._make_spherical_footprint(window)
for i in range(itr):
newmap.fullMap = generic_filter(
newmap.fullMap,
np.mean,
footprint=footprint_sph,
mode='constant',
cval=0.0,
)
return newmap
def _map_digitize(
self,
cutoff,
nbins,
left=False
):
try:
from numpy import digitize
except ImportError:
print('Numpy Digitize missing, try v1.8')
binMap = self.copy()
bins = []
step = (self.fullMap.max() - float(cutoff)) / nbins
ini = float(cutoff) + (0.000001 * step)
if left:
ini = float(cutoff) - (0.000001 * step)
bins.append(ini)
for ii in range(1, nbins + 1):
bins.append(float(cutoff) + ii * step)
if bins[-1] < self.fullMap.max():
bins = bins[:-1]
bins.append(self.fullMap.max())
for z in range(len(self.fullMap)):
for y in range(len(self.fullMap[z])):
binMap.fullMap[z][y] = digitize(self.fullMap[z][y], bins)
return binMap
def _map_depth(self, c):
newmap = self.copy()
binmap = self.fullMap > float(c)
newmap.fullMap = binmap * 1.0
for i in range(3):
newmap.fullMap = uniform_filter(
newmap.fullMap,
size=21,
mode='constant',
cval=0.0,
)
newmap.fullMap = newmap.fullMap * binmap
binmap = newmap.fullMap > 0.0
minval = newmap.fullMap[binmap].min()
newmap.fullMap = newmap.fullMap - minval + 0.001
newmap.fullMap = newmap.fullMap * binmap
newmap.fullMap = newmap.fullMap / float(newmap.fullMap.max())
return newmap
def _label_patches(self, c, prob=0.2):
fp = self._grid_footprint()
binmap = self.fullMap > float(c)
label_array, labels = measurements.label(
self.fullMap * binmap,
structure=fp
)
sizes = measurements.sum(binmap, label_array, range(labels + 1))
if labels < 10:
m_array = sizes < 0.05 * sizes.max()
ct_remove = np.sum(m_array)
remove_points = m_array[label_array]
label_array[remove_points] = 0
return (
(label_array > 0) * (self.fullMap * binmap),
labels - ct_remove + 1
)
freq, bins = np.histogram(sizes[1:], 20)
m_array = np.zeros(len(sizes))
ct_remove = 0
for i in range(len(freq)):
fr = freq[i]
s2 = bins[i + 1]
s1 = bins[i]
p_size = float(fr) / float(np.sum(freq))
if s2 < 10 or p_size > prob:
m_array = m_array + ((sizes >= s1) & (sizes < s2))
ct_remove += 1
m_array = m_array > 0
remove_points = m_array[label_array]
label_array[remove_points] = 0
return (
(label_array > 0) * (self.fullMap * binmap),
labels - ct_remove
)
def _grid_footprint(self):
a = np.zeros((3, 3, 3))
a[1, 1, 1] = 1
a[0, 1, 1] = 1
a[1, 0, 1] = 1
a[1, 1, 0] = 1
a[2, 1, 1] = 1
a[1, 2, 1] = 1
a[1, 1, 2] = 1
return a
def _make_spherical_footprint(self, ln):
rad_z = np.arange(np.floor(ln / 2.0) * -1, np.ceil(ln / 2.0))
rad_y = np.arange(np.floor(ln / 2.0) * -1, np.ceil(ln / 2.0))
rad_x = np.arange(np.floor(ln / 2.0) * -1, np.ceil(ln / 2.0))
rad_x = rad_x**2
rad_y = rad_y**2
rad_z = rad_z**2
dist = np.sqrt(rad_z[:, None, None] + rad_y[:, None] + rad_x)
return (dist <= np.floor(ln / 2.0)) * 1
def _map_binary_opening(self, c, it=1):
"""
current position can be updated based on neighbors only
threshold can be 1*std() to be safe?
"""
fp = self._grid_footprint()
fp[1, 1, 1] = 0
self.fullMap = self.fullMap * (self.fullMap > float(c))
self.fullMap = self.fullMap * binary_opening(
self.fullMap > float(c),
structure=fp,
iterations=it
)
def resize_map(self, new_size):
""" Resize Map instance by cropping/padding (with zeros) the box.
Args:
new_size: 3-tuple (x,y,z) giving the box size.
Returns:
Map instance with new box size.
"""
newMap = self.copy()
newMap.fullMap = np.zeros(new_size)
min_box = [
min(x, y) for x, y in zip(newMap.box_size(), self.box_size())
]
newMap.fullMap[
:min_box[0],
:min_box[1],
:min_box[2]
] = self.fullMap[
:min_box[0],
:min_box[1],
:min_box[2]
]
return newMap
def _mut_normalise(self):
if self.fullMap.std() == 0:
pass
else:
self.fullMap = (
(self.fullMap - self.fullMap.mean()) /
self.fullMap.std()
)
return self
def normalise(self):
"""Returns: 0-mean normalised Map instance. """
return self.copy()._mut_normalise()
def normalise_to_1_minus1(self, in_place=False):
"""
"""
if not in_place:
map = self.copy()
else:
map = self
data = map.fullMap
normalised_data = (np.divide(
(data - data.min()),
(data.max() - data.min())) * 2) - 1
map.fullMap = normalised_data
return map
def pad_map(self, nx, ny, nz):
""" Pad a map (in place) by specified number of voxels along each
dimension.
Args:
nx,ny,nz: Number of voxels to pad in each dimension.
Returns:
Padded Map instance
"""
gridshape = (
self.fullMap.shape[0] + nz,
self.fullMap.shape[1] + ny,
self.fullMap.shape[2] + nx
)
new_array = np.zeros(gridshape)
new_array.fill(self.fullMap.min())
oldshape = self.fullMap.shape
indz, indy, indx = (
round((gridshape[0] - oldshape[0]) / 2.),
round((gridshape[1] - oldshape[1]) / 2.),
round((gridshape[2] - oldshape[2]) / 2.)
)
self.origin = (
self.origin[0] - self.apix[0] * indx,
self.origin[1] - self.apix[1] * indy,
self.origin[2] - self.apix[2] * indz
)
new_array[
indz:indz + oldshape[0],
indy:indy + oldshape[1],
indx:indx + oldshape[2]
] = self.fullMap
self.fullMap = new_array
def get_cropped_box_around_atom(self, atom, new_box_size):
"""Gets a cropped box around an atom's position
"""
x = int(round((atom.x - self.origin[0])/self.apix[0], 0))
y = int(round((atom.y - self.origin[1])/self.apix[1], 0))
z = int(round((atom.z - self.origin[2])/self.apix[2], 0))
if np.isclose(new_box_size, self.fullMap.shape).all():
print("WARNING: Cropped box size is equal to, or bigger than, the "
"original box size.")
return self.copy()
else:
return self.get_cropped_box([z, y, x], new_box_size)
def get_cropped_box(self, centroid, new_box_size):
"""
returns np.array rather than map object
"""
map_np_array = self.fullMap
box_size = self.fullMap.shape
if new_box_size[0] % 2 != 0:
half_mask_left = int((new_box_size[0] / 2) - 0.5)
half_mask_right = int((new_box_size[0] / 2) + 0.5)
else:
half_mask_left = int(new_box_size[0] / 2)
half_mask_right = int(new_box_size[0] / 2)
# check we're not indexing outside limits
if centroid[0] - half_mask_left < 0:
centroid[0] = half_mask_left
if centroid[2] - half_mask_left < 0:
centroid[2] = half_mask_left
if centroid[1] - half_mask_left < 0:
centroid[1] = half_mask_left
if centroid[0] + half_mask_right >= box_size[0]:
centroid[0] = box_size[0] - half_mask_right
if centroid[2] + half_mask_right >= box_size[2]:
centroid[2] = box_size[2] - half_mask_right
if centroid[1] + half_mask_right >= box_size[1]:
centroid[1] = box_size[1] - half_mask_right
top_left = [
centroid[0] - half_mask_left,
centroid[1] - half_mask_left,
centroid[2] - half_mask_left,
]
bottom_right = [
centroid[0] + half_mask_right,
centroid[1] + half_mask_right,
centroid[2] + half_mask_right,
]
cropped_map = map_np_array[
top_left[0]:bottom_right[0],
top_left[1]:bottom_right[1],
top_left[2]:bottom_right[2],
]
return Map(cropped_map, self.origin, self.apix, self.filename)
def rotate_by_axis_angle(
self,
x,
y,
z,
angle,
CoM,
rad=False,
):
""" Rotate map around pivot, given by CoM, using Euler angles.
Args:
x,y,z: Axis to rotate about, ie. x,y,z = 0,0,1 rotates the Map
round the xy-plane.
angle: Angle (in radians if rad == True, else in degrees) of
rotation.
CoM: Centre of mass around which map will be rotated.
Returns:
Rotated Map instance
"""
m = Vector.axis_angle_to_matrix(
x,
y,
z,
angle,
rad,
)
newCoM = CoM.matrix_transform(m.T)
offset = CoM - newCoM
newMap = self.matrix_transform(
m,
offset.x,
offset.y,
offset.z,
)
return newMap
def rotate_by_euler(
self,
x,
y,
z,
CoM,
rad=False
):
"""Rotate map around pivot, given by CoM, using Euler angles.
Args:
x,y,z: Euler angles (in radians if rad == True, else in degrees)
used to rotate map.
CoM: Centre of mass around which map will be rotated.
*x, y, z*
translation in angstroms.
Returns:
Rotated Map instance
"""
m = Vector.euler_to_matrix(
x,
y,
z,
rad,
)
newCoM = CoM.matrix_transform(m.T)
offset = CoM - newCoM
newMap = self.matrix_transform(
m,
offset.x,
offset.y,
offset.z,
)
return newMap
def _box_transform(self, mat):
""" Calculate box dimensions after rotation
Args:
mat: Input rotation matrix
Returns:
New box shape in format x, y, z
"""
v1 = Vector.Vector(
self.origin[0],
self.origin[1],
self.origin[2],
)
v2 = Vector.Vector(
self.origin[0] + (self.apix[0] * self.x_size()),
self.origin[1],
self.origin[2],
)
v3 = Vector.Vector(
self.origin[0] + (self.apix[0] * self.x_size()),
self.origin[1] + (self.apix[1] * self.y_size()),
self.origin[2],
)
v4 = Vector.Vector(
self.origin[0] + (self.apix[0] * self.x_size()),
self.origin[1] + (self.apix[1] * self.y_size()),
self.origin[2] + (self.apix[2] * self.z_size()),
)
v5 = Vector.Vector(
self.origin[0],
self.origin[1] + (self.apix[0] * self.y_size()),
self.origin[2],
)
v6 = Vector.Vector(
self.origin[0],
self.origin[1],
self.origin[2] + (self.apix[1] * self.z_size()),
)
v7 = Vector.Vector(
self.origin[0],
self.origin[1] + (self.apix[1] * self.y_size()),
self.origin[2] + (self.apix[2] * self.z_size()),
)
v8 = Vector.Vector(
self.origin[0] + (self.apix[0] * self.x_size()),
self.origin[1],
self.origin[2] + (self.apix[2] * self.z_size())
)
v1 = v1.matrix_transform(mat)
v2 = v2.matrix_transform(mat)
v3 = v3.matrix_transform(mat)
v4 = v4.matrix_transform(mat)
v5 = v5.matrix_transform(mat)
v6 = v6.matrix_transform(mat)
v7 = v7.matrix_transform(mat)
v8 = v8.matrix_transform(mat)
max_x = 0
max_y = 0
max_z = 0
ltmp = [
v1,
v2,
v3,
v4,
v5,
v6,
v7,
v8,
]
for i in range(8):
for j in range(i, 8):
if abs(ltmp[i].x - ltmp[j].x) > max_x:
max_x = abs(ltmp[i].x - ltmp[j].x)
if abs(ltmp[i].y - ltmp[j].y) > max_y:
max_y = abs(ltmp[i].y - ltmp[j].y)
if abs(ltmp[i].z - ltmp[j].z) > max_z:
max_z = abs(ltmp[i].z - ltmp[j].z)
output_dimension = Vector.Vector(max_x, max_y, max_z)
return output_dimension
def _rotation_offset(
self,
mat,
CoM1,
CoM2,
):
newCoM = CoM2.matrix_transform(mat)
offset = CoM1 - newCoM
return offset
def rotate_by_matrix(self, mat, CoM):
"""Rotate map around pivot, given by CoM, using a rotation matrix
Args:
mat: 3x3 matrix used to rotate map.
CoM: Rotation pivot, usually the centre of mass around which
map will be rotated.
Returns:
Rotated Map instance
"""
newCoM = CoM.matrix_transform(mat.T)
offset = CoM - newCoM
newMap = self.matrix_transform(
mat,
offset.x,
offset.y,
offset.z,
)
return newMap
def _matrix_transform_offset(
self,
mat,
shape,
x=0,
y=0,
z=0,
):
newMap = self.copy()
off_x = float(x / self.apix[0])
off_y = float(y / self.apix[1])
off_z = float(z / self.apix[2])
newMap.fullMap = newMap.fullMap.swapaxes(0, 2)
newMap.fullMap = affine_transform(
newMap.fullMap,
mat,
offset=(off_x, off_y, off_z),
output_shape=shape,
cval=(self.min())
)
newMap.fullMap = newMap.fullMap.swapaxes(0, 2)
return newMap
def matrix_transform(
self,
mat,
x=0,
y=0,
z=0,
):
"""" Apply affine transform to the map.
Arguments:
mat: Affine 3x3 transformation matrix
shape: New box dimensions
x, y, z: Translation in angstroms in respective plane.
Returns:
Transformed Map instance
"""
newMap = self.copy()
mat = mat.T
off_x = x / self.apix[0]
off_y = y / self.apix[1]
off_z = z / self.apix[2]
x_o = -self.x_origin() / self.apix[0]
y_o = -self.y_origin() / self.apix[1]
z_o = -self.z_origin() / self.apix[2]
off_x += x_o - mat[0, 0] * x_o - mat[0, 1] * y_o - mat[0, 2] * z_o
off_y += y_o - mat[1, 0] * x_o - mat[1, 1] * y_o - mat[1, 2] * z_o
off_z += z_o - mat[2, 0] * x_o - mat[2, 1] * y_o - mat[2, 2] * z_o
off_x = float(off_x)
off_y = float(off_y)
off_z = float(off_z)
newMap.fullMap = newMap.fullMap.swapaxes(0, 2)
newMap.fullMap = affine_transform(
newMap.fullMap,
mat,
offset=(off_x, off_y, off_z),
cval=self.min()
)
newMap.fullMap = newMap.fullMap.swapaxes(0, 2)
return newMap
def change_origin(self, x_origin, y_origin, z_origin):
""" Change the origin of the map.
Arguments:
x_origin, y_origin, z_origin: New origin co-ordinate.
Returns:
Map instance with new origin
"""
newMap = self.copy()
newMap.origin = (x_origin, y_origin, z_origin)
return newMap
def shift_origin(self, x_shift, y_shift, z_shift):
""" Shift the Map origin.
Arguments:
x_shift, y_shift, z_shift: Shift (in voxels) applied to origin in
respective plane.
Returns:
Map instance with new origin.
"""
newMap = self.copy()
newMap.origin = (
self.origin[0] + x_shift,
self.origin[1] + y_shift,
self.origin[2] + z_shift
)
return newMap
def translate(
self,
x,
y,
z,
):
""" Translate the map.
Args:
x, y, z: Translation (in A) applied to the map in respective plane.
Returns:
Shifted Map instance
"""
sh = np.array([
z / self.apix[2],
y / self.apix[1],
x / self.apix[0],
])
newMap = self.copy()
newMap.fullMap = shift(
newMap.fullMap,
sh,
cval=self.min()
)
return newMap
def origin_change_maps(self, MapRef):
""" Translate Map such that the origin is moved to the origin of a
reference Map.
Args:
MapRef: Reference Map
Returns:
Translated Map instance
"""
newMap = self.copy()
origin_shift = [
y - x for x, y in
zip(newMap.origin, MapRef.origin)
]
newMap.translate(
origin_shift[0],
origin_shift[1],
origin_shift[2],
)
newMap.origin = MapRef.origin[:]
return newMap
def threshold_map(self, minDens, maxDens):
"""Create a Map instance containing only density values between the
specified min and max values.
Args:
minDens: Minimum density threshold
maxDens: Maximum density threshold
Returns:
Thresholded Map instance
"""
newMap1 = self.fullMap.copy()
newMap1 = newMap1 * (newMap1 < maxDens) * (newMap1 > minDens)
newMap = self.copy()
newMap.fullMap = newMap1
return newMap
def _find_level(self, vol):
"""
Get the level corresponding to volume.
Arguments:
*vol*
volume within the contour
Returns:
level corresponding to volume
"""
c1 = self.fullMap.min()
vol_calc = float(vol) * 2
it = 0
flage = 0
while (vol_calc - float(vol)) / (self.apix.prod()) > 10 and flage == 0:
mask_array = self.fullMap >= c1
dens_freq, dens_bin = np.histogram(self.fullMap[mask_array], 1000)
sum_freq = 0.0
for i in range(len(dens_freq)):
sum_freq += dens_freq[-(i + 1)]
dens_level = dens_bin[-(i + 2)]
vol_calc = sum_freq*(self.apix.prod())
if vol_calc > float(vol):
sel_level = dens_level
it += 1
if sel_level <= c1:
flage = 1
c1 = sel_level
if it == 3:
flage = 1
break
return sel_level
def _rotate_interpolate_to_grid(
self,
mat,
gridshape,
spacing_i,
spacing_f,
cort,
fill=None,
origin=None
):
"""
rotate a map and interpolate to new grid.
Arguments:
*mat*
rotation matrix
*gridshape*
new grid shape (z,y,x)
*spacing_i*
initial grid spacing
*spacing_f*
new grid spacing
*cort*
centre of rotation
Returns:
level corresponding to volume
"""
nz = int(gridshape[0])
ny = int(gridshape[1])
nx = int(gridshape[2])
map_centre = self.centre()
if origin is None:
origin = (
map_centre.x - (nx * spacing_f) / 2.0,
map_centre.y - (ny * spacing_f) / 2.0,
map_centre.z - (nz * spacing_f) / 2.0,
)
orif = np.array(origin).view(float) # noqa:F841
orii = np.array(self.origin).view(float) # noqa:F841
nzi = int(self.fullMap.shape[0]) # noqa:F841
nyi = int(self.fullMap.shape[1]) # noqa:F841
nxi = int(self.fullMap.shape[2]) # noqa:F841
si = float(spacing_i) # noqa:F841
sf = float(spacing_f) # noqa:F841
cor = np.array(cort).astype(float) # noqa:F841
new_grid = np.zeros(gridshape, dtype=float)
if not fill == 0.0:
new_grid.fill(self.min())
maparray = self.fullMap.view(float) # noqa:F841
# rotation matrix transpose
matt = (np.array(mat).T).astype(float) # noqa:F841
# /*calculate offset*/
corfx = orif[0]+(nx*sf)/2.0
corfy = orif[1]+(ny*sf)/2.0
corfz = orif[2]+(nz*sf)/2.0
crx = matt[0, 0] * corfx + matt[0, 1] * corfy + matt[0, 2] * corfz
cry = matt[1, 0] * corfx + matt[1, 1] * corfy + matt[1, 2] * corfz
crz = matt[2, 0] * corfx + matt[2, 1] * corfy + matt[2, 2] * corfz
offx = cor[0] - crx
offy = cor[1] - cry
offz = cor[2] - crz
for z in range(nz):
for y in range(ny):
for x in range(nx):
# /*reverse rotation*/
xf = orif[0]+(sf/2.0)+x*sf
yf = orif[1]+(sf/2.0)+y*sf
zf = orif[2]+(sf/2.0)+z*sf
xi = matt[0, 0]*xf + matt[0, 1]*yf + matt[0, 2]*zf
yi = matt[1, 0]*xf + matt[1, 1]*yf + matt[1, 2]*zf
zi = matt[2, 0]*xf + matt[2, 1]*yf + matt[2, 2]*zf
# /*add offset*/
xi = xi + offx
yi = yi + offy
zi = zi + offz
# /*array coordinates*/
xi = (xi - (orii[0]+(si/2.0)))/si
yi = (yi - (orii[1]+(si/2.0)))/si
zi = (zi - (orii[2]+(si/2.0)))/si
# /*find bounds*/
x0 = np.floor(xi)
y0 = np.floor(yi)
z0 = np.floor(zi)
x1 = np.ceil(xi)
y1 = np.ceil(yi)
z1 = np.ceil(zi)
# noqa: E501 /*std::cout << xf << ' ' << xi << ' ' << x0 << ' ' << x1 << ' ' << offx << std::endl*/
if (
(x0 >= 0 and y0 >= 0 and z0 >= 0) and
(x1 < nxi and y1 < nyi and z1 < nzi)
):
ma000 = maparray[z0, y0, x0]
ma100 = maparray[z1, y0, x0]
ma010 = maparray[z0, y1, x0]
ma001 = maparray[z0, y0, x1]
ma110 = maparray[z1, y1, x0]
ma011 = maparray[z0, y1, x1]
ma101 = maparray[z1, y0, x1]
ma111 = maparray[z1, y1, x1]
new_grid[z, y, x] = ma000*(1-(xi-x0))*(1-(yi-y0))*(1-(zi-z0))+ma001*(xi-x0)*(1-(yi-y0))*(1-(zi-z0))+ma010*(1-(xi-x0))*(yi-y0)*(1-(zi-z0))+ma100*(1-(xi-x0))*(1-(yi-y0))*(zi-z0)+ma101*(xi-x0)*(1-(yi-y0))*(zi-z0)+ma110*(1-(xi-x0))*(yi-y0)*(zi-z0)+ma011*(xi-x0)*(yi-y0)*(1-(zi-z0))+ma111*(xi-x0)*(yi-y0)*(zi-z0) # noqa: E501
self.fullMap = new_grid
self.origin = origin
def _interpolate_to_grid( # noqa:F811
self,
gridshape,
s,
ori,
order_spline=3,
fill='min'
):
"""
Spline interpolation to a grid.
Arguments:
*gridshape*
shape of new grid array (z,y,x)
*s*
new grid spacing
*ori*
origin of the new grid
*order_spine*
order of the spline used for interpolation
Returns:
Interpolated map
"""
(ox, oy, oz) = (
self.origin[0],
self.origin[1],
self.origin[2],
)
(o1x, o1y, o1z) = (
float(ori[0]),
float(ori[1]),
float(ori[2])
)
scale = s / self.apix
offset = (o1x - ox, o1y - oy, o1z - oz)
new_map_origin = (o1x, o1y, o1z)
grid_indices = np.indices(gridshape)
z_ind = grid_indices[0]
z_ind.ravel()
y_ind = grid_indices[1]
y_ind.ravel()
x_ind = grid_indices[2]
x_ind.ravel()
z_ind = ((offset[2]) / self.apix[2]) + scale[2] * z_ind
y_ind = ((offset[1]) / self.apix[1]) + scale[1] * y_ind
x_ind = ((offset[0]) / self.apix[0]) + scale[0] * x_ind
if order_spline > 1:
filtered_array = spline_filter(self.fullMap, order=order_spline)
else:
filtered_array = self.fullMap
if fill == 'zero':
fillval = 0.0
else:
fillval = self.min()
new_array = map_coordinates(
filtered_array,
[z_ind, y_ind, x_ind],
cval=fillval,
order=order_spline,
prefilter=False,
)
new_map = Map(
new_array.reshape(gridshape),
new_map_origin,
s,
self.filename,
self.header[:],
)
new_map.origin = np.array([o1x, o1y, o1z], dtype=np.float32)
new_map.apix = s
return new_map
def _interpolate_to_grid1(
self,
gridshape,
s,
ori,
fill='min',
bound=False,
):
"""
Spline interpolation to a grid.
Arguments:
*gridshape*
shape of new grid array (z,y,x)
*s*
new grid spacing
*ori*
origin of the new grid
*order_spine*
order of the spline used for interpolation
Returns:
interpolated map
"""
(ox, oy, oz) = (
self.origin[0],
self.origin[1],
self.origin[2],
)
(o1x, o1y, o1z) = (
float(ori[0]),
float(ori[1]),
float(ori[2]),
)
scale = s / self.apix
offset = (o1x - ox, o1y - oy, o1z - oz)
new_map_origin = (o1x, o1y, o1z)
# axis coordinates of new grid
z_ind = np.arange(gridshape[0])
y_ind = np.arange(gridshape[1])
x_ind = np.arange(gridshape[2])
# find coordinates relative to old grid
z_ind = ((offset[2]) / self.apix[2]) + scale[2] * z_ind
y_ind = ((offset[1]) / self.apix[1]) + scale[1] * y_ind
x_ind = ((offset[0]) / self.apix[0]) + scale[0] * x_ind
# get indices of points inside the old grid
z_mask_ind = (((np.nonzero((z_ind >= 0) & (z_ind < self.fullMap.shape[0] - 1))[0]) * 1).astype(int)) # noqa:E501
y_mask_ind = ((np.nonzero((y_ind >= 0) & (y_ind < self.fullMap.shape[1]-1))[0])*1).astype(int) # noqa:E501
x_mask_ind = ((np.nonzero((x_ind >= 0) & (x_ind < self.fullMap.shape[2]-1))[0])*1).astype(int) # noqa:E501
# indices of boundaries
z_mask_ind1 = np.nonzero(
(z_ind >= self.fullMap.shape[0]-1) &
(z_ind < self.fullMap.shape[0])
)[0]
y_mask_ind1 = np.nonzero(
(y_ind >= self.fullMap.shape[1]-1) &
(y_ind < self.fullMap.shape[1])
)[0]
x_mask_ind1 = np.nonzero(
(x_ind >= self.fullMap.shape[2]-1) &
(x_ind < self.fullMap.shape[2])
)[0]
z_mask_ind0 = np.nonzero(
(z_ind < 0) & (z_ind > -1)
)[0]
y_mask_ind0 = np.nonzero(
(y_ind < 0) & (y_ind > -1)
)[0]
x_mask_ind0 = np.nonzero(
(x_ind < 0) & (x_ind > -1)
)[0]
# searchsorted/floor
# get the bound int coordinates
# searchsorted gives right bounds of orig array. substract 1 to get
# lower bound
k_z = np.searchsorted(
np.arange(self.fullMap.shape[0], dtype=float),
z_ind - 1,
side='right',
)
k_y = np.searchsorted(
np.arange(self.fullMap.shape[1], dtype=float),
y_ind - 1,
side='right',
)
k_x = np.searchsorted(
np.arange(self.fullMap.shape[2], dtype=float),
x_ind - 1,
side='right',
)
# new_grid
new_grid = np.zeros((gridshape))
# extract lower bounds from original grid
# check coordinate range
x_grid1 = k_x[x_mask_ind].astype(int)
y_grid1 = k_y[y_mask_ind].astype(int)
z_grid1 = k_z[z_mask_ind].astype(int)
# faster option (array broadcasting - operations on different sizes)
# indices from orig array
tmp_grid = np.zeros(
(
len(z_grid1),
len(y_grid1),
len(x_grid1)
),
dtype=int,
)
z_gridL = (tmp_grid + z_grid1[..., np.newaxis, np.newaxis]).flatten()
y_gridL = (tmp_grid + y_grid1[..., np.newaxis]).flatten()
x_gridL = (tmp_grid + x_grid1).flatten()
assert (
len(z_grid1) == len(z_mask_ind) and
len(y_grid1) == len(y_mask_ind) and
len(x_grid1) == len(x_mask_ind)
)
# target array indices
z_grid = (tmp_grid + z_mask_ind[..., np.newaxis, np.newaxis]).flatten()
y_grid = (tmp_grid + y_mask_ind[..., np.newaxis]).flatten()
x_grid = (tmp_grid + x_mask_ind).flatten()
# fill with minimum value/zero
if not fill == 'zero':
new_grid.fill(self.min())
# interpolate
nx = int(len(x_grid1)) # noqa:F841
ny = int(len(y_grid1)) # noqa:F841
nz = int(len(z_grid1)) # noqa:F841
maparray = self.fullMap.view(float) # noqa:F841
xind = x_ind.view(float) # noqa:F841
yind = y_ind.view(float) # noqa:F841
zind = z_ind.view(float) # noqa:F841
# int k,j,i;
# int k1,j1,i1;
# for z in range(nz):
# for y in range(ny):
# for x in range(nx):
# k1 = z_grid1[z]
# j1 = y_grid1[y]
# i1 = x_grid1[x]
# k = z_mask_ind[z]
# j = y_mask_ind[y]
# i = x_mask_ind[x]
# float ma000 = maparray[k1,j1,i1]
# float ma100 = maparray[k1+1,j1,i1]
# float ma010 = maparray[k1,j1+1,i1]
# float ma001 = maparray[k1,j1,i1+1]
# float ma110 = maparray[k1+1,j1+1,i1]
# float ma011 = maparray[k1,j1+1,i1+1]
# float ma101 = maparray[k1+1,j1,i1+1]
# float ma111 = maparray[k1+1,j1+1,i1+1]
# float indx = xind[i];
# float indy = yind[j];
# float indz = zind[k];
# noqa: E501 new_grid[k,j,i] = ma000* (1-(indx-i1))* (1-(indy-j1))* (1-(indz-k1)) +ma001*(indx-i1)*(1-(indy-j1))*(1-(indz-k1))+ma010*(1-(indx-i1))*(indy-j1)*(1-(indz-k1))+ma100*(1-(indx-i1))*(1-(indy-j1))*(indz-k1)+ma101*(indx-i1)*(1-(indy-j1))*(indz-k1)+ma110*(1-(indx-i1))*(indy-j1)*(indz-k1)+ma011*(indx-i1)*(indy-j1)*(1-(indz-k1))+ma111*(indx-i1)*(indy-j1)*(indz-k1);
new_grid[z_grid, y_grid, x_grid] = (1.-(x_ind[x_grid]-x_gridL))*(1-(y_ind[y_grid]-y_gridL))*(1-(z_ind[z_grid]-z_gridL))*self.fullMap[z_gridL, y_gridL, x_gridL]+self.fullMap[z_gridL, y_gridL, x_gridL+1]*(x_ind[x_grid]-x_gridL)*(1-(y_ind[y_grid]-y_gridL))*(1-(z_ind[z_grid]-z_gridL))+self.fullMap[z_gridL, y_gridL+1, x_gridL]*(1.-(x_ind[x_grid]-x_gridL))*(y_ind[y_grid]-y_gridL)*(1-(z_ind[z_grid]-z_gridL))+self.fullMap[z_gridL+1, y_gridL, x_gridL]*(1.-(x_ind[x_grid]-x_gridL))*(1-(y_ind[y_grid]-y_gridL))*(z_ind[z_grid]-z_gridL)+self.fullMap[z_gridL+1, y_gridL, x_gridL+1]*(x_ind[x_grid]-x_gridL)*(1-(y_ind[y_grid]-y_gridL))*(z_ind[z_grid]-z_gridL)+self.fullMap[z_gridL+1, y_gridL+1, x_gridL]*(1.-(x_ind[x_grid]-x_gridL))*(y_ind[y_grid]-y_gridL)*(z_ind[z_grid]-z_gridL)+self.fullMap[z_gridL, y_gridL+1, x_gridL+1]*(x_ind[x_grid]-x_gridL)*(y_ind[y_grid]-y_gridL)*(1-(z_ind[z_grid]-z_gridL))+self.fullMap[z_gridL+1, y_gridL+1, x_gridL+1]*(x_ind[x_grid]-x_gridL)*(y_ind[y_grid]-y_gridL)*(z_ind[z_grid]-z_gridL) # noqa:E501
if bound is True:
# note that the boundary interpolations are done just along one
# axis - to save time - not accurate
# boundary interpolations
for el in x_mask_ind1:
new_grid[z_grid, y_grid, el] = (
(1 - (x_ind[el] - k_x[el])) *
self.fullMap[z_gridL, y_gridL, k_x[el]] +
(x_ind[el] - k_x[el]) *
self.min()
)
for el in y_mask_ind1:
new_grid[z_grid, el, x_grid] = (
(1-(y_ind[el]-k_y[el])) *
self.fullMap[z_gridL, k_y[el], x_gridL] +
(y_ind[el] - k_y[el]) * self.min()
)
for el in z_mask_ind1:
new_grid[el, y_grid, x_grid] = (
(1 - (z_ind[el] - k_z[el])) *
self.fullMap[k_z[el], y_gridL, x_gridL] +
(z_ind[el] - k_z[el]) * self.min()
)
k_x[x_mask_ind0] = -1.
k_y[y_mask_ind0] = -1.
k_z[z_mask_ind0] = -1.
for el in x_mask_ind0:
new_grid[z_grid, y_grid, el] = (
(1 - (x_ind[el] - (-1))) *
self.min() +
(x_ind[el] - (-1)) *
self.fullMap[z_gridL, y_gridL, 0]
)
for el in y_mask_ind0:
new_grid[z_grid, el, x_grid] = (
(1 - (y_ind[el] - (-1))) *
self.min() +
(y_ind[el] - (-1)) *
self.fullMap[z_gridL, 0, x_gridL]
)
for el in z_mask_ind0:
new_grid[el, y_grid, x_grid] = (
(1-(z_ind[el]-(-1))) *
self.min() +
(z_ind[el] - (-1)) *
self.fullMap[0, y_gridL, x_gridL]
)
# interpolate
new_map = Map(
new_grid,
new_map_origin,
s,
self.filename,
self.header[:]
)
new_map.origin = (o1x, o1y, o1z)
new_map.apix = s
return new_map
# TODO: this code gives an error when called as it stands,
# so there must be some inconsistency in it. To be checked
def _check_overlap(
c1,
c2,
mat,
cor,
maxG
):
"""
Check whether transformation of a map overlaps with another.
Note that for maps with large differences in x,y,z dimensions,
some non-overlapping boxes may be returned but this is quick way
to check for overlap without using the grids.
Arguments:
*c1*
box centre of map1
*c2*
box centre of map2
*mat*
transformation matrix
*cor*
centre of rotation
*maxG*
maximum of the dimensions of the maps, in Angstrom
Returns:
True/False
"""
mat1 = np.matrix([
[c2[0]],
[c2[1]],
[c2[2]],
])
mat2 = np.matrix([
mat[0][:-1],
mat[1][:-1],
mat[2][:-1]
])
c2_t = mat2 * mat1
c2_t[0] = c2_t[0] + mat[0][-1] + (float(cor[0]) - c2_t[0])
c2_t[1] = c2_t[1] + mat[1][-1] + (float(cor[1]) - c2_t[1])
c2_t[2] = c2_t[2] + mat[2][-1] + (float(cor[2]) - c2_t[2])
dist = math.sqrt(
math.pow(c2_t[0] - c1[0], 2) +
math.pow(c2_t[1] - c1[1], 2) +
math.pow(c2_t[2] - c1[2], 2)
)
if dist < maxG / 2.0:
return True
else:
return False
def _mask_contour(self, thr, mar=0.0):
"""
Mask backgound beyond contour (in place)
"""
if mar != 0.0: # TODO: NEVER CHECK FOR EQUALITY WITH FLOATS
level = thr - (mar * self.fullMap.std())
else:
level = thr
minVal = self.min()
a = np.ma.masked_less(self.fullMap, level, copy=True)
self.fullMap = np.ma.filled(a, minVal)
def _make_fourier_shell(self, fill=1.0):
"""
For a given grid, make a grid with sampling frequencies as distance
from centre
Returns:
grid with sampling frequencies
"""
rad_z = (
np.arange(
np.floor(self.z_size() / 2.0) * -1,
np.ceil(self.z_size() / 2.0)
) / float(np.floor(self.z_size()))
)
rad_y = (
np.arange(
np.floor(self.y_size() / 2.0) * -1,
np.ceil(self.y_size()/2.0)
) / float(np.floor(self.y_size()))
)
rad_x = (
np.arange(
np.floor(self.x_size()/2.0) * -1,
np.ceil(self.x_size()/2.0)
) / float(np.floor(self.x_size()))
)
rad_x = rad_x**2
rad_y = rad_y**2
rad_z = rad_z**2
dist = np.sqrt(rad_z[:, None, None] + rad_y[:, None] + rad_x)
return dist
def _get_maskArray(self, densValue):
"""
ADDED by APP to use with SSCCC score
"""
mask_array = np.ma.masked_less_equal(self.fullMap, densValue)
return np.ma.getmask(mask_array)
def _get_maskMap(self, maskArray):
"""
ADDED by APP to use with SSCCC score
"""
newMap = self.copy()
newMap.fullMap *= 0
masked_newMAP = np.ma.masked_array(
self.fullMap,
mask=maskArray,
fill_value=0
)
newMap.fullMap = masked_newMAP.filled()
return newMap
def make_bin_map(self, cutoff):
""" Make a binarised version of Map, where values above cutoff = 1 and
below cutoff = 0.
Args:
cutoff: Cutoff density value
Returns:
Binarised Map instance
"""
# TODO: get rid of the copy here
binMap = self.copy()
binMap.fullMap = (self.fullMap > float(cutoff)) * -1
return binMap
def _make_clash_map(self, apix=np.ones(3)):
"""
NOTE: NEEED TO BE CHECKED.
Return an empty Map instance with set Angstrom per pixel sampling
(default is 1)
Returns:
new Map instance
"""
grid = np.zeros(
(
int(self.box_size()[0] * self.apix[0] / apix[0]),
int(self.box_size()[1] * self.apix[1] / apix[1]),
int(self.box_size()[2] * self.apix[2] / apix[2])
)
)
clashMap = self.copy()
clashMap.fullMap = grid
clashMap.apix = apix
return clashMap
def resample_by_apix(self, new_apix):
""" Resample the map to a new pixel size.
Args:
new_apix: New Angstrom per pixel sampling
Returns:
Resampled Map instance
"""
new_map = self.copy()
apix_ratio = self.apix/new_apix
new_map.fullMap = resample(
new_map.fullMap,
self.z_size() * apix_ratio[2],
axis=0
)
new_map.fullMap = resample(
new_map.fullMap,
self.y_size() * apix_ratio[1],
axis=1
)
new_map.fullMap = resample(
new_map.fullMap,
self.x_size() * apix_ratio[0],
axis=2
)
new_map.apix = (self.apix * self.box_size()) / new_map.box_size()
return new_map
def resample_by_box_size(self, new_box_size):
""" Resample the map based on new box size.
Args:
new_box_size: New box dimensions in (Z, Y, X) format
Returns:
Resampled Map instance
"""
new_map = self.copy()
new_map.fullMap = resample(new_map.fullMap, new_box_size[0], axis=0)
new_map.fullMap = resample(new_map.fullMap, new_box_size[1], axis=1)
new_map.fullMap = resample(new_map.fullMap, new_box_size[2], axis=2)
new_map.apix = (self.apix * self.box_size()[2]) / new_box_size[2]
return new_map
def fourier_transform(self):
""" Apply Fourier transform on the density map.
The zero frequency component is in the centre of the spectrum.
Returns:
Fourier Transformed Map instance.
"""
new_map = self.copy()
new_map.fullMap = fftshift(fftn(self.fullMap))
return new_map
def laplace_filtered(self):
""" Laplacian filter Map.
Returns:
Laplacian filtered Map instance
"""
new_map = self.copy()
new_map.fullMap = laplace(self.fullMap)
return new_map
def get_vectors(self):
""" Retrieve all non-zero density points as Vector instances.
Returns:
Numpy array:
An array of 2-tuple (
:class:`Vector Instance <TEMPy.math.vector.Vector>` with
respect to origin, and density value)
"""
a = []
for z in range(len(self.fullMap)):
for y in range(len(self.fullMap[z])):
for x in range(len(self.fullMap[z][y])):
if self.fullMap[z][y][x] != 0:
a.append(
(
Vector.Vector(
(x * self.apix[0]) + self.origin[0],
(y * self.apix[1]) + self.origin[1],
(z * self.apix[2]) + self.origin[2],
),
self.fullMap[z][y][x]
)
)
return np.array(a)
def get_line_between_points(self, point1, point2):
"""Return an array of float values representing a line of density values
between two points on the map.
Args:
point1, point2: Vector instances defining one of the line to
extract density values.
Returns:
Numpy array:
Array of density values along the defined line.
"""
v1 = point1.minus(
Vector.Vector(
self.origin[0],
self.origin[1],
self.origin[2],
)
).times(1.0 / self.apix)
v2 = point2.minus(
Vector.Vector(
self.origin[0],
self.origin[1],
self.origin[2],
)
).times(1.0 / self.apix)
v3 = v2.minus(v1)
noOfPoints = int(round(2 * v3.mod() / self.apix))
points = []
for x in range(0, noOfPoints+1):
p = v1.plus(v3.times(float(x) / noOfPoints))
points.append(self.fullMap[p.z][p.y][p.x])
return np.array(points)
def _get_com_threshold(self, c):
"""
Return Vector instance of the centre of mass of the map.
"""
newmap = self.copy()
binmap = self.fullMap > float(c)
newmap.fullMap = binmap * self.fullMap
total_x_moment = 0.0
total_y_moment = 0.0
total_z_moment = 0.0
total_mass = 0.0
min_mass = newmap.min()
vectorMap = np.argwhere(newmap.fullMap)
for v in vectorMap:
m = newmap.fullMap[v[0]][v[1]][v[2]] + min_mass
total_mass += m
total_x_moment += m * (self.origin[0] + v[2] * self.apix[0])
total_y_moment += m * (self.origin[1] + v[1] * self.apix[1])
total_z_moment += m * (self.origin[2] + v[0] * self.apix[2])
x_CoM = total_x_moment / total_mass
y_CoM = total_y_moment / total_mass
z_CoM = total_z_moment / total_mass
return Vector.Vector(x_CoM, y_CoM, z_CoM)
def get_com(self):
"""
Returns:
the centre of mass as a
:class:`Vector instance <TEMPy.math.vector.Vector>`
"""
total_x_moment = 0.0
total_y_moment = 0.0
total_z_moment = 0.0
total_mass = 0.0
min_mass = self.min()
vectorMap = self.get_vectors()
for v in vectorMap:
m = v[1] + min_mass
total_mass += m
total_x_moment += m * v[0].x
total_y_moment += m * v[0].y
total_z_moment += m * v[0].z
x_CoM = total_x_moment / total_mass
y_CoM = total_y_moment / total_mass
z_CoM = total_z_moment / total_mass
return Vector.Vector(x_CoM, y_CoM, z_CoM)
def pixel_centre(self):
"""
Returns:
:class:`Vector instance <TEMPy.math.vector.Vector>` of the centre
of the map in pixels.
"""
x_centre = self.x_size() / 2
y_centre = self.y_size() / 2
z_centre = self.z_size() / 2
return Vector.Vector(x_centre, y_centre, z_centre)
def centre(self):
"""
Returns:
:class:`Vector instance <TEMPy.math.vector.Vector>` of the centre
of the map in Angstroms.
"""
x_centre = self.origin[0] + (self.apix[0] * self.x_size() / 2)
y_centre = self.origin[1] + (self.apix[1] * self.y_size() / 2)
z_centre = self.origin[2] + (self.apix[2] * self.z_size() / 2)
return Vector.Vector(x_centre, y_centre, z_centre)
def mean(self):
"""
Returns:
Mean density value of map.
"""
return self.fullMap.mean()
def median(self):
"""
Returns:
Median density value of map.
"""
return np.median(self.fullMap)
def std(self):
"""
Returns:
Standard deviation of density values in map.
"""
return self.fullMap.std()
def min(self):
"""
Returns:
Minimum density value of the map.
"""
return self.fullMap.min()
def max(self):
"""
Returns:
Maximum density value of the map.
"""
return self.fullMap.max()
def vectorise_point(
self,
x,
y,
z
):
"""Get a Vector instance for a specific voxel coordinate (index) of the
map.
Args:
x, y, z: Co-ordinate of the density point to be vectorised.
Returns:
:class:`Vector instance <TEMPy.math.vector.Vector>` for the point,
in angstrom units, relative to the origin.
"""
v_x = (self.apix[0] * x) + self.origin[0]
v_y = (self.apix[1] * y) + self.origin[1]
v_z = (self.apix[2] * z) + self.origin[2]
return Vector.Vector(v_x, v_y, v_z)
def get_significant_points(self):
""" Retrieve all points with a density greater than one standard
deviation above the mean.
Returns:
Numpy array:
An array of 4-tuple (indices of the voxels in z, y, x format
and density value)
"""
sig_points = []
boo = self.fullMap > (self.fullMap.mean() + self.fullMap.std())
for z in range(self.z_size()):
for y in range(self.y_size()):
for x in range(self.x_size()):
if boo[z][y][x]:
sig_points.append(
np.array([z, y, x, self.fullMap[z][y][x]])
)
return np.array(sig_points)
def _get_random_significant_pairs(self, amount):
"""
Return an array of tuple pairs of significant points randomly chosen
from 'get_significant_points' function.
For use with the DCCF and DLSF scoring functions.
Arguments:
*amount*
number of significant point pairs to return.
"""
sig_points = self.get_significant_points()
sig_pairs = []
size = len(sig_points)
for r in range(amount):
fst = sig_points[randrange(size)]
snd = sig_points[randrange(size)]
new_value = np.array(
[
fst[0],
fst[1],
fst[2],
snd[0],
snd[1],
snd[2],
fst[3] - snd[3],
]
)
sig_pairs.append(new_value)
return np.array(sig_pairs)
def makeKDTree(self, minDens, maxDens):
""" Make a k-dimensional tree for points in the Map within specified
density thresholds.
The KD-Tree can be used for quick nearest neighbour look-ups.
Args:
minDens: Minimum density value to include in k-dimensional tree.
maxDens: Maximum density value to include in k-dimensional tree.
Returns:
Scipy KDTree containing all relevant points.
"""
maplist = self.get_pos(minDens, maxDens)
if len(maplist) != 0:
return KDTree(maplist)
def get_pos(self, minDens, maxDens):
"""Find the index for all voxels in the Map whose density values fall
within the specified thresholds.
Args:
minDens: Minimum density threshold.
maxDens: Maximum density threshold.
Returns:
An array of 3-tuples (indices of the voxels in x,y,z format)
"""
a = []
for z in range(len(self.fullMap)):
for y in range(len(self.fullMap[z])):
for x in range(len(self.fullMap[z][y])):
if (
(self.fullMap[z][y][x] > minDens) and
(self.fullMap[z][y][x] < maxDens)
):
a.append((x, y, z))
return np.array(a)
def _get_normal_vector(self, points):
arr = points.view(int) # noqa:F841
vecnorm = np.zeros((len(points), 3), dtype=float)
nps = len(points) # noqa:F841
xsize = int(self.x_size()) # noqa:F841
ysize = int(self.y_size()) # noqa:F841
zsize = int(self.z_size()) # noqa:F841
mat = self.fullMap.view(float) # noqa:F841
for v in range(len(points)):
x = arr[v, 2]
y = arr[v, 1]
z = arr[v, 0]
xa = ya = za = 0.0
flag = 0
for i in range(x-1, x+2):
for j in range(y-1, y+2):
for k in range(z-1, z+2):
if (i == x) and (j == y) and (z == k):
continue
elif (i < 0) or (j < 0) or (k < 0):
continue
elif (i > xsize-1) or (j > ysize-1) or (k > zsize-1):
continue
else:
if mat[k, j, i] > mat[z, y, x]:
# sum of unit vectors
mod = math.sqrt((i-x)**2+(j-y)**2+(k-z)**2)
if mod != 0.0:
xa += (i-x)/mod
ya += (j-y)/mod
za += (k-z)/mod
flag = 1
elif mat[k, j, i] < mat[z, y, x]:
flag = 1
if flag != 0:
# unit average
mod = math.sqrt(xa**2+ya**2+za**2)
if mod != 0.0:
vecnorm[v, 0] = xa/mod
vecnorm[v, 1] = ya/mod
vecnorm[v, 2] = za/mod
else:
vecnorm[v, 0] = 0.0
vecnorm[v, 1] = 0.0
vecnorm[v, 2] = 0.0
return vecnorm
def get_normal_vector(
self,
x_pos,
y_pos,
z_pos,
):
"""Calculate the normal vector at the point specified.
Point calculated using 3SOM algorithm used by Ceulemans H. & Russell
R.B. (2004).
Args:
x_pos, y_pos, z_pos: Voxel in map on which to calculate normal
vector.
Returns:
:class:`Vector instance <TEMPy.math.vector.Vector>`:
The Normal vector at the point specified.
"""
flag = 0
internal_vecs = []
for x in range(x_pos - 1, x_pos + 2):
for y in range(y_pos - 1, y_pos + 2):
for z in range(z_pos - 1, z_pos + 2):
if (x_pos, y_pos, z_pos) == (x, y, z):
pass
elif x < 0 or y < 0 or z < 0:
pass
elif (
x > self.x_size()-1 or
y > self.y_size()-1 or
z > self.z_size()-1
):
pass
else:
if (
self.fullMap[z][y][x] >
self.fullMap[z_pos][y_pos][x_pos]
):
internal_vecs.append(
Vector.Vector(
x - x_pos,
y - y_pos,
z - z_pos
).unit()
)
flag = 1
elif (
self.fullMap[z][y][x] <
self.fullMap[z_pos][y_pos][x_pos]
):
flag = 1
sub_vector = Vector.Vector(0, 0, 0)
for v in internal_vecs:
sub_vector = sub_vector + v
if len(internal_vecs) == 0 and flag == 0:
return Vector.Vector(-9.0, -9.0, -9.0)
return sub_vector.unit()
def represent_normal_vectors(self, min_threshold, max_threshold):
""" Create a Structure instance representing normal vectors of density
points specified.
Args:
min_threshold, max_threshold: Minimum/maximum values to include
in normal vector representation.
Returns:
Structure Instance
"""
atomList = []
template = 'HETATM 1 C NOR A 1 23.161 39.732 -25.038 1.00 10.00 C' # noqa:E501
m = self.copy()
print(m.origin)
for x in range(1, (m.box_size()[0]-1)):
for y in range(1, (m.box_size()[1]-1)):
for z in range(1, (m.box_size()[2]-1)):
if (
m.fullMap[z][y][x] > min_threshold and
m.fullMap[z][y][x] < max_threshold
):
n_vec = m.get_normal_vector(x, y, z)
n_vec = n_vec.unit()
pos_vec = Vector.Vector(
(x * m.apix[0]) + m.origin[0],
(y * m.apix[1]) + m.origin[1],
(z * m.apix[2]) + m.origin[2],
)
a = template.BioPyAtom()
a.x = pos_vec.x
a.y = pos_vec.y
a.z = pos_vec.z
b = BioPyAtom(template)
b.x = pos_vec.x + n_vec.x
b.y = pos_vec.y + n_vec.y
b.z = pos_vec.z + n_vec.z
c = BioPyAtom(template)
c.x = pos_vec.x + 2 * n_vec.x
c.y = pos_vec.y + 2 * n_vec.y
c.z = pos_vec.z + 2 * n_vec.z
atomList.append(a)
atomList.append(b)
atomList.append(c)
try:
s = BioPy_Structure(atomList)
except ZeroDivisionError:
return atomList
s.renumber_atoms()
return s
def get_point_map(self, min_thr, percentage=0.2):
""" Calculates the amount of points to use for the
:meth:`Normal vector score <TEMPy.protein.scoring_functions.ScoringFunctions.normal_vector_score>`
and :meth:`Chamfer distance <TEMPy.protein.scoring_functions.ScoringFunctions.chamfer_distance>`
score.
Minimum number of returned points is 100.
Arguments:
min_thr: Minimum threshold, recommended to get value by running
the :meth:`get_primary_boundary <TEMPy.maps.em_map.Mapget_primary_boundary>`
on target map.
percentage: Percentage of the protein volume.
Returns:
Number of points for Chamfer and Normal Vector scores.
"""
new_map = self.copy()
prot_size = 1. * (new_map.fullMap > min_thr).sum()
points = max(100, round(prot_size * percentage))
return points
def get_primary_boundary(
self,
molWeight,
low,
high,
vol_factor=1.21,
):
"""Estimates a threshold value to create an envelope that encapsulates
a volume expected for a protein with a certain molecular size.
The estimation uses a recursive algorithm, so some parameters can be
set as approximate guesses.
NOTE: when used to calculated the NV score this value should be
calculated for the experimental map.
Args:
molWeight: molecular weight of all molecules in model. Can be
calculated using
:meth:`get_prot_mass_from_atoms <TEMPy.protein.prot_rep_biopy.get_prot_mass_from_atoms>`.
low: Minimum threshold to consider. Can be a crude first guess
e.g. :meth:`Map.min <TEMPy.maps.em_map.Map.min`
high: Minimum threshold to consider. Can be a crude first guess
e.g. :meth:`Map.min <TEMPy.maps.em_map.Map.min`
vol_factor: Approximate value for cubic Angstroms per Dalton for
globular proteins. Value used in Chimera
(Petterson et al, 2004), taken from Harpaz 1994, is 1.21.
Other recommended volume factor are 1.5 (1.1-1.9) cubic
Angstroms per Dalton in EMAN Volume/mass conversions assume a
density of 1.35 g/ml (0.81 Da/A3) (~1.23A3/Da)
Returns:
float:
Primary boundary density value
"""
new_map = self.copy()
if np.sum(new_map.fullMap == low) > new_map.fullMap.size / 10:
all_dens = new_map.fullMap.flatten()
all_dens = set(all_dens)
all_dens = sorted(all_dens)
l_ind = all_dens.index(low)
low = all_dens[l_ind+1]
if high - low < 0.0000002 or high < low:
est_weight = int(
np.sum(new_map.fullMap > low) *
new_map.apix.prod() /
(vol_factor * 1000)
)
print(
'Exact molecular weight cannot be found. Approx. weight of '
+ str(est_weight) + ' used instead.'
)
return low
thr = low + (high - low) / 2
this_weight = int(
np.sum(new_map.fullMap > thr) *
new_map.apix.prod() /
(vol_factor * 1000)
)
if this_weight == int(molWeight):
return thr
elif this_weight > molWeight:
return new_map.get_primary_boundary(molWeight, thr, high)
elif this_weight < molWeight:
return new_map.get_primary_boundary(molWeight, low, thr)
def _get_second_boundary_outward(
self,
primary_boundary,
noOfPoints,
low,
high,
err_percent=1,
):
"""
PRIVATE FUNCTION to calculate the second bound density value.
Searching from primary boundary outward.
For a given boundary value, it calculates the second bound density
value such that a specified number of points whose density values fall
between the defined boundaries. Uses recursive algorithm.
Arguments:
*primary_boundary*
primary threshold, normally given by get_primary_boundary method
based on protein molecular weight.
*noOfPoints*
Number of points to use in the normal vector score - try
first with 10% (maybe 5%better) of the number of points in the
map ( round((self.map_size())*0.1)
*low, high*
minimum and maximum values between which the threshold will be
taken. low should be equal to the value returned by the
get_primary_boundary() method and high is the maximum density
values in map.
*err_percent*
default value of 1. Allowed to find a secondary boundary that
includes a 1% error.
Returns:
outward secondary boundary density value
"""
if high - low < 0.0000002 or high < low:
print(
'Non optimal number of pixels to match. Try changing this '
'value or increasing the size of err_percent '
)
return 1j
thr = low + (high - low) / 2
this_no_of_points = np.sum(
(self.fullMap < thr) * (self.fullMap > primary_boundary)
)
if abs(this_no_of_points - noOfPoints) < err_percent * noOfPoints/100.:
return thr
elif this_no_of_points < noOfPoints:
return self._get_second_boundary_outward(
primary_boundary,
noOfPoints,
thr,
high
)
elif this_no_of_points > noOfPoints:
return self._get_second_boundary_outward(
primary_boundary,
noOfPoints,
low,
thr,
)
def _get_second_boundary_inward(
self,
primary_boundary,
noOfPoints,
low,
high,
err_percent=1
):
"""
PRIVATE FUNCTION to calculate the second bound density value.
Searching from primary boundary inward.
For a given boundary value, it calculates the second bound density
value such that a specified number of points whose density values fall
between the defined boundaries. Uses recursive algorithm.
Arguments:
*primary_boundary*
primary threshold, normally given by get_primary_boundary
method based on protein molecular weight.
*noOfPoints*
Number of points to use in the normal vector score - try first
with 10% (maybe 5%better) of the number of points in the map
( round((self.map_size())*0.1)
*low, high*
minimum and maximum values between which the threshold will be
taken. low should be equal to the value returned by the
get_primary_boundary() method and high is the maximum density
values in map.
*err_percent*
default value of 1. Allowed to find a secondary boundary that
includes a 1% error.
Returns:
outward secondary boundary density value
"""
if high - low < 0.0000002 or high < low:
print(
'Non optimal number of pixels to match. Try changing this'
'value or increasing the size of err_percent '
)
return 1j
thr = high - (high - low) / 2
this_no_of_points = np.sum(
(self.fullMap < thr) * (self.fullMap > primary_boundary)
)
if abs(this_no_of_points - noOfPoints) < err_percent * noOfPoints/100.:
return thr
elif this_no_of_points < noOfPoints:
return self._get_second_boundary_inward(
primary_boundary,
noOfPoints,
thr,
high,
)
elif this_no_of_points > noOfPoints:
return self._get_second_boundary_inward(
primary_boundary,
noOfPoints,
low,
thr,
)
def get_second_boundary(
self,
primary_boundary,
noOfPoints,
low,
high,
err_percent=1,
):
"""
Calculate the second bound density value. For a given boundary value,
it calculates the second bound density value such that a specified
number of points whose density values fall between the defined
boundaries. Uses recursive algorithm.
Arguments:
*primary_boundary*
primary threshold, normally given by get_primary_boundary
method based on protein molecular weight.
*noOfPoints*
Number of points to use in the normal vector score - try
first with 10% (maybe 5%better) of the number of points in
the map ( round((self.map_size())*0.1)
*low, high*
minimum and maximum values between which the threshold will be
taken.
low should be equal to the value returned by the
get_primary_boundary() method and high is the maximum density
values in map.
*err_percent*
default value of 1. Allowed to find a secondary boundary that
includes a 1% error.
Returns:
secondary boundary density value
"""
bou = self._get_second_boundary_outward(
primary_boundary,
noOfPoints,
low,
high,
err_percent,
)
if bou == 1j:
bou = self._get_second_boundary_inward(
primary_boundary,
noOfPoints,
low,
high,
err_percent,
)
return bou
def _shrink_map(self, sd=2.):
pass
def _write_to_xplor_file(self, xplorFileName):
"""
OBSOLETE PRIVATE FUNCTION
xplorFileName = name of file to write to. Note that this function
does not automatically append a .xplor suffix.
"""
xplor = '\n 1 !NTITLE\n'
xplor += 'REMARKS '+'"' + xplorFileName + '"' + ' written by ME!\n'
xplor += (
self._pad_grid_line_no(self.z_size()) +
self._pad_grid_line_no(0) +
self._pad_grid_line_no(self.z_size()-1) +
self._pad_grid_line_no(self.y_size()) +
self._pad_grid_line_no(0) +
self._pad_grid_line_no(self.y_size()-1) +
self._pad_grid_line_no(self.x_size()) +
self._pad_grid_line_no(0) +
self._pad_grid_line_no(self.x_size()-1) + '\n'
)
xplor += (
self._convert_point_to_string(self.apix[2] * self.z_size()) +
self._convert_point_to_string(self.apix[1] * self.y_size()) +
self._convert_point_to_string(self.apix[0] * self.x_size())
)
xplor += (
self._convert_point_to_string(90.0) +
self._convert_point_to_string(90.0) +
self._convert_point_to_string(90.0) + '\n'
)
xplor += 'ZYX\n'
flatList = self.fullMap.flatten()
blockSize = self.z_size() * self.y_size()
blockNo = 0
offset = 0
for point in range(len(flatList)):
if point - offset % 6 == 0 and point % blockSize != 0:
xplor += '\n'
if point % blockSize == 0:
xplor += '\n' + self._pad_grid_line_no(blockNo) + '\n'
blockNo += 1
offset = point % 6
xplor += self._convert_point_to_string(np.real(flatList[point]))
xplor += '\n -9999'
f = open(xplorFileName, 'w')
f.write(xplor)
f.close()
def _write_to_situs_file(self, situsFileName):
"""
One day I will do this.
"""
pass
def old_write_to_MRC_file(self, mrcfilename, imod=False):
""" Write out Map instance as an MRC file
Old implementation that uses Python write(filename, 'wb') to write
binary data. Extended header not saved using this implementation.
Arguments:
mrcfilename: Filename for the output mrc file
"""
h = self.update_header(binarise=True)
maparray = np.array(self.fullMap, dtype='float32')
f = open(mrcfilename, 'wb')
f.write(h)
f.write(maparray.tostring())
f.close()
def write_to_MRC_file(self, mrcfilename, overwrite=True):
""" Write out Map instance as an MRC file
Uses `mrcfile <https://mrcfile.readthedocs.io/en/latest/usage_guide.html>`_
library for file writing.
Arguments:
mrcfilename: Filename for the output mrc file
"""
label = 'Created by TEMPy on: ' + str(datetime.date.today())
fullMap_f32 = self.fullMap.astype('float32')
with mrcfile.new(mrcfilename, overwrite=overwrite) as mrc:
mrc.set_data(fullMap_f32)
# Write out modern MRC files which prefer origin over
# nstart fields.
mrc.header.nxstart = 0
mrc.header.nystart = 0
mrc.header.nzstart = 0
# These are determined by density array
mrc.header.mx = self.x_size()
mrc.header.my = self.y_size()
mrc.header.mz = self.z_size()
# TEMPy should produce maps which have x,y,z ordering
mrc.header.mapc = 1
mrc.header.mapr = 2
mrc.header.maps = 3
mrc.header.cellb.alpha = 90
mrc.header.cellb.beta = 90
mrc.header.cellb.gamma = 90
mrc.header.ispg = self.header[22]
mrc.header.extra1 = self.header[24]
mrc.header.extra2 = self.header[27]
mrc.header.origin.x = self.origin[0]
mrc.header.origin.y = self.origin[1]
mrc.header.origin.z = self.origin[2]
mrc.header.label[0] = label
mrc.voxel_size = tuple(self.apix)
mrc.header.exttyp = self.header[25]
mrc.set_extended_header(np.array(self.ext_header))
def update_header(self, binarise=False):
""" Updates all entries in :code:`Map.header`.
Args:
binarse: If True, returns binary version of map header data.
Used in old MRC writing function.
Returns:
Binary version of :code:`Map.header` if :code:`binarise == True`
"""
nx = np.int32(self.x_size())
ny = np.int32(self.y_size())
nz = np.int32(self.z_size())
mode = np.int32(2)
nxstart = 0
nystart = 0
nzstart = 0
mx = nx
my = ny
mz = nz
xlen = np.float32(nx * self.apix[0])
ylen = np.float32(ny * self.apix[1])
zlen = np.float32(nz * self.apix[2])
alpha = np.int32(90)
beta = np.int32(90)
gamma = np.int32(90)
mapc = np.int32(1)
mapr = np.int32(2)
maps = np.int32(3)
amin = np.float32(self.min())
amax = np.float32(self.max())
amean = np.float32(self.mean())
ispg = np.int32(0)
if len(self.header) > 24:
ispg = np.int32(self.header[22])
nsymbt = np.int32(0)
extra = b'\x00'*10
xorigin = np.float32(self.origin[0])
yorigin = np.float32(self.origin[1])
zorigin = np.float32(self.origin[2])
mapword = b'MAP '
if sys.byteorder == 'little':
byteorder = 0x00004444
else:
byteorder = 0x11110000
rms = np.float32(self.std())
nlabels = np.int32(1)
label0 = (
b'Created by TEMpy on: ' +
str(datetime.date.today()).encode('ascii') +
b'\x00'*49
)
otherlabels = b'\x00'*720
self.header = [
nx,
ny,
nz,
mode,
nxstart,
nystart,
nzstart,
mx,
my,
mz,
xlen,
ylen,
zlen,
alpha,
beta,
gamma,
mapc,
mapr,
maps,
amin,
amax,
amean,
ispg,
nsymbt,
extra,
xorigin,
yorigin,
zorigin,
mapword,
byteorder,
rms,
nlabels,
label0,
otherlabels,
]
if binarise:
fm_string = '=10l6f3l3f2l100s3f4slfl80s720s'
return binary.pack(fm_string, *self.header)
def _pad_grid_line_no(self, no):
"""
Private function to help write data to map files.
"""
s = str(no)
spaces = ''
for x in range(8-len(s)):
spaces += ' '
s = spaces + s
return s
def _convert_point_to_string(self, point):
"""
Private function to help write data to map files.
"""
exp = 0
sign = ''
if abs(point) < 0.0001:
point = 0.0
if point >= 0:
sign = '+'
else:
sign = '-'
while abs(point) >= 10.0:
point /= 10.0
exp += 1
pointString = str(point)
if len(pointString) < 7:
for x in range(len(pointString), 7):
pointString += '0'
elif len(pointString) > 7:
pointString = pointString[:7]
pointString += 'E' + sign + '0' + str(exp)
return ' ' + pointString
def _get_component_volumes(
self,
struct,
apix,
blurrer,
):
"""
Private function for check on Map instance.
Return a a list containing the volume of the individual components
based on a grid with voxel size set to apix
Arguments:
*struct*
Structure object containing one or more chains.
*apix*
voxel size of the grid.
*blurrer*
Instance of a StructureBlurrer class.
Returns:
Return a a list containing the volume of the individual components
"""
mapCoM = self.get_com()
ssplit = struct.split_into_chains()
temp_grid = self._make_clash_map(apix)
overlay_maplist = []
cvol = []
for x in ssplit:
tx = mapCoM[0] - x.CoM[0]
ty = mapCoM[1] - x.CoM[1]
tz = mapCoM[2] - x.CoM[2]
x.translate(tx, ty, tz)
overlay_maplist.append(
blurrer.make_atom_overlay_map1(temp_grid, x)
)
for y in overlay_maplist:
cvol.append(y.fullMap.sum() * (apix.prod()))
return cvol
def map_rotate_by_axis_angle(
self,
x,
y,
z,
angle,
CoM,
rad=False,
):
"""Rotate Map instance around pivot point.
Arguments:
angle: Angle (in radians if rad == True, else in degrees) of
rotation
x,y,z: Axis to rotate about, ie. x,y,z = 0,0,1 rotates the Map
round the xy-plane.
CoM: Point around which map will be rotated.
Returns:
Rotated Map instance
"""
m = Vector.axis_angle_to_matrix(
x,
y,
z,
angle,
rad,
)
newCoM = CoM.matrix_transform(m.T)
offset = CoM - newCoM
newMap = self.matrix_transform(
m,
offset.x,
offset.y,
offset.z,
)
return newMap | PypiClean |
/Gridspeccer-0.2.1-py3-none-any.whl/gridspeccer/aux.py | import sys
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
from matplotlib.ticker import MaxNLocator
from matplotlib import cm
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from matplotlib import colorbar
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from skimage.transform import resize
from mpl_toolkits import axes_grid1
from . import core
cm_gray_r = plt.get_cmap("gray_r")
def supp_plot_distributions(axis, sampled, target, error_bar=True):
"""
Keywords:
-- axis: pointer of the axis object
-- sampled: numpy matrix with states in columns and repetitions in rows
-- target: numpy vector of the target distribution
"""
# Get the medain and the quarters for the emulated distr
# obtain the data fro the plots
sampled_median = np.median(sampled, axis=0)
sampled75 = np.percentile(sampled, 75, axis=0)
sampled25 = np.percentile(sampled, 25, axis=0)
err_down = sampled_median - sampled25
err_up = sampled75 - sampled_median
xval = np.array(list(range(0, len(sampled_median))))
# make the bar plots
axis.bar(xval, target, width=0.35, label="target", bottom=1e-3, color="tab:blue")
axis.bar(
xval + 0.35,
sampled_median,
width=0.35,
label="sampled",
bottom=1e-3,
color="tab:orange",
)
if error_bar:
axis.errorbar(
xval + 0.35,
sampled_median,
yerr=[err_down, err_up],
ecolor="black",
elinewidth=1,
capthick=1,
fmt="none",
capsize=0.0,
label="IQR",
)
# axis.legend()
# axis.set_yscale('log')
# axis.set_ylim(5e-2, 3.0001e-1)
axis.set_xticks([])
# axis.set_yticks([.05, .1, .2])
# axis.set_xticklabels(xlabels, rotation='vertical')
# axis.set_yticklabels(ylabels)
ylim = axis.get_ylim()
ylim_new = [0.0, ylim[1]]
axis.set_ylim(ylim_new)
axis.set_xlim([min(xval - 0.35), max(xval + 0.35 + 0.35)])
axis.set_xlabel(r"$\mathbf{z}$")
axis.set_ylabel(r"$p(\mathbf{z})$")
def supp_plot_three_distributions(axis, sampled_p, sampled_s, target, error_bar=True):
"""
Keywords:
-- axis: pointer of the axis object
-- sampled: numpy matrix with states in columns and repetitions in rows
-- target: numpy vector of the target distribution
"""
# Get the medain and the quarters for the emulated distr
# obtain the data fro the plots
sampled_median_p = np.median(sampled_p, axis=0)
errors_p = [
sampled_median_p - np.percentile(sampled_p, 25, axis=0),
np.percentile(sampled_p, 75, axis=0) - sampled_median_p,
]
sampled_median_s = np.median(sampled_s, axis=0)
sampled75_s = np.percentile(sampled_s, 75, axis=0)
sampled25_s = np.percentile(sampled_s, 25, axis=0)
err_down_s = sampled_median_s - sampled25_s
err_up_s = sampled75_s - sampled_median_s
xval = np.array(list(range(0, len(sampled_median_p))))
axis.bar(xval, target, width=0.27, label="target", bottom=1e-3, color="tab:olive")
axis.bar(
xval + 0.27,
sampled_median_p,
width=0.27,
label="Poisson",
bottom=1e-3,
color="tab:blue",
)
axis.bar(
xval + 0.54,
sampled_median_s,
width=0.27,
label="RN",
bottom=1e-3,
color="tab:orange",
)
if error_bar:
axis.errorbar(
xval + 0.27,
sampled_median_p,
yerr=errors_p,
ecolor="black",
elinewidth=1,
capthick=1,
fmt="none",
capsize=0.0,
)
axis.errorbar(
xval + 0.54,
sampled_median_s,
yerr=[err_down_s, err_up_s],
ecolor="black",
elinewidth=1,
capthick=1,
fmt="none",
capsize=0.0,
)
# axis.legend()
# axis.set_yscale('log')
# axis.set_ylim(5e-2, 3.0001e-1)
axis.set_xticks([])
# axis.set_yticks([.05, .1, .2])
# axis.set_xticklabels(xlabels, rotation='vertical')
# axis.set_yticklabels(ylabels)
ylim = axis.get_ylim()
ylim_new = [0.0, ylim[1]]
axis.set_ylim(ylim_new)
axis.set_xlim([min(xval - 0.35), max(xval + 0.35 + 0.35)])
axis.set_xlabel(r"$\mathbf{z}$", fontsize=12)
axis.set_ylabel(r"$p_\mathrm{joint}(\mathbf{z})$", fontsize=12)
def supp_plot_training(
axis,
dkl_iter_value_p,
dkl_final_p,
dkl_iter_p,
dkl_iter_value_s,
dkl_final_s,
dkl_iter_s,
):
"""
Keywords:
-- axis: axes object of the figure
-- dkl_iter: x axes, i.e. vector for the iteration values
-- dkl_iter_value: nupy matrix of the evolution of the DKL in iterations over several repetitions (in rows)
-- dkl_final: in rows: DKL over time for several repetitions
"""
# obtain the data fro the plots
dkl_iter_median_p = np.median(dkl_iter_value_p, axis=0)
dkl_iter_median_s = np.median(dkl_iter_value_s, axis=0)
# Obtain the final DKL values
final_dkl_median_p = np.median(dkl_final_p[:, -1]) * np.ones(len(dkl_iter_p))
final_dkl_median_s = np.median(dkl_final_s[:, -1]) * np.ones(len(dkl_iter_s))
# Do the plotting
linewidth = 2.0
axis.plot(
dkl_iter_p,
dkl_iter_median_p,
color="tab:blue",
linewidth=linewidth,
label="Poisson training",
)
axis.fill_between(
dkl_iter_p,
np.percentile(dkl_iter_value_p, 25, axis=0),
np.percentile(dkl_iter_value_p, 75, axis=0),
color="tab:blue",
alpha=0.5,
linewidth=0.0,
)
axis.plot(
dkl_iter_p,
final_dkl_median_p,
color="tab:blue",
linewidth=linewidth,
label="Poisson test",
linestyle="--",
)
axis.plot(
dkl_iter_s,
dkl_iter_median_s,
color="tab:orange",
linewidth=linewidth,
label="RN training",
)
axis.fill_between(
dkl_iter_s,
np.percentile(dkl_iter_value_s, 25, axis=0),
np.percentile(dkl_iter_value_s, 75, axis=0),
color="tab:orange",
alpha=0.5,
linewidth=0.0,
)
axis.plot(
dkl_iter_s,
final_dkl_median_s,
color="tab:orange",
linewidth=linewidth,
label="RN test",
linestyle="--",
)
axis.set_yscale("log")
axis.set_ylabel(
r"$\mathregular{D}_\mathregular{KL} \left[ \, p(\mathbf{z}) \, || \, p\!^*(\mathbf{z}) \, \right]$",
fontsize=12,
)
axis.set_xlabel(r"# iteration [1]", fontsize=12)
def supp_plot_dkl_time(
axis, dkl_time_array_p, dkl_time_value_p, dkl_time_array_s, dkl_time_value_s
):
"""
Keywords:
-- dkl_time_value: in rows: dkl_ over time for several repetitions
-- dkl_time_array: time array corresponding to the dkl_ evaluations
"""
# obtain the data fro the plots
dkl_median_p = np.median(dkl_time_value_p, axis=0)
dkl_75_p = np.percentile(dkl_time_value_p, 75, axis=0)
dkl_25_p = np.percentile(dkl_time_value_p, 25, axis=0)
dkl_median_s = np.median(dkl_time_value_s, axis=0)
dkl_75_s = np.percentile(dkl_time_value_s, 75, axis=0)
dkl_25_s = np.percentile(dkl_time_value_s, 25, axis=0)
# Do the plotting
linewidth = 2.0
axis.plot(
dkl_time_array_p,
dkl_median_p,
color="tab:blue",
linewidth=linewidth,
label="Poisson",
)
axis.fill_between(
dkl_time_array_p, dkl_25_p, dkl_75_p, color="tab:blue", alpha=0.5, linewidth=0.0
)
axis.plot(
dkl_time_array_s,
dkl_median_s,
color="tab:orange",
linewidth=linewidth,
label="RN",
)
axis.fill_between(
dkl_time_array_s,
dkl_25_s,
dkl_75_s,
color="tab:orange",
alpha=0.5,
linewidth=0.0,
)
axis.set_yscale("log")
axis.set_xscale("log")
axis.set_ylabel(
r"$\mathregular{D}_\mathregular{KL} \left[ \, p(\mathbf{z}) \, || \, p\!^*(\mathbf{z}) \, \right]$",
fontsize=12,
)
axis.set_xlabel(r"$t$ [ms]", fontsize=12)
def plot_itl_training(axis, abstract_ratio, class_ratio, iter_numb):
"""helper function to plot the in-the-loop training for both cases
Keywords:
--- axis: the axes object
--- abstract_ratio: reference values for classification with abstract RBM in sofware.
--- class_ratio: matrix with several repetitions, values for inference with hardware
--- iter_numb: array of the iteration corresponding to the class_ratio
"""
# Do the plotting
cr_median = np.median(class_ratio, axis=0)
cr_75 = np.percentile(class_ratio, 75, axis=0)
cr_25 = np.percentile(class_ratio, 25, axis=0)
a_median = np.median(abstract_ratio, axis=0)
a_75 = np.percentile(abstract_ratio, 75, axis=0)
a_25 = np.percentile(abstract_ratio, 25, axis=0)
print(
(
"Abstract class ratio is: {0}+{1}-{2}".format(
a_median, a_75 - a_median, a_median - a_25
)
)
)
print(
(
"Hardware class ratio is: {0}+{1}-{2}".format(
cr_median[-1], cr_75[-1] - cr_median[-1], cr_median[-1] - cr_25[-1]
)
)
)
axis.plot(iter_numb, cr_median, linewidth=1.5, color="xkcd:black", label="hardware")
axis.fill_between(
iter_numb,
cr_25,
cr_75,
color="xkcd:black",
alpha=0.2,
linewidth=0.0,
)
axis.set_ylabel("classification ratio [1]")
axis.set_xlabel("number of iterations [1]")
# axis.set_ylim([np.min(class_ratio) - 0.05, 1.05])
axis.set_ylim([0.0, 1.05])
# axis.grid(True)
xmin = min(iter_numb)
xmax = max(iter_numb)
axis.axhline(
y=a_median, xmin=xmin, xmax=xmax, linewidth=2, color="r", label="software"
)
x_array = np.linspace(xmin, xmax)
y_array = np.ones(len(x_array))
axis.fill_between(
x_array, a_75 * y_array, a_25 * y_array, color="r", alpha=0.2, linewidth=0.0
)
def plot_itl_training_error(axis, abstract_ratio, class_ratio, iter_numb):
"""helper function to plot the in-the-loop training for both cases
Keywords:
--- axis: the axes object
--- abstract_ratio: reference values for classification with abstract RBM in sofware.
--- class_ratio: matrix with several repetitions, values for inference with hardware
--- iter_numb: array of the iteration corresponding to the class_ratio
"""
# Do the plotting
error_ratio = 1.0 - class_ratio
error_abstract = 1.0 - abstract_ratio
cr_median = np.median(error_ratio, axis=0)
cr_75 = np.percentile(error_ratio, 75, axis=0)
cr_25 = np.percentile(error_ratio, 25, axis=0)
a_median = np.median(error_abstract, axis=0)
a_75 = np.percentile(error_abstract, 75, axis=0)
a_25 = np.percentile(error_abstract, 25, axis=0)
print(
(
"Abstract error ratio is: {0}+{1}-{2}".format(
a_median, a_75 - a_median, a_median - a_25
)
)
)
print(
(
"Hardware error ratio is: {0}+{1}-{2}".format(
cr_median[-1], cr_75[-1] - cr_median[-1], cr_median[-1] - cr_25[-1]
)
)
)
axis.plot(iter_numb, cr_median, linewidth=2, color="xkcd:black", label="hardware")
axis.fill_between(
iter_numb,
cr_25,
cr_75,
color="xkcd:black",
alpha=0.2,
linewidth=0.0,
)
axis.set_ylabel("error ratio [1]", fontsize=12)
axis.set_xlabel("number of iterations [1]", fontsize=12)
# axis.set_ylim([np.min(class_ratio) - 0.05, 1.05])
axis.set_ylim([-0.01, 0.25])
# axis.grid(True)
xmin = min(iter_numb)
xmax = max(iter_numb)
axis.axhline(
y=a_median,
xmin=xmin,
xmax=xmax,
linewidth=2,
linestyle="--",
color="tab:brown",
label="software",
)
# x_array = np.linspace(xmin, xmax)
# y_array = np.ones(len(x_array))
# axis.fill_between(x_array, a_75 * y_array, a_25 * y_array,
# color='r', alpha=0.2, linewidth=0.0)
def plot_mixture_matrix(axis, mixture_matrix, labels):
"""
auxiliary function to plot the mixture matrix
Keywords:
--- axis: the axes object
--- mixture_matrix: the data for the mixture matrix
--- labels: labels in the mixture matrix corresponding to classes
"""
# Add a finite number to the otherwise zero values
# to get around the logarithmic nan values
# mixture_matrix[np.where(mixture_matrix==0)] += 1
mixture_matrix = mixture_matrix / float(np.sum(mixture_matrix))
# disc = np.max(mixture_matrix)
fonts = {"fontsize": 10}
tick_size = 8
cmap = cm.get_cmap("gist_yarg") # , disc)
cmap.set_under((0.0, 0.0, 0.0))
core.show_axis(axis)
core.make_spines(axis)
imge = axis.imshow(
mixture_matrix, cmap=cm_gray_r, aspect=1.0, interpolation="nearest"
)
cax = inset_axes(
axis,
width="5%", # width = 10% of parent_bbox width
height="100%", # height : 50%
loc=3,
bbox_to_anchor=(1.05, 0.0, 1, 1),
bbox_transform=axis.transAxes,
borderpad=0,
)
# f = ticker.ScalarFormatter(useOffset=False, useMathText=True)
cbar = colorbar(imge, cax=cax, ticks=[0, 0.1, 0.2, 0.3], extend="both")
cbar.ax.tick_params(labelsize=9)
axis.set_ylabel("true label", **fonts)
axis.set_xlabel("predicted label", **fonts)
for location in ["top", "bottom", "left", "right"]:
axis.spines[location].set_visible(True)
axis.spines[location].set_linewidth(1.0)
# Change the ticks to labels names
axis.xaxis.set_major_locator(MaxNLocator(integer=True))
axis.yaxis.set_major_locator(MaxNLocator(integer=True))
axis.tick_params(length=0.0, pad=5)
axis.set_xticks(np.arange(len(labels)))
axis.set_xticklabels(labels, fontsize=tick_size)
axis.set_yticks(np.arange(len(labels)))
axis.set_yticklabels(labels, fontsize=tick_size)
axis.tick_params(axis="both", which="minor")
def plot_visible(axis, image_vector, pic_size, label):
"""
plot the visible layer using imshow
Keywords:
--- axis: axes object
--- image_vector: numpy array of the visible units
--- pic_size: size of the picute, tuple
--- label: x label for the image
"""
core.show_axis(axis)
network = image_vector
pic = np.reshape(network, pic_size)
axis.imshow(pic, cmap=cm_gray_r, vmin=0.0, vmax=1.0, interpolation="nearest")
axis.set_xticks([], [])
axis.set_yticks([], [])
axis.set_xlabel(label, labelpad=5)
axis.set_adjustable("box-forced")
def plot_clamping(axis, clamping_vector, pic_size, label, mode="sandp"):
"""
plot the clamping layer using imshow
Keywords:
--- axis: axes object
--- clamping_vector: image vector with clampings
--- pic_size: size of the picute, tuple
--- label: x label for the image
"""
core.show_axis(axis)
clamping = clamping_vector
clamp_mask = np.resize(clamping, pic_size)
overlay = np.ma.masked_where((clamp_mask != -1), np.ones(clamp_mask.shape))
indices = np.where(clamp_mask == -1)
clamp_mask[indices] = 0.0
cmap = cm_gray_r
cmap.set_bad(color="w", alpha=0.0)
axis.imshow(clamp_mask, cmap=cm_gray_r, vmin=0.0, vmax=1.0, interpolation="nearest")
if mode == "sandp":
cmap = plt.get_cmap("rainbow")
elif mode == "patch":
cmap = plt.get_cmap("Blues")
else:
sys.exit("Unknown mode specified in function plotClamping.")
axis.imshow(
overlay, cmap=cmap, vmin=0.0, vmax=1.0, alpha=0.9, interpolation="nearest"
)
axis.set_xticks([], [])
axis.set_yticks([], [])
axis.set_xlabel(label, labelpad=5)
def plot_label(axis, image_vector, labels, label):
"""
plot the label layer using imshow
Keywords:
--- axis: axes object
--- iamge_vector: activity of the label units
--- pic_size: size of the picute, tuple
--- labels: labels at the classification
--- label: x label for the image
"""
core.show_axis(axis)
label_response = image_vector
n_labels = len(label_response)
pic_size_labels = (n_labels, 1)
pic = np.reshape(label_response, pic_size_labels)
axis.imshow(
pic,
cmap=cm_gray_r,
vmin=0.0,
vmax=1.0,
interpolation="nearest",
extent=(0.0, 1.0, -0.5, n_labels - 0.5),
)
axis.set_yticks(list(range(n_labels)))
axis.set_yticklabels(labels, fontsize=6)
axis.tick_params(width=0, length=0)
axis.set_xticks([], [])
axis.set_xlabel(label, labelpad=5)
axis.set_adjustable("box-forced")
def plot_example_pictures(axis, original, pic_size_red, pic_size, grid, indices=None):
"""Plot an example picture"""
indices = indices if indices is not None else list(range(200))
# Layout specification
n_vertical = grid[0]
n_horizontal = grid[1]
half = 3
frame = 1
# Do the actual plotting
# create the picture matrix
pic = (
np.ones(
(
(2 * n_vertical + 1) * frame + 2 * n_vertical * pic_size[0] + half,
(n_horizontal + 1) * frame + n_horizontal * pic_size[1],
)
)
* 255
)
# Plot the upper 8 examples (originals)
for counter in range(n_vertical * n_horizontal):
i = counter % n_vertical
j = int(counter / n_vertical)
pic_vec = original[indices[counter], 1:]
pic_counter = np.reshape(pic_vec, pic_size)
pic[
(i + 1) * frame + i * pic_size[0] : (i + 1) * frame + (i + 1) * pic_size[0],
(j + 1) * frame + j * pic_size[1] : (j + 1) * frame + (j + 1) * pic_size[1],
] = pic_counter
# Plot the lower 8 examples (reduced)
for counter in range(n_vertical * n_horizontal):
i = counter % n_vertical + 2
j = int(counter / n_vertical)
pic_vec = original[indices[counter], 1:]
pic_counter = np.reshape(pic_vec, pic_size)
pic_counter = resize(
pic_counter,
pic_size_red,
) # interp='nearest')
median = np.percentile(pic_counter, 50)
pic_counter = ((np.sign(pic_counter - median) + 1) / 2) * 255.0
pic_counter = resize(
pic_counter,
pic_size,
) # interp='nearest')
pic[
(i + 1) * frame
+ half
+ i * pic_size[0] : (i + 1) * frame
+ (i + 1) * pic_size[0]
+ half,
(j + 1) * frame + j * pic_size[1] : (j + 1) * frame + (j + 1) * pic_size[1],
] = pic_counter
# Make the half line white
lower = 3 * frame + 2 * pic_size[0]
pic[lower : lower + half - 1, :] = 0
axis.imshow(pic, cmap="Greys", aspect="equal")
def plot_tsne(axis, pics, pos, pic_size):
"""
Make the tsne plot of pictures on a speicified axes object
Keywords:
--- axis: axes object
--- X: matrix of the data, the images are in rows
--- Y: position matrix of the data with tsne, the 2d coordinates are in rows
--- pic_size: 2d Tuple, the size of the pictures
"""
# Plot the pictures according to the coordinates
for i, posi in enumerate(pos):
cmap = cm_gray_r
pic = np.reshape(pics[i], pic_size)
img = cmap(np.ma.masked_array(pic, pic < 0.1))
# img = cmap(pic)
imagebox = OffsetImage(img, zoom=1.2, interpolation="nearest")
xy_pos = (posi[0], posi[1])
an_bo = AnnotationBbox(
imagebox, xy_pos, boxcoords="data", pad=0.05, frameon=False
)
an_bo.zorder = 1
axis.add_artist(an_bo)
# make the lines connecting the images
axis.scatter(pos[:, 0], pos[:, 1], 20, "w", alpha=0)
axis.set_xticks([])
axis.set_yticks([])
axis.plot(
pos[:, 0],
pos[:, 1],
linewidth=0.1,
linestyle="-",
color="black",
alpha=0.45,
zorder=0,
)
def plot_mse(axis, time_array, patch, sand_p, patch_abstract, sandp_abstract):
"""
Convenience function to plot the mse plots
Keywords:
--- axis: axes object
--- time_array: time_array
--- patch: Mse matrix for the patch occlusion
--- sand_p: Mse matrix for the salt and pepper occlusion
"""
# Set up the plot
core.show_axis(axis)
core.make_spines(axis)
# set up the data
datas = [patch, sand_p, patch_abstract, sandp_abstract]
labels = ["Patch HW", "S&P HW", "Patch SW", "S&P SW"]
colors = ["tab:blue", "tab:red", "tab:blue", "tab:red"]
dash_style = [[], [], (0, [1, 3]), (2, [1, 3])]
time_array = time_array - 150.0
# do the plotting
for index in range(2):
data = datas[index]
median = np.median(data, axis=0)
value75 = np.percentile(data, 75, axis=0)
value25 = np.percentile(data, 25, axis=0)
axis.plot(
time_array, median, linewidth=1.5, color=colors[index], label=labels[index]
)
axis.fill_between(
time_array,
value25,
value75,
color=colors[index],
alpha=0.2,
linewidth=0.0,
)
for index in range(2, 4):
data = datas[index]
median = np.median(data, axis=0)
value75 = np.percentile(data, 75, axis=0)
value25 = np.percentile(data, 25, axis=0)
axis.plot(
time_array,
np.ones(len(time_array)) * median,
linewidth=1.5,
color=colors[index],
label=labels[index],
ls=dash_style[index],
)
axis.fill_between(
time_array,
value25 * np.ones(len(time_array)),
value75 * np.ones(len(time_array)),
color=colors[index],
alpha=0.2,
linewidth=0.0,
)
# annotate the plot
axis.set_xlabel(r"$t$ [ms]", labelpad=5, fontsize=12)
axis.set_ylabel("mean squeared error [1]", fontsize=12)
axis.set_xlim([-40.0, 140.0])
axis.set_ylim([0.0, 0.55])
axis.legend(fontsize=8, loc=1)
def plot_error_time(
axis, time_array, patch, sand_p, reference, patch_abstract, sandp_abstract
):
"""
Convenience function to plot the mse plots
Keywords:
--- axis: axes object
--- time_array: time_array
--- patch: error matrix for the patch occlusion
--- sand_p: error matrix for the salt and pepper occlusion
"""
# Set up the plot
core.show_axis(axis)
core.make_spines(axis)
# set up the data
datas = [patch, sand_p, patch_abstract, sandp_abstract, reference]
labels = ["Patch HW", "S&P HW", "Patch SW", "S&P SW", "HW ref"]
colors = ["tab:blue", "tab:red", "tab:blue", "tab:red", "xkcd:black"]
dash_style = [[], [], (0, [1, 3]), (2, [1, 3])]
# width = [1., 1., 1.5, 1.5, 1.]
time_array = time_array - 150.0
# do the plotting
for index in range(2):
data = datas[index]
error = 1.0 - np.mean(data, axis=0)
axis.plot(
time_array, error, linewidth=1.5, color=colors[index], label=labels[index]
)
for index in range(2, 4):
data = datas[index]
median = 1.0 - np.median(data, axis=0)
# value75 = 1. - np.percentile(data, 75, axis=0)
# value25 = 1. - np.percentile(data, 25, axis=0)
axis.plot(
time_array,
np.ones(len(time_array)) * median,
linewidth=1.5,
color=colors[index],
label=labels[index],
ls=dash_style[index],
)
# With the index 4
data = datas[4]
error = 1.0 - np.mean(data, axis=0)
axis.plot(
time_array,
error,
linewidth=1.5,
color=colors[4],
label=labels[4],
linestyle="--",
)
# annotate the plot
axis.set_xlabel(r"$t$ [ms]", labelpad=5, fontsize=12)
axis.set_ylabel("error ratio [1]", fontsize=12)
axis.set_xlim([-40.0, 140.0])
axis.set_ylim([0.0, 0.86])
axis.legend(fontsize=8, loc=1)
def plot_psps(axis, time_array, v_array, normed=False):
"""
Plot the measured PSPs
Keywords:
--- axis: axes object
--- time_array: matrix with the time in the rows
--- v_array: matrix with voltages in the rows
"""
# Set up the plot
core.show_axis(axis)
core.make_spines(axis)
# do the plotting
for index in range(len(v_array[:, 0])):
if normed:
memb_pot = v_array[index, :] / np.max(v_array[index, :])
# if np.max(v_array[index,:]) < 0.05:
# continue
else:
memb_pot = v_array[index, :]
axis.plot(
time_array[index, :], memb_pot, linewidth=1.0, alpha=0.2, color="tab:blue"
)
axis.set_xlabel(r"t [ms]")
axis.set_ylabel(r"memb. potential [mV]")
axis.set_xlim([-10.0, 75.0])
def plot_box_plot(axis, data):
"""plot a box plot"""
# plot
datapoints = len(data)
# b1 = axis.boxplot(data[0],
# sym='x',
# positions=[0],
# widths=0.5,
# boxprops={'facecolor': 'tab:red'},
# patch_artist=True)
axis.boxplot(data[1:], sym="x", widths=0.5, positions=list(range(1, datapoints)))
axis.set_xlim([-0.6, datapoints - 0.4])
axis.set_yscale("log")
axis.set_ylabel(
r"$\mathregular{D}_\mathregular{KL} \left[ \, p(\mathbf{z}) \, || \, p\!^*(\mathbf{z}) \, \right]$",
fontsize=12,
)
axis.set_xlabel(r"# Distribution ID", fontsize=12)
def plot_frame(ax,
extent_left=0.18,
extent_right=0.10,
extent_top=0.20,
extent_bottom=0.25,
frame_instead_background=False,
fill_col="#f2f2f2",
):
if frame_instead_background:
val_fill = False
val_ec = 'black'
else:
val_fill = True
val_ec = None
fancybox = mpatches.Rectangle(
(-extent_left, -extent_bottom),
1 + extent_left + extent_right, 1 + extent_bottom + extent_top,
facecolor=fill_col, fill=val_fill, alpha=1.00, # zorder=zorder,
transform=ax.transAxes,
ec=val_ec,
zorder=-3)
plt.gcf().patches.append(fancybox)
def add_colorbar(im, label, aspect=15, pad_fraction=1.7, **kwargs):
"""Add a vertical color bar to an image plot."""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesY(im.axes, aspect=1. / aspect)
pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
current_ax = plt.gca()
cax = divider.append_axes("right", size=width, pad=pad)
plt.sca(current_ax)
cb = im.axes.figure.colorbar(im, cax=cax, **kwargs)
cb.set_label(label)
def add_colorbar_below(im, label, aspect=15, pad_fraction=5.0, **kwargs):
"""Add a vertical color bar to an image plot."""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesX(im.axes, aspect=1. / aspect)
pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
current_ax = plt.gca()
cax = divider.append_axes("bottom", size=width, pad=pad)
plt.sca(current_ax)
cb = im.axes.figure.colorbar(im, cax=cax, orientation='horizontal', **kwargs)
cb.set_label(label) | PypiClean |
/CityLearn-1.3.1-py3-none-any.whl/citylearn/building.py | import math
from typing import List, Mapping, Union
from gym import spaces
import numpy as np
from citylearn.base import Environment
from citylearn.data import EnergySimulation, CarbonIntensity, Pricing, Weather
from citylearn.energy_model import Battery, ElectricHeater, HeatPump, PV, StorageTank
from citylearn.preprocessing import Encoder, PeriodicNormalization, OnehotEncoding, RemoveFeature, Normalize
class Building(Environment):
def __init__(
self, energy_simulation: EnergySimulation, weather: Weather, observation_metadata: Mapping[str, bool], action_metadata: Mapping[str, bool], carbon_intensity: CarbonIntensity = None,
pricing: Pricing = None, dhw_storage: StorageTank = None, cooling_storage: StorageTank = None, heating_storage: StorageTank = None, electrical_storage: Battery = None,
dhw_device: Union[HeatPump, ElectricHeater] = None, cooling_device: HeatPump = None, heating_device: Union[HeatPump, ElectricHeater] = None, pv: PV = None, name: str = None, **kwargs
):
r"""Initialize `Building`.
Parameters
----------
energy_simulation : EnergySimulation
Temporal features, cooling, heating, dhw and plug loads, solar generation and indoor environment time series.
weather : Weather
Outdoor weather conditions and forecasts time sereis.
observation_metadata : dict
Mapping of active and inactive observations.
action_metadata : dict
Mapping od active and inactive actions.
carbon_intensity : CarbonIntensity, optional
Carbon dioxide emission rate time series.
pricing : Pricing, optional
Energy pricing and forecasts time series.
dhw_storage : StorageTank, optional
Hot water storage object for domestic hot water.
cooling_storage : StorageTank, optional
Cold water storage object for space cooling.
heating_storage : StorageTank, optional
Hot water storage object for space heating.
electrical_storage : Battery, optional
Electric storage object for meeting electric loads.
dhw_device : Union[HeatPump, ElectricHeater], optional
Electric device for meeting hot domestic hot water demand and charging `dhw_storage`.
cooling_device : HeatPump, optional
Electric device for meeting space cooling demand and charging `cooling_storage`.
heating_device : Union[HeatPump, ElectricHeater], optional
Electric device for meeting space heating demand and charging `heating_storage`.
pv : PV, optional
PV object for offsetting electricity demand from grid.
name : str, optional
Unique building name.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments used to initialize super class.
"""
self.name = name
self.energy_simulation = energy_simulation
self.weather = weather
self.carbon_intensity = carbon_intensity
self.pricing = pricing
self.dhw_storage = dhw_storage
self.cooling_storage = cooling_storage
self.heating_storage = heating_storage
self.electrical_storage = electrical_storage
self.dhw_device = dhw_device
self.cooling_device = cooling_device
self.heating_device = heating_device
self.pv = pv
self.observation_metadata = observation_metadata
self.action_metadata = action_metadata
self.__observation_epsilon = 1.0 # to avoid out of bound observations
self.observation_space = self.estimate_observation_space()
self.action_space = self.estimate_action_space()
super().__init__(**kwargs)
@property
def energy_simulation(self) -> EnergySimulation:
"""Temporal features, cooling, heating, dhw and plug loads, solar generation and indoor environment time series."""
return self.__energy_simulation
@property
def weather(self) -> Weather:
"""Outdoor weather conditions and forecasts time series."""
return self.__weather
@property
def observation_metadata(self) -> Mapping[str, bool]:
"""Mapping of active and inactive observations."""
return self.__observation_metadata
@property
def action_metadata(self) -> Mapping[str, bool]:
"""Mapping od active and inactive actions."""
return self.__action_metadata
@property
def carbon_intensity(self) -> CarbonIntensity:
"""Carbon dioxide emission rate time series."""
return self.__carbon_intensity
@property
def pricing(self) -> Pricing:
"""Energy pricing and forecasts time series."""
return self.__pricing
@property
def dhw_storage(self) -> StorageTank:
"""Hot water storage object for domestic hot water."""
return self.__dhw_storage
@property
def cooling_storage(self) -> StorageTank:
"""Cold water storage object for space cooling."""
return self.__cooling_storage
@property
def heating_storage(self) -> StorageTank:
"""Hot water storage object for space heating."""
return self.__heating_storage
@property
def electrical_storage(self) -> Battery:
"""Electric storage object for meeting electric loads."""
return self.__electrical_storage
@property
def dhw_device(self) -> Union[HeatPump, ElectricHeater]:
"""Electric device for meeting hot domestic hot water demand and charging `dhw_storage`."""
return self.__dhw_device
@property
def cooling_device(self) -> HeatPump:
"""Electric device for meeting space cooling demand and charging `cooling_storage`."""
return self.__cooling_device
@property
def heating_device(self) -> Union[HeatPump, ElectricHeater]:
"""Electric device for meeting space heating demand and charging `heating_storage`."""
return self.__heating_device
@property
def pv(self) -> PV:
"""PV object for offsetting electricity demand from grid."""
return self.__pv
@property
def name(self) -> str:
"""Unique building name."""
return self.__name
@property
def observation_space(self) -> spaces.Box:
"""Agent observation space."""
return self.__observation_space
@property
def action_space(self) -> spaces.Box:
"""Agent action spaces."""
return self.__action_space
@property
def observation_encoders(self) -> List[Encoder]:
r"""Get observation value transformers/encoders for use in agent algorithm.
The encoder classes are defined in the `preprocessing.py` module and include `PeriodicNormalization` for cyclic observations,
`OnehotEncoding` for categorical obeservations, `RemoveFeature` for non-applicable observations given available storage systems and devices
and `Normalize` for observations with known mnimum and maximum boundaries.
Returns
-------
encoders : List[Encoder]
Encoder classes for observations ordered with respect to `active_observations`.
"""
remove_features = ['net_electricity_consumption']
remove_features += [
'solar_generation', 'diffuse_solar_irradiance', 'diffuse_solar_irradiance_predicted_6h',
'diffuse_solar_irradiance_predicted_12h', 'diffuse_solar_irradiance_predicted_24h',
'direct_solar_irradiance', 'direct_solar_irradiance_predicted_6h',
'direct_solar_irradiance_predicted_12h', 'direct_solar_irradiance_predicted_24h',
] if self.pv.nominal_power == 0 else []
demand_observations = {
'dhw_storage_soc': np.nansum(self.energy_simulation.dhw_demand),
'cooling_storage_soc': np.nansum(self.energy_simulation.cooling_demand),
'heating_storage_soc': np.nansum(self.energy_simulation.heating_demand),
'electrical_storage_soc': np.nansum(np.nansum([
self.energy_simulation.dhw_demand,
self.energy_simulation.cooling_demand,
self.energy_simulation.heating_demand,
self.energy_simulation.non_shiftable_load
], axis = 0)),
'non_shiftable_load': np.nansum(self.energy_simulation.non_shiftable_load),
}
remove_features += [k for k, v in demand_observations.items() if v == 0]
remove_features = [f for f in remove_features if f in self.active_observations]
encoders = []
for i, observation in enumerate(self.active_observations):
if observation in ['month', 'hour']:
encoders.append(PeriodicNormalization(self.observation_space.high[i]))
elif observation == 'day_type':
encoders.append(OnehotEncoding([0, 1, 2, 3, 4, 5, 6, 7, 8]))
elif observation == "daylight_savings_status":
encoders.append(OnehotEncoding([0, 1, 2]))
elif observation in remove_features:
encoders.append(RemoveFeature())
else:
encoders.append(Normalize(self.observation_space.low[i], self.observation_space.high[i]))
return encoders
@property
def observations(self) -> Mapping[str, float]:
"""Observations at current time step."""
observations = {}
data = {
**{k: v[self.time_step] for k, v in vars(self.energy_simulation).items()},
**{k: v[self.time_step] for k, v in vars(self.weather).items()},
**{k: v[self.time_step] for k, v in vars(self.pricing).items()},
'solar_generation':self.pv.get_generation(self.energy_simulation.solar_generation[self.time_step]),
**{
'cooling_storage_soc':self.cooling_storage.soc[self.time_step]/self.cooling_storage.capacity,
'heating_storage_soc':self.heating_storage.soc[self.time_step]/self.heating_storage.capacity,
'dhw_storage_soc':self.dhw_storage.soc[self.time_step]/self.dhw_storage.capacity,
'electrical_storage_soc':self.electrical_storage.soc[self.time_step]/self.electrical_storage.capacity_history[self.time_step - 1],
},
'net_electricity_consumption': self.net_electricity_consumption[self.time_step],
**{k: v[self.time_step] for k, v in vars(self.carbon_intensity).items()},
}
observations = {k: data[k] for k in self.active_observations if k in data.keys()}
unknown_observations = list(set([k for k in self.active_observations]).difference(observations.keys()))
assert len(unknown_observations) == 0, f'Unkown observations: {unknown_observations}'
return observations
@property
def active_observations(self) -> List[str]:
"""Observations in `observation_metadata` with True value i.e. obeservable."""
return [k for k, v in self.observation_metadata.items() if v]
@property
def active_actions(self) -> List[str]:
"""Actions in `action_metadata` with True value i.e. indicates which storage systems are to be controlled during simulation."""
return [k for k, v in self.action_metadata.items() if v]
@property
def net_electricity_consumption_without_storage_and_pv_emission(self) -> np.ndarray:
"""Carbon dioxide emmission from `net_electricity_consumption_without_storage_and_pv` time series, in [kg_co2]."""
return (
self.carbon_intensity.carbon_intensity[0:self.time_step + 1]*self.net_electricity_consumption_without_storage_and_pv
).clip(min=0)
@property
def net_electricity_consumption_without_storage_and_pv_price(self) -> np.ndarray:
"""net_electricity_consumption_without_storage_and_pv` cost time series, in [$]."""
return self.pricing.electricity_pricing[0:self.time_step + 1]*self.net_electricity_consumption_without_storage_and_pv
@property
def net_electricity_consumption_without_storage_and_pv(self) -> np.ndarray:
"""Net electricity consumption in the absence of flexibility provided by `cooling_storage` and self generation time series, in [kWh].
Notes
-----
net_electricity_consumption_without_storage_and_pv = `net_electricity_consumption_without_storage` - `solar_generation`
"""
return self.net_electricity_consumption_without_storage - self.solar_generation
@property
def net_electricity_consumption_without_storage_emission(self) -> np.ndarray:
"""Carbon dioxide emmission from `net_electricity_consumption_without_storage` time series, in [kg_co2]."""
return (self.carbon_intensity.carbon_intensity[0:self.time_step + 1]*self.net_electricity_consumption_without_storage).clip(min=0)
@property
def net_electricity_consumption_without_storage_price(self) -> np.ndarray:
"""`net_electricity_consumption_without_storage` cost time series, in [$]."""
return self.pricing.electricity_pricing[0:self.time_step + 1]*self.net_electricity_consumption_without_storage
@property
def net_electricity_consumption_without_storage(self) -> np.ndarray:
"""net electricity consumption in the absence of flexibility provided by storage devices time series, in [kWh].
Notes
-----
net_electricity_consumption_without_storage = `net_electricity_consumption` - (`cooling_storage_electricity_consumption` + `heating_storage_electricity_consumption` + `dhw_storage_electricity_consumption` + `electrical_storage_electricity_consumption`)
"""
return self.net_electricity_consumption - np.sum([
self.cooling_storage_electricity_consumption,
self.heating_storage_electricity_consumption,
self.dhw_storage_electricity_consumption,
self.electrical_storage_electricity_consumption
], axis = 0)
@property
def net_electricity_consumption_emission(self) -> np.ndarray:
"""Carbon dioxide emmission from `net_electricity_consumption` time series, in [kg_co2]."""
return (self.carbon_intensity.carbon_intensity[0:self.time_step + 1]*self.net_electricity_consumption).clip(min=0)
@property
def net_electricity_consumption_price(self) -> np.ndarray:
"""`net_electricity_consumption` cost time series, in [$]."""
return self.pricing.electricity_pricing[0:self.time_step + 1]*self.net_electricity_consumption
@property
def net_electricity_consumption(self) -> np.ndarray:
"""net electricity consumption time series, in [kWh].
Notes
-----
net_electricity_consumption = `cooling_electricity_consumption` + `heating_electricity_consumption` + `dhw_electricity_consumption` + `electrical_storage_electricity_consumption` + `non_shiftable_load_demand` + `solar_generation`
"""
return np.sum([
self.cooling_electricity_consumption,
self.heating_electricity_consumption,
self.dhw_electricity_consumption,
self.electrical_storage_electricity_consumption,
self.non_shiftable_load_demand,
self.solar_generation,
], axis = 0)
@property
def cooling_electricity_consumption(self) -> np.ndarray:
"""`cooling_device` net electricity consumption in meeting domestic hot water and `cooling_stoage` energy demand time series, in [kWh].
Positive values indicate `cooling_device` electricity consumption to charge `cooling_storage` and/or meet `cooling_demand` while negative values indicate avoided `cooling_device`
electricity consumption by discharging `cooling_storage` to meet `cooling_demand`.
"""
demand = np.sum([self.cooling_demand, self.cooling_storage.energy_balance], axis = 0)
return self.cooling_device.get_input_power(demand, self.weather.outdoor_dry_bulb_temperature[:self.time_step + 1], False)
@property
def heating_electricity_consumption(self) -> np.ndarray:
"""`heating_device` net electricity consumption in meeting domestic hot water and `heating_stoage` energy demand time series, in [kWh].
Positive values indicate `heating_device` electricity consumption to charge `heating_storage` and/or meet `heating_demand` while negative values indicate avoided `heating_device`
electricity consumption by discharging `heating_storage` to meet `heating_demand`.
"""
demand = np.sum([self.heating_demand, self.heating_storage.energy_balance], axis = 0)
if isinstance(self.heating_device, HeatPump):
consumption = self.heating_device.get_input_power(demand, self.weather.outdoor_dry_bulb_temperature[:self.time_step + 1], True)
else:
consumption = self.dhw_device.get_input_power(demand)
return consumption
@property
def dhw_electricity_consumption(self) -> np.ndarray:
"""`dhw_device` net electricity consumption in meeting domestic hot water and `dhw_stoage` energy demand time series, in [kWh].
Positive values indicate `dhw_device` electricity consumption to charge `dhw_storage` and/or meet `dhw_demand` while negative values indicate avoided `dhw_device`
electricity consumption by discharging `dhw_storage` to meet `dhw_demand`.
"""
demand = np.sum([self.dhw_demand, self.dhw_storage.energy_balance], axis = 0)
if isinstance(self.dhw_device, HeatPump):
consumption = self.dhw_device.get_input_power(demand, self.weather.outdoor_dry_bulb_temperature[:self.time_step + 1], True)
else:
consumption = self.dhw_device.get_input_power(demand)
return consumption
@property
def cooling_storage_electricity_consumption(self) -> np.ndarray:
"""`cooling_storage` net electricity consumption time series, in [kWh].
Positive values indicate `cooling_device` electricity consumption to charge `cooling_storage` while negative values indicate avoided `cooling_device`
electricity consumption by discharging `cooling_storage` to meet `cooling_demand`.
"""
return self.cooling_device.get_input_power(self.cooling_storage.energy_balance, self.weather.outdoor_dry_bulb_temperature[:self.time_step + 1], False)
@property
def heating_storage_electricity_consumption(self) -> np.ndarray:
"""`heating_storage` net electricity consumption time series, in [kWh].
Positive values indicate `heating_device` electricity consumption to charge `heating_storage` while negative values indicate avoided `heating_device`
electricity consumption by discharging `heating_storage` to meet `heating_demand`.
"""
if isinstance(self.heating_device, HeatPump):
consumption = self.heating_device.get_input_power(self.heating_storage.energy_balance, self.weather.outdoor_dry_bulb_temperature[:self.time_step + 1], True)
else:
consumption = self.heating_device.get_input_power(self.heating_storage.energy_balance)
return consumption
@property
def dhw_storage_electricity_consumption(self) -> np.ndarray:
"""`dhw_storage` net electricity consumption time series, in [kWh].
Positive values indicate `dhw_device` electricity consumption to charge `dhw_storage` while negative values indicate avoided `dhw_device`
electricity consumption by discharging `dhw_storage` to meet `dhw_demand`.
"""
if isinstance(self.dhw_device, HeatPump):
consumption = self.dhw_device.get_input_power(self.dhw_storage.energy_balance, self.weather.outdoor_dry_bulb_temperature[:self.time_step + 1], True)
else:
consumption = self.dhw_device.get_input_power(self.dhw_storage.energy_balance)
return consumption
@property
def electrical_storage_electricity_consumption(self) -> np.ndarray:
"""Energy supply from grid and/or `PV` to `electrical_storage` time series, in [kWh]."""
return self.electrical_storage.electricity_consumption
@property
def energy_from_cooling_device_to_cooling_storage(self) -> np.ndarray:
"""Energy supply from `cooling_device` to `cooling_storage` time series, in [kWh]."""
return self.cooling_storage.energy_balance.clip(min=0)
@property
def energy_from_heating_device_to_heating_storage(self) -> np.ndarray:
"""Energy supply from `heating_device` to `heating_storage` time series, in [kWh]."""
return self.heating_storage.energy_balance.clip(min=0)
@property
def energy_from_dhw_device_to_dhw_storage(self) -> np.ndarray:
"""Energy supply from `dhw_device` to `dhw_storage` time series, in [kWh]."""
return self.dhw_storage.energy_balance.clip(min=0)
@property
def energy_to_electrical_storage(self) -> np.ndarray:
"""Energy supply from `electrical_device` to building time series, in [kWh]."""
return self.electrical_storage.energy_balance.clip(min=0)
@property
def energy_from_cooling_device(self) -> np.ndarray:
"""Energy supply from `cooling_device` to building time series, in [kWh]."""
return self.cooling_demand - self.energy_from_cooling_storage
@property
def energy_from_heating_device(self) -> np.ndarray:
"""Energy supply from `heating_device` to building time series, in [kWh]."""
return self.heating_demand - self.energy_from_heating_storage
@property
def energy_from_dhw_device(self) -> np.ndarray:
"""Energy supply from `dhw_device` to building time series, in [kWh]."""
return self.dhw_demand - self.energy_from_dhw_storage
@property
def energy_from_cooling_storage(self) -> np.ndarray:
"""Energy supply from `cooling_storage` to building time series, in [kWh]."""
return self.cooling_storage.energy_balance.clip(max = 0)*-1
@property
def energy_from_heating_storage(self) -> np.ndarray:
"""Energy supply from `heating_storage` to building time series, in [kWh]."""
return self.heating_storage.energy_balance.clip(max = 0)*-1
@property
def energy_from_dhw_storage(self) -> np.ndarray:
"""Energy supply from `dhw_storage` to building time series, in [kWh]."""
return self.dhw_storage.energy_balance.clip(max = 0)*-1
@property
def energy_from_electrical_storage(self) -> np.ndarray:
"""Energy supply from `electrical_storage` to building time series, in [kWh]."""
return self.electrical_storage.energy_balance.clip(max = 0)*-1
@property
def cooling_demand(self) -> np.ndarray:
"""Space cooling demand to be met by `cooling_device` and/or `cooling_storage` time series, in [kWh]."""
return self.energy_simulation.cooling_demand[0:self.time_step + 1]
@property
def heating_demand(self) -> np.ndarray:
"""Space heating demand to be met by `heating_device` and/or `heating_storage` time series, in [kWh]."""
return self.energy_simulation.heating_demand[0:self.time_step + 1]
@property
def dhw_demand(self) -> np.ndarray:
"""Domestic hot water demand to be met by `dhw_device` and/or `dhw_storage` time series, in [kWh]."""
return self.energy_simulation.dhw_demand[0:self.time_step + 1]
@property
def non_shiftable_load_demand(self) -> np.ndarray:
"""Electricity load that must be met by the grid, or `PV` and/or `electrical_storage` if available time series, in [kWh]."""
return self.energy_simulation.non_shiftable_load[0:self.time_step + 1]
@property
def solar_generation(self) -> np.ndarray:
"""`PV` solar generation (negative value) time series, in [kWh]."""
return self.pv.get_generation(self.energy_simulation.solar_generation[0:self.time_step + 1])*-1
@energy_simulation.setter
def energy_simulation(self, energy_simulation: EnergySimulation):
self.__energy_simulation = energy_simulation
@weather.setter
def weather(self, weather: Weather):
self.__weather = weather
@observation_metadata.setter
def observation_metadata(self, observation_metadata: Mapping[str, bool]):
self.__observation_metadata = observation_metadata
@action_metadata.setter
def action_metadata(self, action_metadata: Mapping[str, bool]):
self.__action_metadata = action_metadata
@carbon_intensity.setter
def carbon_intensity(self, carbon_intensity: CarbonIntensity):
if carbon_intensity is None:
self.__carbon_intensity = CarbonIntensity(np.zeros(len(self.energy_simulation.hour), dtype = float))
else:
self.__carbon_intensity = carbon_intensity
@pricing.setter
def pricing(self, pricing: Pricing):
if pricing is None:
self.__pricing = Pricing(
np.zeros(len(self.energy_simulation.hour), dtype = float),
np.zeros(len(self.energy_simulation.hour), dtype = float),
np.zeros(len(self.energy_simulation.hour), dtype = float),
np.zeros(len(self.energy_simulation.hour), dtype = float),
)
else:
self.__pricing = pricing
@dhw_storage.setter
def dhw_storage(self, dhw_storage: StorageTank):
self.__dhw_storage = StorageTank(0.0) if dhw_storage is None else dhw_storage
@cooling_storage.setter
def cooling_storage(self, cooling_storage: StorageTank):
self.__cooling_storage = StorageTank(0.0) if cooling_storage is None else cooling_storage
@heating_storage.setter
def heating_storage(self, heating_storage: StorageTank):
self.__heating_storage = StorageTank(0.0) if heating_storage is None else heating_storage
@electrical_storage.setter
def electrical_storage(self, electrical_storage: Battery):
self.__electrical_storage = Battery(0.0, 0.0) if electrical_storage is None else electrical_storage
@dhw_device.setter
def dhw_device(self, dhw_device: Union[HeatPump, ElectricHeater]):
self.__dhw_device = ElectricHeater(0.0) if dhw_device is None else dhw_device
@cooling_device.setter
def cooling_device(self, cooling_device: HeatPump):
self.__cooling_device = HeatPump(0.0) if cooling_device is None else cooling_device
@heating_device.setter
def heating_device(self, heating_device: Union[HeatPump, ElectricHeater]):
self.__heating_device = HeatPump(0.0) if heating_device is None else heating_device
@pv.setter
def pv(self, pv: PV):
self.__pv = PV(0.0) if pv is None else pv
@observation_space.setter
def observation_space(self, observation_space: spaces.Box):
self.__observation_space = observation_space
@action_space.setter
def action_space(self, action_space: spaces.Box):
self.__action_space = action_space
@name.setter
def name(self, name: str):
self.__name = self.uid if name is None else name
def apply_actions(self, cooling_storage_action: float = 0, heating_storage_action: float = 0, dhw_storage_action: float = 0, electrical_storage_action: float = 0):
r"""Charge/discharge storage devices.
Parameters
----------
cooling_storage_action : float, default: 0
Fraction of `cooling_storage` `capacity` to charge/discharge by.
heating_storage_action : float, default: 0
Fraction of `heating_storage` `capacity` to charge/discharge by.
dhw_storage_action : float, default: 0
Fraction of `dhw_storage` `capacity` to charge/discharge by.
electrical_storage_action : float, default: 0
Fraction of `electrical_storage` `capacity` to charge/discharge by.
"""
self.update_cooling(cooling_storage_action)
self.update_heating(heating_storage_action)
self.update_dhw(dhw_storage_action)
self.update_electrical_storage(electrical_storage_action)
def update_cooling(self, action: float = 0):
r"""Charge/discharge `cooling_storage`.
Parameters
----------
action : float, default: 0
Fraction of `cooling_storage` `capacity` to charge/discharge by.
"""
energy = action*self.cooling_storage.capacity
space_demand = self.energy_simulation.cooling_demand[self.time_step]
space_demand = 0 if space_demand is None or math.isnan(space_demand) else space_demand # case where space demand is unknown
max_output = self.cooling_device.get_max_output_power(self.weather.outdoor_dry_bulb_temperature[self.time_step], False)
energy = max(-space_demand, min(max_output - space_demand, energy))
self.cooling_storage.charge(energy)
input_power = self.cooling_device.get_input_power(space_demand + energy, self.weather.outdoor_dry_bulb_temperature[self.time_step], False)
self.cooling_device.update_electricity_consumption(input_power)
def update_heating(self, action: float = 0):
r"""Charge/discharge `heating_storage`.
Parameters
----------
action : float, default: 0
Fraction of `heating_storage` `capacity` to charge/discharge by.
"""
energy = action*self.heating_storage.capacity
space_demand = self.energy_simulation.heating_demand[self.time_step]
space_demand = 0 if space_demand is None or math.isnan(space_demand) else space_demand # case where space demand is unknown
max_output = self.heating_device.get_max_output_power(self.weather.outdoor_dry_bulb_temperature[self.time_step], False)\
if isinstance(self.heating_device, HeatPump) else self.heating_device.get_max_output_power()
energy = max(-space_demand, min(max_output - space_demand, energy))
self.heating_storage.charge(energy)
demand = space_demand + energy
input_power = self.heating_device.get_input_power(demand, self.weather.outdoor_dry_bulb_temperature[self.time_step], False)\
if isinstance(self.heating_device, HeatPump) else self.heating_device.get_input_power(demand)
self.heating_device.update_electricity_consumption(input_power)
def update_dhw(self, action: float = 0):
r"""Charge/discharge `dhw_storage`.
Parameters
----------
action : float, default: 0
Fraction of `dhw_storage` `capacity` to charge/discharge by.
"""
energy = action*self.dhw_storage.capacity
space_demand = self.energy_simulation.dhw_demand[self.time_step]
space_demand = 0 if space_demand is None or math.isnan(space_demand) else space_demand # case where space demand is unknown
max_output = self.dhw_device.get_max_output_power(self.weather.outdoor_dry_bulb_temperature[self.time_step], False)\
if isinstance(self.dhw_device, HeatPump) else self.dhw_device.get_max_output_power()
energy = max(-space_demand, min(max_output - space_demand, energy))
self.dhw_storage.charge(energy)
demand = space_demand + energy
input_power = self.dhw_device.get_input_power(demand, self.weather.outdoor_dry_bulb_temperature[self.time_step], False)\
if isinstance(self.dhw_device, HeatPump) else self.dhw_device.get_input_power(demand)
self.dhw_device.update_electricity_consumption(input_power)
def update_electrical_storage(self, action: float = 0):
r"""Charge/discharge `electrical_storage`.
Parameters
----------
action : float, default: 0
Fraction of `electrical_storage` `capacity` to charge/discharge by.
"""
energy = action*self.electrical_storage.capacity
self.electrical_storage.charge(energy)
def estimate_observation_space(self) -> spaces.Box:
r"""Get estimate of observation spaces.
Find minimum and maximum possible values of all the observations, which can then be used by the RL agent to scale the observations and train any function approximators more effectively.
Returns
-------
observation_space : spaces.Box
Observation low and high limits.
Notes
-----
Lower and upper bounds of net electricity consumption are rough estimates and may not be completely accurate hence,
scaling this observation-variable using these bounds may result in normalized values above 1 or below 0.
"""
low_limit, high_limit = [], []
data = {
'solar_generation':np.array(self.pv.get_generation(self.energy_simulation.solar_generation)),
**vars(self.energy_simulation),
**vars(self.weather),
**vars(self.carbon_intensity),
**vars(self.pricing),
}
for key in self.active_observations:
if key == 'net_electricity_consumption':
net_electric_consumption = self.energy_simulation.non_shiftable_load\
+ (self.energy_simulation.dhw_demand)\
+ self.energy_simulation.cooling_demand\
+ self.energy_simulation.heating_demand\
+ (self.dhw_storage.capacity/0.8)\
+ (self.cooling_storage.capacity/0.8)\
+ (self.heating_storage.capacity/0.8)\
+ (self.electrical_storage.capacity/0.8)\
- data['solar_generation']
low_limit.append(-max(abs(net_electric_consumption)))
high_limit.append(max(abs(net_electric_consumption)))
elif key in ['cooling_storage_soc', 'heating_storage_soc', 'dhw_storage_soc', 'electrical_storage_soc']:
low_limit.append(0.0)
high_limit.append(1.0)
else:
low_limit.append(min(data[key]))
high_limit.append(max(data[key]))
low_limit = [v - self.__observation_epsilon for v in low_limit]
high_limit = [v + self.__observation_epsilon for v in high_limit]
return spaces.Box(low=np.array(low_limit, dtype='float32'), high=np.array(high_limit, dtype='float32'))
def estimate_action_space(self) -> spaces.Box:
r"""Get estimate of action spaces.
Find minimum and maximum possible values of all the actions, which can then be used by the RL agent to scale the selected actions.
Returns
-------
action_space : spaces.Box
Action low and high limits.
Notes
-----
The lower and upper bounds for the `cooling_storage`, `heating_storage` and `dhw_storage` actions are set to (+/-) 1/maximum_demand for each respective end use,
as the energy storage device can't provide the building with more energy than it will ever need for a given time step. .
For example, if `cooling_storage` capacity is 20 kWh and the maximum `cooling_demand` is 5 kWh, its actions will be bounded between -5/20 and 5/20.
These boundaries should speed up the learning process of the agents and make them more stable compared to setting them to -1 and 1.
"""
low_limit, high_limit = [], []
for key in self.active_actions:
if key == 'electrical_storage':
low_limit.append(-1.0)
high_limit.append(1.0)
else:
capacity = vars(self)[f'_{self.__class__.__name__}__{key}'].capacity
energy_simulation = vars(self)[f'_{self.__class__.__name__}__energy_simulation']
maximum_demand = vars(energy_simulation)[f'{key.split("_")[0]}_demand'].max()
maximum_demand_ratio = maximum_demand/capacity
try:
low_limit.append(max(-maximum_demand_ratio, -1.0))
high_limit.append(min(maximum_demand_ratio, 1.0))
except ZeroDivisionError:
low_limit.append(-1.0)
high_limit.append(1.0)
return spaces.Box(low=np.array(low_limit, dtype='float32'), high=np.array(high_limit, dtype='float32'))
def autosize_cooling_device(self, **kwargs):
"""Autosize `cooling_device` `nominal_power` to minimum power needed to always meet `cooling_demand`.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments parsed to `cooling_device` `autosize` function.
"""
self.cooling_device.autosize(self.weather.outdoor_dry_bulb_temperature, cooling_demand = self.energy_simulation.cooling_demand, **kwargs)
def autosize_heating_device(self, **kwargs):
"""Autosize `heating_device` `nominal_power` to minimum power needed to always meet `heating_demand`.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments parsed to `heating_device` `autosize` function.
"""
self.heating_device.autosize(self.weather.outdoor_dry_bulb_temperature, heating_demand = self.energy_simulation.heating_demand, **kwargs)\
if isinstance(self.heating_device, HeatPump) else self.heating_device.autosize(self.energy_simulation.heating_demand, **kwargs)
def autosize_dhw_device(self, **kwargs):
"""Autosize `dhw_device` `nominal_power` to minimum power needed to always meet `dhw_demand`.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments parsed to `dhw_device` `autosize` function.
"""
self.dhw_device.autosize(self.weather.outdoor_dry_bulb_temperature, heating_demand = self.energy_simulation.dhw_demand, **kwargs)\
if isinstance(self.dhw_device, HeatPump) else self.dhw_device.autosize(self.energy_simulation.dhw_demand, **kwargs)
def autosize_cooling_storage(self, **kwargs):
"""Autosize `cooling_storage` `capacity` to minimum capacity needed to always meet `cooling_demand`.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments parsed to `cooling_storage` `autosize` function.
"""
self.cooling_storage.autosize(self.energy_simulation.cooling_demand, **kwargs)
def autosize_heating_storage(self, **kwargs):
"""Autosize `heating_storage` `capacity` to minimum capacity needed to always meet `heating_demand`.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments parsed to `heating_storage` `autosize` function.
"""
self.heating_storage.autosize(self.energy_simulation.heating_demand, **kwargs)
def autosize_dhw_storage(self, **kwargs):
"""Autosize `dhw_storage` `capacity` to minimum capacity needed to always meet `dhw_demand`.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments parsed to `dhw_storage` `autosize` function.
"""
self.dhw_storage.autosize(self.energy_simulation.dhw_demand, **kwargs)
def autosize_electrical_storage(self, **kwargs):
"""Autosize `electrical_storage` `capacity` to minimum capacity needed to store maximum `solar_generation`.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments parsed to `electrical_storage` `autosize` function.
"""
self.electrical_storage.autosize(self.pv.get_generation(self.energy_simulation.solar_generation), **kwargs)
def autosize_pv(self, **kwargs):
"""Autosize `PV` `nominal_pwer` to minimum nominal_power needed to output maximum `solar_generation`.
Other Parameters
----------------
**kwargs : dict
Other keyword arguments parsed to `electrical_storage` `autosize` function.
"""
self.pv.autosize(self.pv.get_generation(self.energy_simulation.solar_generation), **kwargs)
def next_time_step(self):
r"""Advance all energy storage and electric devices and, PV to next `time_step`."""
self.cooling_device.next_time_step()
self.heating_device.next_time_step()
self.dhw_device.next_time_step()
self.cooling_storage.next_time_step()
self.heating_storage.next_time_step()
self.dhw_storage.next_time_step()
self.electrical_storage.next_time_step()
self.pv.next_time_step()
super().next_time_step()
def reset(self):
r"""Reset `Building` to initial state."""
super().reset()
self.cooling_storage.reset()
self.heating_storage.reset()
self.dhw_storage.reset()
self.electrical_storage.reset()
self.cooling_device.reset()
self.heating_device.reset()
self.dhw_device.reset()
self.pv.reset() | PypiClean |
/LongTermBiosignals-1.0.0.tar.gz/LongTermBiosignals-1.0.0/src/biosignals/sources/HEM.py |
# ===================================
# IT - LongTermBiosignals
# Package: biosignals
# Module: HEM
# Description: Class HEM, a type of BiosignalSource, with static procedures to read and write datafiles from
# Hospital Egas Moniz, Portugal.
# Contributors: João Saraiva, Mariana Abreu
# Created: 25/04/2022
# Last Updated: 22/07/2022
# ===================================
from os import listdir, path
from neo import MicromedIO
from numpy import array
from biosignals.modalities.ECG import ECG
from biosignals.sources.BiosignalSource import BiosignalSource
from biosignals.timeseries.Timeseries import Timeseries
class HEM(BiosignalSource):
'''This class represents the source of Hospital de Santa Maria (Lisboa, PT) and includes methods to read and write
biosignal files provided by them. Usually they are in the European EDF/EDF+ format.'''
def __init__(self):
super().__init__()
def __str__(self):
return "Hospital Egas Moniz"
@staticmethod
def __read_trc(list, metadata=False):
"""
Return trc file information, whether it is the values or the metadata, according to boolean metadata
:param list
:param metadata
"""
dirfile = list[0]
sensor = list[1]
# get edf data
seg_micromed = MicromedIO(dirfile)
hem_data = seg_micromed.read_segment()
hem_sig = hem_data.analogsignals[0]
ch_list = seg_micromed.header['signal_channels']['name']
# get channels that correspond to type (POL Ecg = type ecg)
find_idx = [hch for hch in range(len(ch_list)) if sensor.lower() in ch_list[hch].lower()]
# returns ch_list of interest, sampling frequency, initial datetime
if metadata:
return ch_list[find_idx], float(hem_sig.sampling_rate), hem_data.rec_datetime, hem_sig.units
# returns initial date and samples
return array(hem_sig[:, find_idx].T), hem_data.rec_datetime
@staticmethod
def _read(dir, type, **options):
'''Reads multiple EDF/EDF+ files on the directory 'path' and returns a Biosignal associated with a Patient.'''
# first a list is created with all the filenames that end in .edf and are inside the chosen dir
# this is a list of lists where the second column is the type of channel to extract
if type is ECG:
label = 'ecg'
# if type is EEG:
# label = 'eeg'
all_files = sorted([[path.join(dir, file), label] for file in listdir(dir) if file.lower().endswith('.trc')])
# run the edf read function for all files in list all_files
channels, sfreq, start_datetime, units = HEM.__read_trc(all_files[0], metadata=True)
all_trc = list(map(HEM.__read_trc, all_files))
# run the trc read function for all files in list all_files
new_dict = {}
# TODO ADD UNITS TO TIMESERIES
for ch in range(len(channels)):
segments = {trc_data[1]: trc_data[0][ch] for trc_data in all_trc}
if len(segments) > 1:
new_timeseries = Timeseries.withDiscontiguousSegments(segments, sampling_frequency=sfreq, name=channels[ch])
else:
new_timeseries = Timeseries(tuple(segments.values())[0], tuple(segments.keys())[0], sfreq, name=channels[ch])
new_dict[channels[ch]] = new_timeseries
return new_dict
@staticmethod
def _write(path: str, timeseries: dict):
pass
@staticmethod
def _transfer(samples, to_unit):
pass | PypiClean |
/Nuitka_winsvc-1.7.10-cp310-cp310-win_amd64.whl/nuitka/build/inline_copy/lib/scons-4.3.0/SCons/Tool/MSCommon/vc.py | import SCons.compat
import SCons.Util
import subprocess
import os
import platform
from string import digits as string_digits
from subprocess import PIPE
import SCons.Warnings
from SCons.Tool import find_program_path
from . import common
from .common import CONFIG_CACHE, debug
from .sdk import get_installed_sdks
class VisualCException(Exception):
pass
class UnsupportedVersion(VisualCException):
pass
class MSVCUnsupportedHostArch(VisualCException):
pass
class MSVCUnsupportedTargetArch(VisualCException):
pass
class MissingConfiguration(VisualCException):
pass
class NoVersionFound(VisualCException):
pass
class BatchFileExecutionError(VisualCException):
pass
# Dict to 'canonalize' the arch
_ARCH_TO_CANONICAL = {
"amd64" : "amd64",
"emt64" : "amd64",
"i386" : "x86",
"i486" : "x86",
"i586" : "x86",
"i686" : "x86",
"ia64" : "ia64", # deprecated
"itanium" : "ia64", # deprecated
"x86" : "x86",
"x86_64" : "amd64",
"arm" : "arm",
"arm64" : "arm64",
"aarch64" : "arm64",
}
# Starting with 14.1 (aka VS2017), the tools are organized by host directory.
# subdirs for each target. They are now in .../VC/Auxuiliary/Build.
# Note 2017 Express uses Hostx86 even if it's on 64-bit Windows,
# not reflected in this table.
_HOST_TARGET_TO_CL_DIR_GREATER_THAN_14 = {
("arm64","arm64") : ("Hostarm64","arm64"),
("amd64","amd64") : ("Hostx64","x64"),
("amd64","x86") : ("Hostx64","x86"),
("amd64","arm") : ("Hostx64","arm"),
("amd64","arm64") : ("Hostx64","arm64"),
("x86","amd64") : ("Hostx86","x64"),
("x86","x86") : ("Hostx86","x86"),
("x86","arm") : ("Hostx86","arm"),
("x86","arm64") : ("Hostx86","arm64"),
}
# before 14.1 (VS2017): the original x86 tools are in the tools dir,
# any others are in a subdir named by the host/target pair,
# or just a single word if host==target
_HOST_TARGET_TO_CL_DIR = {
("amd64","amd64") : "amd64",
("amd64","x86") : "amd64_x86",
("amd64","arm") : "amd64_arm",
("amd64","arm64") : "amd64_arm64",
("x86","amd64") : "x86_amd64",
("x86","x86") : "",
("x86","arm") : "x86_arm",
("x86","arm64") : "x86_arm64",
("arm","arm") : "arm",
}
# 14.1 (VS2017) and later:
# Given a (host, target) tuple, return the batch file to look for.
# We can't rely on returning an arg to use for vcvarsall.bat,
# because that script will run even if given a pair that isn't installed.
# Targets that already look like a pair are pseudo targets that
# effectively mean to skip whatever the host was specified as.
_HOST_TARGET_TO_BAT_ARCH_GT14 = {
("arm64", "arm64"): "vcvarsarm64.bat",
("amd64", "amd64"): "vcvars64.bat",
("amd64", "x86"): "vcvarsamd64_x86.bat",
("amd64", "x86_amd64"): "vcvarsx86_amd64.bat",
("amd64", "x86_x86"): "vcvars32.bat",
("amd64", "arm"): "vcvarsamd64_arm.bat",
("amd64", "x86_arm"): "vcvarsx86_arm.bat",
("amd64", "arm64"): "vcvarsamd64_arm64.bat",
("amd64", "x86_arm64"): "vcvarsx86_arm64.bat",
("x86", "x86"): "vcvars32.bat",
("x86", "amd64"): "vcvarsx86_amd64.bat",
("x86", "x86_amd64"): "vcvarsx86_amd64.bat",
("x86", "arm"): "vcvarsx86_arm.bat",
("x86", "x86_arm"): "vcvarsx86_arm.bat",
("x86", "arm64"): "vcvarsx86_arm64.bat",
("x86", "x86_arm64"): "vcvarsx86_arm64.bat",
}
# before 14.1 (VS2017):
# Given a (host, target) tuple, return the argument for the bat file;
# Both host and target should be canoncalized.
# If the target already looks like a pair, return it - these are
# pseudo targets (mainly used by Express versions)
_HOST_TARGET_ARCH_TO_BAT_ARCH = {
("x86", "x86"): "x86",
("x86", "amd64"): "x86_amd64",
("x86", "x86_amd64"): "x86_amd64",
("amd64", "x86_amd64"): "x86_amd64", # This is present in (at least) VS2012 express
("amd64", "amd64"): "amd64",
("amd64", "x86"): "x86",
("amd64", "x86_x86"): "x86",
("x86", "ia64"): "x86_ia64", # gone since 14.0
("x86", "arm"): "x86_arm", # since 14.0
("x86", "arm64"): "x86_arm64", # since 14.1
("amd64", "arm"): "amd64_arm", # since 14.0
("amd64", "arm64"): "amd64_arm64", # since 14.1
("x86", "x86_arm"): "x86_arm", # since 14.0
("x86", "x86_arm64"): "x86_arm64", # since 14.1
("amd64", "x86_arm"): "x86_arm", # since 14.0
("amd64", "x86_arm64"): "x86_arm64", # since 14.1
("arm64", "arm64"): "arm64_arm64", # since 14.3
}
_CL_EXE_NAME = 'cl.exe'
def get_msvc_version_numeric(msvc_version):
"""Get the raw version numbers from a MSVC_VERSION string, so it
could be cast to float or other numeric values. For example, '14.0Exp'
would get converted to '14.0'.
Args:
msvc_version: str
string representing the version number, could contain non
digit characters
Returns:
str: the value converted to a numeric only string
"""
return ''.join([x for x in msvc_version if x in string_digits + '.'])
def get_host_target(env):
host_platform = env.get('HOST_ARCH')
debug("HOST_ARCH:" + str(host_platform))
if not host_platform:
host_platform = platform.machine()
# Solaris returns i86pc for both 32 and 64 bit architectures
if host_platform == "i86pc":
if platform.architecture()[0] == "64bit":
host_platform = "amd64"
else:
host_platform = "x86"
# Retain user requested TARGET_ARCH
req_target_platform = env.get('TARGET_ARCH')
debug("TARGET_ARCH:" + str(req_target_platform))
if req_target_platform:
# If user requested a specific platform then only try that one.
target_platform = req_target_platform
else:
target_platform = host_platform
try:
host = _ARCH_TO_CANONICAL[host_platform.lower()]
except KeyError:
msg = "Unrecognized host architecture %s"
raise MSVCUnsupportedHostArch(msg % repr(host_platform))
try:
target = _ARCH_TO_CANONICAL[target_platform.lower()]
except KeyError:
all_archs = str(list(_ARCH_TO_CANONICAL.keys()))
raise MSVCUnsupportedTargetArch(
"Unrecognized target architecture %s\n\tValid architectures: %s"
% (target_platform, all_archs)
)
return (host, target, req_target_platform)
# If you update this, update SupportedVSList in Tool/MSCommon/vs.py, and the
# MSVC_VERSION documentation in Tool/msvc.xml.
_VCVER = [
"14.3",
"14.2",
"14.1", "14.1Exp",
"14.0", "14.0Exp",
"12.0", "12.0Exp",
"11.0", "11.0Exp",
"10.0", "10.0Exp",
"9.0", "9.0Exp",
"8.0", "8.0Exp",
"7.1",
"7.0",
"6.0"]
# if using vswhere, configure command line arguments to probe for installed VC editions
_VCVER_TO_VSWHERE_VER = {
'14.3': [
["-version", "[17.0, 18.0)"], # default: Enterprise, Professional, Community (order unpredictable?)
["-version", "[17.0, 18.0)", "-products", "Microsoft.VisualStudio.Product.BuildTools"], # BuildTools
],
'14.2': [
["-version", "[16.0, 17.0)"], # default: Enterprise, Professional, Community (order unpredictable?)
["-version", "[16.0, 17.0)", "-products", "Microsoft.VisualStudio.Product.BuildTools"], # BuildTools
],
'14.1': [
["-version", "[15.0, 16.0)"], # default: Enterprise, Professional, Community (order unpredictable?)
["-version", "[15.0, 16.0)", "-products", "Microsoft.VisualStudio.Product.BuildTools"], # BuildTools
],
'14.1Exp': [
["-version", "[15.0, 16.0)", "-products", "Microsoft.VisualStudio.Product.WDExpress"], # Express
],
}
_VCVER_TO_PRODUCT_DIR = {
'14.3': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'')], # not set by this version
'14.2': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'')], # not set by this version
'14.1': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'')], # not set by this version
'14.1Exp': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'')], # not set by this version
'14.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\14.0\Setup\VC\ProductDir')],
'14.0Exp': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\14.0\Setup\VC\ProductDir')],
'12.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\12.0\Setup\VC\ProductDir'),
],
'12.0Exp': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\12.0\Setup\VC\ProductDir'),
],
'11.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\11.0\Setup\VC\ProductDir'),
],
'11.0Exp': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\11.0\Setup\VC\ProductDir'),
],
'10.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\10.0\Setup\VC\ProductDir'),
],
'10.0Exp': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\10.0\Setup\VC\ProductDir'),
],
'9.0': [
(SCons.Util.HKEY_CURRENT_USER, r'Microsoft\DevDiv\VCForPython\9.0\installdir',),
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\9.0\Setup\VC\ProductDir',),
],
'9.0Exp': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir'),
],
'8.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir'),
],
'8.0Exp': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir'),
],
'7.1': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\7.1\Setup\VC\ProductDir'),
],
'7.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\7.0\Setup\VC\ProductDir'),
],
'6.0': [
(SCons.Util.HKEY_LOCAL_MACHINE, r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir'),
]
}
def msvc_version_to_maj_min(msvc_version):
msvc_version_numeric = get_msvc_version_numeric(msvc_version)
t = msvc_version_numeric.split(".")
if not len(t) == 2:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
try:
maj = int(t[0])
min = int(t[1])
return maj, min
except ValueError as e:
raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
def is_host_target_supported(host_target, msvc_version):
"""Check if (host, target) pair is supported for a VC version.
Only checks whether a given version *may* support the given
(host, target) pair, not that the toolchain is actually on the machine.
Args:
host_target: canonalized host-target pair, e.g.
("x86", "amd64") for cross compilation from 32- to 64-bit Windows.
msvc_version: Visual C++ version (major.minor), e.g. "10.0"
Returns:
True or False
"""
# We assume that any Visual Studio version supports x86 as a target
if host_target[1] != "x86":
maj, min = msvc_version_to_maj_min(msvc_version)
if maj < 8:
return False
return True
VSWHERE_PATHS = [os.path.join(p,'vswhere.exe') for p in [
os.path.expandvars(r"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer"),
os.path.expandvars(r"%ProgramFiles%\Microsoft Visual Studio\Installer"),
os.path.expandvars(r"%ChocolateyInstall%\bin"),
]]
def msvc_find_vswhere():
""" Find the location of vswhere """
# For bug 3333: support default location of vswhere for both
# 64 and 32 bit windows installs.
# For bug 3542: also accommodate not being on C: drive.
# NB: this gets called from testsuite on non-Windows platforms.
# Whether that makes sense or not, don't break it for those.
vswhere_path = None
for pf in VSWHERE_PATHS:
if os.path.exists(pf):
vswhere_path = pf
break
return vswhere_path
def find_vc_pdir_vswhere(msvc_version, env=None):
""" Find the MSVC product directory using the vswhere program.
Args:
msvc_version: MSVC version to search for
env: optional to look up VSWHERE variable
Returns:
MSVC install dir or None
Raises:
UnsupportedVersion: if the version is not known by this file
"""
try:
vswhere_version = _VCVER_TO_VSWHERE_VER[msvc_version]
except KeyError:
debug("Unknown version of MSVC: %s" % msvc_version)
raise UnsupportedVersion("Unknown version %s" % msvc_version)
if env is None or not env.get('VSWHERE'):
vswhere_path = msvc_find_vswhere()
else:
vswhere_path = env.subst('$VSWHERE')
if vswhere_path is None:
return None
debug('VSWHERE: %s' % vswhere_path)
for vswhere_version_args in vswhere_version:
vswhere_cmd = [vswhere_path] + vswhere_version_args + ["-property", "installationPath"]
debug("running: %s" % vswhere_cmd)
#cp = subprocess.run(vswhere_cmd, capture_output=True) # 3.7+ only
cp = subprocess.run(vswhere_cmd, stdout=PIPE, stderr=PIPE)
if cp.stdout:
# vswhere could return multiple lines, e.g. if Build Tools
# and {Community,Professional,Enterprise} are both installed.
# We could define a way to pick the one we prefer, but since
# this data is currently only used to make a check for existence,
# returning the first hit should be good enough.
lines = cp.stdout.decode("mbcs").splitlines()
return os.path.join(lines[0], 'VC')
else:
# We found vswhere, but no install info available for this version
pass
return None
def find_vc_pdir(env, msvc_version):
"""Find the MSVC product directory for the given version.
Tries to look up the path using a registry key from the table
_VCVER_TO_PRODUCT_DIR; if there is no key, calls find_vc_pdir_wshere
for help instead.
Args:
msvc_version: str
msvc version (major.minor, e.g. 10.0)
Returns:
str: Path found in registry, or None
Raises:
UnsupportedVersion: if the version is not known by this file.
MissingConfiguration: found version but the directory is missing.
Both exceptions inherit from VisualCException.
"""
root = 'Software\\'
try:
hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version]
except KeyError:
debug("Unknown version of MSVC: %s" % msvc_version)
raise UnsupportedVersion("Unknown version %s" % msvc_version)
for hkroot, key in hkeys:
try:
comps = None
if not key:
comps = find_vc_pdir_vswhere(msvc_version, env)
if not comps:
debug('no VC found for version {}'.format(repr(msvc_version)))
raise OSError
debug('VC found: {}'.format(repr(msvc_version)))
return comps
else:
if common.is_win64():
try:
# ordinarily at win64, try Wow6432Node first.
comps = common.read_reg(root + 'Wow6432Node\\' + key, hkroot)
except OSError:
# at Microsoft Visual Studio for Python 2.7, value is not in Wow6432Node
pass
if not comps:
# not Win64, or Microsoft Visual Studio for Python 2.7
comps = common.read_reg(root + key, hkroot)
except OSError:
debug('no VC registry key {}'.format(repr(key)))
else:
debug('found VC in registry: {}'.format(comps))
if os.path.exists(comps):
return comps
else:
debug('reg says dir is {}, but it does not exist. (ignoring)'.format(comps))
raise MissingConfiguration("registry dir {} not found on the filesystem".format(comps))
return None
def find_batch_file(env,msvc_version,host_arch,target_arch):
"""
Find the location of the batch script which should set up the compiler
for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress
In newer (2017+) compilers, make use of the fact there are vcvars
scripts named with a host_target pair that calls vcvarsall.bat properly,
so use that and return an indication we don't need the argument
we would have computed to run vcvarsall.bat.
"""
pdir = find_vc_pdir(env, msvc_version)
if pdir is None:
raise NoVersionFound("No version of Visual Studio found")
debug('looking in {}'.format(pdir))
# filter out e.g. "Exp" from the version name
msvc_ver_numeric = get_msvc_version_numeric(msvc_version)
use_arg = True
vernum = float(msvc_ver_numeric)
if 7 <= vernum < 8:
pdir = os.path.join(pdir, os.pardir, "Common7", "Tools")
batfilename = os.path.join(pdir, "vsvars32.bat")
elif vernum < 7:
pdir = os.path.join(pdir, "Bin")
batfilename = os.path.join(pdir, "vcvars32.bat")
elif 8 <= vernum <= 14:
batfilename = os.path.join(pdir, "vcvarsall.bat")
else: # vernum >= 14.1 VS2017 and above
batfiledir = os.path.join(pdir, "Auxiliary", "Build")
targ = _HOST_TARGET_TO_BAT_ARCH_GT14[(host_arch, target_arch)]
batfilename = os.path.join(batfiledir, targ)
use_arg = False
if not os.path.exists(batfilename):
debug("Not found: %s" % batfilename)
batfilename = None
installed_sdks = get_installed_sdks()
for _sdk in installed_sdks:
sdk_bat_file = _sdk.get_sdk_vc_script(host_arch,target_arch)
if not sdk_bat_file:
debug("batch file not found:%s" % _sdk)
else:
sdk_bat_file_path = os.path.join(pdir,sdk_bat_file)
if os.path.exists(sdk_bat_file_path):
debug('sdk_bat_file_path:%s' % sdk_bat_file_path)
return (batfilename, use_arg, sdk_bat_file_path)
return (batfilename, use_arg, None)
__INSTALLED_VCS_RUN = None
_VC_TOOLS_VERSION_FILE_PATH = ['Auxiliary', 'Build', 'Microsoft.VCToolsVersion.default.txt']
_VC_TOOLS_VERSION_FILE = os.sep.join(_VC_TOOLS_VERSION_FILE_PATH)
def _check_cl_exists_in_vc_dir(env, vc_dir, msvc_version):
"""Return status of finding a cl.exe to use.
Locates cl in the vc_dir depending on TARGET_ARCH, HOST_ARCH and the
msvc version. TARGET_ARCH and HOST_ARCH can be extracted from the
passed env, unless it is None, in which case the native platform is
assumed for both host and target.
Args:
env: Environment
a construction environment, usually if this is passed its
because there is a desired TARGET_ARCH to be used when searching
for a cl.exe
vc_dir: str
the path to the VC dir in the MSVC installation
msvc_version: str
msvc version (major.minor, e.g. 10.0)
Returns:
bool:
"""
# determine if there is a specific target platform we want to build for and
# use that to find a list of valid VCs, default is host platform == target platform
# and same for if no env is specified to extract target platform from
if env:
(host_platform, target_platform, req_target_platform) = get_host_target(env)
else:
host_platform = platform.machine().lower()
target_platform = host_platform
host_platform = _ARCH_TO_CANONICAL[host_platform]
target_platform = _ARCH_TO_CANONICAL[target_platform]
debug('host platform %s, target platform %s for version %s' % (host_platform, target_platform, msvc_version))
ver_num = float(get_msvc_version_numeric(msvc_version))
# make sure the cl.exe exists meaning the tool is installed
if ver_num > 14:
# 2017 and newer allowed multiple versions of the VC toolset to be
# installed at the same time. This changes the layout.
# Just get the default tool version for now
#TODO: support setting a specific minor VC version
default_toolset_file = os.path.join(vc_dir, _VC_TOOLS_VERSION_FILE)
try:
with open(default_toolset_file) as f:
vc_specific_version = f.readlines()[0].strip()
except IOError:
debug('failed to read ' + default_toolset_file)
return False
except IndexError:
debug('failed to find MSVC version in ' + default_toolset_file)
return False
host_trgt_dir = _HOST_TARGET_TO_CL_DIR_GREATER_THAN_14.get((host_platform, target_platform), None)
if host_trgt_dir is None:
debug('unsupported host/target platform combo: (%s,%s)'%(host_platform, target_platform))
return False
cl_path = os.path.join(vc_dir, 'Tools','MSVC', vc_specific_version, 'bin', host_trgt_dir[0], host_trgt_dir[1], _CL_EXE_NAME)
debug('checking for ' + _CL_EXE_NAME + ' at ' + cl_path)
if os.path.exists(cl_path):
debug('found ' + _CL_EXE_NAME + '!')
return True
elif host_platform == "amd64" and host_trgt_dir[0] == "Hostx64":
# Special case: fallback to Hostx86 if Hostx64 was tried
# and failed. This is because VS 2017 Express running on amd64
# will look to our probe like the host dir should be Hostx64,
# but Express uses Hostx86 anyway.
# We should key this off the "x86_amd64" and related pseudo
# targets, but we don't see those in this function.
host_trgt_dir = ("Hostx86", host_trgt_dir[1])
cl_path = os.path.join(vc_dir, 'Tools','MSVC', vc_specific_version, 'bin', host_trgt_dir[0], host_trgt_dir[1], _CL_EXE_NAME)
debug('checking for ' + _CL_EXE_NAME + ' at ' + cl_path)
if os.path.exists(cl_path):
debug('found ' + _CL_EXE_NAME + '!')
return True
elif 14 >= ver_num >= 8:
# Set default value to be -1 as "", which is the value for x86/x86,
# yields true when tested if not host_trgt_dir
host_trgt_dir = _HOST_TARGET_TO_CL_DIR.get((host_platform, target_platform), None)
if host_trgt_dir is None:
debug('unsupported host/target platform combo')
return False
cl_path = os.path.join(vc_dir, 'bin', host_trgt_dir, _CL_EXE_NAME)
debug('checking for ' + _CL_EXE_NAME + ' at ' + cl_path)
cl_path_exists = os.path.exists(cl_path)
if not cl_path_exists and host_platform == 'amd64':
# older versions of visual studio only had x86 binaries,
# so if the host platform is amd64, we need to check cross
# compile options (x86 binary compiles some other target on a 64 bit os)
# Set default value to be -1 as "" which is the value for x86/x86 yields true when tested
# if not host_trgt_dir
host_trgt_dir = _HOST_TARGET_TO_CL_DIR.get(('x86', target_platform), None)
if host_trgt_dir is None:
return False
cl_path = os.path.join(vc_dir, 'bin', host_trgt_dir, _CL_EXE_NAME)
debug('checking for ' + _CL_EXE_NAME + ' at ' + cl_path)
cl_path_exists = os.path.exists(cl_path)
if cl_path_exists:
debug('found ' + _CL_EXE_NAME + '!')
return True
elif 8 > ver_num >= 6:
# quick check for vc_dir/bin and vc_dir/ before walk
# need to check root as the walk only considers subdirectories
for cl_dir in ('bin', ''):
cl_path = os.path.join(vc_dir, cl_dir, _CL_EXE_NAME)
if os.path.exists(cl_path):
debug(_CL_EXE_NAME + ' found %s' % cl_path)
return True
# not in bin or root: must be in a subdirectory
for cl_root, cl_dirs, _ in os.walk(vc_dir):
for cl_dir in cl_dirs:
cl_path = os.path.join(cl_root, cl_dir, _CL_EXE_NAME)
if os.path.exists(cl_path):
debug(_CL_EXE_NAME + ' found %s' % cl_path)
return True
return False
else:
# version not support return false
debug('unsupported MSVC version: ' + str(ver_num))
return False
def get_installed_vcs(env=None):
global __INSTALLED_VCS_RUN
if __INSTALLED_VCS_RUN is not None:
return __INSTALLED_VCS_RUN
installed_versions = []
for ver in _VCVER:
debug('trying to find VC %s' % ver)
try:
VC_DIR = find_vc_pdir(env, ver)
if VC_DIR:
debug('found VC %s' % ver)
if _check_cl_exists_in_vc_dir(env, VC_DIR, ver):
installed_versions.append(ver)
else:
debug('no compiler found %s' % ver)
else:
debug('return None for ver %s' % ver)
except (MSVCUnsupportedTargetArch, MSVCUnsupportedHostArch):
# Allow this exception to propagate further as it should cause
# SCons to exit with an error code
raise
except VisualCException as e:
debug('did not find VC %s: caught exception %s' % (ver, str(e)))
__INSTALLED_VCS_RUN = installed_versions
return __INSTALLED_VCS_RUN
def reset_installed_vcs():
"""Make it try again to find VC. This is just for the tests."""
global __INSTALLED_VCS_RUN
__INSTALLED_VCS_RUN = None
# Running these batch files isn't cheap: most of the time spent in
# msvs.generate() is due to vcvars*.bat. In a build that uses "tools='msvs'"
# in multiple environments, for example:
# env1 = Environment(tools='msvs')
# env2 = Environment(tools='msvs')
# we can greatly improve the speed of the second and subsequent Environment
# (or Clone) calls by memoizing the environment variables set by vcvars*.bat.
#
# Updated: by 2018, vcvarsall.bat had gotten so expensive (vs2017 era)
# it was breaking CI builds because the test suite starts scons so many
# times and the existing memo logic only helped with repeated calls
# within the same scons run. Windows builds on the CI system were split
# into chunks to get around single-build time limits.
# With VS2019 it got even slower and an optional persistent cache file
# was introduced. The cache now also stores only the parsed vars,
# not the entire output of running the batch file - saves a bit
# of time not parsing every time.
script_env_cache = None
def script_env(script, args=None):
global script_env_cache
if script_env_cache is None:
script_env_cache = common.read_script_env_cache()
cache_key = "{}--{}".format(script, args)
cache_data = script_env_cache.get(cache_key, None)
if cache_data is None:
stdout = common.get_output(script, args)
# Stupid batch files do not set return code: we take a look at the
# beginning of the output for an error message instead
olines = stdout.splitlines()
if olines[0].startswith("The specified configuration type is missing"):
raise BatchFileExecutionError("\n".join(olines[:2]))
cache_data = common.parse_output(stdout)
script_env_cache[cache_key] = cache_data
# once we updated cache, give a chance to write out if user wanted
common.write_script_env_cache(script_env_cache)
return cache_data
def get_default_version(env):
msvc_version = env.get('MSVC_VERSION')
msvs_version = env.get('MSVS_VERSION')
debug('msvc_version:%s msvs_version:%s' % (msvc_version, msvs_version))
if msvs_version and not msvc_version:
SCons.Warnings.warn(
SCons.Warnings.DeprecatedWarning,
"MSVS_VERSION is deprecated: please use MSVC_VERSION instead ")
return msvs_version
elif msvc_version and msvs_version:
if not msvc_version == msvs_version:
SCons.Warnings.warn(
SCons.Warnings.VisualVersionMismatch,
"Requested msvc version (%s) and msvs version (%s) do " \
"not match: please use MSVC_VERSION only to request a " \
"visual studio version, MSVS_VERSION is deprecated" \
% (msvc_version, msvs_version))
return msvs_version
if not msvc_version:
installed_vcs = get_installed_vcs(env)
debug('installed_vcs:%s' % installed_vcs)
if not installed_vcs:
#msg = 'No installed VCs'
#debug('msv %s' % repr(msg))
#SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, msg)
debug('No installed VCs')
return None
msvc_version = installed_vcs[0]
debug('using default installed MSVC version %s' % repr(msvc_version))
else:
debug('using specified MSVC version %s' % repr(msvc_version))
return msvc_version
def msvc_setup_env_once(env):
try:
has_run = env["MSVC_SETUP_RUN"]
except KeyError:
has_run = False
if not has_run:
msvc_setup_env(env)
env["MSVC_SETUP_RUN"] = True
def msvc_find_valid_batch_script(env, version):
"""Find and execute appropriate batch script to set up build env.
The MSVC build environment depends heavily on having the shell
environment set. SCons does not inherit that, and does not count
on that being set up correctly anyway, so it tries to find the right
MSVC batch script, or the right arguments to the generic batch script
vcvarsall.bat, and run that, so we have a valid environment to build in.
There are dragons here: the batch scripts don't fail (see comments
elsewhere), they just leave you with a bad setup, so try hard to
get it right.
"""
# Find the host, target, and if present the requested target:
platforms = get_host_target(env)
debug("host_platform %s, target_platform %s req_target_platform %s" % platforms)
host_platform, target_platform, req_target_platform = platforms
# Most combinations of host + target are straightforward.
# While all MSVC / Visual Studio tools are pysically 32-bit, they
# make it look like there are 64-bit tools if the host is 64-bit,
# so you can invoke the environment batch script to set up to build,
# say, amd64 host -> x86 target. Express versions are an exception:
# they always look 32-bit, so the batch scripts with 64-bit
# host parts are absent. We try to fix that up in a couple of ways.
# One is here: we make a table of "targets" to try, with the extra
# targets being tags that tell us to try a different "host" instead
# of the deduced host.
try_target_archs = [target_platform]
if req_target_platform in ('amd64', 'x86_64'):
try_target_archs.append('x86_amd64')
elif req_target_platform in ('x86',):
try_target_archs.append('x86_x86')
elif req_target_platform in ('arm',):
try_target_archs.append('x86_arm')
elif req_target_platform in ('arm64',):
try_target_archs.append('x86_arm64')
elif not req_target_platform:
if target_platform in ('amd64', 'x86_64'):
try_target_archs.append('x86_amd64')
# If the user hasn't specifically requested a TARGET_ARCH,
# and the TARGET_ARCH is amd64 then also try 32 bits
# if there are no viable 64 bit tools installed
try_target_archs.append('x86')
debug("host_platform: %s, try_target_archs: %s"%(host_platform, try_target_archs))
d = None
for tp in try_target_archs:
# Set to current arch.
env['TARGET_ARCH'] = tp
debug("trying target_platform:%s" % tp)
host_target = (host_platform, tp)
if not is_host_target_supported(host_target, version):
warn_msg = "host, target = %s not supported for MSVC version %s" % \
(host_target, version)
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target]
# Try to locate a batch file for this host/target platform combo
try:
(vc_script, use_arg, sdk_script) = find_batch_file(env, version, host_platform, tp)
debug('vc_script:%s sdk_script:%s'%(vc_script,sdk_script))
except VisualCException as e:
msg = str(e)
debug('Caught exception while looking for batch file (%s)' % msg)
warn_msg = "VC version %s not installed. " + \
"C/C++ compilers are most likely not set correctly.\n" + \
" Installed versions are: %s"
warn_msg = warn_msg % (version, get_installed_vcs(env))
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
continue
# Try to use the located batch file for this host/target platform combo
debug('use_script 2 %s, args:%s' % (repr(vc_script), arg))
found = None
if vc_script:
if not use_arg:
arg = '' # bat file will supply platform type
# Get just version numbers
maj, min = msvc_version_to_maj_min(version)
# VS2015+
if maj >= 14:
if env.get('MSVC_UWP_APP') == '1':
# Initialize environment variables with store/UWP paths
arg = (arg + ' store').lstrip()
try:
d = script_env(vc_script, args=arg)
found = vc_script
except BatchFileExecutionError as e:
debug('use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e))
vc_script=None
continue
if not vc_script and sdk_script:
debug('use_script 4: trying sdk script: %s' % sdk_script)
try:
d = script_env(sdk_script)
found = sdk_script
except BatchFileExecutionError as e:
debug('use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script), e))
continue
elif not vc_script and not sdk_script:
debug('use_script 6: Neither VC script nor SDK script found')
continue
debug("Found a working script/target: %s/%s"%(repr(found),arg))
break # We've found a working target_platform, so stop looking
# If we cannot find a viable installed compiler, reset the TARGET_ARCH
# To it's initial value
if not d:
env['TARGET_ARCH']=req_target_platform
return d
def msvc_setup_env(env):
debug('called')
version = get_default_version(env)
if version is None:
warn_msg = "No version of Visual Studio compiler found - C/C++ " \
"compilers most likely not set correctly"
# Nuitka: Useless warning for us.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
# XXX: we set-up both MSVS version for backward
# compatibility with the msvs tool
env['MSVC_VERSION'] = version
env['MSVS_VERSION'] = version
env['MSVS'] = {}
use_script = env.get('MSVC_USE_SCRIPT', True)
if SCons.Util.is_String(use_script):
debug('use_script 1 %s' % repr(use_script))
d = script_env(use_script)
elif use_script:
d = msvc_find_valid_batch_script(env,version)
debug('use_script 2 %s' % d)
if not d:
return d
else:
debug('MSVC_USE_SCRIPT set to False')
warn_msg = "MSVC_USE_SCRIPT set to False, assuming environment " \
"set correctly."
# Nuitka: We use this on purpose.
# SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
return None
for k, v in d.items():
# Nuitka: Make the Windows SDK version visible in environment.
if k == "WindowsSDKVersion":
# Always just a single version if any.
if len(v) == 1:
env["WindowsSDKVersion"] = v[0].rstrip('\\')
elif len(v) == 0:
env["WindowsSDKVersion"] = None
else:
assert False, v
continue
env.PrependENVPath(k, v, delete_existing=True)
debug("env['ENV']['%s'] = %s" % (k, env['ENV'][k]))
# final check to issue a warning if the compiler is not present
if not find_program_path(env, 'cl'):
debug("did not find " + _CL_EXE_NAME)
if CONFIG_CACHE:
propose = "SCONS_CACHE_MSVC_CONFIG caching enabled, remove cache file {} if out of date.".format(CONFIG_CACHE)
else:
propose = "It may need to be installed separately with Visual Studio."
warn_msg = "Could not find MSVC compiler 'cl'. {}".format(propose)
SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
def msvc_exists(env=None, version=None):
vcs = get_installed_vcs(env)
if version is None:
return len(vcs) > 0
return version in vcs | PypiClean |
/mutation_simulator-3.0.1-py3-none-any.whl/mutation_simulator/it_mutator.py | from __future__ import annotations
from random import choice, shuffle
from typing import TYPE_CHECKING, Tuple
from tqdm import tqdm
from .bedpe_writer import BedpeWriter
from .fasta_writer import FastaWriter
from .util import pairwise, print_warning, sample_with_minimum_distance
if TYPE_CHECKING:
from argparse import Namespace
from pyfaidx import Fasta
from .rmt import SimulationSettings
class ITMutator:
"""Stores required data for the simulation and performs interchromosomal
translocations.
"""
def __init__(self, args: Namespace, fasta: Fasta, sim: SimulationSettings):
"""Constructor.
:param args: Commandline arguments
:param fasta: Fasta file used in the simulation
:param sim: Generated SimulationSettings from args, it or rmt mode
"""
self.__args = args
self.__fasta = fasta
self.__sim = sim
self.__fasta_writer = FastaWriter(args.outfastait)
self.__bedpe_writer = BedpeWriter(args.outbedpe)
self.__find_avail_chroms()
self.__assign_parters()
def __del__(self):
self.close()
def close(self):
"""Closes the fasta_writer and bedpe_writer filehandles. Does not close
the fasta.
"""
self.__fasta_writer.close()
self.__bedpe_writer.close()
def __find_avail_chroms(self):
"""Finds all chromosomes elligeble for interchromosomal translocations."""
self.__avail_chroms = [
chrom.number for chrom in self.__sim.chromosomes if
chrom.it_rate is not None # intentional is comparison, 0 is ok
and len(self.__fasta[chrom.number]) > 2
]
def __assign_parters(self):
"""Assigns a random unique partner to all chromosomes."""
self.__partners = {}
remain_chr = self.__avail_chroms
shuffle(self.__avail_chroms)
for chrom in self.__avail_chroms:
remain_chr.remove(chrom)
if remain_chr:
partner = choice(remain_chr)
self.__partners[partner] = chrom
self.__partners[chrom] = partner
remain_chr.remove(partner)
def __get_pairs_to_mut_once(self) -> list[int]:
"""Returns every chromosome pair to mutate only once. (1,2) will not
get returned a second time as (2,1) which would normally be the case.
:return chroms: List of chromosome indices
"""
chroms = list(self.__partners.keys())
for chrom, partner in self.__partners.items():
if chrom in chroms:
chroms.remove(partner)
return chroms
def __get_bp_amount(self, seq_len1: int, rate1: float, seq_len2: int,
rate2: float) -> int:
"""Get the amount of breakpoints.
:param seq_len1: Length of sequence 1
:param rate1: It rate for sequence 1
:param seq_len2: Length of sequence 2
:param rate2: It rate for sequence 2
:return breakpoint_amount: Number of breakpoints to generate
"""
return int((seq_len1 + seq_len2 - 4) / 2 * ((rate1 + rate2) / 2))
def __get_breakpoints(self, chrom: int, seq_len1: int, seq_len2: int,
bp_amount: int) -> Tuple[list[int], list[int]]:
"""Generates the given amount of breakpoints on each sequence when
possible.
:param chrom: Chromosome index
:param seq_len1: Length of sequence 1
:param seq_len2: Length of sequence 2
:param bp_amount: Number of breakpoints to generate
:return bp_chrom: Breakpoints for sequence 1
:return bp_partner: Breakpoints for sequence 2
"""
bp_chrom = []
bp_partner = []
try:
# Keep 1 base at least inbetween breakpoints
bp_chrom = sorted(
sample_with_minimum_distance(seq_len1, bp_amount, 1))
bp_partner = sorted(
sample_with_minimum_distance(seq_len2, bp_amount, 1))
except ValueError:
if not self.__args.ignore_warnings:
print_warning(
f"Interchromosomal translocation rate too high for sequence {chrom+1} and {self.__partners[chrom]+1}.",
self.__args.no_color)
return bp_chrom, bp_partner
def __write_with_bp(self, chrom: str, bp_chrom: list[int], chrom_len: int,
partner: str, bp_partner: list[int], partner_len: int):
"""Writes a chromosome to the opened Fasta file with breakpoints.
:param chrom: Name of the first chromosome
:param bp_chrom: Breakpoints of the first chromosome
:param chrom_len: Length of the first sequence
:param partner: Name of the second chromosome
:param bp_partner: Breakpoints of the second chromosome
:param partner_len: Length of the second sequence
"""
bp_chrom = [0] + bp_chrom + [chrom_len]
bp_partner = [0] + bp_partner + [partner_len]
for i, (interval_chrom, interval_partner) in enumerate(
zip(pairwise(bp_chrom), pairwise(bp_partner))):
if i % 2:
self.__fasta_writer.write_multi(
self.__fasta.get_seq(partner, interval_partner[0] + 1,
interval_partner[1]))
else:
self.__fasta_writer.write_multi(
self.__fasta.get_seq(chrom, interval_chrom[0] + 1,
interval_chrom[1]))
def __write_chrom_full(self, chrom: int):
"""Writes a chromosome to the opened Fasta file without breakpoints.
:param chrom: Chromosome index
"""
self.__fasta_writer.set_bpl(
self.__fasta.faidx.index[self.__fasta[chrom].name].lenc)
self.__fasta_writer.write_header(self.__fasta[chrom].long_name)
self.__fasta_writer.write_multi(self.__fasta[chrom])
def __generate_all_breakpoints(self) -> dict[int, dict[str, list[int]]]:
"""Generates all breakpoints for every chromosome pair.
:return breakpoints: Dict containing all breakpoints for each
chromosome and their partners
"""
breakpoints = {}
for chrom in self.__get_pairs_to_mut_once():
bp_amount = self.__get_bp_amount(
len(self.__fasta[chrom]),
self.__sim.chromosomes[chrom].it_rate, #type:ignore
len(self.__fasta[self.__partners[chrom]]),
self.__sim.chromosomes[
self.__partners[chrom]].it_rate) #type:ignore
bp_chrom, bp_partner = self.__get_breakpoints(
chrom, len(self.__fasta[chrom]),
len(self.__fasta[self.__partners[chrom]]), bp_amount)
if (bp_chrom and bp_partner):
breakpoints[chrom] = {"self": bp_chrom, "partner": bp_partner}
breakpoints[self.__partners[chrom]] = {
"self": bp_partner,
"partner": bp_chrom
}
else:
if not self.__args.ignore_warnings:
print_warning(
f"No interchromosomal translocations could be generated between sequence {chrom+1} and {self.__partners[chrom]+1} (it rates too low).",
self.__args.no_color)
return breakpoints
def __mutate_sequence(self, breakpoints: dict[int, dict[str, list[int]]]):
"""Executes the interchromosomal translocations and writes them out.
:param breakpoints: Dict of each chrom-partner breakpoint pairs
"""
for chrom in tqdm(self.__sim.chromosomes,
desc="IT Mutating Sequences",
disable=self.__args.no_progress):
self.__fasta_writer.set_bpl(self.__fasta.faidx.index[self.__fasta[
chrom.number].name].lenc)
self.__fasta_writer.write_header(
self.__fasta[chrom.number].long_name)
if chrom.number in breakpoints:
self.__write_with_bp(
self.__fasta[chrom.number].name,
breakpoints[chrom.number]["self"],
len(self.__fasta[chrom.number]),
self.__fasta[self.__partners[chrom.number]].name,
breakpoints[chrom.number]["partner"],
len(self.__fasta[self.__partners[chrom.number]]))
self.__bedpe_writer.write(
self.__fasta[chrom.number].name,
breakpoints[chrom.number]["self"],
len(self.__fasta[chrom.number]),
self.__fasta[self.__partners[chrom.number]].name,
breakpoints[chrom.number]["partner"],
len(self.__fasta[self.__partners[chrom.number]]))
else:
self.__write_chrom_full(chrom.number)
def mutate(self):
"""Creates interchromosomal translocations using breakpoints
and writes them to a Fasta and BEDPE file.
"""
breakpoints = self.__generate_all_breakpoints()
self.__mutate_sequence(breakpoints) | PypiClean |
/GraphGit-0.2.0.tar.gz/GraphGit-0.2.0/ez_setup.py | import sys
DEFAULT_VERSION = "0.6c9"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
}
import sys, os
try: from hashlib import md5
except ImportError: from md5 import md5
def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""Automatically find/download setuptools and make it available on sys.path
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end with
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
it is not already available. If `download_delay` is specified, it should
be the number of seconds that will be paused before initiating a download,
should one be required. If an older version of setuptools is installed,
this routine will print a message to ``sys.stderr`` and raise SystemExit in
an attempt to abort the calling script.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
try:
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
except pkg_resources.DistributionNotFound:
return do_download()
def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
def update_md5(filenames):
"""Update our built-in md5 registry"""
import re
for name in filenames:
base = os.path.basename(name)
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()
data = [" %r: %r,\n" % it for it in md5_data.items()]
data.sort()
repl = "".join(data)
import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); src = f.read(); f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >>sys.stderr, "Internal error!"
sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile,'w')
f.write(src)
f.close()
if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:]) | PypiClean |
/MSOIKKG-1.0-py3-none-any.whl/flood_tool/geo.py | from numpy import array, asarray, mod, sin, cos, tan, sqrt, arctan2, floor, rad2deg, deg2rad, stack, pi
from scipy.linalg import inv
import numpy as np
__all__ = ['get_easting_northing_from_gps_lat_long',
'get_gps_lat_long_from_easting_northing']
class Ellipsoid(object):
""" Data structure for a global ellipsoid. """
def __init__(self, a, b, F_0):
self.a = a
self.b = b
self.n = (a - b) / (a + b)
self.e2 = (a ** 2 - b ** 2) / a ** 2
self.F_0 = F_0
class Datum(Ellipsoid):
""" Data structure for a global datum. """
def __init__(self, a, b, F_0, phi_0, lam_0, E_0, N_0, H):
super().__init__(a, b, F_0)
self.phi_0 = phi_0
self.lam_0 = lam_0
self.E_0 = E_0
self.N_0 = N_0
self.H = H
self.af0 = self.a * self.F_0
self.bf0 = self.b * self.F_0
def dms2rad(deg, min=0, sec=0):
"""Convert degrees, minutes, seconds to radians.
Parameters
----------
deg: array_like
Angle in degrees.
min: array_like
(optional) Angle component in minutes.
sec: array_like
(optional) Angle component in seconds.
Returns
-------
numpy.ndarray
Angle in radians.
"""
deg = asarray(deg)
return deg2rad(deg + min / 60. + sec / 3600.)
def rad2dms(rad, dms=False):
"""Convert radians to degrees, minutes, seconds.
Parameters
----------
rad: array_like
Angle in radians.
dms: bool
Use degrees, minutes, seconds format. If False, use decimal degrees.
Returns
-------
numpy.ndarray
Angle in degrees, minutes, seconds or decimal degrees.
"""
rad = asarray(rad)
deg = rad2deg(rad)
if dms:
min = 60.0 * mod(deg, 1.0)
sec = 60.0 * mod(min, 1.0)
return stack((floor(deg), floor(min), sec.round(4)))
else:
return deg
osgb36 = Datum(a=6377563.396,
b=6356256.910,
F_0=0.9996012717,
phi_0=deg2rad(49.0),
lam_0=deg2rad(-2.),
E_0=400000,
N_0=-100000,
H=24.7)
wgs84 = Ellipsoid(a=6378137,
b=6356752.3142,
F_0=0.9996)
def lat_long_to_xyz(phi, lam, rads=False, datum=osgb36):
"""Convert input latitude/longitude in a given datum into
Cartesian (x, y, z) coordinates.
Parameters
----------
phi: array_like
Latitude in degrees (if radians=False) or radians (if radians=True).
lam: array_like
Longitude in degrees (if radians=False) or radians (if radians=True).
rads: bool (optional)
If True, input latitudes and longitudes are in radians.
datum: Datum (optional)
Datum to use for conversion.
"""
if not rads:
phi = deg2rad(phi)
lam = deg2rad(lam)
nu = datum.a * datum.F_0 / sqrt(1 - datum.e2 * sin(phi) ** 2)
return array(((nu + datum.H) * cos(phi) * cos(lam),
(nu + datum.H) * cos(phi) * sin(lam),
((1 - datum.e2) * nu + datum.H) * sin(phi)))
def xyz_to_lat_long(x, y, z, rads=False, datum=osgb36):
p = sqrt(x ** 2 + y ** 2)
lam = arctan2(y, x)
phi = arctan2(z, p * (1 - datum.e2))
for _ in range(10):
nu = datum.a * datum.F_0 / sqrt(1 - datum.e2 * sin(phi) ** 2)
dnu = -datum.a * datum.F_0 * cos(phi) * sin(phi) / (1 - datum.e2 * sin(phi) ** 2) ** 1.5
f0 = (z + datum.e2 * nu * sin(phi)) / p - tan(phi)
f1 = datum.e2 * (nu ** cos(phi) + dnu * sin(phi)) / p - 1.0 / cos(phi) ** 2
phi -= f0 / f1
if not rads:
phi = rad2dms(phi)
lam = rad2dms(lam)
return phi, lam
def get_easting_northing_from_gps_lat_long(phis, lams, rads=False):
""" Get OSGB36 easting/northing from GPS latitude and longitude pairs.
Parameters
----------
phis: float/arraylike
GPS (i.e. WGS84 datum) latitude value(s)
lams: float/arrayling
GPS (i.e. WGS84 datum) longitude value(s).
rads: bool (optional)
If true, specifies input is is radians.
Returns
-------
numpy.ndarray
Easting values (in m)
numpy.ndarray
Northing values (in m)
Examples
--------
>>> get_easting_northing_from_gps_lat_long([55.5], [-1.54])
(array([429157.0]), array([623009]))
References
----------
Based on the formulas in "A guide to coordinate systems in Great Britain".
See also https://webapps.bgs.ac.uk/data/webservices/convertForm.cfm
"""
if not isinstance(phis, list) and not isinstance(phis,np.ndarray):
phis = [phis]
lams = [lams]
assert len(phis) == len(lams)
res_east = []
res_north = []
for i, phi in enumerate(phis):
lam = lams[i]
if not rads:
phi = deg2rad(phi)
lam = deg2rad(lams[i])
M = bigM(osgb36.bf0, osgb36.n, osgb36.phi_0, phi)
nu = osgb36.af0 / (sqrt(1 - (osgb36.e2 * ((sin(phi)) ** 2))))
rho = (nu * (1 - osgb36.e2)) / (1 - (osgb36.e2 * (sin(phi)) ** 2))
eta2 = (nu / rho) - 1
I = M + osgb36.N_0
II = (nu / 2) * sin(phi) * cos(phi)
III = (nu / 24) * sin(phi) * cos(phi) ** 3 * (5 - tan(phi) ** 2 + 9 * eta2)
IIIA = (nu / 720) * sin(phi) * cos(phi) ** 5 * (61 - 58 * tan(phi) ** 2 + tan(phi) ** 4)
IV = nu * cos(phi)
V = (nu / 6) * cos(phi) ** 3 * (nu / rho - tan(phi) ** 2)
VI = (nu / 120) * cos(phi) ** 5 * (
5 - 18 * tan(phi) ** 2 + tan(phi) ** 4 + 14 * eta2 - 58 * tan(phi) ** 2 * eta2)
diff = lam - osgb36.lam_0
N = I + II * diff ** 2 + III * diff ** 4 + IIIA * diff ** 6
E = osgb36.E_0 + IV * diff + V * diff ** 3 + VI * diff ** 5
res_east.append(E)
res_north.append(N)
return res_east, res_north
def bigM(bf0, n, PHI0, PHI):
"""
Compute meridional arc.
Input:
- ellipsoid semi major axis multiplied by central meridian scale factor (bf0) in meters;
- n (computed from a, b and f0);
- lat of false origin (PHI0) and initial or final latitude of point (PHI) IN RADIANS.
"""
M = bf0 * (((1 + n + ((5 / 4) * (n ** 2)) + ((5 / 4) * (n ** 3))) * (PHI - PHI0))
- (((3 * n) + (3 * (n ** 2)) + ((21 / 8) * (n ** 3))) * (sin(PHI - PHI0)) * (
cos(PHI + PHI0)))
+ ((((15 / 8) * (n ** 2)) + ((15 / 8) * (n ** 3))) * (sin(2 * (PHI - PHI0))) * (
cos(2 * (PHI + PHI0))))
- (((35 / 24) * (n ** 3)) * (sin(3 * (PHI - PHI0))) * (cos(3 * (PHI + PHI0)))))
return M
def getNewPhi(North, datum):
PHI1 = ((North - datum.N_0) / datum.af0) + datum.phi_0
M = bigM(datum.bf0, datum.n, datum.phi_0, PHI1)
# Calculate new PHI value (PHI2)
PHI2 = ((North - datum.N_0 - M) / datum.af0) + PHI1
# Iterate to get final value for InitialLat
while abs(North - datum.N_0 - M) > 0.00001:
PHI2 = ((North - datum.N_0 - M) / datum.af0) + PHI1
M = bigM(datum.bf0, datum.n, datum.phi_0, PHI2)
PHI1 = PHI2
return PHI2
def get_gps_lat_long_from_easting_northing(easts: float, norths: float, rads=False, dms=False):
""" Get OSGB36 easting/northing from GPS latitude and
longitude pairs.
Parameters
----------
east: float/arraylike
OSGB36 easting value(s) (in m).
north: float/arrayling
OSGB36 easting value(s) (in m).
rads: bool (optional)
If true, specifies ouput is radians.
dms: bool (optional)
If true, output is in degrees/minutes/seconds. Incompatible
with rads option.
Returns
-------
numpy.ndarray
GPS (i.e. WGS84 datum) latitude value(s).
numpy.ndarray
GPS (i.e. WGS84 datum) longitude value(s).
Examples
--------
>>> get_gps_lat_long_from_easting_northing([429157], [623009])
(array([55.5]), array([-1.540008]))
References
----------
Based on the formulas in "A guide to coordinate systems in Great Britain".
See also https://webapps.bgs.ac.uk/data/webservices/convertForm.cfm
"""
if not isinstance(easts, list) and not isinstance(easts,np.ndarray):
easts = [easts]
norths = [norths]
assert len(easts) == len(norths)
res_lat = []
res_lon = []
for i, east in enumerate(easts):
north = norths[i]
Et = east - osgb36.E_0
PHId = getNewPhi(north, datum=osgb36)
nu = osgb36.af0 / (sqrt(1 - (osgb36.e2 * ((sin(PHId)) ** 2))))
rho = (nu * (1 - osgb36.e2)) / (1 - (osgb36.e2 * (sin(PHId)) ** 2))
eta2 = (nu / rho) - 1
# Compute Latitude
VII = (tan(PHId)) / (2 * rho * nu)
VIII = ((tan(PHId)) / (24 * rho * (nu ** 3))) * (
5 + (3 * ((tan(PHId)) ** 2)) + eta2 - (9 * eta2 * ((tan(PHId)) ** 2)))
IX = ((tan(PHId)) / (720 * rho * (nu ** 5))) * (
61 + (90 * ((tan(PHId)) ** 2)) + (45 * ((tan(PHId)) ** 4)))
X = ((cos(PHId)) ** -1) / nu
XI = (((cos(PHId)) ** -1) / (6 * (nu ** 3))) * ((nu / rho) + (2 * ((tan(PHId)) ** 2)))
XII = (((cos(PHId)) ** -1) / (120 * (nu ** 5))) * (
5 + (28 * ((tan(PHId)) ** 2)) + (24 * ((tan(PHId)) ** 4)))
XIIA = (((cos(PHId)) ** -1) / (5040 * (nu ** 7))) * (
61 + (662 * ((tan(PHId)) ** 2)) + (1320 * ((tan(PHId)) ** 4)) + (
720 * ((tan(PHId)) ** 6)))
E_N_Lat = PHId - ((Et ** 2) * VII) + ((Et ** 4) * VIII) - ((Et ** 6) * IX)
E_N_Long = osgb36.lam_0 + (Et * X) - ((Et ** 3) * XI) + ((Et ** 5) * XII) - ((Et ** 7) * XIIA)
if not rads:
E_N_Lat = rad2dms(E_N_Lat, dms=dms)
E_N_Long = rad2dms(E_N_Long, dms=dms)
res_lat.append(E_N_Lat)
res_lon.append(E_N_Long)
return res_lat, res_lon
class HelmertTransform(object):
"""Callable class to perform a Helmert transform."""
def __init__(self, s, rx, ry, rz, T):
self.T = T.reshape((3, 1))
self.M = array([[1 + s, -rz, ry],
[rz, 1 + s, -rx],
[-ry, rx, 1 + s]])
def __call__(self, X):
X = X.reshape((3, -1))
return self.T + self.M @ X
class HelmertInverseTransform(object):
"""Callable class to perform the inverse of a Helmert transform."""
def __init__(self, s, rx, ry, rz, T):
self.T = T.reshape((3, 1))
self.M = inv(array([[1 + s, -rz, ry],
[rz, 1 + s, -rx],
[-ry, rx, 1 + s]]))
def __call__(self, X):
X = X.reshape((3, -1))
return self.M @ (X - self.T)
OSGB36transform = HelmertTransform(20.4894e-6,
-dms2rad(0, 0, 0.1502),
-dms2rad(0, 0, 0.2470),
-dms2rad(0, 0, 0.8421),
array([-446.448, 125.157, -542.060]))
WGS84transform = HelmertInverseTransform(20.4894e-6,
-dms2rad(0, 0, 0.1502),
-dms2rad(0, 0, 0.2470),
-dms2rad(0, 0, 0.8421),
array([-446.448, 125.157, -542.060]))
def WGS84toOSGB36(phi, lam, rads=False):
"""Convert WGS84 latitude/longitude to OSGB36 latitude/longitude.
Parameters
----------
phi : array_like or float
Latitude in degrees or radians on WGS84 datum.
lam : array_like or float
Longitude in degrees or radians on WGS84 datum.
rads : bool, optional
If True, phi and lam are in radians. If False, phi and lam are in degrees.
Returns
-------
tuple of numpy.ndarrays
Latitude and longitude on OSGB36 datum in degrees or radians.
"""
xyz = OSGB36transform(lat_long_to_xyz(asarray(phi), asarray(lam),
rads=rads, datum=wgs84))
return xyz_to_lat_long(*xyz, rads=rads, datum=osgb36)
def OSGB36toWGS84(phi, lam, rads=False):
"""Convert OSGB36 latitude/longitude to WGS84 latitude/longitude.
Parameters
----------
phi : array_like or float
Latitude in degrees or radians on OSGB36 datum.
lam : array_like or float
Longitude in degrees or radians on OSGB36 datum.
rads : bool, optional
If True, phi and lam are in radians. If False, phi and lam are in degrees.
Returns
-------
tuple of numpy.ndarrays
Latitude and longitude on WGS84 datum in degrees or radians.
"""
xyz = WGS84transform(lat_long_to_xyz(asarray(phi), asarray(lam),
rads=rads, datum=osgb36))
return xyz_to_lat_long(*xyz, rads=rads, datum=wgs84)
if __name__ == "__main__":
print(get_easting_northing_from_gps_lat_long([55.5], [-1.54])) | PypiClean |
/CleanAdminDjango-1.5.3.1.tar.gz/CleanAdminDjango-1.5.3.1/django/contrib/localflavor/mk/forms.py | from __future__ import absolute_import, unicode_literals
import datetime
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField, Select
from django.utils.translation import ugettext_lazy as _
from django.contrib.localflavor.mk.mk_choices import MK_MUNICIPALITIES
class MKIdentityCardNumberField(RegexField):
"""
A Macedonian ID card number. Accepts both old and new format.
"""
default_error_messages = {
'invalid': _('Identity card numbers must contain'
' either 4 to 7 digits or an uppercase letter and 7 digits.'),
}
def __init__(self, *args, **kwargs):
kwargs['min_length'] = None
kwargs['max_length'] = 8
regex = r'(^[A-Z]{1}\d{7}$)|(^\d{4,7}$)'
super(MKIdentityCardNumberField, self).__init__(regex, *args, **kwargs)
class MKMunicipalitySelect(Select):
"""
A form ``Select`` widget that uses a list of Macedonian municipalities as
choices. The label is the name of the municipality and the value
is a 2 character code for the municipality.
"""
def __init__(self, attrs=None):
super(MKMunicipalitySelect, self).__init__(attrs, choices = MK_MUNICIPALITIES)
class UMCNField(RegexField):
"""
A form field that validates input as a unique master citizen
number.
The format of the unique master citizen number has been kept the same from
Yugoslavia. It is still in use in other countries as well, it is not applicable
solely in Macedonia. For more information see:
https://secure.wikimedia.org/wikipedia/en/wiki/Unique_Master_Citizen_Number
A value will pass validation if it complies to the following rules:
* Consists of exactly 13 digits
* The first 7 digits represent a valid past date in the format DDMMYYY
* The last digit of the UMCN passes a checksum test
"""
default_error_messages = {
'invalid': _('This field should contain exactly 13 digits.'),
'date': _('The first 7 digits of the UMCN must represent a valid past date.'),
'checksum': _('The UMCN is not valid.'),
}
def __init__(self, *args, **kwargs):
kwargs['min_length'] = None
kwargs['max_length'] = 13
super(UMCNField, self).__init__(r'^\d{13}$', *args, **kwargs)
def clean(self, value):
value = super(UMCNField, self).clean(value)
if value in EMPTY_VALUES:
return ''
if not self._validate_date_part(value):
raise ValidationError(self.error_messages['date'])
if self._validate_checksum(value):
return value
else:
raise ValidationError(self.error_messages['checksum'])
def _validate_checksum(self, value):
a,b,c,d,e,f,g,h,i,j,k,l,K = [int(digit) for digit in value]
m = 11 - (( 7*(a+g) + 6*(b+h) + 5*(c+i) + 4*(d+j) + 3*(e+k) + 2*(f+l)) % 11)
if (m >= 1 and m <= 9) and K == m:
return True
elif m == 11 and K == 0:
return True
else:
return False
def _validate_date_part(self, value):
daypart, monthpart, yearpart = int(value[:2]), int(value[2:4]), int(value[4:7])
if yearpart >= 800:
yearpart += 1000
else:
yearpart += 2000
try:
date = datetime.datetime(year = yearpart, month = monthpart, day = daypart).date()
except ValueError:
return False
if date >= datetime.datetime.now().date():
return False
return True | PypiClean |
/Machine_Learning_Preprocess_CLI-1.0.1-py3-none-any.whl/cli_app/feature_scaling.py | import pandas as pd
from cli_app.data_description import DataDescription
from sklearn.preprocessing import MinMaxScaler, StandardScaler
class FeatureScaling:
bold_start = "\033[1m"
bold_end = "\033[0;0m"
# All the Tasks associated with this class.
tasks = [
"\n1. Perform Normalization(MinMax Scaler)",
"2. Perform Standardization(Standard Scaler)",
"3. Show the Dataset"
]
tasks_normalization = [
"\n1. Normalize a specific Column",
"2. Normalize the whole Dataset",
"3. Show the Dataset"
]
tasks_standardization = [
"\n1. Standardize a specific Column",
"2. Standardize the whole Dataset",
"3. Show the Dataset"
]
def __init__(self, data):
self.data = data
# Performs Normalization on specific column or on whole dataset.
def normalization(self):
while(1):
print("\nTasks (Normalization)\U0001F447")
for task in self.tasks_normalization:
print(task)
while(1):
try:
choice = int(input(("\n\nWhat you want to do? (Press -1 to go back) ")))
except ValueError:
print("Integer Value required. Try again.....\U0001F974")
continue
break
if choice == -1:
break
# Performs normalization on the columns provided.
elif choice == 1:
print(self.data.dtypes)
columns = input("Enter all the column"+ self.bold_start + "(s)" + self.bold_end + "you want to normalize (Press -1 to go back) ").lower()
if columns == "-1":
break
for column in columns.split(" "):
# This is the basic approach to perform MinMax Scaler on a set of data.
try:
minValue = self.data[column].min()
maxValue = self.data[column].max()
self.data[column] = (self.data[column] - minValue)/(maxValue - minValue)
except:
print("\nNot possible....\U0001F636")
print("Done....\U0001F601")
# Performs normalization on whole dataset.
elif choice == 2:
try:
self.data = pd.DataFrame(MinMaxScaler().fit_transform(self.data))
print("Done.......\U0001F601")
except:
print("\nString Columns are present. So, " + self.bold_start + "NOT" + self.bold_end + " possible.\U0001F636\nYou can try the first option though.")
elif choice==3:
DataDescription.showDataset(self)
else:
print("\nYou pressed the wrong key!! Try again..\U0001F974")
return
# Function to perform standardization on specific column(s) or on whole dataset.
def standardization(self):
while(1):
print("\nTasks (Standardization)\U0001F447")
for task in self.tasks_standardization:
print(task)
while(1):
try:
choice = int(input(("\n\nWhat you want to do? (Press -1 to go back) ")))
except ValueError:
print("Integer Value required. Try again.....")
continue
break
if choice == -1:
break
# This is the basic approach to perform Standard Scaler on a set of data.
elif choice == 1:
print(self.data.dtypes)
columns = input("Enter all the column"+ self.bold_start + "(s)" + self.bold_end + "you want to normalize (Press -1 to go back) ").lower()
if columns == "-1":
break
for column in columns.split(" "):
try:
mean = self.data[column].mean()
standard_deviation = self.data[column].std()
self.data[column] = (self.data[column] - mean)/(standard_deviation)
except:
print("\nNot possible....\U0001F636")
print("Done....\U0001F601")
# Performing standard scaler on whole dataset.
elif choice == 2:
try:
self.data = pd.DataFrame(StandardScaler().fit_transform(self.data))
print("Done.......\U0001F601")
except:
print("\nString Columns are present. So, " + self.bold_start + "NOT" + self.bold_end + " possible.\U0001F636\nYou can try the first option though.")
break
elif choice==3:
DataDescription.showDataset(self)
else:
print("\nYou pressed the wrong key!! Try again..\U0001F974")
return
# main function of the FeatureScaling Class.
def scaling(self):
while(1):
print("\nTasks (Feature Scaling)\U0001F447")
for task in self.tasks:
print(task)
while(1):
try:
choice = int(input(("\n\nWhat you want to do? (Press -1 to go back) ")))
except ValueError:
print("Integer Value required. Try again.....\U0001F974")
continue
break
if choice == -1:
break
elif choice == 1:
self.normalization()
elif choice == 2:
self.standardization()
elif choice==3:
DataDescription.showDataset(self)
else:
print("\nWrong Integer value!! Try again..\U0001F974")
# Returns all the changes on the DataFrame.
return self.data | PypiClean |
/FlexGet-3.9.6-py3-none-any.whl/flexget/components/pending_approval/db.py | from datetime import datetime, timedelta
from loguru import logger
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Unicode, select
from flexget import db_schema
from flexget.entry import Entry
from flexget.event import event
from flexget.utils import json, serialization
from flexget.utils.database import entry_synonym
from flexget.utils.sqlalchemy_utils import table_schema
logger = logger.bind(name='pending_approval')
Base = db_schema.versioned_base('pending_approval', 1)
@db_schema.upgrade('pending_approval')
def upgrade(ver, session):
if ver == 0:
table = table_schema('pending_entries', session)
for row in session.execute(select(table.c.id, table.c.json)):
if not row['json']:
# Seems there could be invalid data somehow. See #2590
continue
data = json.loads(row['json'], decode_datetime=True)
# If title looked like a date, make sure it's a string
title = str(data.pop('title'))
e = Entry(title=title, **data)
session.execute(
table.update().where(table.c.id == row['id']).values(json=serialization.dumps(e))
)
ver = 1
return ver
class PendingEntry(Base):
__tablename__ = 'pending_entries'
id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
task_name = Column(Unicode)
title = Column(Unicode)
url = Column(String)
approved = Column(Boolean)
_json = Column('json', Unicode)
entry = entry_synonym('_json')
added = Column(DateTime, default=datetime.now)
def __init__(self, task_name, entry):
self.task_name = task_name
self.title = entry['title']
self.url = entry['url']
self.approved = False
self.entry = entry
def __repr__(self):
return '<PendingEntry(task_name={},title={},url={},approved={})>'.format(
self.task_name, self.title, self.url, self.approved
)
def to_dict(self):
return {
'id': self.id,
'task_name': self.task_name,
'title': self.title,
'url': self.url,
'approved': self.approved,
'added': self.added,
}
@event('manager.db_cleanup')
def db_cleanup(manager, session):
# Clean unapproved entries older than 1 year
deleted = (
session.query(PendingEntry)
.filter(PendingEntry.added < datetime.now() - timedelta(days=365))
.delete()
)
if deleted:
logger.info('Purged {} pending entries older than 1 year', deleted)
def list_pending_entries(
session, task_name=None, approved=None, start=None, stop=None, sort_by='added', descending=True
):
logger.debug('querying pending entries')
query = session.query(PendingEntry)
if task_name:
query = query.filter(PendingEntry.task_name == task_name)
if approved is not None:
query = query.filter(PendingEntry.approved == approved)
if descending:
query = query.order_by(getattr(PendingEntry, sort_by).desc())
else:
query = query.order_by(getattr(PendingEntry, sort_by))
return query.slice(start, stop).all()
def get_entry_by_id(session, entry_id):
return session.query(PendingEntry).filter(PendingEntry.id == entry_id).one() | PypiClean |
/Grinder-Webtest-0.1.tar.gz/Grinder-Webtest-0.1/webtest/parser.py | # Everything in this script should be compatible with Jython 2.2.1.
import sys
from xml import sax
from urlparse import urlparse
class MalformedXML (Exception):
"""Raised when any malformed XML is encountered."""
pass
class Request:
"""Store attributes pertaining to an HTTP Request, including:
url
The full URL path of the request
headers
A list of ``(Name, Value)`` for the request header
parameters
A list of ``(Name, Value)`` for the request parameters
"""
def __init__(self, attrs, line_number=0):
"""Create a Request with the given attributes.
"""
self.url = attrs.get('Url', '')
self.method = attrs.get('Method', 'GET')
# Keep track of body, headers and parameters for this request
self.body = ''
self.headers = []
self.parameters = []
# List of expressions to capture response data
self.capture = ''
# Human-readable description of the request
self.description = ''
# Line number where this request was defined
self.line_number = line_number
def _add_attrs(self, attrs, to_list):
"""Add a ``(Name, Value)`` pair to a given list.
attrs
A `dict` including 'Name' and 'Value' items
to_list
The list to append ``(Name, Value)`` to
If the 'Name' or 'Value' attributes are not defined, or if the 'Name'
attribute is empty, nothing is added.
"""
# Only add if attrs has a non-empty 'Name',
# and 'Value' is defined (possibly empty)
if attrs.get('Name') and 'Value' in attrs:
name = attrs['Name']
value = attrs['Value']
# Create and append the pair
pair = (name, value)
to_list.append(pair)
def add_header(self, attrs):
"""Add a header ``(Name, Value)`` pair to the request.
attrs
A `dict` including 'Name' and 'Value' items
If the 'Name' or 'Value' attributes are not defined, or if the 'Name'
attribute is empty, nothing is added.
"""
self._add_attrs(attrs, self.headers)
def add_parameter(self, attrs):
"""Add a parameter ``(Name, Value)`` pair to the request.
attrs
A `dict` including 'Name' and 'Value' items
If the 'Name' or 'Value' attributes are not defined, or if the 'Name'
attribute is empty, nothing is added.
"""
self._add_attrs(attrs, self.parameters)
def captures(self):
"""Return capture expressions as a list of strings.
Normally, ``self.capture`` will be a literal block of text as it
appeared inside the ``Capture`` element; it may contain extra spaces
and newlines. This method strips out the extra newlines and
whitespace, and converts to a list for easy iteration over each capture
expression.
"""
result = []
for line in self.capture.splitlines():
if line.strip() != '':
result.append(line.strip())
return result
def __str__(self):
"""Return a one-line string summarizing the request.
"""
result = ''
# Include the request description first
if self.description:
result = self.description + ': '
# Append the URL and its parameters
# Start with method
result += self.method
# Add the URL (minus the http:// part)
server, path = urlparse(self.url)[1:3]
result += ' ' + server + path
# Add parameters, formatted like a dict
result += ' {%s}' % ', '.join(
["'%s': '%s'" % pair for pair in self.parameters])
return result
class WebtestHandler (sax.handler.ContentHandler):
"""Content handler for xml.sax parser.
"""
def __init__(self):
"""Create the Webtest content handler.
"""
sax.handler.ContentHandler.__init__(self)
self.request = None
self.requests = []
# String to indicate when we're inside particular elements
self.in_element = ''
# Locator used to track line numbers
self.locator = None
def setDocumentLocator(self, locator):
"""Set the document locator, for tracking line numbers.
This is set by the parser, and is used in `startElement`.
"""
self.locator = locator
def startElement(self, name, attrs):
"""Called when an opening XML tag is found. If any badly-formed
XML is encountered, a `MalformedXML` exception is raised.
"""
# With sax, attrs is almost, but not quite, a dictionary.
# Convert it here to make things easier in the Request class.
attrs = dict(attrs.items())
# Determine which element is being started, and take
# appropriate action
# Request element? Create a new Request object
if name == 'Request':
self.request = Request(attrs, self.locator.getLineNumber())
# Header element? Add the header to the current request
elif name == 'Header':
if not self.request:
raise MalformedXML("%s not inside Request" % name)
self.request.add_header(attrs)
# Parameter element? Add the parameter to the current request
elif name in ('QueryStringParameter', 'FormPostParameter'):
if not self.request:
raise MalformedXML("%s not inside Request" % name)
self.request.add_parameter(attrs)
# The 'StringHttpBody', 'Capture', and 'Description' elements do not
# have any attributes, only content. Make note of when we enter them,
# so the characters() method can fetch their content.
elif name in ('StringHttpBody', 'Capture', 'Description'):
self.in_element = name
# We don't care about any other elements
else:
pass
def characters(self, data):
"""Called when character data is found inside an element.
"""
# Ignore any empty data, or characters outside a known element
if not (data and self.in_element):
return
# If we're not inside a request, something is wrong
if not self.request:
raise MalformedXML("Characters in %s not inside Request" % \
self.in_element)
# Otherwise, save the data to the appropriate place.
# Append, since characters() may be called with arbitrarily
# small chunks of text, and we don't want to miss anything.
if self.in_element == 'StringHttpBody':
self.request.body += data
elif self.in_element == 'Capture':
self.request.capture += data
elif self.in_element == 'Description':
self.request.description += data
def endElement(self, name):
"""Called when a closing XML tag is found.
"""
# If this is the end of the Request,
# append to requests and clear current request
if name == 'Request':
self.requests.append(self.request)
self.request = None
# For elements with character content, reset in_element
elif name in ('StringHttpBody', 'Capture', 'Description'):
if name != self.in_element:
raise MalformedXML("Got ending tag %d, expected %d" % \
(name, self.in_element))
self.in_element = ''
# No action needed for closing other elements
else:
pass
class Webtest:
"""Webtest XML file parser.
"""
def __init__(self, filename=''):
"""Get requests from the given ``.webtest`` XML file.
After calling this, the ``requests`` attribute will have a
list of all requests found in the given ``.webtest`` file.
"""
self.filename = filename
self.requests = []
# Create the handler and sax parser
self._handler = WebtestHandler()
self.saxparser = sax.make_parser()
self.saxparser.setContentHandler(self._handler)
# Parse the file, if given
if filename:
self.parse(filename)
def parse(self, filename):
"""Parse the given ``.webtest`` XML file, and store the
list of requests found in it.
"""
self.filename = filename
# Parse the given filename
infile = open(filename, 'r')
self.saxparser.parse(infile)
infile.close()
# Store a reference to the list of requests
self.requests = self._handler.requests
def __str__(self):
"""Return the Webtest formatted as a human-readable string.
"""
result = 'Webtest: %s\n\n' % self.filename
result += '\n\n'.join([str(req) for req in self.requests])
return result | PypiClean |
/FreePyBX-1.0-RC1.tar.gz/FreePyBX-1.0-RC1/freepybx/public/js/dojox/data/PicasaStore.js | define("dojox/data/PicasaStore",["dojo/_base/lang","dojo/_base/declare","dojo/_base/connect","dojo/io/script","dojo/data/util/simpleFetch","dojo/date/stamp"],function(_1,_2,_3,_4,_5,_6){
var _7=_2("dojox.data.PicasaStore",null,{constructor:function(_8){
if(_8&&_8.label){
this.label=_8.label;
}
if(_8&&"urlPreventCache" in _8){
this.urlPreventCache=_8.urlPreventCache?true:false;
}
if(_8&&"maxResults" in _8){
this.maxResults=parseInt(_8.maxResults);
if(!this.maxResults){
this.maxResults=20;
}
}
},_picasaUrl:"http://picasaweb.google.com/data/feed/api/all",_storeRef:"_S",label:"title",urlPreventCache:false,maxResults:20,_assertIsItem:function(_9){
if(!this.isItem(_9)){
throw new Error("dojox.data.PicasaStore: a function was passed an item argument that was not an item");
}
},_assertIsAttribute:function(_a){
if(typeof _a!=="string"){
throw new Error("dojox.data.PicasaStore: a function was passed an attribute argument that was not an attribute name string");
}
},getFeatures:function(){
return {"dojo.data.api.Read":true};
},getValue:function(_b,_c,_d){
var _e=this.getValues(_b,_c);
if(_e&&_e.length>0){
return _e[0];
}
return _d;
},getAttributes:function(_f){
return ["id","published","updated","category","title$type","title","summary$type","summary","rights$type","rights","link","author","gphoto$id","gphoto$name","location","imageUrlSmall","imageUrlMedium","imageUrl","datePublished","dateTaken","description"];
},hasAttribute:function(_10,_11){
if(this.getValue(_10,_11)){
return true;
}
return false;
},isItemLoaded:function(_12){
return this.isItem(_12);
},loadItem:function(_13){
},getLabel:function(_14){
return this.getValue(_14,this.label);
},getLabelAttributes:function(_15){
return [this.label];
},containsValue:function(_16,_17,_18){
var _19=this.getValues(_16,_17);
for(var i=0;i<_19.length;i++){
if(_19[i]===_18){
return true;
}
}
return false;
},getValues:function(_1a,_1b){
this._assertIsItem(_1a);
this._assertIsAttribute(_1b);
if(_1b==="title"){
return [this._unescapeHtml(_1a.title)];
}else{
if(_1b==="author"){
return [this._unescapeHtml(_1a.author[0].name)];
}else{
if(_1b==="datePublished"){
return [dateAtamp.fromISOString(_1a.published)];
}else{
if(_1b==="dateTaken"){
return [_6.fromISOString(_1a.published)];
}else{
if(_1b==="updated"){
return [_6.fromISOString(_1a.updated)];
}else{
if(_1b==="imageUrlSmall"){
return [_1a.media.thumbnail[1].url];
}else{
if(_1b==="imageUrl"){
return [_1a.content$src];
}else{
if(_1b==="imageUrlMedium"){
return [_1a.media.thumbnail[2].url];
}else{
if(_1b==="link"){
return [_1a.link[1]];
}else{
if(_1b==="tags"){
return _1a.tags.split(" ");
}else{
if(_1b==="description"){
return [this._unescapeHtml(_1a.summary)];
}
}
}
}
}
}
}
}
}
}
}
return [];
},isItem:function(_1c){
if(_1c&&_1c[this._storeRef]===this){
return true;
}
return false;
},close:function(_1d){
},_fetchItems:function(_1e,_1f,_20){
if(!_1e.query){
_1e.query={};
}
var _21={alt:"jsonm",pp:"1",psc:"G"};
_21["start-index"]="1";
if(_1e.query.start){
_21["start-index"]=_1e.query.start;
}
if(_1e.query.tags){
_21.q=_1e.query.tags;
}
if(_1e.query.userid){
_21.uname=_1e.query.userid;
}
if(_1e.query.userids){
_21.ids=_1e.query.userids;
}
if(_1e.query.lang){
_21.hl=_1e.query.lang;
}
_21["max-results"]=this.maxResults;
var _22=this;
var _23=null;
var _24=function(_25){
if(_23!==null){
_3.disconnect(_23);
}
_1f(_22._processPicasaData(_25),_1e);
};
var _26={url:this._picasaUrl,preventCache:this.urlPreventCache,content:_21,callbackParamName:"callback",handle:_24};
var _27=_4.get(_26);
_27.addErrback(function(_28){
_3.disconnect(_23);
_20(_28,_1e);
});
},_processPicasaData:function(_29){
var _2a=[];
if(_29.feed){
_2a=_29.feed.entry;
for(var i=0;i<_2a.length;i++){
var _2b=_2a[i];
_2b[this._storeRef]=this;
}
}
return _2a;
},_unescapeHtml:function(str){
if(str){
str=str.replace(/&/gm,"&").replace(/</gm,"<").replace(/>/gm,">").replace(/"/gm,"\"");
str=str.replace(/'/gm,"'");
}
return str;
}});
_1.extend(_7,_5);
return _7;
}); | PypiClean |
/Brian2-2.5.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/brian2/codegen/templates.py | import re
from collections.abc import Mapping
from jinja2 import (
ChoiceLoader,
Environment,
PackageLoader,
StrictUndefined,
TemplateNotFound,
)
from brian2.utils.stringtools import get_identifiers, indent, strip_empty_lines
__all__ = ["Templater"]
AUTOINDENT_START = "%%START_AUTOINDENT%%"
AUTOINDENT_END = "%%END_AUTOINDENT%%"
def autoindent(code):
if isinstance(code, list):
code = "\n".join(code)
if not code.startswith("\n"):
code = f"\n{code}"
if not code.endswith("\n"):
code = f"{code}\n"
return AUTOINDENT_START + code + AUTOINDENT_END
def autoindent_postfilter(code):
lines = code.split("\n")
outlines = []
addspaces = 0
for line in lines:
if AUTOINDENT_START in line:
if addspaces > 0:
raise SyntaxError("Cannot nest autoindents")
addspaces = line.find(AUTOINDENT_START)
line = line.replace(AUTOINDENT_START, "")
if AUTOINDENT_END in line:
line = line.replace(AUTOINDENT_END, "")
addspaces = 0
outlines.append(" " * addspaces + line)
return "\n".join(outlines)
def variables_to_array_names(variables, access_data=True):
from brian2.devices.device import get_device
device = get_device()
names = [device.get_array_name(var, access_data=access_data) for var in variables]
return names
class LazyTemplateLoader:
"""
Helper object to load templates only when they are needed.
"""
def __init__(self, environment, extension):
self.env = environment
self.extension = extension
self._templates = {}
def get_template(self, name):
if name not in self._templates:
try:
template = CodeObjectTemplate(
self.env.get_template(name + self.extension),
self.env.loader.get_source(self.env, name + self.extension)[0],
)
except TemplateNotFound:
try:
# Try without extension as well (e.g. for makefiles)
template = CodeObjectTemplate(
self.env.get_template(name),
self.env.loader.get_source(self.env, name)[0],
)
except TemplateNotFound:
raise KeyError(f'No template with name "{name}" found.')
self._templates[name] = template
return self._templates[name]
class Templater:
"""
Class to load and return all the templates a `CodeObject` defines.
Parameters
----------
package_name : str, tuple of str
The package where the templates are saved. If this is a tuple then each template will be searched in order
starting from the first package in the tuple until the template is found. This allows for derived templates
to be used. See also `~Templater.derive`.
extension : str
The file extension (e.g. ``.pyx``) used for the templates.
env_globals : dict (optional)
A dictionary of global values accessible by the templates. Can be used for providing utility functions.
In all cases, the filter 'autoindent' is available (see existing templates for example usage).
templates_dir : str, tuple of str, optional
The name of the directory containing the templates. Defaults to ``'templates'``.
Notes
-----
Templates are accessed using ``templater.template_base_name`` (the base name is without the file extension).
This returns a `CodeObjectTemplate`.
"""
def __init__(
self, package_name, extension, env_globals=None, templates_dir="templates"
):
if isinstance(package_name, str):
package_name = (package_name,)
if isinstance(templates_dir, str):
templates_dir = (templates_dir,)
loader = ChoiceLoader(
[
PackageLoader(name, t_dir)
for name, t_dir in zip(package_name, templates_dir)
]
)
self.env = Environment(
loader=loader,
trim_blocks=True,
lstrip_blocks=True,
undefined=StrictUndefined,
)
self.env.globals["autoindent"] = autoindent
self.env.filters["autoindent"] = autoindent
self.env.filters["variables_to_array_names"] = variables_to_array_names
if env_globals is not None:
self.env.globals.update(env_globals)
else:
env_globals = {}
self.env_globals = env_globals
self.package_names = package_name
self.templates_dir = templates_dir
self.extension = extension
self.templates = LazyTemplateLoader(self.env, extension)
def __getattr__(self, item):
return self.templates.get_template(item)
def derive(
self, package_name, extension=None, env_globals=None, templates_dir="templates"
):
"""
Return a new Templater derived from this one, where the new package name and globals overwrite the old.
"""
if extension is None:
extension = self.extension
if isinstance(package_name, str):
package_name = (package_name,)
if env_globals is None:
env_globals = {}
if isinstance(templates_dir, str):
templates_dir = (templates_dir,)
package_name = package_name + self.package_names
templates_dir = templates_dir + self.templates_dir
new_env_globals = self.env_globals.copy()
new_env_globals.update(**env_globals)
return Templater(
package_name,
extension=extension,
env_globals=new_env_globals,
templates_dir=templates_dir,
)
class CodeObjectTemplate:
"""
Single template object returned by `Templater` and used for final code generation
Should not be instantiated by the user, but only directly by `Templater`.
Notes
-----
The final code is obtained from this by calling the template (see `~CodeObjectTemplater.__call__`).
"""
def __init__(self, template, template_source):
self.template = template
self.template_source = template_source
#: The set of variables in this template
self.variables = set()
#: The indices over which the template iterates completely
self.iterate_all = set()
#: Read-only variables that are changed by this template
self.writes_read_only = set()
# This is the bit inside {} for USES_VARIABLES { list of words }
specifier_blocks = re.findall(
r"\bUSES_VARIABLES\b\s*\{(.*?)\}", template_source, re.M | re.S
)
# Same for ITERATE_ALL
iterate_all_blocks = re.findall(
r"\bITERATE_ALL\b\s*\{(.*?)\}", template_source, re.M | re.S
)
# And for WRITES_TO_READ_ONLY_VARIABLES
writes_read_only_blocks = re.findall(
r"\bWRITES_TO_READ_ONLY_VARIABLES\b\s*\{(.*?)\}",
template_source,
re.M | re.S,
)
#: Does this template allow writing to scalar variables?
self.allows_scalar_write = "ALLOWS_SCALAR_WRITE" in template_source
for block in specifier_blocks:
self.variables.update(get_identifiers(block))
for block in iterate_all_blocks:
self.iterate_all.update(get_identifiers(block))
for block in writes_read_only_blocks:
self.writes_read_only.update(get_identifiers(block))
def __call__(self, scalar_code, vector_code, **kwds):
"""
Return a usable code block or blocks from this template.
Parameters
----------
scalar_code : dict
Dictionary of scalar code blocks.
vector_code : dict
Dictionary of vector code blocks
**kwds
Additional parameters to pass to the template
Notes
-----
Returns either a string (if macros were not used in the template), or a `MultiTemplate` (if macros were used).
"""
if (
scalar_code is not None
and len(scalar_code) == 1
and list(scalar_code)[0] is None
):
scalar_code = scalar_code[None]
if (
vector_code is not None
and len(vector_code) == 1
and list(vector_code)[0] is None
):
vector_code = vector_code[None]
kwds["scalar_code"] = scalar_code
kwds["vector_code"] = vector_code
module = self.template.make_module(kwds)
if len([k for k in module.__dict__ if not k.startswith("_")]):
return MultiTemplate(module)
else:
return autoindent_postfilter(str(module))
class MultiTemplate(Mapping):
"""
Code generated by a `CodeObjectTemplate` with multiple blocks
Each block is a string stored as an attribute with the block name. The
object can also be accessed as a dictionary.
"""
def __init__(self, module):
self._templates = {}
for k, f in module.__dict__.items():
if not k.startswith("_"):
s = autoindent_postfilter(str(f()))
setattr(self, k, s)
self._templates[k] = s
def __getitem__(self, item):
return self._templates[item]
def __iter__(self):
return iter(self._templates)
def __len__(self):
return len(self._templates)
def __str__(self):
s = ""
for k, v in list(self._templates.items()):
s += f"{k}:\n"
s += f"{strip_empty_lines(indent(v))}\n"
return s
__repr__ = __str__ | PypiClean |
/Moose-0.9.9b3.tar.gz/Moose-0.9.9b3/moose/actions/operate.py | from __future__ import unicode_literals
import os
from moose.toolbox import video
from moose.shortcuts import ivisit
from moose.utils._os import makedirs, makeparents
from .base import AbstractAction, IllegalAction
import logging
logger = logging.getLogger(__name__)
class BaseExtract(AbstractAction):
"""
Class to simulate the action of extracting frames from
a video with opencv-python,
`
get_context -> lookup_files -> get_extractor -> dump
`
while the following steps are implemented by subclasses.
`parse`
Get extra info to update context.
`get_extractor`
Returns a generator to yield index and frame in each loop
"""
default_pattern = ('*.mp4', '*.mov', '*.flv', '*.avi')
def get_context(self, kwargs):
if kwargs.has_key('config'):
config = kwargs.get('config')
else:
logger.error("Missing argument: 'config'.")
raise IllegalAction(
"Missing argument: 'config'. This error is not supposed to happen, "
"if the action class was called not in command-line, please provide "
"the argument `config = config_loader._parse()`.")
context = {
'root': config.common['root'],
'relpath': config.common['relpath'] if config.common['relpath'] else config.common['root'],
'src': config.extract['src']
}
context.update(self.parse(config, kwargs))
return context
def parse(self, config, kwargs):
"""
Entry point for subclassed upload actions to update context.
"""
return {}
def lookup_files(self, root, context):
"""
Finds all files located in root which matches the given pattern.
"""
pattern = context.get('pattern', self.default_pattern)
ignorecase = context.get('ignorecase', True)
logger.debug("Visit '%s' with pattern: %s..." % (root, pattern))
files = []
for filepath in ivisit(root, pattern=pattern, ignorecase=ignorecase):
files.append(filepath)
logger.debug("%d files found." % len(files))
return files
def get_extractor(self, context):
raise NotImplementedError
def dump(self, extractor, dst, context):
self.cap.dump(extractor, dst)
def run(self, **kwargs):
output = []
context = self.get_context(kwargs)
src = context['src']
files = self.lookup_files(src, context)
output.append('%d files found to extract frames.' % len(files))
for video_path in files:
video_dirname, _ = os.path.splitext(video_path)
dst = os.path.join(context['root'], os.path.relpath(video_dirname, src))
if os.path.exists(dst):
continue
self.cap = video.VideoCapture(video_path)
if int(self.cap.fps) != self.cap.fps:
logger.warning("FPS of %s is %f, not a integer." % (cap.video_name, cap.fps))
extractor = self.get_extractor(context)
makedirs(dst)
self.dump(extractor, dst, context)
return '\n'.join(output)
class PeriodicExtract(BaseExtract):
"""
Captures frames in an interval
"""
def get_extractor(self, context):
interval = context['step']
return self.cap.capture(step=interval)
class IndexListExtract(BaseExtract):
"""
Captures frames as the index list describes
"""
def get_extractor(self, context):
idx_list = context['frames']
return self.cap.extract(idx_list) | PypiClean |
/Fastoo-0.1.4.tar.gz/Fastoo-0.1.4/README.md | # fastoo
A powerful framework for dealing with FastAPI apps.
It includes various utilities for building big FastAPI apps, inclding templates and modules.
## Quickstart
-m means add default modules
```
python -m pip install fastoo==0.1.4
fastoo new blog -m
cd blog
uvicorn app:app --reload
```
### More commands
```
fastoo module bing
```
Creates a new module named bing in modules/
Url defined in info.toml.
Can be changed to what we want. Default is /module_name
### Configs
Define configuration profile in init (development, production, testing)
In your apps import get_settings from init
### Render templates
consider this
```
.
├── api
│ ├── __init__.py
│ ├── module.py
│ └── templates.py
├── app.py
├── cli.py
├── config.py
├── __init__.py
├── init.py
├── modules
│ └── auth
│ ├── business.py
│ ├── models.py
│ ├── templates
│ │ └── abc.html
│ └── view.py
└── templates
└── themes
├── back
└── front
└── dingy
└── index.html
```
imports
```python
from fastoo.api.module import Module
from fastapi import APIRouter
from fastapi import Request
from fastapi import Depends
from typing import Annotated
from pydantic_settings import BaseSettings
from init import get_settings
```
If we set render_own_templates to True, render_template will look in a folder called templates in the mdoules folder
```python
router = APIRouter(include_in_schema=False)
module = Module(__file__, render_own_templates=True)
@router.get("/login/")
def login(request: Request):
with module.set(request) as m:
return module.render_template("abc.html", {})
```
This can be overriden using
```py
module = Module(__file__, render_own_templates=True, templates="custom/path")
```
If you don't want the whole goodies, just call
```py
from fastoo import render_template
...
return render_template("template/path", {}, request, directory="custom/templates/path")
```
## Modules
Modules must contain info.toml like this
```toml
[base]
url_prefix = "/auth"
```
A module includes
- view.py
- forms.py # stafrlette-wtforms
- models.py
- info.toml
- business.py # view logic goes here
## Validation
fastoo.api.validation has these helpful features
- verify_slug # for wtf forms
- is_valid_url
- is_valid_slug
- is_empty_str
- is_alpha_num_underscore | PypiClean |
/Flask-Heroku-Cacheify-1.6.1.tar.gz/Flask-Heroku-Cacheify-1.6.1/README.md | # flask-heroku-cacheify
Automatic Flask cache configuration on Heroku.

## Purpose
Configuring your cache on Heroku can be a time sink. There are lots of
different caching addons available on Heroku (Redis, Memcached, etc.), and among
those -- lots of competitors.
`flask-heroku-cacheify` makes your life easy by automatically configuring your
Flask application to work with whatever caching addons you've got provisioned
on Heroku, allowing you to easily swap out addon providers at will, without any
trouble. And, just in case you don't have any suitable Heroku addons available,
`flask-heroku-cacheify` will default back to using local memory for your cache!
Instead of looking through documentation, testing stuff out, etc.,
`flask-heroku-cacheify` will just do everything for you :)
## Install
To install `flask-heroku-cacheify`, use [pip](http://pip.readthedocs.org/en/latest/).
```bash
$ pip install flask-heroku-cacheify
```
**NOTE**: If you're install `flask-heroku-cacheify` locally, you'll need to
have `libmemcached-dev` installed on your OS (with SASL support).
Next, modify your `requirements.txt` file in your home directory, and add the
following to the bottom of your file:
```bash
Flask-Heroku-Cacheify>=1.3
pylibmc>=1.2.3
```
The above will ensure that Heroku pulls in the required C header files (in case
you decide to use memcached). This step is **required**.
## Pick an Addon
Heroku has lots of available addons you can use for caching.
`flask-heroku-cacheify` currently works with them all! That means no matter
which option you choose, your cache will work out of the box, guaranteed!
Below is a list of the addons you can install to get started, you should have at
least one of these activated on your Heroku app -- otherwise, your cache will be
in 'local memory' only, and won't be very useful.
- [MemCachier](https://addons.heroku.com/memcachier)
- [RedisGreen](https://addons.heroku.com/redisgreen)
- [Redis Cloud](https://addons.heroku.com/rediscloud)
- [Redis To Go](https://addons.heroku.com/redistogo)
- [openredis](https://addons.heroku.com/openredis)
**NOTE** My favorite providers are MemCachier (for memcache), and openredis for
redis. Both are equally awesome as cache providers. If you're in need of a
stable cache provider for large applications, I'd recommend
[RedisGreen](https://addons.heroku.com/redisgreen) -- they use dedicated EC2
instances (which greatly improves your server power) and have an excellent
interface.
## Usage
Using `flask-heroku-cacheify` is *super easy*! In your `app.py` (or wherever
you define your Flask application), add the following:
```python
from flask_cacheify import init_cacheify
app = Flask(__name__)
cache = init_cacheify(app)
```
Once you've got your `cache` global defined, you can use it anywhere in your
Flask app:
```python
>>> from app import cache
>>> cache.set('hi', 'there', 30)
>>> cache.get('hi')
'there'
```
How does this work? In the background, `flask-heroku-cacheify` is really just
automatically configuring the popular
[Flask-Cache](http://pythonhosted.org/Flask-Cache/) extension! This means, you
can basically skip down to [this
part](http://pythonhosted.org/Flask-Cache/#caching-view-functions) of their
documentation, and begin using all the methods listed there, without worrying
about setting up your caches! Neat, right?
For more information and examples of how to use your cache, don't forget to read
the [Flask-Cache](http://pythonhosted.org/Flask-Cache/) documentation.
## Like This?
Like this software? If you really enjoy `flask-heroku-cacheify`, you can show
your appreciation by:
- Sending me some bitcoin, my address is: **17BE6Q6fRgxJutnn8NsQgeKnACFjzWLbQT**
- Tipping me on [gittip](https://www.gittip.com/rdegges/).
Either way, thanks! <3
## Changelog
1.6.1: 12-20-2017
- Update docs
- Updating code to support latest Flask release
1.6.0: 04-22-2017
- Upgrading to work with latest FLask release (thanks @mattstibbs).
v1.5: 06-20-2015
- Removing MyRedis addon support -- the addon has been shut down.
v1.4: 04-04-2015
- Fixing typos in README.
- Adding Python 3 compatibility.
v1.3: 05-31-2012
- Fixing bug with memcachier support (thanks @eriktaubeneck)!
v1.2: 04-18-2013
- Adding proper documentation.
v1.1: 04-18-2013
- Adding support for MyRedis.
- Adding support for Redis Cloud.
- Adding support for Redis To Go.
- Adding support for openredis.
v1.0: 04-18-2013
- Fixing bug with RedisGreen support.
v0.9: 04-18-2013
- First *real* release! Supports MemCachier and RedisGreen!
v0.8: 04-18-2013
- Pushing eigth release to PyPI (don't use this still!).
v0.7: 04-18-2013
- Pushing seventh release to PyPI (don't use this still!).
v0.6: 04-18-2013
- Pushing sixth release to PyPI (don't use this still!).
v0.5: 04-18-2013
- Pushing fifth release to PyPI (don't use this still!).
v0.4: 04-18-2013
- Pushing fourth release to PyPI (don't use this still!).
v0.3: 04-18-2013
- Pushing third release to PyPI (don't use this still!).
v0.2: 04-18-2013
- Pushing second release to PyPI (don't use this still!).
v0.1: 04-18-2013
- Pushing first release to PyPI (don't use this yet!).
v0.0: 04-14-2013
- Started work >:)
| PypiClean |
/MarsGT-0.2.1.tar.gz/MarsGT-0.2.1/README.md | ## Title:MarsGT:Multi-omics data analysis for rare population inference using single-cell graph transformer
**Note: This project is for internal testing purposes only. Do not use it in a production environment.**
MarsGT, for rare cell identification from matched scRNA-seq (snRNA-seq) and scATAC-seq (snATAC-seq),includes genes, enhancers, and cells in a heterogeneous graph to simultaneously identify major cell clusters and rare cell clusters based on eRegulon.
## Installation
### System Requirements
* Python 3.8.0 or higher
### Installation Steps
* Install the required dependencies using pip:
```bash
pip install -r requirements.txt
```
* use pip to install MarsGT:
```bash
pip install MarsGT
```
| PypiClean |
/MPoL-0.1.13.tar.gz/MPoL-0.1.13/src/mpol/connectors.py | import torch
import torch.fft # to avoid conflicts with old torch.fft *function*
from torch import nn
from . import utils
def index_vis(vis, griddedDataset):
r"""
Index model visibilities to same locations as a :class:`~mpol.datasets.GriddedDataset`. Assumes that vis is "packed" just like the :class:`~mpol.datasets.GriddedDataset`
Args:
vis (torch complex tensor): torch tensor with shape ``(nchan, npix, npix)`` to be indexed by the ``mask`` from :class:`~mpol.datasets.GriddedDataset`. Assumes tensor is "pre-packed."
griddedDataset: instantiated :class:`~mpol.datasets.GriddedDataset` object
Returns:
torch complex tensor: 1d torch tensor of model samples collapsed across cube dimensions like ``vis_indexed`` and ``weight_indexed`` of :class:`~mpol.datasets.GriddedDataset`
"""
assert (
vis.size()[0] == griddedDataset.mask.size()[0]
), "vis and dataset mask do not have the same number of channels."
# As of Pytorch 1.7.0, complex numbers are partially supported.
# However, masked_select does not yet work (with gradients)
# on the complex vis, so hence this awkward step of selecting
# the reals and imaginaries separately
re = vis.real.masked_select(griddedDataset.mask)
im = vis.imag.masked_select(griddedDataset.mask)
# we had trouble returning things as re + 1.0j * im,
# but for some reason torch.complex seems to work OK.
return torch.complex(re, im)
class GriddedResidualConnector(nn.Module):
r"""
Connect a FourierCube to the gridded dataset and calculate residual products useful for visualization and debugging in both the Fourier plane and image plane. The products are available as property attributes after the ``forward`` call.
Args:
fourierCube: instantiated :class:`~mpol.fourier.FourierCube` object
griddedDataset: instantiated :class:`~mpol.datasets.GriddedDataset` object
"""
def __init__(self, fourierCube, griddedDataset):
super().__init__()
# check to make sure that the FourierCube and GriddedDataset
# were both initialized with the same GridCoords settings.
assert fourierCube.coords == griddedDataset.coords
self.fourierCube = fourierCube
self.griddedDataset = griddedDataset
self.coords = fourierCube.coords
# take the mask from the gridded dataset
self.mask = griddedDataset.mask
def forward(self):
r"""Calculate the residuals as
.. math::
\mathrm{residuals} = \mathrm{data} - \mathrm{model}
and store residual products as PyTorch tensor instance and property attributes.
Also take the iFFT of the gridded residuals and store this as an image. After the complex values of the image cube are checked to ensure that they are minimal, store only the real values as `self.cube`.
Returns:
torch tensor complex: The full packed image cube (including imaginaries). This can be useful for debugging purposes.
"""
self.residuals = self.griddedDataset.vis_gridded - self.fourierCube.vis
self.amp = torch.abs(self.residuals)
self.phase = torch.angle(self.residuals)
# calculate the corresponding residual dirty image (under uniform weighting).
# see units_and_conventions.rst for the calculation of the prefactors.
# But essentially this calculation requires a prefactor of npix**2 * uv_cell_size**2
# Assuming uv_cell_size would be measured in units of cycles/arcsec, then this prefactor is
# equivalent to 1/cell_size**2, where cell_size is units of arcsec
cube = (
1
/ (self.coords.cell_size**2)
* torch.fft.ifftn(self.residuals, dim=(1, 2))
) # Jy/arcsec^2
assert (
torch.max(cube.imag) < 1e-10
), "Dirty image contained substantial imaginary values, check input visibilities, otherwise raise a github issue."
self.cube = cube.real
# return the full thing for debugging purposes
return cube
@property
def sky_cube(self):
r"""
The image cube arranged as it would appear on the sky. Array dimensions for plotting given by ``self.coords.img_ext``.
Returns:
torch.double : 3D image cube of shape ``(nchan, npix, npix)`` in units of [:math:`\mathrm{Jy}\,\mathrm{arcsec}^{-2}`].
"""
return utils.packed_cube_to_sky_cube(self.cube)
@property
def ground_mask(self):
r"""
The boolean mask, arranged in ground format.
Returns:
torch.boolean : 3D mask cube of shape ``(nchan, npix, npix)``
"""
return utils.packed_cube_to_ground_cube(self.mask)
@property
def ground_amp(self):
r"""
The amplitude of the residuals, arranged in unpacked format corresponding to the FFT of the sky_cube. Array dimensions for plotting given by ``self.coords.vis_ext``.
Returns:
torch.double : 3D amplitude cube of shape ``(nchan, npix, npix)``
"""
return utils.packed_cube_to_ground_cube(self.amp)
@property
def ground_phase(self):
r"""
The phase of the residuals, arranged in unpacked format corresponding to the FFT of the sky_cube. Array dimensions for plotting given by ``self.coords.vis_ext``.
Returns:
torch.double : 3D phase cube of shape ``(nchan, npix, npix)``
"""
return utils.packed_cube_to_ground_cube(self.phase)
@property
def ground_residuals(self):
r"""
The complex residuals, arranged in unpacked format corresponding to the FFT of the sky_cube. Array dimensions for plotting given by ``self.coords.vis_ext``.
Returns:
torch.complex : 3D phase cube of shape ``(nchan, npix, npix)``
"""
return utils.packed_cube_to_ground_cube(self.residuals) | PypiClean |
/IHEWAcollect-0.0.31.tar.gz/IHEWAcollect-0.0.31/docs/api/IHEWAcollect.scripts.rst | IHEWAcollect.scripts package
============================
Submodules
----------
IHEWAcollect.scripts.credential module
--------------------------------------
.. automodule:: IHEWAcollect.scripts.credential
:members:
:undoc-members:
:show-inheritance:
IHEWAcollect.scripts.main module
--------------------------------
.. automodule:: IHEWAcollect.scripts.main
:members:
:undoc-members:
:show-inheritance:
IHEWAcollect.scripts.skeleton module
------------------------------------
.. automodule:: IHEWAcollect.scripts.skeleton
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: IHEWAcollect.scripts
:members:
:undoc-members:
:show-inheritance:
| PypiClean |
/GeoNode-3.2.0-py3-none-any.whl/geonode/static/geonode/js/jszip/preprocess.js | var geojsonData = {};
// Shapefile parser, following the specification at
// http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
SHP = {
NULL: 0,
POINT: 1,
POLYLINE: 3,
POLYGON: 5
};
SHP.getShapeName = function(id) {
for (var name in this) {
if (id === this[name]) {
return name;
}
}
};
SHPParser = function() {};
SHPParser.load = function(url, callback, returnData) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
geojsonData['shp'] = new SHPParser().parse(xhr.response,url);
callback(geojsonData['shp'], returnData);
URL.revokeObjectURL(url);
};
xhr.onerror = onerror;
xhr.send(null);
};
SHPParser.prototype.parse = function(arrayBuffer,url) {
var o = {},
dv = new DataView(arrayBuffer),
idx = 0;
o.fileName = url;
o.fileCode = dv.getInt32(idx, false);
if (o.fileCode != 0x0000270a) {
throw (new Error("Unknown file code: " + o.fileCode));
}
idx += 6*4;
o.wordLength = dv.getInt32(idx, false);
o.byteLength = o.wordLength * 2;
idx += 4;
o.version = dv.getInt32(idx, true);
idx += 4;
o.shapeType = dv.getInt32(idx, true);
idx += 4;
o.minX = dv.getFloat64(idx, true);
o.minY = dv.getFloat64(idx+8, true);
o.maxX = dv.getFloat64(idx+16, true);
o.maxY = dv.getFloat64(idx+24, true);
o.minZ = dv.getFloat64(idx+32, true);
o.maxZ = dv.getFloat64(idx+40, true);
o.minM = dv.getFloat64(idx+48, true);
o.maxM = dv.getFloat64(idx+56, true);
idx += 8*8;
o.records = [];
while (idx < o.byteLength) {
var record = {};
record.number = dv.getInt32(idx, false);
idx += 4;
record.length = dv.getInt32(idx, false);
idx += 4;
try {
record.shape = this.parseShape(dv, idx, record.length);
} catch(e) {
console.log(e, record);
}
idx += record.length * 2;
o.records.push(record);
}
return o;
};
SHPParser.prototype.parseShape = function(dv, idx, length) {
var i=0,
c=null,
shape = {};
shape.type = dv.getInt32(idx, true);
idx += 4;
// var byteLen = length * 2;
switch (shape.type) {
case SHP.NULL: // Null
break;
case SHP.POINT: // Point (x,y)
shape.content = {
x: dv.getFloat64(idx, true),
y: dv.getFloat64(idx+8, true)
};
break;
case SHP.POLYLINE: // Polyline (MBR, partCount, pointCount, parts, points)
case SHP.POLYGON: // Polygon (MBR, partCount, pointCount, parts, points)
c = shape.content = {
minX: dv.getFloat64(idx, true),
minY: dv.getFloat64(idx+8, true),
maxX: dv.getFloat64(idx+16, true),
maxY: dv.getFloat64(idx+24, true),
parts: new Int32Array(dv.getInt32(idx+32, true)),
points: new Float64Array(dv.getInt32(idx+36, true)*2)
};
idx += 40;
for (i=0; i<c.parts.length; i++) {
c.parts[i] = dv.getInt32(idx, true);
idx += 4;
}
for (i=0; i<c.points.length; i++) {
c.points[i] = dv.getFloat64(idx, true);
idx += 8;
}
break;
case 8: // MultiPoint (MBR, pointCount, points)
case 11: // PointZ (X, Y, Z, M)
case 13: // PolylineZ
case 15: // PolygonZ
case 18: // MultiPointZ
case 21: // PointM (X, Y, M)
case 23: // PolylineM
case 25: // PolygonM
case 28: // MultiPointM
case 31: // MultiPatch
throw new Error("Shape type not supported: "
+ shape.type + ':' +
+ SHP.getShapeName(shape.type));
default:
throw new Error("Unknown shape type at " + (idx-4) + ': ' + shape.type);
}
return shape;
};
/**
* @fileoverview Parses a .dbf file based on the xbase standards as documented
* here: http://www.clicketyclick.dk/databases/xbase/format/dbf.html
* @author Mano Marks
*/
// Creates global namespace.
DBF = {};
DBFParser = function() {};
DBFParser.load = function(url, encoding, callback, returnData) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
var xhrText = new XMLHttpRequest();
// var xhrTextResponse = '';
xhrText.open('GET', url);
xhrText.overrideMimeType('text/plain; charset='+encoding);
xhrText.onload = function() {
geojsonData['dbf'] = new DBFParser().parse(xhr.response,url,xhrText.responseText,encoding);
callback(geojsonData['dbf'], returnData);
URL.revokeObjectURL(url);
};
xhrText.send();
};
xhr.onerror = onerror;
xhr.send(null);
};
DBFParser.prototype.parse = function(arrayBuffer,src,response,encoding) {
var o = {},
dv = new DataView(arrayBuffer),
idx = 0,
offset = (encoding.match(/big5/i))?2:3;
o.fileName = src;
o.version = dv.getInt8(idx, false);
idx += 1;
o.year = dv.getUint8(idx) + 1900;
idx += 1;
o.month = dv.getUint8(idx);
idx += 1;
o.day = dv.getUint8(idx);
idx += 1;
o.numberOfRecords = dv.getInt32(idx, true);
idx += 4;
o.bytesInHeader = dv.getInt16(idx, true);
idx += 2;
o.bytesInRecord = dv.getInt16(idx, true);
idx += 2;
//reserved bytes
idx += 2;
o.incompleteTransation = dv.getUint8(idx);
idx += 1;
o.encryptionFlag = dv.getUint8(idx);
idx += 1;
// skip free record thread for LAN only
idx += 4;
// reserved for multi-user dBASE in dBASE III+
idx += 8;
o.mdxFlag = dv.getUint8(idx);
idx += 1;
o.languageDriverId = dv.getUint8(idx);
idx += 1;
// reserved bytes
idx += 2;
o.fields = [];
var response_handler = response.split('\r');
if(response_handler.length > 2) {
response_handler.pop();
var responseHeader = response_handler.join('\r');
responseHeader = responseHeader.slice(32, responseHeader.length);
} else {
responseHeader = response_handler[0];
responseHeader = responseHeader.slice(32, responseHeader.length);
offset = 2;
}
var charString = [],
count = 0,
index = 0,
z = 0;
/* var sum = (responseHeader.length+1)/32 */
while(responseHeader.length > 0) {
while(count < 10) {
try {
if( encodeURIComponent(responseHeader[z]).match(/%[A-F\d]{2}/g) ) {
if( encodeURIComponent(responseHeader[z]).match(/%[A-F\d]{2}/g).length > 1 ) {
count += offset;
z++;
} else {
count += 1;
z++;
}
} else {
count += 1;
z++;
}
} catch(error) { // avoid malformed URI
count += 1;
z++;
}
}
charString.push(responseHeader.slice(0, 10).replace(/\0/g, ''))
responseHeader = responseHeader.slice(32, responseHeader.length);
}
while (true) {
var field = {},
nameArray = [];
for (var i = 0, z=0; i < 10; i++) {
var letter = dv.getUint8(idx);
if (letter != 0) nameArray.push(String.fromCharCode(letter));
idx += 1;
}
field.name = charString[index++];
idx += 1;
field.type = String.fromCharCode(dv.getUint8(idx));
idx += 1;
// Skip field data address
idx += 4;
field.fieldLength = dv.getUint8(idx);
idx += 1;
//field.decimalCount = dv.getUint8(idx);
idx += 1;
// Skip reserved bytes multi-user dBASE.
idx += 2;
field.workAreaId = dv.getUint8(idx);
idx += 1;
// Skip reserved bytes multi-user dBASE.
idx += 2;
field.setFieldFlag = dv.getUint8(idx);
idx += 1;
// Skip reserved bytes.
idx += 7;
field.indexFieldFlag = dv.getUint8(idx);
idx += 1;
o.fields.push(field);
// var test = dv.getUint8(idx);
// Checks for end of field descriptor array. Valid .dbf files will have this
// flag.
if (dv.getUint8(idx) == 0x0D) break;
}
idx += 1;
o.fieldpos = idx;
o.records = [];
var responseText = response.split('\r')[response.split('\r').length-1];
for (var i = 0; i < o.numberOfRecords; i++) {
responseText = responseText.slice(1, responseText.length);
var record = {};
for (var j = 0; j < o.fields.length; j++) {
var charString = [],
count = 0,
z = 0;
while(count < o.fields[j].fieldLength) {
try {
if( encodeURIComponent(responseText[z]).match(/%[A-F\d]{2}/g) ) {
if( encodeURIComponent(responseText[z]).match(/%[A-F\d]{2}/g).length > 1 ) {
count += offset;
z++;
check = 1;
} else {
count += 1;
z++;
}
} else {
count += 1;
z++;
}
} catch(error) { // avoid malformed URI
count += 1;
z++;
}
}
charString.push(responseText.slice(0, z).replace(/\0/g, ''));
responseText = responseText.slice(z, responseText.length);
if(charString.join('').trim().match(/\d{1}\.\d{11}e\+\d{3}/g)) {
record[o.fields[j].name] = parseFloat(charString.join('').trim());
} else {
record[o.fields[j].name] = charString.join('').trim();
}
}
o.records.push(record);
}
return o;
}; | PypiClean |
/GDAL-3.7.1.1.tar.gz/GDAL-3.7.1.1/gdal-utils/osgeo_utils/auxiliary/color_table.py |
import os
import tempfile
from typing import Optional, Union
from osgeo import gdal
from osgeo_utils.auxiliary.base import PathLikeOrStr
from osgeo_utils.auxiliary.color_palette import (
ColorPalette,
ColorPaletteOrPathOrStrings,
get_color_palette,
)
from osgeo_utils.auxiliary.util import PathOrDS, open_ds
ColorTableLike = Union[gdal.ColorTable, ColorPaletteOrPathOrStrings]
def get_color_table_from_raster(path_or_ds: PathOrDS) -> Optional[gdal.ColorTable]:
ds = open_ds(path_or_ds, silent_fail=True)
if ds is None:
return None
ct = ds.GetRasterBand(1).GetRasterColorTable()
if ct is None:
return None
return ct.Clone()
def color_table_from_color_palette(
pal: ColorPalette,
color_table: gdal.ColorTable,
fill_missing_colors=True,
min_key=0,
max_key=255,
) -> bool:
"""returns None if pal has no values, otherwise returns a gdal.ColorTable from the given ColorPalette"""
if not pal.pal or not pal.is_numeric():
raise Exception("palette has no values or not fully numeric")
if fill_missing_colors:
keys = sorted(list(pal.pal.keys()))
if min_key is None:
min_key = keys[0]
if max_key is None:
max_key = keys[-1]
c = pal.color_to_color_entry(pal.pal[keys[0]])
for key in range(min_key, max_key + 1):
if key in keys:
c = pal.color_to_color_entry(pal.pal[key])
color_table.SetColorEntry(key, c)
else:
for key, col in pal.pal.items():
color_table.SetColorEntry(
key, pal.color_to_color_entry(col)
) # set color for each key
return True
def get_color_table(
color_palette_or_path_or_strings_or_ds: Optional[ColorTableLike], **kwargs
) -> Optional[gdal.ColorTable]:
if color_palette_or_path_or_strings_or_ds is None or isinstance(
color_palette_or_path_or_strings_or_ds, gdal.ColorTable
):
return color_palette_or_path_or_strings_or_ds
if isinstance(color_palette_or_path_or_strings_or_ds, gdal.Dataset):
return get_color_table_from_raster(color_palette_or_path_or_strings_or_ds)
try:
pal = get_color_palette(color_palette_or_path_or_strings_or_ds)
color_table = gdal.ColorTable()
res = color_table_from_color_palette(pal, color_table, **kwargs)
return color_table if res else None
except Exception:
# the input might be a filename of a raster file
return get_color_table_from_raster(color_palette_or_path_or_strings_or_ds)
def is_fixed_color_table(color_table: gdal.ColorTable, c=(0, 0, 0, 0)) -> bool:
for i in range(color_table.GetCount()):
color_entry: gdal.ColorEntry = color_table.GetColorEntry(i)
if color_entry != c:
return False
return True
def get_fixed_color_table(c=(0, 0, 0, 0), count=1):
color_table = gdal.ColorTable()
for i in range(count):
color_table.SetColorEntry(i, c)
return color_table
def are_equal_color_table(
color_table1: gdal.ColorTable, color_table2: gdal.ColorTable
) -> bool:
if color_table1.GetCount() != color_table2.GetCount():
return False
for i in range(color_table1.GetCount()):
color_entry1: gdal.ColorEntry = color_table1.GetColorEntry(i)
color_entry2: gdal.ColorEntry = color_table2.GetColorEntry(i)
if color_entry1 != color_entry2:
return False
return True
def write_color_table_to_file(
color_table: gdal.ColorTable, color_filename: Optional[PathLikeOrStr]
):
tmp_fd = None
if color_filename is None:
tmp_fd, color_filename = tempfile.mkstemp(suffix=".txt")
os.makedirs(os.path.dirname(color_filename), exist_ok=True)
with open(color_filename, mode="w") as fp:
for i in range(color_table.GetCount()):
color_entry = color_table.GetColorEntry(i)
color_entry = " ".join(str(c) for c in color_entry)
fp.write("{} {}\n".format(i, color_entry))
if tmp_fd:
os.close(tmp_fd)
return color_filename | PypiClean |
/ElGamalEllipticCurves-0.1.11.tar.gz/ElGamalEllipticCurves-0.1.11/README.md | This package was written for learning purposes only. It should not be used in any situation where real security is required.
I have implemented the El Gamal method of asymetric key exchnge over elliptic curves. The field, curve, and starting point used in this implementation came from http://www.secg.org/sec2-v2.pdf under the nickname 'secp256r1'. I used this curve and field because it provides an adequate level of security while remaining relatively fast. It is my understanding that fields any larger cannot be proccessed quickly due to current hardware design limitations. One way around this is by using a larger field for an initial asymetric key which would be used to communicate a symmetric key. This would seem to be a best of both worlds type approach but more research would be needed to be certain.
I chose three different classes/objects for this project. The first is modNum.The class of modNum is an integer number that can be manipulated by the usual math functions of +,-,*,/,//,**,+=,...,/= as well as it's own sqrt() function.
The second class is EllipticCurve. The EllipticCurve class has immutable class variables that define the field and curve to be used. Instantiating an instance of EllipticCurve takes two integers, x and y, and uses them to create two instances of the modNum class. The instantiation also confirms that the given x,y are valid points on the curve. This check is crucial since the field must be closed. This class also supercedes the built in functions for * and **. Multiplication becomes the elliptic curve group operation and ** powering using that group operation.
The third class is ElGamal. This class creates a random private key for each instance of the class and uses that private key to create a secondary public key, h. Using encrypt() you can encrypt any message by providing the prime and both public keys of the recipient of the message. Then using the specific instance ElGamal that generated the private key and secondary public key you can decrypt a message intended for for the create of that specifc instance. Obviously in a real application you would need to be able to store the private key. But I chose to not implement a method to do that since this code shouldn't be used in real applications.
I also wrote a full suite of tests for all exposed functions. I even wrote a specifc version of encrypt with a lower level of security to be used solely for testing purposes. | PypiClean |
/ControlYourWay-1.2.1.tar.gz/ControlYourWay-1.2.1/ControlYourWay_p27/ControlYourWay_p27.py | import ssl
import threading
import Queue
import calendar
import time
import httplib
from httplib import HTTPConnection, HTTPS_PORT
import socket
import websocket
import logging
from logging.handlers import RotatingFileHandler
# HTTPSConnection is not working in Ubuntu. This code fixes the problem
# From: http://askubuntu.com/questions/116020/python-https-requests-urllib2-to-some-sites-fail-on-ubuntu-12-04-without-proxy
class HTTPSConnection(HTTPConnection):
# This class allows communication via SSL.
default_port = HTTPS_PORT
def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
HTTPConnection.__init__(self, host, port, strict, timeout, source_address)
self.key_file = key_file
self.cert_file = cert_file
def connect(self):
# Connect to a host on a given (SSL) port.
sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address)
if self._tunnel_host:
self.sock = sock
self._tunnel()
# this is the only line we modified from the httplib.py file
# we added the ssl_version variable
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
# now we override the one in httplib
httplib.HTTPSConnection = HTTPSConnection
# ssl_version corrections are done
class CreateSendData:
def __init__(self):
"""
Object that will store the data used for building a data packet for sending to the cloud
"""
self.data = None
self.data_type = ""
self.to_session_ids = []
self.to_networks = []
self.packet_type = None
class CywConstants:
def __init__(self):
"""
Initialise all the constants used by the Control Your Way Python Library
"""
self.data_packet = -1
self.request_credentials = -2
self.cancel_request = -3
self.max_packet_size = 100000
self.minimum_download_threshold_time = 5
self.download_error_wait_time = 5
self.download_slippage_time = 2
self.minimum_download_timeout = 10
self.maximum_download_timeout = 1800
self.default_download_request_timeout = 120
self.download_decrease_time = 10
self.state_request_credentials = 0
self.state_running = 1
self.wait_before_retry_timeout = 5
self.ws_state_not_connected = 0
self.ws_state_connected_not_auth = 1
self.ws_state_connected_auth_sent = 2
self.ws_state_set_listen_to_networks = 3
self.ws_state_set_listen_to_networks_sent = 4
self.ws_state_running = 5
self.ws_state_closing_connection = 6
self.ws_state_restart_connection = 7
self.ws_state_waiting_for_connection = 8
self.ws_state_connection_timeout = 9
self.terminating_string = "~t=1"
self.websocket_keep_alive_timeout = 30
self.websocket_keep_alive_sent_timeout = 10
self.websocket_thread_dead_timeout = 10
self.use_test_server = False
self.test_server_name = 'localhost:60061'
self.thread_sleep_time = 0.1 # seconds
class CywCounters:
def __init__(self):
self.upload = 0
self.download = 0
class MasterThreadVariables:
def __init__(self):
self.waiting_for_response = False
self.wait_before_retry = 0
self.stop_request_timeout_tick = None
self.url = None
self.retry_count = 0
self.max_retries = 3
self.last_packet_sent = True
self.last_packet_uploaded = None
self.retry_packet = None
self.send_packet = None
class CloudSendPacket:
def __init__(self):
self.url = ''
self.url_ssl = ''
self.page = ''
self.post_data = ''
self.data_packet = False
self.default_params = ''
self.data_type = ''
class UploadResponse:
def __init__(self):
self.response = ''
self.packet_type = False
class DownloadResponse:
def __init__(self):
self.error_code = '0'
self.data = ''
self.data_type = ''
self.from_who = -1
class CreateCywDictionary:
def __init__(self):
self.keys = []
self.values = []
# local variables used in CywInterface class
class CywLocals:
def __init__(self):
self.server_ip_addr = ''
self.server_ip_addr2 = ''
self.download_url = ''
self.upload_url = ''
self.upload_params = ''
self.download_ssl_url = ''
self.upload_ssl_url = ''
self.auth_params = ''
self.download_page = ''
self.error_codes = CreateCywDictionary()
self.user_name = ''
self.network_password = ''
self.network_names = []
self.device_id = ''
self.session_id = -1
self.use_encryption = False
self.service_running = False
self.to_master_for_cloud_queue = CywQueue() # special queue that allows us to push one item to the front
self.from_to_cloud_to_master_queue = Queue.Queue()
self.from_from_cloud_to_master_queue = Queue.Queue()
self.to_cloud_queue = Queue.Queue()
self.last_sent_data = None
self.closing_threads = False
self.from_cloud_running = False
self.wait_before_next_request = False
self.last_download_successful = False
self.restart_download = False
self.networks_updated = False
self.discoverable = True
self.headers = {'Content-type': 'application/octet-stream'}
self.log_level = logging.ERROR
# counters
self.counters = CywCounters()
# state
self.constants = CywConstants()
self.cyw_state = self.constants.state_request_credentials
self.download_timeout = self.constants.default_download_request_timeout
# callbacks
self.data_received_callback = None
self.connection_status_callback = None
self.error_callback = None
# master thread variables
self.master_vars = MasterThreadVariables()
# threads
self.master_thread = None
self.master_thread_running = False
self.master_thread_terminated = True
self.upload_thread = None
self.upload_thread_running = False
self.upload_thread_terminated = True
self.download_thread = None
self.download_thread_running = False
self.download_thread_terminated = True
self.download_thread_request = False # set to true when service is running
self.websocket_thread = None
self.websocket_thread_running = False
self.websocket_thread_terminated = True
# WebSocket
self.websocket_state = self.constants.ws_state_not_connected
self.tick_websocket_keep_alive = calendar.timegm(time.gmtime())
self.keep_alive_sent = False
self.websocket_rec_data_buf = ''
self.websocket_receive_queue = Queue.Queue()
self.websocket_url = ''
self.websocket_ssl_url = ''
self.use_websocket = True
self.set_use_websocket = False
self.logger = logging.getLogger('cyw')
# create a new instance of a blank class
class CywNewInstance:
def __init__(self):
pass
# Custom Control Your Way queue which allows us to push one item back to the front.
# This is important because the last popped packet might not be able to be added to the current packet sent to the
# server, then it is important to put it back to the front of the queue
class CywQueue:
def __init__(self):
self.__queue = Queue.Queue()
self.__unshifted_item = None # this variable hold an item that was pushed in front
self.__queue_count = 0
def put(self, item):
self.__queue.put(item)
self.__queue_count += 1
def get(self):
if self.__unshifted_item is not None:
# return the value that was pushed to the front previously
return_value = self.__unshifted_item
self.__unshifted_item = None
self.__queue_count -= 1
return return_value
else:
self.__queue_count -= 1
return self.__queue.get()
def empty(self):
if self.__queue.empty() and self.__unshifted_item is None:
return True
return False
def unshift(self, item):
self.__unshifted_item = item
self.__queue_count += 1
def get_size(self):
return self.__queue_count
# main class used for communication
class CywInterface:
def __init__(self):
self.__locals = CywLocals()
self.name = 'cywPythonDevice'
self.connected = False
def enable_logging(self, log_filename, log_level, enable_console_logging):
"""This function will enable logging to file for debugging purposes
:param log_filename: The file that will be used to log data, send empty string not to use file logging
:param log_level: The minimum log level that will be logged to file
:param enable_console_logging: If true then send log messages to console
"""
# Add a file handler
l = self.__locals
l.log_level = log_level
for h in list(l.logger.handlers):
l.logger.removeHandler(h)
if log_filename != "":
filehandler = RotatingFileHandler(log_filename, maxBytes=10000, backupCount=5)
# create a logging format
filehandler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
l.logger.addHandler(filehandler)
# Add a console handler
if enable_console_logging:
consolehandler = logging.StreamHandler()
consolehandler.setFormatter(logging.Formatter('%(levelname)s - %(message)s'))
l.logger.addHandler(consolehandler)
l.logger.setLevel(log_level)
def log_application_message(self, log_level, message):
"""This function allows the application to log messages to the same log file used by CYW
:param log_level: The log level of the user message
:param message: The message that the user wants to log
"""
mes = 'Application message: ' + message
l = self.__locals
if log_level == logging.DEBUG:
l.logger.debug(mes)
elif log_level == logging.INFO:
l.logger.info(mes)
elif log_level == logging.WARNING:
l.logger.warning(mes)
elif log_level == logging.ERROR:
l.logger.error(mes)
elif log_level == logging.CRITICAL:
l.logger.critical(mes)
def set_user_name(self, user_name):
"""Change the user name. This can only be changed when the service is not started
:param user_name: Email address that you used to register on www.controlyourway.com
:return: 0 if successful, 10 if failed
"""
if self.__locals.cyw_state == self.__locals.constants.state_request_credentials:
self.__locals.user_name = user_name
return '0'
else:
self.__locals.logger.error('User name cannot be set after service has started')
return '10'
def set_network_password(self, network_password):
"""Change the network password for the user. This can only be changed when the service is not started
:param network_password: The network password on your account page when logged in at www.controlyourway.com.
This is not your account password.
:return: 0 if successful, 10 if failed
"""
if self.__locals.cyw_state == self.__locals.constants.state_request_credentials:
self.__locals.network_password = network_password
return '0'
else:
self.__locals.logger.error('Password cannot be set after service has started')
return '10'
def set_network_names(self, network_names):
"""Change the network names that this instance must be part of. The network names can be changed after the
service has started. For more information about network names
please see https://www.controlyourway.com/Resources/HowItWorks
:param network_names: An array of network names
:return: 0 if successful
"""
l = self.__locals
l.network_names = []
for i in range(len(network_names)):
# remove empty strings from array
if len(network_names[i]) > 0:
l.network_names.append(network_names[i])
l.networks_updated = False
l.logger.debug('New network names set')
if l.cyw_state == l.constants.state_running:
if l.use_websocket:
if l.websocket_state == l.constants.ws_state_running:
l.websocket_state = l.constants.ws_state_set_listen_to_networks
else:
# if service is already running then stop the download request so that new networks can be loaded
self.send_cancel_request()
return '0'
def get_network_names(self):
"""Return the network names that this instance is part of
:return: The network names
"""
return self.__locals.network_names
def set_use_websocket(self, use_websocket):
"""Enable or disable the use of WebSocket for the connection. If this setting is changed while
the service is running then the connection will be re-established.
:param use_websocket: True or False
"""
l = self.__locals
if l.use_websocket != use_websocket:
if l.cyw_state == l.constants.state_running:
if l.use_websocket:
# send websocket termination message
l.websocket.send('~c=t' + l.constants.terminating_string)
l.websocket_state = l.constants.ws_state_closing_connection
l.logger.debug('WebSocket: Close connection message sent')
else:
# send long polling termination message
self.send_cancel_request()
l.logger.debug('WebSocket: Long polling cancel request sent')
l.websocket_state = l.constants.ws_state_not_connected
l.set_use_websocket = True
while not l.to_master_for_cloud_queue.empty():
time.sleep(0.1) # wait for message to be sent before setting use_websocket to true
l.use_websocket = use_websocket
def get_use_websocket(self):
"""Return the true if websocket is enabled
:return: Return the true if websocket is enabled
"""
return self.__locals.use_websocket
def set_discoverable(self, discoverable):
"""If set to True then the library will automatically respond to a discovery request
:param discoverable: True or False
:return: 0 if successful
"""
self.__locals.discoverable = discoverable
self.__locals.logger.debug('Discoverable state set to %s', discoverable)
return '0'
def set_download_timeout(self, value):
"""Set the amount of time in seconds the download thread will wait before starting a new request if no data
was available. Normally user does not need to change this value
:param value: Amount of time in seconds the download thread will wait before starting a new request if no data
was available (min: 10 seconds, max: 600 seconds)
"""
if value > self.__locals.constants.maximum_download_timeout:
self.__locals.download_timeout = self.__locals.constants.maximum_download_timeout
elif value < self.__locals.constants.minimum_download_timeout:
self.__locals.download_timeout = self.__locals.constants.minimum_download_timeout
else:
self.__locals.download_timeout = value
if self.__locals.cyw_state == self.__locals.constants.state_running:
self.send_cancel_request(False)
self.__locals.logger.debug('Download timeout set to %s', self.__locals.download_timeout)
def get_download_timeout(self):
"""Return the amount of time in seconds the download thread will wait before starting a new request if no data
was available. Normally user does not need to change this value
:return: Amount of time in seconds the download thread will wait before starting a new request if no data was
available
"""
return self.__locals.download_timeout
def get_discoverable(self):
"""Return true if the discoverable state is set
:return: Discoverable state
"""
return self.__locals.discoverable
def get_user_name(self):
"""Return user name
:return: The user name
"""
return self.__locals.user_name
def get_network_password(self):
"""Return the network password
:return: The network password for this user
"""
return self.__locals.network_password
def set_use_encryption(self, value):
"""Set if encryption must be used
:param value: True or False
"""
l = self.__locals
if l.use_encryption != value:
l.use_encryption = value
if l.cyw_state == l.constants.state_running:
if l.use_websocket:
l.websocket_state = l.constants.ws_state_restart_connection
l.websocket.send('~c=c' + l.constants.terminating_string)
else:
self.send_cancel_request()
l.logger.debug('Use encryption set to %s', value)
def get_use_encryption(self):
"""Return the value if encryption is used or not
:return: True or False
"""
return self.__locals.use_encryption
def get_session_id(self):
"""Get the session ID that the server assigned to this instance.
:return: Session ID
"""
return self.__locals.session_id
def get_counters(self):
"""Return the upload and download counters. These counters get incremented each time an upload or download
is done
:return: counters variable containing counters.upload and counters.download
"""
return self.__locals.counters
def set_data_received_callback(self, cb):
"""Set the callback function which is called when data is received
:param cb: callback function name
"""
self.__locals.data_received_callback = cb
def set_connection_status_callback(self, cb):
"""Set the callback function which is called when the connection status changed.
:param cb: callback function name
"""
self.__locals.connection_status_callback = cb
def set_error_callback(self, cb):
"""Set the callback function which is called when there was an error.
:param cb: callback function name
"""
self.__locals.error_callback = cb
def start(self):
"""Start the service. This function must be called for communication with the server to start. The connection
status callback will have the result if the connection was successful
:return: 0 if successful, 6 if the user name or network password was not set
"""
l = self.__locals
if l.user_name == '':
l.logger.error('No user name specified')
return '8'
if l.network_password == '':
l.logger.error('No password specified')
return '8'
l.closing_threads = False
# start master thread
l.master_thread = threading.Thread(target=self.master_thread, args=[l.master_vars])
l.master_thread.start()
# start upload thread
l.upload_thread = threading.Thread(target=self.upload_thread)
l.upload_thread.start()
# start download thread
l.download_thread = threading.Thread(target=self.download_thread)
l.download_thread.start()
# start websocket thread
l.websocket_thread = threading.Thread(target=self.websocket_thread)
l.websocket_thread.start()
return '0'
def send_data(self, send_data):
"""Function used for sending data to the cloud
:param send_data: data structure with all the data to be sent. The data structure can be created
by calling CreateSendData()
:return: return 0 if successful, 6 if sendData.data is empty
"""
upload_data = CreateSendData()
upload_data.data = self.tilde_encode_data(send_data.data)
upload_data.to_session_ids = send_data.to_session_ids
for network in send_data.to_networks:
upload_data.to_networks.append(self.tilde_encode_data(network))
upload_data.data_type = self.tilde_encode_data(send_data.data_type)
upload_data.packet_type = self.__locals.constants.data_packet
self.__locals.to_master_for_cloud_queue.put(upload_data)
return '0'
@staticmethod
def test_ip_address(ip):
"""Check if an IP address is valid
:param ip: IP address
:return: True or False
"""
valid = True
try:
ip_parts = ip.split('.')
if len(ip_parts) != 4:
valid = False
else:
for i in range(0, 4):
num = int(ip_parts[i])
if num > 255 or num < 0:
valid = False
except ValueError:
valid = False
return valid
@staticmethod
def get_epoch_time():
"""Get the epoch time
:return: Return epoch time
"""
return calendar.timegm(time.gmtime())
@staticmethod
def check_if_data_can_be_added(packet1, packet2):
"""Compare two upload data packets. If they are the same then their data can be concatenated
:param packet1: First packet used in comparison
:param packet2: Second packet used in comparison
:return: True if packets are the same, otherwise False
"""
the_same = True
if packet1.data_type != packet2.data_type:
the_same = False
if packet1.packet_type != packet2.packet_type:
the_same = False
if len(packet1.to_networks) != len(packet2.to_networks):
the_same = False
if len(packet1.to_session_ids) != len(packet2.to_session_ids):
the_same = False
if the_same:
# check if the individual to networks and session ids are the same
for i in range(0, len(packet1.to_networks)):
if packet1.to_networks[i] != packet2.to_networks[i]:
the_same = False
for i in range(0, len(packet1.to_session_ids)):
if packet1.to_session_ids[i] != packet2.to_session_ids[i]:
the_same = False
return the_same
@staticmethod
def bracket_encode(data):
"""Build a string where all visible ASCII characters will be shown normally and non visible ASCII
characters will be shown between square brackets. An opening square bracket will be [[
:param d: The data that must be bracket encoded
:return:
"""
text = ""
for i in range(0, len(data)):
val = ord(data[i])
if val < 32 or val > 126:
text += '[' + str(val) + ']'
elif data[i] == '[':
text += '[['
else:
text += data[i]
return text
def master_thread(self, m):
"""This function must never be called directly by user. Call Start() to start the service
:param m: variables used by master thread
:return:
"""
l = self.__locals
l.master_thread_running = True
l.master_thread_terminated = False
l.logger.info('Master thread started')
while l.master_thread_running:
something_happened = False
if m.waiting_for_response:
if m.wait_before_retry < self.get_epoch_time():
something_happened = True
m.waiting_for_response = False
l.logger.error('Waiting for response timed out')
else:
if l.cyw_state == l.constants.state_request_credentials and not l.closing_threads:
# check if enough time elapsed between retries to not swamp the server
if m.wait_before_retry < self.get_epoch_time():
something_happened = True
if self.connected:
# connection failed - call connection callback
self.connected = False
if l.connection_status_callback is not None:
l.connection_status_callback(False)
m.wait_before_retry = self.get_epoch_time() + l.constants.wait_before_retry_timeout
m.waiting_for_response = True
send_packet = CywNewInstance()
if l.constants.use_test_server:
send_packet.url = l.constants.test_server_name
send_packet.url_ssl = l.constants.test_server_name
else:
send_packet.url = 'www.controlyourway.com'
send_packet.url_ssl = 'www.controlyourway.com'
send_packet.page = '/GetCredentials'
cyw_dict = CreateCywDictionary()
cyw_dict.keys.append('p') # protocol number
cyw_dict.values.append('1')
cyw_dict.keys.append('u') # username
cyw_dict.values.append(l.user_name)
cyw_dict.keys.append('ps') # network password
cyw_dict.values.append(l.network_password)
cyw_dict.keys.append('ec') # request error code descriptions
cyw_dict.values.append('1')
send_packet.post_data = CywInterface.encode_cyw_protocol(cyw_dict)
send_packet.packet_type = l.constants.request_credentials
l.to_cloud_queue.put(send_packet)
l.logger.debug('Request credentials')
l.networks_updated = False
elif l.cyw_state == l.constants.state_running:
if l.use_websocket:
if l.websocket_state == l.constants.ws_state_connected_not_auth:
l.websocket.send(l.auth_params + l.constants.terminating_string)
l.websocket_state = l.constants.ws_state_connected_auth_sent
m.wait_before_retry = self.get_epoch_time() + + l.constants.wait_before_retry_timeout
m.waiting_for_response = True
something_happened = True
l.logger.debug('WebSocket: Send connection auth message')
elif l.websocket_state == l.constants.ws_state_set_listen_to_networks:
m.wait_before_retry = self.get_epoch_time() + + l.constants.wait_before_retry_timeout
m.waiting_for_response = True
something_happened = True
l.websocket_state = l.constants.ws_state_set_listen_to_networks_sent
network_data = '~nc=1'
for i_networks in range(len(l.network_names)):
network_data += '~ns=' + CywInterface.tilde_encode_data(l.network_names[i_networks])
network_data += l.constants.terminating_string
l.websocket.send(network_data)
self.set_new_websocket_keep_alive_timeout(l.constants.websocket_keep_alive_timeout)
l.logger.debug('WebSocket: Set network names')
if not m.last_packet_sent and m.send_packet is not None:
# try again with packet that failed previously
l.to_cloud_queue.put(m.send_packet)
m.waiting_for_response = True
m.wait_before_retry = self.get_epoch_time() + l.constants.wait_before_retry_timeout
l.logger.debug('Try to send packet again')
# check if there is new data to send
elif not l.to_master_for_cloud_queue.empty():
add_id = True # id must only be added once
send_str = ''
to_cloud_packet = CywNewInstance()
to_cloud_packet.packet_type = l.constants.data_packet
to_cloud_packet.url = l.upload_url
to_cloud_packet.url_ssl = l.upload_ssl_url
to_cloud_packet.page = '/Upload'
to_cloud_packet.post_data = ''
while not l.to_master_for_cloud_queue.empty() and len(send_str) < l.constants.max_packet_size:
if not add_id:
# this is not the first message added. check if the next message in the queue is the
# same type of message, only one message type is allowed per upload
popped_packet = l.to_master_for_cloud_queue.get()
if popped_packet is None:
break
l.to_master_for_cloud_queue.unshift(popped_packet)
if m.send_packet.packet_type != popped_packet.packet_type:
break
m.send_packet = l.to_master_for_cloud_queue.get()
if m.send_packet is not None:
if m.send_packet.packet_type == l.constants.data_packet:
if add_id:
add_id = False
if not l.use_websocket:
to_cloud_packet.post_data += l.upload_params
# add networks
for i in range(len(m.send_packet.to_networks)):
if m.send_packet.to_networks[i] != '':
to_cloud_packet.post_data += '~n=' + m.send_packet.to_networks[i]
# add session IDs
for i in range(len(m.send_packet.to_session_ids)):
if m.send_packet.to_session_ids[i] != '':
to_cloud_packet.post_data += '~s=' + m.send_packet.to_session_ids[i]
# add data type if present
if m.send_packet.data_type != '':
to_cloud_packet.post_data += '~dt=' + m.send_packet.data_type
# add data - must be the last parameter per message
to_cloud_packet.post_data += '~d=' + m.send_packet.data
# see if more packets can be added
while not l.to_master_for_cloud_queue.empty() and len(send_str) < l.constants.max_packet_size:
# make sure that data is going to the same URL before dequeueing it
popped_packet = l.to_master_for_cloud_queue.get()
if popped_packet is not None:
if CywInterface.check_if_data_can_be_added(m.send_packet, popped_packet):
# add the data because the data is going to the same devices
to_cloud_packet.post_data += popped_packet.data
else:
# push back to front of queue because parameters are different
l.to_master_for_cloud_queue.unshift(popped_packet)
break
else:
break
elif m.send_packet.packet_type == l.constants.cancel_request:
to_cloud_packet = CywNewInstance()
to_cloud_packet.packet_type = l.constants.cancel_request
to_cloud_packet.url = l.upload_url
to_cloud_packet.url_ssl = l.upload_ssl_url
to_cloud_packet.post_data = m.send_packet.data
to_cloud_packet.page = '/CancelDownload'
m.retry_count = 0
if l.use_websocket:
to_cloud_packet.post_data += l.constants.terminating_string
else:
# add counter
to_cloud_packet.post_data += '~z=' + str(l.counters.upload)
if l.log_level == logging.DEBUG:
# log detailed data about the data that was sent
log_str = "Data sent: " \
+ CywInterface.bracket_encode(to_cloud_packet.post_data)
l.logger.debug(log_str)
if l.use_websocket:
l.websocket.send(to_cloud_packet.post_data)
self.set_new_websocket_keep_alive_timeout(l.constants.websocket_keep_alive_timeout)
l.logger.debug('WebSocket: Sending packet')
else:
l.to_cloud_queue.put(to_cloud_packet)
l.logger.debug('Long Polling: Sending packet')
l.counters.upload += 1
m.waiting_for_response = True
m.wait_before_retry = self.get_epoch_time() + l.constants.wait_before_retry_timeout
# //////////////////////////////////////////////////////////////////////////////////////////////
# process data received from web socket
if not l.websocket_receive_queue.empty():
wsdict = l.websocket_receive_queue.get()
if wsdict is not None:
something_happened = True
response_type_value = CywInterface.get_cyw_dictionary_single_value(wsdict, 'rt')
ws_error_code = '0'
if (response_type_value != 'r') and (response_type_value != 'k'):
# receive data does not have an error code
ws_error_code = CywInterface.get_cyw_dictionary_single_value(wsdict, 'e')
if response_type_value == 'a': # authentication response
if ws_error_code == '0':
# connection authenticated
l.websocket_state = l.constants.ws_state_set_listen_to_networks
l.logger.debug('WebSocket connection authenticated')
self.set_new_websocket_keep_alive_timeout(l.constants.websocket_keep_alive_timeout)
else:
l.logger.debug('WebSocket authentication failed, error code: ' + ws_error_code)
l.cyw_state = l.constants.state_request_credentials
l.websocket_state = l.constants.ws_state_not_connected
try:
l.websocket.close()
except:
l.logger.error('Exception trying to close WebSocket connection')
m.waiting_for_response = False
self.set_new_websocket_keep_alive_timeout(l.constants.websocket_keep_alive_timeout)
l.keep_alive_sent = False
elif response_type_value == 'n': # set listen to networks response
l.networks_updated = True
l.websocket_state = l.constants.ws_state_running
if ws_error_code == '4': # New set of networks to which device is listening was set
l.logger.debug('All listen to networks was set')
elif ws_error_code == '5': # Not all of the networks to which device is listening was set
l.logger.error('Not all listen to networks was set')
if l.error_callback is not None:
l.error_callback(ws_error_code)
elif ws_error_code == '12': # session id expired
l.websocket_state = l.constants.ws_state_not_connected
l.cyw_state = l.constants.state_request_credentials
l.logger.debug('Session id expired, request credentials again')
else:
l.logger.error('Error updating networks: ' + ws_error_code)
if l.error_callback is not None:
l.error_callback(ws_error_code)
m.waiting_for_response = False
self.set_new_websocket_keep_alive_timeout(l.constants.websocket_keep_alive_timeout)
l.keep_alive_sent = False
elif response_type_value == 's': # send data response
send_error = False
if ws_error_code == '0': # success
l.logger.debug('Last message sent')
elif ws_error_code == '1': # Unknown error
send_error = True
l.logger.error('Unknown error sending last message')
elif ws_error_code == '2': # Data could not be sent to one or more recipients
send_error = True
l.logger.error('Data could not be sent to one or more recipients')
elif ws_error_code == '7': # Protocol error
send_error = True
l.logger.error('Sending data protocol error')
elif ws_error_code == '12': # expired session id
l.websocket_state = l.constants.ws_state_not_connected
l.cyw_state = l.constants.state_request_credentials
l.logger.error('Sending data, session id expired')
elif ws_error_code == '20': # Could not establish connection to website
send_error = True
l.logger.error('Could not establish connection to website')
else:
l.logger.error('Invalid data received from server')
ws_error_code = '3' # Invalid data received from server, please restart service
send_error = True
if send_error:
if l.error_callback is not None:
l.error_callback(ws_error_code)
m.last_packet_sent = True
m.waiting_for_response = False
self.set_new_websocket_keep_alive_timeout(l.constants.websocket_keep_alive_timeout)
l.keep_alive_sent = False
elif response_type_value == 'r': # receive data
ws_rec_data = DownloadResponse()
l.logger.debug('Data received from server')
for i_rec_data in range(1, len(wsdict.keys)):
if wsdict.keys[i_rec_data] == 'f': # from session id
ws_rec_data.from_who = int(wsdict.values[i_rec_data])
elif wsdict.keys[i_rec_data] == 'dt': # data type
ws_rec_data.data_type = wsdict.values[i_rec_data]
elif wsdict.keys[i_rec_data] == 'd': # data
ws_rec_data.data = wsdict.values[i_rec_data]
l.from_from_cloud_to_master_queue.put(ws_rec_data)
ws_rec_data = DownloadResponse()
elif response_type_value == 'k':
self.set_new_websocket_keep_alive_timeout(l.constants.websocket_keep_alive_timeout)
l.keep_alive_sent = False
l.logger.debug('WebSocket: Keep alive message acknowledged')
elif response_type_value == 'c':
if ws_error_code == '0':
if l.websocket_state == l.constants.ws_state_restart_connection:
l.websocket_state = l.constants.ws_state_not_connected
else:
l.websocket_state = l.constants.ws_state_closing_connection
l.websocket.close()
l.logger.info('WebSocket: Connection closed')
if l.closing_threads:
l.cyw_state = l.constants.state_request_credentials
if self.connected:
self.connected = False
if l.connection_status_callback is not None:
l.connection_status_callback(False)
l.logger.info('WebSocket: Stopped the service')
else:
l.logger.error('WebSocket: Error closing connection')
if l.error_callback is not None:
l.error_callback(ws_error_code)
if l.use_websocket:
if (m.wait_before_retry < self.get_epoch_time()) and \
(l.websocket_state == l.constants.ws_state_waiting_for_connection):
# connection has timed out, try again
something_happened = True
l.websocket_state = l.constants.ws_state_not_connected
m.waiting_for_response = False
if (m.wait_before_retry < self.get_epoch_time()) and \
(l.websocket_state == l.constants.ws_state_connected_auth_sent):
# authorisation sent but has timed out, send it again
something_happened = True
l.websocket_state = l.constants.ws_state_connected_not_auth
m.waiting_for_response = False
l.logger.debug('WebSocket: Auth timed out, trying again')
if (m.wait_before_retry < self.get_epoch_time()) and \
(l.websocket_state == l.constants.ws_state_set_listen_to_networks_sent):
# no response when setting networks, try again
something_happened = True
m.waiting_for_response = False
l.websocket_state = l.constants.ws_state_set_listen_to_networks
l.logger.debug('WebSocket: Setting networks timed out, trying again')
if (l.websocket_state == l.constants.ws_state_running) and \
(self.check_if_websocket_keep_alive_expired()):
if not l.keep_alive_sent:
l.websocket.send(l.constants.terminating_string)
self.set_new_websocket_keep_alive_timeout(l.constants.websocket_keep_alive_sent_timeout)
l.keep_alive_sent = True
l.logger.debug('WebSocket: Keep alive message sent')
else:
# websocket response timed out, connection is dead. Create new connection
l.websocket_state = l.constants.ws_state_connection_timeout
m.waiting_for_response = False
self.set_new_websocket_keep_alive_timeout(l.constants.websocket_thread_dead_timeout)
try:
l.websocket.keep_running = False
except:
l.logger.debug('WebSocket: keep_running parameter not supported')
try:
l.websocket.close()
except:
l.logger.debug('WebSocket: error closing websocket connection')
l.logger.debug('WebSocket: Timeout, restarting connection')
if (l.websocket_state == l.constants.ws_state_connection_timeout) and \
(self.check_if_websocket_keep_alive_expired()):
l.logger.debug('WebSocket: WebScoket thread hanged up, create new websocket thread')
l.websocket_state = l.constants.ws_state_not_connected
l.websocket_thread = threading.Thread(target=self.websocket_thread)
l.websocket_thread.start()
# //////////////////////////////////////////////////////////////////////////////////////////////
# see if response from toCloud thread
if not l.from_to_cloud_to_master_queue.empty():
# parse response from upload request
d = l.from_to_cloud_to_master_queue.get()
l.logger.debug('To cloud thread data received')
if d is not None:
something_happened = True
m.waiting_for_response = False
cyw_dict = CywInterface.decode_cyw_protocol(d.response)
error_code = CywInterface.get_cyw_dictionary_single_value(cyw_dict, 'e')
if d.packet_type == l.constants.request_credentials:
if error_code == '0': # success
l.device_id = CywInterface.get_cyw_dictionary_single_value(cyw_dict, 'id')
urls = CywInterface.get_cyw_dictionary_values(cyw_dict, 'ip')
if len(urls) == 2:
if l.constants.use_test_server:
ip_ok = True
ip_ok2 = True
else:
ip_ok = self.test_ip_address(urls[0])
ip_ok2 = self.test_ip_address(urls[1])
if ip_ok and ip_ok2:
l.server_ip_addr = urls[0]
l.server_ip_addr2 = urls[1]
domain_names = CywInterface.get_cyw_dictionary_values(cyw_dict, 'dn')
l.upload_ssl_url = domain_names[0]
l.download_ssl_url = domain_names[1]
# extract session ID from device ID
session_id_str = ''
for i in range(len(l.device_id)):
if l.device_id[i] == 's':
# got the whole session ID
l.session_id = int(session_id_str)
break
else:
session_id_str += l.device_id[i]
# store the error codes
store_error_codes = False
l.error_codes = CreateCywDictionary()
for ie in range(len(cyw_dict.keys)):
if cyw_dict.keys[ie] == '0':
# this is the first error code
store_error_codes = True
if store_error_codes:
l.error_codes.keys.append(cyw_dict.keys[ie])
l.error_codes.values.append((cyw_dict.values[ie]))
l.cyw_state = l.constants.state_running
self.build_urls()
l.download_thread_request = True # download thread can start requesting
self.connected = True
l.logger.debug('Got credentials from server')
if l.connection_status_callback is not None:
l.connection_status_callback(True)
else:
l.logger.debug('Error parsing server IP address')
elif error_code == '8': # invalid username or network password
# stop service
l.closing_threads = True
l.cyw_state = l.constants.state_request_credentials
self.connected = False
l.download_thread_running = False
l.upload_thread_running = False
l.master_thread_running = False
l.websocket_thread_running = False
if l.connection_status_callback is not None:
l.connection_status_callback(False)
if l.error_callback is not None:
l.error_callback(error_code)
l.logger.error('Invalid user credentials')
elif error_code == '20': # connection problem
if l.error_callback is not None:
l.error_callback(error_code)
l.logger.debug('Could not connect to server')
else: # protocol error
if l.error_callback is not None:
l.error_callback('7')
l.logger.debug('Protocol error')
elif d.packet_type == l.constants.data_packet:
send_error = False # fail immediately if true
retry_message = False # retry message again if we have not reached max retries
if error_code == '0': # success
l.logger.debug('Last message sent')
elif error_code == '1': # unknown error
retry_message = True
l.logger.debug('Unknown error')
elif error_code == '2': # data could not be sent to one or more recipients
send_error = True
l.logger.debug('Data could not be sent to one or more recipients')
elif error_code == '7': # protocol error
retry_message = True
l.logger.debug('Protocol error')
elif error_code == '12': # invalid/expired id
send_error = True
l.cyw_state = l.constants.state_request_credentials
l.logger.debug('Expired/invalid session id')
elif error_code == '15': # response to a cancel request
if l.closing_threads:
l.cyw_state = l.constants.state_request_credentials
self.connected = False
if l.connection_status_callback is not None:
l.connection_status_callback(False)
l.logger.debug('Stopped the service')
elif error_code == '20': # could not establish connection to website
retry_message = True
l.logger.debug('Could not establish connection to website')
else:
error_code = '3' # invalid data received from server
retry_message = True
l.logger.debug('Invalid data received from server')
if retry_message:
if m.retry_count < m.max_retries:
m.last_packet_sent = False
m.send_packet = m.last_packet_uploaded
m.retry_count += 1
l.logger.debug('Retrying...')
else:
m.last_packet_sent = True
l.logger.debug('Max retries reached')
if l.error_callback is not None:
l.error_callback(error_code)
if send_error:
l.logger.debug('Send error')
if l.error_callback is not None:
l.error_callback(error_code)
# ////////////////////////////////////////////////////////////////////////////////////////////
# data from FromCloud thread
if not l.from_from_cloud_to_master_queue.empty():
d = l.from_from_cloud_to_master_queue.get()
l.logger.debug('From cloud thread data received')
if d is not None:
something_happened = True
if d.error_code == '0': # no error - data was received
if l.discoverable and d.data == '?' and d.data_type == 'Discovery':
# send discovery response
send_data = CreateSendData()
send_data.data_type = "Discovery Response"
send_data.data = self.name
send_data.to_session_ids.append(str(d.from_who))
self.send_data(send_data)
l.logger.debug('Discovery response sent')
else:
d_mes = 'Data received: ' + d.data + ', Data type: ' + d.data_type
d_mes += ', From: ' + str(d.from_who)
l.logger.debug(d_mes)
if l.data_received_callback is not None:
l.data_received_callback(d.data, d.data_type, d.from_who)
elif d.error_code == '12': # invalid session id
l.cyw_state = l.constants.state_request_credentials
l.logger.debug('Invalid session ID from FromCloud thread')
# elif '16': # no data available
elif d.error_code == '18': # multiple download requests made with the same session id
l.cyw_state = l.constants.state_request_credentials
l.logger.debug('Multiple downloads from same session ID')
elif d.error_code == '24': # download request timeout changed
l.logger.debug('Download request timeout changed to: ' + str(l.download_timeout) + ' seconds')
if not something_happened:
time.sleep(l.constants.thread_sleep_time)
l.master_thread_terminated = True
l.logger.debug('Master thread terminated')
def upload_thread(self):
"""This function must never be called directly by user. Call Start() to start the service
:return:
"""
l = self.__locals
l.upload_thread_running = True
l.upload_thread_terminated = False
l.logger.debug('Upload thread started')
while l.upload_thread_running:
if not l.to_cloud_queue.empty():
try:
packet = l.to_cloud_queue.get()
l.master_vars.last_packet_uploaded = packet
if l.use_encryption:
where = packet.url_ssl
# if l.ssl_context_upload is None:
# l.ssl_context_upload = ssl.create_default_context()
con = httplib.HTTPSConnection(where, 443)
else:
where = packet.url
con = httplib.HTTPConnection(where)
upload_response = UploadResponse()
con.request('POST', packet.page, packet.post_data, l.headers)
response = con.getresponse()
l.logger.debug('Upload request sent')
upload_response.packet_type = packet.packet_type
if response.status == 200:
upload_response.response = response.read()
else:
upload_response.response = '~e=20' # Could not establish connection to website
except:
upload_response.response = '~e=20' # Could not establish connection to website
l.from_to_cloud_to_master_queue.put(upload_response)
else:
time.sleep(self.__locals.constants.thread_sleep_time)
l.upload_thread_terminated = True
l.logger.debug('Upload thread terminated')
def download_thread(self):
"""This function must never be called directly by user. Call Start() to start the service
:return:
"""
l = self.__locals
l.download_thread_running = True
l.download_thread_terminated = False
l.restart_download = False
l.last_download_successful = False
download_started_time = self.get_epoch_time()
l.logger.debug('Download thread started')
while l.download_thread_running:
if l.use_websocket:
# this thread must not do anything if we use websocket
time.sleep(0.2)
else:
wait_before_next_request = False
if l.cyw_state == l.constants.state_running:
url = ''
previous_download_started_time = download_started_time
download_started_time = self.get_epoch_time()
try:
if l.use_encryption:
url += l.download_ssl_url
# if l.ssl_context_download is None:
# l.ssl_context_download = ssl.create_default_context()
con = httplib.HTTPSConnection(url, 443, timeout=l.download_timeout+30)
else:
url += l.download_url
con = httplib.HTTPConnection(url, timeout=l.download_timeout+30)
post_data = l.auth_params
update_networks = False
if not l.networks_updated:
for i in range(len(l.network_names)):
post_data += '~n=' + CywInterface.tilde_encode_data(l.network_names[i])
update_networks = True
else:
if l.download_timeout != l.constants.default_download_request_timeout:
post_data += '~t=' + str(l.download_timeout)
if l.restart_download:
l.restart_download = False
post_data += '~r=1'
post_data += '~z=' + str(l.counters.download)
if update_networks:
l.logger.debug('Update default networks started (' + str(l.counters.download) + ')')
else:
l.logger.debug('New download request started (' + str(l.counters.download) + ')')
l.counters.download += 1
con.request('POST', l.download_page, post_data, l.headers)
response = con.getresponse()
l.logger.debug('Download response received')
if response.status == 200:
temp_resp = response.read()
cyw_dict = CywInterface.decode_cyw_protocol(temp_resp)
error_code = CywInterface.get_cyw_dictionary_single_value(cyw_dict, 'e')
if error_code is None:
l.wait_before_next_request = True
else:
if error_code == '0':
d = DownloadResponse()
for i in range(len(cyw_dict.keys)):
if cyw_dict.keys[i] == 'f': # from session id
d.from_who = int(cyw_dict.values[i])
elif cyw_dict.keys[i] == 'dt': # data type
d.data_type = cyw_dict.values[i]
elif cyw_dict.keys[i] == 'd': # data
d.data = cyw_dict.values[i]
l.from_from_cloud_to_master_queue.put(d)
d = DownloadResponse()
l.last_download_successful = True
elif error_code == '1': # unknown error
l.logger.debug('Download error - Unknown error')
l.wait_before_next_request = True
elif error_code == '4': # new set of networks to which device is listening was set
l.networks_updated = True
l.logger.debug('All listen to networks was set')
l.last_download_successful = True
elif error_code == '5': # not all of the networks to which device is listening was set
l.networks_updated = True
l.logger.debug('Not all listen to networks was set')
if l.error_callback is not None:
l.error_callback(error_code)
l.last_download_successful = True
elif error_code == '7': # protocol error
l.logger.debug('Download error - Protocol error')
l.wait_before_next_request = True
l.last_download_successful = True
elif error_code == '12': # invalid/expired id
d = DownloadResponse()
d.error_code = error_code
l.from_from_cloud_to_master_queue.put(d)
l.logger.debug('Download error - Session ID expired')
l.wait_before_next_request = True
l.last_download_successful = True
l.cyw_state = l.constants.state_request_credentials
elif error_code == '15': # download request cancelled by user
l.logger.debug('Download cancelled by user')
l.last_download_successful = True
if l.set_use_websocket:
l.set_use_websocket = False
l.use_websocket = True
elif error_code == '16': # no data available - restart connection immediately
l.last_download_successful = True
elif error_code == '18': # multiple download requests made with the same session ID
# there are devices on the internet that will send the same request to the server again
# without us knowing about it. This will cause a duplicate request error.
# if the request is older than 5 seconds then this is what happened. Calculate the time
# it took and make sure that the request time is shorter than this
l.logger.debug('Multiple requests to same session ID')
current_time = self.get_epoch_time()
if l.last_download_successful:
delta_t = current_time - download_started_time
else:
delta_t = current_time - previous_download_started_time
check_time = l.constants.minimum_download_threshold_time
if not l.last_download_successful:
# the download request waited before making a new request - account for that
check_time += l.constants.download_error_wait_time
check_time += l.constants.download_slippage_time
if delta_t >= 5:
delta_t -= l.constants.download_decrease_time
delta_t -= l.constants.download_slippage_time
if not l.last_download_successful:
# the download thread waited for 5 seconds before starting a new request
# subtract that as well
delta_t -= l.constants.minimum_download_threshold_time
if delta_t < l.constants.minimum_download_timeout:
delta_t = l.constants.minimum_download_timeout
if delta_t <= l.download_timeout:
l.download_timeout = int(delta_t)
d = DownloadResponse()
d.error_code = '24'
l.restart_download = True
l.from_from_cloud_to_master_queue.put(d)
else:
d = DownloadResponse()
d.error_code = error_code
l.from_from_cloud_to_master_queue.put(d)
l.last_download_successful = True
except:
wait_before_next_request = True
l.last_download_successful = False
if wait_before_next_request:
time.sleep(5)
else:
time.sleep(0.1)
l.download_thread_terminated = True
l.logger.debug('Download thread terminated')
def build_urls(self):
"""This function must never be called directly by user. Call Start() to start the service
:return:
"""
l = self.__locals
# build download parameters
l.download_url = l.server_ip_addr2
l.download_page = '/Download'
l.auth_params = '~id=' + l.device_id
# build upload url
l.upload_url = l.server_ip_addr
l.upload_page = '/Upload'
l.upload_params = '~id=' + l.device_id
# build websocket urls
l.websocket_url = 'ws://' + l.upload_url + '/api/WebSocket'
l.websocket_ssl_url = 'wss://' + l.upload_ssl_url + '/api/WebSocket'
def send_cancel_request(self, terminate_session=False):
"""This function must never be called directly by user. Call Start() to start the service
:param terminate_session: If this value is set to true then the server will terminate the session for this
device. A new session has to be started if the device needs to connect again.
:return:
"""
l = self.__locals
if l.cyw_state != l.constants.state_request_credentials: # service is running
send_packet = CloudSendPacket()
send_packet.url = l.server_ip_addr
send_packet.url_ssl = l.upload_ssl_url
send_packet.page = '/CancelDownload'
post_str = '~id=' + l.device_id
if terminate_session:
post_str += '~ts=1'
l.closing_threads = True
send_packet.data = post_str
send_packet.packet_type = l.constants.cancel_request
l.to_master_for_cloud_queue.put(send_packet)
l.logger.debug('Download cancel request sent to server')
def close_connection(self, clear_callbacks=False):
""" Must be called when service is stopped. This will close all the connections and threads
:param clear_callbacks: Set to true to clear all the callback. This is useful when this function
is called from the window close event. Any callback called with generate an error.
"""
l = self.__locals
if clear_callbacks:
l.data_received_callback = None
l.connection_status_callback = None
l.error_callback = None
l.closing_threads = True
if l.download_thread_running: #check if threads are running
l.download_thread_running = False
if l.cyw_state == l.constants.state_running:
if l.use_websocket:
try:
l.websocket.send('~c=t' + l.constants.terminating_string) # send websocket termination message
l.websocket_state = l.constants.ws_state_closing_connection
l.logger.debug('WebSocket: Close connection message sent')
except Exception, e:
l.logger.error('Error closing WebSocket connection: ' + str(e))
l.websocket_state = l.constants.ws_state_not_connected
else:
self.send_cancel_request(True)
l.logger.debug('Long polling: Close connection message sent')
l.download_thread.join()
l.upload_thread_running = False
l.upload_thread.join()
l.websocket_thread_running = False
l.websocket_thread.join()
l.master_thread_running = False
l.master_thread.join()
if self.connected:
self.connected = False
if l.connection_status_callback is not None:
l.connection_status_callback(False)
def convert_error_code_to_string(self, error_code):
"""Return a string with the description for an error code
:param error_code: The error code, for example: 0
:return: The description of the error
"""
if self.__locals.error_codes is None:
return error_code
if type(error_code) is int:
error_code_num = str(error_code)
elif type(error_code) is str:
error_code_num = error_code
else:
return error_code
error_str = CywInterface.get_cyw_dictionary_single_value(self.__locals.error_codes, error_code_num)
if error_str is None:
error_str = 'Check https://www.controlyourway.com/Resources/CywErrorCodes for error codes'
return error_str
@staticmethod
def get_cyw_dictionary_values(cyw_dict, key):
"""Search the dictionary and return an array of values that matched the key
:param cyw_dict: Dictionary to be searched
:param key: Key to look for in dictionary
:return: An array of values that matched the key
"""
values = []
for i in range(len(cyw_dict.keys)):
if cyw_dict.keys[i] == key:
values.append(cyw_dict.values[i])
return values
@staticmethod
def get_cyw_dictionary_single_value(cyw_dict, key):
"""Search the dictionary and return the first value that matches the key
:param cyw_dict: Dictionary to be searched
:param key: First key to look for in dictionary
:return: The value of the first key that matches, otherwise None
"""
value = None
for i in range(len(cyw_dict.keys)):
if cyw_dict.keys[i] == key:
# found first key that matched
value = cyw_dict.values[i]
break
return value
@staticmethod
def tilde_encode_data(data):
"""Tilde is the control character used by Control Your Way. This function will encode the tilde character
and the character for ASCII 0
:param data: The data that must be encoded
:return: The encoded data
"""
encoded = ''
for i in range(0, len(data)):
if data[i] == '~':
encoded += '~~'
elif ord(data[i]) == 0:
encoded += '~-'
else:
encoded += data[i]
return encoded
@staticmethod
def encode_cyw_protocol(cyw_dict):
"""Will generate an output string based on a cyw dictionary. The values will be tilde encoded
:param cyw_dict: Input cyw dictionary
:return: The output string
"""
encoded_data = ''
for i in range(0, len(cyw_dict.keys)):
encoded_data += '~' + cyw_dict.keys[i] + '=' + CywInterface.tilde_encode_data(cyw_dict.values[i])
return encoded_data
@staticmethod
def decode_cyw_protocol(data):
"""This function will decode the Control Your Way protocol where a tilde is used as a control character
:param data: Raw data received from the server
:return: Return a CYW dictionary with all the decoded data
"""
cyw_dict = CreateCywDictionary()
state_key = 0
state_value = 1
state_control_char_in_value = 2
state = state_key
the_key = ''
the_value = ''
control_char = '~'
end_of_key = '='
if data[0] != '~':
return # protocol problem
for i in range(1, len(data)):
c = data[i]
last_char = False
if i == len(data) - 1:
last_char = True
if state == state_key:
if last_char or c == control_char:
return cyw_dict
if c == end_of_key:
state = state_value
else:
the_key += c
elif state == state_value:
if c == control_char:
if last_char:
return # last character cannot be a control character
else:
state = state_control_char_in_value
else:
the_value += c
if last_char:
cyw_dict.keys.append(the_key)
cyw_dict.values.append(the_value)
elif state == state_control_char_in_value:
if c == control_char:
# double tilde means a tilde was sent
the_value += c
state = state_value
if last_char:
cyw_dict.keys.append(the_key)
cyw_dict.values.append(the_value)
elif c == '-':
# this means a zero was sent in the string
the_value += chr(0)
state = state_value
if last_char:
cyw_dict.keys.append(the_key)
cyw_dict.values.append(the_value)
else:
if last_char:
return # last character cannot be a control character
else:
cyw_dict.keys.append(the_key)
cyw_dict.values.append(the_value)
the_key = ''
the_value = ''
the_key += c
state = state_key
return cyw_dict
def send_discovery(self, to_networks=None):
send_data = CreateSendData()
if to_networks is not None:
send_data.to_networks = to_networks
send_data.data_type = 'Discovery'
send_data.data = '?'
self.send_data(send_data)
def get_buffered_amount(self):
return self.__locals.to_master_for_cloud_queue.get_size()
def set_new_websocket_keep_alive_timeout(self, seconds_from_now):
self.tick_websocket_keep_alive = self.get_epoch_time() + seconds_from_now
def check_if_websocket_keep_alive_expired(self):
if self.tick_websocket_keep_alive < self.get_epoch_time():
return True # expired
return False
def websocket_onopen(self, ws):
l = self.__locals
l.logger.debug('WebSocket onopen event')
l.websocket_state = l.constants.ws_state_connected_not_auth
def websocket_onclose(self, ws):
l = self.__locals
l.logger.debug('WebSocket onclose event')
if l.websocket_state != l.constants.ws_state_waiting_for_connection: # connection has already been restarted
l.websocket_state = l.constants.ws_state_not_connected
def websocket_onerror(self, ws, error):
l = self.__locals
l.logger.debug('WebSocket onerror event' + error)
# restart connection on websocket error
l.websocket_state = l.constants.ws_state_not_connected
l.websocket.close()
l.cyw_state = l.constants.state_request_credentials
def websocket_onmessage(self, ws, message):
l = self.__locals
if l.log_level == logging.DEBUG:
# log detailed data about the data that was received
log_str = "WebSocket onmessage event, data received: " \
+ CywInterface.bracket_encode(message)
l.logger.debug(log_str)
l.websocket_rec_data_buf += message
while self.process_websocket_rec_data():
pass
def websocket_thread(self):
"""This function must never be called directly by user. Call Start() to start the service
:return:
"""
l = self.__locals
l.websocket_thread_running = True
l.websocket_thread_terminated = False
l.logger.info('WebSocket thread started')
while l.websocket_thread_running:
if not l.use_websocket:
time.sleep(0.2) # this thread must not do anything when long polling is used
else:
if l.cyw_state == l.constants.state_running:
if l.websocket_state == l.constants.ws_state_not_connected:
try:
# websocket.enableTrace(True)
l.logger.debug('Create WebSocket connection')
if l.use_encryption:
connect_str = l.websocket_ssl_url
else:
connect_str = l.websocket_url
l.websocket = websocket.WebSocketApp(connect_str,
on_message = self.websocket_onmessage,
on_error = self.websocket_onerror,
on_close = self.websocket_onclose)
l.websocket.on_open = self.websocket_onopen
l.websocket.run_forever()
l.logger.debug('WebSocket connection returned')
l.websocket_state = l.constants.ws_state_waiting_for_connection
except:
l.logger.debug('Error opening WebSocket connection')
time.sleep(1)
time.sleep(0.1)
l.websocket_thread_terminated = True
l.logger.debug('WebSocket thread terminated')
def process_websocket_rec_data(self):
l = self.__locals
try:
terminating_tag_index = l.websocket_rec_data_buf.index(l.constants.terminating_string)
# at least one complete message was received
terminating_tag_index += 4 # add size of terminating tag
new_message = l.websocket_rec_data_buf[:terminating_tag_index]
l.websocket_rec_data_buf = l.websocket_rec_data_buf[terminating_tag_index:] # remove received part
dict = CywInterface.decode_cyw_protocol(new_message)
l.websocket_receive_queue.put(dict)
except:
return False
return True | PypiClean |
/Beat_ML1-0.13.1.tar.gz/Beat_ML1-0.13.1/econml/iv/dr/_dr.py | import numpy as np
from sklearn.base import clone
from sklearn.linear_model import LinearRegression, LogisticRegressionCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer
from sklearn.dummy import DummyClassifier
from ..._ortho_learner import _OrthoLearner
from ..._cate_estimator import (StatsModelsCateEstimatorMixin, DebiasedLassoCateEstimatorMixin,
ForestModelFinalCateEstimatorMixin, GenericSingleTreatmentModelFinalInference,
LinearCateEstimator)
from ...inference import StatsModelsInference
from ...sklearn_extensions.linear_model import StatsModelsLinearRegression, DebiasedLasso, WeightedLassoCVWrapper
from ...sklearn_extensions.model_selection import WeightedStratifiedKFold
from ...utilities import (_deprecate_positional, add_intercept, filter_none_kwargs,
inverse_onehot, get_feature_names_or_default, check_high_dimensional, check_input_arrays)
from ...grf import RegressionForest
from ...dml.dml import _FirstStageWrapper, _FinalWrapper
from ...iv.dml import NonParamDMLIV
from ..._shap import _shap_explain_model_cate
class _BaseDRIVModelNuisance:
def __init__(self, prel_model_effect, model_y_xw, model_t_xw, model_tz_xw, model_z, projection,
discrete_treatment, discrete_instrument):
self._prel_model_effect = prel_model_effect
self._model_y_xw = model_y_xw
self._model_t_xw = model_t_xw
self._model_tz_xw = model_tz_xw
self._projection = projection
self._discrete_treatment = discrete_treatment
self._discrete_instrument = discrete_instrument
if self._projection:
self._model_t_xwz = model_z
else:
self._model_z_xw = model_z
def _combine(self, W, Z, n_samples):
if Z is not None: # Z will not be None
Z = Z.reshape(n_samples, -1)
return Z if W is None else np.hstack([W, Z])
return None if W is None else W
def fit(self, Y, T, X=None, W=None, Z=None, sample_weight=None, groups=None):
# T and Z only allow single continuous or binary, keep the shape of (n,) for continuous and (n,1) for binary
T = T.ravel() if not self._discrete_treatment else T
Z = Z.ravel() if not self._discrete_instrument else Z
self._model_y_xw.fit(X=X, W=W, Target=Y, sample_weight=sample_weight, groups=groups)
self._model_t_xw.fit(X=X, W=W, Target=T, sample_weight=sample_weight, groups=groups)
if self._projection:
WZ = self._combine(W, Z, Y.shape[0])
self._model_t_xwz.fit(X=X, W=WZ, Target=T, sample_weight=sample_weight, groups=groups)
# fit on projected Z: E[T * E[T|X,Z]|X]
T_proj = self._model_t_xwz.predict(X, WZ).reshape(T.shape)
# if discrete, return shape (n,1); if continuous return shape (n,)
target = (T * T_proj).reshape(T.shape[0],)
self._model_tz_xw.fit(X=X, W=W, Target=target,
sample_weight=sample_weight, groups=groups)
else:
self._model_z_xw.fit(X=X, W=W, Target=Z, sample_weight=sample_weight, groups=groups)
if self._discrete_treatment:
if self._discrete_instrument:
# target will be discrete and will be inversed from FirstStageWrapper, shape (n,1)
target = T * Z
else:
# shape (n,)
target = inverse_onehot(T) * Z
else:
if self._discrete_instrument:
# shape (n,)
target = T * inverse_onehot(Z)
else:
# shape(n,)
target = T * Z
self._model_tz_xw.fit(X=X, W=W, Target=target,
sample_weight=sample_weight, groups=groups)
# TODO: prel_model_effect could allow sample_var and freq_weight?
if self._discrete_instrument:
Z = inverse_onehot(Z)
if self._discrete_treatment:
T = inverse_onehot(T)
self._prel_model_effect.fit(Y, T, Z=Z, X=X,
W=W, sample_weight=sample_weight, groups=groups)
return self
def score(self, Y, T, X=None, W=None, Z=None, sample_weight=None, groups=None):
# T and Z only allow single continuous or binary, keep the shape of (n,) for continuous and (n,1) for binary
T = T.ravel() if not self._discrete_treatment else T
Z = Z.ravel() if not self._discrete_instrument else Z
if hasattr(self._model_y_xw, 'score'):
y_xw_score = self._model_y_xw.score(X=X, W=W, Target=Y, sample_weight=sample_weight)
else:
y_xw_score = None
if hasattr(self._model_t_xw, 'score'):
t_xw_score = self._model_t_xw.score(X=X, W=W, Target=T, sample_weight=sample_weight)
else:
t_xw_score = None
if hasattr(self._prel_model_effect, 'score'):
# we need to undo the one-hot encoding for calling effect,
# since it expects raw values
raw_T = inverse_onehot(T) if self._discrete_treatment else T
raw_Z = inverse_onehot(Z) if self._discrete_instrument else Z
effect_score = self._prel_model_effect.score(Y, raw_T,
Z=raw_Z, X=X, W=W, sample_weight=sample_weight)
else:
effect_score = None
if self._projection:
if hasattr(self._model_t_xwz, 'score'):
WZ = self._combine(W, Z, Y.shape[0])
t_xwz_score = self._model_t_xwz.score(X=X, W=WZ, Target=T, sample_weight=sample_weight)
else:
t_xwz_score = None
if hasattr(self._model_tz_xw, 'score'):
T_proj = self._model_t_xwz.predict(X, WZ).reshape(T.shape)
# if discrete, return shape (n,1); if continuous return shape (n,)
target = (T * T_proj).reshape(T.shape[0],)
tz_xw_score = self._model_tz_xw.score(X=X, W=W, Target=target, sample_weight=sample_weight)
else:
tz_xw_score = None
return y_xw_score, t_xw_score, t_xwz_score, tz_xw_score, effect_score
else:
if hasattr(self._model_z_xw, 'score'):
z_xw_score = self._model_z_xw.score(X=X, W=W, Target=Z, sample_weight=sample_weight)
else:
z_xw_score = None
if hasattr(self._model_tz_xw, 'score'):
if self._discrete_treatment:
if self._discrete_instrument:
# target will be discrete and will be inversed from FirstStageWrapper
target = T * Z
else:
target = inverse_onehot(T) * Z
else:
if self._discrete_instrument:
target = T * inverse_onehot(Z)
else:
target = T * Z
tz_xw_score = self._model_tz_xw.score(X=X, W=W, Target=target, sample_weight=sample_weight)
else:
tz_xw_score = None
return y_xw_score, t_xw_score, z_xw_score, tz_xw_score, effect_score
def predict(self, Y, T, X=None, W=None, Z=None, sample_weight=None, groups=None):
Y_pred = self._model_y_xw.predict(X, W)
T_pred = self._model_t_xw.predict(X, W)
TZ_pred = self._model_tz_xw.predict(X, W)
prel_theta = self._prel_model_effect.effect(X)
if X is None:
prel_theta = np.tile(prel_theta.reshape(1, -1), (Y.shape[0], 1))
if W is None:
Y_pred = np.tile(Y_pred.reshape(1, -1), (Y.shape[0], 1))
T_pred = np.tile(T_pred.reshape(1, -1), (Y.shape[0], 1))
TZ_pred = np.tile(TZ_pred.reshape(1, -1), (Y.shape[0], 1))
# for convenience, reshape Z,T to a vector since they are either binary or single dimensional continuous
T = T.reshape(T.shape[0],)
Z = Z.reshape(Z.shape[0],)
# reshape the predictions
Y_pred = Y_pred.reshape(Y.shape)
T_pred = T_pred.reshape(T.shape)
TZ_pred = TZ_pred.reshape(T.shape)
Y_res = Y - Y_pred
T_res = T - T_pred
if self._projection:
# concat W and Z
WZ = self._combine(W, Z, Y.shape[0])
T_proj = self._model_t_xwz.predict(X, WZ).reshape(T.shape)
Z_res = T_proj - T_pred
cov = TZ_pred - T_pred**2
else:
Z_pred = self._model_z_xw.predict(X, W)
if X is None and W is None:
Z_pred = np.tile(Z_pred.reshape(1, -1), (Z.shape[0], 1))
Z_pred = Z_pred.reshape(Z.shape)
Z_res = Z - Z_pred
cov = TZ_pred - T_pred * Z_pred
# check nuisances outcome shape
# Y_res could be a vector or 1-dimensional 2d-array
assert T_res.ndim == 1, "Nuisance outcome should be vector!"
assert Z_res.ndim == 1, "Nuisance outcome should be vector!"
assert cov.ndim == 1, "Nuisance outcome should be vector!"
return prel_theta, Y_res, T_res, Z_res, cov
class _BaseDRIVModelFinal:
def __init__(self, model_final, featurizer, fit_cate_intercept, cov_clip, opt_reweighted):
self._model_final = clone(model_final, safe=False)
self._original_featurizer = clone(featurizer, safe=False)
self._fit_cate_intercept = fit_cate_intercept
self._cov_clip = cov_clip
self._opt_reweighted = opt_reweighted
if self._fit_cate_intercept:
add_intercept_trans = FunctionTransformer(add_intercept,
validate=True)
if featurizer:
self._featurizer = Pipeline([('featurize', self._original_featurizer),
('add_intercept', add_intercept_trans)])
else:
self._featurizer = add_intercept_trans
else:
self._featurizer = self._original_featurizer
def _effect_estimate(self, nuisances):
# all could be reshaped to vector since Y, T, Z are all single dimensional.
prel_theta, res_y, res_t, res_z, cov = [nuisance.reshape(nuisances[0].shape[0]) for nuisance in nuisances]
# Estimate final model of theta(X) by minimizing the square loss:
# (prel_theta(X) + (Y_res - prel_theta(X) * T_res) * Z_res / cov[T,Z | X] - theta(X))^2
# We clip the covariance so that it is bounded away from zero, so as to reduce variance
# at the expense of some small bias. For points with very small covariance we revert
# to the model-based preliminary estimate and do not add the correction term.
cov_sign = np.sign(cov)
cov_sign[cov_sign == 0] = 1
clipped_cov = cov_sign * np.clip(np.abs(cov),
self._cov_clip, np.inf)
return prel_theta + (res_y - prel_theta * res_t) * res_z / clipped_cov, clipped_cov, res_z
def _transform_X(self, X, n=1, fitting=True):
if X is not None:
if self._featurizer is not None:
F = self._featurizer.fit_transform(X) if fitting else self._featurizer.transform(X)
else:
F = X
else:
if not self._fit_cate_intercept:
raise AttributeError("Cannot have X=None and also not allow for a CATE intercept!")
F = np.ones((n, 1))
return F
def fit(self, Y, T, X=None, W=None, Z=None, nuisances=None,
sample_weight=None, freq_weight=None, sample_var=None, groups=None):
self.d_y = Y.shape[1:]
self.d_t = T.shape[1:]
theta_dr, clipped_cov, res_z = self._effect_estimate(nuisances)
X = self._transform_X(X, n=theta_dr.shape[0])
if self._opt_reweighted and (sample_weight is not None):
sample_weight = sample_weight * clipped_cov.ravel()**2
elif self._opt_reweighted:
sample_weight = clipped_cov.ravel()**2
target_var = sample_var * (res_z**2 / clipped_cov**2) if sample_var is not None else None
self._model_final.fit(X, theta_dr, **filter_none_kwargs(sample_weight=sample_weight,
freq_weight=freq_weight, sample_var=target_var))
return self
def predict(self, X=None):
X = self._transform_X(X, fitting=False)
return self._model_final.predict(X).reshape((-1,) + self.d_y + self.d_t)
def score(self, Y, T, X=None, W=None, Z=None, nuisances=None, sample_weight=None):
theta_dr, clipped_cov, _ = self._effect_estimate(nuisances)
X = self._transform_X(X, fitting=False)
if self._opt_reweighted and (sample_weight is not None):
sample_weight = sample_weight * clipped_cov.ravel()**2
elif self._opt_reweighted:
sample_weight = clipped_cov.ravel()**2
return np.average((theta_dr.ravel() - self._model_final.predict(X).ravel())**2,
weights=sample_weight, axis=0)
class _BaseDRIV(_OrthoLearner):
# A helper class that access all the internal fitted objects of a DRIV Cate Estimator.
# Used by both DRIV and IntentToTreatDRIV.
def __init__(self, *,
model_final,
featurizer=None,
fit_cate_intercept=False,
cov_clip=1e-3,
opt_reweighted=False,
discrete_instrument=False,
discrete_treatment=False,
categories='auto',
cv=2,
mc_iters=None,
mc_agg='mean',
random_state=None):
self.model_final = clone(model_final, safe=False)
self.featurizer = clone(featurizer, safe=False)
self.fit_cate_intercept = fit_cate_intercept
self.cov_clip = cov_clip
self.opt_reweighted = opt_reweighted
super().__init__(discrete_instrument=discrete_instrument,
discrete_treatment=discrete_treatment,
categories=categories,
cv=cv,
mc_iters=mc_iters,
mc_agg=mc_agg,
random_state=random_state)
# Maggie: I think that would be the case?
def _get_inference_options(self):
options = super()._get_inference_options()
options.update(auto=GenericSingleTreatmentModelFinalInference)
return options
def _gen_featurizer(self):
return clone(self.featurizer, safe=False)
def _gen_model_final(self):
return clone(self.model_final, safe=False)
def _gen_ortho_learner_model_final(self):
return _BaseDRIVModelFinal(self._gen_model_final(), self._gen_featurizer(), self.fit_cate_intercept,
self.cov_clip, self.opt_reweighted)
def _check_inputs(self, Y, T, Z, X, W):
Y1, T1, Z1, = check_input_arrays(Y, T, Z)
if len(Y1.shape) > 1 and Y1.shape[1] > 1:
raise AssertionError("DRIV only supports single dimensional outcome")
if len(T1.shape) > 1 and T1.shape[1] > 1:
if self.discrete_treatment:
raise AttributeError("DRIV only supports binary treatments")
else:
raise AttributeError("DRIV only supports single-dimensional continuous treatments")
if len(Z1.shape) > 1 and Z1.shape[1] > 1:
if self.discrete_instrument:
raise AttributeError("DRIV only supports binary instruments")
else:
raise AttributeError("DRIV only supports single-dimensional continuous instruments")
return Y, T, Z, X, W
def fit(self, Y, T, *, Z, X=None, W=None, sample_weight=None, freq_weight=None, sample_var=None, groups=None,
cache_values=False, inference="auto"):
"""
Estimate the counterfactual model from data, i.e. estimates function :math:`\\theta(\\cdot)`.
Parameters
----------
Y: (n,) vector of length n
Outcomes for each sample
T: (n,) vector of length n
Treatments for each sample
Z: (n, d_z) matrix
Instruments for each sample
X: optional(n, d_x) matrix or None (Default=None)
Features for each sample
W: optional(n, d_w) matrix or None (Default=None)
Controls for each sample
sample_weight : (n,) array like, default None
Individual weights for each sample. If None, it assumes equal weight.
freq_weight: (n,) array like of integers, default None
Weight for the observation. Observation i is treated as the mean
outcome of freq_weight[i] independent observations.
When ``sample_var`` is not None, this should be provided.
sample_var : (n,) nd array like, default None
Variance of the outcome(s) of the original freq_weight[i] observations that were used to
compute the mean outcome represented by observation i.
groups: (n,) vector, optional
All rows corresponding to the same group will be kept together during splitting.
If groups is not None, the `cv` argument passed to this class's initializer
must support a 'groups' argument to its split method.
cache_values: bool, default False
Whether to cache inputs and first stage results, which will allow refitting a different final model
inference: string, :class:`.Inference` instance, or None
Method for performing inference. This estimator supports 'bootstrap'
(or an instance of :class:`.BootstrapInference`) and 'auto'
(or an instance of :class:`.GenericSingleTreatmentModelFinalInference`)
Returns
-------
self
"""
Y, T, Z, X, W = self._check_inputs(Y, T, Z, X, W)
# Replacing fit from _OrthoLearner, to reorder arguments and improve the docstring
return super().fit(Y, T, X=X, W=W, Z=Z,
sample_weight=sample_weight, freq_weight=freq_weight, sample_var=sample_var, groups=groups,
cache_values=cache_values, inference=inference)
def refit_final(self, *, inference='auto'):
return super().refit_final(inference=inference)
refit_final.__doc__ = _OrthoLearner.refit_final.__doc__
def score(self, Y, T, Z, X=None, W=None, sample_weight=None):
"""
Score the fitted CATE model on a new data set. Generates nuisance parameters
for the new data set based on the fitted residual nuisance models created at fit time.
It uses the mean prediction of the models fitted by the different crossfit folds.
Then calculates the MSE of the final residual Y on residual T regression.
If model_final does not have a score method, then it raises an :exc:`.AttributeError`
Parameters
----------
Y: (n, d_y) matrix or vector of length n
Outcomes for each sample
T: (n, d_t) matrix or vector of length n
Treatments for each sample
Z: (n, d_z) matrix
Instruments for each sample
X: optional(n, d_x) matrix or None (Default=None)
Features for each sample
W: optional(n, d_w) matrix or None (Default=None)
Controls for each sample
sample_weight: optional(n,) vector or None (Default=None)
Weights for each samples
Returns
-------
score: float
The MSE of the final CATE model on the new data.
"""
# Replacing score from _OrthoLearner, to enforce Z to be required and improve the docstring
return super().score(Y, T, X=X, W=W, Z=Z, sample_weight=sample_weight)
@property
def featurizer_(self):
"""
Get the fitted featurizer.
Returns
-------
featurizer: object of type(`featurizer`)
An instance of the fitted featurizer that was used to preprocess X in the final CATE model training.
Available only when featurizer is not None and X is not None.
"""
return self.ortho_learner_model_final_._featurizer
@property
def original_featurizer(self):
# NOTE: important to use the ortho_learner_model_final_ attribute instead of the
# attribute so that the trained featurizer will be passed through
return self.ortho_learner_model_final_._original_featurizer
def cate_feature_names(self, feature_names=None):
"""
Get the output feature names.
Parameters
----------
feature_names: list of strings of length X.shape[1] or None
The names of the input features. If None and X is a dataframe, it defaults to the column names
from the dataframe.
Returns
-------
out_feature_names: list of strings or None
The names of the output features :math:`\\phi(X)`, i.e. the features with respect to which the
final CATE model for each treatment is linear. It is the names of the features that are associated
with each entry of the :meth:`coef_` parameter. Available only when the featurizer is not None and has
a method: `get_feature_names(feature_names)`. Otherwise None is returned.
"""
if self._d_x is None:
# Handles the corner case when X=None but featurizer might be not None
return None
if feature_names is None:
feature_names = self._input_names["feature_names"]
if self.original_featurizer is None:
return feature_names
return get_feature_names_or_default(self.original_featurizer, feature_names)
@property
def model_final_(self):
# NOTE This is used by the inference methods and is more for internal use to the library
return self.ortho_learner_model_final_._model_final
@property
def model_cate(self):
"""
Get the fitted final CATE model.
Returns
-------
model_cate: object of type(model_final)
An instance of the model_final object that was fitted after calling fit which corresponds
to the constant marginal CATE model.
"""
return self.ortho_learner_model_final_._model_final
def shap_values(self, X, *, feature_names=None, treatment_names=None, output_names=None, background_samples=100):
return _shap_explain_model_cate(self.const_marginal_effect, self.model_cate, X, self._d_t, self._d_y,
featurizer=self.featurizer_,
feature_names=feature_names,
treatment_names=treatment_names,
output_names=output_names,
input_names=self._input_names,
background_samples=background_samples)
shap_values.__doc__ = LinearCateEstimator.shap_values.__doc__
@property
def residuals_(self):
"""
A tuple (prel_theta, Y_res, T_res, Z_res, cov, X, W, Z), of the residuals from the first stage estimation
along with the associated X, W and Z. Samples are not guaranteed to be in the same
order as the input order.
"""
if not hasattr(self, '_cached_values'):
raise AttributeError("Estimator is not fitted yet!")
if self._cached_values is None:
raise AttributeError("`fit` was called with `cache_values=False`. "
"Set to `True` to enable residual storage.")
prel_theta, Y_res, T_res, Z_res, cov = self._cached_values.nuisances
return (prel_theta, Y_res, T_res, Z_res, cov, self._cached_values.X, self._cached_values.W,
self._cached_values.Z)
class _DRIV(_BaseDRIV):
"""
Private Base class for the DRIV algorithm.
"""
def __init__(self, *,
model_y_xw="auto",
model_t_xw="auto",
model_z_xw="auto",
model_t_xwz="auto",
model_tz_xw="auto",
prel_model_effect,
model_final,
projection=False,
featurizer=None,
fit_cate_intercept=False,
cov_clip=1e-3,
opt_reweighted=False,
discrete_instrument=False,
discrete_treatment=False,
categories='auto',
cv=2,
mc_iters=None,
mc_agg='mean',
random_state=None):
self.model_y_xw = clone(model_y_xw, safe=False)
self.model_t_xw = clone(model_t_xw, safe=False)
self.model_t_xwz = clone(model_t_xwz, safe=False)
self.model_z_xw = clone(model_z_xw, safe=False)
self.model_tz_xw = clone(model_tz_xw, safe=False)
self.prel_model_effect = clone(prel_model_effect, safe=False)
self.projection = projection
super().__init__(model_final=model_final,
featurizer=featurizer,
fit_cate_intercept=fit_cate_intercept,
cov_clip=cov_clip,
opt_reweighted=opt_reweighted,
discrete_instrument=discrete_instrument,
discrete_treatment=discrete_treatment,
categories=categories,
cv=cv,
mc_iters=mc_iters,
mc_agg=mc_agg,
random_state=random_state)
def _gen_prel_model_effect(self):
return clone(self.prel_model_effect, safe=False)
def _gen_ortho_learner_model_nuisance(self):
if self.model_y_xw == 'auto':
model_y_xw = WeightedLassoCVWrapper(random_state=self.random_state)
else:
model_y_xw = clone(self.model_y_xw, safe=False)
if self.model_t_xw == 'auto':
if self.discrete_treatment:
model_t_xw = LogisticRegressionCV(cv=WeightedStratifiedKFold(random_state=self.random_state),
random_state=self.random_state)
else:
model_t_xw = WeightedLassoCVWrapper(random_state=self.random_state)
else:
model_t_xw = clone(self.model_t_xw, safe=False)
if self.projection:
# this is a regression model since proj_t is probability
if self.model_tz_xw == "auto":
model_tz_xw = WeightedLassoCVWrapper(random_state=self.random_state)
else:
model_tz_xw = clone(self.model_tz_xw, safe=False)
if self.model_t_xwz == 'auto':
if self.discrete_treatment:
model_t_xwz = LogisticRegressionCV(cv=WeightedStratifiedKFold(random_state=self.random_state),
random_state=self.random_state)
else:
model_t_xwz = WeightedLassoCVWrapper(random_state=self.random_state)
else:
model_t_xwz = clone(self.model_t_xwz, safe=False)
return _BaseDRIVModelNuisance(self._gen_prel_model_effect(),
_FirstStageWrapper(model_y_xw, True, self._gen_featurizer(), False, False),
_FirstStageWrapper(model_t_xw, False, self._gen_featurizer(),
False, self.discrete_treatment),
# outcome is continuous since proj_t is probability
_FirstStageWrapper(model_tz_xw, False, self._gen_featurizer(), False,
False),
_FirstStageWrapper(model_t_xwz, False, self._gen_featurizer(),
False, self.discrete_treatment),
self.projection, self.discrete_treatment, self.discrete_instrument)
else:
if self.model_tz_xw == "auto":
if self.discrete_treatment and self.discrete_instrument:
model_tz_xw = LogisticRegressionCV(cv=WeightedStratifiedKFold(random_state=self.random_state),
random_state=self.random_state)
else:
model_tz_xw = WeightedLassoCVWrapper(random_state=self.random_state)
else:
model_tz_xw = clone(self.model_tz_xw, safe=False)
if self.model_z_xw == 'auto':
if self.discrete_instrument:
model_z_xw = LogisticRegressionCV(cv=WeightedStratifiedKFold(random_state=self.random_state),
random_state=self.random_state)
else:
model_z_xw = WeightedLassoCVWrapper(random_state=self.random_state)
else:
model_z_xw = clone(self.model_z_xw, safe=False)
return _BaseDRIVModelNuisance(self._gen_prel_model_effect(),
_FirstStageWrapper(model_y_xw, True, self._gen_featurizer(), False, False),
_FirstStageWrapper(model_t_xw, False, self._gen_featurizer(),
False, self.discrete_treatment),
_FirstStageWrapper(model_tz_xw, False, self._gen_featurizer(), False,
self.discrete_treatment and self.discrete_instrument),
_FirstStageWrapper(model_z_xw, False, self._gen_featurizer(),
False, self.discrete_instrument),
self.projection, self.discrete_treatment, self.discrete_instrument)
class DRIV(_DRIV):
"""
The DRIV algorithm for estimating CATE with IVs. It is the parent of the
public classes {LinearDRIV, SparseLinearDRIV,ForestDRIV}
Parameters
----------
model_y_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Y | X, W]`. Must support `fit` and `predict` methods.
If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.
model_t_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous treatment.
model_z_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Z | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete instrument,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous instrument.
model_t_xwz : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W, Z]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous treatment.
model_tz_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T*Z | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete instrument and discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous instrument or continuous treatment.
flexible_model_effect : estimator or 'auto' (default is 'auto')
a flexible model for a preliminary version of the CATE, must accept sample_weight at fit time.
If 'auto', :class:`.StatsModelsLinearRegression` will be applied.
model_final : estimator, optional
a final model for the CATE and projections. If None, then flexible_model_effect is also used as a final model
prel_cate_approach : one of {'driv', 'dmliv'}, optional (default='driv')
model that estimates a preliminary version of the CATE.
If 'driv', :class:`._DRIV` will be used.
If 'dmliv', :class:`.NonParamDMLIV` will be used
prel_cv : int, cross-validation generator or an iterable, optional, default 1
Determines the cross-validation splitting strategy for the preliminary effect model.
prel_opt_reweighted : bool, optional, default True
Whether to reweight the samples to minimize variance for the preliminary effect model.
projection: bool, optional, default False
If True, we fit a slight variant of DRIV where we use E[T|X, W, Z] as the instrument as opposed to Z,
model_z_xw will be disabled; If False, model_t_xwz will be disabled.
featurizer : :term:`transformer`, optional, default None
Must support fit_transform and transform. Used to create composite features in the final CATE regression.
It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).
If featurizer=None, then CATE is trained on X.
fit_cate_intercept : bool, optional, default False
Whether the linear CATE model should have a constant term.
cov_clip : float, optional, default 0.1
clipping of the covariate for regions with low "overlap", to reduce variance
opt_reweighted : bool, optional, default False
Whether to reweight the samples to minimize variance. If True then
model_final.fit must accept sample_weight as a kw argument. If True then
assumes the model_final is flexible enough to fit the true CATE model. Otherwise,
it method will return a biased projection to the model_final space, biased
to give more weight on parts of the feature space where the instrument is strong.
discrete_instrument: bool, optional, default False
Whether the instrument values should be treated as categorical, rather than continuous, quantities
discrete_treatment: bool, optional, default False
Whether the treatment values should be treated as categorical, rather than continuous, quantities
categories: 'auto' or list, default 'auto'
The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).
The first category will be treated as the control treatment.
cv: int, cross-validation generator or an iterable, optional, default 2
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- :term:`CV splitter`
- An iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if the treatment is discrete
:class:`~sklearn.model_selection.StratifiedKFold` is used, else,
:class:`~sklearn.model_selection.KFold` is used
(with a random shuffle in either case).
Unless an iterable is used, we call `split(concat[W, X], T)` to generate the splits. If all
W, X are None, then we call `split(ones((T.shape[0], 1)), T)`.
mc_iters: int, optional (default=None)
The number of times to rerun the first stage models to reduce the variance of the nuisances.
mc_agg: {'mean', 'median'}, optional (default='mean')
How to aggregate the nuisance value for each sample across the `mc_iters` monte carlo iterations of
cross-fitting.
random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;
If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used
by :mod:`np.random<numpy.random>`.
Examples
--------
A simple example with the default models:
.. testcode::
:hide:
import numpy as np
import scipy.special
np.set_printoptions(suppress=True)
.. testcode::
from econml.iv.dr import DRIV
# Define the data generation functions
def dgp(n, p, true_fn):
X = np.random.normal(0, 1, size=(n, p))
Z = np.random.binomial(1, 0.5, size=(n,))
nu = np.random.uniform(0, 10, size=(n,))
coef_Z = 0.8
C = np.random.binomial(
1, coef_Z * scipy.special.expit(0.4 * X[:, 0] + nu)
) # Compliers when recomended
C0 = np.random.binomial(
1, 0.06 * np.ones(X.shape[0])
) # Non-compliers when not recommended
T = C * Z + C0 * (1 - Z)
y = true_fn(X) * T + 2 * nu + 5 * (X[:, 3] > 0) + 0.1 * np.random.uniform(0, 1, size=(n,))
return y, T, Z, X
def true_heterogeneity_function(X):
return 5 * X[:, 0]
np.random.seed(123)
y, T, Z, X = dgp(1000, 5, true_heterogeneity_function)
est = DRIV(discrete_treatment=True, discrete_instrument=True)
est.fit(Y=y, T=T, Z=Z, X=X)
>>> est.effect(X[:3])
array([-4.45223..., 6.03803..., -2.97548...])
"""
def __init__(self, *,
model_y_xw="auto",
model_t_xw="auto",
model_z_xw="auto",
model_t_xwz="auto",
model_tz_xw="auto",
flexible_model_effect="auto",
model_final=None,
prel_cate_approach="driv",
prel_cv=1,
prel_opt_reweighted=True,
projection=False,
featurizer=None,
fit_cate_intercept=False,
cov_clip=1e-3,
opt_reweighted=False,
discrete_instrument=False,
discrete_treatment=False,
categories='auto',
cv=2,
mc_iters=None,
mc_agg='mean',
random_state=None):
if flexible_model_effect == "auto":
self.flexible_model_effect = StatsModelsLinearRegression(fit_intercept=False)
else:
self.flexible_model_effect = clone(flexible_model_effect, safe=False)
self.prel_cate_approach = prel_cate_approach
self.prel_cv = prel_cv
self.prel_opt_reweighted = prel_opt_reweighted
super().__init__(model_y_xw=model_y_xw,
model_t_xw=model_t_xw,
model_z_xw=model_z_xw,
model_t_xwz=model_t_xwz,
model_tz_xw=model_tz_xw,
prel_model_effect=self.prel_cate_approach,
model_final=model_final,
projection=projection,
featurizer=featurizer,
fit_cate_intercept=fit_cate_intercept,
cov_clip=cov_clip,
opt_reweighted=opt_reweighted,
discrete_instrument=discrete_instrument,
discrete_treatment=discrete_treatment,
categories=categories,
cv=cv,
mc_iters=mc_iters,
mc_agg=mc_agg,
random_state=random_state)
def _gen_model_final(self):
if self.model_final is None:
return clone(self.flexible_model_effect, safe=False)
return clone(self.model_final, safe=False)
def _gen_prel_model_effect(self):
if self.prel_cate_approach == "driv":
return _DRIV(model_y_xw=clone(self.model_y_xw, safe=False),
model_t_xw=clone(self.model_t_xw, safe=False),
model_z_xw=clone(self.model_z_xw, safe=False),
model_t_xwz=clone(self.model_t_xwz, safe=False),
model_tz_xw=clone(self.model_tz_xw, safe=False),
prel_model_effect=_DummyCATE(),
model_final=clone(self.flexible_model_effect, safe=False),
projection=self.projection,
featurizer=self._gen_featurizer(),
fit_cate_intercept=self.fit_cate_intercept,
cov_clip=self.cov_clip,
opt_reweighted=self.prel_opt_reweighted,
discrete_instrument=self.discrete_instrument,
discrete_treatment=self.discrete_treatment,
categories=self.categories,
cv=self.prel_cv,
mc_iters=self.mc_iters,
mc_agg=self.mc_agg,
random_state=self.random_state)
elif self.prel_cate_approach == "dmliv":
return NonParamDMLIV(model_y_xw=clone(self.model_y_xw, safe=False),
model_t_xw=clone(self.model_t_xw, safe=False),
model_t_xwz=clone(self.model_t_xwz, safe=False),
model_final=clone(self.flexible_model_effect, safe=False),
discrete_instrument=self.discrete_instrument,
discrete_treatment=self.discrete_treatment,
featurizer=self._gen_featurizer(),
categories=self.categories,
cv=self.prel_cv,
mc_iters=self.mc_iters,
mc_agg=self.mc_agg,
random_state=self.random_state)
else:
raise ValueError(
"We only support 'dmliv' or 'driv' preliminary model effect, "
f"but received '{self.prel_cate_approach}'!")
def fit(self, Y, T, *, Z, X=None, W=None, sample_weight=None, freq_weight=None, sample_var=None, groups=None,
cache_values=False, inference="auto"):
"""
Estimate the counterfactual model from data, i.e. estimates function :math:`\\theta(\\cdot)`.
Parameters
----------
Y: (n,) vector of length n
Outcomes for each sample
T: (n,) vector of length n
Treatments for each sample
Z: (n, d_z) matrix
Instruments for each sample
X: optional(n, d_x) matrix or None (Default=None)
Features for each sample
W: optional(n, d_w) matrix or None (Default=None)
Controls for each sample
sample_weight : (n,) array like, default None
Individual weights for each sample. If None, it assumes equal weight.
freq_weight: (n,) array like of integers, default None
Weight for the observation. Observation i is treated as the mean
outcome of freq_weight[i] independent observations.
When ``sample_var`` is not None, this should be provided.
sample_var : (n,) nd array like, default None
Variance of the outcome(s) of the original freq_weight[i] observations that were used to
compute the mean outcome represented by observation i.
groups: (n,) vector, optional
All rows corresponding to the same group will be kept together during splitting.
If groups is not None, the `cv` argument passed to this class's initializer
must support a 'groups' argument to its split method.
cache_values: bool, default False
Whether to cache inputs and first stage results, which will allow refitting a different final model
inference: string, :class:`.Inference` instance, or None
Method for performing inference. This estimator supports 'bootstrap'
(or an instance of :class:`.BootstrapInference`) and 'auto'
(or an instance of :class:`.GenericSingleTreatmentModelFinalInference`)
Returns
-------
self
"""
if self.projection:
assert self.model_z_xw == "auto", ("In the case of projection=True, model_z_xw will not be fitted, "
"please keep it as default!")
if self.prel_cate_approach == "driv" and not self.projection:
assert self.model_t_xwz == "auto", ("In the case of projection=False and prel_cate_approach='driv', "
"model_t_xwz will not be fitted, "
"please keep it as default!")
return super().fit(Y, T, X=X, W=W, Z=Z,
sample_weight=sample_weight, freq_weight=freq_weight, sample_var=sample_var, groups=groups,
cache_values=cache_values, inference=inference)
@property
def models_y_xw(self):
"""
Get the fitted models for :math:`\\E[Y | X]`.
Returns
-------
models_y_xw: nested list of objects of type(`model_y_xw`)
A nested list of instances of the `model_y_xw` object. Number of sublist equals to number of monte carlo
iterations, each element in the sublist corresponds to a crossfitting
fold and is the model instance that was fitted for that training fold.
"""
return [[mdl._model_y_xw._model for mdl in mdls] for mdls in super().models_nuisance_]
@property
def models_t_xw(self):
"""
Get the fitted models for :math:`\\E[T | X]`.
Returns
-------
models_t_xw: nested list of objects of type(`model_t_xw`)
A nested list of instances of the `model_t_xw` object. Number of sublist equals to number of monte carlo
iterations, each element in the sublist corresponds to a crossfitting
fold and is the model instance that was fitted for that training fold.
"""
return [[mdl._model_t_xw._model for mdl in mdls] for mdls in super().models_nuisance_]
@property
def models_z_xw(self):
"""
Get the fitted models for :math:`\\E[Z | X]`.
Returns
-------
models_z_xw: nested list of objects of type(`model_z_xw`)
A nested list of instances of the `model_z_xw` object. Number of sublist equals to number of monte carlo
iterations, each element in the sublist corresponds to a crossfitting
fold and is the model instance that was fitted for that training fold.
"""
if self.projection:
raise AttributeError("Projection model is fitted for instrument! Use models_t_xwz.")
return [[mdl._model_z_xw._model for mdl in mdls] for mdls in super().models_nuisance_]
@property
def models_t_xwz(self):
"""
Get the fitted models for :math:`\\E[Z | X]`.
Returns
-------
models_z_xw: nested list of objects of type(`model_z_xw`)
A nested list of instances of the `model_z_xw` object. Number of sublist equals to number of monte carlo
iterations, each element in the sublist corresponds to a crossfitting
fold and is the model instance that was fitted for that training fold.
"""
if not self.projection:
raise AttributeError("Direct model is fitted for instrument! Use models_z_xw.")
return [[mdl._model_t_xwz._model for mdl in mdls] for mdls in super().models_nuisance_]
@property
def models_tz_xw(self):
"""
Get the fitted models for :math:`\\E[T*Z | X]`.
Returns
-------
models_tz_xw: nested list of objects of type(`model_tz_xw`)
A nested list of instances of the `model_tz_xw` object. Number of sublist equals to number of monte carlo
iterations, each element in the sublist corresponds to a crossfitting
fold and is the model instance that was fitted for that training fold.
"""
return [[mdl._model_tz_xw._model for mdl in mdls] for mdls in super().models_nuisance_]
@property
def models_prel_model_effect(self):
"""
Get the fitted preliminary CATE estimator.
Returns
-------
prel_model_effect: nested list of objects of type(`prel_model_effect`)
A nested list of instances of the `prel_model_effect` object. Number of sublist equals to number
of monte carlo iterations, each element in the sublist corresponds to a crossfitting
fold and is the model instance that was fitted for that training fold.
"""
return [[mdl._prel_model_effect for mdl in mdls] for mdls in super().models_nuisance_]
@property
def nuisance_scores_y_xw(self):
"""
Get the scores for y_xw model on the out-of-sample training data
"""
return self.nuisance_scores_[0]
@property
def nuisance_scores_t_xw(self):
"""
Get the scores for t_xw model on the out-of-sample training data
"""
return self.nuisance_scores_[1]
@property
def nuisance_scores_z_xw(self):
"""
Get the scores for z_xw model on the out-of-sample training data
"""
if self.projection:
raise AttributeError("Projection model is fitted for instrument! Use nuisance_scores_t_xwz.")
return self.nuisance_scores_[2]
@property
def nuisance_scores_t_xwz(self):
"""
Get the scores for z_xw model on the out-of-sample training data
"""
if not self.projection:
raise AttributeError("Direct model is fitted for instrument! Use nuisance_scores_z_xw.")
return self.nuisance_scores_[2]
@property
def nuisance_scores_tz_xw(self):
"""
Get the scores for tz_xw model on the out-of-sample training data
"""
return self.nuisance_scores_[3]
@property
def nuisance_scores_prel_model_effect(self):
"""
Get the scores for prel_model_effect model on the out-of-sample training data
"""
return self.nuisance_scores_[4]
class LinearDRIV(StatsModelsCateEstimatorMixin, DRIV):
"""
Special case of the :class:`.DRIV` where the final stage
is a Linear Regression. In this case, inference can be performed via the StatsModels Inference approach
and its asymptotic normal characterization of the estimated parameters. This is computationally
faster than bootstrap inference. Leave the default ``inference='auto'`` unchanged, or explicitly set
``inference='statsmodels'`` at fit time to enable inference via asymptotic normality.
Parameters
----------
model_y_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Y | X, W]`. Must support `fit` and `predict` methods.
If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.
model_t_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous treatment.
model_z_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Z | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete instrument,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous instrument.
model_t_xwz : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W, Z]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous treatment.
model_tz_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T*Z | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete instrument and discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous instrument or continuous treatment.
flexible_model_effect : estimator or 'auto' (default is 'auto')
a flexible model for a preliminary version of the CATE, must accept sample_weight at fit time.
If 'auto', :class:`.StatsModelsLinearRegression` will be applied.
prel_cate_approach : one of {'driv', 'dmliv'}, optional (default='driv')
model that estimates a preliminary version of the CATE.
If 'driv', :class:`._DRIV` will be used.
If 'dmliv', :class:`.NonParamDMLIV` will be used
prel_cv : int, cross-validation generator or an iterable, optional, default 1
Determines the cross-validation splitting strategy for the preliminary effect model.
prel_opt_reweighted : bool, optional, default True
Whether to reweight the samples to minimize variance for the preliminary effect model.
projection: bool, optional, default False
If True, we fit a slight variant of DRIV where we use E[T|X, W, Z] as the instrument as opposed to Z,
model_z_xw will be disabled; If False, model_t_xwz will be disabled.
featurizer : :term:`transformer`, optional, default None
Must support fit_transform and transform. Used to create composite features in the final CATE regression.
It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).
If featurizer=None, then CATE is trained on X.
fit_cate_intercept : bool, optional, default True
Whether the linear CATE model should have a constant term.
cov_clip : float, optional, default 0.1
clipping of the covariate for regions with low "overlap", to reduce variance
opt_reweighted : bool, optional, default False
Whether to reweight the samples to minimize variance. If True then
model_final.fit must accept sample_weight as a kw argument. If True then
assumes the model_final is flexible enough to fit the true CATE model. Otherwise,
it method will return a biased projection to the model_final space, biased
to give more weight on parts of the feature space where the instrument is strong.
discrete_instrument: bool, optional, default False
Whether the instrument values should be treated as categorical, rather than continuous, quantities
discrete_treatment: bool, optional, default False
Whether the treatment values should be treated as categorical, rather than continuous, quantities
categories: 'auto' or list, default 'auto'
The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).
The first category will be treated as the control treatment.
cv: int, cross-validation generator or an iterable, optional, default 2
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- :term:`CV splitter`
- An iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if the treatment is discrete
:class:`~sklearn.model_selection.StratifiedKFold` is used, else,
:class:`~sklearn.model_selection.KFold` is used
(with a random shuffle in either case).
Unless an iterable is used, we call `split(concat[W, X], T)` to generate the splits. If all
W, X are None, then we call `split(ones((T.shape[0], 1)), T)`.
mc_iters: int, optional (default=None)
The number of times to rerun the first stage models to reduce the variance of the nuisances.
mc_agg: {'mean', 'median'}, optional (default='mean')
How to aggregate the nuisance value for each sample across the `mc_iters` monte carlo iterations of
cross-fitting.
random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;
If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used
by :mod:`np.random<numpy.random>`.
Examples
--------
A simple example with the default models:
.. testcode::
:hide:
import numpy as np
import scipy.special
np.set_printoptions(suppress=True)
.. testcode::
from econml.iv.dr import LinearDRIV
# Define the data generation functions
def dgp(n, p, true_fn):
X = np.random.normal(0, 1, size=(n, p))
Z = np.random.binomial(1, 0.5, size=(n,))
nu = np.random.uniform(0, 10, size=(n,))
coef_Z = 0.8
C = np.random.binomial(
1, coef_Z * scipy.special.expit(0.4 * X[:, 0] + nu)
) # Compliers when recomended
C0 = np.random.binomial(
1, 0.06 * np.ones(X.shape[0])
) # Non-compliers when not recommended
T = C * Z + C0 * (1 - Z)
y = true_fn(X) * T + 2 * nu + 5 * (X[:, 3] > 0) + 0.1 * np.random.uniform(0, 1, size=(n,))
return y, T, Z, X
def true_heterogeneity_function(X):
return 5 * X[:, 0]
np.random.seed(123)
y, T, Z, X = dgp(1000, 5, true_heterogeneity_function)
est = LinearDRIV(discrete_treatment=True, discrete_instrument=True)
est.fit(Y=y, T=T, Z=Z, X=X)
>>> est.effect(X[:3])
array([-4.82328..., 5.66220..., -3.37199...])
>>> est.effect_interval(X[:3])
(array([-7.73320..., 1.47710..., -6.00997...]),
array([-1.91335..., 9.84730..., -0.73402...]))
>>> est.coef_
array([ 4.92394..., 0.77110..., 0.26769..., -0.04996..., 0.07749...])
>>> est.coef__interval()
(array([ 3.64471..., -0.48678..., -0.99551... , -1.16740..., -1.24289...]),
array([6.20316..., 2.02898..., 1.53090..., 1.06748..., 1.39788...]))
>>> est.intercept_
-0.35292...
>>> est.intercept__interval()
(-1.54654..., 0.84069...)
"""
def __init__(self, *,
model_y_xw="auto",
model_t_xw="auto",
model_z_xw="auto",
model_t_xwz="auto",
model_tz_xw="auto",
flexible_model_effect="auto",
prel_cate_approach="driv",
prel_cv=1,
prel_opt_reweighted=True,
projection=False,
featurizer=None,
fit_cate_intercept=True,
cov_clip=1e-3,
opt_reweighted=False,
discrete_instrument=False,
discrete_treatment=False,
categories='auto',
cv=2,
mc_iters=None,
mc_agg='mean',
random_state=None):
super().__init__(model_y_xw=model_y_xw,
model_t_xw=model_t_xw,
model_z_xw=model_z_xw,
model_t_xwz=model_t_xwz,
model_tz_xw=model_tz_xw,
flexible_model_effect=flexible_model_effect,
model_final=None,
prel_cate_approach=prel_cate_approach,
prel_cv=prel_cv,
prel_opt_reweighted=prel_opt_reweighted,
projection=projection,
featurizer=featurizer,
fit_cate_intercept=fit_cate_intercept,
cov_clip=cov_clip,
opt_reweighted=opt_reweighted,
discrete_instrument=discrete_instrument,
discrete_treatment=discrete_treatment,
categories=categories,
cv=cv,
mc_iters=mc_iters,
mc_agg=mc_agg,
random_state=random_state)
def _gen_model_final(self):
return StatsModelsLinearRegression(fit_intercept=False)
def fit(self, Y, T, *, Z, X=None, W=None, sample_weight=None, freq_weight=None, sample_var=None, groups=None,
cache_values=False, inference='auto'):
"""
Estimate the counterfactual model from data, i.e. estimates function :math:`\\theta(\\cdot)`.
Parameters
----------
Y: (n,) vector of length n
Outcomes for each sample
T: (n,) vector of length n
Treatments for each sample
Z: (n, d_z) matrix
Instruments for each sample
X: optional(n, d_x) matrix or None (Default=None)
Features for each sample
W: optional(n, d_w) matrix or None (Default=None)
Controls for each sample
sample_weight : (n,) array like, default None
Individual weights for each sample. If None, it assumes equal weight.
freq_weight: (n,) array like of integers, default None
Weight for the observation. Observation i is treated as the mean
outcome of freq_weight[i] independent observations.
When ``sample_var`` is not None, this should be provided.
sample_var : (n,) nd array like, default None
Variance of the outcome(s) of the original freq_weight[i] observations that were used to
compute the mean outcome represented by observation i.
groups: (n,) vector, optional
All rows corresponding to the same group will be kept together during splitting.
If groups is not None, the `cv` argument passed to this class's initializer
must support a 'groups' argument to its split method.
cache_values: bool, default False
Whether to cache inputs and first stage results, which will allow refitting a different final model
inference: string, :class:`.Inference` instance, or None
Method for performing inference. This estimator supports ``'bootstrap'``
(or an instance of :class:`.BootstrapInference`) and ``'statsmodels'``
(or an instance of :class:`.StatsModelsInferenceDiscrete`).
Returns
-------
self
"""
# Replacing fit from _OrthoLearner, to reorder arguments and improve the docstring
return super().fit(Y, T, X=X, W=W, Z=Z,
sample_weight=sample_weight, freq_weight=freq_weight, sample_var=sample_var, groups=groups,
cache_values=cache_values, inference=inference)
@property
def fit_cate_intercept_(self):
return self.ortho_learner_model_final_._fit_cate_intercept
@property
def bias_part_of_coef(self):
return self.ortho_learner_model_final_._fit_cate_intercept
@property
def model_final(self):
return self._gen_model_final()
@model_final.setter
def model_final(self, model):
if model is not None:
raise ValueError("Parameter `model_final` cannot be altered for this estimator!")
class SparseLinearDRIV(DebiasedLassoCateEstimatorMixin, DRIV):
"""
Special case of the :class:`.DRIV` where the final stage
is a Debiased Lasso Regression. In this case, inference can be performed via the debiased lasso approach
and its asymptotic normal characterization of the estimated parameters. This is computationally
faster than bootstrap inference. Leave the default ``inference='auto'`` unchanged, or explicitly set
``inference='debiasedlasso'`` at fit time to enable inference via asymptotic normality.
Parameters
----------
model_y_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Y | X, W]`. Must support `fit` and `predict` methods.
If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.
model_t_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous treatment.
model_z_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Z | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete instrument,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous instrument.
model_t_xwz : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W, Z]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous treatment.
model_tz_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T*Z | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete instrument and discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous instrument or continuous treatment.
flexible_model_effect : estimator or 'auto' (default is 'auto')
a flexible model for a preliminary version of the CATE, must accept sample_weight at fit time.
If 'auto', :class:`.StatsModelsLinearRegression` will be applied.
prel_cate_approach : one of {'driv', 'dmliv'}, optional (default='driv')
model that estimates a preliminary version of the CATE.
If 'driv', :class:`._DRIV` will be used.
If 'dmliv', :class:`.NonParamDMLIV` will be used
prel_cv : int, cross-validation generator or an iterable, optional, default 1
Determines the cross-validation splitting strategy for the preliminary effect model.
prel_opt_reweighted : bool, optional, default True
Whether to reweight the samples to minimize variance for the preliminary effect model.
projection: bool, optional, default False
If True, we fit a slight variant of DRIV where we use E[T|X, W, Z] as the instrument as opposed to Z,
model_z_xw will be disabled; If False, model_t_xwz will be disabled.
featurizer : :term:`transformer`, optional, default None
Must support fit_transform and transform. Used to create composite features in the final CATE regression.
It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).
If featurizer=None, then CATE is trained on X.
fit_cate_intercept : bool, optional, default True
Whether the linear CATE model should have a constant term.
alpha: string | float, optional., default 'auto'.
CATE L1 regularization applied through the debiased lasso in the final model.
'auto' corresponds to a CV form of the :class:`DebiasedLasso`.
n_alphas : int, optional, default 100
How many alphas to try if alpha='auto'
alpha_cov : string | float, optional, default 'auto'
The regularization alpha that is used when constructing the pseudo inverse of
the covariance matrix Theta used to for correcting the final state lasso coefficient
in the debiased lasso. Each such regression corresponds to the regression of one feature
on the remainder of the features.
n_alphas_cov : int, optional, default 10
How many alpha_cov to try if alpha_cov='auto'.
max_iter : int, optional, default 1000
The maximum number of iterations in the Debiased Lasso
tol : float, optional, default 1e-4
The tolerance for the optimization: if the updates are
smaller than ``tol``, the optimization code checks the
dual gap for optimality and continues until it is smaller
than ``tol``.
n_jobs : int or None, optional (default=None)
The number of jobs to run in parallel for both `fit` and `predict`.
``None`` means 1 unless in a :func:`joblib.parallel_backend` context.
``-1`` means using all processors.
cov_clip : float, optional, default 0.1
clipping of the covariate for regions with low "overlap", to reduce variance
opt_reweighted : bool, optional, default False
Whether to reweight the samples to minimize variance. If True then
model_final.fit must accept sample_weight as a kw argument. If True then
assumes the model_final is flexible enough to fit the true CATE model. Otherwise,
it method will return a biased projection to the model_final space, biased
to give more weight on parts of the feature space where the instrument is strong.
discrete_instrument: bool, optional, default False
Whether the instrument values should be treated as categorical, rather than continuous, quantities
discrete_treatment: bool, optional, default False
Whether the treatment values should be treated as categorical, rather than continuous, quantities
categories: 'auto' or list, default 'auto'
The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).
The first category will be treated as the control treatment.
cv: int, cross-validation generator or an iterable, optional, default 2
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- :term:`CV splitter`
- An iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if the treatment is discrete
:class:`~sklearn.model_selection.StratifiedKFold` is used, else,
:class:`~sklearn.model_selection.KFold` is used
(with a random shuffle in either case).
Unless an iterable is used, we call `split(concat[W, X], T)` to generate the splits. If all
W, X are None, then we call `split(ones((T.shape[0], 1)), T)`.
mc_iters: int, optional (default=None)
The number of times to rerun the first stage models to reduce the variance of the nuisances.
mc_agg: {'mean', 'median'}, optional (default='mean')
How to aggregate the nuisance value for each sample across the `mc_iters` monte carlo iterations of
cross-fitting.
random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;
If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used
by :mod:`np.random<numpy.random>`.
Examples
--------
A simple example with the default models:
.. testcode::
:hide:
import numpy as np
import scipy.special
np.set_printoptions(suppress=True)
.. testcode::
from econml.iv.dr import SparseLinearDRIV
# Define the data generation functions
def dgp(n, p, true_fn):
X = np.random.normal(0, 1, size=(n, p))
Z = np.random.binomial(1, 0.5, size=(n,))
nu = np.random.uniform(0, 10, size=(n,))
coef_Z = 0.8
C = np.random.binomial(
1, coef_Z * scipy.special.expit(0.4 * X[:, 0] + nu)
) # Compliers when recomended
C0 = np.random.binomial(
1, 0.06 * np.ones(X.shape[0])
) # Non-compliers when not recommended
T = C * Z + C0 * (1 - Z)
y = true_fn(X) * T + 2 * nu + 5 * (X[:, 3] > 0) + 0.1 * np.random.uniform(0, 1, size=(n,))
return y, T, Z, X
def true_heterogeneity_function(X):
return 5 * X[:, 0]
np.random.seed(123)
y, T, Z, X = dgp(1000, 5, true_heterogeneity_function)
est = SparseLinearDRIV(discrete_treatment=True, discrete_instrument=True)
est.fit(Y=y, T=T, Z=Z, X=X)
>>> est.effect(X[:3])
array([-4.83304..., 5.76728..., -3.38677...])
>>> est.effect_interval(X[:3])
(array([-7.73949... , 1.62799..., -5.92335... ]),
array([-1.92659..., 9.90657..., -0.85020...]))
>>> est.coef_
array([ 4.91422... , 0.75957..., 0.23460..., -0.02084..., 0.08548...])
>>> est.coef__interval()
(array([ 3.71131... , -0.45763..., -1.00739..., -1.20516..., -1.15926...]),
array([6.11713..., 1.97678..., 1.47661..., 1.16347..., 1.33023...]))
>>> est.intercept_
-0.30389...
>>> est.intercept__interval()
(-1.50685..., 0.89906...)
"""
def __init__(self, *,
model_y_xw="auto",
model_t_xw="auto",
model_z_xw="auto",
model_t_xwz="auto",
model_tz_xw="auto",
flexible_model_effect="auto",
prel_cate_approach="driv",
prel_cv=1,
prel_opt_reweighted=True,
projection=False,
featurizer=None,
fit_cate_intercept=True,
alpha='auto',
n_alphas=100,
alpha_cov='auto',
n_alphas_cov=10,
max_iter=1000,
tol=1e-4,
n_jobs=None,
cov_clip=1e-3,
opt_reweighted=False,
discrete_instrument=False,
discrete_treatment=False,
categories='auto',
cv=2,
mc_iters=None,
mc_agg='mean',
random_state=None):
self.alpha = alpha
self.n_alphas = n_alphas
self.alpha_cov = alpha_cov
self.n_alphas_cov = n_alphas_cov
self.max_iter = max_iter
self.tol = tol
self.n_jobs = n_jobs
super().__init__(model_y_xw=model_y_xw,
model_t_xw=model_t_xw,
model_z_xw=model_z_xw,
model_t_xwz=model_t_xwz,
model_tz_xw=model_tz_xw,
flexible_model_effect=flexible_model_effect,
model_final=None,
prel_cate_approach=prel_cate_approach,
prel_cv=prel_cv,
prel_opt_reweighted=prel_opt_reweighted,
projection=projection,
featurizer=featurizer,
fit_cate_intercept=fit_cate_intercept,
cov_clip=cov_clip,
opt_reweighted=opt_reweighted,
discrete_instrument=discrete_instrument,
discrete_treatment=discrete_treatment,
categories=categories,
cv=cv,
mc_iters=mc_iters,
mc_agg=mc_agg,
random_state=random_state)
def _gen_model_final(self):
return DebiasedLasso(alpha=self.alpha,
n_alphas=self.n_alphas,
alpha_cov=self.alpha_cov,
n_alphas_cov=self.n_alphas_cov,
fit_intercept=False,
max_iter=self.max_iter,
tol=self.tol,
n_jobs=self.n_jobs,
random_state=self.random_state)
def fit(self, Y, T, *, Z, X=None, W=None, sample_weight=None, groups=None,
cache_values=False, inference='auto'):
"""
Estimate the counterfactual model from data, i.e. estimates function :math:`\\theta(\\cdot)`.
Parameters
----------
Y: (n,) vector of length n
Outcomes for each sample
T: (n,) vector of length n
Treatments for each sample
Z: (n, d_z) matrix
Instruments for each sample
X: optional(n, d_x) matrix or None (Default=None)
Features for each sample
W: optional(n, d_w) matrix or None (Default=None)
Controls for each sample
sample_weight : (n,) array like, default None
Individual weights for each sample. If None, it assumes equal weight.
groups: (n,) vector, optional
All rows corresponding to the same group will be kept together during splitting.
If groups is not None, the `cv` argument passed to this class's initializer
must support a 'groups' argument to its split method.
cache_values: bool, default False
Whether to cache inputs and first stage results, which will allow refitting a different final model
inference: string, :class:`.Inference` instance, or None
Method for performing inference. This estimator supports ``'bootstrap'``
(or an instance of :class:`.BootstrapInference`) and ``'debiasedlasso'``
(or an instance of :class:`.LinearModelInferenceDiscrete`).
Returns
-------
self
"""
# TODO: support freq_weight and sample_var in debiased lasso
# Replacing fit from _OrthoLearner, to reorder arguments and improve the docstring
check_high_dimensional(X, T, threshold=5, featurizer=self.featurizer,
discrete_treatment=self.discrete_treatment,
msg="The number of features in the final model (< 5) is too small for a sparse model. "
"We recommend using the LinearDRLearner for this low-dimensional setting.")
return super().fit(Y, T, X=X, W=W, Z=Z,
sample_weight=sample_weight, groups=groups,
cache_values=cache_values, inference=inference)
@property
def fit_cate_intercept_(self):
return self.ortho_learner_model_final_._fit_cate_intercept
@property
def bias_part_of_coef(self):
return self.ortho_learner_model_final_._fit_cate_intercept
@property
def model_final(self):
return self._gen_model_final()
@model_final.setter
def model_final(self, model):
if model is not None:
raise ValueError("Parameter `model_final` cannot be altered for this estimator!")
class ForestDRIV(ForestModelFinalCateEstimatorMixin, DRIV):
""" Instance of DRIV with a :class:`~econml.grf.RegressionForest`
as a final model, so as to enable non-parametric inference.
Parameters
----------
model_y_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Y | X, W]`. Must support `fit` and `predict` methods.
If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.
model_t_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous treatment.
model_z_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Z | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete instrument,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous instrument.
model_t_xwz : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W, Z]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous treatment.
model_tz_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T*Z | X, W]`. Must support `fit` and `predict` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete instrument and discrete treatment,
and :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV`
will be applied for continuous instrument or continuous treatment.
flexible_model_effect : estimator or 'auto' (default is 'auto')
a flexible model for a preliminary version of the CATE, must accept sample_weight at fit time.
If 'auto', :class:`.StatsModelsLinearRegression` will be applied.
prel_cate_approach : one of {'driv', 'dmliv'}, optional (default='driv')
model that estimates a preliminary version of the CATE.
If 'driv', :class:`._DRIV` will be used.
If 'dmliv', :class:`.NonParamDMLIV` will be used
prel_cv : int, cross-validation generator or an iterable, optional, default 1
Determines the cross-validation splitting strategy for the preliminary effect model.
prel_opt_reweighted : bool, optional, default True
Whether to reweight the samples to minimize variance for the preliminary effect model.
projection: bool, optional, default False
If True, we fit a slight variant of DRIV where we use E[T|X, W, Z] as the instrument as opposed to Z,
model_z_xw will be disabled; If False, model_t_xwz will be disabled.
featurizer : :term:`transformer`, optional, default None
Must support fit_transform and transform. Used to create composite features in the final CATE regression.
It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).
If featurizer=None, then CATE is trained on X.
n_estimators : integer, optional (default=100)
The total number of trees in the forest. The forest consists of a
forest of sqrt(n_estimators) sub-forests, where each sub-forest
contains sqrt(n_estimators) trees.
max_depth : integer or None, optional (default=None)
The maximum depth of the tree. If None, then nodes are expanded until
all leaves are pure or until all leaves contain less than
min_samples_split samples.
min_samples_split : int, float, optional (default=2)
The minimum number of splitting samples required to split an internal node.
- If int, then consider `min_samples_split` as the minimum number.
- If float, then `min_samples_split` is a fraction and
`ceil(min_samples_split * n_samples)` are the minimum
number of samples for each split.
min_samples_leaf : int, float, optional (default=1)
The minimum number of samples required to be at a leaf node.
A split point at any depth will only be considered if it leaves at
least ``min_samples_leaf`` splitting samples in each of the left and
right branches. This may have the effect of smoothing the model,
especially in regression. After construction the tree is also pruned
so that there are at least min_samples_leaf estimation samples on
each leaf.
- If int, then consider `min_samples_leaf` as the minimum number.
- If float, then `min_samples_leaf` is a fraction and
`ceil(min_samples_leaf * n_samples)` are the minimum
number of samples for each node.
min_weight_fraction_leaf : float, optional (default=0.)
The minimum weighted fraction of the sum total of weights (of all
splitting samples) required to be at a leaf node. Samples have
equal weight when sample_weight is not provided. After construction
the tree is pruned so that the fraction of the sum total weight
of the estimation samples contained in each leaf node is at
least min_weight_fraction_leaf
max_features : int, float, string or None, optional (default="auto")
The number of features to consider when looking for the best split:
- If int, then consider `max_features` features at each split.
- If float, then `max_features` is a fraction and
`int(max_features * n_features)` features are considered at each
split.
- If "auto", then `max_features=n_features`.
- If "sqrt", then `max_features=sqrt(n_features)`.
- If "log2", then `max_features=log2(n_features)`.
- If None, then `max_features=n_features`.
Note: the search for a split does not stop until at least one
valid partition of the node samples is found, even if it requires to
effectively inspect more than ``max_features`` features.
min_impurity_decrease : float, optional (default=0.)
A node will be split if this split induces a decrease of the impurity
greater than or equal to this value.
The weighted impurity decrease equation is the following::
N_t / N * (impurity - N_t_R / N_t * right_impurity
- N_t_L / N_t * left_impurity)
where ``N`` is the total number of split samples, ``N_t`` is the number of
split samples at the current node, ``N_t_L`` is the number of split samples in the
left child, and ``N_t_R`` is the number of split samples in the right child.
``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
if ``sample_weight`` is passed.
max_samples : int or float in (0, .5], default=.45,
The number of samples to use for each subsample that is used to train each tree:
- If int, then train each tree on `max_samples` samples, sampled without replacement from all the samples
- If float, then train each tree on ceil(`max_samples` * `n_samples`), sampled without replacement
from all the samples.
min_balancedness_tol: float in [0, .5], default=.45
How imbalanced a split we can tolerate. This enforces that each split leaves at least
(.5 - min_balancedness_tol) fraction of samples on each side of the split; or fraction
of the total weight of samples, when sample_weight is not None. Default value, ensures
that at least 5% of the parent node weight falls in each side of the split. Set it to 0.0 for no
balancedness and to .5 for perfectly balanced splits. For the formal inference theory
to be valid, this has to be any positive constant bounded away from zero.
honest : boolean, optional (default=True)
Whether to use honest trees, i.e. half of the samples are used for
creating the tree structure and the other half for the estimation at
the leafs. If False, then all samples are used for both parts.
subforest_size : int, default=4,
The number of trees in each sub-forest that is used in the bootstrap-of-little-bags calculation.
The parameter `n_estimators` must be divisible by `subforest_size`. Should typically be a small constant.
n_jobs : int or None, optional (default=-1)
The number of jobs to run in parallel for both `fit` and `predict`.
``None`` means 1 unless in a :func:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
verbose : int, optional (default=0)
Controls the verbosity when fitting and predicting.
cov_clip : float, optional, default 0.1
clipping of the covariate for regions with low "overlap", to reduce variance
opt_reweighted : bool, optional, default False
Whether to reweight the samples to minimize variance. If True then
model_final.fit must accept sample_weight as a kw argument. If True then
assumes the model_final is flexible enough to fit the true CATE model. Otherwise,
it method will return a biased projection to the model_final space, biased
to give more weight on parts of the feature space where the instrument is strong.
discrete_instrument: bool, optional, default False
Whether the instrument values should be treated as categorical, rather than continuous, quantities
discrete_treatment: bool, optional, default False
Whether the treatment values should be treated as categorical, rather than continuous, quantities
categories: 'auto' or list, default 'auto'
The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).
The first category will be treated as the control treatment.
cv: int, cross-validation generator or an iterable, optional, default 2
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- :term:`CV splitter`
- An iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if the treatment is discrete
:class:`~sklearn.model_selection.StratifiedKFold` is used, else,
:class:`~sklearn.model_selection.KFold` is used
(with a random shuffle in either case).
Unless an iterable is used, we call `split(concat[W, X], T)` to generate the splits. If all
W, X are None, then we call `split(ones((T.shape[0], 1)), T)`.
mc_iters: int, optional (default=None)
The number of times to rerun the first stage models to reduce the variance of the nuisances.
mc_agg: {'mean', 'median'}, optional (default='mean')
How to aggregate the nuisance value for each sample across the `mc_iters` monte carlo iterations of
cross-fitting.
random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;
If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used
by :mod:`np.random<numpy.random>`.
Examples
--------
A simple example with the default models:
.. testcode::
:hide:
import numpy as np
import scipy.special
np.set_printoptions(suppress=True)
.. testcode::
from econml.iv.dr import ForestDRIV
# Define the data generation functions
def dgp(n, p, true_fn):
X = np.random.normal(0, 1, size=(n, p))
Z = np.random.binomial(1, 0.5, size=(n,))
nu = np.random.uniform(0, 10, size=(n,))
coef_Z = 0.8
C = np.random.binomial(
1, coef_Z * scipy.special.expit(0.4 * X[:, 0] + nu)
) # Compliers when recomended
C0 = np.random.binomial(
1, 0.06 * np.ones(X.shape[0])
) # Non-compliers when not recommended
T = C * Z + C0 * (1 - Z)
y = true_fn(X) * T + 2 * nu + 5 * (X[:, 3] > 0) + 0.1 * np.random.uniform(0, 1, size=(n,))
return y, T, Z, X
def true_heterogeneity_function(X):
return 5 * X[:, 0]
np.random.seed(123)
y, T, Z, X = dgp(1000, 5, true_heterogeneity_function)
est = ForestDRIV(discrete_treatment=True, discrete_instrument=True, random_state=123)
est.fit(Y=y, T=T, Z=Z, X=X)
>>> est.effect(X[:3])
array([-2.40650..., 6.03247..., -2.46690...])
>>> est.effect_interval(X[:3])
(array([-6.77859..., -0.05394..., -4.48171...]),
array([ 1.96558..., 12.11890..., -0.45210... ]))
"""
def __init__(self, *,
model_y_xw="auto",
model_t_xw="auto",
model_z_xw="auto",
model_t_xwz="auto",
model_tz_xw="auto",
flexible_model_effect="auto",
prel_cate_approach="driv",
prel_cv=1,
prel_opt_reweighted=True,
projection=False,
featurizer=None,
n_estimators=1000,
max_depth=None,
min_samples_split=5,
min_samples_leaf=5,
min_weight_fraction_leaf=0.,
max_features="auto",
min_impurity_decrease=0.,
max_samples=.45,
min_balancedness_tol=.45,
honest=True,
subforest_size=4,
n_jobs=-1,
verbose=0,
cov_clip=1e-3,
opt_reweighted=False,
discrete_instrument=False,
discrete_treatment=False,
categories='auto',
cv=2,
mc_iters=None,
mc_agg='mean',
random_state=None):
self.n_estimators = n_estimators
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.max_features = max_features
self.min_impurity_decrease = min_impurity_decrease
self.max_samples = max_samples
self.min_balancedness_tol = min_balancedness_tol
self.honest = honest
self.subforest_size = subforest_size
self.n_jobs = n_jobs
self.verbose = verbose
super().__init__(model_y_xw=model_y_xw,
model_t_xw=model_t_xw,
model_z_xw=model_z_xw,
model_t_xwz=model_t_xwz,
model_tz_xw=model_tz_xw,
flexible_model_effect=flexible_model_effect,
model_final=None,
prel_cate_approach=prel_cate_approach,
prel_cv=prel_cv,
prel_opt_reweighted=prel_opt_reweighted,
projection=projection,
featurizer=featurizer,
fit_cate_intercept=False,
cov_clip=cov_clip,
opt_reweighted=opt_reweighted,
discrete_instrument=discrete_instrument,
discrete_treatment=discrete_treatment,
categories=categories,
cv=cv,
mc_iters=mc_iters,
mc_agg=mc_agg,
random_state=random_state)
def _gen_model_final(self):
return RegressionForest(n_estimators=self.n_estimators,
max_depth=self.max_depth,
min_samples_split=self.min_samples_split,
min_samples_leaf=self.min_samples_leaf,
min_weight_fraction_leaf=self.min_weight_fraction_leaf,
max_features=self.max_features,
min_impurity_decrease=self.min_impurity_decrease,
max_samples=self.max_samples,
min_balancedness_tol=self.min_balancedness_tol,
honest=self.honest,
inference=True,
subforest_size=self.subforest_size,
n_jobs=self.n_jobs,
random_state=self.random_state,
verbose=self.verbose,
warm_start=False)
def fit(self, Y, T, *, Z, X=None, W=None, sample_weight=None, groups=None,
cache_values=False, inference='auto'):
"""
Estimate the counterfactual model from data, i.e. estimates function :math:`\\theta(\\cdot)`.
Parameters
----------
Y: (n,) vector of length n
Outcomes for each sample
T: (n,) vector of length n
Treatments for each sample
Z: (n, d_z) matrix
Instruments for each sample
X: optional(n, d_x) matrix or None (Default=None)
Features for each sample
W: optional(n, d_w) matrix or None (Default=None)
Controls for each sample
sample_weight : (n,) array like, default None
Individual weights for each sample. If None, it assumes equal weight.
groups: (n,) vector, optional
All rows corresponding to the same group will be kept together during splitting.
If groups is not None, the `cv` argument passed to this class's initializer
must support a 'groups' argument to its split method.
cache_values: bool, default False
Whether to cache inputs and first stage results, which will allow refitting a different final model
inference: string, `Inference` instance, or None
Method for performing inference. This estimator supports 'bootstrap'
(or an instance of :class:`.BootstrapInference`) and 'blb'
(for Bootstrap-of-Little-Bags based inference)
Returns
-------
self
"""
if X is None:
raise ValueError("This estimator does not support X=None!")
# Replacing fit from _OrthoLearner, to reorder arguments and improve the docstring
return super().fit(Y, T, X=X, W=W, Z=Z,
sample_weight=sample_weight, groups=groups,
cache_values=cache_values, inference=inference)
@property
def model_final(self):
return self._gen_model_final()
@model_final.setter
def model_final(self, model):
if model is not None:
raise ValueError("Parameter `model_final` cannot be altered for this estimator!")
class _IntentToTreatDRIVModelNuisance:
def __init__(self, model_y_xw, model_t_xwz, dummy_z, prel_model_effect):
self._model_y_xw = clone(model_y_xw, safe=False)
self._model_t_xwz = clone(model_t_xwz, safe=False)
self._dummy_z = clone(dummy_z, safe=False)
self._prel_model_effect = clone(prel_model_effect, safe=False)
def _combine(self, W, Z, n_samples):
if Z is not None: # Z will not be None
Z = Z.reshape(n_samples, -1)
return Z if W is None else np.hstack([W, Z])
return None if W is None else W
def fit(self, Y, T, X=None, W=None, Z=None, sample_weight=None, groups=None):
self._model_y_xw.fit(X=X, W=W, Target=Y, sample_weight=sample_weight, groups=groups)
# concat W and Z
WZ = self._combine(W, Z, Y.shape[0])
self._model_t_xwz.fit(X=X, W=WZ, Target=T, sample_weight=sample_weight, groups=groups)
self._dummy_z.fit(X=X, W=W, Target=Z, sample_weight=sample_weight, groups=groups)
# we need to undo the one-hot encoding for calling effect,
# since it expects raw values
self._prel_model_effect.fit(Y, inverse_onehot(T), Z=inverse_onehot(Z), X=X, W=W,
sample_weight=sample_weight, groups=groups)
return self
def score(self, Y, T, X=None, W=None, Z=None, sample_weight=None, groups=None):
if hasattr(self._model_y_xw, 'score'):
Y_X_score = self._model_y_xw.score(X=X, W=W, Target=Y, sample_weight=sample_weight)
else:
Y_X_score = None
if hasattr(self._model_t_xwz, 'score'):
# concat W and Z
WZ = self._combine(W, Z, Y.shape[0])
T_XZ_score = self._model_t_xwz.score(X=X, W=WZ, Target=T, sample_weight=sample_weight)
else:
T_XZ_score = None
if hasattr(self._prel_model_effect, 'score'):
# we need to undo the one-hot encoding for calling effect,
# since it expects raw values
effect_score = self._prel_model_effect.score(Y, inverse_onehot(T),
inverse_onehot(Z), X=X, W=W, sample_weight=sample_weight)
else:
effect_score = None
return Y_X_score, T_XZ_score, effect_score
def predict(self, Y, T, X=None, W=None, Z=None, sample_weight=None, groups=None):
Y_pred = self._model_y_xw.predict(X, W)
T_pred_zero = self._model_t_xwz.predict(X, self._combine(W, np.zeros(Z.shape), Y.shape[0]))
T_pred_one = self._model_t_xwz.predict(X, self._combine(W, np.ones(Z.shape), Y.shape[0]))
Z_pred = self._dummy_z.predict(X, W)
prel_theta = self._prel_model_effect.effect(X)
if X is None: # In this case predict above returns a single row
prel_theta = np.tile(prel_theta.reshape(1, -1), (T.shape[0], 1))
if W is None:
Y_pred = np.tile(Y_pred.reshape(1, -1), (Y.shape[0], 1))
Z_pred = np.tile(Z_pred.reshape(1, -1), (Z.shape[0], 1))
# reshape the predictions
Y_pred = Y_pred.reshape(Y.shape)
Z_pred = Z_pred.reshape(Z.shape)
T_pred_one = T_pred_one.reshape(T.shape)
T_pred_zero = T_pred_zero.reshape(T.shape)
# T_res, Z_res, beta expect shape to be (n,1)
beta = Z_pred * (1 - Z_pred) * (T_pred_one - T_pred_zero)
T_pred = T_pred_one * Z_pred + T_pred_zero * (1 - Z_pred)
Y_res = Y - Y_pred
T_res = T - T_pred
Z_res = Z - Z_pred
return prel_theta, Y_res, T_res, Z_res, beta
class _DummyClassifier:
"""
A dummy classifier that always returns the prior ratio
Parameters
----------
ratio: float
The ratio of treatment samples
"""
def __init__(self, *, ratio):
self.ratio = ratio
def fit(self, X, y, **kwargs):
return self
def predict_proba(self, X):
n = X.shape[0]
return np.hstack((np.tile(1 - self.ratio, (n, 1)), np.tile(self.ratio, (n, 1))))
class _IntentToTreatDRIV(_BaseDRIV):
"""
Base class for the DRIV algorithm for the intent-to-treat A/B test setting
"""
def __init__(self, *,
model_y_xw="auto",
model_t_xwz="auto",
prel_model_effect,
model_final,
z_propensity="auto",
featurizer=None,
fit_cate_intercept=False,
cov_clip=1e-3,
opt_reweighted=False,
categories='auto',
cv=3,
mc_iters=None,
mc_agg='mean',
random_state=None):
self.model_y_xw = clone(model_y_xw, safe=False)
self.model_t_xwz = clone(model_t_xwz, safe=False)
self.prel_model_effect = clone(prel_model_effect, safe=False)
self.z_propensity = z_propensity
super().__init__(model_final=model_final,
featurizer=featurizer,
fit_cate_intercept=fit_cate_intercept,
cov_clip=cov_clip,
cv=cv,
mc_iters=mc_iters,
mc_agg=mc_agg,
discrete_instrument=True,
discrete_treatment=True,
categories=categories,
opt_reweighted=opt_reweighted,
random_state=random_state)
def _gen_prel_model_effect(self):
return clone(self.prel_model_effect, safe=False)
def _gen_ortho_learner_model_nuisance(self):
if self.model_y_xw == 'auto':
model_y_xw = WeightedLassoCVWrapper(random_state=self.random_state)
else:
model_y_xw = clone(self.model_y_xw, safe=False)
if self.model_t_xwz == 'auto':
model_t_xwz = LogisticRegressionCV(cv=WeightedStratifiedKFold(random_state=self.random_state),
random_state=self.random_state)
else:
model_t_xwz = clone(self.model_t_xwz, safe=False)
if self.z_propensity == "auto":
dummy_z = DummyClassifier(strategy="prior")
elif isinstance(self.z_propensity, float):
dummy_z = _DummyClassifier(ratio=self.z_propensity)
else:
raise ValueError("Only 'auto' or float is allowed!")
return _IntentToTreatDRIVModelNuisance(_FirstStageWrapper(model_y_xw, True, self._gen_featurizer(),
False, False),
_FirstStageWrapper(model_t_xwz, False,
self._gen_featurizer(), False, True),
_FirstStageWrapper(dummy_z, False,
self._gen_featurizer(), False, True),
self._gen_prel_model_effect()
)
class _DummyCATE:
"""
A dummy cate effect model that always returns zero effect
"""
def __init__(self):
return
def fit(self, y, T, *, Z, X=None, W=None, sample_weight=None, groups=None, **kwargs):
return self
def effect(self, X):
if X is None:
return np.zeros(1)
return np.zeros(X.shape[0])
class IntentToTreatDRIV(_IntentToTreatDRIV):
"""
Implements the DRIV algorithm for the intent-to-treat A/B test setting
Parameters
----------
model_y_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Y | X, W]`. Must support `fit` and `predict` methods.
If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.
model_t_xwz : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W, Z]`. Must support `fit` and `predict_proba` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment.
flexible_model_effect : estimator or 'auto' (default is 'auto')
a flexible model for a preliminary version of the CATE, must accept sample_weight at fit time.
If 'auto', :class:`.StatsModelsLinearRegression` will be applied.
model_final : estimator, optional
a final model for the CATE and projections. If None, then flexible_model_effect is also used as a final model
prel_cate_approach : one of {'driv', 'dmliv'}, optional (default='driv')
model that estimates a preliminary version of the CATE.
If 'driv', :class:`._DRIV` will be used.
If 'dmliv', :class:`.NonParamDMLIV` will be used
prel_cv : int, cross-validation generator or an iterable, optional, default 1
Determines the cross-validation splitting strategy for the preliminary effect model.
prel_opt_reweighted : bool, optional, default True
Whether to reweight the samples to minimize variance for the preliminary effect model.
z_propensity: float or "auto", optional, default "auto"
The ratio of the A/B test in treatment group. If "auto", we assume that the instrument is fully randomized
and independent of any other variables. It's calculated as the proportion of Z=1 in the overall population;
If input a ratio, it has to be a float between 0 to 1.
featurizer : :term:`transformer`, optional, default None
Must support fit_transform and transform. Used to create composite features in the final CATE regression.
It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).
If featurizer=None, then CATE is trained on X.
fit_cate_intercept : bool, optional, default False
Whether the linear CATE model should have a constant term.
cov_clip : float, optional, default 0.1
clipping of the covariate for regions with low "overlap", to reduce variance
cv: int, cross-validation generator or an iterable, optional, default 3
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- :term:`CV splitter`
- An iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if the treatment is discrete
:class:`~sklearn.model_selection.StratifiedKFold` is used, else,
:class:`~sklearn.model_selection.KFold` is used
(with a random shuffle in either case).
Unless an iterable is used, we call `split(concat[W, X], T)` to generate the splits. If all
W, X are None, then we call `split(ones((T.shape[0], 1)), T)`.
mc_iters: int, optional (default=None)
The number of times to rerun the first stage models to reduce the variance of the nuisances.
mc_agg: {'mean', 'median'}, optional (default='mean')
How to aggregate the nuisance value for each sample across the `mc_iters` monte carlo iterations of
cross-fitting.
opt_reweighted : bool, optional, default False
Whether to reweight the samples to minimize variance. If True then
final_model_effect.fit must accept sample_weight as a kw argument (WeightWrapper from
utilities can be used for any linear model to enable sample_weights). If True then
assumes the final_model_effect is flexible enough to fit the true CATE model. Otherwise,
it method will return a biased projection to the model_effect space, biased
to give more weight on parts of the feature space where the instrument is strong.
categories: 'auto' or list, default 'auto'
The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).
The first category will be treated as the control treatment.
random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;
If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used
by :mod:`np.random<numpy.random>`.
Examples
--------
A simple example with the default models:
.. testcode::
:hide:
import numpy as np
import scipy.special
np.set_printoptions(suppress=True)
.. testcode::
from econml.iv.dr import IntentToTreatDRIV
# Define the data generation functions
def dgp(n, p, true_fn):
X = np.random.normal(0, 1, size=(n, p))
Z = np.random.binomial(1, 0.5, size=(n,))
nu = np.random.uniform(0, 10, size=(n,))
coef_Z = 0.8
C = np.random.binomial(
1, coef_Z * scipy.special.expit(0.4 * X[:, 0] + nu)
) # Compliers when recomended
C0 = np.random.binomial(
1, 0.06 * np.ones(X.shape[0])
) # Non-compliers when not recommended
T = C * Z + C0 * (1 - Z)
y = true_fn(X) * T + 2 * nu + 5 * (X[:, 3] > 0) + 0.1 * np.random.uniform(0, 1, size=(n,))
return y, T, Z, X
def true_heterogeneity_function(X):
return 5 * X[:, 0]
np.random.seed(123)
y, T, Z, X = dgp(1000, 5, true_heterogeneity_function)
est = IntentToTreatDRIV()
est.fit(Y=y, T=T, Z=Z, X=X)
>>> est.effect(X[:3])
array([-4.29282..., 6.08590..., -2.11608...])
"""
def __init__(self, *,
model_y_xw="auto",
model_t_xwz="auto",
prel_cate_approach="driv",
flexible_model_effect="auto",
model_final=None,
prel_cv=1,
prel_opt_reweighted=True,
z_propensity="auto",
featurizer=None,
fit_cate_intercept=False,
cov_clip=1e-3,
cv=3,
mc_iters=None,
mc_agg='mean',
opt_reweighted=False,
categories='auto',
random_state=None):
# maybe shouldn't expose fit_cate_intercept in this class?
if flexible_model_effect == "auto":
self.flexible_model_effect = StatsModelsLinearRegression(fit_intercept=False)
else:
self.flexible_model_effect = clone(flexible_model_effect, safe=False)
self.prel_cate_approach = prel_cate_approach
self.prel_cv = prel_cv
self.prel_opt_reweighted = prel_opt_reweighted
super().__init__(model_y_xw=model_y_xw,
model_t_xwz=model_t_xwz,
prel_model_effect=self.prel_cate_approach,
model_final=model_final,
z_propensity=z_propensity,
featurizer=featurizer,
fit_cate_intercept=fit_cate_intercept,
cov_clip=cov_clip,
opt_reweighted=opt_reweighted,
categories=categories,
cv=cv,
mc_iters=mc_iters,
mc_agg=mc_agg,
random_state=random_state)
def _gen_model_final(self):
if self.model_final is None:
return clone(self.flexible_model_effect, safe=False)
return clone(self.model_final, safe=False)
def _gen_prel_model_effect(self):
if self.prel_cate_approach == "driv":
return _IntentToTreatDRIV(model_y_xw=clone(self.model_y_xw, safe=False),
model_t_xwz=clone(self.model_t_xwz, safe=False),
prel_model_effect=_DummyCATE(),
model_final=clone(self.flexible_model_effect, safe=False),
featurizer=self._gen_featurizer(),
fit_cate_intercept=self.fit_cate_intercept,
cov_clip=self.cov_clip,
categories=self.categories,
opt_reweighted=self.prel_opt_reweighted,
cv=self.prel_cv,
random_state=self.random_state)
elif self.prel_cate_approach == "dmliv":
return NonParamDMLIV(model_y_xw=clone(self.model_y_xw, safe=False),
model_t_xw=clone(self.model_t_xwz, safe=False),
model_t_xwz=clone(self.model_t_xwz, safe=False),
model_final=clone(self.flexible_model_effect, safe=False),
discrete_instrument=True,
discrete_treatment=True,
featurizer=self._gen_featurizer(),
categories=self.categories,
cv=self.prel_cv,
mc_iters=self.mc_iters,
mc_agg=self.mc_agg,
random_state=self.random_state)
else:
raise ValueError(
"We only support 'dmliv' or 'driv' preliminary model effect, "
f"but received '{self.prel_cate_approach}'!")
@property
def models_y_xw(self):
"""
Get the fitted models for :math:`\\E[Y | X]`.
Returns
-------
models_y_xw: nested list of objects of type(`model_y_xw`)
A nested list of instances of the `model_y_xw` object. Number of sublist equals to number of monte carlo
iterations, each element in the sublist corresponds to a crossfitting
fold and is the model instance that was fitted for that training fold.
"""
return [[mdl._model_y_xw._model for mdl in mdls] for mdls in super().models_nuisance_]
@property
def models_t_xwz(self):
"""
Get the fitted models for :math:`\\E[T | X, Z]`.
Returns
-------
models_t_xwz: nested list of objects of type(`model_t_xwz`)
A nested list of instances of the `model_t_xwz` object. Number of sublist equals to number of monte carlo
iterations, each element in the sublist corresponds to a crossfitting
fold and is the model instance that was fitted for that training fold.
"""
return [[mdl._model_t_xwz._model for mdl in mdls] for mdls in super().models_nuisance_]
@property
def models_prel_model_effect(self):
"""
Get the fitted preliminary CATE estimator.
Returns
-------
prel_model_effect: nested list of objects of type(`prel_model_effect`)
A nested list of instances of the `prel_model_effect` object. Number of sublist equals to number
of monte carlo iterations, each element in the sublist corresponds to a crossfitting
fold and is the model instance that was fitted for that training fold.
"""
return [[mdl._prel_model_effect for mdl in mdls] for mdls in super().models_nuisance_]
@property
def nuisance_scores_y_xw(self):
"""
Get the scores for y_xw model on the out-of-sample training data
"""
return self.nuisance_scores_[0]
@property
def nuisance_scores_t_xwz(self):
"""
Get the scores for t_xw model on the out-of-sample training data
"""
return self.nuisance_scores_[1]
@property
def nuisance_scores_prel_model_effect(self):
"""
Get the scores for prel_model_effect model on the out-of-sample training data
"""
return self.nuisance_scores_[2]
class LinearIntentToTreatDRIV(StatsModelsCateEstimatorMixin, IntentToTreatDRIV):
"""
Implements the DRIV algorithm for the Linear Intent-to-Treat A/B test setting
Parameters
----------
model_y_xw : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[Y | X, W]`. Must support `fit` and `predict` methods.
If 'auto' :class:`.WeightedLassoCV`/:class:`.WeightedMultiTaskLassoCV` will be chosen.
model_t_xwz : estimator or 'auto' (default is 'auto')
model to estimate :math:`\\E[T | X, W, Z]`. Must support `fit` and `predict_proba` methods.
If 'auto', :class:`~sklearn.linear_model.LogisticRegressionCV`
will be applied for discrete treatment.
flexible_model_effect : estimator or 'auto' (default is 'auto')
a flexible model for a preliminary version of the CATE, must accept sample_weight at fit time.
If 'auto', :class:`.StatsModelsLinearRegression` will be applied.
prel_cate_approach : one of {'driv', 'dmliv'}, optional (default='driv')
model that estimates a preliminary version of the CATE.
If 'driv', :class:`._DRIV` will be used.
If 'dmliv', :class:`.NonParamDMLIV` will be used
prel_cv : int, cross-validation generator or an iterable, optional, default 1
Determines the cross-validation splitting strategy for the preliminary effect model.
prel_opt_reweighted : bool, optional, default True
Whether to reweight the samples to minimize variance for the preliminary effect model.
z_propensity: float or "auto", optional, default "auto"
The ratio of the A/B test in treatment group. If "auto", we assume that the instrument is fully randomized
and independent of any other variables. It's calculated as the proportion of Z=1 in the overall population;
If input a ratio, it has to be a float between 0 to 1.
featurizer : :term:`transformer`, optional, default None
Must support fit_transform and transform. Used to create composite features in the final CATE regression.
It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X).
If featurizer=None, then CATE is trained on X.
fit_cate_intercept : bool, optional, default True
Whether the linear CATE model should have a constant term.
cov_clip : float, optional, default 0.1
clipping of the covariate for regions with low "overlap", to reduce variance
cv: int, cross-validation generator or an iterable, optional, default 3
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- :term:`CV splitter`
- An iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if the treatment is discrete
:class:`~sklearn.model_selection.StratifiedKFold` is used, else,
:class:`~sklearn.model_selection.KFold` is used
(with a random shuffle in either case).
Unless an iterable is used, we call `split(concat[W, X], T)` to generate the splits. If all
W, X are None, then we call `split(ones((T.shape[0], 1)), T)`.
mc_iters: int, optional (default=None)
The number of times to rerun the first stage models to reduce the variance of the nuisances.
mc_agg: {'mean', 'median'}, optional (default='mean')
How to aggregate the nuisance value for each sample across the `mc_iters` monte carlo iterations of
cross-fitting.
opt_reweighted : bool, optional, default False
Whether to reweight the samples to minimize variance. If True then
final_model_effect.fit must accept sample_weight as a kw argument (WeightWrapper from
utilities can be used for any linear model to enable sample_weights). If True then
assumes the final_model_effect is flexible enough to fit the true CATE model. Otherwise,
it method will return a biased projection to the model_effect space, biased
to give more weight on parts of the feature space where the instrument is strong.
categories: 'auto' or list, default 'auto'
The categories to use when encoding discrete treatments (or 'auto' to use the unique sorted values).
The first category will be treated as the control treatment.
random_state: int, :class:`~numpy.random.mtrand.RandomState` instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If :class:`~numpy.random.mtrand.RandomState` instance, random_state is the random number generator;
If None, the random number generator is the :class:`~numpy.random.mtrand.RandomState` instance used
by :mod:`np.random<numpy.random>`.
Examples
--------
A simple example with the default models:
.. testcode::
:hide:
import numpy as np
import scipy.special
np.set_printoptions(suppress=True)
.. testcode::
from econml.iv.dr import LinearIntentToTreatDRIV
# Define the data generation functions
def dgp(n, p, true_fn):
X = np.random.normal(0, 1, size=(n, p))
Z = np.random.binomial(1, 0.5, size=(n,))
nu = np.random.uniform(0, 10, size=(n,))
coef_Z = 0.8
C = np.random.binomial(
1, coef_Z * scipy.special.expit(0.4 * X[:, 0] + nu)
) # Compliers when recomended
C0 = np.random.binomial(
1, 0.06 * np.ones(X.shape[0])
) # Non-compliers when not recommended
T = C * Z + C0 * (1 - Z)
y = true_fn(X) * T + 2 * nu + 5 * (X[:, 3] > 0) + 0.1 * np.random.uniform(0, 1, size=(n,))
return y, T, Z, X
def true_heterogeneity_function(X):
return 5 * X[:, 0]
np.random.seed(123)
y, T, Z, X = dgp(1000, 5, true_heterogeneity_function)
est = LinearIntentToTreatDRIV()
est.fit(Y=y, T=T, Z=Z, X=X)
>>> est.effect(X[:3])
array([-4.81123..., 5.65430..., -2.63204...])
>>> est.effect_interval(X[:3])
(array([-8.42669..., 0.36538... , -5.82840...]),
array([-1.19578... , 10.94323..., 0.56430...]))
>>> est.coef_
array([ 5.01936..., 0.71988..., 0.82603..., -0.08192... , -0.02520...])
>>> est.coef__interval()
(array([ 3.52057... , -0.72550..., -0.72653..., -1.50040... , -1.52896...]),
array([6.51816..., 2.16527..., 2.37861..., 1.33656..., 1.47854...]))
>>> est.intercept_
-0.45176...
>>> est.intercept__interval()
(-1.93313..., 1.02959...)
"""
def __init__(self, *,
model_y_xw="auto",
model_t_xwz="auto",
prel_cate_approach="driv",
flexible_model_effect="auto",
prel_cv=1,
prel_opt_reweighted=True,
z_propensity="auto",
featurizer=None,
fit_cate_intercept=True,
cov_clip=1e-3,
cv=3,
mc_iters=None,
mc_agg='mean',
opt_reweighted=False,
categories='auto',
random_state=None):
super().__init__(model_y_xw=model_y_xw,
model_t_xwz=model_t_xwz,
flexible_model_effect=flexible_model_effect,
model_final=None,
prel_cate_approach=prel_cate_approach,
prel_cv=prel_cv,
prel_opt_reweighted=prel_opt_reweighted,
z_propensity=z_propensity,
featurizer=featurizer,
fit_cate_intercept=fit_cate_intercept,
cov_clip=cov_clip,
cv=cv,
mc_iters=mc_iters,
mc_agg=mc_agg,
opt_reweighted=opt_reweighted,
categories=categories,
random_state=random_state)
def _gen_model_final(self):
return StatsModelsLinearRegression(fit_intercept=False)
# override only so that we can update the docstring to indicate support for `StatsModelsInference`
def fit(self, Y, T, *, Z, X=None, W=None, sample_weight=None, freq_weight=None, sample_var=None, groups=None,
cache_values=False, inference='auto'):
"""
Estimate the counterfactual model from data, i.e. estimates function :math:`\\theta(\\cdot)`.
Parameters
----------
Y: (n, d_y) matrix or vector of length n
Outcomes for each sample
T: (n, d_t) matrix or vector of length n
Treatments for each sample
Z: (n, d_z) matrix or vector of length n
Instruments for each sample
X: optional(n, d_x) matrix or None (Default=None)
Features for each sample
W: optional(n, d_w) matrix or None (Default=None)
Controls for each sample
sample_weight : (n,) array like or None
Individual weights for each sample. If None, it assumes equal weight.
freq_weight: (n,) array like of integers, default None
Weight for the observation. Observation i is treated as the mean
outcome of freq_weight[i] independent observations.
When ``sample_var`` is not None, this should be provided.
sample_var : (n,) nd array like, default None
Variance of the outcome(s) of the original freq_weight[i] observations that were used to
compute the mean outcome represented by observation i.
groups: (n,) vector, optional
All rows corresponding to the same group will be kept together during splitting.
If groups is not None, the `cv` argument passed to this class's initializer
must support a 'groups' argument to its split method.
cache_values: bool, default False
Whether to cache inputs and first stage results, which will allow refitting a different final model
inference: string,:class:`.Inference` instance, or None
Method for performing inference. This estimator supports 'bootstrap'
(or an instance of:class:`.BootstrapInference`) and 'statsmodels'
(or an instance of :class:`.StatsModelsInference`).
Returns
-------
self : instance
"""
# TODO: do correct adjustment for sample_var
return super().fit(Y, T, Z=Z, X=X, W=W,
sample_weight=sample_weight, freq_weight=freq_weight, sample_var=sample_var, groups=groups,
cache_values=cache_values, inference=inference)
@property
def fit_cate_intercept_(self):
return self.ortho_learner_model_final_._fit_cate_intercept
@property
def bias_part_of_coef(self):
return self.ortho_learner_model_final_._fit_cate_intercept
@property
def model_final(self):
return self._gen_model_final()
@model_final.setter
def model_final(self, value):
if value is not None:
raise ValueError("Parameter `model_final` cannot be altered for this estimator.") | PypiClean |
/Nimbus_Splash-1.1.0.tar.gz/Nimbus Splash-1.1.0/nimbus_splash/job.py | import os
import subprocess
from glob import glob
from . import utils as ut
def write_file(input_file: str, node_type: str, time: str,
dependency_paths: dict[str, str],
verbose: bool = False) -> str:
'''
Writes slurm jobscript to file for ORCA calculation on nimbus
Output file name is input_file with .slm extension
Parameters
----------
input_file : str
Full path to input file, including extension
node_type : str
Name of Nimbus node to use
time : str
Job time limit formatted as HH:MM:SS
verbose : bool, default=False
If True, prints job file name to screen
dependency_paths : list[str]
Full path to each dependency
Returns
-------
str
Name of jobscript file
'''
# Check for research allocation id environment variable
ut.check_envvar('CLOUD_ACC')
# Get raw name of input file excluding path
inpath, in_raw = os.path.split(input_file)
# Name of job
job_name = ut.gen_job_name(input_file)
# Name of results directory
results_name = ut.gen_results_name(input_file)
# Job file to write to, must use path if present in input_file
job_file = os.path.join(
inpath,
f'{job_name}.slm'
)
# Path of input file
calc_dir = os.path.abspath(inpath)
with open(job_file, 'w') as j:
j.write('#!/bin/bash\n\n')
j.write(f'#SBATCH --job-name={job_name}\n')
j.write('#SBATCH --nodes=1\n')
j.write('#SBATCH --ntasks-per-node={}\n'.format(
node_type.split('-')[-1])
)
j.write(f'#SBATCH --partition={node_type}\n')
j.write('#SBATCH --account={}\n'.format(os.environ['CLOUD_ACC']))
j.write(f'#SBATCH --qos={node_type}\n')
j.write(f'#SBATCH --output={job_name}.%j.o\n')
j.write(f'#SBATCH --error={job_name}.%j.e\n')
j.write('#SBATCH --signal=B:USR1\n\n')
j.write('# Job time\n')
j.write(f'#SBATCH --time={time}\n\n')
j.write('# name and path of the input/output files and locations\n')
j.write(f'input={in_raw}\n')
j.write(f'output={job_name}.out\n')
j.write(f'campaigndir={calc_dir}\n')
j.write(f'results=$campaigndir/{results_name}\n\n')
j.write('# Local (Node) scratch, either node itself if supported ')
j.write('or burstbuffer\n')
j.write('if [ -d "/mnt/resource/" ]; then\n')
j.write(
' localscratch="/mnt/resource/temp_scratch_$SLURM_JOB_ID"\n'
' mkdir $localscratch\n'
)
j.write('else\n')
j.write(' localscratch=$BURSTBUFFER\n')
j.write('fi\n\n')
j.write('# If output file already exists, append OLD and ')
j.write('last access time\n')
j.write('if [ -f $output ]; then\n')
j.write(
' mv $output "$output"_OLD_$(date -r $output "+%Y-%m-%d-%H-%M-%S")\n') # noqa
j.write('fi\n\n')
j.write('# Copy files to localscratch\n')
j.write('rsync -aP ')
j.write(f'{input_file}')
for dep in dependency_paths:
j.write(f' {dep}')
j.write(' $localscratch\n')
j.write('cd $localscratch\n\n')
j.write('# write date and node type to output\n')
j.write('date > $campaigndir/$output\n')
j.write('uname -n >> $campaigndir/$output\n\n')
j.write('# Module system setup\n')
j.write('source /apps/build/easy_build/scripts/id_instance.sh\n')
j.write('source /apps/build/easy_build/scripts/setup_modules.sh\n\n')
j.write('# Load orca\n')
j.write('module purge\n')
j.write('module load ORCA/5.0.1-gompi-2021a\n\n')
j.write('# UCX transport protocols for MPI\n')
j.write('export UCX_TLS=self,tcp,sm\n\n')
j.write('# If timeout, evicted, cancelled, then manually end orca\n')
j.write("trap 'echo signal recieved in BATCH!; kill -15 ")
j.write('"${PID}"; wait "${PID}";')
j.write("' SIGINT SIGTERM USR1 15\n\n")
j.write('# Run calculation in background\n')
j.write('# Catch the PID var for trap, and wait for process to end\n')
j.write('$(which orca) $input >> $campaigndir/$output &\n')
j.write('PID="$!"\n')
j.write('wait "${PID}"\n\n')
j.write('# Clean up and copy back files\n')
j.write('# Check for existing results directory\n')
j.write('cd $campaigndir\n')
j.write('# If results directory already exists, append OLD and ')
j.write('last access time\n')
j.write('if [ -d $results ]; then\n')
j.write(
' mv $results "$results"_OLD_$(date -r $results "+%Y-%m-%d-%H-%M-%S")\n') # noqa
j.write('fi\n\n')
j.write('cd $localscratch\n')
j.write(
'if compgen -G "$localscratch/*.res.Gradients" > /dev/null; then\n'
' rsync -aP --exclude=*.tmp* $localscratch/*.res.Gradients $results\n' # noqa
'fi\n'
)
j.write(
'if compgen -G "$localscratch/*.res.Dipoles" > /dev/null; then\n'
' rsync -aP --exclude=*.tmp* $localscratch/*.res.Dipoles $results\n'
'fi\n'
)
j.write(
'if compgen -G "$localscratch/*.res.Ramans" > /dev/null; then\n'
' rsync -aP --exclude=*.tmp* $localscratch/*.res.Ramans $results\n'
'fi\n'
)
j.write(
'if compgen -G "$localscratch/*.res.Nacmes" > /dev/null; then\n'
' rsync -aP --exclude=*.tmp* $localscratch/*.res.Nacmes $results\n'
'fi\n'
)
j.write('rsync -aP --exclude=*.tmp* $localscratch/* $results\n')
j.write('rm -r $localscratch\n')
if verbose:
if os.path.split(job_file)[0] == os.getcwd():
pp_jf = os.path.split(job_file)[1]
else:
pp_jf = job_file
ut.cprint(f'Submission script written to {pp_jf}', 'green')
return job_file
def parse_input_contents(input_file: str, max_mem: int,
max_cores: int) -> dict[str, str]:
'''
Checks contents of input file and returns file dependencies
Specifically, checks:
If maxcore (memory) specified is appropriate
Parameters
----------
input_file : str
Full path to orca input file
max_mem : int
Max memory (MB) total on node
max_cores : int
Maximum number of cores on node
Returns
-------
dict[str, str]
Names of relative-path dependencies (files) which this input needs
key is identifier (xyz, gbw), value is file name
'''
# Found memory and cores
mem_found = False
core_found = False
# MO Sections
mo_read = False
mo_inp = False
# Dependencies (files) of this input file
# as full paths
dependencies = dict()
# Path of input file
inpath = os.path.split(input_file)[0]
# head of input file
inhead = os.path.split(os.path.splitext(input_file)[0])[1]
# If input file is in cwd then no need to print massive path for errors
if inpath == os.getcwd():
e_input_file = os.path.split(input_file)[1]
else:
e_input_file = input_file
with open(input_file, 'r') as f:
for line in f:
# xyz file
if 'xyzfile' in line.lower() and '!' not in line:
if len(line.split()) != 5 and line.split()[0] != '*xyzfile':
ut.red_exit(
f'Incorrect xyzfile definition in {e_input_file}'
)
if len(line.split()) != 4 and line.split()[0] != '*':
ut.red_exit(
f'Incorrect xyzfile definition in {e_input_file}'
)
xyzfile = line.split()[-1]
# Check if contains path info, if so error
if os.sep in xyzfile:
ut.red_exit(
f'Path provided for xyz file in {e_input_file}'
)
dependencies['xyz'] = xyzfile
# gbw file
if '%moinp' in line.lower():
mo_inp = True
if len(line.split()) != 2:
ut.red_exit(
f'Incorrect gbw file definition in {e_input_file}'
)
if abs(line.count('"') - line.count("'")) != 2:
ut.red_exit(
f'Missing quotes around gbw file name in {e_input_file}' # noqa
)
gbw_file = line.split()[-1].replace('"', '').replace("'", "")
# Check if contains path info, if so error
if os.sep in gbw_file:
ut.red_exit(
f'Path provided for gbw file in {e_input_file}'
)
dependencies['gbw'] = gbw_file
# Check gbw doesnt have same name as input
if os.path.splitext(gbw_file)[0] == inhead:
ut.red_exit(
f'gbw file in {e_input_file} has same name as input'
)
if 'moread' in line.lower():
mo_read = True
# Per core memory
if '%maxcore' in line.lower():
mem_found = True
if len(line.split()) != 2:
ut.red_exit(
f'Incorrect %maxcore definition in {e_input_file}'
)
try:
n_mb = int(line.split()[-1])
except ValueError:
ut.red_exit(
f'Cannot parse per core memory in {e_input_file}'
)
# Number of cores
if 'pal nprocs' in line.lower():
n_cores = int(line.split()[2])
core_found = True
if n_cores > max_cores:
string = 'Error: Specified number of cores'
string += f' {n_cores:d} in {input_file} exceeds '
string += f'node limit of {max_cores:d} cores'
ut.red_exit(string)
if mo_inp ^ mo_read:
ut.red_exit(
f'Only one of moread and %moinp specified in {e_input_file}'
)
if not mem_found:
ut.red_exit(f'Cannot locate %maxcore definition in {e_input_file}')
if not core_found:
ut.red_exit(f"Cannot locate %maxcore definition in {input_file}")
# Check memory doesnt exceed per-core limit
if n_mb > max_mem / n_cores:
string = 'Warning! Specified per core memory of'
string += f' {n_mb:d} MB in {input_file} exceeds'
string += ' node limit of {:.2f} MB'.format(max_mem / n_cores)
ut.cprint(string, 'black_yellowbg')
return dependencies
def locate_dependencies(files: dict[str, str],
input_file: str) -> dict[str, str]:
'''
Locates each dependency in either input directory or results directory
Parameters
----------
files: dict[str, str]
Keys are filetype e.g. xyz, gbw
Values are name file (no path information)
input_file: str
Full path of input file
Returns
-------
dict[str, str]
Absolute path to each dependency
'''
results_name = ut.gen_results_name(input_file)
in_path = os.path.split(input_file)[0]
dependency_paths = {}
for file_type, file_name in files.items():
if 'extra' not in file_type:
# Potential path of current file if in input directory
curr = os.path.join(in_path, file_name)
# Potential path of current file if in results directory
res = os.path.join(in_path, results_name, file_name)
# gbw check both currdir/results_name and then currdir
if file_type == 'gbw':
if os.path.exists(res):
dependency_paths[file_type] = os.path.abspath(res)
elif os.path.exists(curr):
dependency_paths[file_type] = os.path.abspath(curr)
else:
ut.red_exit(
f'{file_type} file specified in {input_file} cannot be found' # noqa
)
# Extra dependencies
elif file_type == 'extra':
dependency_paths['extra'] = []
# Value is list
for ed in file_name:
# Check for * wildcard and expand if neccessary
if '*' in ed:
found = glob(ed)
else:
found = [ed]
dependency_paths['extra'] += [
os.path.abspath(fo) for fo in found
]
else:
if os.path.exists(curr):
dependency_paths[file_type] = os.path.abspath(curr)
else:
ut.red_exit(
f'{file_type} file specified in {input_file} cannot be found' # noqa
)
return dependency_paths
def add_core_to_input(input_file: str, n_cores: int) -> None:
'''
Adds number of cores (NPROCS) definition to specified input file
Parameters
----------
input_file : str
Name of orca input file
n_cores : int
Number of cores to specify
Returns
-------
None
'''
found = False
new_file = f'{input_file}_tmp'
with open(input_file, 'r') as fold:
with open(new_file, 'w') as fnew:
# Find line if already exists
for oline in fold:
# Number of cores
if 'pal nprocs' in oline.lower():
fnew.write(f'%PAL NPROCS {n_cores:d} END\n')
found = True
else:
fnew.write('{}'.format(oline))
# Add if missing
if not found:
fnew.write('\n%PAL NPROCS {n_cores:d} END\n')
subprocess.call('mv {} {}'.format(new_file, input_file), shell=True)
return | PypiClean |
/Mathics_Django-6.0.0-py3-none-any.whl/mathics_django/web/media/js/mathjax/jax/output/HTML-CSS/fonts/Neo-Euler/Fraktur/Regular/Main.js | MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.NeoEulerMathJax_Fraktur={directory:"Fraktur/Regular",family:"NeoEulerMathJax_Fraktur",testString:"\u00A0\u210C\u2128\u212D\uD835\uDD04\uD835\uDD05\uD835\uDD07\uD835\uDD08\uD835\uDD09\uD835\uDD0A\uD835\uDD0D\uD835\uDD0E\uD835\uDD0F\uD835\uDD10\uD835\uDD11",32:[0,0,333,0,0],160:[0,0,333,0,0],8460:[667,133,720,-8,645],8488:[729,139,602,11,533],8493:[686,24,612,59,613],120068:[697,27,717,22,709],120069:[691,27,904,49,815],120071:[690,27,831,27,746],120072:[686,24,662,86,641],120073:[686,155,611,11,621],120074:[692,25,785,66,711],120077:[686,139,552,-18,522],120078:[681,27,668,16,690],120079:[686,27,666,32,645],120080:[692,27,1049,27,1049],120081:[686,29,832,29,830],120082:[729,27,828,11,746],120083:[692,219,823,6,804],120084:[729,69,828,11,783],120086:[689,27,828,56,756],120087:[703,27,669,24,676],120088:[697,27,645,-26,666],120089:[686,27,831,29,826],120090:[686,28,1046,21,1055],120091:[689,27,719,27,709],120092:[686,219,834,26,741],120094:[471,36,500,65,497],120095:[686,31,513,86,444],120096:[466,29,389,72,359],120097:[612,34,498,13,430],120098:[467,31,400,70,364],120099:[679,238,329,30,324],120100:[470,209,503,16,455],120101:[689,198,521,76,435],120102:[675,21,279,14,268],120103:[673,202,280,-9,196],120104:[686,26,389,24,363],120105:[686,20,279,97,277],120106:[475,26,766,7,757],120107:[475,23,526,18,521],120108:[481,28,488,66,413],120109:[538,214,500,12,430],120110:[480,224,489,59,418],120111:[474,21,389,15,395],120112:[479,30,442,-28,407],120113:[641,21,333,26,349],120114:[474,26,517,8,514],120115:[533,28,511,51,439],120116:[533,28,773,44,693],120117:[473,188,388,10,370],120118:[524,219,498,45,437],120119:[471,215,390,-7,314],120172:[688,31,847,29,827],120173:[685,31,1043,56,963],120174:[677,32,723,71,729],120175:[685,29,981,30,896],120176:[687,29,782,73,733],120177:[684,147,721,17,734],120178:[692,27,927,74,844],120179:[684,127,850,0,753],120180:[683,25,654,31,623],120181:[681,142,652,-8,615],120182:[682,26,789,20,813],120183:[684,28,786,30,764],120184:[686,33,1239,26,1232],120185:[681,33,982,26,968],120186:[726,29,976,11,881],120187:[685,223,977,19,944],120188:[726,82,976,11,917],120189:[689,29,977,19,977],120190:[685,31,978,82,906],120191:[691,30,789,30,798],120192:[689,39,850,16,871],120193:[687,29,981,25,966],120194:[682,30,1235,31,1240],120195:[682,35,849,32,835],120196:[689,214,983,32,879],120197:[718,137,726,17,633],120198:[472,32,602,80,587],120199:[691,32,589,86,504],120200:[473,26,463,87,424],120201:[632,29,588,-1,511],120202:[471,28,471,80,429],120203:[681,242,387,37,387],120204:[473,208,594,16,541],120205:[687,203,615,88,507],120206:[686,26,331,2,327],120207:[683,207,331,-19,238],120208:[683,25,464,33,432],120209:[682,24,336,100,315],120210:[476,31,921,16,900],120211:[474,28,653,3,608],120212:[482,34,609,107,515],120213:[558,208,603,-2,519],120214:[485,212,595,87,515],120215:[473,26,459,12,453],120216:[480,35,522,-24,482],120217:[654,27,393,47,407],120218:[473,35,588,9,604],120219:[546,28,604,56,507],120220:[549,33,917,55,815],120221:[471,188,458,8,449],120222:[559,222,589,60,515],120223:[472,215,461,-8,377]};MathJax.Callback.Queue(["initFont",MathJax.OutputJax["HTML-CSS"],"NeoEulerMathJax_Fraktur"],["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Fraktur/Regular/Main.js"]); | PypiClean |
/MAVR-0.93.tar.gz/MAVR-0.93/scripts/draw/draw_plot.py | __author__ = 'Sergei F. Kliver'
import argparse
import numpy as np
import scipy.stats as stats
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.ioff()
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input_file", action="store", dest="input_file",
help="Input file with data")
parser.add_argument("-o", "--output_prefix", action="store", dest="output_prefix",
help="Prefix of output files")
parser.add_argument("-s", "--separator", action="store", dest="separator", default="\t",
help="Separator between values in input file. Default - '\\t' ")
parser.add_argument("-a", "--x_column_index", action="store", dest="x_column_index", type=int,
help="Index of column with x values. 0-based")
parser.add_argument("-b", "--y_column_index", action="store", dest="y_column_index", type=int,
help="Index of column with y values. 0-based")
parser.add_argument("-n", "--min_x", action="store", dest="min_x", type=float,
help="Minimum x value to show. Default - not set")
parser.add_argument("-x", "--max_x", action="store", dest="max_x", type=float,
help="Maximum x value to show. Default - not set")
parser.add_argument("-q", "--min_y", action="store", dest="min_y", type=float,
help="Minimum y value to show. Default - not set")
parser.add_argument("-r", "--max_y", action="store", dest="max_y", type=float,
help="Maximum y value to show. Default - not set")
parser.add_argument("-e", "--extensions", action="store", dest="extensions", type=lambda x: x.split(","),
default=["png", "svg"],
help="Comma-separated list of extensions for histogram files")
parser.add_argument("-l", "--xlabel", action="store", dest="xlabel",
help="X label")
parser.add_argument("-y", "--ylabel", action="store", dest="ylabel",
help="Y label")
parser.add_argument("-t", "--title", action="store", dest="title",
help="Title of histogram")
parser.add_argument("--width", action="store", dest="width", default=6, type=int,
help="Figure width. Default: 6")
parser.add_argument("--height", action="store", dest="height", default=6, type=int,
help="Figure height. Default: 6")
parser.add_argument("-m", "--markersize", action="store", dest="markersize", default=2, type=int,
help="Size of marker. Default: 2")
parser.add_argument("--ylog", action="store", dest="ylogbase", default=10, type=int,
help="Log base for figure with logarithmic scale on y axis. Default: 10")
parser.add_argument("--type", action="store", dest="type", default="plot",
help="Type of figure. Allowed: plot(default), scatter")
parser.add_argument("-g", "--grid", action="store_true", dest="grid",
help="Show grid. Default: False")
args = parser.parse_args()
data = np.loadtxt(args.input_file, comments="#", usecols=(args.x_column_index, args.y_column_index))
plt.figure(1, figsize=(args.width, args.height), dpi=300)
plt.subplot(1, 1, 1)
if args.type == "plot":
plt.plot(data[:, 0], data[:, 1], markersize=args.markersize)
elif args.type == "scatter":
plt.scatter(data[:, 0], data[:, 1], s=args.markersize)
plt.xlim(xmin=args.min_x, xmax=args.max_x)
plt.ylim(ymin=args.min_y, ymax=args.max_y)
if args.xlabel:
plt.xlabel(args.xlabel)
if args.ylabel:
plt.ylabel(args.ylabel)
if args.title:
plt.title(args.title)
if args.grid:
plt.grid()
print("Kendal's tau")
print(stats.kendalltau(data[:, 0], data[:, 1]))
print("Pearson's r")
print(stats.pearsonr(data[:, 0], data[:, 1]))
for ext in args.extensions:
plt.savefig("%s.%s.%s" % (args.output_prefix, args.type, ext))
plt.yscale("log")
for ext in args.extensions:
plt.savefig("%s.%s.ylog%i.%s" % (args.output_prefix, args.type, args.ylogbase, ext)) | PypiClean |
/Bis-Miner-3.11.1.tar.gz/Bis-Miner-3.11.0/Orange/canvas/gui/tooltree.py | import logging
from AnyQt.QtWidgets import (
QTreeView, QWidget, QVBoxLayout, QSizePolicy, QStyledItemDelegate,
QStyle, QAction
)
from AnyQt.QtGui import QStandardItemModel
from AnyQt.QtCore import Qt, QEvent, QModelIndex, QAbstractProxyModel
from AnyQt.QtCore import pyqtSignal as Signal
log = logging.getLogger(__name__)
class ToolTree(QWidget):
"""
A ListView like presentation of a list of actions.
"""
triggered = Signal(QAction)
hovered = Signal(QAction)
def __init__(self, parent=None, **kwargs):
QTreeView.__init__(self, parent, **kwargs)
self.setSizePolicy(QSizePolicy.MinimumExpanding,
QSizePolicy.Expanding)
self.__model = QStandardItemModel()
self.__flattened = False
self.__actionRole = Qt.UserRole
self.__view = None
self.__setupUi()
def __setupUi(self):
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
view = QTreeView(objectName="tool-tree-view")
view.setUniformRowHeights(True)
view.setFrameStyle(QTreeView.NoFrame)
view.setModel(self.__model)
view.setRootIsDecorated(False)
view.setHeaderHidden(True)
view.setItemsExpandable(True)
view.setEditTriggers(QTreeView.NoEditTriggers)
view.setItemDelegate(ToolTreeItemDelegate(self))
view.activated.connect(self.__onActivated)
view.clicked.connect(self.__onActivated)
view.entered.connect(self.__onEntered)
view.installEventFilter(self)
self.__view = view
layout.addWidget(view)
self.setLayout(layout)
def setFlattened(self, flatten):
"""
Show the actions in a flattened view.
"""
if self.__flattened != flatten:
self.__flattened = flatten
if flatten:
model = FlattenedTreeItemModel()
model.setSourceModel(self.__model)
else:
model = self.__model
self.__view.setModel(model)
def flattened(self):
"""
Are actions shown in a flattened tree (a list).
"""
return self.__flattened
def setModel(self, model):
if self.__model is not model:
self.__model = model
if self.__flattened:
model = FlattenedTreeItemModel()
model.setSourceModel(self.__model)
self.__view.setModel(model)
def model(self):
return self.__model
def setRootIndex(self, index):
"""Set the root index
"""
self.__view.setRootIndex(index)
def rootIndex(self):
"""Return the root index.
"""
return self.__view.rootIndex()
def view(self):
"""Return the QTreeView instance used.
"""
return self.__view
def setActionRole(self, role):
"""Set the action role. By default this is UserRole
"""
self.__actionRole = role
def actionRole(self):
return self.__actionRole
def __actionForIndex(self, index):
val = index.data(self.__actionRole)
if val is not None:
action = val
if isinstance(action, QAction):
return action
else:
log.debug("index does not have an QAction")
else:
log.debug("index does not have a value for action role")
def __onActivated(self, index):
"""The item was activated, if index has an action we
need to trigger it.
"""
if index.isValid():
action = self.__actionForIndex(index)
if action is not None:
action.trigger()
self.triggered.emit(action)
def __onEntered(self, index):
if index.isValid():
action = self.__actionForIndex(index)
if action is not None:
action.hover()
self.hovered.emit(action)
def ensureCurrent(self):
"""Ensure the view has a current item if one is available.
"""
model = self.__view.model()
curr = self.__view.currentIndex()
if not curr.isValid():
for i in range(model.rowCount()):
index = model.index(i, 0)
if index.flags() & Qt.ItemIsEnabled:
self.__view.setCurrentIndex(index)
break
def eventFilter(self, obj, event):
if obj is self.__view and event.type() == QEvent.KeyPress:
key = event.key()
space_activates = \
self.style().styleHint(
QStyle.SH_Menu_SpaceActivatesItem,
None, None)
if key in [Qt.Key_Enter, Qt.Key_Return, Qt.Key_Select] or \
(key == Qt.Key_Space and space_activates):
index = self.__view.currentIndex()
if index.isValid() and index.flags() & Qt.ItemIsEnabled:
# Emit activated on behalf of QTreeView.
self.__view.activated.emit(index)
return True
return QWidget.eventFilter(self, obj, event)
class ToolTreeItemDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
QStyledItemDelegate.paint(self, painter, option, index)
class FlattenedTreeItemModel(QAbstractProxyModel):
"""An Proxy Item model containing a flattened view of a column in a tree
like item model.
"""
Default = 1
InternalNodesDisabled = 2
LeavesOnly = 4
def __init__(self, parent=None):
QAbstractProxyModel.__init__(self, parent)
self.__sourceColumn = 0
self.__flatteningMode = 1
self.__sourceRootIndex = QModelIndex()
def setSourceModel(self, model):
self.beginResetModel()
curr_model = self.sourceModel()
if curr_model is not None:
curr_model.dataChanged.disconnect(self._sourceDataChanged)
curr_model.rowsInserted.disconnect(self._sourceRowsInserted)
curr_model.rowsRemoved.disconnect(self._sourceRowsRemoved)
curr_model.rowsMoved.disconnect(self._sourceRowsMoved)
QAbstractProxyModel.setSourceModel(self, model)
self._updateRowMapping()
model.dataChanged.connect(self._sourceDataChanged)
model.rowsInserted.connect(self._sourceRowsInserted)
model.rowsRemoved.connect(self._sourceRowsRemoved)
model.rowsMoved.connect(self._sourceRowsMoved)
self.endResetModel()
def setSourceColumn(self, column):
raise NotImplementedError
self.beginResetModel()
self.__sourceColumn = column
self._updateRowMapping()
self.endResetModel()
def sourceColumn(self):
return self.__sourceColumn
def setSourceRootIndex(self, rootIndex):
"""Set the source root index.
"""
self.beginResetModel()
self.__sourceRootIndex = rootIndex
self._updateRowMapping()
self.endResetModel()
def sourceRootIndex(self):
"""Return the source root index.
"""
return self.__sourceRootIndex
def setFlatteningMode(self, mode):
"""Set the flattening mode.
"""
if mode != self.__flatteningMode:
self.beginResetModel()
self.__flatteningMode = mode
self._updateRowMapping()
self.endResetModel()
def flatteningMode(self):
"""Return the flattening mode.
"""
return self.__flatteningMode
def mapFromSource(self, sourceIndex):
if sourceIndex.isValid():
key = self._indexKey(sourceIndex)
offset = self._source_offset[key]
row = offset + sourceIndex.row()
return self.index(row, 0)
else:
return sourceIndex
def mapToSource(self, index):
if index.isValid():
row = index.row()
source_key_path = self._source_key[row]
return self._indexFromKey(source_key_path)
else:
return index
def index(self, row, column=0, parent=QModelIndex()):
if not parent.isValid():
return self.createIndex(row, column, object=row)
else:
return QModelIndex()
def parent(self, child):
return QModelIndex()
def rowCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
else:
return len(self._source_key)
def columnCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
else:
return 1
def flags(self, index):
flags = QAbstractProxyModel.flags(self, index)
if self.__flatteningMode == self.InternalNodesDisabled:
sourceIndex = self.mapToSource(index)
sourceModel = self.sourceModel()
if sourceModel.rowCount(sourceIndex) > 0 and \
flags & Qt.ItemIsEnabled:
# Internal node, enabled in the source model, disable it
flags ^= Qt.ItemIsEnabled
return flags
def _indexKey(self, index):
"""Return a key for `index` from the source model into
the _source_offset map. The key is a tuple of row indices on
the path from the top if the model to the `index`.
"""
key_path = []
parent = index
while parent.isValid():
key_path.append(parent.row())
parent = parent.parent()
return tuple(reversed(key_path))
def _indexFromKey(self, key_path):
"""Return an source QModelIndex for the given key.
"""
index = self.sourceModel().index(key_path[0], 0)
for row in key_path[1:]:
index = index.child(row, 0)
return index
def _updateRowMapping(self):
source = self.sourceModel()
source_key = []
source_offset_map = {}
def create_mapping(index, key_path):
if source.rowCount(index) > 0:
if self.__flatteningMode != self.LeavesOnly:
source_offset_map[key_path] = len(source_offset_map)
source_key.append(key_path)
for i in range(source.rowCount(index)):
create_mapping(index.child(i, 0), key_path + (i, ))
else:
source_offset_map[key_path] = len(source_offset_map)
source_key.append(key_path)
for i in range(source.rowCount()):
create_mapping(source.index(i, 0), (i,))
self._source_key = source_key
self._source_offset = source_offset_map
def _sourceDataChanged(self, top, bottom):
changed_indexes = []
for i in range(top.row(), bottom.row() + 1):
source_ind = top.sibling(i, 0)
changed_indexes.append(source_ind)
for ind in changed_indexes:
self.dataChanged.emit(ind, ind)
def _sourceRowsInserted(self, parent, start, end):
self.beginResetModel()
self._updateRowMapping()
self.endResetModel()
def _sourceRowsRemoved(self, parent, start, end):
self.beginResetModel()
self._updateRowMapping()
self.endResetModel()
def _sourceRowsMoved(self, sourceParent, sourceStart, sourceEnd,
destParent, destRow):
self.beginResetModel()
self._updateRowMapping()
self.endResetModel() | PypiClean |
/Data_Generator-1.0.1-py3-none-any.whl/data_generator/output.py | import csv
import json
from datetime import datetime as dt
from os import makedirs
from os.path import isdir, join
# pyre-ignore
from tqdm import tqdm
# pyre-ignore
from xlsxwriter import Workbook
def _check_dir(dirpath: str) -> None:
"""Checks for <dirpath> existence and creates it recursively, if not found.
Arguments:
dirpath -- path to directory
"""
if not isdir(dirpath):
makedirs(dirpath, exist_ok=True)
def to_csv(data: dict, rows_count: int, output_folder: str) -> None:
"""Saves generated data into .csv file.
Arguments:
data -- converted CLI args as dict
rows_count -- number of rows generated excluding header
output_folder -- folder to save generated .csv file into
"""
headers = list(data.keys())
timestamp = dt.now().strftime("%Y%m%d_%H%M%S")
filename = f"data_{timestamp}.csv"
filepath = join(output_folder, filename)
_check_dir(output_folder)
with open(filepath, mode="w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
for _ in tqdm(range(rows_count)):
row = {}
for header, data_generator in list(data.items()):
# key will never be there, dict is empty for each cycle
if header not in row:
row[header] = next(data_generator)
writer.writerow(row)
def to_json(data: dict, rows_count: int, output_folder: str) -> None:
"""Saves generated data into .json file.
Arguments:
data {dict} -- converted CLI args as dict
rows_count {int} -- number of rows generated excluding "header"
output_folder {str} -- folder to save generated .json file into
"""
timestamp = dt.now().strftime("%Y%m%d_%H%M%S")
filename = f"data_{timestamp}.json"
filepath = join(output_folder, filename)
_check_dir(output_folder)
output = {}
for _ in tqdm(range(rows_count)):
for header, data_generator in list(data.items()):
if header not in output:
output[header] = []
output[header].append(next(data_generator))
with open(filepath, mode="w", encoding="utf-8") as f:
json.dump(output, f, ensure_ascii=False, indent=2)
def to_excel(data: dict, rows_count: int, output_folder: str) -> None:
"""Saves generated data into .xlsx file.
Arguments:
data {dict} -- converted CLI args as dict
rows_count {int} -- number of rows generated excluding "header"
output_folder {str} -- folder to save generated .xlsx file into
"""
timestamp = dt.now().strftime("%Y%m%d_%H%M%S")
filename = f"data_{timestamp}.xlsx"
filepath = join(output_folder, filename)
_check_dir(output_folder)
workbook = Workbook(filepath, {"constant_memory": True})
sheet = workbook.add_worksheet()
for col, header in enumerate(list(data.keys())):
sheet.write(0, col, header)
for row in tqdm(range(1, rows_count + 1)):
for col, data_generator in enumerate(list(data.values())):
sheet.write(row, col, next(data_generator))
workbook.close() | PypiClean |
/DataExpress-0.0.2.tar.gz/DataExpress-0.0.2/Extract.py | import DE_LibUtil as U
import DE_DataBase as D
import DE_LogEventos as L
import DE_Parametros as P
import DE_Gera_Arquivos as G
import inspect
import os
import socket as sk
import datetime as dt
import json
import pandas as pd
import requests
lib = U.LIB()
db = D.DATABASE()
par = P.PARAMETROS()
class EXTRACAO:
class_name = inspect.stack()[0].function
log, logger = None, None
def __init__(self, **kwargs):
msglog, loginfo = None, None
self._PID = lib.getPID()
self._dthr_inicio_processo = dt.datetime.now()
try:
method_name = inspect.stack()[0].function
# Analizando parametros recebidos
if "nom_processo" in kwargs.keys():
if "des_processo" not in kwargs.keys():
kwargs["des_processo"] = f"""Descritivo do processo não definido na inicialização da classe {self._class_name}, PID={self.PID}"""
self._PROCESSO = []
self._PROCESSO.append(kwargs["nom_processo"])
self._PROCESSO.append(kwargs["des_processo"])
# Obtendo parametros para processamento
result = self._get_parametros()
if result is not None:
raise result
# criando um LOG para os eventos
self._set_LogEventos()
msglog = f"""Iniciando execucao do processo... [pid: {self._PID}]-{self._PROCESSO[0]}-{self._PROCESSO[1]}\n{log.Sublinhado}Lista de parametros utilizados para o processamento...\n{log.Italico}{json.dumps(self._PAR, indent=2)}"""
log.Popula(logger=logger, level=log.INFO, content=msglog, function_name=method_name, cor=log.Verde_Claro_Fore)
else:
raise Exception(f"""Falha ao instanciar a classe {self._class_name}, para o processo {self._PROCESSO[0]}-{self._PROCESSO[1]}""")
msglog = "Classe de extração instanciada, pronta para uso!"
loginfo = log.INFO
except Exception as error:
msglog = error
loginfo = log.ERROR
finally:
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name, cor=log.Verde_Claro_Fore)
def Execute(self):
global log, logger
msglog, loginfo, method_name, result = "Iniciando execução do processo...", log.INFO, inspect.stack()[0].function, True
try:
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name, cor=log.Amarelo_Claro_Fore)
self._arq = G.ARQUIVOS(**{"log":log, "logger":logger})
# Iniciando a extração
if self._PAR["ESTRATEGIA"]["origem_extracao"].upper() == "DATABASE":
self._cnnORIGEM = None
result = self._inicia_extracao_database()
if not isinstance(result, bool):
raise Exception(result)
elif self._PAR["ESTRATEGIA"]["origem_extracao"].upper() == "FILESYSTEM":
pass
elif self._PAR["ESTRATEGIA"]["origem_extracao"].upper() == "CLOUD":
pass
elif self._PAR["ESTRATEGIA"]["origem_extracao"].upper() == "URL":
pass
if result == False:
raise Exception()
#--------------------------------------------------------------------------
# Os tipos possiveis ate o momento para extração de dados são os seguintes:
# 1. Database
# 2. fileSystem
# 3. Cloud (GPC, AZURE, AWS)
# 4. HTML
# --------------------------------------------
msglog = f"""Processo: [{self._PID}-{self._PROCESSO[0]}] concluido com exito!"""
loginfo = log.INFO
cor = log.Amarelo_Claro_Fore
except Exception as error:
loginfo = log.ERROR
msglog = f"""ERRO==> [pid: {self._PID}]-{self._PROCESSO[0]}-{self._PROCESSO[1]} - {error}"""
result = False
cor = log.Vermelho_Claro_Fore
finally:
#dfPAR = pd.DataFrame.from_dict(data=self._PAR)
msg = ''
msgslack = self._onboarding_template_slack()
self.post_message_to_slack(text=msg, token=self._PAR["SLACK"]["token"], channel=self._PAR["SLACK"]["channel"], icon_emoji=self._PAR["SLACK"]["icon_emoji"], blocks=msgslack, username=self._PAR["SLACK"]["user_name"])
self._set_parametros()
self._close_connections()
msglog = f"""...Finalizando a execução do processo... {msglog}"""
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name, cor=cor)
log.Finaliza(logger)
return result
def _inicia_extracao_database(self):
where, delta, delta_segundos = None, None, None
msglog, loginfo, method_name, result, cor = None, None, inspect.stack()[0].function, True, log.Cyan_Fore
try:
log.Popula(logger=logger, level=log.INFO, content="Iniciando extracao...", function_name=method_name, cor=cor)
# 1. efetuar conexao com a origem
self._cnnORIGEM = self._conecta_origem(sgbd=self._PAR["CONEXAO"]["database"].upper(), str_conexao=self._PAR["CONEXAO"])
if isinstance(self._cnnORIGEM, str):
raise Exception(self._cnnORIGEM)
# 2. montar resumo do processamento para analise
# monta um resumo do processamento para posterior utilizacao
self._candidatas = self._set_resumo_processo()
if isinstance(self._candidatas, str):
raise Exception(self._candidatas)
# 3. Montar as queries (metadados ou sql) para extração com seus respectivos filtros
# Montas as querys para todos os objetos e popyla o dataframe com o conteudo a query
self._monta_querys(df=self._candidatas, conexao=self._cnnORIGEM)
# 4. Gerar arquivos (efetuar quebra por numero de linhas)
self._extracao_dados(df=self._candidatas)
msglog = f"""{cor}... Finalizando extracao!"""
loginfo = log.INFO
cor = log.Cyan_Fore
except Exception as error:
msglog = error
loginfo = log.ERROR
result = msglog
cor = log.Vermelho_Claro_Fore
finally:
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name, cor=cor)
return result
# 1. Conexão com a base de dados de ORIGEM
def _conecta_origem(self, sgbd: str, str_conexao: str):
msglog, loginfo, method_name, result = None, log.INFO, inspect.stack()[0].function, None
try:
msglog = f"""Conectando com a base de ORIGEM: {self._PAR["CONEXAO"]["database"].upper()} - {self._PROCESSO[0]}!"""
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name, lf=False, cor=log.Azul_Fore)
# 1. efetuar conexao com a origem
if sgbd.upper() == "ORACLE":
#self._cnnORIGEM = db.ORACLE(self._PAR["CONEXAO"])
conexao = db.ORACLE(str_conexao)
elif sgbd.upper() == "MYSQL":
pass
elif sgbd.upper() == "EXADATA":
pass
elif sgbd.upper() == "POSTGRES":
pass
elif sgbd.upper() == "AZURE":
pass
elif sgbd.upper() == "REDSHIFT":
pass
elif sgbd.upper() == "MSSQL":
pass
elif sgbd.upper() == "SQLITE":
pass
if isinstance(conexao, str):
msglog = f"""Falha ao tentar conexão com a origem dos dados!"""
raise Exception(msglog)
msglog = f"""Conexao com a base de ORIGEM estabelecida!"""
loginfo = log.INFO
result = conexao
except Exception as error:
msglog = error
loginfo = log.ERROR
result = msglog
finally:
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name)
return result
# 2. montar resumo do processamento para analise
# monta um resumo do processamento para posterior utilizacao
def _set_resumo_processo(self):
result, method_name, msglog, loginfo, cor = None, inspect.stack()[0].function, None, log.INFO, log.Azul_Fore
try:
log.Popula(logger=logger, level=log.INFO, content="Montando dataframe com os objetos candidatos e resumo do processo...", function_name=method_name, lf=False, cor=cor)
df = pd.DataFrame(self._PAR["OBJETOS"])
df["ext_dh_inicio"] = None
df["ext_dh_fim"] = None
df["ext_tempo"] = None
df["ext_linhas_lidas"] = 0
df["ext_stmt"] = None
df["ext_file_size"] = None
df["ext_file_qtd"] = None
result = df
loginfo = log.INFO
msglog = f"""Resumo do processo montado!"""
except Exception as error:
loginfo = log.ERROR
msglog = error
result = msglog
finally:
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name)
return result
# 3. Montar as queries (metadados ou sql) para extração com seus respectivos filtros
# Monta as querys para todos os objetos e popyla o dataframe com o conteudo a query
def _monta_querys(self, df, conexao):
msglog, loginfo, method_name, cor = None, None, inspect.stack()[0].function, log.Branco_Fore
try:
msglog = f"""Montando query´s para execução..."""
log.Popula(logger=logger, level=log.INFO, content=msglog, function_name=method_name, cor=cor)
for key in self._PAR["OBJETOS"]:
if key["flg_processa"] == "S":
if key["estrategia"]["flg_tipo_carga"].upper() == 'INCREMENTAL':
if key["estrategia"]["data_type"].upper() in ["DATE", "DATETIME"]:
if key["estrategia"]["delta_range_type"] == 'segundos':
delta_segundos = 1
if key["estrategia"]["delta_range_type"] == 'minutos':
delta_segundos = 60
if key["estrategia"]["delta_range_type"] == 'horas':
delta_segundos = (60 * 60)
if key["estrategia"]["delta_range_type"] == 'dias': # dias, semana, dezena, quinzena, mes, ano
delta_segundos = (60 * 60 * 24)
delta_inicial = dt.datetime.strptime(key["estrategia"]["ultimo_delta"], key["estrategia"]["formato"]) + dt.timedelta(
seconds=1)
delta_final = delta_inicial + (dt.timedelta(seconds=key["estrategia"]["delta_range"]) * delta_segundos) - dt.timedelta(
seconds=1)
where = f"""where {key["estrategia"]["nom_coluna"]} between TO_DATE('{delta_inicial}', 'YYYY-MM-DD HH24:MI:SS') and TO_DATE('{delta_final}', 'YYYY-MM-DD HH24:MI:SS')"""
elif key["estrategia"]["data_type"].upper() == "NUMBER":
delta_inicial = key["estrategia"]["ultimo_delta"] + 1
x = key["estrategia"]["delta_range"]
if x is None:
delta_final = 99999999999999
else:
delta_final = delta_inicial + key["estrategia"]["delta_range"]
where = f"""where {key["estrategia"]["nom_coluna"]} between {delta_inicial} and {delta_final}"""
else:
pass
elif key["flg_tipo_carga"].upper() == 'HISTORICA':
pass
msglog = f"""\t\t{key["nome_tabela"]}"""
log.Popula(logger=logger, level=log.INFO, content=msglog, function_name=method_name, lf=False, cor=log.Cinza_Claro_Fore)
md = db.METADATA(conexao=conexao,
database=self._PAR["CONEXAO"]["database"].upper(),
nome_tabela=key["nome_tabela"],
owner=key["owner"].upper(),
where=where
)
msglog = f"""\n{md}\n Query montada!"""
log.Popula(logger=logger, level=log.INFO, content=msglog, function_name=method_name, cor=log.Cinza_Escuro_Fore)
df.loc[df["nome_tabela"] == key["nome_tabela"], "ext_stmt"] = md
msglog = f"""Query´s montadas com sucesso!"""
loginfo = log.INFO
cor = log.Branco_Fore
except Exception as error:
msglog = error
loginfo = log.ERROR
cor = log.Vermelho_Claro_Fore
finally:
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name, cor=cor)
# 4. gerar arquivos (efetuar quebra por numero de linhas)
def _extracao_dados(self, df):
msglog, loginfo, method_name, cor = None, None, inspect.stack()[0].function, log.Magenta_Claro_Fore
try:
log.Popula(logger=logger, level=log.INFO, content="Extraindo dados e gerando arquivos...", function_name=method_name, cor=cor)
for index, value in df.iterrows():
msglog = f"""\t{index} - {df.loc[index,"nome_tabela"]}"""
log.Popula(logger=logger, level=log.INFO, content=msglog, function_name=method_name, cor=log.Branco_Fore)
now = dt.datetime.now()
df.loc[index, "ext_dh_inicio"] = str(now)
stmt = df.loc[index]["ext_stmt"]
cur = self._cnnORIGEM.cursor()
cur.execute(stmt)
header = lib.colunas_cursor(cur)
filenumber = 0
lines_read = 0
while (True):
rows = cur.fetchmany(self._PAR["ESTRATEGIA"]["lines_fetch"])
if len(rows) == 0:
break
dfExtracao = pd.DataFrame(data=rows, columns=header)
filenumber = filenumber + 1
lines_read = lines_read + len(dfExtracao)
if len(dfExtracao) > 0:
df.loc[index, "ext_linhas_lidas"] = df.loc[index, "ext_linhas_lidas"] + len(dfExtracao)
# 5.1 - gera os arquivos baseado na extração (1 arquivo para cada paginação: self._PAR["ESTRATEGIA"]["lote"]["lines_page"]
file = df.loc[index, "export_file"]
status = []
for filetype in file["extencao"]:
# geracao dos arquivos retorna um dict:
# status = {"filename": full_filename, "size": size, "ext_inicio": str(ext_inicio), "ext_termino": str(ext_termino),
# "ext_tempo": str(ext_tempo), "msg": msg}
nome_tabela = df.loc[index, "nome_tabela"]
file_name = f"""{self._PROCESSO[0]}_LOTE{self._numero_proximo_lote:07}_{nome_tabela}_{filenumber:04}_{dt.datetime.now().strftime("%Y%m%d%H%M%S")}"""
file_path = os.path.join(self._PAR["root"], self._PAR["PATH"]["tgt_files"])
if "CSV" in filetype.upper():
file = self._arq.CSV(df=dfExtracao, file_path=file_path, file_name=file_name, file_sufix='', decimal=file["separador_decimal"], sep=file["delimitador_campos"], quotechar=file["quotedchar"], index=False)
status.append(file)
if "TXT" in filetype.upper():
file_path = file_path + "." + filetype
if "JSON" in filetype.upper():
file_path = file_path + "." + filetype
if "XLSX" in filetype.upper():
file_path = file_path + "." + filetype
if "PARQUET" in filetype.upper():
file_path = file_path + "." + filetype
cur.close()
msglog = f"""{log.Cinza_Escuro_Fore}Arquivos gerados: {filenumber}, Linhas lidas: {lines_read}"""
log.Popula(logger=logger, level=log.INFO, content=msglog, function_name=method_name)
df.loc[index, "ext_file_qtd"] = str(filenumber)
df.loc[index, "ext_dh_fim"] = str(dt.datetime.now())
df.loc[index, "ext_tempo"] = str(dt.datetime.now() - now)
msglog = f"""Fim da extração e geração dos arquivos"""
loginfo = log.INFO
except Exception as error:
msglog = error
loginfo = log.ERROR
finally:
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name, cor=cor)
def _get_parametros(self):
result = None
method_name = inspect.stack()[0].function
try:
self._cnnPAR = db.SQLITE(database="c:\Projetos\db\DATAx.db")
if not db.CONNECTION_VALID:
msg = "Parametros para DATAx inexistentes!"
raise Exception(msg)
par = P.PARAMETROS(**{"conexao": self._cnnPAR, "table": "SYS_PAR"})
parDICT = par.APLICACAO_get(['GERAL', self._PROCESSO[0].upper()])
if isinstance(parDICT, str):
raise Exception(parDICT)
self._PAR = {}
for key in parDICT:
self._PAR[key["nom_variavel"]] = key["val_parametro"]
# Definindo o numero do proximo lote
self._numero_proximo_lote = int(self._PAR["ESTRATEGIA"]["lote"]["numero_ultimo_lote"]) + self._PAR["ESTRATEGIA"]["lote"]["incremento_lote"]
# Definindo o ROOT_DIR
if sk.gethostname() == self._PAR["HOST_APP"]:
self._PAR["root"] = self._PAR["PATH"]["root_server"]
else:
self._PAR["root"] = self._PAR["PATH"]["root_local"]
except Exception as error:
result = error
finally:
return result
def _set_parametros(self, status: str=None):
msglog, loginfo, method_name, cor = None, None, inspect.stack()[0].function, log.DESTAQUE
try:
log.Popula(logger=logger, level=log.INFO, content="Salvando parametros", function_name=method_name, cor=cor)
par = P.PARAMETROS(**{"conexao": self._cnnPAR, "table": "SYS_PAR"})
# Atualizando parametro de resumo do processo
inicio = self._dthr_inicio_processo
termino = dt.datetime.now()
resumo = self._PAR["RESUMO"]
resumo["ultimo_processamento"]["pid"] = self._PID
resumo["ultimo_processamento"]["dthr_inicio"] = str(inicio)
resumo["ultimo_processamento"]["dthr_fim"] = str(termino)
resumo["ultimo_processamento"]["tempo_ultima_execucao"] = str(termino - inicio)
resumo["ultimo_processamento"]["tempo_medio"] = dt.datetime.strftime((termino - inicio) + dt.datetime.strptime(resumo["ultimo_processamento"]["tempo_ultima_execucao"], "%H:%M:%S.%f"), "%H:%M:%S.%f")
resumo["ultimo_processamento"]["status"] = status
xdf = self._candidatas.loc[self._candidatas["flg_processa"] == "S", ["nome_tabela", "export_file", "ext_dh_inicio", "ext_dh_fim", "ext_tempo", "ext_linhas_lidas"]]
xdf.set_index("nome_tabela", inplace=True)
resumo["extracao"] = xdf.to_dict(orient="index")
par.PARAMETRO_set(nome_parametro=f"""{self._PROCESSO[0]}_RESUMO""", value=json.dumps(resumo, indent=4))
# Atualizando parametro de LOTE de processamento
lote = self._PAR["ESTRATEGIA"]["lote"]
lote["numero_ultimo_lote"] = str(self._numero_proximo_lote)
#lote["incremento_lote"] = lote["incremento_lote"]
par.PARAMETRO_set(nome_parametro=f"""{self._PROCESSO[0]}_LOTE""", value=json.dumps(lote, indent=2))
#lote["extracao"] = self._CANDIDATAS[""]
msglog = f"""Parametros salvos!"""
loginfo = log.INFO
except Exception as error:
msglog = error
loginfo = log.ERROR
finally:
log.Popula(logger=logger, level=loginfo, content=msglog, function_name=method_name)
def _set_LogEventos(self, **parametros):
global log, logger
result = None
method_name = inspect.stack()[0].function
try:
self._cnnLOG = db.SQLITE("c:\Projetos\db\LOG.db")
if isinstance(self._cnnLOG, object):
log_file = os.path.join(self._PAR['root'], self._PAR["PATH"]["log_files"], f"""{self._PROCESSO[0]}_LOG_LOTE{self._numero_proximo_lote:07}_{dt.datetime.now().strftime("%Y%m%d%H%M%S")}.json""")
self._PAR["LOG"]["nom_rotina"] = self._PROCESSO[0]
self._PAR["LOG"]["nom_subrotina"] = self.class_name
self._PAR["LOG"]["descricao"] = self._PROCESSO[1]
processo = {"nom_rotina": self._PROCESSO[0], # nome da rotina (obrigatorio)
"nom_subrotina": f"""{self.class_name}""", # nome da subrotina (opcional)
"descricao": self._PROCESSO[1], # descrição da rotina (HEADER do log)
"file": log_file,
"conexao_log": self._cnnLOG, # conexão com o banco de dados
"nome_tabela_log": "LOG", # nome da tabela de LOG (Header)
"nome_tabela_log_evento": "LOG_EVENT",
# nome da tabela onde serao gravados os eventos do log (a estrutura nao se pode mexer)
# "dataframe": pd, # objeto PANDAS
"device_out": ["screen", "file", "database"]
# ["screen", "database"|"memory", "file"]. Não permite utilizar "database" e "memory" simultaneamente
}
log = L.LOG(**processo)
logger = log.Inicializa()
else:
raise Exception("Problemas na conexão com o BD LOG")
except Exception as error:
result = error
finally:
return result
def _close_connections(self):
method_name = inspect.stack()[0].function
log.Popula(logger=logger, level=log.INFO, content="Fechando conexões", function_name=method_name)
self._cnnPAR.close()
self._cnnORIGEM.close()
# def modelo(self):
# result = None
# method_name = inspect.stack()[0].function
# try:
# pass
# except Exception as error:
# result = error
# finally:
# return result
def _onboarding_template_slack(self):
blocks = '''{
"type": "modal",
"title": {
"type": "plain_text",
"text": "My App",
"emoji": true
},
"submit": {
"type": "plain_text",
"text": "Submit",
"emoji": true
},
"close": {
"type": "plain_text",
"text": "Cancel",
"emoji": true
},
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Processo: ETL - CDPI/MULTIMAGEM\n• Inicio: 2022-08-19 23:45:55\n• Término: 2022-08-20 01:05:43"
}
},
{
"type": "header",
"text": {
"type": "plain_text",
"text": "😍 This is a header block 333",
"emoji": true
}
}
]
}'''
# blocks = '''[{"type":"section",
# "text":{"type":"mrkdwn",
# "text": ":sorriso_olhos_arregalados: Processo: ETL - CDPI/MULTIMAGEM"
# }
# }
# ]'''
return blocks
def post_message_to_slack(self, token, channel, text, icon_emoji, username, blocks=None, url="https://slack.com/api/chat.postMessage" ):
result = None
x = blocks
try:
result = requests.post(url,
{'token': token,
'channel': channel,
'text': text,
'icon_emoji': icon_emoji,
'username': username,
'blocks': blocks
}
).json()
except Exception as error:
print(error)
finally:
return result
# 'blocks': '''[{"type":"section",
# "text":{"type":"mrkdwn",
# "text": "teste 123456"
# }
# }
# ]
if __name__ == "__main__" :
processo = {"nom_processo": "MULTIMED",
"des_processo": "Extração MULTIMED/CDPI"
}
x = EXTRACAO(**processo)
x.Execute() | PypiClean |
/netket-3.9.2.tar.gz/netket-3.9.2/netket/sampler/base.py |
import abc
from typing import Optional, Union, Tuple, Callable, Iterator
import numpy as np
from flax import linen as nn
from jax import numpy as jnp
from netket import jax as nkjax
from netket.hilbert import AbstractHilbert
from netket.utils import mpi, get_afun_if_module, wrap_afun
from netket.utils.deprecation import deprecated
from netket.utils.types import PyTree, DType, SeedT
from netket.jax import HashablePartial
from netket.utils import struct, numbers
fancy = []
@struct.dataclass
class SamplerState(abc.ABC):
"""
Base class holding the state of a sampler.
"""
pass
@struct.dataclass
class Sampler(abc.ABC):
"""
Abstract base class for all samplers.
It contains the fields that all of them should possess, defining the common
API.
Note that fields marked with `pytree_node=False` are treated as static arguments
when jitting.
Subclasses should be NetKet dataclasses and they should define the `_init_state`,
`_reset` and `_sample_chain` methods which only accept positional arguments.
See the respective method's definition for its signature.
Notice that those methods are different from the API-entry point without the leading
underscore in order to allow us to share some pre-processing code between samplers
and simplify the definition of a new sampler.
"""
hilbert: AbstractHilbert = struct.field(pytree_node=False)
"""The Hilbert space to sample."""
n_chains_per_rank: int = struct.field(pytree_node=False, default=None, repr=False)
"""Number of independent chains on every MPI rank."""
machine_pow: int = struct.field(default=2)
"""The power to which the machine should be exponentiated to generate the pdf."""
dtype: DType = struct.field(pytree_node=False, default=np.float64)
"""The dtype of the states sampled."""
def __pre_init__(
self, hilbert: AbstractHilbert, n_chains: Optional[int] = None, **kwargs
):
"""
Construct a Monte Carlo sampler.
Args:
hilbert: The Hilbert space to sample.
n_chains: The total number of independent chains across all MPI ranks. Either specify this or `n_chains_per_rank`.
n_chains_per_rank: Number of independent chains on every MPI rank (default = 1).
machine_pow: The power to which the machine should be exponentiated to generate the pdf (default = 2).
dtype: The dtype of the states sampled (default = np.float64).
"""
if "n_chains_per_rank" in kwargs:
if n_chains is not None:
raise ValueError(
"Cannot specify both `n_chains` and `n_chains_per_rank`"
)
else:
if n_chains is None:
# Default value
n_chains_per_rank = 1
else:
n_chains_per_rank = max(int(np.ceil(n_chains / mpi.n_nodes)), 1)
if mpi.n_nodes > 1 and mpi.rank == 0:
if n_chains_per_rank * mpi.n_nodes != n_chains:
import warnings
warnings.warn(
f"Using {n_chains_per_rank} chains per rank among {mpi.n_nodes} ranks "
f"(total={n_chains_per_rank * mpi.n_nodes} instead of n_chains={n_chains}). "
f"To directly control the number of chains on every rank, specify "
f"`n_chains_per_rank` when constructing the sampler. "
f"To silence this warning, either use `n_chains_per_rank` or use `n_chains` "
f"that is a multiple of the number of MPI ranks.",
category=UserWarning,
stacklevel=2,
)
kwargs["n_chains_per_rank"] = n_chains_per_rank
return (hilbert,), kwargs
def __post_init__(self):
# Raise errors if hilbert is not an Hilbert
if not isinstance(self.hilbert, AbstractHilbert):
raise TypeError(
"\n\nThe argument `hilbert` of a Sampler must be a subtype "
"of netket.hilbert.AbstractHilbert, but you passed in an object "
f"of type {type(self.hilbert)}, which is not an AbstractHilbert.\n\n"
"TO FIX THIS ERROR,\ndouble check the arguments passed to the "
"sampler when constructing it, and verify that they have the "
"correct types.\n\n"
"For more information, check the correct arguments in the API "
"reference at https://netket.readthedocs.io/en/latest/api/sampler.html"
"\n"
)
# workaround Jax bug under pmap
# might be removed in the future
if type(self.machine_pow) != object:
if not np.issubdtype(numbers.dtype(self.machine_pow), np.integer):
raise ValueError(
f"machine_pow ({self.machine_pow}) must be a positive integer"
)
@property
def n_chains(self) -> int:
"""
The total number of independent chains across all MPI ranks.
If you are not using MPI, this is equal to :attr:`~Sampler.n_chains_per_rank`.
"""
return self.n_chains_per_rank * mpi.n_nodes
@property
def n_batches(self) -> int:
r"""
The batch size of the configuration $\sigma$ used by this sampler.
In general, it is equivalent to :attr:`~Sampler.n_chains_per_rank`.
"""
return self.n_chains_per_rank
@property
def is_exact(self) -> bool:
"""
Returns `True` if the sampler is exact.
The sampler is exact if all the samples are exactly distributed according to the
chosen power of the variational state, and there is no correlation among them.
"""
return False
def log_pdf(self, model: Union[Callable, nn.Module]) -> Callable:
"""
Returns a closure with the log-pdf function encoded by this sampler.
Args:
model: A Flax module or callable with the forward pass of the log-pdf.
If it is a callable, it should have the signature :code:`f(parameters, σ) -> jnp.ndarray`.
Returns:
The log-probability density function.
Note:
The result is returned as a `HashablePartial` so that the closure
does not trigger recompilation.
"""
apply_fun = get_afun_if_module(model)
log_pdf = HashablePartial(
lambda apply_fun, pars, σ: self.machine_pow * apply_fun(pars, σ).real,
apply_fun,
)
return log_pdf
def init_state(
sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
seed: Optional[SeedT] = None,
) -> SamplerState:
"""
Creates the structure holding the state of the sampler.
If you want reproducible samples, you should specify `seed`, otherwise the state
will be initialised randomly.
If running across several MPI processes, all `sampler_state`s are guaranteed to be
in a different (but deterministic) state.
This is achieved by first reducing (summing) the seed provided to every MPI rank,
then generating `n_rank` seeds starting from the reduced one, and every rank is
initialized with one of those seeds.
The resulting state is guaranteed to be a frozen Python dataclass (in particular,
a Flax dataclass), and it can be serialized using Flax serialization methods.
Args:
machine: A Flax module or callable with the forward pass of the log-pdf.
If it is a callable, it should have the signature :code:`f(parameters, σ) -> jnp.ndarray`.
parameters: The PyTree of parameters of the model.
seed: An optional seed or jax PRNGKey. If not specified, a random seed will be used.
Returns:
The structure holding the state of the sampler. In general you should not expect
it to be in a valid state, and should reset it before use.
"""
key = nkjax.PRNGKey(seed)
key = nkjax.mpi_split(key)
return sampler._init_state(wrap_afun(machine), parameters, key)
def reset(
sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
state: Optional[SamplerState] = None,
) -> SamplerState:
"""
Resets the state of the sampler. To be used every time the parameters are changed.
Args:
machine: A Flax module or callable with the forward pass of the log-pdf.
If it is a callable, it should have the signature :code:`f(parameters, σ) -> jnp.ndarray`.
parameters: The PyTree of parameters of the model.
state: The current state of the sampler. If not specified, it will be constructed
by calling :code:`sampler.init_state(machine, parameters)` with a random seed.
Returns:
A valid sampler state.
"""
if state is None:
state = sampler.init_state(machine, parameters)
return sampler._reset(wrap_afun(machine), parameters, state)
def sample(
sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
*,
state: Optional[SamplerState] = None,
chain_length: int = 1,
) -> Tuple[jnp.ndarray, SamplerState]:
"""
Samples `chain_length` batches of samples along the chains.
Arguments:
machine: A Flax module or callable with the forward pass of the log-pdf.
If it is a callable, it should have the signature :code:`f(parameters, σ) -> jnp.ndarray`.
parameters: The PyTree of parameters of the model.
state: The current state of the sampler. If not specified, then initialize and reset it.
chain_length: The length of the chains (default = 1).
Returns:
σ: The generated batches of samples.
state: The new state of the sampler.
"""
if state is None:
state = sampler.reset(machine, parameters)
return sampler._sample_chain(
wrap_afun(machine), parameters, state, chain_length
)
def samples(
sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
*,
state: Optional[SamplerState] = None,
chain_length: int = 1,
) -> Iterator[jnp.ndarray]:
"""
Returns a generator sampling `chain_length` batches of samples along the chains.
Arguments:
machine: A Flax module or callable with the forward pass of the log-pdf.
If it is a callable, it should have the signature :code:`f(parameters, σ) -> jnp.ndarray`.
parameters: The PyTree of parameters of the model.
state: The current state of the sampler. If not specified, then initialize and reset it.
chain_length: The length of the chains (default = 1).
"""
if state is None:
state = sampler.reset(machine, parameters)
machine = wrap_afun(machine)
for _i in range(chain_length):
samples, state = sampler._sample_chain(machine, parameters, state, 1)
yield samples[:, 0, :]
@abc.abstractmethod
def _sample_chain(
sampler,
machine: nn.Module,
parameters: PyTree,
state: SamplerState,
chain_length: int,
) -> Tuple[jnp.ndarray, SamplerState]:
"""
Implementation of `sample` for subclasses of `Sampler`.
If you subclass `Sampler`, you should override this and not `sample`
itself, because `sample` contains some common logic.
If using Jax, this function should be jitted.
Arguments:
machine: A Flax module with the forward pass of the log-pdf.
parameters: The PyTree of parameters of the model.
state: The current state of the sampler.
chain_length: The length of the chains.
Returns:
σ: The generated batches of samples.
state: The new state of the sampler.
"""
@abc.abstractmethod
def _init_state(sampler, machine, params, seed) -> SamplerState:
"""
Implementation of `init_state` for subclasses of `Sampler`.
If you subclass `Sampler`, you should override this and not `init_state`
itself, because `init_state` contains some common logic.
"""
@abc.abstractmethod
def _reset(sampler, machine, parameters, state):
"""
Implementation of `reset` for subclasses of `Sampler`.
If you subclass `Sampler`, you should override this and not `reset`
itself, because `reset` contains some common logic.
"""
@deprecated(
"The module function `sampler_state` is deprecated in favor of the class method `init_state`."
)
def sampler_state(
sampler: Sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
seed: Optional[SeedT] = None,
) -> SamplerState:
"""
Creates the structure holding the state of the sampler.
If you want reproducible samples, you should specify `seed`, otherwise the state
will be initialised randomly.
If running across several MPI processes, all `sampler_state`s are guaranteed to be
in a different (but deterministic) state.
This is achieved by first reducing (summing) the seed provided to every MPI rank,
then generating `n_rank` seeds starting from the reduced one, and every rank is
initialized with one of those seeds.
The resulting state is guaranteed to be a frozen Python dataclass (in particular,
a Flax dataclass), and it can be serialized using Flax serialization methods.
Args:
sampler: The Monte Carlo sampler.
machine: A Flax module or callable with the forward pass of the log-pdf.
If it is a callable, it should have the signature :code:`f(parameters, σ) -> jnp.ndarray`.
parameters: The PyTree of parameters of the model.
seed: An optional seed or jax PRNGKey. If not specified, a random seed will be used.
Returns:
The structure holding the state of the sampler. In general you should not expect
it to be in a valid state, and should reset it before use.
"""
return sampler.init_state(machine, parameters, seed)
@deprecated(
"The module function `reset` is deprecated in favor of the class method `reset`."
)
def reset(
sampler: Sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
state: Optional[SamplerState] = None,
) -> SamplerState:
"""
Resets the state of the sampler. To be used every time the parameters are changed.
Args:
sampler: The Monte Carlo sampler.
machine: A Flax module or callable with the forward pass of the log-pdf.
If it is a callable, it should have the signature :code:`f(parameters, σ) -> jnp.ndarray`.
parameters: The PyTree of parameters of the model.
state: The current state of the sampler. If not specified, it will be constructed
by calling :code:`sampler.init_state(machine, parameters)` with a random seed.
Returns:
A valid sampler state.
"""
return sampler.reset(machine, parameters, state)
@deprecated(
"The module function `sample` is deprecated in favor of the class method `sample`."
)
def sample(
sampler: Sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
*,
state: Optional[SamplerState] = None,
chain_length: int = 1,
) -> Tuple[jnp.ndarray, SamplerState]:
"""
Samples `chain_length` batches of samples along the chains.
Arguments:
sampler: The Monte Carlo sampler.
machine: A Flax module or callable with the forward pass of the log-pdf.
If it is a callable, it should have the signature :code:`f(parameters, σ) -> jnp.ndarray`.
parameters: The PyTree of parameters of the model.
state: The current state of the sampler. If not specified, then initialize and reset it.
chain_length: The length of the chains (default = 1).
Returns:
σ: The generated batches of samples.
state: The new state of the sampler.
"""
return sampler.sample(machine, parameters, state=state, chain_length=chain_length)
@deprecated(
"The module function `samples` is deprecated in favor of the class method `samples`."
)
def samples(
sampler: Sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
*,
state: Optional[SamplerState] = None,
chain_length: int = 1,
) -> Iterator[jnp.ndarray]:
"""
Returns a generator sampling `chain_length` batches of samples along the chains.
Arguments:
sampler: The Monte Carlo sampler.
machine: A Flax module or callable with the forward pass of the log-pdf.
If it is a callable, it should have the signature :code:`f(parameters, σ) -> jnp.ndarray`.
parameters: The PyTree of parameters of the model.
state: The current state of the sampler. If not specified, then initialize and reset it.
chain_length: The length of the chains (default = 1).
"""
yield from sampler.samples(
machine, parameters, state=state, chain_length=chain_length
) | PypiClean |
/DeepGMAP-0.2.0.tar.gz/DeepGMAP-0.2.0/deepgmap/post_train_tools/inputfileGeneratorForGenomeScan_p.py | import re
import numpy as np
import gzip
#output_handle=open("/home/koh/MLData/test.txt", 'w')
import time
import gzip
import math
import os.path
import multiprocessing
import sys
import glob
import deepgmap.data_preprocessing_tools.seq_to_binary2 as sb2
import time
import psutil
import getopt
#from __future__ import print_function
PATH_SEP=os.path.sep
def DNA_to_array_converter(input_file,target_chr):
if "," in target_chr:
target_chr=set(target_chr.split(','))
else:
target_chr=set([target_chr])
#print target_chr
seq_list=[]
position_list=[]
b1=0.0
i=0
with open(input_file, 'r') as fin:
SEQ=False
for line in fin:
if line.startswith('>'):
_line=line.strip('>').split(':')[0]
if _line in target_chr:
print(line)
position_list.append(line.strip('\n'))
SEQ=True
else:
SEQ=False
elif SEQ:
line=line.strip('\n')
data_width=len(line)
#sequence=np.zeros([1,1000,4,1], np.int16)
seq_list.append(sb2.AGCTtoArray4(line.encode('utf-8'),data_width))
#seq_list.append(sb2.ACGTtoaltArray(line,data_width))
return position_list, seq_list
def array_saver(outfile,positions,sequences):
print('saving '+outfile)
np.savez_compressed(outfile,positions=positions,sequences=sequences)
def run(args):
main(args)
def main(args=None):
"""
argparser_generate_test = subparsers.add_parser( "generate_test",
help = "Generate a data set for a test or an application of a trained model." )
argparser_generate_test.add_argument( "-i", "--in_file", dest = "input_genome" , type = str, required = True,
help = "A multiple fasta file containing genome DNA sequences. REQUIRED" )
argparser_generate_test.add_argument("-C", "--chromosome", dest = "chromosome", type = str, default = "chr2",
help = "Set a target chromosome or a contig for prediction. Default: chr2" )
argparser_generate_test.add_argument( "-o", "--out_dir", dest = "out_directory", type = str, required = True,
help = "")
argparser_generate_test.add_argument( "-t", "--threads", dest = "thread_number", type = int,
help = "The number of threads. Multithreading is performed only when saving output numpy arrays. Default: 1", default = 1 )
"""
input_file=args.input_genome
if not input_file.endswith(".fa") and not input_file.endswith(".fasta"):
input_file+=PATH_SEP+"genome.fa"
if not os.path.isfile(input_file):
print("input file must be a dirctory containing genome.fa or a fasta file.")
target_chr=args.chromosome
output_file=args.out_directory+"_"+target_chr
threads=args.thread_number
if threads==0:
threads=multiprocessing.cpu_count()//2
print(args)
os.makedirs(output_file)
output_file+=PATH_SEP
position_list, seq_list=DNA_to_array_converter(input_file,target_chr)
seq_num=len(position_list)
print(seq_num)
DIVIDES_NUM=seq_num//120000
if DIVIDES_NUM%threads==0:
outerloop=DIVIDES_NUM//threads
else:
outerloop=DIVIDES_NUM//threads+1
if seq_num%DIVIDES_NUM==0:
chunk_num=seq_num//DIVIDES_NUM
else:
chunk_num=seq_num//DIVIDES_NUM+1
if DIVIDES_NUM>=threads:
job_num=threads
else:
job_num=DIVIDES_NUM
print(DIVIDES_NUM, threads, outerloop, job_num)
for l in range(outerloop):
jobs = []
for i in range(job_num):
if i*chunk_num+l*threads>seq_num:
break
jobs.append(multiprocessing.Process(target=array_saver,
args=(str(output_file)+str(i+l*threads),
position_list[i*chunk_num+l*threads*chunk_num:(i+1)*chunk_num+l*threads*chunk_num],
seq_list[i*chunk_num+l*threads*chunk_num:(i+1)*chunk_num+l*threads*chunk_num])))
for j in jobs:
j.start()
for j in jobs:
j.join()
if __name__== '__main__':
main() | PypiClean |
/CustomerProfile-0.1.1.tar.gz/CustomerProfile-0.1.1/docs/installation.rst | .. highlight:: shell
============
Installation
============
Stable release
--------------
To install CustomerProfile, run this command in your terminal:
.. code-block:: console
$ pip install CustomerProfile
This is the preferred method to install CustomerProfile, as it will always install the most recent stable release.
If you don't have `pip`_ installed, this `Python installation guide`_ can guide
you through the process.
.. _pip: https://pip.pypa.io
.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/
From sources
------------
The sources for CustomerProfile can be downloaded from the `Github repo`_.
You can either clone the public repository:
.. code-block:: console
$ git clone git://github.com/HrayrMuradyan/CustomerProfile
Or download the `tarball`_:
.. code-block:: console
$ curl -OJL https://github.com/HrayrMuradyan/CustomerProfile/tarball/master
Once you have a copy of the source, you can install it with:
.. code-block:: console
$ python setup.py install
.. _Github repo: https://github.com/HrayrMuradyan/CustomerProfile
.. _tarball: https://github.com/HrayrMuradyan/CustomerProfile/tarball/master
| PypiClean |
/BPMN_RPA-7.1.2.tar.gz/BPMN_RPA-7.1.2/BPMN_RPA/Scripts/TextMining.py | import json
import os
import pickle
import shutil
import subprocess
import sys
import BPMN_RPA.Scripts.SQLserver as SQLserver
import spacy
import tensorflow
# The BPMN-RPA TextMining module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# The BPMN-RPA TextMining module 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 this program. If not, see <https://www.gnu.org/licenses/>.
#
# The TextMining module is based on the Spacy library. Spacy is licensed under the MIT license:
# Copyright (C) 2016-2022 ExplosionAI GmbH, 2016 spaCy GmbH, 2015 Matthew Honnibal
# 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.
#
#check if the attribute is present
hasattr(tensorflow, '__version__')
#if the attribute is not present
if not hasattr(tensorflow, '__version__'):
#add the attribute
tensorflow.__version__ = sys.version
class TextMining:
def __init__(self, standard_model='en_core_web_lg'):
"""
Initializes the TextMining module.
:param standard_model: The standard model to use. Default is 'en_core_web_lg'. To download this model, see https://spacy.io/models/en. If you want to use any other language, please refer to https://spacy.io/models
"""
self.standard_model = standard_model
self.nlp = None
self.__connect__()
def __connect__(self):
"""
Internal function to connect to the Spacy model.
"""
self.nlp = spacy.load(self.standard_model)
def __is_picklable__(self, obj: any) -> bool:
"""
Internal function to determine if the object is pickable.
:param obj: The object to check.
:return: True or False
"""
try:
pickle.dumps(obj)
return True
except Exception as e:
return False
def __getstate__(self):
"""
Internal function for serialization
"""
state = self.__dict__.copy()
for key, val in state.items():
if not self.__is_picklable__(val):
state[key] = str(val)
return state
def __setstate__(self, state):
"""
Internal function for deserialization
:param state: The state to set to the 'self' object of the class
"""
self.__dict__.update(state)
self.__connect__()
def get_named_entities(self, text):
"""
Returns the named entities of a text.
:param text: Text to analyze
:return: A list of named entities
"""
doc = self.nlp(text)
return doc.ents
def get_named_entities_as_string(self, text):
"""
Returns the named entities of a text as a string.
:param text: Text to analyze
:return: A string of named entities
"""
doc = self.nlp(text)
return str(doc.ents)
def get_named_entities_as_json(self, text):
"""
Returns the named entities of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of named entities
"""
doc = self.nlp(text)
return json.dumps(doc.ents)
def get_named_entities_as_dict(self, text):
"""
Returns the named entities of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of named entities
"""
doc = self.nlp(text)
return doc.ents
def get_named_entities_as_list(self, text):
"""
Returns the named entities of a text as a list.
:param text: Text to analyze
:return: A list of named entities
"""
doc = self.nlp(text)
return list(doc.ents)
def get_subjects(self, text):
"""
Returns the subjects of a text.
:param text: Text to analyze
:return: A list of subjects
"""
doc = self.nlp(text)
return [chunk.root.text for chunk in doc.noun_chunks if chunk.root.dep_ == "nsubj"]
def get_subjects_as_string(self, text):
"""
Returns the subjects of a text as a string.
:param text: Text to analyze
:return: A string of subjects
"""
doc = self.nlp(text)
return str([chunk.root.text for chunk in doc.noun_chunks if chunk.root.dep_ == "nsubj"])
def get_subjects_as_json(self, text):
"""
Returns the subjects of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of subjects
"""
doc = self.nlp(text)
return json.dumps([chunk.root.text for chunk in doc.noun_chunks if chunk.root.dep_ == "nsubj"])
def get_subjects_as_dict(self, text):
"""
Returns the subjects of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of subjects
"""
doc = self.nlp(text)
return [chunk.root.text for chunk in doc.noun_chunks if chunk.root.dep_ == "nsubj"]
def get_subjects_as_list(self, text):
"""
Returns the subjects of a text as a list.
:param text: Text to analyze
:return: A list of subjects
"""
doc = self.nlp(text)
return [chunk.root.text for chunk in doc.noun_chunks if chunk.root.dep_ == "nsubj"]
def get_verbs(self, text):
"""
Returns the verbs of a text.
:param text: Text to analyze
:return: A list of verbs
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "VERB"]
def get_verbs_as_string(self, text):
"""
Returns the verbs of a text as a string.
:param text: Text to analyze
:return: A string of verbs
"""
doc = self.nlp(text)
return str([token.text for token in doc if token.pos_ == "VERB"])
def get_verbs_as_json(self, text):
"""
Returns the verbs of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of verbs
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc if token.pos_ == "VERB"])
def get_verbs_as_dict(self, text):
"""
Returns the verbs of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of verbs
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "VERB"]
def get_verbs_as_list(self, text):
"""
Returns the verbs of a text as a list.
:param text: Text to analyze
:return: A list of verbs
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "VERB"]
def get_nouns(self, text):
"""
Returns the nouns of a text.
:param text: Text to analyze
:return: A list of nouns
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "NOUN"]
def get_nouns_as_string(self, text):
"""
Returns the nouns of a text as a string.
:param text: Text to analyze
:return: A string of nouns
"""
doc = self.nlp(text)
return str([token.text for token in doc if token.pos_ == "NOUN"])
def get_nouns_as_json(self, text):
"""
Returns the nouns of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of nouns
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc if token.pos_ == "NOUN"])
def get_nouns_as_dict(self, text):
"""
Returns the nouns of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of nouns
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "NOUN"]
def get_nouns_as_list(self, text):
"""
Returns the nouns of a text as a list.
:param text: Text to analyze
:return: A list of nouns
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "NOUN"]
def get_adjectives(self, text):
"""
Returns the adjectives of a text.
:param text: Text to analyze
:return: A list of adjectives
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "ADJ"]
def get_adjectives_as_string(self, text):
"""
Returns the adjectives of a text as a string.
:param text: Text to analyze
:return: A string of adjectives
"""
doc = self.nlp(text)
return str([token.text for token in doc if token.pos_ == "ADJ"])
def get_adjectives_as_json(self, text):
"""
Returns the adjectives of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of adjectives
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc if token.pos_ == "ADJ"])
def get_adjectives_as_dict(self, text):
"""
Returns the adjectives of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of adjectives
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "ADJ"]
def get_adjectives_as_list(self, text):
"""
Returns the adjectives of a text as a list.
:param text: Text to analyze
:return: A list of adjectives
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "ADJ"]
def get_adverbs(self, text):
"""
Returns the adverbs of a text.
:param text: Text to analyze
:return: A list of adverbs
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "ADV"]
def get_adverbs_as_string(self, text):
"""
Returns the adverbs of a text as a string.
:param text: Text to analyze
:return: A string of adverbs
"""
doc = self.nlp(text)
return str([token.text for token in doc if token.pos_ == "ADV"])
def get_adverbs_as_json(self, text):
"""
Returns the adverbs of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of adverbs
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc if token.pos_ == "ADV"])
def get_adverbs_as_dict(self, text):
"""
Returns the adverbs of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of adverbs
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "ADV"]
def get_adverbs_as_list(self, text):
"""
Returns the adverbs of a text as a list.
:param text: Text to analyze
:return: A list of adverbs
"""
doc = self.nlp(text)
return [token.text for token in doc if token.pos_ == "ADV"]
def get_persons(self, text):
"""
Returns the persons of a text.
:param text: Text to analyze
:return: A list of persons
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "PERSON"]
def get_persons_as_string(self, text):
"""
Returns the persons of a text as a string.
:param text: Text to analyze
:return: A string of persons
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "PERSON"])
def get_persons_as_json(self, text):
"""
Returns the persons of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of persons
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "PERSON"])
def get_persons_as_dict(self, text):
"""
Returns the persons of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of persons
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "PERSON"]
def get_persons_as_list(self, text):
"""
Returns the persons of a text as a list.
:param text: Text to analyze
:return: A list of persons
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "PERSON"]
def get_locations(self, text):
"""
Returns the locations of a text.
:param text: Text to analyze
:return: A list of locations
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "LOC"]
def get_locations_as_string(self, text):
"""
Returns the locations of a text as a string.
:param text: Text to analyze
:return: A string of locations
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "LOC"])
def get_locations_as_json(self, text):
"""
Returns the locations of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of locations
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "LOC"])
def get_locations_as_dict(self, text):
"""
Returns the locations of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of locations
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "LOC"]
def get_locations_as_list(self, text):
"""
Returns the locations of a text as a list.
:param text: Text to analyze
:return: A list of locations
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "LOC"]
def get_organizations(self, text):
"""
Returns the organizations of a text.
:param text: Text to analyze
:return: A list of organizations
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "ORG"]
def get_organizations_as_string(self, text):
"""
Returns the organizations of a text as a string.
:param text: Text to analyze
:return: A string of organizations
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "ORG"])
def get_organizations_as_json(self, text):
"""
Returns the organizations of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of organizations
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "ORG"])
def get_organizations_as_dict(self, text):
"""
Returns the organizations of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of organizations
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "ORG"]
def get_organizations_as_list(self, text):
"""
Returns the organizations of a text as a list.
:param text: Text to analyze
:return: A list of organizations
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "ORG"]
def get_dates(self, text):
"""
Returns the dates of a text.
:param text: Text to analyze
:return: A list of dates
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "DATE"]
def get_dates_as_string(self, text):
"""
Returns the dates of a text as a string.
:param text: Text to analyze
:return: A string of dates
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "DATE"])
def get_dates_as_json(self, text):
"""
Returns the dates of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of dates
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "DATE"])
def get_dates_as_dict(self, text):
"""
Returns the dates of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of dates
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "DATE"]
def get_dates_as_list(self, text):
"""
Returns the dates of a text as a list.
:param text: Text to analyze
:return: A list of dates
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "DATE"]
def get_money(self, text):
"""
Returns the money of a text.
:param text: Text to analyze
:return: A list of money
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "MONEY"]
def get_money_as_string(self, text):
"""
Returns the money of a text as a string.
:param text: Text to analyze
:return: A string of money
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "MONEY"])
def get_money_as_json(self, text):
"""
Returns the money of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of money
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "MONEY"])
def get_money_as_dict(self, text):
"""
Returns the money of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of money
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "MONEY"]
def get_money_as_list(self, text):
"""
Returns the money of a text as a list.
:param text: Text to analyze
:return: A list of money
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "MONEY"]
def get_percentages(self, text):
"""
Returns the percentages of a text.
:param text: Text to analyze
:return: A list of percentages
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "PERCENT"]
def get_percentages_as_string(self, text):
"""
Returns the percentages of a text as a string.
:param text: Text to analyze
:return: A string of percentages
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "PERCENT"])
def get_percentages_as_json(self, text):
"""
Returns the percentages of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of percentages
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "PERCENT"])
def get_percentages_as_dict(self, text):
"""
Returns the percentages of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of percentages
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "PERCENT"]
def get_percentages_as_list(self, text):
"""
Returns the percentages of a text as a list.
:param text: Text to analyze
:return: A list of percentages
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "PERCENT"]
def get_times(self, text):
"""
Returns the times of a text.
:param text: Text to analyze
:return: A list of times
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "TIME"]
def get_times_as_string(self, text):
"""
Returns the times of a text as a string.
:param text: Text to analyze
:return: A string of times
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "TIME"])
def get_times_as_json(self, text):
"""
Returns the times of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of times
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "TIME"])
def get_times_as_dict(self, text):
"""
Returns the times of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of times
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "TIME"]
def get_times_as_list(self, text):
"""
Returns the times of a text as a list.
:param text: Text to analyze
:return: A list of times
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "TIME"]
def get_nationalities(self, text):
"""
Returns the nationalities of a text.
:param text: Text to analyze
:return: A list of nationalities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "NORP"]
def get_nationalities_as_string(self, text):
"""
Returns the nationalities of a text as a string.
:param text: Text to analyze
:return: A string of nationalities
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "NORP"])
def get_nationalities_as_json(self, text):
"""
Returns the nationalities of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of nationalities
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "NORP"])
def get_nationalities_as_dict(self, text):
"""
Returns the nationalities of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of nationalities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "NORP"]
def get_nationalities_as_list(self, text):
"""
Returns the nationalities of a text as a list.
:param text: Text to analyze
:return: A list of nationalities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "NORP"]
def get_languages(self, text):
"""
Returns the languages of a text.
:param text: Text to analyze
:return: A list of languages
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "LANGUAGE"]
def get_languages_as_string(self, text):
"""
Returns the languages of a text as a string.
:param text: Text to analyze
:return: A string of languages
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "LANGUAGE"])
def get_languages_as_json(self, text):
"""
Returns the languages of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of languages
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "LANGUAGE"])
def get_languages_as_dict(self, text):
"""
Returns the languages of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of languages
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "LANGUAGE"]
def get_languages_as_list(self, text):
"""
Returns the languages of a text as a list.
:param text: Text to analyze
:return: A list of languages
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "LANGUAGE"]
def get_facilities(self, text):
"""
Returns the facilities of a text.
:param text: Text to analyze
:return: A list of facilities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "FAC"]
def get_facilities_as_string(self, text):
"""
Returns the facilities of a text as a string.
:param text: Text to analyze
:return: A string of facilities
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "FAC"])
def get_facilities_as_json(self, text):
"""
Returns the facilities of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of facilities
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "FAC"])
def get_facilities_as_dict(self, text):
"""
Returns the facilities of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of facilities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "FAC"]
def get_facilities_as_list(self, text):
"""
Returns the facilities of a text as a list.
:param text: Text to analyze
:return: A list of facilities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "FAC"]
def get_cities_countries_and_states(self, text):
"""
Returns the cities of a text.
:param text: Text to analyze
:return: A list of cities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "GPE"]
def get_cities_countries_and_states_as_string(self, text):
"""
Returns the cities of a text as a string.
:param text: Text to analyze
:return: A string of cities
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "GPE"])
def get_cities_countries_and_states_as_json(self, text):
"""
Returns the cities of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of cities
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "GPE"])
def get_cities_countries_and_states_as_dict(self, text):
"""
Returns the cities of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of cities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "GPE"]
def get_cities_countries_and_states_as_list(self, text):
"""
Returns the cities of a text as a list.
:param text: Text to analyze
:return: A list of cities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "GPE"]
def get_products(self, text):
"""
Returns the products of a text.
:param text: Text to analyze
:return: A list of products
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "PRODUCT"]
def get_products_as_string(self, text):
"""
Returns the products of a text as a string.
:param text: Text to analyze
:return: A string of products
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "PRODUCT"])
def get_products_as_json(self, text):
"""
Returns the products of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of products
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "PRODUCT"])
def get_products_as_dict(self, text):
"""
Returns the products of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of products
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "PRODUCT"]
def get_products_as_list(self, text):
"""
Returns the products of a text as a list.
:param text: Text to analyze
:return: A list of products
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "PRODUCT"]
def get_laws(self, text):
"""
Returns the laws of a text.
:param text: Text to analyze
:return: A list of laws
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "LAW"]
def get_laws_as_string(self, text):
"""
Returns the laws of a text as a string.
:param text: Text to analyze
:return: A string of laws
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "LAW"])
def get_laws_as_json(self, text):
"""
Returns the laws of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of laws
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "LAW"])
def get_laws_as_dict(self, text):
"""
Returns the laws of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of laws
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "LAW"]
def get_laws_as_list(self, text):
"""
Returns the laws of a text as a list.
:param text: Text to analyze
:return: A list of laws
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "LAW"]
def get_quantities(self, text):
"""
Returns the quantities of a text.
:param text: Text to analyze
:return: A list of quantities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "QUANTITY"]
def get_quantities_as_string(self, text):
"""
Returns the quantities of a text as a string.
:param text: Text to analyze
:return: A string of quantities
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "QUANTITY"])
def get_quantities_as_json(self, text):
"""
Returns the quantities of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of quantities
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "QUANTITY"])
def get_quantities_as_dict(self, text):
"""
Returns the quantities of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of quantities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "QUANTITY"]
def get_quantities_as_list(self, text):
"""
Returns the quantities of a text as a list.
:param text: Text to analyze
:return: A list of quantities
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "QUANTITY"]
def get_ordinal_numbers(self, text):
"""
Returns the ordinal numbers of a text.
:param text: Text to analyze
:return: A list of ordinal numbers
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "ORDINAL"]
def get_ordinal_numbers_as_string(self, text):
"""
Returns the ordinal numbers of a text as a string.
:param text: Text to analyze
:return: A string of ordinal numbers
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "ORDINAL"])
def get_ordinal_numbers_as_json(self, text):
"""
Returns the ordinal numbers of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of ordinal numbers
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "ORDINAL"])
def get_ordinal_numbers_as_dict(self, text):
"""
Returns the ordinal numbers of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of ordinal numbers
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "ORDINAL"]
def get_ordinal_numbers_as_list(self, text):
"""
Returns the ordinal numbers of a text as a list.
:param text: Text to analyze
:return: A list of ordinal numbers
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "ORDINAL"]
def get_cardinal_numbers(self, text):
"""
Returns the cardinal numbers of a text.
:param text: Text to analyze
:return: A list of cardinal numbers
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "CARDINAL"]
def get_cardinal_numbers_as_string(self, text):
"""
Returns the cardinal numbers of a text as a string.
:param text: Text to analyze
:return: A string of cardinal numbers
"""
doc = self.nlp(text)
return str([token.text for token in doc.ents if token.label_ == "CARDINAL"])
def get_cardinal_numbers_as_json(self, text):
"""
Returns the cardinal numbers of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of cardinal numbers
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc.ents if token.label_ == "CARDINAL"])
def get_cardinal_numbers_as_dict(self, text):
"""
Returns the cardinal numbers of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of cardinal numbers
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "CARDINAL"]
def get_cardinal_numbers_as_list(self, text):
"""
Returns the cardinal numbers of a text as a list.
:param text: Text to analyze
:return: A list of cardinal numbers
"""
doc = self.nlp(text)
return [token.text for token in doc.ents if token.label_ == "CARDINAL"]
def get_part_of_speech_tags(self, text):
"""
Returns the part of speech tags of a text.
:param text: Text to analyze
:return: A list of part of speech tags
"""
doc = self.nlp(text)
return [token.pos_ for token in doc]
def get_part_of_speech_tags_as_string(self, text):
"""
Returns the part of speech tags of a text as a string.
:param text: Text to analyze
:return: A string of part of speech tags
"""
doc = self.nlp(text)
return str([token.pos_ for token in doc])
def get_part_of_speech_tags_as_json(self, text):
"""
Returns the part of speech tags of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of part of speech tags
"""
doc = self.nlp(text)
return json.dumps([token.pos_ for token in doc])
def get_part_of_speech_tags_as_dict(self, text):
"""
Returns the part of speech tags of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of part of speech tags
"""
doc = self.nlp(text)
return [token.pos_ for token in doc]
def get_part_of_speech_tags_as_list(self, text):
"""
Returns the part of speech tags of a text as a list.
:param text: Text to analyze
:return: A list of part of speech tags
"""
doc = self.nlp(text)
return [token.pos_ for token in doc]
def get_lemmas(self, text):
"""
Returns the lemmas of a text.
:param text: Text to analyze
:return: A list of lemmas
"""
doc = self.nlp(text)
return [token.lemma_ for token in doc]
def get_lemmas_as_string(self, text):
"""
Returns the lemmas of a text as a string.
:param text: Text to analyze
:return: A string of lemmas
"""
doc = self.nlp(text)
return str([token.lemma_ for token in doc])
def get_lemmas_as_json(self, text):
"""
Returns the lemmas of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of lemmas
"""
doc = self.nlp(text)
return json.dumps([token.lemma_ for token in doc])
def get_lemmas_as_dict(self, text):
"""
Returns the lemmas of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of lemmas
"""
doc = self.nlp(text)
return [token.lemma_ for token in doc]
def get_lemmas_as_list(self, text):
"""
Returns the lemmas of a text as a list.
:param text: Text to analyze
:return: A list of lemmas
"""
doc = self.nlp(text)
return [token.lemma_ for token in doc]
def get_dependencies(self, text):
"""
Returns the dependencies of a text.
:param text: Text to analyze
:return: A list of dependencies
"""
doc = self.nlp(text)
return [token.dep_ for token in doc]
def get_dependencies_as_string(self, text):
"""
Returns the dependencies of a text as a string.
:param text: Text to analyze
:return: A string of dependencies
"""
doc = self.nlp(text)
return str([token.dep_ for token in doc])
def get_dependencies_as_json(self, text):
"""
Returns the dependencies of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of dependencies
"""
doc = self.nlp(text)
return json.dumps([token.dep_ for token in doc])
def get_dependencies_as_dict(self, text):
"""
Returns the dependencies of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of dependencies
"""
doc = self.nlp(text)
return [token.dep_ for token in doc]
def get_dependencies_as_list(self, text):
"""
Returns the dependencies of a text as a list.
:param text: Text to analyze
:return: A list of dependencies
"""
doc = self.nlp(text)
return [token.dep_ for token in doc]
def sentiment_analysis(self, text):
"""
Returns the sentiment analysis of a text.
:param text: Text to analyze
:return: A list of sentiment analysis
"""
doc = self.nlp(text)
return doc.sentiment
def sentiment_analysis_as_string(self, text):
"""
Returns the sentiment analysis of a text as a string.
:param text: Text to analyze
:return: A string of sentiment analysis
"""
doc = self.nlp(text)
return str(doc.sentiment)
def sentiment_analysis_as_json(self, text):
"""
Returns the sentiment analysis of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of sentiment analysis
"""
doc = self.nlp(text)
return json.dumps(doc.sentiment)
def sentiment_analysis_as_dict(self, text):
"""
Returns the sentiment analysis of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of sentiment analysis
"""
doc = self.nlp(text)
return doc.sentiment
def sentiment_analysis_as_list(self, text):
"""
Returns the sentiment analysis of a text as a list.
:param text: Text to analyze
:return: A list of sentiment analysis
"""
doc = self.nlp(text)
return doc.sentiment
def get_noun_chunks(self, text):
"""
Returns the noun chunks of a text.
:param text: Text to analyze
:return: A list of noun chunks
"""
doc = self.nlp(text)
return [chunk.text for chunk in doc.noun_chunks]
def get_noun_chunks_as_string(self, text):
"""
Returns the noun chunks of a text as a string.
:param text: Text to analyze
:return: A string of noun chunks
"""
doc = self.nlp(text)
return str([chunk.text for chunk in doc.noun_chunks])
def get_noun_chunks_as_json(self, text):
"""
Returns the noun chunks of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of noun chunks
"""
doc = self.nlp(text)
return json.dumps([chunk.text for chunk in doc.noun_chunks])
def get_noun_chunks_as_dict(self, text):
"""
Returns the noun chunks of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of noun chunks
"""
doc = self.nlp(text)
return [chunk.text for chunk in doc.noun_chunks]
def get_noun_chunks_as_list(self, text):
"""
Returns the noun chunks of a text as a list.
:param text: Text to analyze
:return: A list of noun chunks
"""
doc = self.nlp(text)
return [chunk.text for chunk in doc.noun_chunks]
def get_most_similar_words(self, text):
"""
Returns the most similar words of a text.
:param text: Text to analyze
:return: A list of most similar words
"""
doc = self.nlp(text)
return [token.text for token in doc if token.has_vector and token.is_oov]
def get_most_similar_words_as_string(self, text):
"""
Returns the most similar words of a text as a string.
:param text: Text to analyze
:return: A string of most similar words
"""
doc = self.nlp(text)
return str([token.text for token in doc if token.has_vector and token.is_oov])
def get_most_similar_words_as_json(self, text):
"""
Returns the most similar words of a text as a JSON string.
:param text: Text to analyze
:return: A JSON string of most similar words
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc if token.has_vector and token.is_oov])
def get_most_similar_words_as_dict(self, text):
"""
Returns the most similar words of a text as a dictionary.
:param text: Text to analyze
:return: A dictionary of most similar words
"""
doc = self.nlp(text)
return [token.text for token in doc if token.has_vector and token.is_oov]
def get_most_similar_words_as_list(self, text):
"""
Returns the most similar words of a text as a list.
:param text: Text to analyze
:return: A list of most similar words
"""
doc = self.nlp(text)
return [token.text for token in doc if token.has_vector and token.is_oov]
def get_most_similar_words_with_similarity(self, text):
"""
Returns the most similar words of a text with similarity.
:param text: Text to analyze
:return: A list of most similar words with similarity
"""
doc = self.nlp(text)
return [(token.text, token.similarity(doc)) for token in doc if token.has_vector and token.is_oov]
def get_most_similar_words_with_similarity_as_string(self, text):
"""
Returns the most similar words of a text with similarity as a string.
:param text: Text to analyze
:return: A string of most similar words with similarity
"""
doc = self.nlp(text)
return str([(token.text, token.similarity(doc)) for token in doc if token.has_vector and token.is_oov])
def get_most_similar_words_with_similarity_as_json(self, text):
"""
Returns the most similar words of a text with similarity as a JSON string.
:param text: Text to analyze
:return: A JSON string of most similar words with similarity
"""
doc = self.nlp(text)
return json.dumps([(token.text, token.similarity(doc)) for token in doc if token.has_vector and token.is_oov])
def get_most_similar_words_with_similarity_as_dict(self, text):
"""
Returns the most similar words of a text with similarity as a dictionary.
:param text: Text to analyze
:return: A dictionary of most similar words with similarity
"""
doc = self.nlp(text)
return [(token.text, token.similarity(doc)) for token in doc if token.has_vector and token.is_oov]
def get_most_similar_words_with_similarity_as_list(self, text):
"""
Returns the most similar words of a text with similarity as a list.
:param text: Text to analyze
:return: A list of most similar words with similarity
"""
doc = self.nlp(text)
return [(token.text, token.similarity(doc)) for token in doc if token.has_vector and token.is_oov]
def get_best_match(self, text, words):
"""
Returns the best match of a text.
:param text: Text to analyze
:param words: List of words to match
:return: A list of best match
"""
doc = self.nlp(text)
return [doc.similarity(self.nlp(word)) for word in words]
def get_best_match_as_string(self, text, words):
"""
Returns the best match of a text as a string.
:param text: Text to analyze
:param words: List of words to match
:return: A string of best match
"""
doc = self.nlp(text)
return str([doc.similarity(self.nlp(word)) for word in words])
def get_best_match_as_json(self, text, words):
"""
Returns the best match of a text as a JSON string.
:param text: Text to analyze
:param words: List of words to match
:return: A JSON string of best match
"""
doc = self.nlp(text)
return json.dumps([doc.similarity(self.nlp(word)) for word in words])
def get_best_match_as_dict(self, text, words):
"""
Returns the best match of a text as a dictionary.
:param text: Text to analyze
:param words: List of words to match
:return: A dictionary of best match
"""
doc = self.nlp(text)
return [doc.similarity(self.nlp(word)) for word in words]
def get_best_match_as_list(self, text, words):
"""
Returns the best match of a text as a list.
:param text: Text to analyze
:param words: List of words to match
:return: A list of best match
"""
doc = self.nlp(text)
return [doc.similarity(self.nlp(word)) for word in words]
def get_best_match_with_similarity(self, text, words):
"""
Returns the best match of a text with similarity.
:param text: Text to analyze
:param words: List of words to match
:return: A list of best match with similarity
"""
doc = self.nlp(text)
return [(word, doc.similarity(self.nlp(word))) for word in words]
def get_best_match_with_similarity_as_string(self, text, words):
"""
Returns the best match of a text with similarity as a string.
:param text: Text to analyze
:param words: List of words to match
:return: A string of best match with similarity
"""
doc = self.nlp(text)
return str([(word, doc.similarity(self.nlp(word))) for word in words])
def get_best_match_with_similarity_as_json(self, text, words):
"""
Returns the best match of a text with similarity as a JSON string.
:param text: Text to analyze
:param words: List of words to match
:return: A JSON string of best match with similarity
"""
doc = self.nlp(text)
return json.dumps([(word, doc.similarity(self.nlp(word))) for word in words])
def get_best_match_with_similarity_as_dict(self, text, words):
"""
Returns the best match of a text with similarity as a dictionary.
:param text: Text to analyze
:param words: List of words to match
:return: A dictionary of best match with similarity
"""
doc = self.nlp(text)
return [(word, doc.similarity(self.nlp(word))) for word in words]
def get_best_match_with_similarity_as_list(self, text, words):
"""
Returns the best match of a text with similarity as a list.
:param text: Text to analyze
:param words: List of words to match
:return: A list of best match with similarity
"""
doc = self.nlp(text)
return [(word, doc.similarity(self.nlp(word))) for word in words]
def get_summary(self, text):
"""
Returns the summary of a text.
:param text: Text to analyze
:return: A list of summary
"""
doc = self.nlp(text)
return [sent.text for sent in doc.sents if sent._.is_highest]
def get_summary_as_string(self, text, ratio=0.2):
"""
Returns the summary of a text as a string.
:param text: Text to analyze
:param ratio: Ratio of summary
:return: A string of summary
"""
doc = self.nlp(text)
return str([sent.text for sent in doc.sents if sent._.is_highest])
def get_summary_as_json(self, text, ratio=0.2):
"""
Returns the summary of a text as a JSON string.
:param text: Text to analyze
:param ratio: Ratio of summary
:return: A JSON string of summary
"""
doc = self.nlp(text)
return json.dumps([sent.text for sent in doc.sents if sent._.is_highest])
def get_summary_as_dict(self, text, ratio=0.2):
"""
Returns the summary of a text as a dictionary.
:param text: Text to analyze
:param ratio: Ratio of summary
:return: A dictionary of summary
"""
doc = self.nlp(text)
return [sent.text for sent in doc.sents if sent._.is_highest]
def get_summary_as_list(self, text, ratio=0.2):
"""
Returns the summary of a text as a list.
:param text: Text to analyze
:param ratio: Ratio of summary
:return: A list of summary
"""
doc = self.nlp(text)
return [sent.text for sent in doc.sents if sent._.is_highest]
def get_stopwords(self):
"""
Returns the list of stopwords.
:return: A list of stopwords
"""
return self.nlp.Defaults.stop_words
def get_stopwords_as_string(self):
"""
Returns the list of stopwords as a string.
:return: A string of stopwords
"""
return str(self.nlp.Defaults.stop_words)
def get_stopwords_as_json(self):
"""
Returns the list of stopwords as a JSON string.
:return: A JSON string of stopwords
"""
return json.dumps(self.nlp.Defaults.stop_words)
def get_stopwords_as_dict(self):
"""
Returns the list of stopwords as a dictionary.
:return: A dictionary of stopwords
"""
return self.nlp.Defaults.stop_words
def get_stopwords_as_list(self):
"""
Returns the list of stopwords as a list.
:return: A list of stopwords
"""
return self.nlp.Defaults.stop_words
def get_tokens(self, text):
"""
Returns the list of tokens.
:param text: Text to analyze
:return: A list of tokens
"""
doc = self.nlp(text)
return [token.text for token in doc]
def get_tokens_as_string(self, text):
"""
Returns the list of tokens as a string.
:param text: Text to analyze
:return: A string of tokens
"""
doc = self.nlp(text)
return str([token.text for token in doc])
def get_tokens_as_json(self, text):
"""
Returns the list of tokens as a JSON string.
:param text: Text to analyze
:return: A JSON string of tokens
"""
doc = self.nlp(text)
return json.dumps([token.text for token in doc])
def get_tokens_as_dict(self, text):
"""
Returns the list of tokens as a dictionary.
:param text: Text to analyze
:return: A dictionary of tokens
"""
doc = self.nlp(text)
return [token.text for token in doc]
def get_tokens_as_list(self, text):
"""
Returns the list of tokens as a list.
:param text: Text to analyze
:return: A list of tokens
"""
doc = self.nlp(text)
return [token.text for token in doc]
def get_tokens_with_pos(self, text):
"""
Returns the list of tokens with POS.
:param text: Text to analyze
:return: A list of tokens with POS
"""
doc = self.nlp(text)
return [(token.text, token.pos_) for token in doc]
def get_tokens_with_pos_as_string(self, text):
"""
Returns the list of tokens with POS as a string.
:param text: Text to analyze
:return: A string of tokens with POS
"""
doc = self.nlp(text)
return str([(token.text, token.pos_) for token in doc])
def get_tokens_with_pos_as_json(self, text):
"""
Returns the list of tokens with POS as a JSON string.
:param text: Text to analyze
:return: A JSON string of tokens with POS
"""
doc = self.nlp(text)
return json.dumps([(token.text, token.pos_) for token in doc])
def get_tokens_with_pos_as_dict(self, text):
"""
Returns the list of tokens with POS as a dictionary.
:param text: Text to analyze
:return: A dictionary of tokens with POS
"""
doc = self.nlp(text)
return [(token.text, token.pos_) for token in doc]
def get_tokens_with_pos_as_list(self, text):
"""
Returns the list of tokens with POS as a list.
:param text: Text to analyze
:return: A list of tokens with POS
"""
doc = self.nlp(text)
return [(token.text, token.pos_) for token in doc]
def get_tokens_with_pos_and_dep(self, text):
"""
Returns the list of tokens with POS and dependency.
:param text: Text to analyze
:return: A list of tokens with POS and dependency
"""
doc = self.nlp(text)
return [(token.text, token.pos_, token.dep_) for token in doc]
def get_tokens_with_pos_and_dep_as_string(self, text):
"""
Returns the list of tokens with POS and dependency as a string.
:param text: Text to analyze
:return: A string of tokens with POS and dependency
"""
doc = self.nlp(text)
return str([(token.text, token.pos_, token.dep_) for token in doc])
def get_tokens_with_pos_and_dep_as_json(self, text):
"""
Returns the list of tokens with POS and dependency as a JSON string.
:param text: Text to analyze
:return: A JSON string of tokens with POS and dependency
"""
doc = self.nlp(text)
return json.dumps([(token.text, token.pos_, token.dep_) for token in doc])
def get_tokens_with_pos_and_dep_as_dict(self, text):
"""
Returns the list of tokens with POS and dependency as a dictionary.
:param text: Text to analyze
:return: A dictionary of tokens with POS and dependency
"""
doc = self.nlp(text)
return [(token.text, token.pos_, token.dep_) for token in doc]
def get_tokens_with_pos_and_dep_as_list(self, text):
"""
Returns the list of tokens with POS and dependency as a list.
:param text: Text to analyze
:return: A list of tokens with POS and dependency
"""
doc = self.nlp(text)
return [(token.text, token.pos_, token.dep_) for token in doc]
def get_tokens_with_lemma(self, text):
"""
Returns the list of tokens with lemma.
:param text: Text to analyze
:return: A list of tokens with lemma
"""
doc = self.nlp(text)
return [(token.text, token.lemma_) for token in doc]
def get_tokens_with_lemma_as_string(self, text):
"""
Returns the list of tokens with lemma as a string.
:param text: Text to analyze
:return: A string of tokens with lemma
"""
doc = self.nlp(text)
return str([(token.text, token.lemma_) for token in doc])
def get_tokens_with_lemma_as_json(self, text):
"""
Returns the list of tokens with lemma as a JSON string.
:param text: Text to analyze
:return: A JSON string of tokens with lemma
"""
doc = self.nlp(text)
return json.dumps([(token.text, token.lemma_) for token in doc])
def get_tokens_with_lemma_as_dict(self, text):
"""
Returns the list of tokens with lemma as a dictionary.
:param text: Text to analyze
:return: A dictionary of tokens with lemma
"""
doc = self.nlp(text)
return [(token.text, token.lemma_) for token in doc]
def get_tokens_with_lemma_as_list(self, text):
"""
Returns the list of tokens with lemma as a list.
:param text: Text to analyze
:return: A list of tokens with lemma
"""
doc = self.nlp(text)
return [(token.text, token.lemma_) for token in doc]
def get_tokens_with_lemma_and_pos(self, text):
"""
Returns the list of tokens with lemma and POS.
:param text: Text to analyze
:return: A list of tokens with lemma and POS
"""
doc = self.nlp(text)
return [(token.text, token.lemma_, token.pos_) for token in doc]
def get_tokens_with_lemma_and_pos_as_string(self, text):
"""
Returns the list of tokens with lemma and POS as a string.
:param text: Text to analyze
:return: A string of tokens with lemma and POS
"""
doc = self.nlp(text)
return str([(token.text, token.lemma_, token.pos_) for token in doc])
def get_tokens_with_lemma_and_pos_as_json(self, text):
"""
Returns the list of tokens with lemma and POS as a JSON string.
:param text: Text to analyze
:return: A JSON string of tokens with lemma and POS
"""
doc = self.nlp(text)
return json.dumps([(token.text, token.lemma_, token.pos_) for token in doc])
def get_tokens_with_lemma_and_pos_as_dict(self, text):
"""
Returns the list of tokens with lemma and POS as a dictionary.
:param text: Text to analyze
:return: A dictionary of tokens with lemma and POS
"""
doc = self.nlp(text)
return [(token.text, token.lemma_, token.pos_) for token in doc]
def get_tokens_with_lemma_and_pos_as_list(self, text):
"""
Returns the list of tokens with lemma and POS as a list.
:param text: Text to analyze
:return: A list of tokens with lemma and POS
"""
doc = self.nlp(text)
return [(token.text, token.lemma_, token.pos_) for token in doc]
def get_tokens_with_lemma_and_pos_and_dep(self, text):
"""
Returns the list of tokens with lemma, POS and dependency.
:param text: Text to analyze
:return: A list of tokens with lemma, POS and dependency
"""
doc = self.nlp(text)
return [(token.text, token.lemma_, token.pos_, token.dep_) for token in doc]
def get_tokens_with_lemma_and_pos_and_dep_as_string(self, text):
"""
Returns the list of tokens with lemma, POS and dependency as a string.
:param text: Text to analyze
:return: A string of tokens with lemma, POS and dependency
"""
doc = self.nlp(text)
return str([(token.text, token.lemma_, token.pos_, token.dep_) for token in doc])
def get_tokens_with_lemma_and_pos_and_dep_as_json(self, text):
"""
Returns the list of tokens with lemma, POS and dependency as a JSON string.
:param text: Text to analyze
:return: A JSON string of tokens with lemma, POS and dependency
"""
doc = self.nlp(text)
return json.dumps([(token.text, token.lemma_, token.pos_, token.dep_) for token in doc])
def get_tokens_with_lemma_and_pos_and_dep_as_dict(self, text):
"""
Returns the list of tokens with lemma, POS and dependency as a dictionary.
:param text: Text to analyze
:return: A dictionary of tokens with lemma, POS and dependency
"""
doc = self.nlp(text)
return [(token.text, token.lemma_, token.pos_, token.dep_) for token in doc]
def get_tokens_with_lemma_and_pos_and_dep_as_list(self, text):
"""
Returns the list of tokens with lemma, POS and dependency as a list.
:param text: Text to analyze
:return: A list of tokens with lemma, POS and dependency
"""
doc = self.nlp(text)
return [(token.text, token.lemma_, token.pos_, token.dep_) for token in doc]
def get_tokens_with_lemma_and_pos_and_dep_and_shape(self, text):
"""
Returns the list of tokens with lemma, POS, dependency and shape.
:param text: Text to analyze
:return: A list of tokens with lemma, POS, dependency and shape
"""
doc = self.nlp(text)
return [(token.text, token.lemma_, token.pos_, token.dep_, token.shape_) for token in doc]
def get_tokens_with_lemma_and_pos_and_dep_and_shape_as_string(self, text):
"""
Returns the list of tokens with lemma, POS, dependency and shape as a string.
:param text: Text to analyze
:return: A string of tokens with lemma, POS, dependency and shape
"""
doc = self.nlp(text)
return str([(token.text, token.lemma_, token.pos_, token.dep_, token.shape_) for token in doc])
def get_tokens_with_lemma_and_pos_and_dep_and_shape_as_json(self, text):
"""
Returns the list of tokens with lemma, POS, dependency and shape as a JSON string.
:param text: Text to analyze
:return: A JSON string of tokens with lemma, POS, dependency and shape
"""
doc = self.nlp(text)
return json.dumps([(token.text, token.lemma_, token.pos_, token.dep_, token.shape_) for token in doc])
def get_tokens_with_lemma_and_pos_and_dep_and_shape_as_dict(self, text):
"""
Returns the list of tokens with lemma, POS, dependency and shape as a dictionary.
:param text: Text to analyze
:return: A dictionary of tokens with lemma, POS, dependency and shape
"""
doc = self.nlp(text)
return [(token.text, token.lemma_, token.pos_, token.dep_, token.shape_) for token in doc]
def get_tokens_with_lemma_and_pos_and_dep_and_shape_as_list(self, text):
"""
Returns the list of tokens with lemma, POS, dependency and shape as a list.
:param text: Text to analyze
:return: A list of tokens with lemma, POS, dependency and shape
"""
doc = self.nlp(text)
return [(token.text, token.lemma_, token.pos_, token.dep_, token.shape_) for token in doc]
def __create_config__(self):
"""
Fill the base_config.cfg file with remaining defaults and save it as config.cfg.
After you’ve saved the starter config to a file base_config.cfg, you can use the init fill-config command to fill in the remaining defaults. Training configs should always be complete and without hidden defaults, to keep your experiments reproducible.
"""
# Check if english model is present
nlp = None
try:
nlp = spacy.load("en_core_web_lg")
except Exception as e:
print("English model is not installed. Now downloading and installing...")
# Download the englisch model
subprocess.run("python -m spacy download en_core_web_lg", shell=True)
subprocess.run("python -m spacy init fill-config base_config.cfg config.cfg", shell=True)
def train(self, data, folder, model_name="model_best", language="en"):
"""
Train the model with the data from the given database.
:param data: The data to train the model with
:param folder: The folder to save the model to.
:param model_name: The name of the model. Default is "model_best".
:param language: The language of the data. Default is "en".
"""
nlp = spacy.blank(language)
cfglang = ""
# check if right language is used in config.cfg file
module_path = os.path.dirname(__file__)
cfg = module_path + "/config.cfg"
with open(cfg, "r") as f:
while True:
line = f.readline()
if not line:
break
if line.startswith("lang = "):
cfglang = line[7:].replace("\n", "")
break
if cfglang != language:
# replace the language in the config.cfg file
with open(cfg, "r") as f:
lines = f.readlines()
with open(cfg, "w") as f:
for line in lines:
if line.startswith("lang = "):
f.write("lang = \"" + language + "\"\n")
else:
f.write(line)
# Get unique labels
labels = set([x[1] for x in data])
db = spacy.tokens.DocBin()
train = []
dev = []
all = []
for text, label in data:
doc = nlp.make_doc(text)
# set doc label
for lbl in labels:
if lbl == label:
doc.cats[lbl] = 1.0
else:
doc.cats[lbl] = 0.0
all.append(doc)
# The dev.spacy file should look exactly the same as the train.spacy file, but should contain new examples that the training process hasn't seen before to get a realistic evaluation of the performance of your model.
from spacy.cli.train import train
# split the training data to 20% dev data
if len(all) >= 5:
train_data, test_data = all[:int(len(all) * 0.2)], all[int(len(all) * 0.2):]
else:
train_data, test_data = all, all
# Create docbin
train_db = spacy.tokens.DocBin(docs=train_data)
dev_db = spacy.tokens.DocBin(docs=test_data)
# Delete files if they exist
if os.path.exists("./train.spacy"):
os.remove("./train.spacy")
if os.path.exists("./dev.spacy"):
os.remove("./dev.spacy")
train_db.to_disk("./train.spacy")
dev_db.to_disk("./dev.spacy")
train(config_path=cfg, output_path="./output")
# move the model to the given path
# delete the folder with the same name as the model_name if it exists
if os.path.exists(folder + "/" + model_name):
shutil.rmtree(folder + "/" + model_name)
source_dir = "./output/model-best"
shutil.copytree(source_dir, folder + "/" + model_name)
def load_model(self, model_path):
"""
Load the model from the given path.
:param model_path: The path to the model.
"""
self.nlp = spacy.load(model_path)
def save_model(self, model_path):
"""
Save the model to the given path.
:param model_path: The path to the model.
"""
self.nlp.to_disk(model_path)
def __load_data__(self, data_path):
"""
Load the data from the given path.
:param data_path: The path to the data.
"""
self.data = spacy.tokens.DocBin().from_disk(data_path)
def predict(self, text):
"""
Predict the label of the given text by using the already loaded model.
:param text: The text to predict.
:return: The predicted label.
"""
doc = self.nlp(text)
return max(doc.cats)
def data_to_jsonl(self, data: list, file_path: str):
"""
Saves the given data to a jsonl file.
:param data: The data to save.
:param file_path: The path to the file.
"""
with open(file_path, "w") as f:
for item in data:
f.write(json.dumps(item) + "\n")
def __get_data_from_database__(self, host, database, table_name):
"""
Get the data from the sql server database by using a generator with yield.
:param host: The host of the database.
:param database: The name of the database.
:param table_name: The name of the table in the database. This table must have columns named 'text' and 'label'.
:return: The data from the database.
"""
sqlserver = SQLserver.SQLserver(host, database)
results = sqlserver.sqlserver_query_and_get_results("SELECT * FROM " + table_name)
for result in results:
yield result.text, result.label
def train_from_sql_server_database(self, database, table_name, folder, model_name="model_best", host="localhost", language="en"):
"""
Train the model with the data from the given database.
:param host: Optional. The host of the database. Default is "localhost".
:param database: The path to the database.
:param table_name: The name of the table in the database. This table must have columns named 'text' and 'label'.
:param folder: The folder to save the model to.
:param model_name: The name of the model. Default is "model_best".
:param language: The language of the data. Default is "en".
"""
nlp = spacy.blank(language)
cfglang = ""
# check if right language is used in config.cfg file in the same folder as this module
module_path = os.path.dirname(__file__)
cfg = module_path + "./config.cfg"
with open(cfg, "r") as f:
print("opened")
while True:
line = f.readline()
if not line:
break
if line.startswith("lang = "):
cfglang = line[7:].replace("\n", "")
break
if cfglang != language:
# replace the language in the config.cfg file
with open(cfg, "r") as f:
lines = f.readlines()
with open(cfg, "w") as f:
for line in lines:
if line.startswith("lang = "):
f.write("lang = \"" + language + "\"\n")
else:
f.write(line)
# Get unique labels
labels = set([x[1] for x in self.__get_data_from_database__(host, database, table_name)])
db = spacy.tokens.DocBin()
train = []
dev = []
all = []
for text, label in self.__get_data_from_database__(host, database, table_name):
doc = nlp.make_doc(text)
# set doc label
for lbl in labels:
if lbl == label:
doc.cats[lbl] = 1.0
else:
doc.cats[lbl] = 0.0
all.append(doc)
# The dev.spacy file should look exactly the same as the train.spacy file, but should contain new examples that the training process hasn't seen before to get a realistic evaluation of the performance of your model.
from spacy.cli.train import train
# split the training data to 20% dev data
if len(all) >= 5:
train_data, test_data = all[:int(len(all) * 0.2)], all[int(len(all) * 0.2):]
else:
train_data, test_data = all, all
# Create docbin
train_db = spacy.tokens.DocBin(docs=train_data)
dev_db = spacy.tokens.DocBin(docs=test_data)
# Delete files if they exist
if os.path.exists("./train.spacy"):
os.remove("./train.spacy")
if os.path.exists("./dev.spacy"):
os.remove("./dev.spacy")
train_db.to_disk("./train.spacy")
dev_db.to_disk("./dev.spacy")
train(config_path=cfg, output_path="./output")
# move the model to the given path
# delete the folder with the same name as the model_name if it exists
if os.path.exists(folder + "/" + model_name):
shutil.rmtree(folder + "/" + model_name)
source_dir = "./output/model-best"
shutil.copytree(source_dir, folder + "/" + model_name) | PypiClean |
/dirtrav-1.0.0.tar.gz/dirtrav-1.0.0/docs/appcontext.rst | .. currentmodule:: flask
The Application Context
=======================
The application context keeps track of the application-level data during
a request, CLI command, or other activity. Rather than passing the
application around to each function, the :data:`current_app` and
:data:`g` proxies are accessed instead.
This is similar to :doc:`/reqcontext`, which keeps track of
request-level data during a request. A corresponding application context
is pushed when a request context is pushed.
Purpose of the Context
----------------------
The :class:`Flask` application object has attributes, such as
:attr:`~Flask.config`, that are useful to access within views and
:doc:`CLI commands </cli>`. However, importing the ``app`` instance
within the modules in your project is prone to circular import issues.
When using the :doc:`app factory pattern </patterns/appfactories>` or
writing reusable :doc:`blueprints </blueprints>` or
:doc:`extensions </extensions>` there won't be an ``app`` instance to
import at all.
Flask solves this issue with the *application context*. Rather than
referring to an ``app`` directly, you use the :data:`current_app`
proxy, which points to the application handling the current activity.
Flask automatically *pushes* an application context when handling a
request. View functions, error handlers, and other functions that run
during a request will have access to :data:`current_app`.
Flask will also automatically push an app context when running CLI
commands registered with :attr:`Flask.cli` using ``@app.cli.command()``.
Lifetime of the Context
-----------------------
The application context is created and destroyed as necessary. When a
Flask application begins handling a request, it pushes an application
context and a :doc:`request context </reqcontext>`. When the request
ends it pops the request context then the application context.
Typically, an application context will have the same lifetime as a
request.
See :doc:`/reqcontext` for more information about how the contexts work
and the full life cycle of a request.
Manually Push a Context
-----------------------
If you try to access :data:`current_app`, or anything that uses it,
outside an application context, you'll get this error message:
.. code-block:: pytb
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that
needed to interface with the current application object in some way.
To solve this, set up an application context with app.app_context().
If you see that error while configuring your application, such as when
initializing an extension, you can push a context manually since you
have direct access to the ``app``. Use :meth:`~Flask.app_context` in a
``with`` block, and everything that runs in the block will have access
to :data:`current_app`. ::
def create_app():
app = Flask(__name__)
with app.app_context():
init_db()
return app
If you see that error somewhere else in your code not related to
configuring the application, it most likely indicates that you should
move that code into a view function or CLI command.
Storing Data
------------
The application context is a good place to store common data during a
request or CLI command. Flask provides the :data:`g object <g>` for this
purpose. It is a simple namespace object that has the same lifetime as
an application context.
.. note::
The ``g`` name stands for "global", but that is referring to the
data being global *within a context*. The data on ``g`` is lost
after the context ends, and it is not an appropriate place to store
data between requests. Use the :data:`session` or a database to
store data across requests.
A common use for :data:`g` is to manage resources during a request.
1. ``get_X()`` creates resource ``X`` if it does not exist, caching it
as ``g.X``.
2. ``teardown_X()`` closes or otherwise deallocates the resource if it
exists. It is registered as a :meth:`~Flask.teardown_appcontext`
handler.
For example, you can manage a database connection using this pattern::
from flask import g
def get_db():
if 'db' not in g:
g.db = connect_to_database()
return g.db
@app.teardown_appcontext
def teardown_db(exception):
db = g.pop('db', None)
if db is not None:
db.close()
During a request, every call to ``get_db()`` will return the same
connection, and it will be closed automatically at the end of the
request.
You can use :class:`~werkzeug.local.LocalProxy` to make a new context
local from ``get_db()``::
from werkzeug.local import LocalProxy
db = LocalProxy(get_db)
Accessing ``db`` will call ``get_db`` internally, in the same way that
:data:`current_app` works.
Events and Signals
------------------
The application will call functions registered with
:meth:`~Flask.teardown_appcontext` when the application context is
popped.
If :data:`~signals.signals_available` is true, the following signals are
sent: :data:`appcontext_pushed`, :data:`appcontext_tearing_down`, and
:data:`appcontext_popped`.
| PypiClean |
/OceanMonkey-1.0.0.tar.gz/OceanMonkey-1.0.0/oceanmonkey/core/template.py | import abc
import os
import string
import oceanmonkey
class Template(abc.ABC):
@abc.abstractmethod
def create(self):
""" """
class ProjectTemplate(Template):
def __init__(self, project_name):
self.__project_name = project_name
self.__project_template_path = os.path.join(
os.path.dirname(oceanmonkey.__file__), "templates", "project"
)
self.__monkeys_template_path = os.path.join(
os.path.dirname(oceanmonkey.__file__), "templates", "monkeys"
)
def create(self, monkey_name="WuKong"):
clean_project_name = os.path.basename(self.__project_name)
template_args = {"project_name": clean_project_name}
os.makedirs(os.path.join(self.__project_name, clean_project_name))
for root, dirs, files in os.walk(self.__project_template_path, topdown=False):
for name in files:
if not name.endswith(".cfg") and not name.endswith(".tmpl"):
continue
file_name = os.path.join(root, name)
template = string.Template(open(file_name, "r").read())
template = template.substitute(template_args)
if file_name.endswith(".cfg"):
with open(os.path.join(self.__project_name, "oceanmonkey.cfg"), "w") as f:
f.write(template)
elif file_name.endswith(".tmpl"):
basename = os.path.basename(file_name)
python_file_name = basename[:basename.find(".tmpl")]
with open(os.path.join(self.__project_name, clean_project_name,
python_file_name), "w") as f:
f.write(template)
monkeys = "monkeys"
template_args = {"monkey_name": monkey_name}
os.makedirs(os.path.join(self.__project_name, clean_project_name, monkeys))
for root, dirs, files in os.walk(self.__monkeys_template_path, topdown=False):
for name in files:
if not name.endswith(".tmpl"):
continue
file_name = os.path.join(root, name)
template = string.Template(open(file_name, "r").read())
template = template.substitute(template_args)
basename = os.path.basename(file_name)
python_file = basename[:basename.find(".tmpl")]
with open(os.path.join(self.__project_name, clean_project_name,monkeys,
python_file), "w") as f:
f.write(template) | PypiClean |
/Nuitka-1.8.tar.gz/Nuitka-1.8/nuitka/build/inline_copy/jinja2/jinja2/exceptions.py | from jinja2._compat import imap, text_type, PY2, implements_to_string
class TemplateError(Exception):
"""Baseclass for all template errors."""
if PY2:
def __init__(self, message=None):
if message is not None:
message = text_type(message).encode('utf-8')
Exception.__init__(self, message)
@property
def message(self):
if self.args:
message = self.args[0]
if message is not None:
return message.decode('utf-8', 'replace')
def __unicode__(self):
return self.message or u''
else:
def __init__(self, message=None):
Exception.__init__(self, message)
@property
def message(self):
if self.args:
message = self.args[0]
if message is not None:
return message
@implements_to_string
class TemplateNotFound(IOError, LookupError, TemplateError):
"""Raised if a template does not exist."""
# looks weird, but removes the warning descriptor that just
# bogusly warns us about message being deprecated
message = None
def __init__(self, name, message=None):
IOError.__init__(self)
if message is None:
message = name
self.message = message
self.name = name
self.templates = [name]
def __str__(self):
return self.message
class TemplatesNotFound(TemplateNotFound):
"""Like :class:`TemplateNotFound` but raised if multiple templates
are selected. This is a subclass of :class:`TemplateNotFound`
exception, so just catching the base exception will catch both.
.. versionadded:: 2.2
"""
def __init__(self, names=(), message=None):
if message is None:
message = u'none of the templates given were found: ' + \
u', '.join(imap(text_type, names))
TemplateNotFound.__init__(self, names and names[-1] or None, message)
self.templates = list(names)
@implements_to_string
class TemplateSyntaxError(TemplateError):
"""Raised to tell the user that there is a problem with the template."""
def __init__(self, message, lineno, name=None, filename=None):
TemplateError.__init__(self, message)
self.lineno = lineno
self.name = name
self.filename = filename
self.source = None
# this is set to True if the debug.translate_syntax_error
# function translated the syntax error into a new traceback
self.translated = False
def __str__(self):
# for translated errors we only return the message
if self.translated:
return self.message
# otherwise attach some stuff
location = 'line %d' % self.lineno
name = self.filename or self.name
if name:
location = 'File "%s", %s' % (name, location)
lines = [self.message, ' ' + location]
# if the source is set, add the line to the output
if self.source is not None:
try:
line = self.source.splitlines()[self.lineno - 1]
except IndexError:
line = None
if line:
lines.append(' ' + line.strip())
return u'\n'.join(lines)
class TemplateAssertionError(TemplateSyntaxError):
"""Like a template syntax error, but covers cases where something in the
template caused an error at compile time that wasn't necessarily caused
by a syntax error. However it's a direct subclass of
:exc:`TemplateSyntaxError` and has the same attributes.
"""
class TemplateRuntimeError(TemplateError):
"""A generic runtime error in the template engine. Under some situations
Jinja may raise this exception.
"""
class UndefinedError(TemplateRuntimeError):
"""Raised if a template tries to operate on :class:`Undefined`."""
class SecurityError(TemplateRuntimeError):
"""Raised if a template tries to do something insecure if the
sandbox is enabled.
"""
class FilterArgumentError(TemplateRuntimeError):
"""This error is raised if a filter was called with inappropriate
arguments
""" | PypiClean |
/Gnosis_Utils-1.2.2.tar.gz/Gnosis_Utils-1.2.2/gnosis/util/introspect.py |
import gnosis.pyconfig
def docstrings():
if not gnosis.pyconfig.Can_AssignDoc(): return
"""
containers.__doc__ = "A tuple of built-in types that contain parts"
simpletypes.__doc__ = "A tuple of built-in types that have no parts"
datatypes.__doc__ = "A tuple of all the built-in types that hold data"
immutabletypes.__doc__="A tuple of built-in types that are immutable"
"""
isContainer.__doc__ = "this and that"
import sys, string
from types import *
from operator import add
from gnosis.util.combinators import or_, not_, and_, lazy_any
containers = (ListType, TupleType, DictType)
simpletypes = (IntType, LongType, FloatType, ComplexType, StringType)
if gnosis.pyconfig.Have_Unicode():
simpletypes = simpletypes + (UnicodeType,)
datatypes = simpletypes+containers
immutabletypes = simpletypes+(TupleType,)
class undef: pass
def isinstance_any(o, types):
"A varargs form of isinstance()"
for t in types:
if isinstance(o, t): return t
isContainer = lambda o: isinstance_any(o, containers)
isSimpleType = lambda o: isinstance_any(o, simpletypes)
isInstance = lambda o: type(o) is InstanceType
isImmutable = lambda o: isinstance_any(o, immutabletypes)
if gnosis.pyconfig.Have_ObjectClass():
isNewStyleInstance = lambda o: issubclass(o.__class__,object) and \
not type(o) in datatypes
else:
isNewStyleInstance = lambda o: 0
isOldStyleInstance = lambda o: isinstance(o, ClassType)
isClass = or_(isOldStyleInstance, isNewStyleInstance)
if gnosis.pyconfig.Have_ObjectClass():
def isNewStyleClass(o):
try:
# would give a NameError on Python <= 2.1
return issubclass(o,object)
except TypeError:
return 0
else:
def isNewStyleClass(o):
return 0
hasSlots = lambda o: hasattr(o,'__slots__')
hasInit = lambda o: hasattr(o,'__init__')
hasDictAttrs = lambda o: (hasattr(o,'__dict__') and o.__dict__)
isInstanceLike = lazy_any(isInstance, hasDictAttrs, hasSlots)
hasCompoundShape = and_(isInstanceLike, not_(isInstance))
true_container = lambda o: type(o) in containers
true_simpletype = lambda o: type(o) in simpletypes
true_datatype = or_(true_container, true_simpletype)
child_container = and_(not_(true_container), isContainer)
child_simpletype = and_(not_(true_simpletype), isSimpleType)
child_datatype = or_(child_container, child_simpletype)
def hasCoreData(o):
"""Is 'o' an object subclassed from a builtin type?
(i.e. does it contain data other than attributes)
We only want subclasses, not the class itself (otherwise we'd
catch ALL lists, integers, etc.)
"""
return child_datatype(o)
# semantic convenience - maybe it'll do something else later?
wantsCoreData = hasCoreData
def attr_dict(o, fillslots=0):
if hasattr(o,'__dict__'):
return o.__dict__
elif hasattr(o,'__slots__'):
dct = {}
for attr in o.__slots__:
if fillslots and not hasattr(o, attr):
setattr(o, attr, undef())
dct[attr] = getattr(o,attr)
elif hasattr(o, attr):
dct[attr] = getattr(o,attr)
return dct
else:
raise TypeError, "Object has neither __dict__ nor __slots__"
attr_keys = lambda o: attr_dict(o).keys()
attr_vals = lambda o: attr_dict(o).values()
def attr_update(o,new):
for k,v in new.items():
setattr(o,k,v)
def data2attr(o):
"COPY (not move) data to __coredata__ 'magic' attribute"
o.__coredata__ = getCoreData(o)
return o
def attr2data(o):
"Move 'magic' attribute back to 'core' data"
if hasattr(o,'__coredata__'):
o = setCoreData(o, o.__coredata__)
del o.__coredata__
return o
def setCoreData(o, data, force=0):
"Set core data of obj subclassed from a builtin type, return obj"
#-- Only newobjects unless force'd
if not force and not wantsCoreData(o): pass
#-- Tuple and simpletypes are immutable (need new copy)!
elif isImmutable(o):
# Python appears to guarantee that all classes subclassed
# from immutables must take one and only one argument
# to __init__ [calling __init__() is not usually allowed
# when unpickling] ... lucky us :-)
new = o.__class__(data)
attr_update(new, attr_dict(o)) # __slots__ safe attr_dict()
o = new
elif isinstance(o, DictType):
o.clear()
o.update(data)
elif isinstance(o, ListType):
o[:] = data
return o
def getCoreData(o):
"Return the core data of object subclassed from builtin type"
if hasCoreData(o):
return isinstance_any(o, datatypes)(o)
else:
raise TypeError, "Unhandled type in getCoreData for: ", o
def instance_noinit(C):
"""Create an instance of class C without calling __init__
[Note: This function was greatly simplified in gnosis-1.0.7,
but I'll leave these notes here for future reference.]
We go to some lengths here to avoid calling __init__. It
gets complicated because we cannot always do the same thing;
it depends on whether there are __slots__, and even whether
__init__ is defined in a class or in its parent. Even still,
there are ways to construct *highly artificial* cases where
the wrong thing happens.
If you change this, make sure ALL test cases still work ...
easy to break things
"""
if isOldStyleInstance(C):
import new
# 2nd arg is required for Python 2.0 (optional for 2.1+)
return new.instance(C,{})
elif isNewStyleInstance(C):
return C.__new__(C)
else:
raise TypeError, "You must specify a class to create instance of."
if __name__ == '__main__':
"We could use some could self-tests (see test/ subdir though)"
else:
docstrings() | PypiClean |
/BlueWhale3-3.31.3.tar.gz/BlueWhale3-3.31.3/Orange/clustering/clustering.py | import numpy as np
import scipy.sparse
from Orange.data import Table, Instance
from Orange.data.table import DomainTransformationError
from Orange.misc.wrapper_meta import WrapperMeta
from Orange.preprocess import Continuize, SklImpute
class ClusteringModel:
def __init__(self, projector):
self.projector = projector
self.domain = None
self.original_domain = None
self.labels = projector.labels_
def __call__(self, data):
def fix_dim(x):
return x[0] if one_d else x
one_d = False
if isinstance(data, np.ndarray):
one_d = data.ndim == 1
prediction = self.predict(np.atleast_2d(data))
elif isinstance(data, scipy.sparse.csr.csr_matrix) or \
isinstance(data, scipy.sparse.csc.csc_matrix):
prediction = self.predict(data)
elif isinstance(data, (Table, Instance)):
if isinstance(data, Instance):
data = Table.from_list(data.domain, [data])
one_d = True
if data.domain != self.domain:
if self.original_domain.attributes != data.domain.attributes \
and data.X.size \
and not np.isnan(data.X).all():
data = data.transform(self.original_domain)
if np.isnan(data.X).all():
raise DomainTransformationError(
"domain transformation produced no defined values")
data = data.transform(self.domain)
prediction = self.predict(data.X)
elif isinstance(data, (list, tuple)):
if not isinstance(data[0], (list, tuple)):
data = [data]
one_d = True
data = Table.from_list(self.original_domain, data)
data = data.transform(self.domain)
prediction = self.predict(data.X)
else:
raise TypeError("Unrecognized argument (instance of '{}')"
.format(type(data).__name__))
return fix_dim(prediction)
def predict(self, X):
raise NotImplementedError(
"This clustering algorithm does not support predicting.")
class Clustering(metaclass=WrapperMeta):
"""
${skldoc}
Additional Orange parameters
preprocessors : list, optional (default = [Continuize(), SklImpute()])
An ordered list of preprocessors applied to data before
training or testing.
"""
__wraps__ = None
__returns__ = ClusteringModel
preprocessors = [Continuize(), SklImpute()]
def __init__(self, preprocessors, parameters):
self.preprocessors = preprocessors if preprocessors is not None else self.preprocessors
self.params = {k: v for k, v in parameters.items()
if k not in ["self", "preprocessors", "__class__"]}
def __call__(self, data):
return self.get_model(data).labels
def get_model(self, data):
orig_domain = data.domain
data = self.preprocess(data)
model = self.fit_storage(data)
model.domain = data.domain
model.original_domain = orig_domain
return model
def fit_storage(self, data):
# only data Table
return self.fit(data.X)
def fit(self, X: np.ndarray, y: np.ndarray = None):
return self.__returns__(self.__wraps__(**self.params).fit(X))
def preprocess(self, data):
for pp in self.preprocessors:
data = pp(data)
return data | PypiClean |
/BubbleTea-py-0.0.7.tar.gz/BubbleTea-py-0.0.7/README.md | Bubbletea
--
A python library which enables developers and data scientists to quickly build any data applications on top of The Graph network. Whether you are building dashboards to visualize protocol data or leveraging existing machine learning models to do some data science work, we hope this library will be the fastest way to get what you want.
This project is made possible by a grant (wave 2) from The Graph foundation.
### What problems are we solving
- An improved way to query data from The Graph network
- A set of handy functions for common data transformations (built on Pandas)
- A set of out-of-box charting components to make visualizations effortless (built on Altair)
- A simple templating system to build dashboards (built on Streamlit)
### Install
pip install BubbleTea-py
### [Demos](https://bubbletea-demo.herokuapp.com/?demo=demo_1.py)
### [Documentation](https://scout-1.gitbook.io/bubbletea/)
### Get in touch
https://twitter.com/scout_cool
| PypiClean |
/ChadBot6-0.1-py3-none-any.whl/ChadBot/generation/rajat_work/qgen/generator/symsub.py | import string
from itertools import product
import numpy as np
from nltk.corpus import stopwords
from nltk.corpus import wordnet as wn
from tqdm import tqdm
from .base import BaseGenerator
import sys
from ..util.nlp import get_spacy_model
class SymSubGenerator(BaseGenerator):
""" Generate questions via sense-disambiguated synonyms substitution. """
def __init__(self, encoder, discount_factor=0.5, threshold=0.5):
"""
:param encoder: encoder for the computation of sentence embeddings
:param discount_factor: discount factor for weightage calculation during word sense disambiguation (wsd)
:param threshold: threshold value ranging from 0 to 1 for wsd score.
"""
super().__init__("Sense-disambiguated Synonym Substitution")
self.encoder = encoder
self.discount_factor = discount_factor
self.threshold = threshold
def _get_best_sense_key(self, sentence, lemma, pos):
def _compute_weightage(main_synset, related_synset):
distance = main_synset.shortest_path_distance(related_synset)
if distance is None:
return 1
else:
return 1 / (1 + distance)
wordnet_pos = {'VERB': wn.VERB, 'NOUN': wn.NOUN, 'ADJ': wn.ADJ, 'ADV': wn.ADV}
if pos not in wordnet_pos:
return None
results = [] # tuple of lemma and average similarity score
lemma_count = 0
for synset in wn.synsets(lemma, pos=wordnet_pos[pos]):
if lemma.lower() not in [l.name().lower() for l in synset.lemmas()]:
continue
extended_gloss = {synset.definition(): 1} # gloss and weightage map
for s in synset.hypernyms():
extended_gloss[s.definition()] = _compute_weightage(synset, s)
for e in s.examples():
extended_gloss[e] = extended_gloss[s.definition()] * self.discount_factor
for s in synset.hyponyms():
extended_gloss[s.definition()] = _compute_weightage(synset, s)
for e in s.examples():
extended_gloss[e] = extended_gloss[s.definition()] * self.discount_factor
for s in synset.verb_groups():
extended_gloss[s.definition()] = _compute_weightage(synset, s)
for e in s.examples():
extended_gloss[e] = extended_gloss[s.definition()] * self.discount_factor
for s in synset.similar_tos():
extended_gloss[s.definition()] = _compute_weightage(synset, s)
for e in s.examples():
extended_gloss[e] = extended_gloss[s.definition()] * self.discount_factor
for lemma_ in synset.lemmas():
if lemma_.name().lower() == lemma.lower():
for s in [l.synset() for l in lemma_.derivationally_related_forms()]:
extended_gloss[s.definition()] = _compute_weightage(synset, s)
break
for e in synset.examples():
extended_gloss[e] = 1
sentences = [sentence] + list(extended_gloss.keys())
embeddings = self.encoder.get_vectors(sentences)
similarity_matrix = np.inner(embeddings, embeddings)
score = 0
weightage = list(extended_gloss.values())
for i in range(1, len(similarity_matrix)):
score += similarity_matrix[0][i] * weightage[i - 1]
for lemma_ in synset.lemmas():
if lemma_.name().lower() == lemma.lower():
lemma_count += lemma_.count()
results.append((lemma_, score))
break
if not results:
return None
sense_count = len(results)
results = [(l.key(), s * ((l.count() + 1) / (lemma_count + sense_count))) for l, s in results]
return sorted(results, key=lambda r: r[1], reverse=True)[0][0]
def _get_synonyms(self, spacy_doc, word):
sentence = spacy_doc.text
if not sentence or not word or word.lower() in stopwords.words('english') or len(word.split()) > 1:
return []
# ignore `word` that is a part of noun_chunk
for noun_chunk in spacy_doc.noun_chunks:
tokens = [t.strip(string.punctuation) for t in noun_chunk.text.split()
if t.strip(string.punctuation).lower() not in stopwords.words('english')]
if len(tokens) > 1 and word in tokens:
return []
for token in spacy_doc:
if token.text == word:
key = self._get_best_sense_key(sentence, token.lemma_, token.pos_)
if key is None:
return []
else:
return [w.replace("_", " ") for w in wn.lemma_from_key(key).synset().lemma_names()
if w.lower() != word.lower()]
def generate(self, sentence):
return list(self.batch_generate([sentence], use_tqdm=False).values())[0]
def batch_generate(self, sentences, use_tqdm=True):
results = dict()
nlp = get_spacy_model()
with nlp.disable_pipes('ner'):
docs = nlp.pipe(sentences)
for doc in (tqdm(docs, total=len(sentences)) if use_tqdm else docs):
sentence = doc.text
tokens = [token.text for token in doc]
tokens_for_sub = [token for token in tokens if tokens.count(token) == 1]
token2synonyms = dict()
for token in tokens_for_sub:
syms = self._get_synonyms(doc, token)
if syms:
token2synonyms[token] = [token] + syms
result = []
keys = list(token2synonyms.keys())
combinations = product(*token2synonyms.values())
next(combinations) # skip the first combination as it contains all original tokens
for combination in combinations:
temp = tokens.copy()
for i, sub_token in enumerate(combination):
key = keys[i]
temp[temp.index(key)] = sub_token
sent = ' '.join(temp).strip('?').strip() + "?"
if sent != sentence:
result.append(sent)
results[sentence] = result
return results | PypiClean |
/Finance-Ultron-1.0.8.1.tar.gz/Finance-Ultron-1.0.8.1/ultron/ump/trade/capital.py | import numpy as np
import pandas as pd
from ultron.kdutils import date as date_utils
from ultron.utilities.logger import kd_logger
from ultron.kdutils.progress import Progress
from ultron.ump.core.base import PickleStateMixin
from ultron.ump.trade.commission import Commission
from ultron.ump.trade.order import Order
class Capital(PickleStateMixin):
"""资金类"""
def __init__(self, init_cash, benchmark, user_commission_dict=None):
"""
:param init_cash: 初始资金值,注意这里不区分美元,人民币等类型,做美股交易默认当作美元,a股默认当作人民币,int
:param benchmark: 资金回测时间标尺,做为资金类表格时间范围确定使用,AbuBenchmark实例对象
:param user_commission_dict: dict对象,可自定义交易手续费计算方法,详情查看AbuCommission
"""
self.read_cash = init_cash
kl_pd = benchmark.kl_pd
if kl_pd is None:
# 要求基准必须有数据
raise ValueError('CapitalClass init klPd is None')
# 根据基准时间序列,制作相同的时序资金对象capital_pd(pd.DcataFrame对象)
self.capital_pd = pd.DataFrame(
{
'cash_blance': np.NAN * kl_pd.shape[0],
'stocks_blance': np.zeros(kl_pd.shape[0]),
'atr21': kl_pd['atr21'],
'date': kl_pd['date']
},
index=kl_pd.index)
self.capital_pd['date'] = self.capital_pd['date'].astype(int)
# cash_blance除了第一个其它都是nan
self.capital_pd.loc[self.capital_pd.index[0],
'cash_blance'] = self.read_cash
# 构造交易手续费对象AbuCommission,如果user自定义手续费计算方法,通过user_commission_dict传入
self.commission = Commission(user_commission_dict)
def __str__(self):
"""打印对象显示:capital_pd.info commission_df.info"""
return 'capital_pd:\n{}\ncommission_pd:\n{}'.format(
self.capital_pd.info(), self.commission.commission_df.info())
__repr__ = __str__
def __len__(self):
"""对象长度:时序资金对象capital_pd的行数,即self.capital_pd.shape[0]"""
return self.capital_pd.shape[0]
def init_k_line(self, a_symbol):
"""
每一个交易对象在时序资金对象capital_pd上都添加对应的call keep(买涨持仓量),call worth(买涨总价值),
put keep(买跌持仓量),put worth(买跌总价值)
:param a_symbol: symbol str对象
"""
# 买涨持仓量
call_keep = '_call_keep'
if self.capital_pd.columns.tolist().count(a_symbol + call_keep) == 0:
self.capital_pd[a_symbol + call_keep] = np.NAN * \
self.capital_pd.shape[0]
# 买跌持仓量
put_keep = '_put_keep'
if self.capital_pd.columns.tolist().count(a_symbol + put_keep) == 0:
self.capital_pd[a_symbol + put_keep] = np.NAN * \
self.capital_pd.shape[0]
# 买涨总价值
call_worth = '_call_worth'
if self.capital_pd.columns.tolist().count(a_symbol + call_worth) == 0:
self.capital_pd[a_symbol + call_worth] = np.NAN * \
self.capital_pd.shape[0]
# 买跌总价值
put_worth = '_put_worth'
if self.capital_pd.columns.tolist().count(a_symbol + put_worth) == 0:
self.capital_pd[a_symbol + put_worth] = np.NAN * \
self.capital_pd.shape[0]
def apply_init_kl(self, action_pd, show_progress):
"""
根据回测交易在时序资金对象capital_pd上新建对应的call,put列
:param action_pd: 回测交易行为对象,pd.DataFrame对象
:param show_progress: 外部设置是否需要显示进度条
"""
# 使用set筛选唯一的symbol交易序列
symbols = set(action_pd.symbol)
# 单进程进度条
with Progress(len(symbols), 0, label='apply_init_kl...') as progress:
for pos, symbol in enumerate(symbols):
if show_progress:
progress.show(a_progress=pos + 1)
# 迭代symbols,新建对应的call,put列
self.init_k_line(symbol)
def apply_k_line(self, a_k_day, kl_pd, buy_type_head):
"""
在apply_kl中的do_apply_kl方法中时序资金对象capital进行apply的对应方法,
即迭代金融时间序列的每一个交易日,根据持仓量计算每一个交易日的市场价值
:param a_k_day: 每一个被迭代中的时间,即每一个交易日数据
:param kl_pd: 正在被apply迭代的金融时间序列本体,pd.DataFrame对象
:param buy_type_head: 代表交易类型,范围(_call,_put)
:return:
"""
if a_k_day[kl_pd.name + buy_type_head + '_keep'] > 0:
kl = kl_pd[kl_pd['date'] == a_k_day['date']]
if kl is None or kl.shape[0] == 0:
# 前提是当前交易日有对应的持仓
return
# 今天的收盘价格
td_close = kl['close'].values[0]
if buy_type_head == '_put':
# 针对buy put对价格进行转换,主要是针对put特殊处理
today_key = kl.key.values[0]
if today_key > 0:
yd_close = kl_pd.iloc[today_key - 1].close
# 如果是买跌,实时市场收益以昨天为基础进行计算,即*-1进行方向计算,以收益来映射重新定义今天的收盘价格
td_close = (td_close - yd_close) * -1 + yd_close
# 根据持仓量即处理后的今日收盘价格,进行今日价值计算
self.capital_pd.loc[kl.index, [kl_pd.name + buy_type_head + '_worth']] \
= np.round(td_close * a_k_day[kl_pd.name + buy_type_head + '_keep'], 3)
def apply_kl(self, action_pd, kl_pd_manager, show_progress):
"""
apply_action之后对实际成交的交易分别迭代更新时序资金对象capital_pd上每一个交易日的实时价值
:param action_pd: 回测结果生成的交易行为构成的pd.DataFrame对象
:param kl_pd_manager: 金融时间序列管理对象,AbuKLManager实例
:param show_progress: 是否显示进度条
"""
# 在apply_action之后形成deal列后,set出考虑资金下成交了的交易序列
deal_symbols_set = set(action_pd[action_pd['deal'] == 1].symbol)
def do_apply_kl(kl_pd, buy_type_head):
"""
根据金融时间序列在时序资金对象capital_pd上进行call(买涨),put(买跌)的交易日实时价值更新
:param kl_pd: 金融时间序列,pd.DataFrame对象
:param buy_type_head: 代表交易类型,范围(_call,_put)
"""
# cash_blance对na进行pad处理
self.capital_pd['cash_blance'].fillna(method='pad', inplace=True)
# symbol对应列持仓量对na进行处理
self.capital_pd[kl_pd.name + buy_type_head + '_keep'].fillna(
method='pad', inplace=True)
self.capital_pd[kl_pd.name + buy_type_head + '_keep'].fillna(
0, inplace=True)
# 使用apply在axis=1上,即每一个交易日上对持仓量及市场价值进行更新
self.capital_pd.apply(self.apply_k_line,
axis=1,
args=(kl_pd, buy_type_head))
# symbol对应列市场价值对na进行处理
self.capital_pd[kl_pd.name + buy_type_head + '_worth'].fillna(
method='pad', inplace=True)
self.capital_pd[kl_pd.name + buy_type_head + '_worth'].fillna(
0, inplace=True)
# 纠错处理把keep=0但是worth被pad的进行二次修正
fe_mask = (self.capital_pd[kl_pd.name + buy_type_head + '_keep']
== 0) & (self.capital_pd[kl_pd.name + buy_type_head +
'_worth'] > 0)
# 筛出需要纠错的index
fe_index = self.capital_pd[fe_mask].index
# 将需要纠错的对应index上市场价值进行归零处理
cp_w = self.capital_pd[kl_pd.name + buy_type_head + '_worth']
cp_w.loc[fe_index] = 0
# 单进程进度条
with Progress(len(deal_symbols_set), 0,
label='apply_kl...') as progress:
for pos, deal_symbol in enumerate(deal_symbols_set):
if show_progress:
progress.show(a_progress=pos + 1)
# 从kl_pd_manager中获取对应的金融时间序列kl,每一个kl分别进行call(买涨),put(买跌)的交易日实时价值更新
kl = kl_pd_manager.get_pick_time_kl_pd(deal_symbol)
# 进行call(买涨)的交易日实时价值更新
do_apply_kl(kl, '_call')
# 进行put(买跌)的交易日实时价值更新
do_apply_kl(kl, '_put')
def apply_action(self, a_action, progress):
"""
在回测结果生成的交易行为构成的pd.DataFrame对象上进行apply对应本方法,即
将交易行为根据资金情况进行处理,处理手续费以及时序资金对象capital_pd上的
数据更新
:param a_action: 每一个被迭代中的action,即每一个交易行为
:param progress: 进度条对象
:return: 是否成交deal bool
"""
# 区别买入行为和卖出行为
is_buy = True if a_action['action'] == 'buy' else False
# 从action数据构造Order对象
order = Order()
order.buy_symbol = a_action['symbol']
order.buy_cnt = a_action['Cnt']
if is_buy:
# 如果是买单,sell_price = price2 ,详情阅读ABuTradeExecute中transform_action
order.buy_price = a_action['Price']
order.sell_price = a_action['Price2']
else:
# 如果是卖单,buy_price = price2 ,详情阅读ABuTradeExecute中transform_action
order.sell_price = a_action['Price']
order.buy_price = a_action['Price2']
# 交易发生的时间
order.buy_date = a_action['Date']
order.sell_date = a_action['Date']
# 交易的方向
order.expect_direction = a_action['Direction']
# 对买单和卖单分别进行处理,确定是否成交deal
deal = self.buy_stock(order) if is_buy else self.sell_stock(order)
if progress is not None:
progress.show()
return deal
def buy_stock(self, a_order):
"""
在apply_action中每笔交易进行处理,根据买单计算cost,在时序资金对象capital_pd上修改对应cash_blance,
以及更新对应symbol上的持仓量
:param a_order: 在apply_action中由action转换的AbuOrder对象
:return: 是否成交deal bool
"""
# 首先使用commission对象计算手续费
with self.commission.buy_commission_func(a_order) as (buy_func,
commission_list):
commission = buy_func(a_order.buy_cnt, a_order.buy_price)
# 将上下文管理器中返回的commission_list中添加计算结果commission,内部根据list长度决定写入手续费记录pd.DataFrame
commission_list.append(commission)
# cost = 买单数量 * 单位价格 + 手续费
order_cost = a_order.buy_cnt * a_order.buy_price + commission
# 买单时间转换成pd时间日期对象
time_ind = pd.to_datetime(date_utils.fmt_date(a_order.buy_date))
# pd时间日期对象置换出对应的index number
num_index = self.capital_pd.index.tolist().index(time_ind)
# cash_blance初始化init中除了第一个其它都是nan
cash_blance = self.capital_pd['cash_blance'].dropna()
# 先截取cash_blance中 < time_ind的时间序列
bl_ss = cash_blance[cash_blance.index <= time_ind]
if bl_ss is None or bl_ss.shape[0] == 0:
kd_logger.info('bl_ss.shape[0] == 0 ' + str(a_order.buy_date))
return False
# 截取的bl_ss中选中最后一个元素做为判定买入时刻的cash值
cash = bl_ss.iloc[-1]
# 判定买入时刻的cash值是否能够钱买入
if cash >= order_cost and a_order.buy_cnt > 0:
# 够的话,买入,先将cash - cost
cash -= order_cost
# 根据a_order.expect_direction确定是要更新call的持仓量还是put的持仓量
buy_type_keep = '_call_keep' if a_order.expect_direction == 1.0 else '_put_keep'
# 前提1: 资金时间序列中有这个a_order.buy_symbol + buy_type_keep列
has_cond1 = self.capital_pd.columns.tolist().count(
a_order.buy_symbol + buy_type_keep) > 0
# 前提2: 对应这个列从单子买入日期index开始,在dropna后还有shape说明本就有持仓
has_cond2 = self.capital_pd[
a_order.buy_symbol +
buy_type_keep].iloc[:num_index + 1].dropna().shape[0] > 0
keep_cnt = 0
if has_cond1 and has_cond2:
# 前提1 + 前提2->本就有持仓, 拿到之前的持仓量
keep_cnt = self.capital_pd[a_order.buy_symbol +
buy_type_keep].iloc[:num_index +
1].dropna()[-1]
keep_cnt += a_order.buy_cnt
# TODO 这里迁移之前逻辑,删除了一些未迁移模块的逻辑,所以看起来多写了一个流程,需要重构逻辑
# 将计算好的cash更新到资金时间序列中对应的位置
self.capital_pd.loc[time_ind, ['cash_blance']] = np.round(cash, 3)
# 资金时间序列中之后的cash_blance也对应开始减去order_cost
self.capital_pd.loc[cash_blance[cash_blance.index > time_ind].index, ['cash_blance']] \
-= order_cost
# 在更新持仓量前,取出之前的数值
org_cnt = self.capital_pd.loc[time_ind][a_order.buy_symbol +
buy_type_keep]
# 更新持仓量
self.capital_pd.loc[time_ind, [a_order.buy_symbol +
buy_type_keep]] = keep_cnt
if not np.isnan(org_cnt):
# 对多个因子作用在同一个symbol上,且重叠了持股时间提前更新之后的持仓量
keep_pos = self.capital_pd[a_order.buy_symbol +
buy_type_keep].dropna()
self.capital_pd.loc[keep_pos[keep_pos.index > time_ind].index, [a_order.buy_symbol + buy_type_keep]] \
+= a_order.buy_cnt
return True
else:
return False
def sell_stock(self, a_order):
"""
在apply_action中每笔交易进行处理,根据卖单计算cost,在时序资金对象capital_pd上修改对应cash_blance,
以及更新对应symbol上的持仓量
:param a_order: 在apply_action中由action转换的AbuOrder对象
:return: 是否成交deal bool
"""
# 卖单时间转换成pd时间日期对象
time_ind = pd.to_datetime(date_utils.fmt_date(a_order.sell_date))
# # pd时间日期对象置换出对应的index number
num_index = self.capital_pd.index.tolist().index(time_ind)
# 根据a_order.expect_direction确定是要更新call的持仓量还是put的持仓量
buy_type_keep = '_call_keep' if a_order.expect_direction == 1.0 else '_put_keep'
# 前提1: 资金时间序列中有这个a_order.buy_symbol + buy_type_keep列
has_cond1 = self.capital_pd.columns.tolist().count(a_order.buy_symbol +
buy_type_keep) > 0
# 前提2: 对应这个列从单子买入日期index开始,在dropna后还有shape说明本就有持仓
has_cond2 = self.capital_pd[
a_order.buy_symbol + buy_type_keep].iloc[:num_index +
1].dropna().shape[0] > 0
if has_cond1 and has_cond2:
# 有持仓, 拿到之前的持仓量
keep_cnt = self.capital_pd[a_order.buy_symbol +
buy_type_keep].iloc[:num_index +
1].dropna()[-1]
sell_cnt = a_order.buy_cnt
if keep_cnt < sell_cnt:
# 忽略一个问题,就算是当时买时的这个单子没有成交,这里也试图卖出当时设想买入的股数
sell_cnt = keep_cnt
if sell_cnt == 0:
# 有可能由于没买入的单子,造成没有成交
return False
# 更新对应持仓量
keep_cnt -= sell_cnt
# 将卖出价格转换成call,put都可计算收益的价格,不要进行计算公式合并,保留冗余,便于理解
sell_earn_price = (a_order.sell_price - a_order.buy_price
) * a_order.expect_direction + a_order.buy_price
order_earn = sell_earn_price * sell_cnt
# 使用commission对象计算手续费
with self.commission.sell_commission_func(a_order) as (
sell_func, commission_list):
commission = sell_func(sell_cnt, a_order.sell_price)
# 将上下文管理器中返回的commission_list中添加计算结果commission,内部根据list长度决定写入手续费记录pd.DataFrame
commission_list.append(commission)
# cash_blance初始化init中除了第一个其它都是nan
cash_blance = self.capital_pd['cash_blance'].dropna()
# 截取 < time_indd的cash_blance中最后一个元素做为cash值
cash = cash_blance[cash_blance.index <= time_ind].iloc[-1]
cash += (order_earn - commission)
# 将计算好的cash更新到资金时间序列中对应的位置
self.capital_pd.loc[time_ind, ['cash_blance']] = np.round(cash, 3)
# TODO 这里迁移之前逻辑,删除了一些未迁移模块的逻辑,所以看起来多写了一个流程,需要重构逻辑
self.capital_pd.loc[cash_blance[cash_blance.index > time_ind].index, ['cash_blance']] \
+= (order_earn - commission)
org_cnt = self.capital_pd.loc[time_ind][a_order.buy_symbol +
buy_type_keep]
# 更新持仓量
self.capital_pd.loc[time_ind, [a_order.buy_symbol +
buy_type_keep]] = keep_cnt
if not np.isnan(org_cnt):
# 针对diff factor same stock的情况
keep_pos = self.capital_pd[a_order.buy_symbol +
buy_type_keep].dropna()
self.capital_pd.loc[keep_pos[keep_pos.index > time_ind].index, [a_order.buy_symbol + buy_type_keep]] \
-= sell_cnt
return True
else:
return False | PypiClean |
/KitnIRC-0.3.1.tar.gz/KitnIRC-0.3.1/kitnirc/contrib/cron.py | import datetime
import logging
import random
import threading
import time
from kitnirc.modular import Module
_log = logging.getLogger(__name__)
class Cron(object):
"""An individual cron entry."""
def __init__(self, event, seconds, minutes, hours):
self.event = event
self.seconds = self.parse_time_field(seconds, 60)
self.minutes = self.parse_time_field(minutes, 60)
self.hours = self.parse_time_field(hours, 24)
now = datetime.datetime.now().replace(microsecond=0)
self.next_fire = self.calculate_next_fire(now)
def parse_time_field(self, inputstr, count):
values = set()
for item in inputstr.split(","):
# See if it's just a single number.
try:
values.add(int(item))
continue
except ValueError:
pass
# ? can be used to specify "a single random value"
if item.startswith('?'):
# With an optional /X to specify "every Xth value,
# offset randomly"
_, _, divisor = item.partition("/")
if divisor:
divisor = int(divisor)
offset = random.randint(0, divisor-1)
values.update(range(offset, count, divisor))
else:
values.add(random.randint(0, count-1))
continue
# * can be used to specify "all values"
if item.startswith("*"):
# With an optional /X to specify "every Xth value"
_, _, divisor = item.partition("/")
if divisor:
values.update(range(0, count, int(divisor)))
else:
values.update(range(count))
continue
_log.warning("Ignoring invalid specifier '%s' for cron event '%s'",
item, self.event)
# Ensure only values within the proper range are utilized
return sorted(val for val in values if 0 <= val < count)
def calculate_next_fire(self, after):
# Keeps track of if we've already moved a field by at least
# one notch, so that other fields are allowed to stay the same.
equal_okay = False
next_second = self.seconds[0]
for second in self.seconds:
if second > after.second:
next_second = second
equal_okay = True
break
next_minute = self.minutes[0]
for minute in self.minutes:
if equal_okay and minute == after.minute:
next_minute = minute
break
elif minute > after.minute:
next_minute = minute
equal_okay = True
break
next_hour = self.hours[0]
for hour in self.hours:
if equal_okay and hour == after.hour:
next_hour = hour
break
elif hour > after.hour:
next_hour = hour
break
next_fire = after.replace(hour=next_hour, minute=next_minute,
second=next_second, microsecond=0)
# If we need to roll over to the next day...
if next_fire <= after:
next_fire += datetime.timedelta(days=1)
return next_fire
def maybe_fire(self, client, after, upto):
if self.next_fire is None:
return
if after < self.next_fire <= upto:
_log.debug("Cron event '%s' firing.", self.event)
client.dispatch_event(self.event)
self.next_fire = self.calculate_next_fire(upto)
class CronModule(Module):
"""A KitnIRC module which provides other modules with scheduling.
Note: due to how this module interacts with other modules, reloading
it without reloading other modules will result in previously added
crons being wiped. If you need to reload this module, you should
probably just reload all modules.
"""
def __init__(self, *args, **kwargs):
super(CronModule, self).__init__(*args, **kwargs)
self.crons = []
self.last_tick = datetime.datetime.now()
self.thread = threading.Thread(target=self.loop, name='cron')
self.thread.daemon = True
self._stop = False
def start(self, *args, **kwargs):
super(CronModule, self).start(*args, **kwargs)
self._stop = False
self.last_tick = datetime.datetime.now()
self.thread.start()
def stop(self, *args, **kwargs):
super(CronModule, self).stop(*args, **kwargs)
self._stop = True
# In any normal circumstances, the cron thread should finish in
# about half a second or less. We'll give it a little extra buffer.
self.thread.join(1.0)
if self.thread.is_alive():
_log.warning("Cron thread alive 1s after shutdown request.")
def loop(self):
while not self._stop:
# Use a single "now" for all crons, to ensure consistency
# relative to the next last_tick value.
now = datetime.datetime.now().replace(microsecond=0)
for cron in self.crons:
cron.maybe_fire(self.controller.client, self.last_tick, now)
self.last_tick = now
# Wake up every half-second or so to avoid missing seconds
time.sleep(0.5)
@Module.handle("ADDCRON")
def add_cron(self, client, event, seconds="*", minutes="*", hours="*"):
"""Add a cron entry.
The arguments for this event are:
1. The name of the event to dispatch when the cron fires.
2. What seconds to trigger on, as a timespec (default "*")
3. What minutes to trigger on, as a timespec (default "*")
4. What hours to trigger on, as a timespec (default "*")
Timespecs may be omitted in reverse order of frequency - if hours
is omitted, the previous timespecs will be applied every hour. If
both hours and minutes are omitted, the seconds timespec will be
applied every minute of every hour, and if all timespecs are omitted,
the event will fire each second.
Timespecs are strings in the following formats:
Plain integer - specifies that exact value for the unit.
"?" - specifies a random value from 0 to the unit max.
"?/X" - specifies all multiples of X for this unit, randomly offset
by a fixed amount (e.g. ?/15 might become 4,19,34,49).
"*" - specifies all values for the unix from 0 to max.
"*/X" - specifies all multiples of X for the unit.
Any number of these can be combined in a comma-separated list.
For instance, "*/15" would be the same as "0,15,30,45" if used
in the seconds field.
"""
for cron in self.crons:
if cron.event == event:
_log.warning("Cron '%s' is already registered.", event)
return True
_log.info("Registering cron for '%s'.", event)
cron = Cron(event, seconds, minutes, hours)
self.crons.append(cron)
return True
@Module.handle("REMOVECRON")
def remove_cron(self, client, event):
"""Remove a cron entry by event name."""
for index, cron in enumerate(self.crons):
if cron.event == event:
_log.info("De-registering cron '%s'.", event)
# Yes, we're modifying the list we're iterating over, but
# we immediate stop iterating so it's okay.
self.crons.pop(index)
break
return True
module = CronModule
# vim: set ts=4 sts=4 sw=4 et: | PypiClean |
/Booktype-1.5.tar.gz/Booktype-1.5/lib/booki/site_static/js/tiny_mce/plugins/autolink/editor_plugin.js | (function(){tinymce.create("tinymce.plugins.AutolinkPlugin",{init:function(a,b){var c=this;if(tinyMCE.isIE){return}a.onKeyDown.add(function(d,f){if(f.keyCode==13){return c.handleEnter(d)}});a.onKeyPress.add(function(d,f){if(f.which==41){return c.handleEclipse(d)}});a.onKeyUp.add(function(d,f){if(f.keyCode==32){return c.handleSpacebar(d)}})},handleEclipse:function(a){this.parseCurrentLine(a,-1,"(",true)},handleSpacebar:function(a){this.parseCurrentLine(a,0,"",true)},handleEnter:function(a){this.parseCurrentLine(a,-1,"",false)},parseCurrentLine:function(i,d,b,g){var a,f,c,n,k,m,h,e,j;a=i.selection.getRng().cloneRange();if(a.startOffset<5){e=a.endContainer.previousSibling;if(e==null){if(a.endContainer.firstChild==null||a.endContainer.firstChild.nextSibling==null){return}e=a.endContainer.firstChild.nextSibling}j=e.length;a.setStart(e,j);a.setEnd(e,j);if(a.endOffset<5){return}f=a.endOffset;n=e}else{n=a.endContainer;if(n.nodeType!=3&&n.firstChild){while(n.nodeType!=3&&n.firstChild){n=n.firstChild}a.setStart(n,0);a.setEnd(n,n.nodeValue.length)}if(a.endOffset==1){f=2}else{f=a.endOffset-1-d}}c=f;do{a.setStart(n,f-2);a.setEnd(n,f-1);f-=1}while(a.toString()!=" "&&a.toString()!=""&&a.toString().charCodeAt(0)!=160&&(f-2)>=0&&a.toString()!=b);if(a.toString()==b||a.toString().charCodeAt(0)==160){a.setStart(n,f);a.setEnd(n,c);f+=1}else{if(a.startOffset==0){a.setStart(n,0);a.setEnd(n,c)}else{a.setStart(n,f);a.setEnd(n,c)}}m=a.toString();h=m.match(/^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)(.+)$/i);if(h){if(h[1]=="www."){h[1]="http://www."}k=i.selection.getBookmark();i.selection.setRng(a);tinyMCE.execCommand("createlink",false,h[1]+h[2]);i.selection.moveToBookmark(k);if(tinyMCE.isWebKit){i.selection.collapse(false);var l=Math.min(n.length,c+1);a.setStart(n,l);a.setEnd(n,l);i.selection.setRng(a)}}},getInfo:function(){return{longname:"Autolink",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autolink",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("autolink",tinymce.plugins.AutolinkPlugin)})(); | PypiClean |
/ImmuneDB-0.29.11.tar.gz/ImmuneDB-0.29.11/immunedb/identification/vdj_sequence.py | import re
from Bio.Seq import Seq
import dnautils
from immunedb.common.models import CDR3_OFFSET
import immunedb.util.lookups as lookups
class VDJSequence(object):
def __init__(self, seq_id, sequence, quality=None, rev_comp=False,
copy_number=1):
if quality and len(sequence) != len(quality):
raise ValueError('Sequence and quality must be the same length')
sequence = re.sub(r'[^ATCGN-]', 'N', sequence)
self.seq_id = seq_id
self.copy_number = copy_number
self.orig_sequence = sequence[:]
self.orig_quality = quality[:] if quality else None
self.rev_comp = rev_comp
self._sequence = sequence
self._quality = quality
self._removed_prefix_sequence = ''
self._removed_prefix_quality = ''
@property
def sequence(self):
return self._sequence
@property
def quality(self):
return self._quality
@property
def removed_prefix_sequence(self):
return self._removed_prefix_sequence
@property
def removed_prefix_quality(self):
return self._removed_prefix_quality
def reverse_complement(self):
return VDJSequence(
self.seq_id,
str(Seq(self._sequence).reverse_complement()),
self._quality[::-1] if self._quality else None,
rev_comp=not self.rev_comp,
copy_number=self.copy_number
)
def pad(self, count):
self._sequence = ('N' * count) + self._sequence
if self._quality:
self._quality = (' ' * count) + self._quality
def pad_right(self, count):
self._sequence += 'N' * count
if self._quality:
self._quality += ' ' * count
def remove_prefix(self, count):
self._removed_prefix_sequence = self._sequence[:count]
self._sequence = self._sequence[count:]
if self._quality:
self._removed_prefix_quality = self._sequence[:count]
self._quality = self._quality[count:]
def trim(self, count):
new_prefix = ''.join([
c if c == '-' else 'N' for c in self._sequence[:count]
])
self._sequence = new_prefix + self._sequence[count:]
if self._quality:
self._quality = (' ' * count) + self._quality[count:]
def trim_right(self, count):
self._sequence = self._sequence[:count]
if self._quality:
self._quality = self._quality[:count]
def add_gap(self, pos, char='-'):
self._sequence = self._sequence[:pos] + char + self._sequence[pos:]
if self._quality:
self._quality = self._quality[:pos] + ' ' + self._quality[pos:]
def remove(self, pos):
self._sequence = self._sequence[:pos] + self._sequence[pos + 1:]
if self._quality:
self._quality = self._quality[:pos] + self._quality[pos + 1:]
def rfind(self, seq):
return self._sequence.rfind(seq)
def __getitem__(self, key):
return self._sequence[key]
def __setitem__(self, key, value):
self._sequence[key] = value
def __len__(self):
return len(self._sequence)
class VDJAlignment(object):
INDEL_WINDOW = 30
INDEL_MISMATCH_THRESHOLD = .6
def __init__(self, sequence):
self.sequence = sequence
self.germline = None
self.j_gene = set()
self.v_gene = set()
self.locally_aligned = False
self.seq_offset = 0
self.v_length = 0
self.j_length = 0
self.v_mutation_fraction = 0
self.cdr3_start = CDR3_OFFSET
self.cdr3_num_nts = 0
self.germline_cdr3 = None
self.post_cdr3_length = 0
self.insertions = set([])
self.deletions = set([])
@property
def filled_germline(self):
return ''.join((
self.germline[:self.cdr3_start],
self.germline_cdr3,
self.germline[self.cdr3_start + self.cdr3_num_nts:]
))
@property
def seq_start(self):
return max(0, self.seq_offset)
@property
def num_gaps(self):
return self.sequence[self.seq_start:self.cdr3_start].count('-')
@property
def cdr3(self):
return self.sequence[self.cdr3_start:self.cdr3_start +
self.cdr3_num_nts]
@property
def partial(self):
return self.seq_start > 0
@property
def in_frame(self):
return len(self.cdr3) % 3 == 0 and self.cdr3_start % 3 == 0
@property
def stop(self):
return lookups.has_stop(self.sequence)
@property
def functional(self):
return self.in_frame and not self.stop
@property
def v_match(self):
start = self.seq_start
end = start + self.v_length + self.num_gaps
return self.v_length - dnautils.hamming(
self.filled_germline[start:end],
self.sequence[start:end]
)
@property
def j_match(self):
return self.j_length - dnautils.hamming(
self.filled_germline[-self.j_length:],
self.sequence[-self.j_length:]
)
@property
def pre_cdr3_length(self):
return self.cdr3_start - self.seq_start - self.num_gaps
@property
def pre_cdr3_match(self):
start = self.seq_start + self.num_gaps
end = self.cdr3_start
return self.pre_cdr3_length - dnautils.hamming(
self.germline[start:end],
self.sequence[start:end]
)
@property
def post_cdr3_match(self):
return self.post_cdr3_length - dnautils.hamming(
self.germline[-self.post_cdr3_length:],
self.sequence[-self.post_cdr3_length:]
)
@property
def has_possible_indel(self):
# Start comparison on first full AA to the INDEL_WINDOW or CDR3,
# whichever comes first
start = re.search('[ATCG]', self.sequence.sequence).start()
germ = self.germline[start:self.cdr3_start]
seq = self.sequence[start:self.cdr3_start]
for i in range(0, len(germ) - self.INDEL_WINDOW + 1):
dist = dnautils.hamming(germ[i:i+self.INDEL_WINDOW],
seq[i:i+self.INDEL_WINDOW])
if dist >= self.INDEL_MISMATCH_THRESHOLD * self.INDEL_WINDOW:
return True
return False
def trim_to(self, count):
old_pad = self.seq_start - self.sequence[:self.seq_start].count('-')
n_extension = re.match(
'[N]*', self.sequence[count:]).span()[1]
self.sequence.trim(count)
self.seq_offset = re.match(r'[N-]*', self.sequence.sequence).span()[1]
self.seq_offset -= n_extension
new_pad = self.sequence[:self.seq_start].count('-')
self.v_length = self.v_length - self.seq_start + old_pad + new_pad | PypiClean |
/B9gemyaeix-4.14.1.tar.gz/B9gemyaeix-4.14.1/docs/admin/continuous.rst | .. _continuous-translation:
Continuous localization
=======================
There is infrastructure in place so that your translation closely follows
development. This way translators can work on translations the entire time,
instead of working through huge amount of new text just prior to release.
.. seealso::
:doc:`/devel/integration` describes basic ways to integrate your development
with Weblate.
This is the process:
1. Developers make changes and push them to the VCS repository.
2. Optionally the translation files are updated (this depends on the file format, see :ref:`translations-update`).
3. Weblate pulls changes from the VCS repository, see :ref:`update-vcs`.
4. Once Weblate detects changes in translations, translators are notified based on their subscription settings.
5. Translators submit translations using the Weblate web interface, or upload offline changes.
6. Once the translators are finished, Weblate commits the changes to the local repository (see :ref:`lazy-commit`) and pushes them back if it has permissions to do so (see :ref:`push-changes`).
.. graphviz::
digraph translations {
graph [fontname = "sans-serif", fontsize=10];
node [fontname = "sans-serif", fontsize=10, margin=0.1, height=0];
edge [fontname = "sans-serif", fontsize=10];
"Developers" [shape=box, fillcolor="#144d3f", fontcolor=white, style=filled];
"Translators" [shape=box, fillcolor="#144d3f", fontcolor=white, style=filled];
"Developers" -> "VCS repository" [label=" 1. Push "];
"VCS repository" -> "VCS repository" [label=" 2. Updating translations ", style=dotted];
"VCS repository" -> "Weblate" [label=" 3. Pull "];
"Weblate" -> "Translators" [label=" 4. Notification "];
"Translators" -> "Weblate" [label=" 5. Translate "];
"Weblate" -> "VCS repository" [label=" 6. Push "];
}
.. _update-vcs:
Updating repositories
---------------------
You should set up some way of updating backend repositories from their
source.
* Use :ref:`hooks` to integrate with most of common code hosting services:
* :ref:`github-setup`
* :ref:`gitlab-setup`
* :ref:`bitbucket-setup`
* :ref:`pagure-setup`
* :ref:`azure-setup`
* Manually trigger update either in the repository management or using :ref:`api` or :ref:`wlc`
* Enable :setting:`AUTO_UPDATE` to automatically update all components on your Weblate instance
* Execute :djadmin:`updategit` (with selection of project or ``--all`` to update all)
Whenever Weblate updates the repository, the post-update addons will be
triggered, see :ref:`addons`.
.. _avoid-merge-conflicts:
Avoiding merge conflicts
++++++++++++++++++++++++
The merge conflicts from Weblate arise when same file was changed both in
Weblate and outside it. There are two approaches to deal with that - avoid
edits outside Weblate or integrate Weblate into your updating process, so that
it flushes changes prior to updating the files outside Weblate.
The first approach is easy with monolingual files - you can add new strings
within Weblate and leave whole editing of the files there. For bilingual files,
there is usually some kind of message extraction process to generate
translatable files from the source code. In some cases this can be split into
two parts - one for the extraction generates template (for example gettext POT
is generated using :program:`xgettext`) and then further process merges it into
actual translations (the gettext PO files are updated using
:program:`msgmerge`). You can perform the second step within Weblate and it
will make sure that all pending changes are included prior to this operation.
The second approach can be achieved by using :ref:`api` to force Weblate to
push all pending changes and lock the translation while you are doing changes
on your side.
The script for doing updates can look like this:
.. code-block:: sh
# Lock Weblate translation
wlc lock
# Push changes from Weblate to upstream repository
wlc push
# Pull changes from upstream repository to your local copy
git pull
# Update translation files, this example is for Django
./manage.py makemessages --keep-pot -a
git commit -m 'Locale updates' -- locale
# Push changes to upstream repository
git push
# Tell Weblate to pull changes (not needed if Weblate follows your repo
# automatically)
wlc pull
# Unlock translations
wlc unlock
If you have multiple components sharing same repository, you need to lock them
all separately:
.. code-block:: sh
wlc lock foo/bar
wlc lock foo/baz
wlc lock foo/baj
.. note::
The example uses :ref:`wlc`, which needs configuration (API keys) to be
able to control Weblate remotely. You can also achieve this using any HTTP
client instead of wlc, e.g. curl, see :ref:`api`.
.. seealso::
:ref:`wlc`
.. _github-setup:
Automatically receiving changes from GitHub
+++++++++++++++++++++++++++++++++++++++++++
Weblate comes with native support for GitHub.
If you are using Hosted Weblate, the recommended approach is to install the
`Weblate app <https://github.com/apps/weblate>`_, that way you will get the
correct setup without having to set much up. It can also be used for pushing
changes back.
To receive notifications on every push to a GitHub repository,
add the Weblate Webhook in the repository settings (:guilabel:`Webhooks`)
as shown on the image below:
.. image:: /images/github-settings.png
For the payload URL, append ``/hooks/github/`` to your Weblate URL, for example
for the Hosted Weblate service, this is ``https://hosted.weblate.org/hooks/github/``.
You can leave other values at default settings (Weblate can handle both
content types and consumes just the `push` event).
.. seealso::
:http:post:`/hooks/github/`, :ref:`hosted-push`
.. _bitbucket-setup:
Automatically receiving changes from Bitbucket
++++++++++++++++++++++++++++++++++++++++++++++
Weblate has support for Bitbucket webhooks, add a webhook
which triggers upon repository push, with destination to ``/hooks/bitbucket/`` URL
on your Weblate installation (for example
``https://hosted.weblate.org/hooks/bitbucket/``).
.. image:: /images/bitbucket-settings.png
.. seealso::
:http:post:`/hooks/bitbucket/`, :ref:`hosted-push`
.. _gitlab-setup:
Automatically receiving changes from GitLab
+++++++++++++++++++++++++++++++++++++++++++
Weblate has support for GitLab hooks, add a project webhook
with destination to ``/hooks/gitlab/`` URL on your Weblate installation
(for example ``https://hosted.weblate.org/hooks/gitlab/``).
.. seealso::
:http:post:`/hooks/gitlab/`, :ref:`hosted-push`
.. _pagure-setup:
Automatically receiving changes from Pagure
+++++++++++++++++++++++++++++++++++++++++++
.. versionadded:: 3.3
Weblate has support for Pagure hooks, add a webhook
with destination to ``/hooks/pagure/`` URL on your Weblate installation (for
example ``https://hosted.weblate.org/hooks/pagure/``). This can be done in
:guilabel:`Activate Web-hooks` under :guilabel:`Project options`:
.. image:: /images/pagure-webhook.png
.. seealso::
:http:post:`/hooks/pagure/`, :ref:`hosted-push`
.. _azure-setup:
Automatically receiving changes from Azure Repos
++++++++++++++++++++++++++++++++++++++++++++++++
.. versionadded:: 3.8
Weblate has support for Azure Repos web hooks, add a webhook for
:guilabel:`Code pushed` event with destination to ``/hooks/azure/`` URL on your
Weblate installation (for example ``https://hosted.weblate.org/hooks/azure/``).
This can be done in :guilabel:`Service hooks` under :guilabel:`Project
settings`.
.. seealso::
`Web hooks in Azure DevOps manual <https://docs.microsoft.com/en-us/azure/devops/service-hooks/services/webhooks?view=azure-devops>`_,
:http:post:`/hooks/azure/`, :ref:`hosted-push`
.. _gitea-setup:
Automatically receiving changes from Gitea Repos
++++++++++++++++++++++++++++++++++++++++++++++++
.. versionadded:: 3.9
Weblate has support for Gitea webhooks, add a :guilabel:`Gitea Webhook` for
:guilabel:`Push events` event with destination to ``/hooks/gitea/`` URL on your
Weblate installation (for example ``https://hosted.weblate.org/hooks/gitea/``).
This can be done in :guilabel:`Webhooks` under repository :guilabel:`Settings`.
.. seealso::
`Webhooks in Gitea manual <https://docs.gitea.io/en-us/webhooks/>`_,
:http:post:`/hooks/gitea/`, :ref:`hosted-push`
.. _gitee-setup:
Automatically receiving changes from Gitee Repos
++++++++++++++++++++++++++++++++++++++++++++++++
.. versionadded:: 3.9
Weblate has support for Gitee webhooks, add a :guilabel:`WebHook` for
:guilabel:`Push` event with destination to ``/hooks/gitee/`` URL on your
Weblate installation (for example ``https://hosted.weblate.org/hooks/gitee/``).
This can be done in :guilabel:`WebHooks` under repository :guilabel:`Management`.
.. seealso::
`Webhooks in Gitee manual <https://gitee.com/help/categories/40>`_,
:http:post:`/hooks/gitee/`, :ref:`hosted-push`
Automatically updating repositories nightly
+++++++++++++++++++++++++++++++++++++++++++
Weblate automatically fetches remote repositories nightly to improve
performance when merging changes later. You can optionally turn this into doing
nightly merges as well, by enabling :setting:`AUTO_UPDATE`.
.. _push-changes:
Pushing changes from Weblate
----------------------------
Each translation component can have a push URL set up (see
:ref:`component-push`), and in that case Weblate will be able to push change to
the remote repository. Weblate can be also be configured to automatically push
changes on every commit (this is default, see :ref:`component-push_on_commit`).
If you do not want changes to be pushed automatically, you can do that manually
under :guilabel:`Repository maintenance` or using API via :option:`wlc push`.
The push options differ based on the :ref:`vcs` used, more details are found in that chapter.
In case you do not want direct pushes by Weblate, there is support for
:ref:`vcs-github`, :ref:`vcs-gitlab`, :ref:`vcs-pagure` pull requests or
:ref:`vcs-gerrit` reviews, you can activate these by choosing
:guilabel:`GitHub`, :guilabel:`GitLab`, :guilabel:`Gerrit` or
:guilabel:`Pagure` as :ref:`component-vcs` in :ref:`component`.
Overall, following options are available with Git, GitHub and GitLab:
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
| Desired setup | :ref:`component-vcs` | :ref:`component-push` | :ref:`component-push_branch` |
+===================================+===============================+===============================+===============================+
| No push | :ref:`vcs-git` | `empty` | `empty` |
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
| Push directly | :ref:`vcs-git` | SSH URL | `empty` |
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
| Push to separate branch | :ref:`vcs-git` | SSH URL | Branch name |
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
| GitHub pull request from fork | :ref:`vcs-github` | `empty` | `empty` |
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
| GitHub pull request from branch | :ref:`vcs-github` | SSH URL [#empty]_ | Branch name |
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
| GitLab merge request from fork | :ref:`vcs-gitlab` | `empty` | `empty` |
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
| GitLab merge request from branch | :ref:`vcs-gitlab` | SSH URL [#empty]_ | Branch name |
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
| Pagure merge request from fork | :ref:`vcs-pagure` | `empty` | `empty` |
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
| Pagure merge request from branch | :ref:`vcs-pagure` | SSH URL [#empty]_ | Branch name |
+-----------------------------------+-------------------------------+-------------------------------+-------------------------------+
.. [#empty] Can be empty in case :ref:`component-repo` supports pushing.
.. note::
You can also enable automatic pushing of changes after Weblate commits, this can be done in
:ref:`component-push_on_commit`.
.. seealso::
See :ref:`vcs-repos` for setting up SSH keys, and :ref:`lazy-commit` for
info about when Weblate decides to commit changes.
Protected branches
++++++++++++++++++
If you are using Weblate on protected branch, you can configure it to use pull
requests and perform actual review on the translations (what might be
problematic for languages you do not know). An alternative approach is to waive
this limitation for the Weblate push user.
For example on GitHub this can be done in the repository configuration:
.. image:: /images/github-protected.png
Interacting with others
-----------------------
Weblate makes it easy to interact with others using its API.
.. seealso::
:ref:`api`
.. _lazy-commit:
Lazy commits
------------
The behaviour of Weblate is to group commits from the same author into one
commit if possible. This greatly reduces the number of commits, however you
might need to explicitly tell it to do the commits in case you want to get the
VCS repository in sync, e.g. for merge (this is by default allowed for the :guilabel:`Managers`
group, see :ref:`privileges`).
The changes in this mode are committed once any of the following conditions are
fulfilled:
* Somebody else changes an already changed string.
* A merge from upstream occurs.
* An explicit commit is requested.
* A file download is requested.
* Change is older than period defined as :ref:`component-commit_pending_age` on :ref:`component`.
.. hint::
Commits are created for every component. So in case you have many components
you will still see lot of commits. You might utilize
:ref:`addon-weblate.git.squash` add-on in that case.
If you want to commit changes more frequently and without checking of age, you
can schedule a regular task to perform a commit:
.. literalinclude:: ../../weblate/examples/beat-settings.py
:language: python
.. _processing:
Processing repository with scripts
----------------------------------
The way to customize how Weblate interacts with the repository is
:ref:`addons`. Consult :ref:`addon-script` for info on how to execute
external scripts through add-ons.
.. _translation-consistency:
Keeping translations same across components
-------------------------------------------
Once you have multiple translation components, you might want to ensure that
the same strings have same translation. This can be achieved at several levels.
Translation propagation
+++++++++++++++++++++++
With :ref:`component-allow_translation_propagation` enabled (what is the default, see
:ref:`component`), all new translations are automatically done in all
components with matching strings. Such translations are properly credited to
currently translating user in all components.
.. note::
The translation propagation requires the key to be match for monolingual
translation formats, so keep that in mind when creating translation keys.
Consistency check
+++++++++++++++++
The :ref:`check-inconsistent` check fires whenever the strings are different.
You can utilize this to review such differences manually and choose the right
translation.
Automatic translation
+++++++++++++++++++++
Automatic translation based on different components can be way to synchronize
the translations across components. You can either trigger it manually (see
:ref:`auto-translation`) or make it run automatically on repository update
using add-on (see :ref:`addon-weblate.autotranslate.autotranslate`).
| PypiClean |
/OASYS1-XOPPY-1.2.10.tar.gz/OASYS1-XOPPY-1.2.10/orangecontrib/xoppy/widgets/source/xtc.py | import sys,os
import numpy
import platform
from PyQt5.QtWidgets import QApplication
from orangewidget import gui
from orangewidget.settings import Setting
from oasys.widgets import gui as oasysgui, congruence
from xoppylib.xoppy_util import locations
from oasys.widgets.exchange import DataExchangeObject
from orangecontrib.xoppy.widgets.gui.ow_xoppy_widget import XoppyWidget
from syned.widget.widget_decorator import WidgetDecorator
import syned.beamline.beamline as synedb
from syned.storage_ring.magnetic_structures.insertion_device import InsertionDevice as synedid
from xoppylib.xoppy_run_binaries import xoppy_calc_xtc
class OWxtc(XoppyWidget):
name = "TC"
id = "orange.widgets.dataxtc"
description = "Undulator Tuning Curves"
icon = "icons/xoppy_xtc.png"
priority = 7
category = ""
keywords = ["xoppy", "xtc"]
#19 variables (minus one: TITLE removed)
ENERGY = Setting(7.0)
CURRENT = Setting(100.0)
ENERGY_SPREAD = Setting(0.00096)
SIGX = Setting(0.274)
SIGY = Setting(0.011)
SIGX1 = Setting(0.0113)
SIGY1 = Setting(0.0036)
PERIOD = Setting(3.23)
NP = Setting(70)
EMIN = Setting(2950.0)
EMAX = Setting(13500.0)
N = Setting(40)
HARMONIC_FROM = Setting(1)
HARMONIC_TO = Setting(15)
HARMONIC_STEP = Setting(2)
HELICAL = Setting(0)
METHOD = Setting(1)
NEKS = Setting(100)
inputs = WidgetDecorator.syned_input_data()
def __init__(self):
super().__init__(show_script_tab=True)
def build_gui(self):
self.IMAGE_WIDTH = 850
box = oasysgui.widgetBox(self.controlArea, self.name + " Input Parameters", orientation="vertical", width=self.CONTROL_AREA_WIDTH-5)
idx = -1
#widget index 1
idx += 1
box1 = gui.widgetBox(box)
self.id_ENERGY = oasysgui.lineEdit(box1, self, "ENERGY",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 2
idx += 1
box1 = gui.widgetBox(box)
self.id_CURRENT = oasysgui.lineEdit(box1, self, "CURRENT",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 3
idx += 1
box1 = gui.widgetBox(box)
self.id_ENERGY_SPREAD = oasysgui.lineEdit(box1, self, "ENERGY_SPREAD",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 5
idx += 1
box1 = gui.widgetBox(box)
self.id_SIGX = oasysgui.lineEdit(box1, self, "SIGX",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 6
idx += 1
box1 = gui.widgetBox(box)
self.id_SIGY = oasysgui.lineEdit(box1, self, "SIGY",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 7
idx += 1
box1 = gui.widgetBox(box)
self.id_SIGX1 = oasysgui.lineEdit(box1, self, "SIGX1",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 8
idx += 1
box1 = gui.widgetBox(box)
self.id_SIGY1 = oasysgui.lineEdit(box1, self, "SIGY1",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 10
idx += 1
box1 = gui.widgetBox(box)
self.id_PERIOD = oasysgui.lineEdit(box1, self, "PERIOD",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 11
idx += 1
box1 = gui.widgetBox(box)
self.id_NP = oasysgui.lineEdit(box1, self, "NP",
label=self.unitLabels()[idx], addSpace=False,
valueType=int, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 13
idx += 1
box1 = gui.widgetBox(box)
oasysgui.lineEdit(box1, self, "EMIN",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 14
idx += 1
box1 = gui.widgetBox(box)
oasysgui.lineEdit(box1, self, "EMAX",
label=self.unitLabels()[idx], addSpace=False,
valueType=float, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 15
idx += 1
box1 = gui.widgetBox(box)
oasysgui.lineEdit(box1, self, "N",
label=self.unitLabels()[idx], addSpace=False,
valueType=int, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 17
idx += 1
box1 = gui.widgetBox(box)
oasysgui.lineEdit(box1, self, "HARMONIC_FROM",
label=self.unitLabels()[idx], addSpace=False,
valueType=int, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 18
idx += 1
box1 = gui.widgetBox(box)
oasysgui.lineEdit(box1, self, "HARMONIC_TO",
label=self.unitLabels()[idx], addSpace=False,
valueType=int, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 19
idx += 1
box1 = gui.widgetBox(box)
oasysgui.lineEdit(box1, self, "HARMONIC_STEP",
label=self.unitLabels()[idx], addSpace=False,
valueType=int, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 21
idx += 1
box1 = gui.widgetBox(box)
gui.comboBox(box1, self, "HELICAL",
label=self.unitLabels()[idx], addSpace=False,
items=['Planar undulator', 'Helical undulator'],
valueType=int, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 22
idx += 1
box1 = gui.widgetBox(box)
gui.comboBox(box1, self, "METHOD",
label=self.unitLabels()[idx], addSpace=False,
items=['Finite-N', 'Infinite N with convolution'],
valueType=int, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
#widget index 24
idx += 1
box1 = gui.widgetBox(box)
oasysgui.lineEdit(box1, self, "NEKS",
label=self.unitLabels()[idx], addSpace=False,
valueType=int, orientation="horizontal", labelWidth=250)
self.show_at(self.unitFlags()[idx], box1)
def unitLabels(self):
return ['Electron energy (GeV)','Current (mA)','Energy Spread (DE/E)',
'Sigma X (mm)','Sigma Y (mm)',"Sigma X' (mrad)","Sigma Y' (mrad)",
'Period length (cm)','Number of periods',
'E1 minimum energy (eV)','E1 maximum energy (eV)',
'Number of energy-points','Minimum harmonic number','Maximum harmonic number','Harmonic step size',
'Mode','Method','Neks OR % Helicity']
def unitFlags(self):
return ['True' for i in range(19)]
def get_help_name(self):
return 'tc'
def check_fields(self):
self.ENERGY = congruence.checkStrictlyPositiveNumber(self.ENERGY, "Electron Energy")
self.CURRENT = congruence.checkStrictlyPositiveNumber(self.CURRENT, "Current")
self.ENERGY_SPREAD = congruence.checkStrictlyPositiveNumber(self.ENERGY_SPREAD, "Energy Spread")
self.SIGX = congruence.checkPositiveNumber(self.SIGX , "Sigma X")
self.SIGY = congruence.checkPositiveNumber(self.SIGY , "Sigma Y")
self.SIGX1 = congruence.checkPositiveNumber(self.SIGX1, "Sigma X'")
self.SIGY1 = congruence.checkPositiveNumber(self.SIGY1, "Sigma Y'")
self.PERIOD = congruence.checkStrictlyPositiveNumber(self.PERIOD, "Period length")
self.NP = congruence.checkStrictlyPositiveNumber(self.NP, "Number of periods")
self.EMIN = congruence.checkPositiveNumber(self.EMIN, "E1 minimum energy")
self.EMAX = congruence.checkStrictlyPositiveNumber(self.EMAX, "E1 maximum energy")
congruence.checkLessThan(self.EMIN, self.EMAX, "E1 minimum energy", "E1 maximum energy")
self.N = congruence.checkStrictlyPositiveNumber(self.N, "Number of Energy Points")
self.HARMONIC_FROM = congruence.checkStrictlyPositiveNumber(self.HARMONIC_FROM, "Minimum harmonic number")
self.HARMONIC_TO = congruence.checkStrictlyPositiveNumber(self.HARMONIC_TO, "Maximum harmonic number")
congruence.checkLessThan(self.HARMONIC_FROM, self.HARMONIC_TO, "Minimum harmonic number", "Maximum harmonic number")
self.HARMONIC_STEP = congruence.checkStrictlyPositiveNumber(self.HARMONIC_STEP, "Harmonic step size")
self.NEKS = congruence.checkPositiveNumber(self.NEKS , "Neks OR % Helicity")
def do_xoppy_calculation(self):
data, harmonics_data = xoppy_calc_xtc(
ENERGY = self.ENERGY ,
CURRENT = self.CURRENT ,
ENERGY_SPREAD = self.ENERGY_SPREAD ,
SIGX = self.SIGX ,
SIGY = self.SIGY ,
SIGX1 = self.SIGX1 ,
SIGY1 = self.SIGY1 ,
PERIOD = self.PERIOD ,
NP = self.NP ,
EMIN = self.EMIN ,
EMAX = self.EMAX ,
N = self.N ,
HARMONIC_FROM = self.HARMONIC_FROM ,
HARMONIC_TO = self.HARMONIC_TO ,
HARMONIC_STEP = self.HARMONIC_STEP ,
HELICAL = self.HELICAL ,
METHOD = self.METHOD ,
NEKS = self.NEKS ,
)
dict_parameters = {
"ENERGY" : self.ENERGY ,
"CURRENT" : self.CURRENT ,
"ENERGY_SPREAD" : self.ENERGY_SPREAD ,
"SIGX" : self.SIGX ,
"SIGY" : self.SIGY ,
"SIGX1" : self.SIGX1 ,
"SIGY1" : self.SIGY1 ,
"PERIOD" : self.PERIOD ,
"NP" : self.NP ,
"EMIN" : self.EMIN ,
"EMAX" : self.EMAX ,
"N" : self.N ,
"HARMONIC_FROM" : self.HARMONIC_FROM ,
"HARMONIC_TO" : self.HARMONIC_TO ,
"HARMONIC_STEP" : self.HARMONIC_STEP ,
"HELICAL" : self.HELICAL ,
"METHOD" : self.METHOD ,
"NEKS" : self.NEKS ,
}
script = self.script_template().format_map(dict_parameters)
self.xoppy_script.set_code(script)
return data, harmonics_data, script
def script_template(self):
return """
#
# script to make the calculations (created by XOPPY:XTC)
#
from xoppylib.xoppy_run_binaries import xoppy_calc_xtc
data, harmonics_data = xoppy_calc_xtc(
ENERGY = {ENERGY},
CURRENT = {CURRENT},
ENERGY_SPREAD = {ENERGY_SPREAD},
SIGX = {SIGX},
SIGY = {SIGY},
SIGX1 = {SIGX1},
SIGY1 = {SIGY1},
PERIOD = {PERIOD},
NP = {NP},
EMIN = {EMIN},
EMAX = {EMAX},
N = {N},
HARMONIC_FROM = {HARMONIC_FROM},
HARMONIC_TO = {HARMONIC_TO},
HARMONIC_STEP = {HARMONIC_STEP},
HELICAL = {HELICAL},
METHOD = {METHOD},
NEKS = {NEKS},
)
#
# example plot
#
import numpy
from srxraylib.plot.gol import plot
#
#
print("Number of harmonics calculated: ",len(harmonics_data))
plot((harmonics_data[0][1])[:,0],
(harmonics_data[0][1])[:,2],
title="harmonic number = %d" % (harmonics_data[0][0]), xtitle="Energy[eV]", ytitle="Brilliance" )
#
# end script
#
"""
def extract_data_from_xoppy_output(self, calculation_output):
#send exchange
data, harmonics_data, script = calculation_output
calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name())
try:
calculated_data.add_content("xoppy_data", data)
calculated_data.add_content("xoppy_data_harmonics", harmonics_data)
calculated_data.add_content("plot_x_col", 1)
calculated_data.add_content("plot_y_col", 2)
except:
pass
try:
calculated_data.add_content("labels",["Energy (eV) without emittance", "Energy (eV) with emittance",
"Brilliance (ph/s/mrad^2/mm^2/0.1%bw)","Ky","Total Power (W)","Power density (W/mr^2)"])
except:
pass
try:
calculated_data.add_content("info",txtlist)
except:
pass
return calculated_data
def plot_results(self, calculated_data, progressBarValue=80):
if not self.view_type == 0:
if not calculated_data is None:
self.view_type_combo.setEnabled(False)
xoppy_data_harmonics = calculated_data.get_content("xoppy_data_harmonics")
titles = self.getTitles()
xtitles = self.getXTitles()
ytitles = self.getYTitles()
progress_bar_step = (100-progressBarValue)/len(titles)
for index in range(0, len(titles)):
x_index, y_index = self.getVariablesToPlot()[index]
log_x, log_y = self.getLogPlot()[index]
if not self.plot_canvas[index] is None:
self.plot_canvas[index].clear()
try:
for h_index in range(0, len(xoppy_data_harmonics)):
self.plot_histo(xoppy_data_harmonics[h_index][1][:, x_index],
xoppy_data_harmonics[h_index][1][:, y_index],
progressBarValue + ((index+1)*progress_bar_step),
tabs_canvas_index=index,
plot_canvas_index=index,
title=titles[index],
xtitle=xtitles[index],
ytitle=ytitles[index],
log_x=log_x,
log_y=log_y,
harmonic=xoppy_data_harmonics[h_index][0],
control=True)
self.plot_canvas[index].addCurve(numpy.zeros(1),
numpy.array([max(xoppy_data_harmonics[h_index][1][:, y_index])]),
"Click on curve to highlight it",
xlabel=xtitles[index], ylabel=ytitles[index],
symbol='', color='white')
self.plot_canvas[index].setActiveCurve("Click on curve to highlight it")
self.plot_canvas[index].getLegendsDockWidget().setFixedHeight(150)
self.plot_canvas[index].getLegendsDockWidget().setVisible(True)
self.tabs.setCurrentIndex(index)
except Exception as e:
self.view_type_combo.setEnabled(True)
raise Exception("Data not plottable: bad content\n" + str(e))
self.view_type_combo.setEnabled(True)
else:
raise Exception("Empty Data")
try:
self.tabs.setCurrentIndex(0)
except:
pass
def plot_histo(self, x, y, progressBarValue, tabs_canvas_index, plot_canvas_index, title="", xtitle="", ytitle="",
log_x=False, log_y=False, harmonic=1, color='blue', control=True):
h_title = "Harmonic " + str(harmonic)
hex_r = hex(min(255, 128 + harmonic*10))[2:].upper()
hex_g = hex(min(255, 20 + harmonic*15))[2:].upper()
hex_b = hex(min(255, harmonic*10))[2:].upper()
if len(hex_r) == 1: hex_r = "0" + hex_r
if len(hex_g) == 1: hex_g = "0" + hex_g
if len(hex_b) == 1: hex_b = "0" + hex_b
super().plot_histo(x, y, progressBarValue, tabs_canvas_index, plot_canvas_index, h_title, xtitle, ytitle,
log_x, log_y, color="#" + hex_r + hex_g + hex_b, replace=False, control=control)
self.plot_canvas[plot_canvas_index].setGraphTitle(title)
self.plot_canvas[plot_canvas_index].setDefaultPlotLines(True)
self.plot_canvas[plot_canvas_index].setDefaultPlotPoints(True)
def get_data_exchange_widget_name(self):
return "XTC"
def getTitles(self):
return ["Brilliance","Ky","Total Power","Power density"]
def getXTitles(self):
return ["Energy (eV)","Energy (eV)","Energy (eV)","Energy (eV)"]
def getYTitles(self):
return ["Brilliance (ph/s/mrad^2/mm^2/0.1%bw)","Ky","Total Power (W)","Power density (W/mr^2)"]
def getVariablesToPlot(self):
return [(1, 2), (1, 3), (1, 4), (1, 5)]
def getLogPlot(self):
return[(False, True), (False, False), (False, False), (False, False)]
# def xoppy_calc_xtc(self):
#
# for file in ["tc.inp","tc.out"]:
# try:
# os.remove(os.path.join(locations.home_bin_run(),file))
# except:
# pass
#
# with open("tc.inp", "wt") as f:
# f.write("TS called from xoppy\n")
# f.write("%10.3f %10.2f %10.6f %s\n"%(self.ENERGY,self.CURRENT,self.ENERGY_SPREAD,"Ring-Energy(GeV) Current(mA) Beam-Energy-Spread"))
# f.write("%10.4f %10.4f %10.4f %10.4f %s\n"%(self.SIGX,self.SIGY,self.SIGX1,self.SIGY1,"Sx(mm) Sy(mm) Sx1(mrad) Sy1(mrad)"))
# f.write("%10.3f %d %s\n"%(self.PERIOD,self.NP,"Period(cm) N"))
# f.write("%10.1f %10.1f %d %s\n"%(self.EMIN,self.EMAX,self.N,"Emin Emax Ne"))
# f.write("%d %d %d %s\n"%(self.HARMONIC_FROM,self.HARMONIC_TO,self.HARMONIC_STEP,"Hmin Hmax Hstep"))
# f.write("%d %d %d %d %s\n"%(self.HELICAL,self.METHOD,1,self.NEKS,"Helical Method Print_K Neks"))
# f.write("foreground\n")
#
#
# if platform.system() == "Windows":
# command = "\"" + os.path.join(locations.home_bin(),'tc.exe') + "\""
# else:
# command = "'" + os.path.join(locations.home_bin(), 'tc') + "'"
#
#
# print("Running command '%s' in directory: %s "%(command, locations.home_bin_run()))
# print("\n--------------------------------------------------------\n")
# os.system(command)
# print("Output file: %s"%("tc.out"))
# print("\n--------------------------------------------------------\n")
#
# #
# # parse result files to exchange object
# #
#
#
# with open("tc.out","r") as f:
# lines = f.readlines()
#
# # print output file
# # for line in lines:
# # print(line, end="")
#
#
# # remove returns
# lines = [line[:-1] for line in lines]
# harmonics_data = []
#
# # separate numerical data from text
# floatlist = []
# harmoniclist = []
# txtlist = []
# for line in lines:
# try:
# tmp = line.strip()
#
# if tmp.startswith("Harmonic"):
# harmonic_number = int(tmp.split("Harmonic")[1].strip())
#
# if harmonic_number != self.HARMONIC_FROM:
# harmonics_data[-1][1] = harmoniclist
# harmoniclist = []
#
# harmonics_data.append([harmonic_number, None])
#
# tmp = float(line.strip()[0])
#
# floatlist.append(line)
# harmoniclist.append(line)
# except:
# txtlist.append(line)
#
# harmonics_data[-1][1] = harmoniclist
#
# data = numpy.loadtxt(floatlist)
#
# for index in range(0, len(harmonics_data)):
# # print (harmonics_data[index][0], harmonics_data[index][1])
# harmonics_data[index][1] = numpy.loadtxt(harmonics_data[index][1])
#
# #send exchange
# calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name())
#
# try:
# calculated_data.add_content("xoppy_data", data)
# calculated_data.add_content("xoppy_data_harmonics", harmonics_data)
# calculated_data.add_content("plot_x_col", 1)
# calculated_data.add_content("plot_y_col", 2)
# except:
# pass
# try:
# calculated_data.add_content("labels",["Energy (eV) without emittance", "Energy (eV) with emittance",
# "Brilliance (ph/s/mrad^2/mm^2/0.1%bw)","Ky","Total Power (W)","Power density (W/mr^2)"])
# except:
# pass
# try:
# calculated_data.add_content("info",txtlist)
# except:
# pass
#
# return calculated_data
def receive_syned_data(self, data):
if isinstance(data, synedb.Beamline):
if not data._light_source is None and isinstance(data.get_light_source().get_magnetic_structure(), synedid):
light_source = data.get_light_source()
self.ENERGY = light_source.get_electron_beam().energy()
self.ENERGY_SPREAD = light_source.get_electron_beam()._energy_spread
self.CURRENT = 1000.0 * light_source._electron_beam.current()
x, xp, y, yp = light_source.get_electron_beam().get_sigmas_all()
self.SIGX = 1e3 * x
self.SIGY = 1e3 * y
self.SIGX1 = 1e3 * xp
self.SIGY1 = 1e3 * yp
self.PERIOD = 100.0 * light_source.get_magnetic_structure().period_length()
self.NP = light_source.get_magnetic_structure().number_of_periods()
self.EMIN = light_source.get_magnetic_structure().resonance_energy(gamma=light_source.get_electron_beam().gamma())
self.EMAX = 5 * self.EMIN
self.set_enabled(False)
else:
self.set_enabled(True)
# raise ValueError("Syned data not correct")
else:
self.set_enabled(True)
# raise ValueError("Syned data not correct")
def set_enabled(self,value):
if value == True:
self.id_ENERGY.setEnabled(True)
self.id_ENERGY_SPREAD.setEnabled(True)
self.id_SIGX.setEnabled(True)
self.id_SIGX1.setEnabled(True)
self.id_SIGY.setEnabled(True)
self.id_SIGY1.setEnabled(True)
self.id_CURRENT.setEnabled(True)
self.id_PERIOD.setEnabled(True)
self.id_NP.setEnabled(True)
else:
self.id_ENERGY.setEnabled(False)
self.id_ENERGY_SPREAD.setEnabled(False)
self.id_SIGX.setEnabled(False)
self.id_SIGX1.setEnabled(False)
self.id_SIGY.setEnabled(False)
self.id_SIGY1.setEnabled(False)
self.id_CURRENT.setEnabled(False)
self.id_PERIOD.setEnabled(False)
self.id_NP.setEnabled(False)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = OWxtc()
w.show()
app.exec()
w.saveSettings() | PypiClean |
/CLOVER_GUI-1.0.0a1-py3-none-any.whl/clover_gui/details/system.py |
import ttkbootstrap as ttk
import tkinter as tk
from clover import ProgrammerJudgementFault
from clover.fileparser import BATTERY, DIESEL_GENERATOR
from clover.generation.solar import PVPanel
from clover.impact.finance import ImpactingComponent
from clover.impact.__utils__ import LIFETIME, SIZE_INCREMENT
from clover.simulation.__utils__ import (
AC_TO_AC,
AC_TO_DC,
CONVERSION,
DC_TO_AC,
DC_TO_DC,
)
from clover.simulation.diesel import DieselGenerator
from clover.simulation.energy_system import Minigrid
from clover.simulation.storage_utils import Battery
from ttkbootstrap.constants import *
from ttkbootstrap.scrolled import *
__all__ = ("SystemFrame",)
class SystemFrame(ttk.Frame):
"""
Represents the System frame.
Contains System inputs for the system.
TODO: Update attributes.
"""
def __init__(self, parent):
super().__init__(parent)
self.rowconfigure(0, weight=1) # scrolled frame
self.columnconfigure(0, weight=1)
# Create the scrollable frame and rows
self.scrollable_system_frame = ScrolledFrame(
self,
)
self.scrollable_system_frame.grid(
row=0,
column=0,
padx=10,
pady=5,
ipady=0,
ipadx=0,
sticky="news",
)
self.scrollable_system_frame.rowconfigure(0, weight=1)
self.scrollable_system_frame.rowconfigure(1, weight=1)
self.scrollable_system_frame.rowconfigure(2, weight=1)
self.scrollable_system_frame.rowconfigure(3, weight=1)
self.scrollable_system_frame.rowconfigure(4, weight=1)
self.scrollable_system_frame.rowconfigure(5, weight=1)
self.scrollable_system_frame.rowconfigure(6, weight=1)
self.scrollable_system_frame.rowconfigure(7, weight=1)
self.scrollable_system_frame.rowconfigure(8, weight=1)
self.scrollable_system_frame.rowconfigure(9, weight=1)
self.scrollable_system_frame.rowconfigure(10, weight=1)
self.scrollable_system_frame.rowconfigure(11, weight=1)
self.scrollable_system_frame.rowconfigure(12, weight=1)
self.scrollable_system_frame.rowconfigure(13, weight=1)
self.scrollable_system_frame.rowconfigure(14, weight=1)
self.scrollable_system_frame.rowconfigure(15, weight=1)
self.scrollable_system_frame.rowconfigure(16, weight=1)
self.scrollable_system_frame.rowconfigure(17, weight=1)
self.scrollable_system_frame.rowconfigure(18, weight=1)
self.scrollable_system_frame.columnconfigure(0, weight=1)
self.scrollable_system_frame.columnconfigure(1, weight=1)
self.scrollable_system_frame.columnconfigure(2, weight=1)
self.scrollable_system_frame.columnconfigure(3, weight=1)
self.scrollable_system_frame.columnconfigure(4, weight=1)
self.scrollable_system_frame.columnconfigure(5, weight=1)
# Transmission and conversion efficiencies header
# custom_font = tk.font.nametofont("TkDefaultFont")
# custom_font_bold =custom_font.configure(weight="bold")
bold_head = ttk.Style()
bold_head.configure("Bold.TLabel", font=("TkDefaultFont", 12, "bold"))
self.efficiencies_header = ttk.Label(
self.scrollable_system_frame,
text="Transmission and Conversion Efficiencies",
style="Bold.TLabel",
)
self.efficiencies_header.grid(row=0, column=1, padx=10, pady=5, sticky="w")
# AC transmission efficiency
self.ac_transmission_label = ttk.Label(
self.scrollable_system_frame, text="AC transmission efficiency"
)
self.ac_transmission_label.grid(row=1, column=1, padx=10, pady=5, sticky="w")
self.ac_transmission = ttk.DoubleVar(self, "92")
def scalar_ac_transmission(_):
self.ac_transmission.set(
round(max(min(self.ac_transmission.get(), 100), 0), 0)
)
self.ac_transmission_entry.update()
self.ac_transmission_slider = ttk.Scale(
self.scrollable_system_frame,
from_=0,
to=100,
orient=ttk.HORIZONTAL,
length=320,
command=scalar_ac_transmission,
bootstyle=WARNING,
variable=self.ac_transmission,
)
self.ac_transmission_slider.grid(row=1, column=2, padx=10, pady=5, sticky="ew")
def enter_ac_transmission(_):
self.ac_transmission.set(round(self.ac_transmission_entry.get(), 2))
self.ac_transmission_slider.set(round(self.ac_transmission.get(), 2))
self.ac_transmission_entry = ttk.Entry(
self.scrollable_system_frame,
bootstyle=WARNING,
textvariable=self.ac_transmission,
)
self.ac_transmission_entry.grid(row=1, column=3, padx=10, pady=5, sticky="ew")
self.ac_transmission_entry.bind("<Return>", enter_ac_transmission)
self.ac_transmission_unit = ttk.Label(self.scrollable_system_frame, text=f"%")
self.ac_transmission_unit.grid(row=1, column=4, padx=10, pady=5, sticky="ew")
# DC transmission efficiency
self.dc_transmission_label = ttk.Label(
self.scrollable_system_frame, text="DC transmission efficiency"
)
self.dc_transmission_label.grid(row=2, column=1, padx=10, pady=5, sticky="w")
self.dc_transmission = ttk.DoubleVar(self, "96")
def scalar_dc_transmission(_):
self.dc_transmission.set(
round(max(min(self.dc_transmission.get(), 100), 0), 0)
)
self.dc_transmission_entry.update()
self.dc_transmission_slider = ttk.Scale(
self.scrollable_system_frame,
from_=0,
to=100,
orient=ttk.HORIZONTAL,
length=320,
command=scalar_dc_transmission,
bootstyle=WARNING,
variable=self.dc_transmission,
)
self.dc_transmission_slider.grid(row=2, column=2, padx=10, pady=5, sticky="ew")
def enter_dc_transmission(_):
self.dc_transmission.set(round(self.dc_transmission_entry.get(), 2))
self.dc_transmission_slider.set(round(self.dc_transmission.get()), 2)
self.dc_transmission_entry = ttk.Entry(
self.scrollable_system_frame,
bootstyle=WARNING,
textvariable=self.dc_transmission,
)
self.dc_transmission_entry.grid(row=2, column=3, padx=10, pady=5, sticky="ew")
self.dc_transmission_entry.bind("<Return>", enter_dc_transmission)
self.dc_transmission_unit = ttk.Label(self.scrollable_system_frame, text=f"%")
self.dc_transmission_unit.grid(row=2, column=4, padx=10, pady=5, sticky="ew")
# # DC to AC conversion efficiency
self.dc_to_ac_conversion_label = ttk.Label(
self.scrollable_system_frame, text="DC to AC conversion efficiency"
)
self.dc_to_ac_conversion_label.grid(
row=3, column=1, padx=10, pady=5, sticky="w"
)
self.dc_to_ac_conversion = ttk.DoubleVar(self, 97)
def scalar_dc_to_ac_conversion(_):
self.dc_to_ac_conversion.set(
round(max(min(self.dc_to_ac_conversion.get(), 100), 0), 0)
)
self.dc_to_ac_conversion_entry.update()
self.dc_to_ac_conversion_slider = ttk.Scale(
self.scrollable_system_frame,
from_=0,
to=100,
orient=ttk.HORIZONTAL,
length=320,
command=scalar_dc_to_ac_conversion,
bootstyle=WARNING,
variable=self.dc_to_ac_conversion,
)
self.dc_to_ac_conversion_slider.grid(
row=3, column=2, padx=10, pady=5, sticky="ew"
)
def enter_dc_to_ac_conversion(_):
self.dc_to_ac_conversion.set(round(self.dc_to_ac_conversion_entry.get(), 2))
self.dc_to_ac_conversion_slider.set(
round(self.dc_to_ac_conversion.get(), 2)
)
self.dc_to_ac_conversion_entry = ttk.Entry(
self.scrollable_system_frame,
bootstyle=WARNING,
textvariable=self.dc_to_ac_conversion,
)
self.dc_to_ac_conversion_entry.grid(
row=3, column=3, padx=10, pady=5, sticky="ew"
)
self.dc_to_ac_conversion_entry.bind("<Return>", enter_dc_to_ac_conversion)
self.dc_to_ac_conversion_unit = ttk.Label(
self.scrollable_system_frame, text=f"%"
)
self.dc_to_ac_conversion_unit.grid(
row=3, column=4, padx=10, pady=5, sticky="ew"
)
# # DC to DC conversion efficiency
self.dc_to_dc_conversion_label = ttk.Label(
self.scrollable_system_frame, text="DC to DC conversion efficiency"
)
self.dc_to_dc_conversion_label.grid(
row=4, column=1, padx=10, pady=5, sticky="w"
)
self.dc_to_dc_conversion = ttk.DoubleVar(self, "95")
def scalar_dc_to_dc_conversion(_):
self.dc_to_dc_conversion.set(
round(max(min(self.dc_to_dc_conversion.get(), 100), 0), 0)
)
self.dc_to_dc_conversion_entry.update()
self.dc_to_dc_conversion_slider = ttk.Scale(
self.scrollable_system_frame,
from_=0,
to=100,
orient=ttk.HORIZONTAL,
length=320,
command=scalar_dc_to_dc_conversion,
bootstyle=WARNING,
variable=self.dc_to_dc_conversion,
)
self.dc_to_dc_conversion_slider.grid(
row=4, column=2, padx=10, pady=5, sticky="ew"
)
def enter_dc_to_dc_conversion(_):
self.dc_to_dc_conversion.set(round(self.dc_to_dc_conversion_entry.get(), 2))
self.dc_to_dc_conversion_slider.set(
round(self.dc_to_dc_conversion.get(), 2)
)
self.dc_to_dc_conversion_entry = ttk.Entry(
self.scrollable_system_frame,
bootstyle=WARNING,
textvariable=self.dc_to_dc_conversion,
)
self.dc_to_dc_conversion_entry.grid(
row=4, column=3, padx=10, pady=5, sticky="ew"
)
self.dc_to_dc_conversion_entry.bind("<Return>", enter_dc_to_dc_conversion)
self.dc_to_dc_conversion_unit = ttk.Label(
self.scrollable_system_frame, text=f"%"
)
self.dc_to_dc_conversion_unit.grid(
row=4, column=4, padx=10, pady=5, sticky="ew"
)
# # AC to DC conversion efficiency
self.ac_to_dc_conversion_label = ttk.Label(
self.scrollable_system_frame, text="AC to DC conversion efficiency"
)
self.ac_to_dc_conversion_label.grid(
row=5, column=1, padx=10, pady=5, sticky="w"
)
self.ac_to_dc_conversion = ttk.DoubleVar(self, "90")
def scalar_ac_to_dc_conversion(_):
self.ac_to_dc_conversion.set(
round(max(min(self.ac_to_dc_conversion.get(), 100), 0), 0)
)
self.ac_to_dc_conversion_entry.update()
self.ac_to_dc_conversion_slider = ttk.Scale(
self.scrollable_system_frame,
from_=0,
to=100,
orient=ttk.HORIZONTAL,
length=320,
command=scalar_ac_to_dc_conversion,
bootstyle=WARNING,
variable=self.ac_to_dc_conversion,
)
self.ac_to_dc_conversion_slider.grid(
row=5, column=2, padx=10, pady=5, sticky="ew"
)
def enter_ac_to_dc_conversion(_):
self.ac_to_dc_conversion.set(round(self.ac_to_dc_conversion_entry.get(), 2))
self.ac_to_dc_conversion_slider.set(
round(self.ac_to_dc_conversion.get(), 2)
)
self.ac_to_dc_conversion_entry = ttk.Entry(
self.scrollable_system_frame,
bootstyle=WARNING,
textvariable=self.ac_to_dc_conversion,
)
self.ac_to_dc_conversion_entry.grid(
row=5, column=3, padx=10, pady=5, sticky="ew"
)
self.ac_to_dc_conversion_entry.bind("<Return>", enter_ac_to_dc_conversion)
self.ac_to_dc_conversion_unit = ttk.Label(
self.scrollable_system_frame, text=f"%"
)
self.ac_to_dc_conversion_unit.grid(
row=5, column=4, padx=10, pady=5, sticky="ew"
)
# # AC to AC conversion efficiency
self.ac_to_ac_conversion_label = ttk.Label(
self.scrollable_system_frame, text="AC to AC conversion efficiency"
)
self.ac_to_ac_conversion_label.grid(
row=6, column=1, padx=10, pady=5, sticky="w"
)
self.ac_to_ac_conversion = ttk.DoubleVar(self.scrollable_system_frame, "98")
def scalar_ac_to_ac_conversion(_):
self.ac_to_ac_conversion.set(
round(max(min(self.ac_to_ac_conversion.get(), 100), 0), 0)
)
self.ac_to_ac_conversion_entry.update()
self.ac_to_ac_conversion_slider = ttk.Scale(
self.scrollable_system_frame,
from_=0,
to=100,
orient=ttk.HORIZONTAL,
length=320,
command=scalar_ac_to_ac_conversion,
bootstyle=WARNING,
variable=self.ac_to_ac_conversion,
)
self.ac_to_ac_conversion_slider.grid(
row=6, column=2, padx=10, pady=5, sticky="ew"
)
def enter_ac_to_ac_conversion(_):
self.ac_to_ac_conversion.set(round(self.ac_to_ac_conversion_entry.get(), 2))
self.ac_to_ac_conversion_slider.set(
round(self.ac_to_ac_conversion.get(), 2)
)
self.ac_to_ac_conversion_entry = ttk.Entry(
self.scrollable_system_frame,
bootstyle=WARNING,
textvariable=self.ac_to_ac_conversion,
)
self.ac_to_ac_conversion_entry.grid(
row=6, column=3, padx=10, pady=5, sticky="ew"
)
self.ac_to_ac_conversion_entry.bind("<Return>", enter_ac_to_ac_conversion)
self.ac_to_ac_conversion_unit = ttk.Label(
self.scrollable_system_frame, text=f"%"
)
self.ac_to_ac_conversion_unit.grid(
row=6, column=4, padx=10, pady=5, sticky="ew"
)
# Empty row
self.empty_row = ttk.Label(self.scrollable_system_frame, text="")
self.empty_row.grid(row=7, column=1, padx=10, pady=5, sticky="w")
# Line separator
self.horizontal_divider = ttk.Separator(
self.scrollable_system_frame, orient=ttk.HORIZONTAL
)
self.horizontal_divider.grid(
row=8, column=1, columnspan=7, padx=10, pady=5, sticky="ew"
)
# Inverter settings header
self.inverter_header = ttk.Label(
self.scrollable_system_frame, text="Inverter Settings", style="Bold.TLabel"
)
self.inverter_header.grid(row=9, column=1, padx=10, pady=5, sticky="w")
# Inverter lifetime
self.inverter_lifetime_label = ttk.Label(
self.scrollable_system_frame, text="Inverter lifetime"
)
self.inverter_lifetime_label.grid(row=10, column=1, padx=10, pady=5, sticky="w")
self.inverter_lifetime = ttk.IntVar(self, "10")
def _round_inverter_lifetime(_) -> None:
"""Round the inverter lifetime to the nearest integer."""
self.inverter_lifetime.set(int(self.inverter_lifetime.get()))
self.inverter_lifetime_entry.update()
self.inverter_lifetime_entry = ttk.Entry(
self.scrollable_system_frame,
bootstyle=WARNING,
textvariable=self.inverter_lifetime,
)
self.inverter_lifetime_entry.bind("<Return>", _round_inverter_lifetime)
self.inverter_lifetime_entry.grid(
row=10, column=2, padx=10, pady=5, sticky="ew"
)
self.inverter_lifetime_unit = ttk.Label(
self.scrollable_system_frame, text=f"years"
)
self.inverter_lifetime_unit.grid(row=10, column=3, padx=10, pady=5, sticky="ew")
# Inverter step size
self.inverter_step_size_label = ttk.Label(
self.scrollable_system_frame, text="Inverter step size"
)
self.inverter_step_size_label.grid(
row=11, column=1, padx=10, pady=5, sticky="w"
)
self.inverter_step_size = ttk.IntVar(self, "1")
self.inverter_step_size_entry = ttk.Entry(
self.scrollable_system_frame,
bootstyle=WARNING,
textvariable=self.inverter_step_size,
)
self.inverter_step_size_entry.grid(
row=11, column=2, padx=10, pady=5, sticky="ew"
)
self.inverter_step_size_unit = ttk.Label(
self.scrollable_system_frame, text=f"kW"
)
self.inverter_step_size_unit.grid(
row=11, column=3, padx=10, pady=5, sticky="ew"
)
# Empty line
self.empty_row = ttk.Label(self.scrollable_system_frame, text="")
self.empty_row.grid(row=12, column=1, padx=10, pady=5, sticky="w")
# Line separator
self.horizontal_divider = ttk.Separator(
self.scrollable_system_frame, orient=ttk.HORIZONTAL
)
# Line divider
self.horizontal_divider.grid(
row=13, column=1, columnspan=7, padx=10, pady=5, sticky="ew"
)
# System set-up header
self.system_header = ttk.Label(
self.scrollable_system_frame, text="System Setup", style="Bold.TLabel"
)
self.system_header.grid(row=14, column=1, padx=10, pady=5, sticky="w")
# Select battery
self.battery_label = ttk.Label(self.scrollable_system_frame, text="Battery")
self.battery_label.grid(row=15, column=1, padx=10, pady=5, sticky="w")
self.battery = ttk.StringVar(self, "")
self.battery_combobox = ttk.Combobox(
self.scrollable_system_frame,
values=[],
state=READONLY,
bootstyle=WARNING,
textvariable=self.battery,
)
self.battery_combobox.grid(row=15, column=2, padx=10, pady=5, sticky="ew")
# Select diesel generator
self.diesel_generator_label = ttk.Label(
self.scrollable_system_frame, text="Diesel generator"
)
self.diesel_generator_label.grid(row=16, column=1, padx=10, pady=5, sticky="w")
self.diesel_generator = ttk.StringVar(self, "")
self.diesel_generator_combobox = ttk.Combobox(
self.scrollable_system_frame,
values=[],
state=READONLY,
bootstyle=WARNING,
textvariable=self.diesel_generator,
)
self.diesel_generator_combobox.grid(
row=16, column=2, padx=10, pady=5, sticky="ew"
)
# Select PV panel
self.pv_panel_label = ttk.Label(self.scrollable_system_frame, text="PV panel")
self.pv_panel_label.grid(row=17, column=1, padx=10, pady=5, sticky="w")
self.pv_panel = ttk.StringVar(self, "")
self.pv_panel_combobox = ttk.Combobox(
self.scrollable_system_frame,
values=[],
state=READONLY,
bootstyle=WARNING,
textvariable=self.pv_panel,
)
self.pv_panel_combobox.grid(row=17, column=2, padx=10, pady=5, sticky="ew")
# Select heat exchanger
self.heat_exchanger_label = ttk.Label(
self.scrollable_system_frame, text="AC heat exchanger"
)
# self.heat_exchanger_label.grid(row=12, column=1, padx=10, pady=5, sticky="w")
self.heat_exchanger = ttk.StringVar(self, "")
self.heat_exchanger_combobox = ttk.Combobox(
self.scrollable_system_frame,
values=[],
state=DISABLED,
bootstyle=WARNING,
)
# self.heat_exchanger_combobox.grid(
# row=12, column=2, padx=10, pady=5, sticky="ew"
# )
# Select the grid profile
self.grid_profile_label = ttk.Label(
self.scrollable_system_frame, text="Grid profile"
)
self.grid_profile_label.grid(row=18, column=1, padx=10, pady=5, sticky="w")
self.grid_profile = ttk.StringVar(self, "")
self.grid_profile_combobox = ttk.Combobox(
self.scrollable_system_frame,
values=[],
state=READONLY,
bootstyle=WARNING,
textvariable=self.grid_profile,
)
self.grid_profile_combobox.grid(row=18, column=2, padx=10, pady=5, sticky="ew")
# Empty row
self.empty_row = ttk.Label(self.scrollable_system_frame, text="")
self.empty_row.grid(row=19, column=1, padx=10, pady=5, sticky="w")
def set_system(
self,
batteries: list[Battery],
diesel_generators: list[DieselGenerator],
grid_profile_name: str,
minigrid: Minigrid,
pv_panels: list[PVPanel],
) -> None:
"""
Sets the scenarios on the system frame.
"""
# Update the AC transmission efficiency
self.ac_transmission.set(float(100 * minigrid.ac_transmission_efficiency))
self.ac_transmission_entry.update()
self.ac_transmission_slider.set(self.ac_transmission.get())
# Update the DC transmission efficiency
self.dc_transmission.set(float(100 * minigrid.dc_transmission_efficiency))
self.dc_transmission_entry.update()
self.dc_transmission_slider.set(self.dc_transmission.get())
# Update the conversion efficincies
self.ac_to_ac_conversion.set(
float(100 * minigrid.ac_to_ac_conversion_efficiency)
)
self.ac_to_ac_conversion_entry.update()
self.ac_to_ac_conversion_slider.set(self.ac_to_ac_conversion.get())
self.ac_to_dc_conversion.set(
float(100 * minigrid.ac_to_dc_conversion_efficiency)
)
self.ac_to_dc_conversion_entry.update()
self.ac_to_dc_conversion_slider.set(self.ac_to_dc_conversion.get())
self.dc_to_ac_conversion.set(
float(100 * minigrid.dc_to_ac_conversion_efficiency)
)
self.dc_to_ac_conversion_entry.update()
self.dc_to_ac_conversion_slider.set(self.dc_to_ac_conversion.get())
self.dc_to_dc_conversion.set(
float(100 * minigrid.dc_to_dc_conversion_efficiency)
)
self.dc_to_dc_conversion_entry.update()
self.dc_to_dc_conversion_slider.set(self.dc_to_dc_conversion.get())
# Update the battery name
if minigrid.battery is not None:
self.battery.set(minigrid.battery.name)
else:
self.battery_combobox.configure(state=DISABLED)
# Update the combobox
self.battery_combobox["values"] = [entry.name for entry in batteries]
self.battery_combobox.set(self.battery.get())
# Update the PV-panel name
try:
if minigrid.pv_panel is not None:
self.pv_panel.set(minigrid.pv_panel.name)
else:
self.pv_panel_combobox.configure(state=DISABLED)
except ProgrammerJudgementFault:
self.pv_panel.set(minigrid.pv_panels[0].name)
# Update the combobox
self.pv_panel_combobox["values"] = [entry.name for entry in pv_panels]
self.pv_panel_combobox.set(self.pv_panel.get())
# Update the diesel-generator name
if minigrid.diesel_generator is not None:
self.diesel_generator.set(minigrid.diesel_generator.name)
else:
self.diesel_generator_combobox.configure(state=DISABLED)
# Update the combobox
self.diesel_generator_combobox["values"] = [
entry.name for entry in diesel_generators
]
self.diesel_generator_combobox.set(self.diesel_generator.get())
# Update the heat-exchanger name
if minigrid.heat_exchanger is not None:
self.heat_exchanger.set(minigrid.heat_exchanger.name)
self.heat_exchanger_combobox.configure(state=READONLY)
else:
self.heat_exchanger_combobox.configure(state=DISABLED)
self.heat_exchanger_combobox.set(self.heat_exchanger.get())
# Update the grid profile name
self.grid_profile_combobox.set(grid_profile_name)
# Update the inverter information.
self.inverter_lifetime.set(minigrid.inverter.lifetime)
self.inverter_lifetime_entry.update()
self.inverter_step_size.set(minigrid.inverter.size_increment)
self.inverter_step_size_entry.update()
def add_battery(self, battery_name: str) -> None:
"""
Add a battery to the list of selectable options.
:param: battery_name
The name of the battery to add.
"""
self.battery_combobox["values"] = self.battery_combobox["values"] + (
battery_name,
)
def add_diesel_generator(self, diesel_generator_name: str) -> None:
"""
Add a diesel generator to the list of selectable options.
:param: diesel_generator_name
The name of the diesel generator to add.
"""
self.diesel_generator_combobox["values"] = self.diesel_generator_combobox[
"values"
] + (diesel_generator_name,)
def add_pv_panel(self, pv_panel_name: str) -> None:
"""
Add a solar panel to the list of selectable options.
:param: pv_panel_name
The name of the PV panel to add.
"""
self.pv_panel_combobox["values"] = self.pv_panel_combobox["values"] + (
pv_panel_name,
)
def add_grid_profile(self, grid_profile_name: str) -> None:
"""
Add a grid profile to the list of selectable options.
:param: grid_profile_name
The name of the grid profile to add.
"""
if not isinstance(self.grid_profile_combobox["values"], tuple):
self.grid_profile_combobox["values"] = (grid_profile_name,)
return
self.grid_profile_combobox["values"] = self.grid_profile_combobox["values"] + (
grid_profile_name,
)
def set_batteries(self, battery_names: list[str]) -> None:
"""
Set the names of the batteries in the combobox.
:param: battery_names
The `list` of battery names to set.
"""
self.battery_combobox["values"] = battery_names
if self.battery_combobox.get() not in battery_names:
self.battery_combobox.set(battery_names[0])
def set_diesel_generators(self, generator_names: list[str]) -> None:
"""
Set the names of the generators in the combobox.
:param: generator_names
The `list` of diesel generator names to set.
"""
self.diesel_generator_combobox["values"] = generator_names
if self.diesel_generator_combobox.get() not in generator_names:
self.diesel_generator_combobox.set(generator_names[0])
def set_pv_panels(self, panel_names: list[str]) -> None:
"""
Set the names of the panel in the combobox.
:param: panel_names
The `list` of panel names to set.
"""
self.pv_panel_combobox["values"] = panel_names
if self.pv_panel_combobox.get() not in panel_names:
self.pv_panel_combobox.set(panel_names[0])
def set_grid_profiles(self, grid_profile_names: list[str]) -> None:
"""
Set the names of the grid profiles in the combobox.
:param: grid_profile_names
The `list` of grid-profile names to set.
"""
self.grid_profile_combobox[(_values := "values")] = grid_profile_names
if self.grid_profile_combobox.get() not in grid_profile_names:
self.grid_profile_combobox.set(grid_profile_names[0])
@property
def as_dict(self) -> dict[str, dict[str, float] | float | str]:
"""
Return the energy-system information as a `dict`.
:returns:
The information as a `dict` ready for saving.
"""
return {
"ac_transmission_efficiency": self.ac_transmission.get() / 100,
"dc_transmission_efficiency": self.dc_transmission.get() / 100,
BATTERY: self.battery_combobox.get(),
CONVERSION: {
AC_TO_AC: self.ac_to_ac_conversion.get() / 100,
AC_TO_DC: self.ac_to_dc_conversion.get() / 100,
DC_TO_AC: self.dc_to_ac_conversion.get() / 100,
DC_TO_DC: self.dc_to_dc_conversion.get() / 100,
},
DIESEL_GENERATOR: self.diesel_generator_combobox.get(),
"pv_panel": self.pv_panel_combobox.get(),
ImpactingComponent.INVERTER.value: {
LIFETIME: int(self.inverter_lifetime.get()),
SIZE_INCREMENT: self.inverter_step_size.get(),
},
} | PypiClean |
/EMC-info-1.5.2.tar.gz/EMC-info-1.5.2/README.md | 
EarthMC is a large Minecraft server this package lets you get info about things on that server.
[PyPI](https://pypi.org/project/EMC-info) **|** [Github](https://github.com/TheSuperGamer20578/EMC-info) **|** [Changelog](https://github.com/TheSuperGamer20578/EMC-info/releases) | [Documentation](https://emc-info.readthedocs.io/en/stable/)
## Installation
```shell
pip install EMC-info
```
## Usage
Importing:
```py
import emc
```
Getting info about a town and printing its mayor's name:
```py
town = emc.Town("town")
print(town.mayor.name)
```
Read the [documentation](https://emc-info.readthedocs.io/en/stable/) for more information
| PypiClean |
/CSVSee-0.2.tar.gz/CSVSee-0.2/docs/csvs.rst | csvs
====
``csvs`` is the primary frontend for CSVSee. You can run this without arguments
to see what it expects. At minimum, you'll need to provide the name of a
command. Currently, two commands are implemented:
* ``csvs graph``: Generate graphs from ``.csv`` files
* ``csvs grep``: Search in text files and generate a ``.csv`` file
* ``csvs grinder``: Create ``.csv`` reports based on Grinder_ output file
csvs graph
----------
The ``graph`` command is designed to generate graphs of comma-separated (.csv)
data files. It was originally designed for graphing data from the Windows
Performance Monitor tool, but it can also be used more generally to graph any
CSV data that includes timestamps.
The only thing you must provide is a ``filename.csv`` containing your data. By
default, the first column of data is used as the X-coordinate; if it's a
timestamp, its format will be guessed.
You can optionally specify one or more regular expressions to match the column
names you want to graph. If you don't provide these, all columns will be
graphed. All data must be integer or floating-point numeric values; anything
that isn't a date or number will be plotted as a 0.
Column names can be specified as regular expressions that may match one or more
column headings in the .csv file. For example, if you have a file called
``perfmon.csv`` with columns named like this::
"Eastern Time","CPU (user)","CPU (system)","CPU (idle)","Memory"
You can generate a graph of user, system, and idle CPU values over time like
this::
csvs graph perfmon.csv "CPU.*"
Run ``csvs graph`` without arguments to see full usage notes.
csvs grep
---------
The ``grep`` command generates a ``.csv`` file by matching strings in one or
more timestamped log files. It would typically be used to generate a report of
how frequently certain messages or errors appear through time.
For example, if you have ``parrot.log`` containing::
2010/08/30 13:57:14 Pushing up the daisies
2010/08/30 13:58:08 Stunned
2010/08/30 13:58:11 Stunned
2010/08/30 14:04:22 Pining for the fjords
2010/08/30 14:05:37 Pushing up the daisies
2010/08/30 14:09:48 Pining for the fjords
And you wanted to see how often each of these phrases occur, do::
csvs grep parrot.log \
-match "Stunned" "Pushing up the daisies" "Pining for the fjords" \
-out parrot.csv
By default, the ``grep`` command counts the number of occurrences each minute,
so this would give you a ``.csv`` file looking something like this (whitespace
added for readability)::
"Timestamp", "Stunned", "Pushing up the daisies", "Pining for the fjords"
2010/08/30 13:57, 0, 1, 0
2010/08/30 13:58, 2, 0, 0
2010/08/30 14:04, 0, 0, 1
2010/08/30 14:05, 0, 1, 0
2010/08/30 14:09, 0, 0, 1
You can change the resolution using the ``-seconds`` option. For example, to
count the occurrences each hour, use ``-seconds 3600``.
Run ``csvs grep`` without arguments to see full usage notes.
csvs grinder
------------
The ``grinder`` command generates ``.csv`` files from Grinder_ logs. You must
provide the name of a ``out*`` file, and one or more ``data*`` files generated
from the same test run::
csvs grinder out-0.log data-*.log foo
This will write four ``.csv`` files in the current directory:
* ``foo_Errors.csv``
* ``foo_HTTP_response_errors.csv``
* ``foo_HTTP_response_length.csv``
* ``foo_Test_time.csv``
By default, statistics are summarized with a 60-second resolution; that is, all
statistics within each 60-second interval are summed (in the case of errors) or
averaged (in the case of response length and test time). To change the interval
resolution, pass the ``-seconds`` option. For instance, to summarize statistics
in 10-minute intervals::
csvs grinder -seconds 600 out-0.log data-*.log foo
Run ``csvs grinder`` without arguments to see full usage notes.
.. _Grinder: http://grinder.sourceforge.net/
| PypiClean |
/Couchapp-1.0.2.tar.gz/Couchapp-1.0.2/couchapp/templates/vendor/couchapp/_attachments/jquery.couchProfile.js |
(function($) {
$.couchProfile = {};
$.couchProfile.templates = {
profileReady : '<div class="avatar">{{#gravatar_url}}<img src="{{gravatar_url}}"/>{{/gravatar_url}}<div class="name">{{nickname}}</div></div><p>Hello {{nickname}}!</p><div style="clear:left;"></div>',
newProfile : '<form><p>Hello {{name}}, Please setup your user profile.</p><label for="nickname">Nickname <input type="text" name="nickname" value=""></label><label for="email">Email (<em>for <a href="http://gravatar.com">Gravatar</a></em>) <input type="text" name="email" value=""></label><label for="url">URL <input type="text" name="url" value=""></label><input type="submit" value="Go →"><input type="hidden" name="userCtxName" value="{{name}}" id="userCtxName"></form>'
};
$.fn.couchProfile = function(session, opts) {
opts = opts || {};
var templates = $.couchProfile.templates;
var userCtx = session.userCtx;
var widget = $(this);
// load the profile from the user doc
var db = $.couch.db(session.info.authentication_db);
var userDocId = "org.couchdb.user:"+userCtx.name;
db.openDoc(userDocId, {
success : function(userDoc) {
var profile = userDoc["couch.app.profile"];
if (profile) {
profile.name = userDoc.name;
profileReady(profile);
} else {
newProfile(userCtx)
}
}
});
function profileReady(profile) {
widget.html($.mustache(templates.profileReady, profile));
if (opts.profileReady) {opts.profileReady(profile)};
};
function storeProfileOnUserDoc(newProfile) {
// store the user profile on the user account document
$.couch.userDb(function(db) {
var userDocId = "org.couchdb.user:"+userCtx.name;
db.openDoc(userDocId, {
success : function(userDoc) {
userDoc["couch.app.profile"] = newProfile;
db.saveDoc(userDoc, {
success : function() {
newProfile.name = userDoc.name;
profileReady(newProfile);
}
});
}
});
});
};
function newProfile(userCtx) {
widget.html($.mustache(templates.newProfile, userCtx));
widget.find("form").submit(function(e) {
e.preventDefault();
var form = this;
var name = $("input[name=userCtxName]",form).val();
var newProfile = {
rand : Math.random().toString(),
nickname : $("input[name=nickname]",form).val(),
email : $("input[name=email]",form).val(),
url : $("input[name=url]",form).val()
};
// setup gravatar_url if md5.js is loaded
if (hex_md5) {
newProfile.gravatar_url = 'http://www.gravatar.com/avatar/'+hex_md5(newProfile.email || newProfile.rand)+'.jpg?s=40&d=identicon';
}
storeProfileOnUserDoc(newProfile);
return false;
});
};
}
})(jQuery); | PypiClean |
/MistressGPT-0.9.9.tar.gz/MistressGPT-0.9.9/chatmistress/chatmistress.py | import os
from typing import Dict, List, Optional, Union
import click
from dotenv import load_dotenv
from prompt_toolkit import PromptSession
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import FileHistory
from rich.console import Console
from .core import init_chat_components, interact
from .utils import RoleInfo, fetch_template, load_roles
from .webbot2 import creat_gui_chat
from .logging_utils import logger
load_dotenv()
def launch_cli_chat(
role_info: RoleInfo, session: PromptSession,
res_completer: WordCompleter, console: Console, temperature=0.5, top_p=1, max_token_limit=200,
init_user_input='您好',
debug=False):
conversation, prompt, memory, parser, fix_parser, retry_parser = init_chat_components(
role_info, temperature, top_p, max_token_limit, debug=debug)
parsed_response = interact(conversation, init_user_input,
prompt, memory, parser, fix_parser, retry_parser,
console=console, debug=debug)
i = 0
while True:
i += 1
console.print(f"{role_info.mistress_name} ({parsed_response.pose}):",
parsed_response.line, sep="\n", style="magenta")
if debug:
user_input = '我今天早上出门之前吃了两个苹果' * 20
else:
user_input = session.prompt('我: ', completer=res_completer)
if user_input == '!switch':
return False
if user_input == '!exit':
return True
elif user_input.startswith('~'):
user_input = user_input[1:]
parsed_response = interact(conversation, user_input,
prompt, memory, parser, fix_parser, retry_parser,
console=console, debug=debug)
memory.summrize_lines()
@click.command()
@click.argument('cmd', type=click.Choice(['cli', 'gui']))
@click.option('--debug', default=False, help='Debug mode if True')
@click.option('--max-token-limit', default=1000, help='temperature for openai')
@click.option('--ext-url', default=None, help='外部模板URL')
@click.option('--concurrency', default=20, help='并发数')
@click.option('--inbrowser', default=True, help='是否开启浏览器')
@click.option('--server-name', default=None, help='是否外网可用')
def main(cmd, debug, max_token_limit, ext_url, concurrency, inbrowser, server_name):
assert cmd in ('cli', 'gui')
if 'OPENAI_API_KEY' not in os.environ:
os.environ['OPENAI_API_KEY'] = input(
'OPENAI_API_KEY 环境变量未设置, 请输入你的OPENAI_API_KEY: ')
logger.debug(f'OPENAI_API_KEY: {os.environ["OPENAI_API_KEY"]}')
if ext_url is not None:
roles: Dict[str, RoleInfo] = fetch_template(ext_url)
else:
roles: Dict[str, RoleInfo] = load_roles()
if debug:
max_token_limit = 200
if cmd == 'gui':
gui = creat_gui_chat(roles, debug=debug,
max_token_limit=max_token_limit)
gui.queue(concurrency_count=concurrency).launch(
server_name=server_name, inbrowser=inbrowser)
elif cmd == 'cli':
console = Console()
session = PromptSession(history=FileHistory('./.role_play_history'))
res_completer = WordCompleter([
'!switch',
'!exit',
'~是,主人',
'~抱歉主人',
'~都听您的',
])
exited = False
while not exited:
role_list = [k for k in roles.keys()]
if len(role_list) > 1:
print(
f'选择你的主人: {", ".join([f"{i}: {k}" for i, k in enumerate(role_list)])}')
if debug:
role_selected = role_list[0]
else:
role_selected = role_list[int(
session.prompt('我想要 (请输入数字): ').strip())]
else:
role_selected = role_list[0]
print(f'你选择了{role_selected}作为你的主人. 请按照提示进行对话.')
exited = launch_cli_chat(roles[role_selected],
session, res_completer, console, debug=debug, max_token_limit=max_token_limit)
print('Bye~')
if __name__ == "__main__":
main()
# roles: Dict[str, RoleInfo] = load_roles()
# debug = True
# max_token_limit = 1000
# demo = creat_gui_chat(
# roles, debug=debug, max_token_limit=max_token_limit)
# if __name__ == "__main__":
# demo.launch() | PypiClean |
/AX3_model_extras-2.0.0-py3-none-any.whl/ax3_model_extras/fields.py | from io import BytesIO
from django.core.exceptions import ValidationError
from django.db.models import ImageField
from django.utils.translation import gettext_lazy as _
from PIL import Image
from resizeimage import resizeimage
from resizeimage.imageexceptions import ImageSizeError
class OptimizedImageField(ImageField):
def __init__(self, *args, **kwargs):
"""
`optimized_image_output_size` must be a tuple and `optimized_image_resize_method` can be
'crop', 'cover', 'contain', 'width', 'height' or 'thumbnail'.
"""
self.optimized_image_output_size = kwargs.pop('optimized_image_output_size', None)
self.optimized_image_resize_method = kwargs.pop('optimized_image_resize_method', 'cover')
self.optimized_file_formats = kwargs.pop('optimized_file_formats', ['JPEG', 'PNG', 'GIF'])
self.optimized_image_quality = kwargs.pop('optimized_image_quality', 75)
super().__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
# Remove the arguments from the kwargs dict.
kwargs.pop('optimized_image_output_size', None)
kwargs.pop('optimized_image_resize_method', None)
kwargs.pop('optimized_file_formats', None)
kwargs.pop('optimized_image_quality', None)
return name, path, args, kwargs
def save_form_data(self, instance, data):
updating_image = data and getattr(instance, self.name) != data
if updating_image:
if self.optimized_image_quality < 0 or self.optimized_image_quality > 100:
raise ValidationError({self.name: [_('The allowed quality is from 0 to 100')]})
try:
data = self.optimize_image(
image_data=data,
output_size=self.optimized_image_output_size,
resize_method=self.optimized_image_resize_method,
quality=self.optimized_image_quality,
)
except ImageSizeError:
raise ValidationError({self.name: [_('Image too small to be scaled')]})
except OSError:
raise ValidationError({self.name: [_('The image is invalid or corrupted')]})
super().save_form_data(instance, data)
def optimize_image(self, image_data, output_size, resize_method, quality):
"""Optimize an image that has not been saved to a file."""
img = Image.open(image_data)
if img.format not in self.optimized_file_formats:
raise ValidationError({self.name: [_('Image format unsupported')]})
# GIF files needs strict size validation
if img.format == 'GIF' and output_size and output_size != (img.width, img.height):
raise ValidationError({self.name: [_('GIF image size unsupported')]})
# Check if is a supported format for optimization
if img.format not in ['JPEG', 'PNG']:
return image_data
# If output_size content 0.
if output_size and output_size[0] == 0:
output_size = (img.width, output_size[1])
elif output_size and output_size[1] == 0:
output_size = (output_size[0], img.height)
# If output_size is set, resize the image with the selected resize_method.
if output_size and output_size != (img.width, img.height):
output_image = resizeimage.resize(resize_method, img, output_size)
else:
output_image = img
# If the file extension is JPEG, convert the output_image to RGB
if img.format == 'JPEG':
output_image = output_image.convert('RGB')
bytes_io = BytesIO()
output_image.save(bytes_io, format=img.format, optimize=True, quality=quality)
image_data.seek(0)
image_data.file.write(bytes_io.getvalue())
image_data.file.truncate()
return image_data | PypiClean |
/InowasFlopyAdapter-1.5.0.tar.gz/InowasFlopyAdapter-1.5.0/FlopyAdapter/Read/ReadDrawdown.py | import os
import flopy.utils.binaryfile as bf
class ReadDrawdown:
_filename = None
def __init__(self, workspace):
for file in os.listdir(workspace):
if file.endswith(".ddn"):
self._filename = os.path.join(workspace, file)
pass
def read_times(self):
try:
heads = bf.HeadFile(filename=self._filename, text='drawdown', precision='single')
times = heads.get_times()
if times is not None:
return times
return []
except:
return []
def read_idx(self):
try:
heads = bf.HeadFile(filename=self._filename, text='drawdown', precision='single')
times = heads.get_times()
return list(range(len(times)))
except:
return []
def read_kstpkper(self):
try:
heads = bf.HeadFile(filename=self._filename, text='drawdown', precision='single')
kstpkper = heads.get_kstpkper()
if kstpkper is not None:
return kstpkper
return []
except:
return []
def read_number_of_layers(self):
try:
heads = bf.HeadFile(filename=self._filename, text='drawdown', precision='single')
number_of_layers = heads.get_data().shape[0]
return number_of_layers
except:
return 0
def read_layer(self, **kwargs):
return self.read_layer_by_totim(**kwargs)
def read_layer_by_totim(self, totim=0, layer=0):
try:
heads = bf.HeadFile(filename=self._filename, text='drawdown', precision='single')
data = heads.get_data(totim=totim, mflay=layer).tolist()
for i in range(len(data)):
for j in range(len(data[i])):
data[i][j] = round(data[i][j], 2)
if data[i][j] < -999:
data[i][j] = None
return data
except:
return []
def read_layer_by_idx(self, idx=0, layer=0):
try:
heads = bf.HeadFile(filename=self._filename, text='drawdown', precision='single')
data = heads.get_data(idx=idx, mflay=layer).tolist()
for i in range(len(data)):
for j in range(len(data[i])):
data[i][j] = round(data[i][j], 2)
if data[i][j] < -999:
data[i][j] = None
return data
except:
return []
def read_layer_by_kstpkper(self, kstpkper=(0, 0), layer=0):
try:
heads = bf.HeadFile(filename=self._filename, text='drawdown', precision='single')
data = heads.get_data(kstpkper=kstpkper, mflay=layer).tolist()
for i in range(len(data)):
for j in range(len(data[i])):
data[i][j] = round(data[i][j], 2)
if data[i][j] < -999:
data[i][j] = None
return data
except:
return []
def read_ts(self, layer=0, row=0, column=0):
try:
heads = bf.HeadFile(filename=self._filename, text='drawdown', precision='single')
return heads.get_ts(idx=(layer, row, column)).tolist()
except:
return [] | PypiClean |
/KarnaughMap-1.1.2.tar.gz/KarnaughMap-1.1.2/src/KMap/Mapper.py | __all__ = ["KarnaughMap"]
__author__ = "Alexander Bisland"
__version__ = "2.6.1"
supported_from = "3.8.1"
import re
import itertools
from typing import Union, TypeVar, List
_KMap = TypeVar("_KMap", bound="KarnaughMap")
class KarnaughMap: # TODO - map middle for 5+6
"""Create Karnaugh Map objects which can be solved and manipulated.
Supported characters:
Any case is supported
or equivalents: |, ||, +, v
and equivalents: &, &&, *, ^
not equivalents: !, ~, ¬
Functions:
Public:
KarnaughMap.reset(self: _KMap) -> None
KarnaughMap.create_map(self: _KMap, tot_input: int = None, expression: str = None) -> (bool) success
KarnaughMap.print(self: _KMap) -> (None)
KarnaughMap.to_string(self: _KMap) -> (str) reader-friendly table
@staticmethod KarnaughMap.get_tot_variables(expression: str) -> (Union[int, None]) total number of variables
KarnaughMap.solve_map(self: _KMap) -> (str) simplified binary logic representation of map
Private:
@staticmethod KarnaughMap._evaluate_expression(equation: Union[str, List]) -> (str) The solution
(bool True/False) as an
integer string ("1"/"0")
GLOBAL static variables:
SINGLE - headings for one variable
DOUBLE - headings for two variables
TRIPLE - headings for three variables
VALUES - pairings for a whole table (index=number of variable)
LETTERS - letters than can be used
Class variables:
self.tot_input = None - total number of variables in the expression (used for table dimensions)
self.expression = None - unsimplified expression
self.valid_symbols = None - list of valid symbols that can be used
self.debug = debug - debug mode (enables some prints)
self.table = [] - the table (can also get access through __repr__)
self.result = "" - the simplified expression
self.raise_error = True - whether to raise errors or just print them
Other data:
Order of operations: BNAO
Only tested up to 4 variables
"""
SINGLE = ['0', '1'] # headings for one variable
DOUBLE = ['00', '01', '11', '10'] # headings for two variables
TRIPLE = ['000', '001', '011', '010', '110', '111', '101', '100'] # headings for three variables
VALUES = [(["0"], ["0"]), (["0"], ["0"]), (SINGLE, SINGLE), (DOUBLE, SINGLE), (DOUBLE, DOUBLE), (TRIPLE, DOUBLE),
(TRIPLE, TRIPLE)] # pairings for a whole table (index=number of variable)
LETTERS = ['a', 'b', 'c', 'd', 'e', 'f'] # letters than can be used
def __init__(self: _KMap, tot_input: int = None, expression: str = None, debug: bool = False,
raise_error: bool = True) -> None:
"""Constructor for the class
Parameters:
self (_KMap): The instantiated object
tot_input (int): The total number of variables in the expression in the expression
(used for table dimensions)
expression (int): An unsimplified expression to map
debug (bool): Whether debug mode is on or not (enables some prints)
raise_error (bool): Whether to raise an error or just print the error
Returns:
Nothing (None): Null
"""
self.table = []
self.tot_input = tot_input
self.expression = expression
self.valid_symbols = None
self.debug = debug
self.result = ""
self.raise_error = raise_error
self.groups = []
def reset(self: _KMap) -> None:
"""Reset all attributes to their defaults (should be used before class is reused)
Parameters:
self (_KMap): The instantiated object
Returns:
Nothing (None): Null
"""
self.tot_input = None
self.expression = None
self.valid_symbols = None
self.table = []
self.result = ""
self.groups = []
def create_map(self: _KMap, tot_input: int = None, expression: str = None) -> bool:
"""Create the actual Karnaugh Map (stored in self.table)
Parameters:
self (_KMap): The instantiated object
tot_input (int): The total number of variables in the expression
expression (int): An unsimplified expression to map
Returns:
success (bool): whether the program succeeded
"""
self.tot_input = self.tot_input if tot_input is None else tot_input
self.expression = self.expression if expression is None else expression
if self.__get_valid_expression():
tableDim = KarnaughMap.VALUES[self.tot_input]
self.table = [[0 for _ in range(len(tableDim[0]))] for _ in range(len(tableDim[1]))]
arrayPos = 0
for heading in itertools.product(tableDim[0], tableDim[1]):
expression = self.expression[:]
for index, letter in enumerate(KarnaughMap.LETTERS[:self.tot_input]):
expression = expression.replace(letter, str(heading[0] + heading[1])[index])
self.table[arrayPos % len(tableDim[1])][arrayPos // len(tableDim[1])] = int(
KarnaughMap._evaluate_expression(KarnaughMap.__remove_brackets(expression)))
arrayPos += 1
if any(len(str(self.table[y][x])) != 1 for y in range(len(tableDim[1])) for x in range(len(tableDim[0]))):
self.table = []
if self.raise_error:
raise ValueError("Invalid Input. Please put symbols between variables")
elif self.debug:
print("Invalid Input. Please put symbols between variables")
return True
return False
def print(self: _KMap) -> None:
"""Function to print the table in a user-friendly way
Parameters:
self (_KMap): The instantiated object
Returns:
Nothing (None): Null
"""
print(self.__str__())
def to_string(self: _KMap) -> str:
"""Function to return the table in a user-friendly way
Parameters:
self (_KMap): The instantiated object
Returns:
table (str): The table as a string in a user-friendly way
" ab 00 01 11 10
cd
00 [ 1, 1, 1, 1],
01 [ 1, 0, 0, 1],
11 [ 1, 0, 0, 1],
10 [ 1, 1, 1, 1]"
"""
return self.__str__()
def __str__(self: _KMap) -> str:
"""Function to return the table in a user-friendly way
Parameters:
self (_KMap): The instantiated object
Returns:
table (str): The table as a string in a user-friendly way e.g.
" ab 00 01 11 10
cd
00 [ 1, 1, 1, 1],
01 [ 1, 0, 0, 1],
11 [ 1, 0, 0, 1],
10 [ 1, 1, 1, 1]"
"""
tableDimValues = KarnaughMap.VALUES[self.tot_input]
output = (" " * len(tableDimValues[1][0])) + "".join(KarnaughMap.LETTERS[:len(tableDimValues[0][0])]) + \
(" " * (4 - len(tableDimValues[0][0]))) + \
(" " * (4 - len(tableDimValues[0][0]))).join(tableDimValues[0]) + "\n"
output += "".join(KarnaughMap.LETTERS[len(tableDimValues[0][0]):
len(tableDimValues[0][0]) + len(tableDimValues[1][0])]) + "\n"
for index, row in enumerate(self.table):
output += tableDimValues[1][index] + " " * len(tableDimValues[0][0]) + "[ " + \
", ".join([str(cell) for cell in row]) + "],\n"
return output[:-1]
def __repr__(self: _KMap) -> List[List[int]]:
"""Function that defines the representation of the class
Parameters:
self (_KMap): The instantiated object
Returns:
self.table (List[List[str]]): The Karnaugh map stored in the class
"""
return self.table
@staticmethod
def _evaluate_expression(equation: Union[str, List]) -> str:
"""Function to take a multi-dimensional list (seperated by brackets) and solve it
Parameters:
equation (Union[str, List]): multi-dimensional list
Returns:
solution (str): The solution (bool True/False) as an integer string ("1"/"0")
"""
for index, element in enumerate(equation):
if isinstance(element, list): # if the element is a list then recursively perform this function \
equation[index] = KarnaughMap._evaluate_expression(element) # until you have the innermost list
return KarnaughMap.__solve_simple("".join(equation))
@staticmethod
def __solve_simple(equation: str) -> str:
"""Private function to simplify a simple boolean expression (no brackets)
Parameters:
equation (str): A simple boolean expression (no brackets)
Returns:
solution (str): The solution (bool True/False) as an integer string ("1"/"0")
"""
equation = list(equation)
while '¬' in equation: # find all nots and replace with the solution
pos = equation.index('¬')
equation = equation[:pos] + equation[pos + 1:]
equation[pos] = str(int(not int(equation[pos])))
while '^' in equation: # find all ands and replace with the solution
pos = equation.index('^')
equation[pos + 1] = str(int(int(equation[pos - 1]) and int(equation[pos + 1])))
equation = equation[:pos - 1] + equation[pos + 1:]
while 'v' in equation: # find all ors and replace with the solution
pos = equation.index('v')
equation[pos + 1] = str(int(int(equation[pos - 1]) or int(equation[pos + 1])))
equation = equation[:pos - 1] + equation[pos + 1:]
return "".join(equation) # should be only one character
def __get_valid_expression(self: _KMap) -> bool:
"""Private function to get an expression, check if it is valid and simplify format (e.g. remove spaces)
Parameters:
self (_KMap): The instantiated object
Returns:
valid (bool): whether the expression is valid
"""
try: # attempt to get a valid number for the total number of variables
if self.tot_input is None: # if not predefined (passed in)
if self.expression is not None: # first try to calculate automatically
self.tot_input = KarnaughMap.get_tot_variables(self.expression)
if self.tot_input is None: # otherwise ask for user input
self.tot_input = int(input("How many variables (max 4)? "))
if self.tot_input not in [2, 3, 4, 5, 6]: # start the checks for validity
if self.tot_input < 2:
self.table = []
if self.raise_error:
raise ValueError("Num of inputs must be greater than or equal to 2: " + str(self.tot_input))
elif self.debug:
print("Num of inputs must be greater than or equal to 2: " + str(self.tot_input))
self.tot_input = None
elif self.tot_input > 6:
self.table = []
if self.raise_error:
raise ValueError("Num of inputs must be less than or equal to 6: " + str(self.tot_input))
elif self.debug:
print("Num of inputs must be less than or equal to 6: " + str(self.tot_input))
self.tot_input = None
return False
except ValueError:
self.table = []
if self.raise_error:
raise ValueError("Num of inputs must be a number")
elif self.debug:
print("Num of inputs must be a number")
self.tot_input = None
return False
self.valid_symbols = ['v', '^', '¬', '(', ')'] + KarnaughMap.LETTERS[:self.tot_input]
if self.expression is None: # if expression isn't defined ask for user input
self.expression = input(
"Type your expression (using " + ",".join(KarnaughMap.LETTERS[:self.tot_input]) + "): ")
self.expression = self.expression.lower() # start reformatting of expression to only contain letters and ^v¬
self.expression = self.expression.replace('|', 'v')
self.expression = self.expression.replace('&', '^')
self.expression = self.expression.replace('||', 'v')
self.expression = self.expression.replace('&&', '^')
self.expression = self.expression.replace('!', '¬')
self.expression = self.expression.replace('+', 'v')
self.expression = self.expression.replace('*', '^')
self.expression = self.expression.replace('~', '¬')
self.expression = self.expression.replace('or', 'v')
self.expression = self.expression.replace('and', '^')
self.expression = self.expression.replace('not', '¬')
self.expression = self.expression.replace(' ', '')
self.expression = self.expression.replace('¬¬', '')
if len(self.expression) == 0: # start the checks for validity
self.table = []
if self.raise_error:
raise ValueError("Please input an expression")
elif self.debug:
print("Please input an expression")
self.expression = None
return False
if all(symbol in ['v', '^', '¬', '(', ')'] + KarnaughMap.LETTERS for symbol in self.expression):
if not all(symbol in self.valid_symbols for symbol in self.expression):
self.table = []
if self.raise_error:
raise ValueError("Some invalid letters were used, please change the total number of inputs")
elif self.debug:
print("Some invalid letters were used, please change the total number of inputs")
return False
else:
self.table = []
if self.raise_error:
raise ValueError("Expression contains invalid symbols")
elif self.debug:
print("Expression contains invalid symbols")
self.expression = None
return False
if self.expression.count('(') != self.expression.count(')'):
self.table = []
if self.raise_error:
raise ValueError("Number of brackets does\'t match")
elif self.debug:
print("Number of brackets does\'t match")
self.expression = None
return False
if self.debug:
print(self.expression)
return True
@staticmethod
def __remove_brackets(text: str) -> List:
"""A private static function to convert a string with brackets into a nested list
(e.g. "(AvB)^C)" -> [["AvB"],"^C"]
Parameters:
text (str): The string to remove brackets from
Returns:
stack (List): A nested list showing where all the brackets are
"""
tokens = re.split(r'([(]|[)]|,)', text)
stack = [[]]
for token in tokens:
if not token or re.match(r',', token):
continue
if re.match(r'[(]', token):
stack[-1].append([])
stack.append(stack[-1][-1])
elif re.match(r'[)]', token):
stack.pop()
if not stack:
raise ValueError('Error: opening bracket is missing, this shouldn\'t happen')
else:
stack[-1].append(token)
if len(stack) > 1:
print(stack)
raise ValueError('Error: closing bracket is missing, this shouldn\'t happen')
return stack.pop()
@staticmethod
def get_tot_variables(expression: str) -> Union[int, None]:
"""Function to calculate the total number of variables used (not recommended)
Parameters:
expression (str): An expression to use to calculate the total variables
Returns:
variables (Union[int, None]): The total number of variables used
"""
variables = 5
try:
while not KarnaughMap.LETTERS[variables] in expression.lower():
variables -= 1
return variables + 1
except IndexError:
return None
def solve_map(self: _KMap) -> str:
"""Function to solve a generated Karnaugh map
Parameters:
self (_KMap): The instantiated object
Returns:
self.result (str): The simplified form of the original equation
"""
self.result = ""
self.groups = []
tableDim = [len(self.table[0]), len(self.table)]
headings = KarnaughMap.VALUES[self.tot_input]
temp_table = [[self.table[y][x] for x in range(len(self.table[0]))] for y in range(len(self.table))]
"""First check if the entire table is one or zero"""
if all(cell == 0 for row in self.table for cell in row):
self.result = "(0)"
return self.result
if all(cell == 1 for row in self.table for cell in row):
self.result = "(1)"
return self.result
"""This section works by iterating through each cell in the table and creating all the allowed
group sizes and then calculating the largest one.
Variables to note:
- largest = size of largest group
- xStart = starting column
- yStart = starting row
- point = ending point (x and y)
- xwrap = if it wraps around to the first column
- ywrap = if it wraps around to the first row
"""
for yStart in range(tableDim[1]):
for xStart in range(tableDim[0]):
if temp_table[yStart][xStart] != 0:
largest = 1
point = [xStart, yStart]
xwrap = False
ywrap = False
for ySize in [1, 2, 4, 8][:[1, 2, 4, 8].index(tableDim[1]) + 1]:
for xSize in [1, 2, 4, 8][:[1, 2, 4, 8].index(tableDim[0]) + 1]:
found = 1
contain_one = temp_table[yStart][xStart] == 1
for yPosition in range(yStart, yStart + ySize):
for xPosition in range(xStart, xStart + xSize):
if temp_table[yPosition % tableDim[1]][xPosition % tableDim[0]] == 0:
found = 0
if temp_table[yPosition % tableDim[1]][xPosition % tableDim[0]] == 1:
contain_one = True
if ySize * xSize > largest and found == 1 and contain_one:
largest = ySize * xSize
point = [(xStart + xSize - 1) % tableDim[0], (yStart + ySize - 1) % tableDim[1]]
if xStart + xSize - 1 != point[0]:
xwrap = True
else:
xwrap = False
if yStart + ySize - 1 != point[1]:
ywrap = True
else:
ywrap = False
found = 1
contain_one = temp_table[yStart][xStart] == 1
for yPosition in range(yStart, yStart - ySize, -1):
for xPosition in range(xStart, xStart - xSize, -1):
if temp_table[yPosition % tableDim[1]][xPosition % tableDim[0]] == 0:
found = 0
if temp_table[yPosition % tableDim[1]][xPosition % tableDim[0]] == 1:
contain_one = True
if ySize * xSize > largest and found == 1 and contain_one:
largest = ySize * xSize
point = [(xStart - xSize + 1) % tableDim[0], (yStart - ySize + 1) % tableDim[1]]
if xStart - xSize + 1 != point[0]:
xwrap = True
else:
xwrap = False
if yStart - ySize + 1 != point[1]:
ywrap = True
else:
ywrap = False
found = 1
contain_one = temp_table[yStart][xStart] == 1
for yPosition in range(yStart, yStart + ySize):
for xPosition in range(xStart, xStart - xSize, -1):
if temp_table[yPosition % tableDim[1]][xPosition % tableDim[0]] == 0:
found = 0
if temp_table[yPosition % tableDim[1]][xPosition % tableDim[0]] == 1:
contain_one = True
if ySize * xSize > largest and found == 1 and contain_one:
largest = ySize * xSize
point = [(xStart - xSize + 1) % tableDim[0], (yStart + ySize - 1) % tableDim[1]]
if xStart - xSize + 1 != point[0]:
xwrap = True
else:
xwrap = False
if yStart + ySize - 1 != point[1]:
ywrap = True
else:
ywrap = False
found = 1
contain_one = temp_table[yStart][xStart] == 1
for yPosition in range(yStart, yStart - ySize, -1):
for xPosition in range(xStart, xStart + xSize):
if temp_table[yPosition % tableDim[1]][xPosition % tableDim[0]] == 0:
found = 0
if temp_table[yPosition % tableDim[1]][xPosition % tableDim[0]] == 1:
contain_one = True
if ySize * xSize > largest and found == 1 and contain_one:
largest = ySize * xSize
point = [(xStart + xSize - 1) % tableDim[0], (yStart - ySize + 1) % tableDim[1]]
if xStart + xSize - 1 != point[0]:
xwrap = True
else:
xwrap = False
if yStart - ySize + 1 != point[1]:
ywrap = True
else:
ywrap = False
"""This section works by calculating the minimum and the maximum of the points and then filling
the tables with 2s to show that these are already included in a group
Variables to note:
- changed_vals = list of all coordinates of cells that have been changed
"""
if not (largest == 1 and temp_table[yStart][xStart] == 2):
(xmin, xmax) = (xStart, point[0] + 1) if xStart < point[0] else (point[0], xStart + 1)
(ymin, ymax) = (yStart, point[1] + 1) if yStart < point[1] else (point[1], yStart + 1)
changed_vals = []
if ywrap and not xwrap: # wrap around y
for yPosition in range(0, ymin + 1):
for xPosition in range(xmin, xmax):
temp_table[yPosition][xPosition] = 2
changed_vals.append([xPosition, yPosition])
for yPosition in range(ymax - 1, tableDim[1]):
for xPosition in range(xmin, xmax):
temp_table[yPosition][xPosition] = 2
changed_vals.append([xPosition, yPosition])
elif xwrap and not ywrap: # wrap around x
for yPosition in range(ymin, ymax):
for xPosition in range(0, xmin + 1):
temp_table[yPosition][xPosition] = 2
changed_vals.append([xPosition, yPosition])
for yPosition in range(ymin, ymax):
for xPosition in range(xmax - 1, tableDim[0]):
temp_table[yPosition][xPosition] = 2
changed_vals.append([xPosition, yPosition])
elif not xwrap and not ywrap: # no wrap around
for yPosition in range(ymin, ymax):
for xPosition in range(xmin, xmax):
temp_table[yPosition][xPosition] = 2
changed_vals.append([xPosition, yPosition])
else: # wrap around y and x
for yPosition in range(0, ymin + 1):
for xPosition in range(0, xmin + 1):
temp_table[yPosition][xPosition] = 2
changed_vals.append([xPosition, yPosition])
for yPosition in range(0, ymin + 1):
for xPosition in range(xmax - 1, tableDim[0]):
temp_table[yPosition][xPosition] = 2
changed_vals.append([xPosition, yPosition])
for yPosition in range(ymax - 1, tableDim[1]):
for xPosition in range(0, xmin + 1):
temp_table[yPosition][xPosition] = 2
changed_vals.append([xPosition, yPosition])
for yPosition in range(ymax - 1, tableDim[1]):
for xPosition in range(xmax - 1, tableDim[0]):
temp_table[yPosition][xPosition] = 2
changed_vals.append([xPosition, yPosition])
"""This section takes the changed_vals and modifies an array to show what the values have in
common, if all of the values have 1 heading in common then it will have a score of the size of
the group and if if all of them dont have it in common (not variable) then it will have a score
of zero
Variables to note:
- self.result = the result as a string
"""
changed = [0 for _ in range(self.tot_input)]
self.groups.append(changed_vals)
for i in changed_vals:
for index, j in enumerate(headings[0][i[0]]):
changed[index] += int(j)
for index, j in enumerate(headings[1][i[1]]):
changed[index + len(headings[0][0])] += int(j)
if len(self.result) != 0:
self.result += "v"
self.result += "(" + "^".join(
[KarnaughMap.LETTERS[i].upper() for i, x in enumerate(changed) if x == len(changed_vals)] +
["¬" + KarnaughMap.LETTERS[i].upper() for i, x in enumerate(changed) if x == 0]) + ")"
if all(cell == 0 for row in self.table for cell in row):
self.result = "(0)"
if all(cell == 1 for row in self.table for cell in row):
self.result = "(1)"
return self.result | PypiClean |
/Djblets-3.3.tar.gz/Djblets-3.3/docs/releasenotes/0.8.20.rst | ============================
Djblets 0.8.20 Release Notes
============================
**Release date**: June 15, 2015
djblets.webapi
==============
.. currentmodule:: djblets.webapi.resources
* Fix :py:meth:`WebAPIResource.serialize_object` failing to return a copy
of the original serialized data.
This could break things if the caller modified the resulting data in its
own :py:meth:`serialize_object`, if called more than twice on the same
object in a given request.
Contributors
============
* Christian Hammond
| PypiClean |
/KalturaApiClient-19.3.0.tar.gz/KalturaApiClient-19.3.0/KalturaClient/Plugins/ScheduledTaskMetadata.py | from __future__ import absolute_import
from .Core import *
from .ScheduledTask import *
from .Metadata import *
from ..Base import (
getXmlNodeBool,
getXmlNodeFloat,
getXmlNodeInt,
getXmlNodeText,
KalturaClientPlugin,
KalturaEnumsFactory,
KalturaObjectBase,
KalturaObjectFactory,
KalturaParams,
KalturaServiceBase,
)
########## enums ##########
########## classes ##########
# @package Kaltura
# @subpackage Client
class KalturaExecuteMetadataXsltObjectTask(KalturaObjectTask):
def __init__(self,
type=NotImplemented,
stopProcessingOnError=NotImplemented,
metadataProfileId=NotImplemented,
metadataObjectType=NotImplemented,
xslt=NotImplemented):
KalturaObjectTask.__init__(self,
type,
stopProcessingOnError)
# Metadata profile id to lookup the metadata object
# @var int
self.metadataProfileId = metadataProfileId
# Metadata object type to lookup the metadata object
# @var KalturaMetadataObjectType
self.metadataObjectType = metadataObjectType
# The XSLT to execute
# @var string
self.xslt = xslt
PROPERTY_LOADERS = {
'metadataProfileId': getXmlNodeInt,
'metadataObjectType': (KalturaEnumsFactory.createString, "KalturaMetadataObjectType"),
'xslt': getXmlNodeText,
}
def fromXml(self, node):
KalturaObjectTask.fromXml(self, node)
self.fromXmlImpl(node, KalturaExecuteMetadataXsltObjectTask.PROPERTY_LOADERS)
def toParams(self):
kparams = KalturaObjectTask.toParams(self)
kparams.put("objectType", "KalturaExecuteMetadataXsltObjectTask")
kparams.addIntIfDefined("metadataProfileId", self.metadataProfileId)
kparams.addStringEnumIfDefined("metadataObjectType", self.metadataObjectType)
kparams.addStringIfDefined("xslt", self.xslt)
return kparams
def getMetadataProfileId(self):
return self.metadataProfileId
def setMetadataProfileId(self, newMetadataProfileId):
self.metadataProfileId = newMetadataProfileId
def getMetadataObjectType(self):
return self.metadataObjectType
def setMetadataObjectType(self, newMetadataObjectType):
self.metadataObjectType = newMetadataObjectType
def getXslt(self):
return self.xslt
def setXslt(self, newXslt):
self.xslt = newXslt
########## services ##########
########## main ##########
class KalturaScheduledTaskMetadataClientPlugin(KalturaClientPlugin):
# KalturaScheduledTaskMetadataClientPlugin
instance = None
# @return KalturaScheduledTaskMetadataClientPlugin
@staticmethod
def get():
if KalturaScheduledTaskMetadataClientPlugin.instance == None:
KalturaScheduledTaskMetadataClientPlugin.instance = KalturaScheduledTaskMetadataClientPlugin()
return KalturaScheduledTaskMetadataClientPlugin.instance
# @return array<KalturaServiceBase>
def getServices(self):
return {
}
def getEnums(self):
return {
}
def getTypes(self):
return {
'KalturaExecuteMetadataXsltObjectTask': KalturaExecuteMetadataXsltObjectTask,
}
# @return string
def getName(self):
return 'scheduledTaskMetadata' | PypiClean |
/Dero-0.15.0-py3-none-any.whl/dero/manager/sectionpath/sectionpath.py | from typing import List, Union
import os
from dero.mixins.repr import ReprMixin
SectionPathOrStr = Union[str, 'SectionPath']
class SectionPath(ReprMixin):
repr_cols = ['path_str', 'sections']
def __init__(self, section_path: str):
self.path_str = section_path
self.sections = _section_path_str_to_section_strs(section_path)
def __iter__(self):
for section in self.sections:
yield section
def __getitem__(self, item):
return self.sections[item]
def __len__(self):
return len(self.sections)
@classmethod
def from_filepath(cls, basepath: str, filepath: str):
relative_path = os.path.relpath(filepath, start=basepath)
section_path = _relative_filepath_to_section_path(relative_path)
return cls(section_path)
@classmethod
def from_section_str_list(cls, section_strs: List[str]):
section_path = _section_strs_to_section_path_str(section_strs)
return cls(section_path)
@classmethod
def join(cls, section_path_1: SectionPathOrStr, section_path_2: SectionPathOrStr):
section_path_1 = _convert_to_section_path_if_necessary(section_path_1)
section_path_2 = _convert_to_section_path_if_necessary(section_path_2)
output_path_sections = section_path_1.sections + section_path_2.sections
return cls.from_section_str_list(output_path_sections)
def to_filepath(self, basepath: str):
relative_path = _section_path_to_relative_filepath(self)
return os.path.join(basepath, relative_path)
def _section_path_str_to_section_strs(section_path_str: str) -> List[str]:
return section_path_str.split('.')
def _section_strs_to_section_path_str(section_strs: List[str]) -> str:
return '.'.join(section_strs)
def _relative_filepath_to_section_path(filepath: str) -> str:
sections = filepath.split(os.path.sep)
sections[-1] = _strip_py(sections[-1]) # remove .py if exists at end of filepath
return _section_strs_to_section_path_str(sections)
def _section_path_to_relative_filepath(section_path: SectionPath) -> str:
return os.path.sep.join(section_path.sections)
def _strip_py(filename_str: str) -> str:
if not filename_str.endswith('.py'):
return filename_str
return filename_str[:-3]
def _convert_to_section_path_if_necessary(section_path: SectionPathOrStr) -> SectionPath:
if isinstance(section_path, SectionPath):
return section_path
elif isinstance(section_path, str):
return SectionPath(section_path)
else:
raise ValueError(f'expected SectionPath or str. got {section_path} of type {type(section_path)}') | PypiClean |
/Kallithea-0.7.0.tar.gz/Kallithea-0.7.0/kallithea/lib/vcs/utils/helpers.py | import datetime
import logging
import os
import re
import time
import urllib.request
import mercurial.url
from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers import ClassNotFound, guess_lexer_for_filename
from kallithea.lib.vcs import backends
from kallithea.lib.vcs.exceptions import RepositoryError, VCSError
from kallithea.lib.vcs.utils import safe_str
from kallithea.lib.vcs.utils.paths import abspath
ALIASES = ['hg', 'git']
def get_scm(path, search_up=False, explicit_alias=None):
"""
Returns one of alias from ``ALIASES`` (in order of precedence same as
shortcuts given in ``ALIASES``) and top working dir path for the given
argument. If no scm-specific directory is found or more than one scm is
found at that directory, ``VCSError`` is raised.
:param search_up: if set to ``True``, this function would try to
move up to parent directory every time no scm is recognized for the
currently checked path. Default: ``False``.
:param explicit_alias: can be one of available backend aliases, when given
it will return given explicit alias in repositories under more than one
version control, if explicit_alias is different than found it will raise
VCSError
"""
if not os.path.isdir(path):
raise VCSError("Given path %s is not a directory" % path)
while True:
found_scms = [(scm, path) for scm in get_scms_for_path(path)]
if found_scms or not search_up:
break
newpath = abspath(path, '..')
if newpath == path:
break
path = newpath
if len(found_scms) > 1:
for scm in found_scms:
if scm[0] == explicit_alias:
return scm
raise VCSError('More than one [%s] scm found at given path %s'
% (', '.join((x[0] for x in found_scms)), path))
if len(found_scms) == 0:
raise VCSError('No scm found at given path %s' % path)
return found_scms[0]
def get_scms_for_path(path):
"""
Returns all scm's found at the given path. If no scm is recognized
- empty list is returned.
:param path: path to directory which should be checked. May be callable.
:raises VCSError: if given ``path`` is not a directory
"""
if hasattr(path, '__call__'):
path = path()
if not os.path.isdir(path):
raise VCSError("Given path %r is not a directory" % path)
result = []
for key in ALIASES:
# find .hg / .git
dirname = os.path.join(path, '.' + key)
if os.path.isdir(dirname):
result.append(key)
continue
# find rm__.hg / rm__.git too - left overs from old method for deleting
dirname = os.path.join(path, 'rm__.' + key)
if os.path.isdir(dirname):
return result
# We still need to check if it's not bare repository as
# bare repos don't have working directories
try:
backends.get_backend(key)(path)
result.append(key)
continue
except RepositoryError:
# Wrong backend
pass
except VCSError:
# No backend at all
pass
return result
def get_scm_size(alias, root_path):
if not alias.startswith('.'):
alias += '.'
size_scm, size_root = 0, 0
for path, dirs, files in os.walk(root_path):
if path.find(alias) != -1:
for f in files:
try:
size_scm += os.path.getsize(os.path.join(path, f))
except OSError:
pass
else:
for f in files:
try:
size_root += os.path.getsize(os.path.join(path, f))
except OSError:
pass
return size_scm, size_root
def get_highlighted_code(name, code, type='terminal'):
"""
If pygments are available on the system
then returned output is colored. Otherwise
unchanged content is returned.
"""
try:
lexer = guess_lexer_for_filename(name, code)
formatter = TerminalFormatter()
content = highlight(code, lexer, formatter)
except ClassNotFound:
logging.debug("Couldn't guess Lexer, will not use pygments.")
content = code
return content
def parse_changesets(text):
"""
Returns dictionary with *start*, *main* and *end* ids.
Examples::
>>> parse_changesets('aaabbb')
{'start': None, 'main': 'aaabbb', 'end': None}
>>> parse_changesets('aaabbb..cccddd')
{'start': 'aaabbb', 'end': 'cccddd', 'main': None}
"""
text = text.strip()
CID_RE = r'[a-zA-Z0-9]+'
if '..' not in text:
m = re.match(r'^(?P<cid>%s)$' % CID_RE, text)
if m:
return {
'start': None,
'main': text,
'end': None,
}
else:
RE = r'^(?P<start>%s)?\.{2,3}(?P<end>%s)?$' % (CID_RE, CID_RE)
m = re.match(RE, text)
if m:
result = m.groupdict()
result['main'] = None
return result
raise ValueError("IDs not recognized")
def parse_datetime(text):
"""
Parses given text and returns ``datetime.datetime`` instance or raises
``ValueError``.
:param text: string of desired date/datetime or something more verbose,
like *yesterday*, *2weeks 3days*, etc.
"""
text = text.strip().lower()
INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M',
'%Y-%m-%d',
'%m/%d/%Y %H:%M:%S',
'%m/%d/%Y %H:%M',
'%m/%d/%Y',
'%m/%d/%y %H:%M:%S',
'%m/%d/%y %H:%M',
'%m/%d/%y',
)
for format in INPUT_FORMATS:
try:
return datetime.datetime(*time.strptime(text, format)[:6])
except ValueError:
pass
# Try descriptive texts
if text == 'tomorrow':
future = datetime.datetime.now() + datetime.timedelta(days=1)
args = future.timetuple()[:3] + (23, 59, 59)
return datetime.datetime(*args)
elif text == 'today':
return datetime.datetime(*datetime.datetime.today().timetuple()[:3])
elif text == 'now':
return datetime.datetime.now()
elif text == 'yesterday':
past = datetime.datetime.now() - datetime.timedelta(days=1)
return datetime.datetime(*past.timetuple()[:3])
else:
days = 0
matched = re.match(
r'^((?P<weeks>\d+) ?w(eeks?)?)? ?((?P<days>\d+) ?d(ays?)?)?$', text)
if matched:
groupdict = matched.groupdict()
if groupdict['days']:
days += int(matched.groupdict()['days'])
if groupdict['weeks']:
days += int(matched.groupdict()['weeks']) * 7
past = datetime.datetime.now() - datetime.timedelta(days=days)
return datetime.datetime(*past.timetuple()[:3])
raise ValueError('Wrong date: "%s"' % text)
def get_dict_for_attrs(obj, attrs):
"""
Returns dictionary for each attribute from given ``obj``.
"""
data = {}
for attr in attrs:
data[attr] = getattr(obj, attr)
return data
def get_urllib_request_handlers(url_obj):
handlers = []
test_uri, authinfo = url_obj.authinfo()
if authinfo:
# authinfo is a tuple (realm, uris, user, password) where 'uris' itself
# is a tuple of URIs.
# If url_obj is obtained via mercurial.util.url, the obtained authinfo
# values will be bytes, e.g.
# (None, (b'http://127.0.0.1/repo', b'127.0.0.1'), b'user', b'pass')
# However, urllib expects strings, not bytes, so we must convert them.
# create a password manager
passmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
passmgr.add_password(
safe_str(authinfo[0]) if authinfo[0] else None, # realm
tuple(safe_str(x) for x in authinfo[1]), # uris
safe_str(authinfo[2]), # user
safe_str(authinfo[3]), # password
)
handlers.extend((mercurial.url.httpbasicauthhandler(passmgr),
mercurial.url.httpdigestauthhandler(passmgr)))
return test_uri, handlers | PypiClean |
/FEV_KEGG-1.1.4.tar.gz/FEV_KEGG-1.1.4/FEV_KEGG/lib/Biopython/KEGG/KGML/KGML_parser.py | from xml.etree import ElementTree
from io import StringIO
from FEV_KEGG.lib.Biopython.KEGG.KGML.KGML_pathway import Component, Entry, Graphics
from FEV_KEGG.lib.Biopython.KEGG.KGML.KGML_pathway import Pathway, Reaction, Relation
def read(handle):
"""Parse a single KEGG Pathway from given file handle.
Returns a single Pathway object. There should be one and only
one pathway in each file, but there may well be pathological
examples out there.
"""
pathways = parse(handle)
try:
pathway = next(pathways)
except StopIteration:
raise ValueError("No pathways found in handle") from None
try:
next(pathways)
raise ValueError("More than one pathway found in handle")
except StopIteration:
pass
return pathway
def parse(handle):
"""Return an iterator over Pathway elements.
Arguments:
- handle - file handle to a KGML file for parsing, or a KGML string
This is a generator for the return of multiple Pathway objects.
"""
# Check handle
try:
handle.read(0)
except AttributeError:
try:
handle = StringIO(handle)
except TypeError:
raise TypeError(
"An XML-containing handle or an XML string must be provided"
) from None
# Parse XML and return each Pathway
for event, elem in ElementTree.iterparse(handle, events=("start", "end")):
if event == "end" and elem.tag == "pathway":
yield KGMLParser(elem).parse()
elem.clear()
class KGMLParser:
"""Parses a KGML XML Pathway entry into a Pathway object.
Example: Read and parse large metabolism file
>>> from FEV_KEGG.lib.Biopython.KEGG.KGML.KGML_parser import read
>>> pathway = read(open('KEGG/ko01100.xml', 'r'))
>>> print(len(pathway.entries))
3628
>>> print(len(pathway.reactions))
1672
>>> print(len(pathway.maps))
149
>>> pathway = read(open('KEGG/ko00010.xml', 'r'))
>>> print(pathway) #doctest: +NORMALIZE_WHITESPACE
Pathway: Glycolysis / Gluconeogenesis
KEGG ID: path:ko00010
Image file: http://www.kegg.jp/kegg/pathway/ko/ko00010.png
Organism: ko
Entries: 99
Entry types:
ortholog: 61
compound: 31
map: 7
"""
def __init__(self, elem):
"""Initialize the class."""
self.entry = elem
def parse(self):
"""Parse the input elements."""
def _parse_pathway(attrib):
for k, v in attrib.items():
self.pathway.__setattr__(k, v)
def _parse_entry(element):
new_entry = Entry()
for k, v in element.attrib.items():
new_entry.__setattr__(k, v)
for subelement in element:
if subelement.tag == "graphics":
_parse_graphics(subelement, new_entry)
elif subelement.tag == "component":
_parse_component(subelement, new_entry)
self.pathway.add_entry(new_entry)
def _parse_graphics(element, entry):
new_graphics = Graphics(entry)
for k, v in element.attrib.items():
new_graphics.__setattr__(k, v)
entry.add_graphics(new_graphics)
def _parse_component(element, entry):
new_component = Component(entry)
for k, v in element.attrib.items():
new_component.__setattr__(k, v)
entry.add_component(new_component)
def _parse_reaction(element):
new_reaction = Reaction()
for k, v in element.attrib.items():
new_reaction.__setattr__(k, v)
for subelement in element:
if subelement.tag == "substrate":
new_reaction.add_substrate(int(subelement.attrib["id"]))
elif subelement.tag == "product":
new_reaction.add_product(int(subelement.attrib["id"]))
self.pathway.add_reaction(new_reaction)
def _parse_relation(element):
new_relation = Relation()
new_relation.entry1 = int(element.attrib["entry1"])
new_relation.entry2 = int(element.attrib["entry2"])
new_relation.type = element.attrib["type"]
for subtype in element:
name, value = subtype.attrib["name"], subtype.attrib["value"]
if name in ("compound", "hidden compound"):
new_relation.subtypes.append((name, int(value)))
else:
new_relation.subtypes.append((name, value))
self.pathway.add_relation(new_relation)
# ==========
# Initialize Pathway
self.pathway = Pathway()
# Get information about the pathway itself
_parse_pathway(self.entry.attrib)
for element in self.entry:
if element.tag == "entry":
_parse_entry(element)
elif element.tag == "reaction":
_parse_reaction(element)
elif element.tag == "relation":
_parse_relation(element)
# # Parsing of some elements not implemented - no examples yet
# else:
# # This should warn us of any unimplemented tags
# import warnings
# from Bio import BiopythonParserWarning
#
# warnings.warn(
# "Warning: tag %s not implemented in parser" % element.tag,
# BiopythonParserWarning,
# )
return self.pathway
# if __name__ == "__main__":
# from Bio._utils import run_doctest
#
# run_doctest(verbose=0) | PypiClean |
/3DJCG-3Dvisual-question-answering-0.1.0.tar.gz/3DJCG-3Dvisual-question-answering-0.1.0/3DJCG_3Dvisual_question_answering/app.py | from uuid import uuid4
from pathlib import Path
from typing import Optional
import aiofiles
import torch
import argparse
from fastapi import FastAPI, UploadFile
from PIL import Image
# from .models import ImageEntityRecognition
from data.scannet.model_util_scannet import ScannetDatasetConfig
from models.vqanet.vqanet import VqaNet
app = FastAPI()
model = None
DC = ScannetDatasetConfig()
# model: Optional[ImageEntityRecognition] = None
# def get_model() -> ImageEntityRecognition:
# global model
# if model is None:
# model = ImageEntityRecognition()
# device = "cuda" if torch.cuda.is_available() else "cpu"
# model.to(device)
# model.eval()
# return model
def get_model(args):
global model
if model is None:
# initiate model
input_channels = int(args.use_multiview) * 128 + int(args.use_normal) * 3 + int(args.use_color) * 3 + int(not args.no_height)
model = VqaNet(
num_class=DC.num_class,
num_heading_bin=DC.num_heading_bin,
num_size_cluster=DC.num_size_cluster,
mean_size_arr=DC.mean_size_arr,
input_feature_dim=input_channels,
num_proposal=args.num_proposals,
use_lang_classifier=(not args.no_lang_cls),
no_reference=args.no_reference,
dataset_config=DC
)
# trainable model
if args.use_pretrained:
# load model
print("loading pretrained VoteNet...")
pretrained_path = os.path.join(CONF.PATH.OUTPUT, args.use_pretrained, "model_last.pth")
load_result = model.load_state_dict(torch.load(pretrained_path), strict=False)
print(load_result, flush=True)
# mount
# model.backbone_net = pretrained_model.backbone_net
# model.vgen = pretrained_model.vgen
# model.proposal = pretrained_model.proposal
if args.no_detection:
# freeze pointnet++ backbone
for param in model.backbone_net.parameters():
param.requires_grad = False
# freeze voting
for param in model.vgen.parameters():
param.requires_grad = False
# freeze detector
for param in model.proposal.parameters():
param.requires_grad = False
# to CUDA
model = model.cuda()
return model
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--tag", type=str, help="tag for the training, e.g. cuda_wl", default="")
parser.add_argument("--gpu", type=str, help="gpu", default="0")
parser.add_argument("--batch_size", type=int, help="batch size", default=14)
parser.add_argument("--epoch", type=int, help="number of epochs", default=50)
parser.add_argument("--verbose", type=int, help="iterations of showing verbose", default=10)
parser.add_argument("--val_step", type=int, help="iterations of validating", default=5000)
parser.add_argument("--lr", type=float, help="learning rate", default=1e-3)
parser.add_argument("--wd", type=float, help="weight decay", default=1e-3)
parser.add_argument("--lang_num_max", type=int, help="lang num max", default=32)
parser.add_argument("--num_points", type=int, default=40000, help="Point Number [default: 40000]")
parser.add_argument("--num_proposals", type=int, default=256, help="Proposal number [default: 256]")
parser.add_argument("--num_scenes", type=int, default=-1, help="Number of scenes [default: -1]")
parser.add_argument("--seed", type=int, default=42, help="random seed")
parser.add_argument("--coslr", action='store_true', help="cosine learning rate")
parser.add_argument("--amsgrad", action='store_true', help="optimizer with amsgrad")
parser.add_argument("--no_height", action="store_true", help="Do NOT use height signal in input.")
parser.add_argument("--no_lang_cls", action="store_true", help="Do NOT use language classifier.")
parser.add_argument("--no_detection", action="store_true", help="Do NOT train the detection module.")
parser.add_argument("--no_reference", action="store_true", help="Do NOT train the localization module.")
parser.add_argument("--use_color", action="store_true", help="Use RGB color in input.")
parser.add_argument("--use_normal", action="store_true", help="Use RGB color in input.")
parser.add_argument("--use_multiview", action="store_true", help="Use multiview images.")
parser.add_argument("--use_pretrained", type=str,
help="Specify the folder name containing the pretrained detection module.")
parser.add_argument("--use_checkpoint", type=str, help="Specify the checkpoint root", default="")
parser.add_argument("--use_generated_dataset", action="store_true", help="Use Generated Dataset.")
parser.add_argument("--use_generated_masked_dataset", action="store_true", help="Use Generated Masked Dataset.")
args = parser.parse_args()
get_model(args)
@app.get("/")
async def root():
return {"message": "Hello World"}
async def save_upload_file(upload_file: UploadFile) -> str:
file_path = f"uploaded_images/{uuid4()}{Path(upload_file.filename).suffix}"
async with aiofiles.open(file_path, "wb") as f:
while content := await upload_file.read(4 * 1024):
await f.write(content)
return file_path
@app.post("/inference")
async def inference(image: UploadFile):
image_path = await save_upload_file(image)
image = Image.open(image_path).convert("RGB")
model = get_model()
label_id, label, prob = model.inference(image)
return {
"label_id": label_id,
"label": label,
"prob": prob,
} | PypiClean |
/MASSA_Algorithm-0.9.1-py3-none-any.whl/MASSA_Algorithm/MASSApreparation.py | import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler
def normalizer_or_matrix(file, biological_activity):
# Biological activity:
if len(biological_activity) == 1:
bio_array = (file[biological_activity].to_numpy(copy=True)).reshape(-1,1) #Transforming the list of biological activities into an array of shape -1:1.
else:
bio_array = file[biological_activity].to_numpy(copy=True) # Transforming the list of biological activities into an array.
scaler = MinMaxScaler() # Definition of the normalization parameter.
bio_array_normalized = scaler.fit_transform(bio_array) # Normalization.
# Physicochemical descriptors:
descriptors_physicochemical = ['NumHAcceptors', 'NumHDonors', 'ExactMolWt', 'NumRotatableBonds', 'FractionCSP3', 'TPSA', 'LogP_WildmanCrippen']
PhCh_array = file[descriptors_physicochemical].to_numpy(copy=True) # Insertion of physicochemical properties into an array.
scaler = MinMaxScaler() # Definition of the normalization parameter.
PhCh_array_normalized = scaler.fit_transform(PhCh_array) # Normalization.
# Fingerprint:
FP_array = np.array(list(file['AtomPairs'])) # Insertion of fingerprints into an array.
return bio_array_normalized, PhCh_array_normalized, FP_array
def pca_maker(file, nPCS, svd_parameter):
# (if/elif:) Setting parameters to skip PCA: If the number of properties is less than or equal to 3 and if it is less than or equal to the number of principal components desired.
if (nPCS >= file.shape[1]):
pca_props = file
elif (file.shape[1] <= 3):
pca_props = file
else: # If it did not meet any exclusion criteria, proceed with the analysis.
pca = PCA(n_components=nPCS, svd_solver=svd_parameter)
pca_props = pca.fit_transform(file)
return pca_props
def organize_df_clusterization(file, HCAdict, ident): # Add the cluster identification to the spreadsheet.
if ident == 'all':
file['Cluster_General'] = pd.Series(HCAdict)
return file
elif ident == 'bio':
file['Cluster_Biological'] = pd.Series(HCAdict)
return file
elif ident == 'PhCh':
file['Cluster_Physicochemical'] = pd.Series(HCAdict)
return file
else:
file['Cluster_Structural'] = pd.Series(HCAdict)
return file
def organize_for_kmodes(file): # Create a matrix with cluster identifications for each of the three domains, in order to prepare for Kmodes.
kmodes_columns = file[['Cluster_Biological', 'Cluster_Physicochemical', 'Cluster_Structural']]
dict_cluster_bio = {}
dict_cluster_PhCh = {}
dict_cluster_FP = {}
for i, a, b, c in zip(kmodes_columns.index, kmodes_columns.Cluster_Biological, kmodes_columns.Cluster_Physicochemical, kmodes_columns.Cluster_Structural):
dict_cluster_bio[i] = 'cluster '+str(a)
dict_cluster_PhCh[i] = 'cluster '+str(b)
dict_cluster_FP[i] = 'cluster '+str(c)
kmodes_new_columns = pd.DataFrame()
kmodes_new_columns['Cluster_Biological'] = pd.Series(dict_cluster_bio)
kmodes_new_columns['Cluster_Physicochemical'] = pd.Series(dict_cluster_PhCh)
kmodes_new_columns['Cluster_Structural'] = pd.Series(dict_cluster_FP)
kmodes_matrix = np.array(kmodes_new_columns)
return kmodes_matrix | PypiClean |
/Bis-Miner-3.11.1.tar.gz/Bis-Miner-3.11.0/Orange/data/instance.py | from itertools import chain
from math import isnan
from numbers import Real, Integral
import numpy as np
from Orange.data import Value, Unknown
__all__ = ["Instance"]
class Instance:
def __init__(self, domain, data=None, id=None):
"""
Construct a new data instance.
:param domain: domain that describes the instance's variables
:type domain: Orange.data.Domain
:param data: instance's values
:type data: Orange.data.Instance or a sequence of values
:param id: instance id
:type id: hashable value
"""
if data is None and isinstance(domain, Instance):
data = domain
domain = data.domain
self._domain = domain
if data is None:
self._x = np.repeat(Unknown, len(domain.attributes))
self._y = np.repeat(Unknown, len(domain.class_vars))
self._metas = np.array([var.Unknown for var in domain.metas],
dtype=object)
self._weight = 1
elif isinstance(data, Instance) and data.domain == domain:
self._x = np.array(data._x)
self._y = np.array(data._y)
self._metas = np.array(data._metas)
self._weight = data._weight
else:
self._x, self._y, self._metas = domain.convert(data)
self._weight = 1
if id is not None:
self.id = id
else:
from Orange.data import Table
self.id = Table.new_id()
@property
def domain(self):
"""The domain describing the instance's values."""
return self._domain
@property
def x(self):
"""
Instance's attributes as a 1-dimensional numpy array whose length
equals `len(self.domain.attributes)`.
"""
return self._x
@property
def y(self):
"""
Instance's classes as a 1-dimensional numpy array whose length
equals `len(self.domain.attributes)`.
"""
return self._y
@property
def metas(self):
"""
Instance's meta attributes as a 1-dimensional numpy array whose length
equals `len(self.domain.attributes)`.
"""
return self._metas
@property
def list(self):
"""
All instance's values, including attributes, classes and meta
attributes, as a list whose length equals `len(self.domain.attributes)
+ len(self.domain.class_vars) + len(self.domain.metas)`.
"""
n_self, n_metas = len(self), len(self._metas)
return [self[i].value if i < n_self else self[n_self - i - 1].value
for i in range(n_self + n_metas)]
@property
def weight(self):
"""The weight of the data instance. Default is 1."""
return self._weight
@weight.setter
def weight(self, weight):
self._weight = weight
def __setitem__(self, key, value):
if not isinstance(key, Integral):
key = self._domain.index(key)
value = self._domain[key].to_val(value)
if key >= 0 and not isinstance(value, (int, float)):
raise TypeError("Expected primitive value, got '%s'" %
type(value).__name__)
if 0 <= key < len(self._domain.attributes):
self._x[key] = value
elif len(self._domain.attributes) <= key:
self._y[key - len(self.domain.attributes)] = value
else:
self._metas[-1 - key] = value
def __getitem__(self, key):
if not isinstance(key, Integral):
key = self._domain.index(key)
if 0 <= key < len(self._domain.attributes):
value = self._x[key]
elif key >= len(self._domain.attributes):
value = self._y[key - len(self.domain.attributes)]
else:
value = self._metas[-1 - key]
return Value(self._domain[key], value)
#TODO Should we return an instance of `object` if we have a meta attribute
# that is not Discrete or Continuous? E.g. when we have strings, we'd
# like to be able to use startswith, lower etc...
# Or should we even return Continuous as floats and use Value only
# for discrete attributes?!
# Same in Table.__getitem__
@staticmethod
def str_values(data, variables, limit=True):
if limit:
s = ", ".join(var.str_val(val)
for var, val in zip(variables, data[:5]))
if len(data) > 5:
s += ", ..."
return s
else:
return ", ".join(var.str_val(val)
for var, val in zip(variables, data))
def _str(self, limit):
s = "[" + self.str_values(self._x, self._domain.attributes, limit)
if self._domain.class_vars:
s += " | " + \
self.str_values(self._y, self._domain.class_vars, limit)
s += "]"
if self._domain.metas:
s += " {" + \
self.str_values(self._metas, self._domain.metas, limit) + \
"}"
return s
def __str__(self):
return self._str(False)
def __repr__(self):
return self._str(True)
def __eq__(self, other):
if not isinstance(other, Instance):
other = Instance(self._domain, other)
def same(x1, x2):
nan1 = np.isnan(x1)
nan2 = np.isnan(x2)
return np.array_equal(nan1, nan2) and \
np.array_equal(x1[~nan1], x2[~nan2])
return same(self._x, other._x) and same(self._y, other._y) \
and all(m1 == m2 or
type(m1) == type(m2) == float and isnan(m1) and isnan(m2)
for m1, m2 in zip(self._metas, other._metas))
def __iter__(self):
return chain(iter(self._x), iter(self._y))
def values(self):
return (Value(var, val)
for var, val in zip(self.domain.variables, self))
def __len__(self):
return len(self._x) + len(self._y)
def attributes(self):
"""Return iterator over the instance's attributes"""
return iter(self._x)
def classes(self):
"""Return iterator over the instance's class attributes"""
return iter(self._y)
# A helper function for get_class and set_class
def _check_single_class(self):
if not self._domain.class_vars:
raise TypeError("Domain has no class variable")
elif len(self._domain.class_vars) > 1:
raise TypeError("Domain has multiple class variables")
def get_class(self):
"""
Return the class value as an instance of :obj:`Orange.data.Value`.
Throws an exception if there are multiple classes.
"""
self._check_single_class()
return Value(self._domain.class_var, self._y[0])
def get_classes(self):
"""
Return the class value as a list of instances of
:obj:`Orange.data.Value`.
"""
return (Value(var, value)
for var, value in zip(self._domain.class_vars, self._y))
def set_class(self, value):
"""
Set the instance's class. Throws an exception if there are multiple
classes.
"""
self._check_single_class()
if not isinstance(value, Real):
self._y[0] = self._domain.class_var.to_val(value)
else:
self._y[0] = value | PypiClean |
/Nuitka-1.8.tar.gz/Nuitka-1.8/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Scanner/C.py |
__revision__ = "src/engine/SCons/Scanner/C.py 2014/07/05 09:42:21 garyo"
import SCons.Node.FS
import SCons.Scanner
import SCons.Util
import SCons.cpp
class SConsCPPScanner(SCons.cpp.PreProcessor):
"""
SCons-specific subclass of the cpp.py module's processing.
We subclass this so that: 1) we can deal with files represented
by Nodes, not strings; 2) we can keep track of the files that are
missing.
"""
def __init__(self, *args, **kw):
SCons.cpp.PreProcessor.__init__(self, *args, **kw)
self.missing = []
def initialize_result(self, fname):
self.result = SCons.Util.UniqueList([fname])
def finalize_result(self, fname):
return self.result[1:]
def find_include_file(self, t):
keyword, quote, fname = t
result = SCons.Node.FS.find_file(fname, self.searchpath[quote])
if not result:
self.missing.append((fname, self.current_file))
return result
def read_file(self, file):
try:
fp = open(str(file.rfile()))
except EnvironmentError, e:
self.missing.append((file, self.current_file))
return ''
else:
return fp.read()
def dictify_CPPDEFINES(env):
cppdefines = env.get('CPPDEFINES', {})
if cppdefines is None:
return {}
if SCons.Util.is_Sequence(cppdefines):
result = {}
for c in cppdefines:
if SCons.Util.is_Sequence(c):
result[c[0]] = c[1]
else:
result[c] = None
return result
if not SCons.Util.is_Dict(cppdefines):
return {cppdefines : None}
return cppdefines
class SConsCPPScannerWrapper(object):
"""
The SCons wrapper around a cpp.py scanner.
This is the actual glue between the calling conventions of generic
SCons scanners, and the (subclass of) cpp.py class that knows how
to look for #include lines with reasonably real C-preprocessor-like
evaluation of #if/#ifdef/#else/#elif lines.
"""
def __init__(self, name, variable):
self.name = name
self.path = SCons.Scanner.FindPathDirs(variable)
def __call__(self, node, env, path = ()):
cpp = SConsCPPScanner(current = node.get_dir(),
cpppath = path,
dict = dictify_CPPDEFINES(env))
result = cpp(node)
for included, includer in cpp.missing:
fmt = "No dependency generated for file: %s (included from: %s) -- file not found"
SCons.Warnings.warn(SCons.Warnings.DependencyWarning,
fmt % (included, includer))
return result
def recurse_nodes(self, nodes):
return nodes
def select(self, node):
return self
def CScanner():
"""Return a prototype Scanner instance for scanning source files
that use the C pre-processor"""
# Here's how we would (or might) use the CPP scanner code above that
# knows how to evaluate #if/#ifdef/#else/#elif lines when searching
# for #includes. This is commented out for now until we add the
# right configurability to let users pick between the scanners.
#return SConsCPPScannerWrapper("CScanner", "CPPPATH")
cs = SCons.Scanner.ClassicCPP("CScanner",
"$CPPSUFFIXES",
"CPPPATH",
'^[ \t]*#[ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")')
return cs
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4: | PypiClean |
/Eskapade_Spark-1.0.0-py3-none-any.whl/eskapadespark/links/spark_df_creator.py | from eskapade import Link, StatusCode, process_manager, DataStore
from eskapadespark.helpers import process_transform_funcs
from eskapadespark import SparkManager, data_conversion
class SparkDfCreator(Link):
"""Link to create a Spark dataframe from generic input data."""
def __init__(self, **kwargs):
"""Initialize link instance.
:param str name: name of link
:param str read_key: key of the input data in the data store
:param str store_key: key of the output data frame in the data store
:param schema: schema to create data frame if input data have a different format
:param iterable process_methods: methods to apply sequentially on the produced data frame
:param dict process_meth_args: positional arguments for process methods
:param dict process_meth_kwargs: keyword arguments for process methods
:param bool fail_missing_data: fail execution if data are missing (default is "True")
"""
# initialize Link
Link.__init__(self, kwargs.pop('name', 'SparkDfCreator'))
# process keyword arguments
self._process_kwargs(kwargs, read_key='', store_key=None, schema=None, process_methods=[],
process_meth_args={}, process_meth_kwargs={}, fail_missing_data=True)
self.kwargs = kwargs
def initialize(self):
"""Initialize the link."""
# check input arguments
self.check_arg_types(read_key=str, process_meth_args=dict, process_meth_kwargs=dict)
self.check_arg_types(allow_none=True, store_key=str)
self.check_arg_vals('read_key')
self.fail_missing_data = bool(self.fail_missing_data)
if not self.store_key:
self.store_key = self.read_key
# process post-process methods
self._process_methods = process_transform_funcs(self.process_methods, self.process_meth_args,
self.process_meth_kwargs)
return StatusCode.Success
def execute(self):
"""Execute the link."""
# get process manager and data store
ds = process_manager.service(DataStore)
# fetch data from data store
if self.read_key not in ds:
err_msg = 'No input data found in data store with key "{}".'.format(self.read_key)
if not self.fail_missing_data:
self.logger.error(err_msg.capitalize())
return StatusCode.Success
raise KeyError(err_msg)
data = ds[self.read_key]
# create data frame
spark = process_manager.service(SparkManager).get_session()
self.logger.debug('Converting data of type "{type}" to a Spark data frame.', type=type(data))
ds[self.store_key] = data_conversion.create_spark_df(spark, data, schema=self.schema,
process_methods=self._process_methods, **self.kwargs)
return StatusCode.Success | PypiClean |
/INGInious-0.8.7.tar.gz/INGInious-0.8.7/inginious/frontend/static/js/codemirror/mode/yaml/yaml.js |
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("yaml", function() {
var cons = ['true', 'false', 'on', 'off', 'yes', 'no'];
var keywordRegex = new RegExp("\\b(("+cons.join(")|(")+"))$", 'i');
return {
token: function(stream, state) {
var ch = stream.peek();
var esc = state.escaped;
state.escaped = false;
/* comments */
if (ch == "#" && (stream.pos == 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))) {
stream.skipToEnd();
return "comment";
}
if (stream.match(/^('([^']|\\.)*'?|"([^"]|\\.)*"?)/))
return "string";
if (state.literal && stream.indentation() > state.keyCol) {
stream.skipToEnd(); return "string";
} else if (state.literal) { state.literal = false; }
if (stream.sol()) {
state.keyCol = 0;
state.pair = false;
state.pairStart = false;
/* document start */
if(stream.match(/---/)) { return "def"; }
/* document end */
if (stream.match(/\.\.\./)) { return "def"; }
/* array list item */
if (stream.match(/\s*-\s+/)) { return 'meta'; }
}
/* inline pairs/lists */
if (stream.match(/^(\{|\}|\[|\])/)) {
if (ch == '{')
state.inlinePairs++;
else if (ch == '}')
state.inlinePairs--;
else if (ch == '[')
state.inlineList++;
else
state.inlineList--;
return 'meta';
}
/* list seperator */
if (state.inlineList > 0 && !esc && ch == ',') {
stream.next();
return 'meta';
}
/* pairs seperator */
if (state.inlinePairs > 0 && !esc && ch == ',') {
state.keyCol = 0;
state.pair = false;
state.pairStart = false;
stream.next();
return 'meta';
}
/* start of value of a pair */
if (state.pairStart) {
/* block literals */
if (stream.match(/^\s*(\||\>)\s*/)) { state.literal = true; return 'meta'; };
/* references */
if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) { return 'variable-2'; }
/* numbers */
if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) { return 'number'; }
if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) { return 'number'; }
/* keywords */
if (stream.match(keywordRegex)) { return 'keyword'; }
}
/* pairs (associative arrays) -> key */
if (!state.pair && stream.match(/^\s*(?:[,\[\]{}&*!|>'"%@`][^\s'":]|[^,\[\]{}#&*!|>'"%@`])[^#]*?(?=\s*:($|\s))/)) {
state.pair = true;
state.keyCol = stream.indentation();
return "atom";
}
if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; return 'meta'; }
/* nothing found, continue */
state.pairStart = false;
state.escaped = (ch == '\\');
stream.next();
return null;
},
startState: function() {
return {
pair: false,
pairStart: false,
keyCol: 0,
inlinePairs: 0,
inlineList: 0,
literal: false,
escaped: false
};
}
};
});
CodeMirror.defineMIME("text/x-yaml", "yaml");
CodeMirror.defineMIME("text/yaml", "yaml");
}); | PypiClean |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.