input
stringlengths
2.65k
237k
output
stringclasses
1 value
<filename>qcengine/util.py """ Several import utilities """ import importlib import io import json import operator import os import shutil import signal import subprocess import sys import tempfile import time import traceback from contextlib import contextmanager from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Union from qcelemental.models import ComputeError, FailedOperation from .config import LOGGER, get_provenance_augments __all__ = ["compute_wrapper", "get_module_function", "model_wrapper", "handle_output_metadata"] def model_wrapper(input_data: Dict[str, Any], model: 'BaseModel') -> 'BaseModel': """ Wrap input data in the given model, or return a controlled error """ try: if isinstance(input_data, dict): input_data = model(**input_data) elif isinstance(input_data, model): input_data = input_data.copy() else: raise KeyError("Input type of {} not understood.".format(type(model))) # Older QCElemental compat try: input_data.extras except AttributeError: input_data = input_data.copy(update={"extras": {}}) except Exception: input_data = FailedOperation( input_data=input_data, success=False, error=ComputeError( error_type="input_error", error_message=("Input data could not be processed correctly:\n" + traceback.format_exc()))) return input_data @contextmanager def compute_wrapper(capture_output: bool=True) -> Dict[str, Any]: """Wraps compute for timing, output capturing, and raise protection """ metadata = {"stdout": None, "stderr": None} # Start timer comp_time = time.time() # Capture stdout/err new_stdout = io.StringIO() new_stderr = io.StringIO() if capture_output: old_stdout, sys.stdout = sys.stdout, new_stdout old_stderr, sys.stderr = sys.stderr, new_stderr try: yield metadata metadata["success"] = True except Exception as e: metadata["error_message"] = "QCEngine Call Error:\n" + traceback.format_exc() metadata["success"] = False # Place data metadata["wall_time"] = time.time() - comp_time if capture_output: sys.stdout = old_stdout sys.stderr = old_stderr # Pull over values metadata["stdout"] = new_stdout.getvalue() or None metadata["stderr"] = new_stderr.getvalue() or None def get_module_function(module: str, func_name: str, subpackage=None) -> Callable[..., Any]: """Obtains a function from a given string Parameters ---------- module : str The module to pull the function from func_name : str The name of the function to acquire, can be in a subpackage subpackage : None, optional Explicitly import a subpackage if required Returns ------- ret : function The requested functions Example ------- # Import numpy.linalg.eigh f = get_module_function("numpy", "linalg.eigh") f(np.ones((2, 2))) """ # Will throw import error if we fail pkg = importlib.import_module(module, subpackage) return operator.attrgetter(func_name)(pkg) def handle_output_metadata(output_data: Union[Dict[str, Any], 'BaseModel'], metadata: Dict[str, Any], raise_error: bool=False, return_dict: bool=True) -> Union[Dict[str, Any], 'BaseModel']: """ Fuses general metadata and output together. Returns ------- result : dict or pydantic.models.Result Output type depends on return_dict or a dict if an error was generated in model construction """ if isinstance(output_data, dict): output_fusion = output_data # Error handling else: output_fusion = output_data.dict() # Do not override if computer generates output_fusion["stdout"] = output_fusion.get("stdout", None) or metadata["stdout"] output_fusion["stderr"] = output_fusion.get("stderr", None) or metadata["stderr"] if metadata["success"] is not True: output_fusion["success"] = False output_fusion["error"] = {"error_type": "meta_error", "error_message": metadata["error_message"]} # Raise an error if one exists and a user requested a raise if raise_error and (output_fusion["success"] is not True): msg = "stdout:\n{}".format(output_fusion["stdout"]) msg += "\nstderr:\n{}".format(output_fusion["stderr"]) LOGGER.info(msg) raise ValueError(output_fusion["error"]["error_message"]) # Fill out provenance datadata provenance_augments = get_provenance_augments() provenance_augments["wall_time"] = metadata["wall_time"] if "provenance" in output_fusion: output_fusion["provenance"].update(provenance_augments) else: # Add onto the augments with some missing info provenance_augments["creator"] = "QCEngine" provenance_augments["version"] = provenance_augments["qcengine_version"] output_fusion["provenance"] = provenance_augments # Make sure pydantic sparsity is upheld for val in ["stdout", "stderr"]: if output_fusion[val] is None: output_fusion.pop(val) # We need to return the correct objects; e.g. Results, Procedures if output_fusion["success"]: # This will only execute if everything went well ret = output_data.__class__(**output_fusion) else: # Should only be reachable on failures ret = FailedOperation( success=output_fusion.pop("success", False), error=output_fusion.pop("error"), input_data=output_fusion) if return_dict: return json.loads(ret.json()) # Use Pydantic to serialize, then reconstruct as Python dict of Python Primals else: return ret def terminate_process(proc: Any, timeout: int=15) -> None: if proc.poll() is None: # Sigint (keyboard interupt) if sys.platform.startswith('win'): proc.send_signal(signal.CTRL_BREAK_EVENT) else: proc.send_signal(signal.SIGINT) try: start = time.time() while (proc.poll() is None) and (time.time() < (start + timeout)): time.sleep(0.02) # Flat kill finally: proc.kill() @contextmanager def popen(args: List[str], append_prefix: bool=False, popen_kwargs: Optional[Dict[str, Any]]=None) -> Dict[str, Any]: """ Opens a background task Code and idea from dask.distributed's testing suite https://github.com/dask/distributed """ args = list(args) if popen_kwargs is None: popen_kwargs = {} else: popen_kwargs = popen_kwargs.copy() # Bin prefix if sys.platform.startswith('win'): bin_prefix = os.path.join(sys.prefix, 'Scripts') else: bin_prefix = os.path.join(sys.prefix, 'bin') # Do we prefix with Python? if append_prefix: args[0] = os.path.join(bin_prefix, args[0]) if sys.platform.startswith('win'): # Allow using CTRL_C_EVENT / CTRL_BREAK_EVENT popen_kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP popen_kwargs['stdout'] = subprocess.PIPE popen_kwargs['stderr'] = subprocess.PIPE LOGGER.info('Popen', args, popen_kwargs) ret = {"proc": subprocess.Popen(args, **popen_kwargs)} try: yield ret except Exception: raise finally: try: terminate_process(ret["proc"]) finally: output, error = ret["proc"].communicate() ret["stdout"] = output.decode() ret["stderr"] = error.decode() def execute(command: List[str], infiles: Optional[Dict[str, str]]=None, outfiles: Optional[List[str]]=None, *, scratch_name: Optional[str]=None, scratch_location: Optional[str]=None, scratch_messy: bool=False, blocking_files: Optional[List[str]]=None, timeout: Optional[int]=None, interupt_after: Optional[int]=None, environment: Optional[Dict[str, str]]=None) -> Dict[str, str]: """ Runs a process in the background until complete. Returns True if exit code zero Parameters ---------- command : list of str infiles : Dict[str] = str Input file names (names, not full paths) and contents. to be written in scratch dir. May be {}. outfiles : List[str] = None Output file names to be collected after execution into values. May be {}. scratch_name : str, optional Passed to scratch_directory scratch_location : str, optional Passed to scratch_directory scratch_messy : bool, optional Passed to scratch_directory blocking_files : list, optional Files which should stop execution if present beforehand. timeout : int, optional Stop the process after n seconds. interupt_after : int, optional Interupt the process (not hard kill) after n seconds. environment : dict, optional The environment to run in Raises ------ FileExistsError If any file in `blocking` is present """ # Format inputs if infiles is None: infiles = {} if outfiles is None: outfiles = [] outfiles = {k: None for k in outfiles} # Check for blocking files if blocking_files is not None: for fl in blocking_files: if os.path.isfile(fl): raise FileExistsError('Existing file can interfere with execute operation.', fl) # Format popen popen_kwargs = {} if environment is not None: popen_kwargs["env"] = {k: v for k, v in environment.items() if v is not None} # Execute with scratch_directory(scratch_name, scratch_location, scratch_messy) as scrdir: popen_kwargs["cwd"] = scrdir with disk_files(infiles, outfiles, scrdir) as extrafiles: with popen(command, popen_kwargs=popen_kwargs) as proc: realtime_stdout = "" while True: output = proc["proc"].stdout.readline() if output == b'' and proc["proc"].poll() is not None: break if output: realtime_stdout += output.decode('utf-8') if interupt_after is None: proc["proc"].wait(timeout=timeout) else: time.sleep(interupt_after) terminate_process(proc["proc"]) proc["stdout"] = realtime_stdout retcode = proc["proc"].poll() proc['outfiles'] = extrafiles proc['scratch_directory'] = scrdir return retcode == 0, proc @contextmanager def scratch_directory(child: str=None, parent: str=None, messy: bool=False) -> str: """Create and cleanup a quarantined working directory with a parent scratch directory. Parameters ---------- child : str, optional By default, `None`, quarantine directory generated through `tempfile.mdktemp` so guaranteed unique and safe. When specified, quarantine directory has exactly `name`. parent : str, optional Create directory `child` elsewhere than TMP default. For TMP default, see https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir messy : bool, optional Leave scratch directory and contents on disk after completion. Yields ------ str Full path of scratch directory. Raises ------ FileExistsError If `child` specified and directory already exists (perhaps from a previous `messy=True` run). Examples -------- parent child --> creates ------ ----- ------- None None --> /tmp/tmpliyp1i7x/ None myqcjob --> /tmp/myqcjob/ /scratch/johndoe None --> /scratch/johndoe/tmpliyp1i7x/ /scratch/johndoe myqcjob --> /scratch/johndoe/myqcjob/ """ if child is None: tmpdir = tempfile.mkdtemp(dir=parent) else: if parent is None: parent = Path(tempfile.gettempdir()) else: parent = Path(parent) tmpdir = parent / child os.mkdir(tmpdir) try: yield tmpdir finally: if not messy: shutil.rmtree(tmpdir) LOGGER.info(f'... Removing {tmpdir}') @contextmanager def disk_files(infiles: Dict[str, str], outfiles: Dict[str, None], cwd: Optional[str]=None) -> Dict[str, str]: """ Parameters ---------- infiles : Dict[str] = str Input file names (names, not full paths) and contents. to be written in scratch dir. May be {}. outfiles : Dict[str] = None Output file names to be collected after execution into values. May be {}. cwd : str, optional Directory to which to write and read files. Yields ------ Dict[str] = str outfiles with RHS filled in. """ if cwd is None: lwd = Path.cwd() else: lwd = Path(cwd) try: # need an extra flag for text/binary for fl, content in infiles.items(): filename = lwd / fl with open(filename, 'w') as fp: fp.write(content) LOGGER.info(f'... Writing: {filename}') yield outfiles finally: for fl in outfiles.keys(): try: filename = lwd /
# coding=utf-8 import tensorflow as tf from colorama import Fore import numpy as np import logging from collections import OrderedDict import Putil.DenseNet.model_base as dmb from tensorflow.contrib import layers import Putil.np.util as npu import Putil.tf.util as tfu def get_image_summary(img, idx=0): """ Make an image summary for 4d tensor image with index idx """ V = tf.slice(img, (0, 0, 0, idx), (1, -1, -1, 1)) V -= tf.reduce_min(V) V /= tf.reduce_max(V) V *= 255 img_w = tf.shape(img)[1] img_h = tf.shape(img)[2] V = tf.reshape(V, tf.stack((img_w, img_h, 1))) V = tf.transpose(V, (2, 0, 1)) V = tf.reshape(V, tf.stack((-1, img_w, img_h, 1))) return V def weight_variable(shape, stddev=0.1, name="weight"): initial = tf.truncated_normal(shape, stddev=stddev) return tf.Variable(initial, name=name) def weight_variable_devonc(shape, stddev=0.1, name="weight_devonc"): return tf.Variable(tf.truncated_normal(shape, stddev=stddev), name=name) def bias_variable(shape, name="bias"): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=name) def conv2d(x, W, b, keep_prob_): with tf.name_scope("conv2d"): conv_2d = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID') conv_2d_b = tf.nn.bias_add(conv_2d, b) return tf.nn.dropout(conv_2d_b, keep_prob_) def deconv2d(x, W,stride): with tf.name_scope("deconv2d"): x_shape = tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1]*2, x_shape[2]*2, x_shape[3]//2]) return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='VALID', name="conv2d_transpose") def max_pool(x,n): return tf.nn.max_pool(x, ksize=[1, n, n, 1], strides=[1, n, n, 1], padding='VALID') def crop_and_concat(x1, x2): with tf.name_scope("crop_and_concat"): x1_shape = tf.shape(x1) x2_shape = tf.shape(x2) # offsets for the top left corner of the crop offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) // 2, 0] size = [-1, x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2], 3) def pixel_wise_softmax(output_map): with tf.name_scope("pixel_wise_softmax"): # subtract max is work for avoid overflow max_axis = tf.reduce_max(output_map, axis=3, keepdims=True, name='calc_max') exponential_map = tf.exp(tf.subtract(output_map, max_axis, 'sub_for_avoid_overflow'), 'exp') normalize = tf.reduce_sum(exponential_map, axis=3, keepdims=True, name='exp_sum') return tf.div(exponential_map, normalize, name='normalize') def cross_entropy(y_, output_map): return -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(output_map, 1e-10, 1.0)), name="cross_entropy") def create_conv_net(x, keep_prob, channels, n_class, layers=3, features_root=16, filter_size=3, pool_size=2, summaries=True): """ Creates a new convolutional unet for the given parametrization. :param x: input tensor, shape [?,nx,ny,channels] :param keep_prob: dropout probability tensor :param channels: number of channels in the input image :param n_class: number of output labels :param layers: number of layers in the net :param features_root: number of features in the first layer :param filter_size: size of the convolution filter :param pool_size: size of the max pooling operation :param summaries: Flag if summaries should be created """ logging.info( Fore.GREEN + "Layers {layers}, features {features}, filter size {filter_size}x{filter_size}, pool size: " "{pool_size}x{pool_size}".format( layers=layers, features=features_root, filter_size=filter_size, pool_size=pool_size)) # Placeholder for the input image with tf.name_scope("preprocessing"): nx = tf.shape(x)[1] ny = tf.shape(x)[2] x_image = tf.reshape(x, tf.stack([-1, nx, ny, channels])) in_node = x_image batch_size = tf.shape(x_image)[0] weights = [] biases = [] convs = [] pools = OrderedDict() deconv = OrderedDict() dw_h_convs = OrderedDict() up_h_convs = OrderedDict() in_size = 1000 size = in_size # down layers for layer in range(0, layers): with tf.name_scope("down_conv_{}".format(str(layer))): features = 2 ** layer * features_root stddev = np.sqrt(2 / (filter_size ** 2 * features)) if layer == 0: w1 = weight_variable([filter_size, filter_size, channels, features], stddev, name="w1") else: w1 = weight_variable([filter_size, filter_size, features // 2, features], stddev, name="w1") w2 = weight_variable([filter_size, filter_size, features, features], stddev, name="w2") b1 = bias_variable([features], name="b1") b2 = bias_variable([features], name="b2") conv1 = conv2d(in_node, w1, b1, keep_prob) tmp_h_conv = tf.nn.relu(conv1) conv2 = conv2d(tmp_h_conv, w2, b2, keep_prob) dw_h_convs[layer] = tf.nn.relu(conv2) weights.append((w1, w2)) biases.append((b1, b2)) convs.append((conv1, conv2)) size -= 4 if layer < layers - 1: pools[layer] = max_pool(dw_h_convs[layer], pool_size) in_node = pools[layer] size /= 2 in_node = dw_h_convs[layers - 1] # up layers for layer in range(layers - 2, -1, -1): with tf.name_scope("up_conv_{}".format(str(layer))): features = 2 ** (layer + 1) * features_root stddev = np.sqrt(2 / (filter_size ** 2 * features)) wd = weight_variable_devonc([pool_size, pool_size, features // 2, features], stddev, name="wd") bd = bias_variable([features // 2], name="bd") h_deconv = tf.nn.relu(deconv2d(in_node, wd, pool_size) + bd) h_deconv_concat = crop_and_concat(dw_h_convs[layer], h_deconv) deconv[layer] = h_deconv_concat w1 = weight_variable([filter_size, filter_size, features, features // 2], stddev, name="w1") w2 = weight_variable([filter_size, filter_size, features // 2, features // 2], stddev, name="w2") b1 = bias_variable([features // 2], name="b1") b2 = bias_variable([features // 2], name="b2") conv1 = conv2d(h_deconv_concat, w1, b1, keep_prob) h_conv = tf.nn.relu(conv1) conv2 = conv2d(h_conv, w2, b2, keep_prob) in_node = tf.nn.relu(conv2) up_h_convs[layer] = in_node weights.append((w1, w2)) biases.append((b1, b2)) convs.append((conv1, conv2)) size *= 2 size -= 4 # Output Map with tf.name_scope("output_map"): weight = weight_variable([1, 1, features_root, n_class], stddev) bias = bias_variable([n_class], name="bias") conv = conv2d(in_node, weight, bias, tf.constant(1.0)) output_map = tf.nn.relu(conv) up_h_convs["out"] = output_map if summaries: with tf.name_scope("summaries"): for i, (c1, c2) in enumerate(convs): tf.summary.image('summary_conv_%02d_01' % i, get_image_summary(c1)) tf.summary.image('summary_conv_%02d_02' % i, get_image_summary(c2)) for k in pools.keys(): tf.summary.image('summary_pool_%02d' % k, get_image_summary(pools[k])) for k in deconv.keys(): tf.summary.image('summary_deconv_concat_%02d' % k, get_image_summary(deconv[k])) for k in dw_h_convs.keys(): tf.summary.histogram("dw_convolution_%02d" % k + '/activations', dw_h_convs[k]) for k in up_h_convs.keys(): tf.summary.histogram("up_convolution_%s" % k + '/activations', up_h_convs[k]) variables = [] for w1, w2 in weights: variables.append(w1) variables.append(w2) for b1, b2 in biases: variables.append(b1) variables.append(b2) return output_map, variables, int(in_size - size) def __reducor_for_DenseUNet( output_map, training, params ): param_dtype = tfu.tf_type(params.get('param_dtype')).Type regularize_weight = params.get('regularize_weight') grow = params.get('grows') kernel = params.get('kernels') layer_param = params.get('layer_param') layer_param['training'] = training output_map = dmb.DenseNetBlockLayers( output_map, param_dtype, grow, 'reducor', regularize_weight, kernel, layer_param ) return output_map pass def __base_feature( output_map, params ): filter = params.get('feature_amount') kernel = params.get('kernel') stride = params.get('stride') param_dtype = tfu.tf_type(params.get('param_dtype')).Type regularize_weight = params.get('regularize_weight') output_map = tf.layers.conv2d( output_map, filter, kernel, stride, "same", activation=tf.nn.relu, kernel_initializer=tf.variance_scaling_initializer(mode='fan_avg', dtype=param_dtype), kernel_regularizer=layers.l2_regularizer(regularize_weight), bias_initializer=tf.zeros_initializer(dtype=param_dtype), bias_regularizer=layers.l2_regularizer(regularize_weight), name='base' ) return output_map pass def __DenseUNet( output_map, training, DenseUNetConfig ): """ :param output_map: :param training: :param DenseUNetConfig: # { # "BaseModel": "DenseNet", # "BaseFeature":{ # "feature_amount": 32, # "kernel": [3, 3], # "stride": [1, 1], # "param_dtype": 0.32, # "regularize_weight": 0.0001 # }, # "DenseNet":[ # { # "param_dtype": 0.32, # "grows": [3, 3, 3], # "regularize_weight": 0.0001, # "kernels": [[3, 3], [3, 3], [3, 3]], # "pool_kernel": [2, 2], # "pool_stride": [2, 2], # "pool_type": "max", # "layer_param":{ # "batch_normal": true, # "activate_param":{ # "type": "ReLU" # } # }, # "transition_param":{ # "batch_normal": true, # "activate_param": { # "type": "ReLU" # }, # "compress_rate": null, # "dropout_rate": 0.1 # } # }, # { # "param_dtype": 0.32, # "grows": [3, 3, 3], # "regularize_weight": 0.0001, # "kernels": [[3, 3], [3, 3], [3, 3]], # "pool_kernel": [2, 2], # "pool_stride": [2, 2], # "pool_type": "max", # "layer_param":{ # "batch_normal": true, # "activate_param":{ # "type": "ReLU" # } # }, # "transition_param":{ # "batch_normal": true, # "activate_param": { # "type": "ReLU" # }, # "compress_rate": null, # "dropout_rate": 0.1 # } # }, # { # "param_dtype": 0.32, # "grows": [3, 3, 3], # "regularize_weight": 0.0001, # "kernels": [[3, 3], [3, 3], [3, 3]], # "pool_kernel": [2, 2], # "pool_stride": [2, 2], # "pool_type": "max", # "layer_param":{ # "batch_normal": true, # "activate_param":{ # "type": "ReLU" # } # }, # "transition_param":{ # "batch_normal": true, # "activate_param": { # "type": "ReLU" # }, # "compress_rate": null, # "dropout_rate": 0.1 # } # }, # { # "param_dtype": 0.32, # "grows": [3, 3, 3], # "regularize_weight": 0.0001, # "kernels": [[3, 3], [3, 3], [3, 3]], # "pool_kernel": [2, 2], # "pool_stride": [2, 2], # "pool_type": "max", # "layer_param":{ # "batch_normal": true, # "activate_param":{ # "type": "ReLU" # } # }, # "transition_param":{ # "batch_normal": true, # "activate_param": { # "type": "ReLU" # }, # "compress_rate": null, # "dropout_rate": 0.1 # } # } # ], # "DeDenseNet":[ # { # "param_dtype": 0.32, # # "grows": [3, 3, 3], # "regularize_weight": 0.0001, # "kernels": [[3, 3], [3, 3], [3, 3]], # # "t_kernel": [3, 3], # "t_stride": [2, 2], # "compress_rate": 0.3, # # "layer_param":{ # "batch_normal": true, # "activate":{ # "type": "ReLU" # } # }, # # "transition_param":{ # "batch_normal": true, # "activate_param":{ # "type": "ReLU" # }, # "dropout_rate": 0.1 # } # }, # { # "param_dtype": 0.32, # # "grows": [3, 3, 3], # "regularize_weight": 0.0001, # "kernels": [[3, 3], [3, 3], [3, 3]], # # "t_kernel": [3, 3], # "t_stride": [2, 2], # "compress_rate": 0.3, # # "layer_param":{ # "batch_normal": true, # "activate":{ # "type": "ReLU" # } # }, # # "transition_param":{ # "batch_normal": true, # "activate_param":{ # "type": "ReLU" # }, # "dropout_rate": 0.1 # } # }, # { # "param_dtype": 0.32, # # "grows": [3, 3, 3], # "regularize_weight": 0.0001, # "kernels": [[3, 3], [3, 3], [3, 3]], # # "t_kernel": [3, 3], # "t_stride": [2, 2], # "compress_rate": 0.3, # # "layer_param":{ # "batch_normal": true, # "activate":{ # "type": "ReLU" # } # }, # # "transition_param":{ # "batch_normal": true, # "activate_param":{ # "type": "ReLU" # }, # "dropout_rate": 0.1 # } # }, # { # "param_dtype": 0.32, # # "grows": [3, 3, 3], # "regularize_weight": 0.0001, # "kernels": [[3, 3], [3, 3], [3, 3]], # # "t_kernel": [3, 3], # "t_stride": [2, 2], # "compress_rate": 0.3, # # "layer_param":{ # "batch_normal": true, # "activate":{ # "type": "ReLU" # } # }, # # "transition_param":{ # "batch_normal": true, # "activate_param":{ # "type": "ReLU" # }, # "dropout_rate": 0.1 # } # } # ], # "BlockReducor":{ # "param_dtype": 0.32, # "regularize_weight": 0.0001, # "grows": [3, 2, 1], # "kernels": [[1, 1], [2, 2], [3, 3]], # "layer_param":{ # "batch_normal": true, # "activate":{ # "type": "ReLU" # } # } # } # } :return: """ BaseFeature = DenseUNetConfig.get('BaseFeature') DenseNetConfig = DenseUNetConfig.get('DenseNet') DeDenseNetConfig = DenseUNetConfig.get('DeDenseNet') BlockReducor = DenseUNetConfig.get('BlockReducor') output_map = __base_feature(output_map, BaseFeature) cl = dmb.DenseNetProvide() cld = dmb.DeDenseNetProvide() output_map =
"{}" has status: "{}"' .format(var, job, status)) return row[4] return None @staticmethod def squeue(name=None): """Run the SLURM squeue command and return the stdout split to rows. Parameters ---------- name : str | None Optional to check the squeue for a specific job name (not limited to the 8 shown characters) or show users whole squeue. Returns ------- squeue_rows : list | None List of strings where each string is a row in the squeue printout. Returns None if squeue is empty. """ cmd = ('squeue -u {user}{job_name}' .format(user=SLURM.USER, job_name=' -n {}'.format(name) if name else '')) stdout, _ = SLURM.submit(cmd) if not stdout: # No jobs are currently running. return None else: squeue_rows = stdout.split('\n') return squeue_rows @staticmethod def scontrol(cmd): """Submit an scontrol command. Parameters ---------- cmd : str Command string after "scontrol" word """ cmd = 'scontrol {}'.format(cmd) cmd = shlex.split(cmd) call(cmd) @staticmethod def scancel(arg): """Cancel a slurm job. Parameters ---------- arg : int | list | str SLURM job id(s) to cancel. Can be a list of integer job ids, 'all' to cancel all jobs, or a feature (-p short) to cancel all jobs with a given feature """ if isinstance(arg, (list, tuple)): for jid in arg: SLURM.scancel(jid) elif str(arg).lower() == 'all': sq = SLURM.squeue() for row in sq[1:]: job_id = int(row.strip().split(' ')[0]) SLURM.scancel(job_id) elif isinstance(arg, (int, str)): cmd = ('scancel {}'.format(arg)) cmd = shlex.split(cmd) call(cmd) else: e = ('Could not cancel: {} with type {}' .format(arg, type(arg))) logger.error(e) raise ExecutionError(e) @staticmethod def change_qos(arg, qos): """Change the priority (quality of service) for a job. Parameters ---------- arg : int | list | str SLURM job id(s) to change qos for. Can be 'all' for all jobs. qos : str New qos value """ if isinstance(arg, (list, tuple)): for jid in arg: SLURM.change_qos(jid, qos) elif isinstance(arg, int): cmd = 'update job {} QOS={}'.format(arg, qos) SLURM.scontrol(cmd) elif str(arg).lower() == 'all': sq = SLURM.squeue() for row in sq[1:]: row_list = [x for x in row.strip().split(' ') if x != ''] job_id = int(row_list[0]) status = row_list[4] if status == 'PD': SLURM.change_qos(job_id, qos) else: e = ('Could not change qos of: {} with type {}' .format(arg, type(arg))) logger.error(e) raise ExecutionError(e) @staticmethod def hold(arg): """Temporarily hold a job from submitting. Held jobs will stay in queue but will not get nodes until released. Parameters ---------- arg : int | list | str SLURM job id(s) to hold. Can be 'all' to hold all jobs. """ if isinstance(arg, (list, tuple)): for jid in arg: SLURM.hold(jid) elif isinstance(arg, int): cmd = 'hold {}'.format(arg) SLURM.scontrol(cmd) elif str(arg).lower() == 'all': sq = SLURM.squeue() for row in sq[1:]: row_list = [x for x in row.strip().split(' ') if x != ''] job_id = int(row_list[0]) status = row_list[4] if status == 'PD': SLURM.hold(job_id) else: e = ('Could not hold: {} with type {}' .format(arg, type(arg))) logger.error(e) raise ExecutionError(e) @staticmethod def release(arg): """Release a job that was previously on hold so it will be submitted to a compute node. Parameters ---------- arg : int | list | str SLURM job id(s) to release. Can be 'all' to release all jobs. """ if isinstance(arg, (list, tuple)): for jid in arg: SLURM.release(jid) elif isinstance(arg, int): cmd = 'release {}'.format(arg) SLURM.scontrol(cmd) elif str(arg).lower() == 'all': sq = SLURM.squeue() for row in sq[1:]: row_list = [x for x in row.strip().split(' ') if x != ''] job_id = int(row_list[0]) status = row_list[4] reason = row_list[-1] if status == 'PD' and 'jobheld' in reason.lower(): SLURM.release(job_id) else: e = ('Could not release: {} with type {}' .format(arg, type(arg))) logger.error(e) raise ExecutionError(e) def sbatch(self, cmd, alloc, walltime, memory=None, feature=None, name='reV', stdout_path='./stdout', keep_sh=False, conda_env=None, module=None, module_root='/shared-projects/rev/modulefiles'): """Submit a SLURM job via sbatch command and SLURM shell script Parameters ---------- cmd : str Command to be submitted in PBS shell script. Example: 'python -m reV.generation.cli_gen' alloc : str HPC project (allocation) handle. Example: 'rev'. walltime : float Node walltime request in hours. memory : int Node memory request in GB. feature : str Additional flags for SLURM job. Format is "--qos=high" or "--depend=[state:job_id]". Default is None. name : str SLURM job name. stdout_path : str Path to print .stdout and .stderr files. keep_sh : bool Boolean to keep the .sh files. Default is to remove these files after job submission. conda_env : str Conda environment to activate module : bool Module to load module_root : str Path to module root to load Returns ------- out : str sbatch standard output, this is typically the SLURM job ID. err : str sbatch standard error, this is typically an empty string if the job was submitted successfully. """ status = self.check_status(name, var='name') if status in ('PD', 'R'): warn('Not submitting job "{}" because it is already in ' 'squeue with status: "{}"'.format(name, status)) out = None err = 'already_running' else: feature_str = '' if feature is not None: feature_str = '#SBATCH {} # extra feature\n'.format(feature) mem_str = '' if memory is not None: mem_str = ('#SBATCH --mem={} # node RAM in MB\n' .format(int(memory * 1000))) env_str = '' if module is not None: env_str = ("echo module use {module_root}\n" "module use {module_root}\n" "echo module load {module}\n" "module load {module}\n" "echo module load complete!\n" .format(module_root=module_root, module=module)) elif conda_env is not None: env_str = ("echo source activate {conda_env}\n" "source activate {conda_env}\n" "echo conda env activate complete!\n" .format(conda_env=conda_env)) fname = '{}.sh'.format(name) script = ('#!/bin/bash\n' '#SBATCH --account={a} # allocation account\n' '#SBATCH --time={t} # walltime\n' '#SBATCH --job-name={n} # job name\n' '#SBATCH --nodes=1 # number of nodes\n' '#SBATCH --output={p}/{n}_%j.o\n' '#SBATCH --error={p}/{n}_%j.e\n{m}{f}' 'echo Running on: $HOSTNAME, Machine Type: $MACHTYPE\n' '{e}\n{cmd}' .format(a=alloc, t=self.walltime(walltime), n=name, p=stdout_path, m=mem_str, f=feature_str, e=env_str, cmd=cmd)) # write the shell script file and submit as qsub job self.make_sh(fname, script) out, err = self.submit('sbatch {script}'.format(script=fname)) if err: w = 'Received a SLURM error or warning: {}'.format(err) logger.warning(w) warn(w, SlurmWarning) else: logger.debug('SLURM job "{}" with id #{} submitted ' 'successfully'.format(name, out)) if not keep_sh: self.rm(fname) return out, err class SpawnProcessPool(cf.ProcessPoolExecutor): """An adaptation of concurrent futures ProcessPoolExecutor with spawn processes instead of fork or forkserver.""" def __init__(self, *args, loggers=None, **kwargs): """ Parameters ---------- loggers : str | list, optional logger(s) to initialize on workers, by default None """ if 'mp_context' in kwargs: w = ('SpawnProcessPool being initialized with mp_context: "{}". ' 'This will override default SpawnProcessPool behavior.' .format(kwargs['mp_context'])) logger.warning(w) warn(w, ParallelExecutionWarning) else: kwargs['mp_context'] = multiprocessing.get_context('spawn') if loggers is not None: kwargs['initializer'] = LOGGERS.init_logger kwargs['initargs'] = (loggers, ) super().__init__(*args, **kwargs) def execute_parallel(fun, execution_iter, n_workers=None, **kwargs): """Execute concurrent futures with an established cluster. Parameters ---------- fun : function Python function object that will be submitted to futures. See downstream execution methods for arg passing structure. execution_iter : iter Python iterator that controls the futures submitted in parallel. n_workers : int Number of workers to run in parallel **kwargs : dict Key word arguments passed to the fun. Returns ------- results : list List of futures results. """ futures = [] # initialize a client based on the input cluster. with SpawnProcessPool(max_workers=n_workers) as executor: # iterate through split executions, submitting each to worker for i, exec_slice in enumerate(execution_iter): logger.debug('Kicking off serial worker #{} for: {}' .format(i, exec_slice)) # submit executions and append to futures list futures.append(executor.submit(execute_single, fun, exec_slice, worker=i, **kwargs)) # gather results results = [future.result() for future in futures] return results def execute_single(fun, input_obj, worker=0, **kwargs): """Execute a serial compute on a single core. Parameters ---------- fun : function Function to execute. input_obj : object Object passed as first argument to fun. Typically a project control object that can be the result of iteration in the parallel execution framework. worker : int Worker number (for debugging purposes). **kwargs : dict Key word arguments passed to fun. """ logger.debug('Running single serial execution on worker #{} for: {}' .format(worker, input_obj)) out = fun(input_obj, **kwargs) log_mem() return out class SmartParallelJob: """Single node parallel compute manager with smart data flushing.""" def __init__(self, obj,
import negation.modifiers as modifiers from abc import ABC, abstractmethod import re import pandas as pd from pprint import pprint class RiskVar(ABC): _df_atr_exclude = ["object", "mod"] def __init__(self, object): self.object = object self.literal = object.getLiteral() self.cat = object.categoryString() self.phrase = object.getPhrase() self._setSubClass() # Modification initialization self.mod = [] # self.negation = { # "score" : [], # "polarity" : None, # "conflict" : None} # self.date = [] # self.temp = [] # self.exam = [] # General post_process attributes # self.result = [] @abstractmethod def __eq__(self, other): pass @abstractmethod def _setSubClass(self): pass # @abstractmethod # def getOverview(self): # pass def addMod(self, mod): """Adds mod to self.mod list""" self.mod.append(mod) # All methods that must be called after object construction # and modifier addition def processInfo(self): """processes object and mod information after complete construction of object""" # If self.mod is not empty: if True: #self.mod: self._processMod() # self._analyseNeg() def getModInfo(self): dict = {} for index, mod in enumerate(self.mod): dict.update({index : mod.view()}) return(dict) def view(self): dict = { "literal" : self.literal, "category" : self.cat, "phrase" : self.phrase, "mods" : self.getModInfo()} return(dict) def getDataframe(self): # Add atributes that are not in exclude list to dataframe incl = list(set(vars(self)) - set(self._df_atr_exclude)) atr_df = pd.DataFrame() for atr in incl: # Exclude private attributes from dataframe if atr[0] != "_": # print(atr, getattr(self, atr)) atr_series = pd.Series(data=getattr(self, atr), name=atr) atr_df.insert(0, atr_series.name, atr_series, True) atr_df = atr_df.add_prefix("var_") # Gather mod info and put in dataframe mod_df = pd.DataFrame() for mod in self.mod: mod_df = mod_df.append(mod.getDataframe(), ignore_index=True, sort=False) # mod_df = mod_df.add_prefix("mod_") # combine both in dataframe: if len(mod_df.index > 0): df = pd.DataFrame() # Replicate atr_df rows to match number of mods atr_df = pd.concat([atr_df]*len(mod_df.index), ignore_index=True) # Join both dataframes: df = atr_df.join(mod_df, on=None, how='outer', sort=False) return(df) return(atr_df) def loopOverMods(self, method): for mod in self.mod: func = getattr(mod, method) pprint(func()) def _translate_negation(self): pass # # Check for modification # def _processMod(self): # """Processes modifier information: # """ # for mod in self.mod: # if isinstance(mod, modifiers.ExamMod): # self.exam.append(mod.value) # elif isinstance(mod, modifiers.NegMod): # self.negation["score"].append(mod.value) # elif isinstance(mod, modifiers.DateMod): # self.date.append(mod.value) # elif isinstance(mod, modifiers.TempMod): # self.temp.append(mod.value) # else: # raise Exception( # "Mod not recognized as one of valid options", # mod, mod.phrase, mod.type, mod.literal) _modSubClasses = ["negation", "date", "temporality", "examination"] def _processMod(self): """Processes the mods from this object into information displayed in a dataframe: Currently this dataframe contains per modifier sublclass: - Number of modifiers - If a conflict is present between modifiers of same subclass """ info = {} # Function to produce column for self._modInfo df def base(start): base = {} this_type = type(start) for subclass in self._modSubClasses: # Necessary to prevent same object is pasted into # every row # if "copy" in dir(start): # base.update({subclass : start.copy}) # else: # base.update({subclass : start}) base.update({subclass : this_type()}) return(base) ## Frequency freq = base(int()) for mod in self.mod: freq[mod.subClass] = freq[mod.subClass] + 1 ## Conflict conf = base(bool()) # compare every mod length = len(self.mod) for i in range(length): for j in range(i+1, length): # First check if same subclass if self.mod[i].subClass == self.mod[j].subClass: # If same subclass, but different mod value match = (self.mod[i] == self.mod[j]) # Set true if conflict (match = False) if not match: conf[self.mod[i].subClass] = True # Puts key in list if value is True conf_list = [key for key, value in conf.items() if value] if conf_list: self.mod_conflict = conf_list else: self.mod_conflict = False ## Modifier values: # Make a list per modifier subclass value = base(list()) for mod in self.mod: # print(value[mod.subClass]) # print(type(value[mod.subClass])) # Add the modifier value to the corresponding item value[mod.subClass].append(mod.value) ## Add all to info dictionary info.update({ "frequency" : freq, "conflict" : conf, "values" : value}) self._modInfo = pd.DataFrame(info) # df = pd.DataFrame() # for subclass in self._modSubClasses: # row = pd.Series(name = "Subclass", data = subclass) def getSummary(self): """returns a pandas series with for each mod type the value(s) in a list""" # Include: cat, phrase, value, modInfo to_df = {} to_df.update({ "category" : self.cat, "phrase" : self.phrase, "type" : self.subClass, "value" : self.value}) for row in self._modInfo.index: to_df.update({row : self._modInfo.at[row, "values"]}) row = pd.Series(to_df) return(pd.DataFrame(row).transpose()) # def _analyseNeg(self): # """Checks negation scores of finding. # If negation scores contradict eachother, a conflict is noted # If no conflict, negation can be determined to be "positive" (not negated) # or "negative" (negated). # """ # # If the finding has no negation modifiers, # # we assume it is positive # if not self.negation["score"]: # self.negation["conflict"] = False # self.negation["polarity"] = "positive" # else: # # Sets can't have duplicates # set_neg = set(self.negation["score"]) # pos = any(n > 0 for n in set_neg) # neg = any(n < 0 for n in set_neg) # oth = any(n == 0 for n in set_neg) # if len(set_neg) > 1 and pos and neg: # self.negation["conflict"] = True # else: # self.negation["conflict"] = False # if not self.negation["conflict"]: # if pos: # self.negation["polarity"] = "positive" # if neg: # self.negation["polarity"] = "negative" class NumVar(RiskVar): def __init__(self, object): # Numeric post_process attributes # self.rec_values = [] self.value = [] # self.values_conflict = None return super().__init__(object) def __eq__(self, other): return(self.value == other.value) def _setSubClass(self): self.subClass = "numeric" def processInfo(self): super().processInfo() self._setValue() # self._conflictValue() # self._processValue() # self._setResult() def _setValue(self): if self.cat == "vef": self._setValueVef() elif self.cat == "sbp": self._setValueSbp() else: raise Exception("Numeric variable, but not recognized as vef or sbp", self.phrase) def _setValueVef(self): """Collects values from target's phrase. Multiple values per string are separately added to self.rec_values list """ # Search for pattern with outer characters digits string = re.search(pattern = r"\d(.*)\d", string = self.phrase) if string is None: raise Exception( "No value found when searching in phrase of numeric variable", self.phrase) # If there are no other other characters within string # that are no digits, value is just the string if re.search(pattern=r"\D", string=string.group()) is None: self.value = int(string.group()) # Else, it is a range, so split up values else: values = re.findall(pattern = r"\d+", string=string.group()) range_list = [] for value in values: range_list.append(int(value)) if len(range_list) != 2: raise Exception("Phrase recognized as range, but no 2 values", self.phrase, string.group(), values, range_list) self.value = range_list def _setValueSbp(self): string = re.search(pattern = r"\d{2,3}(?=/(\d{2,3}))", string = self.phrase) if string is None: raise Exception( "No value found when searching in phrase of numeric variable", self.phrase) else: self.value = int(string.group()) def _conflictValue(self): ranges = [] ints = [] for i in self.value: if isinstance(i, int): ints.append(i) elif isinstance(i, list): ranges.append(i) else: raise Exception("No int and no list in self.values", i, self.value) if len(set(ints)) > 1: return True if any(isinstance(i, list) for i in self.value) \ or len(set(self.rec_values)) > 1: self.values_conflict = True else: self.values_conflict = False def _processValue(self): pass def _setResult(self): pass def getOverview(self): return({"value" : self.value, "negation" : self.negation["polarity"]}) class BinVar(RiskVar): def __init__(self, object): return super().__init__(object) def __eq__(self, other): if self.negation["conflict"] or other.negation["conflict"]: return False elif self.negation["polarity"] == other.negation["polarity"]: return True elif self.negation["polarity"] is not other.negation["polarity"]: return False else: raise Exception("__eq__ evaluation unseen outcome of:\n", self.negation,"\n", other.negation) def _setSubClass(self): self.subClass = "binary" def processInfo(self): super().processInfo() self._setValue() # self._setResult() # def _setResult(self): # self.result = {"negation" : self.negation["polarity"]} def _setValue(self): ls = self._modInfo.at["negation", "values"] # # In case now negation mods: True, so positive # if not ls: # ls = True self.value = ls def getOverview(self): return({"negation" : self.negation["polarity"]}) class FactVar(RiskVar): def __init__(self, object): self.factor = None return super().__init__(object) def __eq__(self, other): if self.negation["conflict"] or other.negation["conflict"]: neg = False elif self.negation["polarity"] == other.negation["polarity"]: neg = True elif self.negation["polarity"] is not other.negation["polarity"]: neg = False else: raise Exception("__eq__ evaluation unseen outcome of:\n", self.negation,"\n", other.negation) if self.factor == other.factor and neg: return True else: return False def _setSubClass(self):
<filename>sim21/unitop/EquiliReactor.py """Models a Equilibrium reactor Classes: ReactionDisplay - For rendering reaction EquilibriumReaction - Equilibrium reaction class InternalEqmReactor - Internal equilibrium reactor EquilibriumReactor - General equilibrium reactor """ import math # Common constants from sim21.unitop.BaseForReactors import QEXOTHERMIC_ISPOS_PAR, NURXN_PAR, REACTION from sim21.solver.Messages import MessageHandler from sim21.solver.Variables import * from sim21.unitop import UnitOperations, Balance, Sensor, Stream from sim21.unitop.ConvRxn import ConversionReaction from sim21.unitop.Pump import ATable # Particual constants and equations of this unit op MAXOUTERLOOPS = 50 EQM_CONST = 'EqmConst' CALCOPTION_PAR = 'CalculationOption' CONSTBASIS_PAR = 'CalculationBasis' BASISPUNIT_PAR = 'BasisPressureUnit' RXNTABLE = 'Table' RXNEQM = 'Eequilibrium' EQMCNSTCOEFF = 'EqmConstCoeff' NUMBSERIES_PAR = 'NumberSeries' SERIESTYPE_PAR = 'SeriesType' SERIES_OBJ = 'Series' class RxnVariable(object): """ translated from VB model """ def __init__(self, varName, varValue): self.name = varName self.currentValue = varValue def CopyFrom(self, otherVar): self.name = otherVar.name self.currentValue = otherVar.currentValue class RxnUnknowns(object): """ translated from VB model """ def __init__(self): self.numberOfUnknowns = 0 self.myVariables = [] def AddUnknown(self, uName, uValue): var = RxnVariable(uName, uValue) self.myVariables.append(var) self.numberOfUnknowns = len(self.myVariables) def RemoveUnknown(self, uName): for eachVar in self.myVariables: if eachVar.name == uName: self.myVariables.remove(eachVar) break self.numberOfUnknowns = len(self.myVariables) def GetNumberOfUnknowns(self): return self.numberOfUnknowns def GetMyVariableValues(self): vars = [] for i in range(self.numberOfUnknowns): vars.append(self.myVariables[i].currentValue) return vars def SetMyVariableValues(self, vars): for i in range(self.numberOfUnknowns): self.myVariables[i].currentValue = vars[i] def CleanUp(self): self.numberOfUnknowns = 0 self.myVariables = [] class NonLinearSolver(object): """ Non-linear solver class for EquiliReactor, translated from VB model """ def __init__(self): self.converged = 0 self.epsilon = 0.0001 self.useNumericJac = True def Solve(self, parent, uObj, numberOfEquations, max_num_iterations): self.converged = 0 self.useNumericJac = True x0 = uObj.GetMyVariableValues() x = x0 # Set initial deltaX to 1.0 to ensure that convergence check works deltaX = np.ones(numberOfEquations, np.float) idex = 0 try: while idex < max_num_iterations: # for idex in range(max_num_iterations): stepX = parent.CalculateStep(x) if stepX is None: return 0 rhs = parent.CalculateRHS(x) if self.useNumericJac == True: jacobian = parent.CalculateJacobian(x) elif self.useNumericJac == False: try: jacobian = parent.CalculateJacobian1(x) except: pass jacobian = np.linalg.inv(jacobian) deltaX = np.dot(jacobian, stepX) # deltaX = self.GetSolutionSolver(numberOfEquations, jacobian, stepX) # rhs) self.converged = self.CheckForConvergence(numberOfEquations, rhs, stepX, deltaX) if idex == max_num_iterations - 1: # show intermidiate results if self.useNumericJac == False: try: parentPath = parent.GetPath() parent.InfoMessage('ShowIntermidiateResults', (parentPath,)) uObj.SetMyVariableValues(x) return 2 except: return 0 else: self.useNumericJac = False x = x0 deltaX = np.zeros(numberOfEquations, np.float) idex = 0 elif self.converged: uObj.SetMyVariableValues(x) return 1 parent.UpdateX(x, deltaX) idex = idex + 1 except ArithmeticError as e: return 0 if not self.converged: return 0 def CheckForConvergence(self, numberOfEquations, rhs, dItem, deltaX): try: for i in range(numberOfEquations): if (abs(rhs[i]) > self.epsilon) and ( abs(dItem[i]) > self.epsilon * 0.01): # and (abs(deltaX[i]) > self.epsilon * 0.01) return 0 return 1 except: return 0 class EquilibriumConstant(object): """ class for returning a Equilibrium reaction Constant""" def __init__(self, parent): self._parent = parent # newly added for EquiliReactor, some may be removed later self.eqmCoeffs = [] self.tblEqmCoeffs = [] self.eqmKSpecs = [] self.eqmConstant = None # calculated equilibrium constant # A table lookup unit # with 2 series: tableTemperature, tablePressure self.kTable = ATable() self.kTable.SetSeriesCount(4) # 4 series: TableT, tebleK, Eff, KSpec self.kTable.SetSeriesType(0, T_VAR) self.kTable.SetSeriesType(1, GENERIC_VAR) self.kTable.SetSeriesType(2, GENERIC_VAR) # A,B,C,D self.kTable.SetSeriesType(3, GENERIC_VAR) # K Spec # self.kTable.SetSeriesType(2, GENERIC_VAR) self.tableTemp = [] self.tableKeq = [] self.myUnknowns = RxnUnknowns() self.mySolver = NonLinearSolver() def CorrelateCoeffs(self): # clear equlibrium constant and coefficients first self.eqmConstant = None # calculated equilibrium constant self.tblEqmCoeffs = [] tbl = self.kTable if tbl is None: return 0 srs0 = tbl.GetObject(SERIES_OBJ + str(0)) srs1 = tbl.GetObject(SERIES_OBJ + str(1)) if srs0 is None or srs1 is None: return 0 vals0 = srs0.GetValues() vals1 = srs1.GetValues() self.tableTemp = vals0 self.tableKeq = vals1 if len(vals0) == 0 or len(vals1) == 0 or len(vals0) != len(vals1): return 0 else: self.myUnknowns.CleanUp() if len(vals0) == 1: self.myUnknowns.AddUnknown("A", -10) nuEqu = 1 elif len(vals0) == 2: self.myUnknowns.AddUnknown("A", -10) self.myUnknowns.AddUnknown("B", 1) nuEqu = 2 elif len(vals0) == 3: self.myUnknowns.AddUnknown("A", -10) self.myUnknowns.AddUnknown("B", 1) self.myUnknowns.AddUnknown("C", 1) nuEqu = 3 else: self.myUnknowns.AddUnknown("A", -10) self.myUnknowns.AddUnknown("B", 1) self.myUnknowns.AddUnknown("C", 1) self.myUnknowns.AddUnknown("D", 0.001) nuEqu = 4 if not self.mySolver.Solve(self, self.myUnknowns, nuEqu, MAXOUTERLOOPS): return 0 self.tblEqmCoeffs = self.myUnknowns.GetMyVariableValues() if nuEqu < 4: for i in range(nuEqu, 4): self.tblEqmCoeffs.append(0) return 1 def GetObject(self, name): if name == RXNTABLE: return self.kTable else: return None def __str__(self): s = 'K value: ' + str(self.eqmConstant) s += '\nSpecified A, B, C, D: ' + str(self.eqmCoeffs) s += '\nRegressed A, B, C, D: ' + str(self.tblEqmCoeffs) def GetContents(self): result = [('K value', self.eqmConstant), ('Specified A, B, C, D', self.eqmCoeffs), ('Regressed A, B, C, D', self.tblEqmCoeffs)] result.extend(self.kTable.GetContents()) return result def CalculateKeq(self, temperature): calcOption = self._parent.parentUO.GetParameterValue(CALCOPTION_PAR) try: self.eqmConstant = None # self.eqmCoeffs = [] logK = None if calcOption == 1: # or calcOption == 3: if self.CorrelateCoeffs(): logK = (self.tblEqmCoeffs[0] + self.tblEqmCoeffs[1] / temperature + self.tblEqmCoeffs[2] * math.log( temperature) + self.tblEqmCoeffs[3] * temperature) else: self.eqmConstant = None elif calcOption == 2: logK = self.GibbsEqmConstant(temperature) elif calcOption == 3: tbl = self.kTable if tbl is None: return None srs2 = tbl.GetObject(SERIES_OBJ + str(3)) vals2 = srs2.GetValues() self.eqmKSpecs = vals2 self.eqmConstant = self.eqmKSpecs[0] logK = None elif calcOption == 4: tbl = self.kTable if tbl is None: return None srs2 = tbl.GetObject(SERIES_OBJ + str(2)) vals2 = srs2.GetValues() self.eqmCoeffs = vals2 self.tblEqmCoeffs = [] # self.eqmCoeffs = self.kTable.GetObject(SERIES_OBJ + str(2)).GetValues() logK = (self.eqmCoeffs[0] + self.eqmCoeffs[1] / temperature + self.eqmCoeffs[2] * math.log( temperature) + self.eqmCoeffs[3] * temperature) if logK is not None: if logK > 300: logK = 300 if logK < -300: logK = -300 self.eqmConstant = math.exp(logK) return self.eqmConstant except: return None def CalculateStep(self, x): rhs = np.zeros(len(x), np.float) try: dum = 0 if len(self.tableKeq) == len(self.tableTemp): if len(x) == 1: for i in range(len(self.tableTemp)): dum = x[0] - math.log(self.tableKeq[i]) rhs[0] = rhs[0] + 2 * dum elif len(x) == 2: for i in range(len(self.tableTemp)): dum = x[0] + x[1] / self.tableTemp[i] - math.log(self.tableKeq[i]) rhs[0] = rhs[0] + 2 * dum rhs[1] = rhs[1] + 2 * dum / self.tableTemp[i] elif len(x) == 3: for i in range(len(self.tableTemp)): dum = x[0] + x[1] / self.tableTemp[i] + x[2] * math.log(self.tableTemp[i]) - math.log( self.tableKeq[i]) rhs[0] = rhs[0] + 2 * dum rhs[1] = rhs[1] + 2 * dum / self.tableTemp[i] rhs[2] = rhs[2] + 2 * dum * math.log(self.tableTemp[i]) else: for i in range(len(self.tableTemp)): dum = x[0] + x[1] / self.tableTemp[i] + x[2] * math.log(self.tableTemp[i]) + x[3] * \ self.tableTemp[i] - math.log(self.tableKeq[i]) rhs[0] = rhs[0] + 2 * dum rhs[1] = rhs[1] + 2 * dum / self.tableTemp[i] rhs[2] = rhs[2] + 2 * dum * math.log(self.tableTemp[i]) rhs[3] = rhs[3] + 2 * dum * self.tableTemp[i] return rhs except: return None def CalculateRHS(self, x): try: sum = 0.0 nEq = len(x) if len(self.tableKeq) == len(self.tableTemp): for i in range(len(self.tableTemp)): denom = 1.e-20 if abs(math.log(self.tableKeq[i])) > denom: denom = math.log(self.tableKeq[i]) if nEq == 1: tVal = x[0] elif nEq == 2: tVal = x[0] + x[1] / self.tableTemp[i] elif nEq == 3: tVal = x[0] + x[1] / self.tableTemp[i] + x[2] * math.log(self.tableTemp[i]) else: tVal = x[0] + x[1] / self.tableTemp[i] + x[2] * math.log(self.tableTemp[i]) + x[3] * \ self.tableTemp[i] dum = tVal - math.log(self.tableKeq[i]) sum += abs(dum / denom) rhs = 2 * sum * np.ones(nEq, np.float) return rhs except: return None def CalculateJacobian(self, x): j = np.zeros((len(x), len(x)), np.float) try: workArray1 = self.CalculateStep(x) # Calculate Jacobian by shifting # unshifted RHS's shift = 1 for i2 in range(len(x)): xOld = x[i2] x[i2] = x[i2] + shift workArray2 = self.CalculateStep(x) for i1 in range(len(x)): j[i1][i2] = (workArray2[i1] - workArray1[i1]) / shift x[i2] = xOld return j except: return j def UpdateX(self, x, deltaX): scaleFactor = 1 for i in range(len(x)): if deltaX[i] != 0.0: scaleFactor1 = 100000 / abs(deltaX[i]) if scaleFactor1 < scaleFactor: scaleFactor = scaleFactor1 for i in range(len(x)): x[i] = x[i] - deltaX[i] * scaleFactor def CompoundGibbs(self, nc, rxnT): try: parent = self._parent.parentUO # rxnT = parent.outPort.GetPropValue(T_VAR) rxnP = parent.outPort.GetPropValue(P_VAR) # arbitary composition x = np.zeros(nc, np.float) x[0] = 1.0 # check whether it returns G or g/RT # check whether it has mixing rule thCaseObj = parent.GetThermo() thAdmin, prov, case = thCaseObj.thermoAdmin, thCaseObj.provider, thCaseObj.case
import math import logging import numpy as np from os.path import join import os import torch from torch import nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from collections import OrderedDict from .dla import DLAMain,BasicBlock,DLAUp,IDAUp # from .DCNv2.dcn_v2 import DCN from ..registry import BACKBONES logger = logging.getLogger(__name__) def fill_up_weights(up): w = up.weight.data f = math.ceil(w.size(2) / 2) c = (2 * f - 1 - f % 2) / (2. * f) for i in range(w.size(2)): for j in range(w.size(3)): w[0, 0, i, j] = \ (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c)) for c in range(1, w.size(0)): w[c, 0, :, :] = w[0, 0, :, :] def load_state_dict(checkpoint_path, use_ema=False): if checkpoint_path and os.path.isfile(checkpoint_path): checkpoint = torch.load(checkpoint_path, map_location='cpu') state_dict_key = 'state_dict' if state_dict_key and state_dict_key in checkpoint: if use_ema and 'state_dict_ema' in checkpoint: state_dict_key = 'state_dict_ema' state_dict = checkpoint[state_dict_key] else: state_dict = checkpoint #if state_dict_key and state_dict_key in checkpoint: if 1: new_state_dict = OrderedDict() for k, v in state_dict.items(): # strip `module.` prefix name = k[7:] if k.startswith('module') else k if 'fc.weight' == name: classifier_weight = v[:5] new_state_dict[name] = classifier_weight[:] elif 'fc.bias' == name: classifier_bias = v[:5] new_state_dict[name] = classifier_bias[:] else: new_state_dict[name] = v # del new_state_dict['fc.weight'] # del new_state_dict['fc.bias'] state_dict = new_state_dict else: state_dict = checkpoint logging.info("Loaded {} from checkpoint '{}'".format(state_dict_key, checkpoint_path)) return state_dict else: logging.error("No checkpoint found at '{}'".format(checkpoint_path)) raise FileNotFoundError() def load_checkpoint(model, checkpoint_path, use_ema=False): state_dict = load_state_dict(checkpoint_path, use_ema) model.load_state_dict(state_dict, strict=False) class ConvBnRelu(nn.Module): def __init__(self, inplanes, first_planes, outplanes, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d,): super(ConvBnRelu, self).__init__() self.conv = nn.Conv2d(inplanes, first_planes, kernel_size=3, padding=1, bias=False) self.bn = norm_layer(first_planes) self.conv_h = nn.Conv2d(inplanes, first_planes, kernel_size=(1,3), padding=(0,1), bias=False) self.bn_h = norm_layer(first_planes) self.conv_v = nn.Conv2d(inplanes, first_planes, kernel_size=(3,1), padding=(1,0), bias=False) self.bn_v = norm_layer(first_planes) self.act = act_layer(inplace=True) def forward(self, x): x1 = self.conv(x) x1 = self.bn(x1) x2 = self.conv_h(x) x2 = self.bn_h(x2) x3 = self.conv_v(x) x3 = self.bn_v(x3) x = x1+x2+x3 x = self.act(x) return x class ConvBnRelu1x1(nn.Module): def __init__(self, inplanes, first_planes, outplanes, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d,): super(ConvBnRelu1x1, self).__init__() self.conv = nn.Conv2d(inplanes, first_planes, kernel_size=1, padding=0, bias=False) self.bn = norm_layer(first_planes) # self.conv_h = nn.Conv2d(inplanes, first_planes, kernel_size=(1,3), padding=(0,1), bias=False) # self.bn_h = norm_layer(first_planes) # self.conv_v = nn.Conv2d(inplanes, first_planes, kernel_size=(3,1), padding=(1,0), bias=False) # self.bn_v = norm_layer(first_planes) self.act = act_layer(inplace=True) def forward(self, x): x = self.conv(x) x = self.bn(x) x = self.act(x) # x2 = self.conv_dw_(x) # x2 = self.bn_dw_h(x2) # x3 = self.conv_dw_v(x) # x3 = self.bn_dw_v(x3) # x = x1+x2+x3 return x class DlaBlock1(nn.Module): def __init__(self, inplanes, first_planes, outplanes, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d,): super(DlaBlock1, self).__init__() self._1_conv1 = nn.Conv2d(inplanes, first_planes, stride = 2, kernel_size=3, padding=1, bias=False) self._1_bn1 = norm_layer(first_planes) self._1_conv1_h = nn.Conv2d(inplanes, first_planes,stride = 2, kernel_size=(1,3), padding=(0,1), bias=False) self._1_bn1_h = norm_layer(first_planes) self._1_conv1_v = nn.Conv2d(inplanes, first_planes, stride = 2, kernel_size=(3,1), padding=(1,0), bias=False) self._1_bn1_v = norm_layer(first_planes) self._1_act1 = act_layer(inplace=True) self._1_conv2 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._1_bn2 = norm_layer(first_planes) self._1_conv2_h = nn.Conv2d(first_planes, first_planes,stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._1_bn2_h = norm_layer(first_planes) self._1_conv2_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._1_bn2_v = norm_layer(first_planes) self._1_act2 = act_layer(inplace=True) self._1_pool = nn.MaxPool2d(stride=2, kernel_size=2) self._1_pool_conv = nn.Conv2d(inplanes, first_planes, kernel_size=1, stride=1, padding=0, bias=False) self._1_pool_bn = norm_layer(first_planes) self._2_conv1 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._2_bn1 = norm_layer(first_planes) self._2_conv1_h = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._2_bn1_h = norm_layer(first_planes) self._2_conv1_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._2_bn1_v = norm_layer(first_planes) self._2_act1 = act_layer(inplace=True) self._2_conv2 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._2_bn2 = norm_layer(first_planes) self._2_conv2_h = nn.Conv2d(first_planes, first_planes,stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._2_bn2_h = norm_layer(first_planes) self._2_conv2_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._2_bn2_v = norm_layer(first_planes) self._2_act2 = act_layer(inplace=True) #self._2_conv_proj = nn.Conv2d(inplanes + first_planes * 2, first_planes, kernel_size=1, stride=1, padding=0, bias=False) self._2_conv_proj = nn.Conv2d(first_planes, first_planes, kernel_size=1, stride=1, padding=0, bias=False) self._2_bn_proj = norm_layer(first_planes) self._2_act_proj = act_layer(inplace=True) def forward(self, x): r = x r = self._1_pool(r) #r1 = r r = self._1_pool_conv(r) r = self._1_pool_bn(r) x1 = self._1_conv1(x) x1 = self._1_bn1(x1) x2 = self._1_conv1_h(x) x2 = self._1_bn1_h(x2) x3 = self._1_conv1_v(x) x3 = self._1_bn1_v(x3) x = x1+x2+x3 x = self._1_act1(x) x1 = self._1_conv2(x) x1 = self._1_bn2(x1) x2 = self._1_conv2_h(x) x2 = self._1_bn2_h(x2) x3 = self._1_conv2_v(x) x3 = self._1_bn2_v(x3) x = x1+x2+x3 x = x + r x = self._1_act2(x) r2 = x x1 = self._2_conv1(x) x1 = self._2_bn1(x1) x2 = self._2_conv1_h(x) x2 = self._2_bn1_h(x2) x3 = self._2_conv1_v(x) x3 = self._2_bn1_v(x3) x = x1+x2+x3 x = self._2_act1(x) x1 = self._2_conv2(x) x1 = self._2_bn2(x1) x2 = self._2_conv2_h(x) x2 = self._2_bn2_h(x2) x3 = self._2_conv2_v(x) x3 = self._2_bn2_v(x3) x = x1+x2+x3 x = x + r2 x = self._2_act2(x) #x = torch.cat([r1, r2, x], 1) #x = r2 + x x = self._2_conv_proj(x) x = self._2_bn_proj(x) x = self._2_act_proj(x) return x class DlaBlock2(nn.Module): def __init__(self, inplanes, first_planes, outplanes, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d,): super(DlaBlock2, self).__init__() self._1_conv1 = nn.Conv2d(inplanes, first_planes, stride = 2, kernel_size=3, padding=1, bias=False) self._1_bn1 = norm_layer(first_planes) self._1_conv1_h = nn.Conv2d(inplanes, first_planes,stride = 2, kernel_size=(1,3), padding=(0,1), bias=False) self._1_bn1_h = norm_layer(first_planes) self._1_conv1_v = nn.Conv2d(inplanes, first_planes, stride = 2, kernel_size=(3,1), padding=(1,0), bias=False) self._1_bn1_v = norm_layer(first_planes) self._1_act1 = act_layer(inplace=True) self._1_conv2 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._1_bn2 = norm_layer(first_planes) self._1_conv2_h = nn.Conv2d(first_planes, first_planes,stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._1_bn2_h = norm_layer(first_planes) self._1_conv2_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._1_bn2_v = norm_layer(first_planes) self._1_act2 = act_layer(inplace=True) self._1_pool = nn.MaxPool2d(stride=2, kernel_size=2) self._1_pool_conv = nn.Conv2d(inplanes, first_planes, kernel_size=1, stride=1, padding=0, bias=False) self._1_pool_bn = norm_layer(first_planes) self._2_conv1 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._2_bn1 = norm_layer(first_planes) self._2_conv1_h = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._2_bn1_h = norm_layer(first_planes) self._2_conv1_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._2_bn1_v = norm_layer(first_planes) self._2_act1 = act_layer(inplace=True) self._2_conv2 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._2_bn2 = norm_layer(first_planes) self._2_conv2_h = nn.Conv2d(first_planes, first_planes,stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._2_bn2_h = norm_layer(first_planes) self._2_conv2_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._2_bn2_v = norm_layer(first_planes) self._2_act2 = act_layer(inplace=True) #self._2_conv_proj = nn.Conv2d(inplanes + first_planes * 2, first_planes, kernel_size=1, stride=1, padding=0, bias=False) self._2_conv_proj = nn.Conv2d(first_planes, first_planes, kernel_size=1, stride=1, padding=0, bias=False) self._2_bn_proj = norm_layer(first_planes) self._2_act_proj = act_layer(inplace=True) self._3_conv1 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._3_bn1 = norm_layer(first_planes) self._3_conv1_h = nn.Conv2d(first_planes, first_planes,stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._3_bn1_h = norm_layer(first_planes) self._3_conv1_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._3_bn1_v = norm_layer(first_planes) self._3_act1 = act_layer(inplace=True) self._3_conv2 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._3_bn2 = norm_layer(first_planes) self._3_conv2_h = nn.Conv2d(first_planes, first_planes,stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._3_bn2_h = norm_layer(first_planes) self._3_conv2_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._3_bn2_v = norm_layer(first_planes) self._3_act2 = act_layer(inplace=True) self._4_conv1 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._4_bn1 = norm_layer(first_planes) self._4_conv1_h = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._4_bn1_h = norm_layer(first_planes) self._4_conv1_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._4_bn1_v = norm_layer(first_planes) self._4_act1 = act_layer(inplace=True) self._4_conv2 = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=3, padding=1, bias=False) self._4_bn2 = norm_layer(first_planes) self._4_conv2_h = nn.Conv2d(first_planes, first_planes,stride = 1, kernel_size=(1,3), padding=(0,1), bias=False) self._4_bn2_h = norm_layer(first_planes) self._4_conv2_v = nn.Conv2d(first_planes, first_planes, stride = 1, kernel_size=(3,1), padding=(1,0), bias=False) self._4_bn2_v = norm_layer(first_planes) self._4_act2 = act_layer(inplace=True) #self._4_conv_proj = nn.Conv2d(inplanes + first_planes * 3, first_planes, kernel_size=1, stride=1, padding=0, bias=False) self._4_conv_proj = nn.Conv2d(first_planes, first_planes, kernel_size=1, stride=1, padding=0, bias=False) self._4_bn_proj = norm_layer(first_planes) self._4_act_proj = act_layer(inplace=True) def forward(self, x): r = x r = self._1_pool(r) #r1 = r r = self._1_pool_conv(r) r = self._1_pool_bn(r) x1 = self._1_conv1(x) x1 = self._1_bn1(x1) x2 = self._1_conv1_h(x) x2 = self._1_bn1_h(x2) x3 = self._1_conv1_v(x) x3 = self._1_bn1_v(x3) x = x1+x2+x3 x = self._1_act1(x) x1 = self._1_conv2(x) x1 = self._1_bn2(x1) x2 = self._1_conv2_h(x) x2 = self._1_bn2_h(x2) x3 = self._1_conv2_v(x) x3 = self._1_bn2_v(x3) x = x1+x2+x3 x = x + r x = self._1_act2(x) r2 = x x1 = self._2_conv1(x) x1 = self._2_bn1(x1) x2 = self._2_conv1_h(x) x2 = self._2_bn1_h(x2) x3 = self._2_conv1_v(x) x3 = self._2_bn1_v(x3) x = x1+x2+x3 x = self._2_act1(x) x1 = self._2_conv2(x) x1 = self._2_bn2(x1) x2 = self._2_conv2_h(x) x2 = self._2_bn2_h(x2) x3 = self._2_conv2_v(x) x3 = self._2_bn2_v(x3) x = x1+x2+x3 x = x + r2
# # Autogenerated by Thrift # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # from cyclozzo.thrift.Thrift import * from ttypes import * from cyclozzo.thrift.Thrift import TProcessor from cyclozzo.thrift.transport import TTransport from cyclozzo.thrift.protocol import TBinaryProtocol, TProtocol try: from cyclozzo.thrift.protocol import fastbinary except: fastbinary = None class Iface: """ The client service mimics the C++ client API, with table, scanner and mutator interface flattened. """ def create_namespace(self, ns): """ Create a namespace @param ns - namespace name Parameters: - ns """ pass def create_table(self, ns, table_name, schema): """ Create a table @param ns - namespace id @param table_name - table name @param schema - schema of the table (in xml) Parameters: - ns - table_name - schema """ pass def open_namespace(self, ns): """ Open a namespace @param ns - namespace @return value is guaranteed to be non-zero and unique Parameters: - ns """ pass def close_namespace(self, ns): """ Close a namespace @param ns - namespace Parameters: - ns """ pass def open_scanner(self, ns, table_name, scan_spec, retry_table_not_found): """ Open a table scanner @param ns - namespace id @param table_name - table name @param scan_spec - scan specification @param retry_table_not_found - whether to retry upon errors caused by drop/create tables with the same name Parameters: - ns - table_name - scan_spec - retry_table_not_found """ pass def close_scanner(self, scanner): """ Close a table scanner @param scanner - scanner id to close Parameters: - scanner """ pass def next_cells(self, scanner): """ Iterate over cells of a scanner @param scanner - scanner id Parameters: - scanner """ pass def next_cells_as_arrays(self, scanner): """ Parameters: - scanner """ pass def next_cells_serialized(self, scanner): """ Alternative interface returning buffer of serialized cells Parameters: - scanner """ pass def next_row(self, scanner): """ Iterate over rows of a scanner @param scanner - scanner id Parameters: - scanner """ pass def next_row_as_arrays(self, scanner): """ Alternative interface using array as cell Parameters: - scanner """ pass def next_row_serialized(self, scanner): """ Alternate interface returning a buffer of serialized cells for iterating by row for a given scanner @param scanner - scanner id Parameters: - scanner """ pass def get_row(self, ns, table_name, row): """ Get a row (convenience method for random access a row) @param ns - namespace id @param table_name - table name @param row - row key @return a list of cells (with row_keys unset) Parameters: - ns - table_name - row """ pass def get_row_as_arrays(self, ns, name, row): """ Alternative interface using array as cell Parameters: - ns - name - row """ pass def get_row_serialized(self, ns, table_name, row): """ Alternative interface returning buffer of serialized cells Parameters: - ns - table_name - row """ pass def get_cell(self, ns, table_name, row, column): """ Get a cell (convenience method for random access a cell) @param ns - namespace id @param table_name - table name @param row - row key @param column - column name @return value (byte sequence) Parameters: - ns - table_name - row - column """ pass def get_cells(self, ns, table_name, scan_spec): """ Get cells (convenience method for access small amount of cells) @param ns - namespace id @param table_name - table name @param scan_spec - scan specification @return a list of cells (a cell with no row key set is assumed to have the same row key as the previous cell) Parameters: - ns - table_name - scan_spec """ pass def get_cells_as_arrays(self, ns, name, scan_spec): """ Alternative interface using array as cell Parameters: - ns - name - scan_spec """ pass def get_cells_serialized(self, ns, name, scan_spec): """ Alternative interface returning buffer of serialized cells Parameters: - ns - name - scan_spec """ pass def refresh_shared_mutator(self, ns, table_name, mutate_spec): """ Create a shared mutator with specified MutateSpec. Delete and recreate it if the mutator exists. @param ns - namespace id @param table_name - table name @param mutate_spec - mutator specification Parameters: - ns - table_name - mutate_spec """ pass def offer_cells(self, ns, table_name, mutate_spec, cells): """ Open a shared periodic mutator which causes cells to be written asyncronously. Users beware: calling this method merely writes cells to a local buffer and does not guarantee that the cells have been persisted. If you want guaranteed durability, use the open_mutator+set_cells* interface instead. @param ns - namespace id @param table_name - table name @param mutate_spec - mutator specification @param cells - set of cells to be written Parameters: - ns - table_name - mutate_spec - cells """ pass def offer_cells_as_arrays(self, ns, table_name, mutate_spec, cells): """ Alternative to offer_cell interface using array as cell Parameters: - ns - table_name - mutate_spec - cells """ pass def offer_cell(self, ns, table_name, mutate_spec, cell): """ Open a shared periodic mutator which causes cells to be written asyncronously. Users beware: calling this method merely writes cells to a local buffer and does not guarantee that the cells have been persisted. If you want guaranteed durability, use the open_mutator+set_cells* interface instead. @param ns - namespace id @param table_name - table name @param mutate_spec - mutator specification @param cell - cell to be written Parameters: - ns - table_name - mutate_spec - cell """ pass def offer_cell_as_array(self, ns, table_name, mutate_spec, cell): """ Alternative to offer_cell interface using array as cell Parameters: - ns - table_name - mutate_spec - cell """ pass def open_mutator(self, ns, table_name, flags, flush_interval): """ Open a table mutator @param ns - namespace id @param table_name - table name @param flags - mutator flags @param flush_interval - auto-flush interval in milliseconds; 0 disables it. @return mutator id Parameters: - ns - table_name - flags - flush_interval """ pass def close_mutator(self, mutator, flush): """ Close a table mutator @param mutator - mutator id to close Parameters: - mutator - flush """ pass def set_cell(self, mutator, cell): """ Set a cell in the table @param mutator - mutator id @param cell - the cell to set Parameters: - mutator - cell """ pass def set_cell_as_array(self, mutator, cell): """ Alternative interface using array as cell Parameters: - mutator - cell """ pass def set_cells(self, mutator, cells): """ Put a list of cells into a table @param mutator - mutator id @param cells - a list of cells (a cell with no row key set is assumed to have the same row key as the previous cell) Parameters: - mutator - cells """ pass def set_cells_as_arrays(self, mutator, cells): """ Alternative interface using array as cell Parameters: - mutator - cells """ pass def set_cells_serialized(self, mutator, cells, flush): """ Alternative interface using buffer of serialized cells Parameters: - mutator - cells - flush """ pass def flush_mutator(self, mutator): """ Flush mutator buffers Parameters: - mutator """ pass def exists_namespace(self, ns): """ Check if the namespace exists @param ns - namespace name @return true if ns exists, false ow Parameters: - ns """ pass def exists_table(self, ns, name): """ Check if the table exists @param ns - namespace id @param name - table name @return true if table exists, false ow Parameters: - ns - name """ pass def get_table_id(self, ns, table_name): """ Get the id of a table @param ns - namespace id @param table_name - table name @return table id string Parameters: - ns - table_name """ pass def get_schema_str(self, ns, table_name): """ Get the schema of a table as a string (that can be used with create_table) @param ns - namespace id @param table_name - table name @return schema string (in xml) Parameters: - ns - table_name """ pass def get_schema(self, ns, table_name): """ Get the schema of a table as a string (that can be used with create_table) @param ns - namespace id @param table_name - table name @return schema object describing a table Parameters: - ns - table_name """ pass def get_tables(self, ns): """ Get a list of table names in the namespace @param ns - namespace id @return a list of
is None: a_alpha_ijs, a_alpha_roots, a_alpha_ij_roots_inv = a_alpha_aijs_composition_independent(a_alphas, kijs) z_products = [[zs[i]*zs[j] for j in range(N)] for i in range(N)] # numba : delete # z_products = np.zeros((N, N)) # numba: uncomment # for i in range(N): # numba: uncomment # for j in range(N): # numba: uncomment # z_products[i][j] = zs[i]*zs[j] # numba: uncomment a_alpha = 0.0 for i in range(N): a_alpha_ijs_i = a_alpha_ijs[i] z_products_i = z_products[i] for j in range(i): term = a_alpha_ijs_i[j]*z_products_i[j] a_alpha += term + term a_alpha += a_alpha_ijs_i[i]*z_products_i[i] da_alpha_dT_ijs = [[0.0]*N for _ in range(N)] # numba : delete # da_alpha_dT_ijs = np.zeros((N, N)) # numba: uncomment d2a_alpha_dT2_ijs = [[0.0]*N for _ in range(N)] # numba : delete # d2a_alpha_dT2_ijs = np.zeros((N, N)) # numba: uncomment d2a_alpha_dT2_ij = 0.0 for i in range(N): kijs_i = kijs[i] a_alphai = a_alphas[i] z_products_i = z_products[i] da_alpha_dT_i = da_alpha_dTs[i] d2a_alpha_dT2_i = d2a_alpha_dT2s[i] a_alpha_ij_roots_inv_i = a_alpha_ij_roots_inv[i] da_alpha_dT_ijs_i = da_alpha_dT_ijs[i] for j in range(N): # for j in range(0, i+1): if j < i: # # skip the duplicates continue a_alphaj = a_alphas[j] x0_05_inv = a_alpha_ij_roots_inv_i[j] zi_zj = z_products_i[j] da_alpha_dT_j = da_alpha_dTs[j] x1 = a_alphai*da_alpha_dT_j x2 = a_alphaj*da_alpha_dT_i x1_x2 = x1 + x2 x3 = x1_x2 + x1_x2 kij_m1 = kijs_i[j] - 1.0 da_alpha_dT_ij = -0.5*kij_m1*x1_x2*x0_05_inv # For temperature derivatives of fugacities da_alpha_dT_ijs_i[j] = da_alpha_dT_ijs[j][i] = da_alpha_dT_ij da_alpha_dT_ij *= zi_zj x0 = a_alphai*a_alphaj d2a_alpha_dT2_ij = kij_m1*( (x0*( -0.5*(a_alphai*d2a_alpha_dT2s[j] + a_alphaj*d2a_alpha_dT2_i) - da_alpha_dT_i*da_alpha_dT_j) +.25*x1_x2*x1_x2)/(x0_05_inv*x0*x0)) d2a_alpha_dT2_ijs[i][j] = d2a_alpha_dT2_ijs[j][i] = d2a_alpha_dT2_ij d2a_alpha_dT2_ij *= zi_zj if i != j: da_alpha_dT += da_alpha_dT_ij + da_alpha_dT_ij d2a_alpha_dT2 += d2a_alpha_dT2_ij + d2a_alpha_dT2_ij else: da_alpha_dT += da_alpha_dT_ij d2a_alpha_dT2 += d2a_alpha_dT2_ij return a_alpha, da_alpha_dT, d2a_alpha_dT2, a_alpha_ijs, da_alpha_dT_ijs, d2a_alpha_dT2_ijs def a_alpha_quadratic_terms(a_alphas, a_alpha_roots, T, zs, kijs, a_alpha_j_rows=None, vec0=None): r'''Calculates the `a_alpha` term for an equation of state along with the vector quantities needed to compute the fugacities of the mixture. This routine is efficient in both numba and PyPy. .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} The secondary values are as follows: .. math:: \sum_i y_i(a\alpha)_{ij} Parameters ---------- a_alphas : list[float] EOS attractive terms, [J^2/mol^2/Pa] a_alpha_roots : list[float] Square roots of `a_alphas`; provided for speed [J/mol/Pa^0.5] T : float Temperature, not used, [K] zs : list[float] Mole fractions of each species kijs : list[list[float]] Constant kijs, [-] a_alpha_j_rows : list[float], optional EOS attractive term row destimation vector (does not need to be zeroed, should be provided to prevent allocations), [J^2/mol^2/Pa] vec0 : list[float], optional Empty vector, used in internal calculations, provide to avoid the allocations; does not need to be zeroed, [-] Returns ------- a_alpha : float EOS attractive term, [J^2/mol^2/Pa] a_alpha_j_rows : list[float] EOS attractive term row sums, [J^2/mol^2/Pa] Notes ----- Tried moving the i=j loop out, no difference in speed, maybe got a bit slower in PyPy. Examples -------- >>> kijs = [[0,.083],[0.083,0]] >>> zs = [0.1164203, 0.8835797] >>> a_alphas = [0.2491099357671155, 0.6486495863528039] >>> a_alpha_roots = [i**0.5 for i in a_alphas] >>> a_alpha, a_alpha_j_rows = a_alpha_quadratic_terms(a_alphas, a_alpha_roots, 299.0, zs, kijs) >>> a_alpha, a_alpha_j_rows (0.58562139582, [0.35469988173, 0.61604757237]) ''' N = len(a_alphas) if a_alpha_j_rows is None: a_alpha_j_rows = [0.0]*N for i in range(N): a_alpha_j_rows[i] = 0.0 if vec0 is None: vec0 = [0.0]*N for i in range(N): vec0[i] = a_alpha_roots[i]*zs[i] a_alpha = 0.0 i = 0 while i < N: kijs_i = kijs[i] j = 0 while j < i: # Numba appears to be better with this split into two loops. # PyPy has 1.5x speed reduction when so. a_alpha_j_rows[j] += (1. - kijs_i[j])*vec0[i] a_alpha_j_rows[i] += (1. - kijs_i[j])*vec0[j] j += 1 i += 1 for i in range(N): a_alpha_j_rows[i] *= a_alpha_roots[i] a_alpha_j_rows[i] += (1. - kijs[i][i])*a_alphas[i]*zs[i] a_alpha += a_alpha_j_rows[i]*zs[i] return a_alpha, a_alpha_j_rows # This is faster in PyPy and can be made even faster optimizing a_alpha! ''' N = len(a_alphas) a_alpha_j_rows = [0.0]*N a_alpha = 0.0 for i in range(N): kijs_i = kijs[i] a_alpha_i_root_i = a_alpha_roots[i] for j in range(i): a_alpha_ijs_ij = (1. - kijs_i[j])*a_alpha_i_root_i*a_alpha_roots[j] t200 = a_alpha_ijs_ij*zs[i] a_alpha_j_rows[j] += t200 a_alpha_j_rows[i] += zs[j]*a_alpha_ijs_ij t200 *= zs[j] a_alpha += t200 + t200 t200 = (1. - kijs_i[i])*a_alphas[i]*zs[i] a_alpha += t200*zs[i] a_alpha_j_rows[i] += t200 return a_alpha, a_alpha_j_rows ''' def a_alpha_and_derivatives_quadratic_terms(a_alphas, a_alpha_roots, da_alpha_dTs, d2a_alpha_dT2s, T, zs, kijs, a_alpha_j_rows=None, da_alpha_dT_j_rows=None): r'''Calculates the `a_alpha` term, and its first two temperature derivatives, for an equation of state along with the vector quantities needed to compute the fugacitie and temperature derivatives of fugacities of the mixture. This routine is efficient in both numba and PyPy. .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} .. math:: \frac{\partial (a\alpha)}{\partial T} = \sum_i \sum_j z_i z_j \frac{\partial (a\alpha)_{ij}}{\partial T} .. math:: \frac{\partial^2 (a\alpha)}{\partial T^2} = \sum_i \sum_j z_i z_j \frac{\partial^2 (a\alpha)_{ij}}{\partial T^2} .. math:: (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} .. math:: \frac{\partial (a\alpha)_{ij}}{\partial T} = \frac{\sqrt{\operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}} {\left(T \right)}} \left(1 - k_{ij}\right) \left(\frac{\operatorname{a\alpha_{i}} {\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)}}{2} + \frac{\operatorname{a\alpha_{j}}{\left(T \right)} \frac{d}{d T} \operatorname{ a\alpha_{i}}{\left(T \right)}}{2}\right)}{\operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}}{\left(T \right)}} .. math:: \frac{\partial^2 (a\alpha)_{ij}}{\partial T^2} = - \frac{\sqrt{\operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}} {\left(T \right)}} \left(k_{ij} - 1\right) \left(\frac{\left(\operatorname{ a\alpha_{i}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)} + \operatorname{a\alpha_{j}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{i}} {\left(T \right)}\right)^{2}}{4 \operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}}{\left(T \right)}} - \frac{\left(\operatorname{a\alpha_{i}} {\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)} + \operatorname{a\alpha_{j}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{i}}{\left(T \right)}\right) \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)}}{2 \operatorname{a\alpha_{j}} {\left(T \right)}} - \frac{\left(\operatorname{a\alpha_{i}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)} + \operatorname{a\alpha_{j}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{i}}{\left(T \right)}\right) \frac{d}{d T} \operatorname{a\alpha_{i}}{\left(T \right)}}{2 \operatorname{a\alpha_{i}} {\left(T \right)}} + \frac{\operatorname{a\alpha_{i}}{\left(T \right)} \frac{d^{2}}{d T^{2}} \operatorname{a\alpha_{j}}{\left(T \right)}}{2} + \frac{\operatorname{a\alpha_{j}}{\left(T \right)} \frac{d^{2}}{d T^{2}} \operatorname{a\alpha_{i}}{\left(T \right)}}{2} + \frac{d}{d T} \operatorname{a\alpha_{i}}{\left(T \right)} \frac{d}{d T} \operatorname{a\alpha_{j}}{\left(T \right)}\right)} {\operatorname{a\alpha_{i}}{\left(T \right)} \operatorname{a\alpha_{j}} {\left(T \right)}} The secondary values are as follows: .. math:: \sum_i y_i(a\alpha)_{ij} .. math:: \sum_i y_i \frac{\partial (a\alpha)_{ij}}{\partial T} Parameters ---------- a_alphas : list[float] EOS attractive terms, [J^2/mol^2/Pa] a_alpha_roots : list[float] Square roots of `a_alphas`; provided for speed [J/mol/Pa^0.5] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] T : float Temperature, not used, [K] zs : list[float] Mole fractions of each species kijs : list[list[float]] Constant kijs, [-] Returns ------- a_alpha : float EOS attractive term, [J^2/mol^2/Pa] da_alpha_dT : float Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2 : float Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] a_alpha_j_rows : list[float] EOS attractive term row sums, [J^2/mol^2/Pa] da_alpha_dT_j_rows : list[float] Temperature derivative of EOS attractive term row sums, [J^2/mol^2/Pa/K] Notes ----- Examples -------- >>> kijs = [[0,.083],[0.083,0]] >>> zs = [0.1164203, 0.8835797] >>> a_alphas = [0.2491099357671155, 0.6486495863528039] >>> a_alpha_roots = [i**0.5 for i in a_alphas] >>> da_alpha_dTs = [-0.0005102028006086241, -0.0011131153520304886] >>> d2a_alpha_dT2s = [1.8651128859234162e-06, 3.884331923127011e-06] >>> a_alpha_and_derivatives_quadratic_terms(a_alphas, a_alpha_roots, da_alpha_dTs, d2a_alpha_dT2s, 299.0, zs, kijs) (0.58562139582, -0.001018667672, 3.56669817856e-06, [0.35469988173, 0.61604757237], [-0.000672387374, -0.001064293501]) ''' N = len(a_alphas) a_alpha = da_alpha_dT = d2a_alpha_dT2 = 0.0 if a_alpha_j_rows is None: a_alpha_j_rows = [0.0]*N if da_alpha_dT_j_rows is None: da_alpha_dT_j_rows = [0.0]*N # If d2a_alpha_dT2s were all halved, could save one more multiply for i in range(N): kijs_i = kijs[i] a_alpha_i_root_i = a_alpha_roots[i] # delete these references? a_alphai = a_alphas[i] da_alpha_dT_i = da_alpha_dTs[i] d2a_alpha_dT2_i = d2a_alpha_dT2s[i] workingd1 = workings2 = 0.0 for j in range(i): # TODO: optimize this, compute a_alpha after v0 = a_alpha_i_root_i*a_alpha_roots[j] a_alpha_ijs_ij = (1. - kijs_i[j])*v0 t200 = a_alpha_ijs_ij*zs[i] a_alpha_j_rows[j] += t200 a_alpha_j_rows[i] += zs[j]*a_alpha_ijs_ij t200 *= zs[j] a_alpha += t200 + t200 a_alphaj = a_alphas[j] da_alpha_dT_j = da_alpha_dTs[j] zi_zj = zs[i]*zs[j] x1 = a_alphai*da_alpha_dT_j x2 = a_alphaj*da_alpha_dT_i x1_x2 = x1 + x2 kij_m1 = kijs_i[j] - 1.0 v0_inv = 1.0/v0 v1 = kij_m1*v0_inv da_alpha_dT_ij = x1_x2*v1 # da_alpha_dT_ij = -0.5*x1_x2*v1 # Factor the -0.5 out, apply at end da_alpha_dT_j_rows[j] += zs[i]*da_alpha_dT_ij da_alpha_dT_j_rows[i] += zs[j]*da_alpha_dT_ij da_alpha_dT_ij *= zi_zj x0 = a_alphai*a_alphaj # Technically could use a second list of double a_alphas, probably not used d2a_alpha_dT2_ij = v0_inv*v0_inv*v1*( (x0*( -0.5*(a_alphai*d2a_alpha_dT2s[j] + a_alphaj*d2a_alpha_dT2_i) - da_alpha_dT_i*da_alpha_dT_j) +.25*x1_x2*x1_x2)) d2a_alpha_dT2_ij *= zi_zj workingd1 += da_alpha_dT_ij workings2 += d2a_alpha_dT2_ij # 23 multiplies, 1 divide
None], self.xy_shift, 'bilinear') self.gausswin = gausswin[:, :, :, 0] # get rid of color channels self.gausswin_batch = tf.gather(self.gausswin, self.batch_inds) self.illumination *= tf.to_complex64(self.gausswin_batch) # gaussian window # forward propagation: def propagate_1layer(field, t_i): # field: the input field; # t_i, the 2D object transmittance function at the current (ith) plane, referenced to background index; return tf.ifft2d(tf.fft2d(field) * self.F) * t_i dN = tf.transpose(DT_recon, [2, 0, 1]) # make z the leading dim t = tf.exp(1j * 2 * np.pi * k0 * dN * self.dz) # transmittance function self.propped = tf.scan(propagate_1layer, initializer=self.illumination, elems=t, swap_memory=True) self.propped = tf.transpose(self.propped, [1, 2, 3, 0]) # num ill, x, y, z self.pupil_phase = tf.Variable(np.zeros((self.xy_cap_n, self.xy_cap_n)), dtype=tf.float32, name='pupil_phase_function') pupil = tf.exp(1j * tf.to_complex64(self.pupil_phase)) limiting_aperture = tf.squeeze(tf.to_complex64(self.aperture_mask)) k_2 = self.k_2 * limiting_aperture # to prevent values far away from origin from being too large self.F_to_focus = tf.exp(-1j * 2 * np.pi * k_2 * tf.to_complex64(-self.focus - self.sample_thickness / 2) / (kn + tf.sqrt(kn ** 2 - k_2))) # restrict to the experimental aperture self.F_to_focus *= limiting_aperture self.F_to_focus *= pupil # to account for aberrations common to all self.F_to_focus = self.tf_fftshift2(self.F_to_focus) self.F_to_focus = tf.to_complex64(self.F_to_focus, name='fresnel_kernel_prop_to_focus') self.field = tf.ifft2d(tf.fft2d(self.propped[:, :, :, -1]) * self.F_to_focus[None]) self.forward_pred = tf.abs(self.field) self.forward_pred = tf.reshape(self.forward_pred, [-1, self.xy_cap_n ** 2]) self.data_batch *= tf.reshape(gausswin0, [-1])[None] # since prediction is windowed, also window data self.generate_train_ops() def reconstruct(self): if self.scattering_model == 'multislice': self.reconstruct_with_multislice() else: self.reconstruct_with_born() def reconstruct_with_born(self): # use intensity (no phase) data and try to reconstruct 3D index distribution; if self.optimize_k_directly: # tf variables are k space self.initialize_k_space_domain() else: # tf variables are space domain self.initialize_space_space_domain() # DT_recon is the scattering potiential; then to get RI: self.RI = self.V_to_RI(self.DT_recon) # generate k-spherical caps: self.generate_cap() self.generate_apertures() self.subtract_illumination() # already batched, because derived from xyz_LED_batch: self.k_fft_shift_batch = self.k_fft_shift self.xyz_caps_batch = self.xyz_caps self.pupil_phase = tf.Variable(np.zeros((self.xy_cap_n, self.xy_cap_n)), dtype=tf.float32, name='pupil_phase_function') pupil = tf.exp(1j * tf.to_complex64(self.pupil_phase)) # error between prediction and data: k_space_T = tf.transpose(self.k_space, [1, 0, 2]) forward_fourier = self.tf_gather_nd3(k_space_T, self.xyz_caps_batch) forward_fourier /= tf.complex(0., self.kz_cap[ None]) * 2 # prefactor; it's 1i*kz/pi, but my kz is not in angular frequency forward_fourier = tf.reshape(forward_fourier, # so we can do ifft (-1, len(self.k_illum), # self.batch_size self.xy_cap_n, self.xy_cap_n)) # zero out fourier support outside aperture before fftshift: forward_fourier *= tf.complex(self.aperture_mask[None], 0.) if self.pupil_function: forward_fourier *= pupil self.forward_pred = self.tf_ifftshift2(tf.ifft2d(self.tf_fftshift2(forward_fourier))) # fft phase factor compensation: self.forward_pred *= tf.to_complex64(self.dxy ** 2 * self.dz / self.dxy_sample ** 2) self.forward_pred = tf.reshape(self.forward_pred, # reflatten (-1, self.points_per_cap)) # self.batch_size self.field = tf.identity(self.forward_pred) # to monitor the E field for diagnostic purposes unscattered = self.DC_batch * self.k_fft_shift_batch * tf.exp( 1j * tf.to_complex64(self.illumination_phase_batch[:, None])) if self.zero_out_background_if_outside_aper: # to zero out background from illumination angles that miss the aperture self.miss_aper_mask_batch = tf.to_complex64(self.miss_aper_mask) self.forward_pred_field = self.DC_batch * self.forward_pred + unscattered * self.miss_aper_mask_batch self.forward_pred = tf.abs(self.forward_pred_field) else: self.forward_pred_field = self.DC_batch * self.forward_pred + unscattered self.forward_pred = tf.abs(self.forward_pred_field) self.generate_train_ops() def generate_train_ops(self): self.MSE = tf.reduce_mean((self.data_batch - self.forward_pred) ** 2) self.loss = [self.MSE] # only add these additive regularization terms if the coefficient is not essentially 0: if self.TV_reg_coeff > 1e-12: self.loss.append(self.TV_reg()) if self.positivity_reg_coeff > 1e-12: self.loss.append(self.positivity_reg()) if self.negativity_reg_coeff > 1e-12: self.loss.append(self.negativity_reg()) loss = tf.reduce_sum(self.loss) self.train_op_list = list() if self.optimize_k_directly: # rescale learning rate depending on input size train_op_k = tf.train.AdamOptimizer( learning_rate=self.kspace_lr_scale * self.z_upsamp * self.xy_upsamp).minimize( loss, var_list=[self.DT_recon_r, self.DT_recon_i]) self.train_op_list.append(train_op_k) else: if self.use_deep_image_prior: train_op_k = tf.train.AdamOptimizer(learning_rate=self.DIP_lr).minimize( loss, var_list=tf.trainable_variables(scope='deep_image_prior')) self.train_op_list.append(train_op_k) else: if self.scattering_model == 'born': self.lr = .0002 elif self.scattering_model == 'multislice': self.lr = .00002 else: raise Exception('invalid scattering model') train_op_k = tf.train.AdamOptimizer(learning_rate=self.lr).minimize( loss, var_list=[self.DT_recon_r, self.DT_recon_i]) self.train_op_list.append(train_op_k) if self.pupil_function: train_op_pupil = tf.train.AdamOptimizer(learning_rate=.1).minimize(loss, var_list=[self.pupil_phase]) self.train_op_list.append(train_op_pupil) if self.scattering_model == 'multislice' and self.optimize_focal_shift: train_op_focus = tf.train.AdamOptimizer(learning_rate=.1).minimize(loss, var_list=[self.focus]) self.train_op_list.append(train_op_focus) if self.train_DC: train_op_DC = tf.train.AdamOptimizer(learning_rate=.1).minimize(loss, var_list=[self.DC]) self.train_op_list.append(train_op_DC) self.train_op = tf.group(*self.train_op_list) self.saver = tf.train.Saver() def initialize_space_space_domain(self): if self.use_spatial_patching: recon_shape = self.recon_shape_full else: recon_shape = self.recon_shape if self.use_deep_image_prior: with tf.variable_scope('deep_image_prior'): self.deep_image_prior() else: if self.DT_recon_r_initialize is not None: self.DT_recon_r = tf.Variable(self.DT_recon_r_initialize, dtype=tf.float32, name='recon_real') else: self.DT_recon_r = tf.get_variable(shape=recon_shape, dtype=tf.float32, initializer=tf.random_uniform_initializer(0, 1e-7), name='recon_real') self.DT_recon_i = tf.get_variable(shape=recon_shape, dtype=tf.float32, initializer=tf.random_uniform_initializer(0, 1e-7), name='recon_imag') self.DT_recon = tf.complex(self.DT_recon_r, self.DT_recon_i) self.k_space = self.tf_ifftshift3(tf.fft3d(self.tf_fftshift3(self.DT_recon))) def initialize_k_space_domain(self): if self.use_spatial_patching: recon_shape = self.recon_shape_full else: recon_shape = self.recon_shape self.DT_recon_r = tf.get_variable(shape=recon_shape, dtype=tf.float32, initializer=tf.random_uniform_initializer(0, 1e-7), name='recon_real_k') self.DT_recon_i = tf.get_variable(shape=recon_shape, dtype=tf.float32, initializer=tf.random_uniform_initializer(0, 1e-7), name='recon_imag_k') self.k_space = tf.complex(self.DT_recon_r, self.DT_recon_i) self.DT_recon = self.tf_ifftshift3(tf.ifft3d(self.tf_fftshift3(self.k_space))) def TV_reg(self): # total variation regularization A = self.DT_recon d0 = (A[1:, :-1, :-1] - A[:-1, :-1, :-1]) d1 = (A[:-1, 1:, :-1] - A[:-1, :-1, :-1]) d2 = (A[:-1, :-1, 1:] - A[:-1, :-1, :-1]) return self.TV_reg_coeff * tf.reduce_sum(tf.sqrt(tf.abs(d0) ** 2 + tf.abs(d1) ** 2 + tf.abs(d2) ** 2)) def positivity_reg(self): # the real part of the index doesn't drop below the background index negative_components = tf.minimum(tf.real(self.RI) - self.n_back, 0) return self.positivity_reg_coeff * tf.reduce_sum(negative_components ** 2) def negativity_reg(self): positive_components = tf.maximum(tf.real(self.RI) - self.n_back, 0) return self.negativity_reg_coeff * tf.reduce_sum(positive_components ** 2) def deep_image_prior(self): def build_model(net_input): def downsample_block(net, numfilters=32, kernel_size=3): net = tf.layers.conv3d(net, filters=numfilters, kernel_size=kernel_size, strides=(2, 2, 2), padding='same') net = self.normalizing_layer(net) net = tf.nn.leaky_relu(net) # repeat, but no downsample this time net = tf.layers.conv3d(net, filters=numfilters, kernel_size=3, strides=(1, 1, 1), padding='same') net = self.normalizing_layer(net) net = tf.nn.leaky_relu(net) return net def upsample_block(net, numfilters=32, kernel_size=3): def upsample3D(A, factor): # because tf only has a 2D version ... # A is of shape [1, x, y, z, channels]; # upsample x and y first, then z; if self.DIP_upsample_method == 'nearest': method = tf.image.ResizeMethod.NEAREST_NEIGHBOR elif self.DIP_upsample_method == 'bilinear': method = tf.image.ResizeMethod.BILINEAR A = A[0] # remove batch dim; now x by y by z by channels s = tf.shape(A) # upsample y and z: A = tf.image.resize_images(A, (s[1] * factor, s[2] * factor), method=method) # upsample x: A = tf.transpose(A, (3, 0, 1, 2)) # move channels dim to 0 A = tf.image.resize_images(A, (s[0] * factor, s[1] * factor), method=method) # restore shape: A = tf.transpose(A, (1, 2, 3, 0))[None] return A net = upsample3D(net, 2) # unlike paper, upsample before convs net = tf.layers.conv3d(net, filters=numfilters, kernel_size=kernel_size, strides=(1, 1, 1), padding='same') net = self.normalizing_layer(net) net = tf.nn.leaky_relu(net) net = tf.layers.conv3d(net, filters=numfilters, kernel_size=1, strides=(1, 1, 1), padding='same') # kernel size 1 net = self.normalizing_layer(net) return net def skip_block(net, numfilters=4, kernel_size=1): if numfilters == 0: # no skip connections return None else: net = tf.layers.conv3d(net, filters=numfilters, kernel_size=kernel_size, strides=(1, 1, 1), padding='same') net = self.normalizing_layer(net) net = tf.nn.leaky_relu(net) return net if len(self.numfilters_list) != len(self.numskipfilters_list): # the longer list will be truncated; print('Warning: length of numfilters_list and numskip_filters list not the same!') net = net_input print(net) skip_block_list = list() for numfilters, numskipfilters in zip(self.numfilters_list, self.numskipfilters_list): net = downsample_block(net, numfilters) print(net) skip_block_list.append(skip_block(net, numskipfilters)) for numfilters, skip_block in zip(self.numfilters_list[::-1][:-1], skip_block_list[::-1][:-1]): if skip_block is not None: # first pad skip block in case input doesn't have dims that are powers of 2: skip_shape = tf.shape(skip_block) # 1, x, y, z, numfilt net_shape = tf.shape(net) pad_x = net_shape[1] - skip_shape[1] pad_y = net_shape[2] - skip_shape[2] pad_z = net_shape[3] - skip_shape[3] # handle odd numbers by using ceil: skip_block = tf.pad(skip_block, [[0, 0], [tf.to_int32(pad_x / 2), tf.to_int32(tf.ceil(pad_x / 2))], [tf.to_int32(pad_y / 2), tf.to_int32(tf.ceil(pad_y / 2))], [tf.to_int32(pad_z / 2), tf.to_int32(tf.ceil(pad_z / 2))], [0, 0]]) net = tf.concat([net, skip_block], axis=4) net = upsample_block(net, numfilters) net = tf.nn.leaky_relu(net) print(net) # process the last layer separately, because no activation: net = upsample_block(net, self.numfilters_list[0]) if not self.linear_DIP_output: net = tf.nn.leaky_relu(net) print(net) net = tf.squeeze(net) # remove batch dimension, which is 1 return net input_featmaps = 32 # network input: # smallest power of 2 greater than the current dims (to allow skip connections): if self.DIP_make_pow2: side_kxy = np.int32(2 ** np.ceil(np.log(self.side_kxy) / np.log(2))) side_kz = np.int32(2 ** np.ceil(np.log(self.side_kz) / np.log(2))) else: side_kxy = self.side_kxy side_kz = self.side_kz if self.use_spatial_patching: # if you're using spatial patching, just choose a recon size that's a power of 2 assert self.DIP_make_pow2 is False side_kxy, _, side_kz = self.recon_shape_full self.noisy_input = tf.Variable(np.random.rand(1, side_kxy, side_kxy, side_kz, input_featmaps) * .1, dtype=tf.float32, trainable=False) ULcorner = self.spatial_batch_inds[:, 0] begin = tf.concat([[0], ULcorner, [0, 0]], axis=0) # cropping only x and
# -*- coding: utf-8 -*- """ Tests for functionalities in geofileops.general. """ from pathlib import Path import sys import geopandas as gpd import pandas as pd import pytest import shapely.geometry as sh_geom # Add path so the local geofileops packages are found sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # noqa: E402 import geofileops as gfo from geofileops import fileops from geofileops.util import geoseries_util from geofileops.util.geometry_util import GeometryType from geofileops.util import _io_util from tests import test_helper from tests.test_helper import DEFAULT_SUFFIXES def test_add_column(tmp_path): test_path = test_helper.get_testfile("polygon-parcel", dst_dir=tmp_path) # The area column shouldn't be in the test file yet layerinfo = gfo.get_layerinfo(path=test_path, layer="parcels") assert "AREA" not in layerinfo.columns # Add area column gfo.add_column( test_path, layer="parcels", name="AREA", type="real", expression="ST_area(geom)" ) layerinfo = gfo.get_layerinfo(path=test_path, layer="parcels") assert "AREA" in layerinfo.columns gdf = gfo.read_file(test_path) assert round(gdf["AREA"].astype("float")[0], 1) == round( gdf["OPPERVL"].astype("float")[0], 1 ) # Add perimeter column gfo.add_column( test_path, name="PERIMETER", type=gfo.DataType.REAL, expression="ST_perimeter(geom)", ) layerinfo = gfo.get_layerinfo(path=test_path, layer="parcels") assert "AREA" in layerinfo.columns gdf = gfo.read_file(test_path) assert round(gdf["AREA"].astype("float")[0], 1) == round( gdf["OPPERVL"].astype("float")[0], 1 ) # Add a column of different gdal types gdal_types = [ "Binary", "Date", "DateTime", "Integer", "Integer64", "String", "Time", "Real", ] for type in gdal_types: gfo.add_column(test_path, name=f"column_{type}", type=type) info = gfo.get_layerinfo(test_path) for type in gdal_types: assert f"column_{type}" in info.columns @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_cmp(tmp_path, suffix): src = test_helper.get_testfile("polygon-parcel", suffix=suffix) src2 = test_helper.get_testfile("polygon-invalid", suffix=suffix) # Copy test file to tmpdir dst = tmp_path / f"polygons_parcels_output{suffix}" gfo.copy(src, dst) # Now compare source and dst files assert gfo.cmp(src, dst) is True assert gfo.cmp(src2, dst) is False @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_convert(tmp_path, suffix): src = test_helper.get_testfile("polygon-parcel", suffix=suffix) # Convert dst = tmp_path / f"{src.stem}-output{suffix}" gfo.convert(src, dst) # Now compare source and dst file src_layerinfo = gfo.get_layerinfo(src) dst_layerinfo = gfo.get_layerinfo(dst) assert src_layerinfo.featurecount == dst_layerinfo.featurecount assert len(src_layerinfo.columns) == len(dst_layerinfo.columns) # Convert with reproject dst = tmp_path / f"{src.stem}-output_reproj4326{suffix}" gfo.convert(src, dst, dst_crs=4326, reproject=True) # Now compare source and dst file src_layerinfo = gfo.get_layerinfo(src) dst_layerinfo = gfo.get_layerinfo(dst) assert src_layerinfo.featurecount == dst_layerinfo.featurecount assert src_layerinfo.crs is not None assert src_layerinfo.crs.to_epsg() == 31370 assert dst_layerinfo.crs is not None assert dst_layerinfo.crs.to_epsg() == 4326 # Check if dst file actually seems to contain lat lon coordinates dst_gdf = gfo.read_file(dst) first_geom = dst_gdf.geometry[0] first_poly = ( first_geom if isinstance(first_geom, sh_geom.Polygon) else first_geom.geoms[0] ) assert first_poly.exterior is not None for x, y in first_poly.exterior.coords: assert x < 100 and y < 100 @pytest.mark.parametrize( "testfile, force_geometrytype", [ ("polygon-parcel", GeometryType.POLYGON), ("polygon-parcel", GeometryType.MULTIPOLYGON), ("polygon-parcel", GeometryType.LINESTRING), ("polygon-parcel", GeometryType.MULTILINESTRING), ("polygon-parcel", GeometryType.POINT), ("polygon-parcel", GeometryType.MULTIPOINT), ], ) def test_convert_force_output_geometrytype(tmp_path, testfile, force_geometrytype): # The conversion is done by ogr, and the "test" is rather written to # explore the behaviour of this ogr functionality # Convert testfile and force to force_geometrytype src = test_helper.get_testfile(testfile) dst = tmp_path / f"{src.stem}_to_{force_geometrytype}.gpkg" gfo.convert(src, dst, force_output_geometrytype=force_geometrytype) assert gfo.get_layerinfo(dst).geometrytype == force_geometrytype @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_copy(tmp_path, suffix): src = test_helper.get_testfile("polygon-parcel", suffix=suffix) # Copy to dest file dst = tmp_path / f"{src.stem}-output{suffix}" gfo.copy(src, dst) assert src.exists() assert dst.exists() if suffix == ".shp": assert dst.with_suffix(".shx").exists() # Copy to dest dir dst_dir = tmp_path / "dest_dir" dst_dir.mkdir(parents=True, exist_ok=True) gfo.copy(src, dst_dir) dst = dst_dir / src.name assert src.exists() assert dst.exists() if suffix == ".shp": assert dst.with_suffix(".shx").exists() def test_driver_enum(): # Test ESRIShapefile Driver # Test getting a driver for a suffix geofiletype = gfo.GeofileType(".shp") assert geofiletype == gfo.GeofileType.ESRIShapefile # Test getting a driver for a Path path = Path("/testje/path_naar_gfo.sHp") geofiletype = gfo.GeofileType(path) assert geofiletype == gfo.GeofileType.ESRIShapefile # GPKG Driver # Test getting a driver for a suffix geofiletype = gfo.GeofileType(".gpkg") assert geofiletype == gfo.GeofileType.GPKG # Test getting a driver for a Path path = Path("/testje/path_naar_gfo.gPkG") geofiletype = gfo.GeofileType(path) assert geofiletype == gfo.GeofileType.GPKG # SQLite Driver # Test getting a driver for a suffix geofiletype = gfo.GeofileType(".sqlite") assert geofiletype == gfo.GeofileType.SQLite # Test getting a driver for a Path path = Path("/testje/path_naar_gfo.sQlItE") geofiletype = gfo.GeofileType(path) assert geofiletype == gfo.GeofileType.SQLite @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_drop_column(tmp_path, suffix): test_path = test_helper.get_testfile( "polygon-parcel", dst_dir=tmp_path, suffix=suffix ) original_info = gfo.get_layerinfo(test_path) assert "GEWASGROEP" in original_info.columns gfo.drop_column(test_path, "GEWASGROEP") new_info = gfo.get_layerinfo(test_path) assert len(original_info.columns) == len(new_info.columns) + 1 assert "GEWASGROEP" not in new_info.columns @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_get_crs(suffix): src = test_helper.get_testfile("polygon-parcel", suffix=suffix) crs = gfo.get_crs(src) assert crs.to_epsg() == 31370 @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_get_default_layer(suffix): # Prepare test data + test src = test_helper.get_testfile("polygon-parcel", suffix=suffix) layer = gfo.get_default_layer(src) assert layer == src.stem @pytest.mark.parametrize( "testfile, suffix, layer", [ ("polygon-parcel", ".gpkg", None), ("polygon-parcel", ".shp", None), ("polygon-twolayers", ".gpkg", "parcels"), ], ) def test_get_layerinfo(testfile, suffix, layer): src = test_helper.get_testfile(testfile, suffix=suffix) # Tests layerinfo = gfo.get_layerinfo(src, layer) assert str(layerinfo).startswith("<class 'geofileops.fileops.LayerInfo'>") assert layerinfo.featurecount == 46 if src.suffix == ".shp": assert layerinfo.geometrycolumn == "geometry" assert layerinfo.name == src.stem elif src.suffix == ".gpkg": assert layerinfo.geometrycolumn == "geom" assert layerinfo.name == "parcels" assert layerinfo.geometrytypename == gfo.GeometryType.MULTIPOLYGON.name assert layerinfo.geometrytype == gfo.GeometryType.MULTIPOLYGON assert len(layerinfo.columns) == 11 assert layerinfo.columns["OIDN"].gdal_type == "Integer64" assert layerinfo.total_bounds is not None assert layerinfo.crs is not None assert layerinfo.crs.to_epsg() == 31370 # Some tests for exception cases # Layer specified that doesn't exist with pytest.raises(ValueError, match="Layer not_existing_layer not found in file"): layerinfo = gfo.get_layerinfo(src, "not_existing_layer") # Path specified that doesn't exist with pytest.raises(ValueError, match="File does not exist"): not_existing_path = _io_util.with_stem(src, "not_existing_layer") layerinfo = gfo.get_layerinfo(not_existing_path) # Multiple layers available, but no layer specified if len(gfo.listlayers(src)) > 1: with pytest.raises(ValueError, match="Layer has > 1 layer"): layerinfo = gfo.get_layerinfo(src) @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_get_only_layer_one_layer(suffix): # Test Geopackage with 1 layer src = test_helper.get_testfile("polygon-parcel", suffix=suffix) layer = gfo.get_only_layer(src) if suffix == ".gpkg": assert layer == "parcels" else: assert layer == src.stem def test_get_only_layer_two_layers(): # Test Geopackage with 2 layers src = test_helper.get_testfile("polygon-twolayers") layers = gfo.listlayers(src) assert len(layers) == 2 with pytest.raises(ValueError, match="Layer has > 1 layer"): _ = gfo.get_only_layer(src) def test_is_geofile(): assert gfo.is_geofile(test_helper.get_testfile("polygon-parcel")) assert gfo.is_geofile( test_helper.get_testfile("polygon-parcel").with_suffix(".shp") ) assert gfo.is_geofile("/test/testje.txt") is False @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_listlayers_one_layer(suffix): # Test Geopackage with 1 layer src = test_helper.get_testfile("polygon-parcel", suffix=suffix) layers = gfo.listlayers(src) if suffix == ".gpkg": assert layers[0] == "parcels" else: assert layers[0] == src.stem def test_listlayers_two_layers(): # Test geopackage 2 layers src = test_helper.get_testfile("polygon-twolayers") layers = gfo.listlayers(src) assert "parcels" in layers assert "zones" in layers @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_move(tmp_path, suffix): src = test_helper.get_testfile("polygon-parcel", dst_dir=tmp_path, suffix=suffix) # Test dst = tmp_path / f"{src.stem}-output{suffix}" gfo.move(src, dst) assert src.exists() is False assert dst.exists() if suffix == ".shp": assert dst.with_suffix(".shx").exists() # Test move to dest dir src = test_helper.get_testfile("polygon-parcel", dst_dir=tmp_path, suffix=suffix) dst_dir = tmp_path / "dest_dir" dst_dir.mkdir(parents=True, exist_ok=True) gfo.move(src, dst_dir) dst = dst_dir / src.name assert src.exists() is False assert dst.exists() if suffix == ".shp": assert dst.with_suffix(".shx").exists() def test_update_column(tmp_path): test_path = test_helper.get_testfile("polygon-parcel", dst_dir=tmp_path) # The area column shouldn't be in the test file yet layerinfo = gfo.get_layerinfo(path=test_path, layer="parcels") assert "area" not in layerinfo.columns # Add + update area column gfo.add_column( test_path, layer="parcels", name="AREA", type="real", expression="ST_area(geom)" ) gfo.update_column(test_path, name="AreA", expression="ST_area(geom)") layerinfo = gfo.get_layerinfo(path=test_path, layer="parcels") assert "AREA" in layerinfo.columns gdf = gfo.read_file(test_path) assert round(gdf["AREA"].astype("float")[0], 1) == round( gdf["OPPERVL"].astype("float")[0], 1 ) # Update column for rows where area > 5 gfo.update_column(test_path, name="AreA", expression="-1", where="area > 4000") gdf = gfo.read_file(test_path) gdf_filtered = gdf[gdf["AREA"] == -1] assert len(gdf_filtered) == 20 # Trying to update column that doesn't exist should raise ValueError assert "not_existing column" not in layerinfo.columns with pytest.raises(ValueError, match="Column .* doesn't exist in"): gfo.update_column( test_path, name="not_existing column", expression="ST_area(geom)" ) @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_read_file(suffix): # Prepare test data src = test_helper.get_testfile("polygon-parcel", suffix=suffix) # Test with defaults read_gdf = gfo.read_file(src) assert isinstance(read_gdf, gpd.GeoDataFrame) assert len(read_gdf) == 46 # Test no columns read_gdf = gfo.read_file(src, columns=[]) assert isinstance(read_gdf, gpd.GeoDataFrame) assert len(read_gdf) == 46 # Test specific columns (+ test case insensitivity) columns = ["OIDN", "uidn", "HFDTLT", "lblhfdtlt", "GEWASGROEP", "lengte", "OPPERVL"] read_gdf = gfo.read_file(src, columns=columns) assert len(read_gdf) == 46 assert len(read_gdf.columns) == (len(columns) + 1) # Test no geom read_gdf = gfo.read_file_nogeom(src) assert isinstance(read_gdf, pd.DataFrame) assert len(read_gdf) == 46 # Test ignore_geometry, no columns read_gdf = gfo.read_file_nogeom(src, columns=[]) assert isinstance(read_gdf, pd.DataFrame) assert len(read_gdf) == 46 @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_rename_column(tmp_path, suffix): test_path = test_helper.get_testfile( "polygon-parcel", dst_dir=tmp_path, suffix=suffix ) # Check if input file is ok orig_layerinfo = gfo.get_layerinfo(test_path) assert "OPPERVL" in orig_layerinfo.columns assert "area" not in orig_layerinfo.columns # Rename if test_path.suffix == ".shp": with pytest.raises(ValueError, match="rename_column is not possible for"): gfo.rename_column(test_path, "OPPERVL", "area") else: gfo.rename_column(test_path, "OPPERVL", "area") result_layerinfo = gfo.get_layerinfo(test_path) assert "OPPERVL" not in result_layerinfo.columns assert "area" in result_layerinfo.columns @pytest.mark.parametrize("suffix", DEFAULT_SUFFIXES) def test_rename_layer(tmp_path, suffix): test_path = test_helper.get_testfile( "polygon-parcel", dst_dir=tmp_path, suffix=suffix ) if suffix == ".gpkg": gfo.rename_layer(test_path, layer="parcels", new_layer="parcels_renamed") layernames_renamed = gfo.listlayers(path=test_path) assert layernames_renamed[0]
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import re import os.path as osp def list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'): return sorted([os.path.join(root, f) for root, _, files in os.walk(directory) for f in files if re.match(r'([\w]+\.(?:' + ext + '))', f)]) def list_picture_name(directory, ext='jpg|jpeg|bmp|png|ppm'): return sorted([f for root, _, files in os.walk(directory) for f in files if re.match(r'([\w]+\.(?:' + ext + '))', f)]) class VeRi776(object): dataset_dir = 'VeRi' def __init__(self, root='data', verbose=True, **kwargs): super(VeRi776, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.train_dir = osp.join(self.dataset_dir, 'image_train') self.query_dir = osp.join(self.dataset_dir, 'image_query') self.gallery_dir = osp.join(self.dataset_dir, 'image_test') self.train_gallery_dir = osp.join(self.dataset_dir, 'gallery_from_train_eq3') self.train_query_dir = osp.join(self.dataset_dir, 'query_from_train_v2') self._check_before_run() train, num_train_pids, num_train_imgs = self._process_dir(self.train_dir, relabel=True) query, num_query_pids, num_query_imgs = self._process_dir(self.query_dir, relabel=False) gallery, num_gallery_pids, num_gallery_imgs = self._process_dir(self.gallery_dir, relabel=False) train_query, num_train_query_pids, num_train_query_imgs = self._process_dir(self.train_query_dir, relabel=False) train_gallery, num_train_gallery_pids, num_train_gallery_imgs = self._process_dir(self.train_gallery_dir, relabel=False) num_total_pids = num_train_pids + num_query_pids num_total_imgs = num_train_imgs + num_query_imgs + num_gallery_imgs if verbose: print("=> VeRi776 loaded") print("Dataset statistics:") print(" ------------------------------") print(" subset | # ids | # images") print(" ------------------------------") print(" train | {:5d} | {:8d}".format(num_train_pids, num_train_imgs)) print(" query | {:5d} | {:8d}".format(num_query_pids, num_query_imgs)) print(" gallery | {:5d} | {:8d}".format(num_gallery_pids, num_gallery_imgs)) print(" train_query | {:5d} | {:8d}".format(num_train_query_pids, num_train_query_imgs)) print(" train_gallery | {:5d} | {:8d}".format(num_train_gallery_pids, num_train_gallery_imgs)) print(" ------------------------------") print(" total | {:5d} | {:8d}".format(num_total_pids, num_total_imgs)) print(" ------------------------------") self.train = train self.query = query self.gallery = gallery self.train_query = train_query self.train_gallery = train_gallery self.num_train_pids = num_train_pids self.num_query_pids = num_query_pids self.num_gallery_pids = num_gallery_pids def _check_before_run(self): """Check if all files are available before going deeper""" if not osp.exists(self.dataset_dir): raise RuntimeError("'{}' is not available".format(self.dataset_dir)) if not osp.exists(self.train_dir): raise RuntimeError("'{}' is not available".format(self.train_dir)) if not osp.exists(self.query_dir): raise RuntimeError("'{}' is not available".format(self.query_dir)) if not osp.exists(self.gallery_dir): raise RuntimeError("'{}' is not available".format(self.gallery_dir)) def _process_dir(self, dir_path, relabel=False): # img_paths = glob.glob(osp.join(dir_path, '*.jpg')) img_paths = list_pictures(dir_path) pattern = re.compile(r'([-\d]+)_c([\d]+)') pid_container = set() for img_path in img_paths: pid, _ = map(int, pattern.search(img_path).groups()) if pid == -1: continue # junk images are just ignored pid_container.add(pid) pid2label = {pid:label for label, pid in enumerate(pid_container)} dataset = [] for img_path in img_paths: pid, camid = map(int, pattern.search(img_path).groups()) if pid == -1: continue # junk images are just ignored assert 1 <= pid <= 776 # pid == 0 means background assert 1 <= camid <= 20 # camid -= 1 # index starts from 0 if relabel: pid = pid2label[pid] dataset.append((img_path, pid, camid)) num_pids = len(pid_container) num_imgs = len(dataset) return dataset, num_pids, num_imgs class VeRi776Plt(object): dataset_dir = 'VeRi-plate' def __init__(self, root='data', verbose=True, **kwargs): super(VeRi776Plt, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.train_dir = osp.join(self.dataset_dir, 'plate_train') self.query_dir = osp.join(self.dataset_dir, 'plate_query') self.gallery_dir = osp.join(self.dataset_dir, 'plate_test') self._check_before_run() train, num_train_pids, num_train_imgs = self._process_dir(self.train_dir, relabel=True) query, num_query_pids, num_query_imgs = self._process_dir(self.query_dir, relabel=False) gallery, num_gallery_pids, num_gallery_imgs = self._process_dir(self.gallery_dir, relabel=False) num_total_pids = num_train_pids + num_query_pids num_total_imgs = num_train_imgs + num_query_imgs + num_gallery_imgs if verbose: print("=> VeRi776 loaded") print("Dataset statistics:") print(" ------------------------------") print(" subset | # ids | # images") print(" ------------------------------") print(" train | {:5d} | {:8d}".format(num_train_pids, num_train_imgs)) print(" query | {:5d} | {:8d}".format(num_query_pids, num_query_imgs)) print(" gallery | {:5d} | {:8d}".format(num_gallery_pids, num_gallery_imgs)) print(" ------------------------------") print(" total | {:5d} | {:8d}".format(num_total_pids, num_total_imgs)) print(" ------------------------------") self.train = train self.query = query self.gallery = gallery self.num_train_pids = num_train_pids self.num_query_pids = num_query_pids self.num_gallery_pids = num_gallery_pids def _check_before_run(self): """Check if all files are available before going deeper""" if not osp.exists(self.dataset_dir): raise RuntimeError("'{}' is not available".format(self.dataset_dir)) if not osp.exists(self.train_dir): raise RuntimeError("'{}' is not available".format(self.train_dir)) if not osp.exists(self.query_dir): raise RuntimeError("'{}' is not available".format(self.query_dir)) if not osp.exists(self.gallery_dir): raise RuntimeError("'{}' is not available".format(self.gallery_dir)) def _process_dir(self, dir_path, relabel=False): # img_paths = glob.glob(osp.join(dir_path, '*.jpg')) img_paths = list_pictures(dir_path) pattern = re.compile(r'([-\d]+)_c([\d]+)') pid_container = set() for img_path in img_paths: pid, _ = map(int, pattern.search(img_path).groups()) if pid == -1: continue # junk images are just ignored pid_container.add(pid) pid2label = {pid:label for label, pid in enumerate(pid_container)} dataset = [] for img_path in img_paths: pid, camid = map(int, pattern.search(img_path).groups()) if pid == -1: continue # junk images are just ignored assert 1 <= pid <= 776 # pid == 0 means background assert 1 <= camid <= 20 # camid -= 1 # index starts from 0 if relabel: pid = pid2label[pid] dataset.append((img_path, pid, camid)) num_pids = len(pid_container) num_imgs = len(dataset) return dataset, num_pids, num_imgs class VeRi776WithGroupLabel(object): dataset_dir = 'VeRi' def __init__(self, root='data', verbose=True, **kwargs): super(VeRi776WithGroupLabel, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.train_dir = osp.join(self.dataset_dir, 'image_train') self.query_dir = osp.join(self.dataset_dir, 'image_query') self.gallery_dir = osp.join(self.dataset_dir, 'image_test') self.train_gallery_dir = osp.join(self.dataset_dir, 'gallery_from_train_eq3') self.train_query_dir = osp.join(self.dataset_dir, 'query_from_train_v2') self.name_query_with_view = osp.join(self.dataset_dir, 'name_query_with_view.txt') self.name_test_with_view = osp.join(self.dataset_dir, 'name_test_with_view.txt') self.name_train_with_view = osp.join(self.dataset_dir, 'name_train_with_view.txt') self._check_before_run() # train, num_train_pids, num_train_imgs = \ # self._process_dir(self.train_dir, relabel=True, group_label=True, data_type='train') # query, num_query_pids, num_query_imgs = \ # self._process_dir(self.query_dir, relabel=False, group_label=True, data_type='query') # gallery, num_gallery_pids, num_gallery_imgs = \ # self._process_dir(self.gallery_dir, relabel=False, group_label=True, data_type='gallery') train, num_train_pids, num_train_imgs = \ self._process_dir(self.train_dir, relabel=True, group_label=False, data_type='train') query, num_query_pids, num_query_imgs = \ self._process_dir(self.query_dir, relabel=False, group_label=False, data_type='query') gallery, num_gallery_pids, num_gallery_imgs = \ self._process_dir(self.gallery_dir, relabel=False, group_label=False, data_type='gallery') train_query, num_train_query_pids, num_train_query_imgs = \ self._process_dir(self.train_query_dir, relabel=False) train_gallery, num_train_gallery_pids, num_train_gallery_imgs = \ self._process_dir(self.train_gallery_dir, relabel=False) num_total_pids = num_train_pids + num_query_pids num_total_imgs = num_train_imgs + num_query_imgs + num_gallery_imgs if verbose: print("=> VeRi776 loaded") print("Dataset statistics:") print(" ------------------------------") print(" subset | # ids | # images") print(" ------------------------------") print(" train | {:5d} | {:8d}".format(num_train_pids, num_train_imgs)) print(" query | {:5d} | {:8d}".format(num_query_pids, num_query_imgs)) print(" gallery | {:5d} | {:8d}".format(num_gallery_pids, num_gallery_imgs)) print(" train_query | {:5d} | {:8d}".format(num_train_query_pids, num_train_query_imgs)) print(" train_gallery | {:5d} | {:8d}".format(num_train_gallery_pids, num_train_gallery_imgs)) print(" ------------------------------") print(" total | {:5d} | {:8d}".format(num_total_pids, num_total_imgs)) print(" ------------------------------") self.train = train self.query = query self.gallery = gallery self.train_query = train_query self.train_gallery = train_gallery self.num_train_pids = num_train_pids self.num_query_pids = num_query_pids self.num_gallery_pids = num_gallery_pids def _check_before_run(self): """Check if all files are available before going deeper""" if not osp.exists(self.dataset_dir): raise RuntimeError("'{}' is not available".format(self.dataset_dir)) if not osp.exists(self.train_dir): raise RuntimeError("'{}' is not available".format(self.train_dir)) if not osp.exists(self.query_dir): raise RuntimeError("'{}' is not available".format(self.query_dir)) if not osp.exists(self.gallery_dir): raise RuntimeError("'{}' is not available".format(self.gallery_dir)) def _process_dir(self, dir_path, relabel=False, group_label=False, data_type=None): # img_paths = glob.glob(osp.join(dir_path, '*.jpg')) # pattern = re.compile(r'([-\d]+)_c([\d]+)') pid_container = set() img_id = 0 gopid = 0 dataset = {} if group_label: if data_type == 'train': name_txt = self.name_train_with_view elif data_type == 'query': name_txt = self.name_query_with_view else: name_txt = self.name_test_with_view f_txt = open(name_txt) img_paths = f_txt.readlines() f_txt.close() pattern = re.compile('c([\d]+)_([\d]+)_([\d]+)_([\d]+)_([\d]+)_([\d]+)_([\d]+)') for img_path in img_paths: img_path = img_path.split() img_path = [im_pth.strip() for im_pth in img_path] _, _, _, _, pid, _, _ = map(int, pattern.search(img_path[1]).groups()) if pid == -1: continue # junk images are just ignored pid_container.add(pid) pid2label = {pid: label for label, pid in enumerate(pid_container)} for img_path in img_paths: img_path = img_path.split() img_path = [im_pth.strip() for im_pth in img_path] camid, gopid, _, _, pid, _, _ = map(int, pattern.search(img_path[1]).groups()) if pid == -1: continue # junk images are just ignored assert 1 <= pid <= 776 # pid == 0 means background assert 1 <= camid <= 20 if relabel: pid = pid2label[pid] img_path = osp.join(dir_path, img_path[0]) dataset[img_id] = [img_id, pid, camid, gopid, img_path] img_id += 1 else: img_paths = list_pictures(dir_path) pattern = re.compile('([\d]+)_c([\d]+)') for img_path in img_paths: pid, _ = map(int, pattern.search(img_path).groups()) if pid == -1: continue # junk images are just ignored pid_container.add(pid) pid2label = {pid: label for label, pid in enumerate(pid_container)} for img_path in img_paths: pid, camid = map(int, pattern.search(img_path).groups()) if pid == -1: continue # junk images are just ignored assert 1 <= pid <= 776 # pid == 0 means background assert 1 <= camid <= 20 # camid -= 1 # index starts from 0 if relabel: pid = pid2label[pid] dataset[img_id] = [img_id, pid, camid, gopid, img_path] img_id += 1 num_pids = len(pid_container) num_imgs = len(dataset) return dataset, num_pids, num_imgs def _update_group_label(self, group_label): for gl in group_label: self.train[gl[0]][3] = gl[1] class VeRi776WithColorLBP(object): dataset_dir = 'VeRi' def __init__(self, root='data', verbose=True, **kwargs): super(VeRi776WithColorLBP, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.train_dir = osp.join(self.dataset_dir, 'image_train') self.query_dir = osp.join(self.dataset_dir, 'image_query') self.gallery_dir = osp.join(self.dataset_dir, 'image_test') self.train_gallery_dir = osp.join(self.dataset_dir, 'gallery_from_train_eq3') self.train_query_dir = osp.join(self.dataset_dir, 'query_from_train_v2') self.train_rgb_color_lbp_dir = osp.join(self.dataset_dir, 'image_train_re_arrange') self.test_rgb_color_lbp_dir = osp.join(self.dataset_dir, 'image_test_re_arrange') self.name_test_new2origin = osp.join(self.dataset_dir, 'name_test_new2origin.txt') self.name_train_new2origin = osp.join(self.dataset_dir, 'name_train_new2origin.txt') self._check_before_run()
""" Base class for plugins - frameworks or systems that may: * add code at startup * allow hooks to be called and base class for plugins that: * serve static content * serve templated html * have some configuration at startup """ import os.path import sys import imp import pkg_resources pkg_resources.require( 'MarkupSafe' ) pkg_resources.require( 'Mako' ) import mako from galaxy import util from galaxy.util import odict from galaxy.util import bunch import logging log = logging.getLogger( __name__ ) # ============================================================================= exceptions class PluginManagerException( Exception ): """Base exception for plugin frameworks. """ pass class PluginManagerConfigException( PluginManagerException ): """Exception for plugin framework configuration errors. """ pass # ============================================================================= base class PluginManager( object ): """ Plugins represents an section of code that is not tracked in the Galaxy repository, allowing the addition of custom code to a Galaxy installation without changing the code base. A PluginManager discovers and manages these plugins. This is an non-abstract class but its usefulness is limited and is meant to be inherited. """ def __init__( self, app, directories_setting=None, skip_bad_plugins=True, **kwargs ): """ Set up the manager and load all plugins. :type app: UniverseApplication :param app: the application (and its configuration) using this manager :type directories_setting: string (default: None) :param directories_setting: the filesystem path (or paths) to search for plugins. Can be CSV string of paths. Will be treated as absolute if a path starts with '/', relative otherwise. :type skip_bad_plugins: boolean (default: True) :param skip_bad_plugins: whether to skip plugins that cause exceptions when loaded or to raise that exception """ #log.debug( 'PluginManager.init: %s, %s', directories_setting, kwargs ) self.directories = [] self.skip_bad_plugins = skip_bad_plugins self.plugins = odict.odict() self.directories = self.parse_directories_setting( app.config.root, directories_setting ) #log.debug( '\t directories: %s', self.directories ) self.load_configuration() self.load_plugins() def parse_directories_setting( self, galaxy_root, directories_setting ): """ Parse the ``directories_setting`` into a list of relative or absolute filesystem paths that will be searched to discover plugins. :type galaxy_root: string :param galaxy_root: the root path of this galaxy installation :type directories_setting: string (default: None) :param directories_setting: the filesystem path (or paths) to search for plugins. Can be CSV string of paths. Will be treated as absolute if a path starts with '/', relative otherwise. :rtype: list of strings :returns: list of filesystem paths """ directories = [] if not directories_setting: return directories for directory in util.listify( directories_setting ): directory = directory.strip() if not directory.startswith( '/' ): directory = os.path.join( galaxy_root, directory ) if not os.path.exists( directory ): log.warn( '%s, directory not found: %s', self, directory ) continue directories.append( directory ) return directories def load_configuration( self ): """ Override to load some framework/plugin specifc configuration. """ # Abstract method return True def load_plugins( self ): """ Search ``self.directories`` for potential plugins, load them, and cache in ``self.plugins``. :rtype: odict :returns: ``self.plugins`` """ for plugin_path in self.find_plugins(): try: plugin = self.load_plugin( plugin_path ) if not plugin: log.warn( '%s, plugin load failed or disabled: %s. Skipping...', self, plugin_path ) #NOTE: prevent silent, implicit overwrite here (two plugins in two diff directories) #TODO: overwriting may be desired elif plugin.name in self.plugins: log.warn( '%s, plugin with name already exists: %s. Skipping...', self, plugin.name ) else: self.plugins[ plugin.name ] = plugin log.info( '%s, loaded plugin: %s', self, plugin.name ) except Exception, exc: if not self.skip_bad_plugins: raise log.exception( 'Plugin loading raised exception: %s. Skipping...', plugin_path ) return self.plugins def find_plugins( self ): """ Return the directory paths of plugins within ``self.directories``. Paths are considered a plugin path if they pass ``self.is_plugin``. :rtype: string generator :returns: paths of valid plugins """ # due to the ordering of listdir, there is an implicit plugin loading order here # could instead explicitly list on/off in master config file for directory in self.directories: for plugin_dir in sorted( os.listdir( directory ) ): plugin_path = os.path.join( directory, plugin_dir ) if self.is_plugin( plugin_path ): yield plugin_path def is_plugin( self, plugin_path ): """ Determines whether the given filesystem path contains a plugin. In this base class, all sub-directories are considered plugins. :type plugin_path: string :param plugin_path: relative or absolute filesystem path to the potential plugin :rtype: bool :returns: True if the path contains a plugin """ if not os.path.isdir( plugin_path ): return False return True def load_plugin( self, plugin_path ): """ Create, load, and/or initialize the plugin and return it. Plugin bunches are decorated with: * name : the plugin name * path : the plugin path :type plugin_path: string :param plugin_path: relative or absolute filesystem path to the plugin :rtype: ``util.bunch.Bunch`` :returns: the loaded plugin object """ plugin = bunch.Bunch( #TODO: need a better way to define plugin names # pro: filesystem name ensures uniqueness # con: rel. inflexible name = os.path.split( plugin_path )[1], path = plugin_path ) return plugin # ============================================================================= plugin managers using hooks class HookPluginManager( PluginManager ): """ A hook plugin is a directory containing python modules or packages that: * allow creating, including, and running custom code at specific 'hook' points/events * are not tracked in the Galaxy repository and allow adding custom code to a Galaxy installation A HookPluginManager imports the plugin code needed and calls the plugin's hook functions at the specified time. """ #: the python file that will be imported - hook functions should be contained here loading_point_filename = 'plugin.py' hook_fn_prefix = 'hook_' def is_plugin( self, plugin_path ): """ Determines whether the given filesystem path contains a hookable plugin. All sub-directories that contain ``loading_point_filename`` are considered plugins. :type plugin_path: string :param plugin_path: relative or absolute filesystem path to the potential plugin :rtype: bool :returns: True if the path contains a plugin """ if not super( HookPluginManager, self ).is_plugin( plugin_path ): return False #TODO: possibly switch to <plugin.name>.py or __init__.py if self.loading_point_filename not in os.listdir( plugin_path ): return False return True def load_plugin( self, plugin_path ): """ Import the plugin ``loading_point_filename`` and attach to the plugin bunch. Plugin bunches are decorated with: * name : the plugin name * path : the plugin path * module : the plugin code :type plugin_path: string :param plugin_path: relative or absolute filesystem path to the plugin :rtype: ``util.bunch.Bunch`` :returns: the loaded plugin object """ plugin = super( HookPluginManager, self ).load_plugin( plugin_path ) loading_point_name = self.loading_point_filename[:-3] plugin[ 'module' ] = self.import_plugin_module( loading_point_name, plugin ) return plugin def import_plugin_module( self, loading_point_name, plugin, import_as=None ): """ Import the plugin code and cache the module in the plugin object. :type loading_point_name: string :param loading_point_name: name of the python file to import (w/o extension) :type plugin: ``util.bunch.Bunch`` :param plugin: the plugin containing the template to render :type import_as: string :param import_as: namespace to use for imported module This will be prepended with the ``__name__`` of this file. Defaults to ``plugin.name`` :rtype: ``util.bunch.Bunch`` :returns: the loaded plugin object """ # add this name to import_as (w/ default to plugin.name) to prevent namespace pollution in sys.modules import_as = '%s.%s' %( __name__, ( import_as or plugin.name ) ) module_file, pathname, description = imp.find_module( loading_point_name, [ plugin.path ] ) try: #TODO: hate this hack but only way to get package imports inside the plugin to work? sys.path.append( plugin.path ) # sys.modules will now have import_as in its list module = imp.load_module( import_as, module_file, pathname, description ) finally: module_file.close() if plugin.path in sys.path: sys.path.remove( plugin.path ) return module def run_hook( self, hook_name, *args, **kwargs ): """ Search all plugins for a function named ``hook_fn_prefix`` + ``hook_name`` and run it passing in args and kwargs. Return values from each hook are returned in a dictionary keyed with the plugin names. :type hook_name: string :param hook_name: name (suffix) of the hook to run :rtype: dictionary :returns: where keys are plugin.names and values return values from the hooks """ #TODO: is hook prefix necessary? #TODO: could be made more efficient if cached by hook_name in the manager on load_plugin # (low maint. overhead since no dynamic loading/unloading of plugins) hook_fn_name = ''.join([ self.hook_fn_prefix, hook_name ]) returned = {} for plugin_name, plugin in self.plugins.items(): hook_fn = getattr( plugin.module, hook_fn_name, None ) if hook_fn and hasattr(
<filename>sqlitehouse.py # -*- coding: utf-8 -*- import logging import random import sqlite3 from contextlib import closing logger = logging.getLogger(__name__) def clean(line): """Strip a string of non-alphanumerics (except underscores). Can use to clean strings before using them in a database query. Args: line (str): String to clean. Returns: line (str): A string safe to use in a database query. Examples: >>> clean("Robert'); DROP TABLE Students;") RobertDROPTABLEStudents """ return "".join(char for char in line if (char.isalnum() or "_" == char)) class TableColumn(object): """Represents a column in a database table. Args: name (str): Name of the column. datatype (str): Data type the column contains. Kwargs: primary_key (bool, optional): Specifies if the column is the primary key or not. Defaults to False. allow_null (bool, optional): Whether fields may have null values or not. Defaults to True. unique (bool, optional): Specifies if column fields must be unique. Defaults to False. """ def __init__(self, name, datatype, **constraints): self.name = clean(name) self.datatype = datatype self.primary_key = constraints.get("primary_key", False) self.allow_null = constraints.get("allow_null", True) self.unique = constraints.get("unique", False) class Database(object): """For reading and writing records in a SQLite database. Args: dbFile (str): The filepath of the database. """ def __init__(self, db_file): self.db = db_file def _get_conditions(self, conditions, delimiter=","): """Returns a WHERE clause according to given conditions. Args: conditions (dict): Conditions you want to filter the search by: {"column1": "value1,value2", "column2": "value3"} Multiple conditions under a single column are separated with the delimiter. delimiter (str, optional): Delimiter of column values for conditions. Default is a comma. Returns: clause (tuple): The string statement and the substitutes for ? placeholders. Examples: >>> db._get_conditions({"colour": "green", "food": "eggs,ham"}) ('WHERE (colour=?) AND (food=? OR food=?)', ["green", "eggs", "ham"]) """ clause = "WHERE (" clause_list = [clause,] substitutes = [] cat_count = 1 column_count = 1 ## TODO: Add ability to specify comparison operator (e.g. =, <, LIKE, etc.) for con in conditions: if 1 < column_count: clause_list.append(" AND (") sub_count = 1 subconditions = conditions[con].split(delimiter) for sub in subconditions: if 1 < sub_count: clause_list.append(" OR ") clause_list.append(f"{clean(con)}=?") substitutes.append(sub) sub_count += 2 clause_list.append(")") column_count += 2 cat_count = 1 clause = "".join(clause_list) return (clause, substitutes) def execute(self, statement, substitutes=None): """Executes a statement. Args: statement (str): Statement to execute. substitutes (list): Values to substitute placeholders in statement. """ connection = sqlite3.connect(self.db) with closing(connection) as connection: c = connection.cursor() if substitutes: c.execute(statement, substitutes) else: c.execute(statement) connection.commit() def create_table(self, name, columns): """Creates a table. Args: name (str): Name of table. columns (list): List of TableColumns. """ connection = sqlite3.connect(self.db) name = clean(name) statement = [f"CREATE TABLE IF NOT EXISTS \"{name}\"(",] with closing(connection) as connection: i = 1 for col in columns: pk = " PRIMARY KEY" if col.primary_key else "" null = " NOT NULL" if not col.allow_null else "" unique = " UNIQUE" if col.unique else "" if len(columns) > i: column = f"\"{col.name}\" {col.datatype}{pk}{null}{unique}," else: column = f"\"{col.name}\" {col.datatype}{pk}{null}{unique}" statement.append(column) i += 1 statement.append(");") statement = "\n".join(statement) connection.execute(statement) def rename_table(self, table, new_name): """Renames a table.""" table = clean(table) new_name = clean(new_name) connection = sqlite3.connect(self.db) with closing(connection) as connection: connection.execute(f"ALTER TABLE \"{table}\" RENAME TO \"{new_name}\"") def add_column(self, table, column): """Adds a column to a table.""" connection = sqlite3.connect(self.db) table = clean(table) with closing(connection) as connection: null = " NOT NULL" if not col.allow_null else "" unique = " UNIQUE" if col.unique else "" col = f"\"{column.name}\" {column.datatype}{null}{unique}" connection.execute(f"ALTER TABLE \"{table}\" ADD COLUMN \"{col}\"") def drop_table(self, table): """Deletes a table.""" table = clean(table) connection = sqlite3.connect(self.db) with closing(connection) as connection: connection.execute(f"DROP TABLE IF EXISTS \"{table}\"") def insert(self, table, values, columns=None): """Inserts records into the table. Args: table (str): Name of table. values (list): List of tuples containing the values to insert. Each tuple represents one row. columns (list, optional): List of column names corresponding to the values being inserted. """ table = clean(table) if columns: columns = [clean(h) for h in columns] connection = sqlite3.connect(self.db) with closing(connection) as connection: c = connection.cursor() cols = "" if columns: cols = ",".join(columns) cols = f"({cols})" for row in values: placeholders = ",".join(["?" for field in row]) statement = f"INSERT INTO \"{table}\"{cols} VALUES({placeholders})" c.execute(statement, row) connection.commit() def update(self, table, new_values, conditions=None): """Updates records on a table. Args: table (str): Name of the table. new_values (dict): The new values in each column. e.g. {"column1": "new1", "column2": "new2"} conditions (dict, optional): Categories to filter the update by: {"column of categories 1": "category1,category2", "column of category 2": "category3"} Multiple categories under a single column are separated with a comma. """ table = clean(table) connection = sqlite3.connect(self.db) with closing(connection) as connection: c = connection.cursor() to_update = [] substitutes = [] for column in new_values: to_update.append(f"\"{column}\" = ?") substitutes.append(new_values[column]) to_update = ", ".join(to_update) where = "" if conditions: where, where_subs = self._get_conditions(conditions) substitutes = [*substitutes, *where_subs] statement = f"UPDATE \"{table}\" SET {to_update} {where}" print(statement, substitutes) c.execute(statement, substitutes) connection.commit() def delete(self, table, conditions=None): """Deletes records from a table.""" table = clean(table) connection = sqlite3.connect(self.db) with closing(connection) as connection: c = connection.cursor() if conditions: where, substitutes = self._get_conditions(conditions) statement = f"DELETE FROM \"{table}\" {conditions}" c.execute(statement, substitutes) else: c.execute(f"DELETE FROM \"{table}\"") connection.commit() def create_index(self, name, table, columns, unique=False): """Create an index for a table. Args: name (str): Name of index. table (str): Table to index. columns (list): List of columns to index. unique (bool, optional): Specify if index is unique or not. """ name = clean(name) table = clean(table) connection = sqlite3.connect(self.db) with closing(connection) as connection: cols = ",".join([clean(c) for c in columns]) u = "UNIQUE " if unique else "" statement = f"CREATE {u}INDEX IF NOT EXISTS {name} ON \"{table}\"({cols})" connection.execute(statement) def drop_index(self, name): """Deletes an index.""" name = clean(name) connection = sqlite3.connect(self.db) with closing(connection) as connection: connection.execute(f"DROP INDEX IF EXISTS \"{name}\"") def get_column(self, column, table, maximum=None): """Gets fields under a column. Args: column (str): Name of column. table (str): Name of table. maximum (int, optional): Maximum amount of fields to fetch. Returns: fields (list): List of fields under column. """ fields = [] table = clean(table) connection = sqlite3.connect(self.db) with closing(connection) as connection: connection.row_factory = lambda cursor, row: row[0] c = connection.cursor() if maximum: c.execute(f"SELECT \"{column}\" FROM \"{table}\" LIMIT ?", [maximum]) else: c.execute(f"SELECT \"{column}\" FROM \"{table}\"") fields = c.fetchall() return fields def get_field(self, field_id, column, table): """Gets the field under the specified column by its primary key value. Args: field_id (int, str): Unique ID of line the field is in. column (str): Column of the field to fetch. table (str): Name of table to look into. Returns: The desired field, or None if the lookup failed. Raises: TypeError: If field_id doesn't exist in the table. Examples: >>> get_field(123, "firstname", "kings") Adgar """ column = clean(column) table = clean(table) field = None connection = sqlite3.connect(self.db) with closing(connection) as connection: c = connection.cursor() statement = f"SELECT \"{column}\" FROM \"{table}\" WHERE id=?" logger.debug(statement) c.execute(statement, [field_id]) try: field = c.fetchone()[0] except TypeError: logger.exception(f"ID '{field_id}' was not in table '{table}'") return field def get_ids(self, table, column_id="id", conditions=None, delimiter=","): """Gets the IDs that fit within the specified conditions. Gets all IDs if conditions is None. Args: table (str): Name of table to look into. column_id (str, optional): Name of the id column. Default is "id". conditions (dict, optional): Categories you want to filter the line by: {"column of categories 1": "category1,category2", "column of category 2": "category3"} Multiple categories under a single column are separated with a comma. delimiter (str, optional): Delimiter of column values for conditions. Default is a comma. Returns: ids (list): List of IDs that match the categories. Raises: OperationalError: If table or column doesn't exist. TypeError: If category is neither None nor a dictionary. Examples: >>> get_ids({"type": "greeting"}) [1, 2, 3, 5, 9, 15] # Any row that has the type "greeting". >>> get_ids({"type": "nickname,quip", "by": "Varric"}) #
<filename>lib/custom_operations/custom_check.py # -------------------------------------------------------- # PyTorch Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by <NAME>, based on code from <NAME> # -------------------------------------------------------- import os import sys import numpy as np import time import cv2 import torch from custom_operations.custom_show import vis_text_beautiful, vis_detections_beautiful, vis_count_text class CustomChecker: def __init__(self, regional_file_path): self.smooth = False self.identify = True self.all_cls_dets_time_seq = [] self.dist_th = 500 self.frame_rate = 24 self.active_limit = self.frame_rate / 3 self.center_keep_time = self.frame_rate self.path_keep_time = self.frame_rate self.path_speed_dict = {} self.idf_center_list = [[[0, 0, 0, 0, 0.0], ]] # idf, x_c, y_c, keep_time, speed self.line_point_list = self.get_regional(regional_file_path) # 车流 self.now_max_label = 0 self.car_count_list = [] self.max_count_per_count_time = 0 self.count_time = 60 # 车流量单位 60s self.count_num_limit = self.count_time * self.frame_rate def count_check(self, im2show): self.car_count_list.append(self.now_max_label) if len(self.car_count_list) > self.count_num_limit: del self.car_count_list[0] count_per_count_time = self.car_count_list[-1] - self.car_count_list[0] if count_per_count_time > self.max_count_per_count_time: self.max_count_per_count_time = count_per_count_time im2show = vis_count_text(im2show, [self.now_max_label, count_per_count_time, self.max_count_per_count_time]) return im2show def thresh_check(self, all_cls_dets, thresh=0.90): for j in range(len(all_cls_dets)): cls_dets = all_cls_dets[j] if cls_dets.any(): # no value check keep_idx = [idx for idx, det in enumerate(cls_dets) if det[-1]>thresh] cls_dets = cls_dets[keep_idx] all_cls_dets[j] = cls_dets return all_cls_dets def regional_check(self, im2show, all_cls_dets): # line_point_list = self.line_point_list im2show = self.regional_show(im2show) for j in range(len(all_cls_dets)): cls_dets = all_cls_dets[j] if cls_dets.any(): # no value check cls_dets = self.get_in_regional(cls_dets) all_cls_dets[j] = cls_dets return im2show, all_cls_dets def identify_check(self, im2show, all_cls_dets): point_size = 1 color1 = (0, 0, 255) # BGR color2 = (0, 255, 0) # BGR # color3 = (0, 0, 255) # BGR thickness = 2 # 可以为 0 、4、8 # f_s = cv2.FONT_HERSHEY_SIMPLEX # 文字字体 # t_s = 0.6 # 文字大小 # t_t = 2 # 文字线条粗细 all_cls_labels = [] all_cls_speeds = [] # get center by class for j in range(len(all_cls_dets)): # plot idf center cls_idf_center = self.idf_center_list[j] for idf_center in cls_idf_center: idf, xx, yy, count, speed = idf_center if idf and count: cv2.circle(im2show, (xx, yy), 3, color2, thickness) # print('cls:', j) cls_dets = all_cls_dets[j] # print(cls_dets) if cls_dets.any(): # no value check cls_dets_center = self.get_rec_center(cls_dets) # plot det center for dets_center in cls_dets_center: cv2.circle(im2show, dets_center, point_size, color1, thickness) else: cls_dets_center = [] # identify label labels, speeds = self.identify_label(j, cls_dets_center) all_cls_labels.append(labels) all_cls_speeds.append(speeds) # move path save self.path_save() # plot path line im2show = self.path_show(im2show) pass # plot labels # for j in range(len(all_cls_dets)): # cls_labels = all_cls_labels[j] # for i, label in enumerate(cls_labels): # if label > 0: # # plot label # # cv2.circle(im2show, cls_dets_center[i], 8, color3, thickness) # cv2.putText(im2show, str(label), cls_dets_center[i], f_s, t_s, color3, thickness=3) pass return im2show, all_cls_dets, all_cls_labels, all_cls_speeds def path_predict(self, im2show): color = (100, 100, 100) speed_color_list = [(200, 200, 0), (0, 200, 200), (0, 0, 200), (0, 0, 255)] # print('show ====>', self.path_speed_dict) for key in self.path_speed_dict.keys(): path_speed_list = self.path_speed_dict[key] if len(path_speed_list) < 2: continue # get history x_n0, y_n0, speed_n0 = path_speed_list[-1] x_n1, y_n1, speed_n1 = path_speed_list[-2] # predict value mutiply = 3 x_pre = x_n0 + mutiply * (x_n0 - x_n1) y_pre = y_n0 + mutiply * (y_n0 - y_n1) # speed_pre = 2 * speed_n0 - speed_n1 # plot predict point1 = (x_n0, y_n0) point2 = (x_pre, y_pre) # speed_avg = (speed_n0 + speed_pre) / 2 cv2.line(im2show, point1, point2, color, thickness=5) return im2show def path_show(self, im2show): speed_color_list = [(200, 200, 0), (0, 200, 200), (0, 0, 200), (0, 0, 255)] # print('show ====>', self.path_speed_dict) for key in self.path_speed_dict.keys(): path_speed_list = self.path_speed_dict[key] if len(path_speed_list) < 2: continue for i in range(len(path_speed_list)-1): x1, y1, speed1 = path_speed_list[i] point1 = (x1, y1) x2, y2, speed2 = path_speed_list[i+1] point2 = (x2, y2) speed_avg = (speed1 + speed2) / 2 if speed_avg <= 2.0: color = speed_color_list[0] elif speed_avg <= 4.0: color = speed_color_list[1] elif speed_avg <= 6.0: color = speed_color_list[2] else: color = speed_color_list[3] cv2.line(im2show, point1, point2, color, thickness=3) return im2show def path_save(self): # print('befor save ====>', self.path_speed_dict) for idx_cls in range(len(self.idf_center_list)): cls_idf_center = self.idf_center_list[idx_cls] # print('cls_idf_center', cls_idf_center) for idf_center in cls_idf_center: idf, xx, yy, count, speed = idf_center # print(idf, xx, yy, count, speed) if idf <= 0: # zero label and nagetivate label continue if count: # is avaliable # save path if idf in self.path_speed_dict.keys(): # print('exist') path_speed_list = self.path_speed_dict[idf] path_speed_list.append((xx, yy, speed)) # long limit if len(path_speed_list) > self.path_keep_time: del path_speed_list[0] self.path_speed_dict[idf] = path_speed_list else: # print('not exist') self.path_speed_dict[idf] = [(xx, yy, speed)] else: # not avaliable # del path if idf in self.path_speed_dict.keys(): # print('exist not avalible key %d !' % idf) del self.path_speed_dict[idf] # print(self.path_speed_dict) # print('after save ====>', self.path_speed_dict) pass def identify_label(self, cls_idx, cls_dets_center): # no value == not car detected if not cls_dets_center: cls_idf_center = self.idf_center_list[cls_idx] for idf_idx, idf_center in enumerate(cls_idf_center): # print('idf_center', idf_center) idf, x_c, y_c, count, speed = idf_center if count<=0 or idf==0: # check label is avalible # print('continue!') continue # update count = count - 1 speed = 0 cls_idf_center[idf_idx] = [idf, x_c, y_c, count, speed] self.idf_center_list[cls_idx] = cls_idf_center # print('finally modifity labels: ', labels) # print('finally modifity cls_idf_center: ', self.idf_center_list[cls_idx]) labels = [] speeds = [] pass return labels, speeds # have value == have car detected cls_idf_center = self.idf_center_list[cls_idx] labels = np.zeros((len(cls_dets_center),), dtype=np.int) speeds = np.zeros((len(cls_dets_center),), dtype=np.float32) # print('initial labels: ', labels) for idf_idx, idf_center in enumerate(cls_idf_center): # print('对 idf_center', idf_center, '遍历所有检测框') idf, x_c, y_c, count, speed = idf_center if count<=0 or idf==0: # check label is avalible # print('continue!') continue best_det_idx = -100 best_det_dist = 100000000 for i, det_center in enumerate(cls_dets_center): # print('cls_dets_center ', i, det_center) xx, yy = det_center dist = (xx-x_c)**2 + (yy-y_c)**2 # print('dist : ', dist) if dist < best_det_dist: best_det_dist = dist best_det_idx = i # print('best_det_dist', best_det_dist) # print('best_det_idx', best_det_idx) # if best_det_dist < self.dist_th: # get exist label and speed labels[best_det_idx] = idf speed = best_det_dist / self.frame_rate speeds[best_det_idx] = speed xx, yy = cls_dets_center[best_det_idx] x_c = xx y_c = yy # print('find ', 'cls_dets_center ', best_det_idx, cls_dets_center[best_det_idx], 'like ', 'idf_center', idf_center) # add count # print('idf_center ', idf_center, '+') if count < self.center_keep_time: count += 1 else: # sub count # print('idf_center ', idf_center, '-') if count > 0: count -= 1 # add new label codes if count == self.active_limit and idf == -1: # 如果未被赋予正label值,且达到消除抖动值 self.now_max_label += 1 # print('======> set new label: %d to ' % self.now_max_label, idf_center) idf = self.now_max_label # update cls_idf_center[idf_idx] = [idf, x_c, y_c, count, speed] # print('update ', 'cls_idf_center ', [idf, x_c, y_c, count]) # print('after label %d modifity labels: ' % idf, labels) # update self.idf_center_list[cls_idx] = cls_idf_center # add new idf_center codes for i, label in enumerate(labels): xx, yy = cls_dets_center[i] if label == 0: # new_num = cls_idf_center[-1][0] + 1 label_num = -1 # 抖动消除 未标记为活动的中心点标记为-1, keep_time 设置为1 cls_idf_center.append([label_num, xx, yy, 1, 0.0]) labels[i] = label_num self.idf_center_list[cls_idx] = cls_idf_center # print('finally modifity labels: ', labels) # print('finally modifity cls_idf_center: ', self.idf_center_list[cls_idx]) pass return labels, speeds def get_rec_center(self, cls_dets): cls_dets_center = [] for j in range(cls_dets.shape[0]): bbox = tuple(int(np.round(x)) for x in cls_dets[j, :4]) xx1, yy1, xx2, yy2 = bbox x_c = round((xx1 + xx2) / 2) y_c = round((yy1 + yy2) / 2) cls_dets_center.append((x_c, y_c)) pass return cls_dets_center def regional_show(self, im2show): line_point_list = self.line_point_list # print('regional_show') color = (255, 238, 147) # 监测框显示 for i in range(len(line_point_list)): cv2.line(im2show, line_point_list[i][0:2], line_point_list[i][2:4], color, thickness=6) return im2show def get_in_regional(self, cls_dets): line_point_list = self.line_point_list # 取每条线判断 # print('init ', 'line_point_list', len(line_point_list), 'cls_dets', len(cls_dets)) for i in range(len(line_point_list)): x1, y1, x2, y2, direction = line_point_list[i] # 竖线 if x2 == x1: keep_ind = [] for j in range(cls_dets.shape[0]): bbox = tuple(int(np.round(x)) for x in cls_dets[j, :4]) xx1, yy1, xx2, yy2 = bbox # calculate center point xx = round((xx1+xx2)/2) yy = round((yy1+yy2)/2) # point below line --> keep if xx >= direction*x1: keep_ind.append(j) # 保留区域内点 cls_dets = cls_dets[keep_ind] # print(i, 'cls_dets', len(cls_dets)) continue # k =
func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Switching sites on `Tableau REST API` (site={contenturl})') url = f'{self.baseapi}/auth/switchSite' body = {'site': {'contentUrl': contenturl}} request = self.session.post(url, json=body) response = Response(request, func) credentials = response.body['credentials'] self.session.headers.update({'x-tableau-auth': credentials['token']}) self.site = credentials['site']['contentUrl'] self.userid = credentials['user']['id'] self.siteid = credentials['site']['id'] return None # -------- Area: Sites -------- # # Additional Endpoints: None @min_api_version('2.5') def createSite(self, name, site=None, **kwargs): """Create New Site on Tableau Server. Parameters ---------- name : str User friendly name of site to create. site : str, optional (default=None) URL friendly name of site to create. If None, one will be created from `name`. **kwargs Optional site creation parameters. See official documentation for details. Returns ------- anonymous : dict Dict of newly created site details. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Creating new site on `Tableau REST API`') url = f'{self.baseapi}/sites' body = { 'site': { 'name': name, 'contentUrl': re.sub('\W', '', name.title()) if site is None else site } } _optionals = ('adminMode', 'userQuota', 'storageQuota', 'disableSubscriptions',) body['site'].update({k: v for k, v in kwargs.items() if k in _optionals}) request = self.session.post(url, json=body) response = Response(request, func) return response.body['site'] @min_api_version('2.5') def querySite(self, **kwargs): """Query Site Details on Tableau Server. Parameters ---------- **kwargs Optional site (name) parameters. Options are (siteid, name, contenturl) If missing, uses current signed in site. Returns ------- anonymous : dict Dict of requested site details. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info('Querying site on `Tableau REST API`') extension = self.site if 'siteid' in kwargs: extension = f'{kwargs["siteid"]}' elif 'name' in kwargs: extension = f'{kwargs["name"]}?key=name' elif 'contenturl' in kwargs: extension = f'{kwargs["contenturl"]}?key=contentUrl' url = f'{self.baseapi}/sites/{extension}' request = self.session.get(url) response = Response(request, func) return response.body['site'] @min_api_version('2.5') def querySites(self, pagesize=1000): """Query List of Sites on Tableau Server. Parameters ---------- pagesize : int, optional (default=1000) Number of items to fetch per request. Returns ------- sites : dict Dict of sites available to current user. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info('Querying sites on `Tableau REST API`') url = f'{self.baseapi}/sites' sites = dict() done, totalsize, pagenumber = False, 0, 1 while not done: paged = f'{url}?pageSize={pagesize}&pageNumber={pagenumber}' request = self.session.get(paged) response = Response(request, func) pagenumber += 1 totalsize += response.pagination.pageSize done = response.pagination.totalAvailable <= totalsize for site in response.body['sites']['site']: siteid = site['id'] sites[siteid] = site logging.debug(f'Found {len(sites)} sites on `Tableau REST API`') return sites @min_api_version('2.5') def queryViewsforSite(self, pagesize=1000): """Query Viewable Views on Tableau Server for Site. Parameters ---------- pagesize : int, optional (default=1000) Number of items to fetch per request. Returns ------- views : dict Dict of viewable views on server. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Querying views for site on `Tableau REST API` (site={self.site})') url = f'{self.baseapi}/sites/{self.siteid}/views' views = dict() done, totalsize, pagenumber = False, 0, 1 while not done: paged = f'{url}?includeUsageStatistics=true&pageSize={pagesize}&pageNumber={pagenumber}' request = self.session.get(paged) response = Response(request, func) pagenumber += 1 totalsize += response.pagination.pageSize done = response.pagination.totalAvailable <= totalsize for view in response.body['views']['view']: viewid = view['id'] views[viewid] = view logging.debug(f'Found {len(views)} views on `Tableau REST API` (site={self.site})') return views @min_api_version('2.5') def updateSite(self, siteid, **kwargs): """Update Site Details on Tableau Server. Parameters ---------- siteid : str Id of site to update details for. **kwargs Optional site update parameters. See official documentation for details. Returns ------- anonymous : dict Dict of newly created site details. Notes ----- This method does not at present support logo updating. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Updating site details on `Tableau REST API`') url = f'{self.baseapi}/sites{siteid}' _optionals = ( 'name', 'contentUrl', 'adminMode', 'userQuota', 'state', 'storageQuota', 'disableSubscriptions', 'revisionHistoryEnabled', 'revisionLimit', ) body = {'site': {k: v for k, v in kwargs.items() if k in _optionals}} request = self.session.post(url, json=body) response = Response(request, func) return response.body['site'] @min_api_version('2.5') def deleteSite(self, **kwargs): """Delete Site on Tableau Server. Parameters ---------- **kwargs Optional site (name) parameters. Options are (siteid, name, contenturl) If missing, uses current signed in site. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Deleting site on `Tableau REST API`') extension = self.site if 'siteid' in kwargs: extension = f'{kwargs["siteid"]}' elif 'name' in kwargs: extension = f'{kwargs["name"]}?key=name' elif 'contenturl' in kwargs: extension = f'{kwargs["contenturl"]}?key=contentUrl' url = f'{self.baseapi}/sites/{extension}' request = self.session.delete(url) Response(request, func) return None # -------- Area: Projects -------- # # Additional Endpoints: None @min_api_version('2.5') def createProject(self, **kwargs): """Create New Project on Tableau Server. Parameters ---------- **kwargs Optional project parameters to update. Options are (name, description, contentPermissions). See official documentation for details. Returns ------- anonymous : dict Dict of newly created project details. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Creating new project on `Tableau REST API` (site={self.site})') url = f'{self.baseapi}/sites/{self.siteid}/projects' _optional = ('name', 'description', 'contentPermissions',) body = {'project': {k: v for k, v in kwargs.items() if k in _optional}} request = self.session.post(url, json=body) response = Response(request, func) return response.body['project'] @min_api_version('2.5') def queryProjects(self, pagesize=1000): """Query List of Site Projects on Tableau Server. Parameters ---------- pagesize : int, optional (default=1000) Number of items to fetch per request. Returns ------- projects : dict Dict of projects available to current user. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Querying projects on `Tableau REST API` (site={self.site})') url = f'{self.baseapi}/sites/{self.siteid}/projects' projects = dict() done, totalsize, pagenumber = False, 0, 1 while not done: paged = f'{url}?pageSize={pagesize}&pageNumber={pagenumber}' request = self.session.get(paged) response = Response(request, func) pagenumber += 1 totalsize += response.pagination.pageSize done = response.pagination.totalAvailable <= totalsize for project in response.body['projects']['project']: projectid = project['id'] projects[projectid] = project logging.debug(f'Found {len(projects)} projects on `Tableau REST API` (site={self.site})') return projects @min_api_version('2.5') def updateProject(self, projectid, **kwargs): """Update Project Details on Tableau Server. Parameters ---------- projectid : str ID of project to update on tableau server. **kwargs Optional project parameters to update. Options are (name, description, contentPermissions) Returns ------- anonymous : dict Dict of newly created project details. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Update project details on `Tableau REST API` (projectid={projectid})') url = f'{self.baseapi}/sites/{self.siteid}/projects/{projectid}' _optional = ('name', 'description', 'contentPermissions',) body = {'project': {k: v for k, v in kwargs.items() if k in _optional}} request = self.session.put(url, json=body) response = Response(request, func) return response.body['project'] @min_api_version('2.5') def deleteProject(self, projectid): """Delete Project on Tableau Server. Parameters ---------- projectid : str ID of project to update on tableau server. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Deleting project on `Tableau REST API` (projectid={projectid})') url = f'{self.baseapi}/sites/{self.siteid}/projects/{projectid}' request = self.session.delete(url) Response(request, func) return None # -------- Area: Workbooks and Views -------- # # Additional Endpoints: publishWorkbook, addTagstoView, queryViewsforSite, # queryViewImage, queryViewPreviewImage, getWorkbookRevisions, # queryWorkbookPreviewImage, queryWorkbooksforSite, downloadWorkbookRevision, # removeWorkbookRevision, deleteTagfromView, deleteTagfromWorkbook @min_api_version('2.5') def addTagstoWorkbook(self, workbookid, tags): """Add Tags to Workbook on Tableau Server. Parameters ---------- workbookid : str ID of workbook to query information about. tags : list List of tags to add to workbook. Returns ------- anonymous : list List of dict tags from Tableau Server. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Adding tags to workbook on `Tableau REST API` (workbookid={workbookid})') url = f'{self.baseapi}/sites/{self.siteid}/workbooks/{workbookid}/tags' body = {'tags': [{'tag': {'label': tag}} for tag in tags]} request = self.session.put(url, json=body) response = Response(request, func) return response.body['tags'] @min_api_version('2.5') def queryViewsforWorkbook(self, workbookid, usagestats=True): """Query Workbook Views on Tableau Server. Parameters ---------- workbookid : str ID of workbook to query information about. usagestats : bool, optional (default=True) Flag for including usage statistics for views. Returns ------- views : dict Dict of view available to current user for workbook. """ # noinspection PyProtectedMember func = sys._getframe().f_code.co_name # pylint: disable=protected-access logging.info(f'Querying views for workbook on `Tableau REST API` (workbookid={workbookid})') url = f'{self.baseapi}/sites/{self.siteid}/workbooks/{workbookid}/views' optional = f'{url}?includeUsageStatistics={str(usagestats).lower()}' request = self.session.get(optional) response = Response(request, func) views = dict() for view in response.body['views']['view']: viewid = view['id'] views[viewid] = view logging.debug(f'Found {len(views)} views on `Tableau REST API` (workbookid={workbookid})') return views @min_api_version('2.5') def queryWorkbook(self, workbookid): """Query Workbook Information on Tableau Server. Parameters ---------- workbookid : str ID of
import pandas as pd from pyparsing import * from utils import * texttest = """ Record Number 1802 Weapon Scoring Application ID: 13 Record Type: 3 Record Subtype: 2 Minor Frame: 01196646 Time (UTC): 18:41:47.563 Recording Length: 284 (16-bit words) Tail Number: 0 Tail Year: 0 Date: 07/28/20 Mode: STRIKE Launch PERTINENT DATA Dev ID LP3 (0x0000003C) WPN Mode Switches (0x0000003E) In Go NoGo Test False In SIT False ECU Override Sel False Manual LNCH Enabled True Auto TGTING Enabled False GPS Keys Avail In ACU True LCD In Progress False JETT In Progress False Left WIU Unlock Enabled True Right WIU Unlock Enabled False Two Man Unlock Consent Enabled True Any MDT In Progress False TDS Mod Act False War MSN True Ferry MSN False Operational Test LNCH False TLI MSN False JTU False Captive Carry MSN False Latitude N 040:29.4333 deg (0x00000042) Longitude W 113:21.9649 deg (0x00000046) Altitude + 26014.00000 feet (0x0000004A) True Heading + 070.2440033 deg (0x0000004E) GND Trk Angle + 071.9620285 deg (0x00000052) Pitch Angle - 000.6811523 deg (0x00000056) Roll Angle + 000.3719696 deg (0x0000005A) Yaw Angle - 070.0598145 deg (0x0000005E) Velocity North 224.0614471 ft/sec (0x00000062) Velocity East 688.0382690 ft/sec (0x00000066) Velocity Vertical 003.5946419 ft/sec (0x0000006A) GND Speed 723.6022339 ft/sec (0x0000006E) True Air Speed North + 0225.466919 ft/sec (0x00000072) True Air Speed East + 628.2985840 ft/sec (0x00000076) Prime Nav Info (0x0000007A) Prime INU Mode INU1 Prime Nav System INU1 WPN TGT Status Word (0x0000007E) TDS 1 Valid True TDS 2 Valid True Primary TGT Location 2 Tgt Store Loc Num 2 WPN Status 22T02 (0x00000080) Safe To Release True Crit HW Passed True Min TXA RCVD True Min TDS RCVD True AUR Ready True TXA Good True MIN GPS Data True Last BIT Passed True Warm Up Complete True Release Consent False Commit To Sep Store True TM Present False PF Present False AJ AEM Present False PWR Interruption False Timeline Aborted False WPN Status 22T03 (0x00000082) Modify TGT Data RCVD True Almanac RCVD True Ephemeris RCVD True AS SV RCVD True GPS Keys RCVD True Time RCVD True CNM RCVD False GPS Key Failed CHKSum False PF Program Status True GPS Keys Loading False WPN State (0x00000084) WPN PWR State Off WPN Type J1 IBIT In Progress False WPN Present False TGTed False TGTING In Progress False Direct TGT True MSN Planned TGT False Captive Carry Launched False CTS Battery Activated True Manual LNCH Required False Wpn LNCH In Progress False IR Status Inside IZ Status Inside AC Store Station ID RCVD True GPS Config Non SAASM WPN Alignment State (0x0000008A) GPS Nav Halted False TXA Halted False TXA Quality 1 Satellites Tracked 0 NAV Solution Quality Good WPN Status 22T24 (0x0000008C) Fuze Type 0 Fuze Variant 0 WPN Bit 22T09 (0x0000008E) Processor Good True GPS Good True CS Good True IMU Good True PS Good True TIK Good True Squibs Good True PF Good True Aj AEM Good True Laser Kit Good True WPN Test 22T10 (0x00000090) TXA Reinitiated False TM On False TXA Halted False GPS Nav Halted False In SIM Flight False GPS Acq Started False In Timeline Intg False Sim Rlse Countdown False Last AIU 1553 Status Word (0x00000092) Remote Term Address 11 Message Error False Instrumentation True Service Req False Broadcast RCVD False Busy False Subsys Failure False Dynamic Control False Remote Term Failure False WCD System Status (0x00000094) IDC PWR Enable Status False Bay Store DC PWR Status False RP Store DC PWR Status True LP Store DC PWR Status True ECU PWR Status True Environmental No Go Monitor False Bay Door Close Monitor False Bay Door Open Monitor True WCD Expected Status (0x00000096) IDC PWR Enable Status False Bay Store DC PWR Status False RP Store DC PWR Status True LP Store DC PWR Status True ECU PWR Status True Environmental No Go Monitor False WIU BIT Error Map (0x00000098) Initial PWR False Unauthorized Write False Window Open Time Expired False Extra Write False Out Of Tolerance 5V False Window Open False RTC Response Error False Handshake Resp Error False BIT Error Code 0 WIU PWR Discrete Status (0x0000009A) Ejector Locked False Ejector Unlocked True Ejector WPN Present False Ejector Arm Solenoid On Umbilical WPN Present False PWR 28 VDC 1 Off PWR 28 VDC 2 Off PWR 115 VAC Off Comm 1553B Failed False Instrumentation Present False Service Req False Broadcast CMD RCVD False RT Subsys Busy False Subsys FLT Flag False RT Term Failed False WIU Ejector Status (0x0000009C) Ejector Unlock CMDed False Ejector Squib Fire CMDed False Release Consent CMDed False Left Unlock Enabled True Right Unlock Enabled True Ejectors 8 False Ejectors 7 False Ejectors 6 False Ejectors 5 False Ejectors 4 False Ejectors 3 False Ejectors 2 False Ejectors 1 False MSN Data ACCUM MSN Time 003:17:57.3846 hr,min,sec (0x000000A0) Speed of Sound Ft Per Sec 1045.1602 ft/sec (0x000000A4) ATMOS Density Slugs Per CuFt 000.0010 slug/ft3 (0x000000A8) Alternate Nav Mode (0x000000AC) Velocity Doppler Attitude AHRS Heading AHRS Manual Mode True WPN Group ID (0x000000B4) TGTING Data (0x000000B6) TGTING Mode Direct TGT MSN Group 0 LP DT Num 127 TGT Header 0 (0x000000BE) TGT Invalidity (0x000000C0) ID Invalid False Type Invalid False Name Invalid False Position Invalid False Impact Azimuth Invalid True Impact Angle Invalid False Offsets Invalid False Relative TGTING Invalid False Min Impact Vel Invalid False TGT Vel Invalid True Laser Code Invalid True Laser CCM Invalid False TGT Target ID 65535 (0x000000C2) TGT Type (0x000000C4) TGT Alt Ref MSL PF Control Source PF If Present TGT Orientation Horizontal Attack Mode Bomb On Coordinates TGT Hardness Not Specified TGT Name (0x000000C6) TGT LAT N 040:30.2001 deg (0x000000D6) TGT LONG W 113:17.7164 deg (0x000000DA) TGT Altitude + 01405.43 meters (0x000000DE) Min Impact Velocity (0x000000E2) Minimum Impact Velocity 0 meters/sec Impact Azimuth 0 deg (0x000000E4) Impact Angle 90 deg (0x000000E6) TGT Vel North + 000.0000 meters/sec (0x000000E8) TGT Vel East + 000.0000 meters/sec (0x000000EA) Laser Code (0x000000EC) Laser Code 1 0 Laser Code 2 0 Laser Code 3 0 Laser Code 4 0 Laser CCM (0x000000EE) Last Pulse Logic Long Last Pulse Logic Inhibit Laser True Stationary TGT True Basis for TGT Position False Offset North + 00000.0 meters (0x000000F0) Offset East + 00000.0 meters (0x000000F2) Offset Down + 00000.0 meters (0x000000F4) Relative TGT SV1 (0x000000F6) Channel 1 ID 0 Channel 2 ID 0 Channel 3 ID 0 Relative TGT SV2 (0x000000F8) Channel 4 ID 0 PF Record/Block Num (0x000000FA) Record Num 1 Block Number 2 PF Invalidity Word 1 (0x000000FC) Word 1 Invalid False Word 2 Invalid False Word 3 Invalid False Word 4 Invalid False
= self.genotypes[i] # Getting the genotype o_geno = self.pedfile.get_geno_marker(marker) np.testing.assert_array_equal(o_geno, e_geno) # Asking for an unknown marker should raise an ValueError with self.assertRaises(ValueError) as cm: self.pedfile.get_geno_marker("dummy_marker") self.assertEqual( "dummy_marker: marker not in BIM", str(cm.exception), ) def test_get_geno_marker_w_mode(self): """Tests that an exception is raised if in write mode.""" with self.assertRaises(UnsupportedOperation) as cm: # Creating the dummy PyPlink object prefix = os.path.join(self.tmp_dir, "test_error") with pyplink.PyPlink(prefix, "w") as p: p.get_geno_marker("M1") self.assertEqual("not available in 'w' mode", str(cm.exception)) def test_get_iter_w_mode(self): """Tests that an exception is raised if in write mode.""" with self.assertRaises(UnsupportedOperation) as cm: # Creating the dummy PyPlink object prefix = os.path.join(self.tmp_dir, "test_error") with pyplink.PyPlink(prefix, "w") as p: iter(p) self.assertEqual("not available in 'w' mode", str(cm.exception)) def test_get_acgt_geno_marker(self): """Tests the 'get_acgt_geno_marker' function.""" # Getting a random marker to test i = random.choice(range(len(self.markers))) marker = self.markers[i] e_geno = self.acgt_genotypes[i] # Getting the genotype o_geno = self.pedfile.get_acgt_geno_marker(marker) np.testing.assert_array_equal(o_geno, e_geno) # Asking for an unknown marker should raise an ValueError with self.assertRaises(ValueError) as cm: self.pedfile.get_acgt_geno_marker("dummy_marker") self.assertEqual("dummy_marker: marker not in BIM", str(cm.exception)) def test_get_acgt_geno_marker_w_mode(self): """Tests that an exception is raised if in write mode.""" with self.assertRaises(UnsupportedOperation) as cm: # Creating the dummy PyPlink object prefix = os.path.join(self.tmp_dir, "test_error") with pyplink.PyPlink(prefix, "w") as p: p.get_acgt_geno_marker("M1") self.assertEqual("not available in 'w' mode", str(cm.exception)) def test_get_context_read_mode(self): """Tests the PyPlink object as context manager.""" with pyplink.PyPlink(self.prefix) as genotypes: self.assertEqual(3, len(genotypes.get_fam().head(n=3))) def test_invalid_mode(self): """Tests invalid mode when PyPlink as context manager.""" with self.assertRaises(ValueError) as cm: pyplink.PyPlink(self.prefix, "u") self.assertEqual("invalid mode: 'u'", str(cm.exception)) def test_write_binary(self): """Tests writing a Plink binary file.""" # The expected genotypes expected_genotypes = [ np.array([0, 0, 0, 1, 0, 1, 2], dtype=int), np.array([0, 0, 0, 0, -1, 0, 1], dtype=int), np.array([0, -1, -1, 2, 0, 0, 0], dtype=int), ] # The prefix test_prefix = os.path.join(self.tmp_dir, "test_write") # Writing the binary file with pyplink.PyPlink(test_prefix, "w") as pedfile: for genotypes in expected_genotypes: pedfile.write_genotypes(genotypes) # Checking the file exists self.assertTrue(os.path.isfile(test_prefix + ".bed")) # Writing the FAM file with open(test_prefix + ".fam", "w") as o_file: for i in range(7): print("f{}".format(i+1), "s{}".format(i+1), "0", "0", random.choice((1, 2)), "-9", sep=" ", file=o_file) # Writing the BIM file with open(test_prefix + ".bim", "w") as o_file: for i in range(3): print(i+1, "m{}".format(i+1), "0", i+1, "T", "A", sep="\t", file=o_file) # Reading the written binary file with pyplink.PyPlink(test_prefix) as pedfile: for i, (marker, genotypes) in enumerate(pedfile): self.assertEqual("m{}".format(i+1), marker) np.testing.assert_array_equal(expected_genotypes[i], genotypes) def test_write_binary_error(self): """Tests writing a binary file, with different number of sample.""" # The expected genotypes expected_genotypes = [ np.array([0, 0, 0, 1, 0, 1, 2], dtype=int), np.array([0, 0, 0, 0, -1, 0], dtype=int), np.array([0, -1, -1, 2, 0, 0, 0], dtype=int), ] # The prefix test_prefix = os.path.join(self.tmp_dir, "test_write") # Writing the binary file with self.assertRaises(ValueError) as cm: with pyplink.PyPlink(test_prefix, "w") as pedfile: pedfile.write_genotypes(expected_genotypes[0]) # 7 genotypes pedfile.write_genotypes(expected_genotypes[1]) # 6 genotypes self.assertEqual("7 samples expected, got 6", str(cm.exception)) def test_grouper_padding(self): """Tests the _grouper function (when padding is required).""" expected_chunks = [ (0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 0, 0), ] observed_chunks = pyplink.PyPlink._grouper(range(10), 3) for expected, observed in zip(expected_chunks, observed_chunks): self.assertEqual(expected, observed) def test_grouper_no_padding(self): """Tests the _grouper function (when padding is not required).""" expected_chunks = [ (0, 1, 2, 3, 4), (5, 6, 7, 8, 9), ] observed_chunks = pyplink.PyPlink._grouper(range(10), 5) for expected, observed in zip(expected_chunks, observed_chunks): self.assertEqual(expected, observed) @unittest.skipIf(platform.system() not in {"Darwin", "Linux", "Windows"}, "Plink not available for {}".format(platform.system())) def test_with_plink(self): """Tests to read a binary file using Plink.""" # Checking if we need to skip if self.plink_path is None: self.skipTest(self.plink_message) # Creating the BED file all_genotypes = [ [0, 1, 0, 0, -1, 0, 1, 0, 0, 2], [2, 1, 2, 2, 2, 2, 2, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], ] prefix = os.path.join(self.tmp_dir, "test_output") with pyplink.PyPlink(prefix, "w") as pedfile: for genotypes in all_genotypes: pedfile.write_genotypes(genotypes) # Creating the FAM file fam_content = [ ["F0", "S0", "0", "0", "1", "-9"], ["F1", "S1", "0", "0", "1", "-9"], ["F2", "S2", "0", "0", "2", "-9"], ["F3", "S3", "0", "0", "1", "-9"], ["F4", "S4", "0", "0", "1", "-9"], ["F5", "S5", "0", "0", "2", "-9"], ["F6", "S6", "0", "0", "1", "-9"], ["F7", "S7", "0", "0", "0", "-9"], ["F8", "S8", "0", "0", "1", "-9"], ["F9", "S9", "0", "0", "2", "-9"], ] with open(prefix + ".fam", "w") as o_file: for sample in fam_content: print(*sample, sep=" ", file=o_file) # Creating the BIM file bim_content = [ ["1", "M0", "0", "123", "A", "G"], ["1", "M1", "0", "124", "C", "T"], ["2", "M2", "0", "117", "G", "C"], ] with open(prefix + ".bim", "w") as o_file: for marker in bim_content: print(*marker, sep="\t", file=o_file) # Creating a transposed pedfile using Plink out_prefix = prefix + "_transposed" try: check_call([ self.plink_path, "--noweb", "--bfile", prefix, "--recode", "--transpose", "--tab", "--out", out_prefix, ], stdout=PIPE, stderr=PIPE) except CalledProcessError: self.fail("Plink could not recode file") # Checking the two files exists self.assertTrue(os.path.isfile(out_prefix + ".tped")) self.assertTrue(os.path.isfile(out_prefix + ".tfam")) # Checking the content of the TFAM file expected = "\n".join("\t".join(sample) for sample in fam_content) with open(out_prefix + ".tfam", "r") as i_file: self.assertEqual(expected + "\n", i_file.read()) # Checking the content of the TPED file with open(out_prefix + ".tped", "r") as i_file: # Checking the first marker marker_1 = i_file.readline().rstrip("\r\n").split("\t") self.assertEqual(["1", "M0", "0", "123"], marker_1[:4]) self.assertEqual(["G G", "A G", "G G", "G G", "0 0", "G G", "A G", "G G", "G G", "A A"], marker_1[4:]) # Checking the second marker marker_2 = i_file.readline().rstrip("\r\n").split("\t") self.assertEqual(["1", "M1", "0", "124"], marker_2[:4]) self.assertEqual(["C C", "T C", "C C", "C C", "C C", "C C", "C C", "T C", "T T", "T C"], marker_2[4:]) # Checking the third marker marker_3 = i_file.readline().rstrip("\r\n").split("\t") self.assertEqual(["2", "M2", "0", "117"], marker_3[:4]) self.assertEqual(["C C", "C C", "C C", "C C", "C C", "G C", "C C", "C C", "C C", "C C"], marker_3[4:]) # Checking this is the end of the file self.assertEqual("", i_file.readline()) @unittest.skipIf(platform.system() not in {"Darwin", "Linux", "Windows"}, "Plink not available for {}".format(platform.system())) def test_with_plink_individual_major(self): """Tests to read a binary file (INDIVIDUAL-major) using Plink.""" # Checking if we need to skip if self.plink_path is None: self.skipTest(self.plink_message) # The genotypes all_genotypes = [ [0, 1, 0, 0, -1, 0, 1, 0, 0, 2], [2, 1, 2, 2, 2, 2, 2, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], ] transposed_genotypes = [ [row[i] for row in all_genotypes] for i in range(len(all_genotypes[0])) ] # Creating the BED file (INDIVIDUAL-major) prefix = os.path.join(self.tmp_dir, "test_output") with pyplink.PyPlink(prefix, "w", "INDIVIDUAL-major") as pedfile: for genotypes in transposed_genotypes: pedfile.write_genotypes(genotypes) # Creating the FAM file fam_content = [ ["F0", "S0", "0", "0", "1", "-9"], ["F1", "S1", "0", "0", "1", "-9"], ["F2", "S2", "0", "0", "2", "-9"], ["F3", "S3", "0", "0", "1", "-9"], ["F4", "S4", "0", "0", "1", "-9"], ["F5", "S5", "0", "0", "2", "-9"], ["F6", "S6", "0", "0", "1", "-9"], ["F7", "S7", "0", "0", "0", "-9"], ["F8", "S8", "0", "0", "1", "-9"], ["F9", "S9", "0", "0", "2", "-9"], ] with open(prefix + ".fam", "w") as o_file: for sample in fam_content: print(*sample, sep=" ", file=o_file) # Creating the BIM file bim_content = [ ["1", "M0", "0", "123", "A", "G"], ["1", "M1", "0", "124", "C", "T"], ["2", "M2", "0", "117", "G", "C"], ] with open(prefix + ".bim", "w") as o_file: for marker in bim_content: print(*marker, sep="\t", file=o_file) # Creating a transposed pedfile using Plink out_prefix = prefix + "_transposed" try: check_call([ self.plink_path, "--noweb", "--bfile", prefix, "--recode", "--transpose", "--tab", "--out", out_prefix, ], stdout=PIPE, stderr=PIPE) except CalledProcessError: self.fail("Plink could not recode file") # Checking the two files exists self.assertTrue(os.path.isfile(out_prefix + ".tped")) self.assertTrue(os.path.isfile(out_prefix + ".tfam")) # Checking the content of the TFAM file expected = "\n".join("\t".join(sample) for sample in fam_content) with open(out_prefix + ".tfam", "r") as i_file: self.assertEqual(expected + "\n", i_file.read()) # Checking the content of the TPED file with open(out_prefix + ".tped", "r") as i_file: # Checking the first marker marker_1 = i_file.readline().rstrip("\r\n").split("\t") self.assertEqual(["1", "M0", "0", "123"], marker_1[:4]) self.assertEqual(["G G", "A G", "G G", "G G", "0 0", "G G", "A
<filename>01_build_caliber_codelist.py # Databricks notebook source # MAGIC %md # MAGIC # Build CALIBER codelist # MAGIC # MAGIC **Description** # MAGIC # MAGIC 1. Imports the CALIBER codelist dictionary from *<NAME>., <NAME>., <NAME>. et al. A chronological map of 308 physical and mental health conditions from 4 million individuals in the National Health Service published in the Lancet Digital Health - DOI 10.1016/S2589-7500(19)30012-3* at https://github.com/spiros/chronological-map-phenotypes # MAGIC * NB owing to lack of external connectivity within the TRE, this is imported by hardcoding # MAGIC 2. Applies a series of 'regex' transformations to map the dictionary to the format of codelists stored within the TRE `bhf_cvd_covid_uk_byod` database # MAGIC 3. Uses the transformed dictionary to loop through all relevant codelists and compile a **master codelist** of: `phenotype`, `code` & `terminology` # MAGIC # MAGIC # MAGIC **Project(s)** CCU013 # MAGIC # MAGIC **Author(s)** <NAME> # MAGIC # MAGIC **Reviewer(s)** *UNREVIEWED !!!* # MAGIC # MAGIC **Date last updated** 2021-04-22 # MAGIC # MAGIC **Date last reviewed** *UNREVIEWED !!!* # MAGIC # MAGIC **Date last run** 2021-04-22 # MAGIC # MAGIC **Changelog** # MAGIC 0. `21-04-22` **Initial version** # MAGIC 1. `21-07-13`: # MAGIC a) upgrade to optimised delta table # MAGIC b) sort phenotype regexp cleaning # MAGIC # MAGIC # MAGIC **Data input** # MAGIC * ALL `caliber_...` tables in `bhf_cvd_covid_uk_byod` database # MAGIC # MAGIC # MAGIC **Data output** # MAGIC * `ccu013_caliber_dictionary` # MAGIC * `ccu013_caliber_codelist_master` # MAGIC # MAGIC **Software and versions** `python`, `sql` # MAGIC # MAGIC **Packages and versions** `pyspark`, `pandas` # COMMAND ---------- # MAGIC %run /Workspaces/dars_nic_391419_j3w9t_collab/CCU013/COVID-19-SEVERITY-PHENOTYPING/CCU013_00_helper_functions # COMMAND ---------- # MAGIC %md # MAGIC ## 0. Exploration of phenotypes in `bhf_cvd_covid_uk_byod` # COMMAND ---------- # MAGIC %sql # MAGIC SHOW TABLES IN bhf_cvd_covid_uk_byod # COMMAND ---------- # MAGIC %sql # MAGIC SHOW TABLES IN bhf_cvd_covid_uk_byod LIKE "caliber*" # COMMAND ---------- # MAGIC %md # MAGIC #### Terminologies # MAGIC There is no column for this so have to infer from the table name # MAGIC # MAGIC | Terminology | **tableName** | **col** | date field | # MAGIC | ----------- | ----------- | # MAGIC | SNOMED | `caliber_cprd_***_snomedct` | `conceptId` | `RecordDate` | # MAGIC | Readcode | `caliber_cprd_***` | `Readcode` | `RecordDate` | # MAGIC | Medcode | `caliber_cprd_***` | `Medcode` | `RecordDate` | # MAGIC | ICD10 | `caliber_icd_***` | `ICD10code` | `RecordDate` | # MAGIC | OPCS4 | `caliber_opcs_***` | `OPCS4code` | `RecordDate` | # MAGIC # MAGIC # MAGIC So each terminology can be uniquely identified by the column name! # COMMAND ---------- # MAGIC %md # MAGIC Plan: # MAGIC 1. Get all CALIBER table names # MAGIC 2. Loop through and extract: # MAGIC * `Disease` as `phenotype` # MAGIC * code # MAGIC * terminology # MAGIC 3. at end of loop append to the temp view `ccu013_caliber_codelists` # MAGIC 4. make permanent # COMMAND ---------- # MAGIC %md # MAGIC # 1. Build CALIBER dictionary (of codelists!) # MAGIC # MAGIC The dictionary is hardcoded below by copying and pasting from [https://github.com/spiros/chronological-map-phenotypes/blob/master/dictionary.csv] # COMMAND ---------- # MAGIC %md # MAGIC ## 1.1 Hardcode dictionary # COMMAND ---------- dictionary = """phenotype,CPRD,ICD,OPCS Abdominal Hernia,CPRD_hernia_abdo.csv,ICD_hernia_abdo.csv,OPCS_hernia_abdo.csv Abdominal aortic aneurysm,CPRD_AAA.csv,ICD_AAA.csv, Acne,CPRD_acne.csv,ICD_acne.csv, Actinic keratosis,CPRD_actinic_keratosis.csv,ICD_actinic_keratosis.csv, Acute Kidney Injury,,ICD_AKI.csv, Agranulocytosis,CPRD_agranulocytosis.csv,ICD_agranulocytosis.csv, Alcohol Problems,CPRD_alc_problems.csv,ICD_alc_problems.csv, Alcoholic liver disease,CPRD_liver_alc.csv,ICD_liver_alc.csv, Allergic and chronic rhinitis,CPRD_allergic_rhinitis.csv,ICD_allergic_rhinitis.csv, Alopecia areata,CPRD_alopecia_areata.csv,ICD_alopecia_areata.csv, Anal fissure,CPRD_anal_fissure.csv,ICD_anal_fissure.csv,OPCS_anal_fissure.csv Angiodysplasia of colon,CPRD_angiodysplasia_colon.csv,ICD_angiodysplasia_colon.csv, Ankylosing spondylitis,CPRD_ank_spond.csv,ICD_ank_spond.csv, Anorectal fistula,CPRD_anorectal_fistula.csv,ICD_anorectal_fistula.csv,OPCS_anorectal_fistula.csv Anorectal prolapse,CPRD_anorectal_prolapse.csv,ICD_anorectal_prolapse.csv,OPCS_anorectal_prolapse.csv Anorexia and bulimia nervosa,CPRD_eating_dz.csv,ICD_eating_dz.csv, Anterior and Intermediate Uveitis,CPRD_ant_uveitis.csv,ICD_ant_uveitis.csv, Anxiety disorders,CPRD_anxiety.csv,ICD_anxiety.csv, Aplastic anaemias,CPRD_aplastic.csv,ICD_aplastic.csv, Appendicitis,CPRD_appendicitis.csv,ICD_appendicitis.csv,OPCS_appendicitis.csv Asbestosis,CPRD_asbestosis.csv,ICD_asbestosis.csv, Aspiration pneumonitis,CPRD_aspiration_pneumo.csv,ICD_aspiration_pneumo.csv, Asthma,CPRD_asthma.csv,ICD_asthma.csv, Atrial fibrillation,CPRD_AF.csv,ICD_AF.csv, "Atrioventricular block, complete",CPRD_av_block_3.csv,ICD_av_block_3.csv, "Atrioventricular block, first degree",CPRD_av_block_1.csv,ICD_av_block_1.csv, "Atrioventricular block, second degree",CPRD_av_block_2.csv,ICD_av_block_2.csv, Autism and Asperger's syndrome,CPRD_autism.csv,ICD_autism.csv, Autoimmune liver disease,CPRD_autoimm_liver.csv,ICD_autoimm_liver.csv, Bacterial Diseases (excl TB),,ICD_bacterial.csv, Bacterial sepsis of newborn,CPRD_sepsis_newborn.csv,ICD_sepsis_newborn.csv, Barrett's oesophagus,CPRD_barretts.csv,ICD_barretts.csv, Bell's palsy,CPRD_bells.csv,ICD_bells.csv, Benign neoplasm and polyp of uterus,CPRD_benign_uterus.csv,ICD_benign_uterus.csv, Benign neoplasm of brain and other parts of central nervous system,CPRD_benign_brain.csv,ICD_benign_brain.csv, "Benign neoplasm of colon, rectum, anus and anal canal",CPRD_benign_colon.csv,ICD_benign_colon.csv, Benign neoplasm of ovary,CPRD_benign_ovary.csv,ICD_benign_ovary.csv, Benign neoplasm of stomach and duodenum,CPRD_benign_stomach.csv,ICD_benign_stomach.csv, Bifascicular block,CPRD_bifasc_block.csv,ICD_bifasc_block.csv, Bipolar affective disorder and mania,CPRD_BAD.csv,ICD_BAD.csv, Bronchiectasis,CPRD_bronchiectasis.csv,ICD_bronchiectasis.csv, COPD,CPRD_COPD.csv,ICD_COPD.csv, Carcinoma in situ_cervical,CPRD_cin_cervical.csv,ICD_cin_cervical.csv, Carpal tunnel syndrome,CPRD_carpal_tunnel.csv,ICD_carpal_tunnel.csv,OPCS_carpal_tunnel.csv Cataract,CPRD_cataract.csv,ICD_cataract.csv,OPCS_cataract.csv Cerebral Palsy,CPRD_cerebral_palsy.csv,ICD_cerebral_palsy.csv, Cholangitis,CPRD_cholangitis.csv,ICD_cholangitis.csv, Cholecystitis,CPRD_cholecystitis.csv,ICD_cholecystitis.csv, Cholelithiasis,CPRD_cholelithiasis.csv,ICD_cholelithiasis.csv, Chronic sinusitis,CPRD_sinusitis.csv,ICD_sinusitis.csv, Chronic viral hepatitis,CPRD_chr_hep.csv,ICD_chr_hep.csv, Coeliac disease,CPRD_coeliac.csv,ICD_coeliac.csv, Collapsed vertebra,CPRD_collapsed_vert.csv,ICD_collapsed_vert.csv,OPCS_collapsed_vert.csv Congenital malformations of cardiac septa,CPRD_congenital_septal.csv,ICD_congenital_septal.csv,OPCS_congenital_septal.csv Coronary heart disease not otherwise specified,CPRD_CHD_NOS.csv,ICD_CHD_NOS.csv, Crohn's disease,CPRD_crohns.csv,ICD_crohns.csv, Cystic Fibrosis,CPRD_CF.csv,ICD_CF.csv, "Delirium, not induced by alcohol and other psychoactive substances",CPRD_delirium.csv,ICD_delirium.csv, Dementia,CPRD_dementia.csv,ICD_dementia.csv, Depression,CPRD_depression.csv,ICD_depression.csv, Dermatitis (atopc/contact/other/unspecified),CPRD_dermatitis.csv,ICD_dermatitis.csv, Diabetes,CPRD_diabetes.csv,ICD_diabetes.csv, Diabetic neurological complications,CPRD_dm_neuro.csv,ICD_dm_neuro.csv, Diabetic ophthalmic complications,CPRD_diab_eye.csv,ICD_diab_eye.csv, Diaphragmatic hernia,CPRD_hernia_diaphragm.csv,ICD_hernia_diaphragm.csv,OPCS_hernia_diaphragm.csv Dilated cardiomyopathy,CPRD_dcm.csv,ICD_dcm.csv, Disorders of autonomic nervous system,CPRD_autonomic_neuro.csv,ICD_autonomic_neuro.csv, Diverticular disease of intestine (acute and chronic),CPRD_diverticuli.csv,ICD_diverticuli.csv,OPCS_diverticuli.csv Down's syndrome,CPRD_downs.csv,ICD_downs.csv, Dysmenorrhoea,CPRD_dysmenorrhoea.csv,ICD_dysmenorrhoea.csv, Ear and Upper Respiratory Tract Infections,,ICD_ear_urti.csv, Encephalitis,,ICD_enceph.csv, End stage renal disease,CPRD_ESRD.csv,ICD_ESRD.csv,OPCS_ESRD.csv Endometrial hyperplasia and hypertrophy,CPRD_endometrial_hyper.csv,ICD_endometrial_hyper.csv, Endometriosis,CPRD_endometriosis.csv,ICD_endometriosis.csv, Enteropathic arthropathy,CPRD_entero_arthro.csv,ICD_entero_arthro.csv, Enthesopathies & synovial disorders,CPRD_enthesopathy.csv,ICD_enthesopathy.csv, Epilepsy,CPRD_epilepsy.csv,ICD_epilepsy.csv, Erectile dysfunction,CPRD_ED.csv,ICD_ED.csv, Essential tremor,CPRD_essential_tremor.csv,ICD_essential_tremor.csv, Eye infections,,ICD_eye.csv, Fatty Liver,CPRD_fatty_liver.csv,ICD_fatty_liver.csv, Female genital prolapse,CPRD_female_genital_prolapse.csv,ICD_female_genital_prolapse.csv, Female infertility,CPRD_female_infertility.csv,ICD_female_infertility.csv, Female pelvic inflammatory disease,,ICD_PID.csv, Fibromatoses,CPRD_fibromatosis.csv,ICD_fibromatosis.csv,OPCS_fibromatosis.csv Folate deficiency anaemia,CPRD_folatedef.csv,ICD_folatedef.csv, Fracture of hip,CPRD_fracture_hip.csv,ICD_fracture_hip.csv,OPCS_fracture_hip.csv Fracture of wrist,CPRD_fracture_wrist.csv,ICD_fracture_wrist.csv, Gastritis and duodenitis,CPRD_gastritis_duodenitis.csv,ICD_gastritis_duodenitis.csv, Gastro-oesophageal reflux disease,CPRD_GORD.csv,ICD_GORD.csv,OPCS_GORD.csv Giant Cell arteritis,CPRD_GCA.csv,ICD_GCA.csv, Glaucoma,CPRD_glaucoma.csv,ICD_glaucoma.csv,OPCS_glaucoma.csv Glomerulonephritis,CPRD_GN.csv,ICD_GN.csv, Gout,CPRD_gout.csv,ICD_gout.csv, HIV,CPRD_hiv.csv,ICD_hiv.csv, "Haemangioma, any site",CPRD_haemangioma.csv,ICD_haemangioma.csv, Hearing loss,CPRD_deaf.csv,ICD_deaf.csv, Heart failure,CPRD_hf.csv,ICD_hf.csv, Hepatic failure,CPRD_liver_fail.csv,ICD_liver_fail.csv, Hidradenitis suppurativa,CPRD_hidradenitis.csv,ICD_hidradenitis.csv, High birth weight,CPRD_HBW.csv,ICD_HBW.csv, Hodgkin Lymphoma,CPRD_hodgkins.csv,ICD_hodgkins.csv, Hydrocoele (incl infected),CPRD_hydrocele.csv,ICD_hydrocele.csv, Hyperkinetic disorders,CPRD_ADHD.csv,ICD_ADHD.csv, Hyperparathyroidism,CPRD_PTH.csv,ICD_PTH.csv, Hyperplasia of prostate,CPRD_BPH.csv,ICD_BPH.csv, Hypertension,CPRD_hypertension.csv,ICD_hypertension.csv, Hypertrophic Cardiomyopathy,CPRD_hocm.csv,ICD_hocm.csv, Hypertrophy of nasal turbinates,CPRD_hyper_nasal_turbs.csv,ICD_hyper_nasal_turbs.csv, Hypo or hyperthyroidism,CPRD_thyroid.csv,ICD_thyroid.csv, Hyposplenism,CPRD_hyposplenism.csv,ICD_hyposplenism.csv, Immunodeficiencies,CPRD_immunodef.csv,ICD_immunodef.csv, Infection of anal and rectal regions,,ICD_anorectal.csv, Infection of bones and joints,,ICD_bone.csv, Infection of liver,,ICD_liver.csv, Infection of male genital system,,ICD_male_GU.csv, Infection of other or unspecified genitourinary system,,ICD_oth_gu.csv, Infection of skin and subcutaneous tissues,,ICD_skin.csv, Infections of Other or unspecified organs,,ICD_oth_organs.csv, Infections of the Heart,,ICD_heart.csv, Infections of the digestive system,,ICD_digestive.csv, Intellectual disability,CPRD_intell_dz.csv,ICD_intell_dz.csv, Intervertebral disc disorders,CPRD_intervert_disc.csv,ICD_intervert_disc.csv,OPCS_intervert_disc.csv Intracerebral haemorrhage,CPRD_Intracereb_haem.csv,ICD_Intracereb_haem.csv, Intracranial hypertension,CPRD_intracranial_htn.csv,ICD_intracranial_htn.csv, Intrauterine hypoxia,CPRD_intrauterine_hypoxia.csv,ICD_intrauterine_hypoxia.csv, Iron deficiency anaemia,CPRD_IDA.csv,ICD_IDA.csv, Irritable bowel syndrome,CPRD_IBS.csv,ICD_IBS.csv, Ischaemic stroke,CPRD_Isch_stroke.csv,ICD_Isch_stroke.csv, Juvenile arthritis,CPRD_juv_arth.csv,ICD_juv_arth.csv, Keratitis,CPRD_keratitis.csv,ICD_keratitis.csv, Left bundle branch block,CPRD_LBBB.csv,ICD_LBBB.csv, Leiomyoma of uterus,CPRD_leiomyoma.csv,ICD_leiomyoma.csv, Leukaemia,CPRD_leukaemia.csv,ICD_leukaemia.csv, Lichen planus,CPRD_lichen_planus.csv,ICD_lichen_planus.csv, "Liver fibrosis, sclerosis and cirrhosis",CPRD_cirrhosis.csv,ICD_cirrhosis.csv, Lower Respiratory Tract Infections,,ICD_lrti.csv, Lupus erythematosus (local and systemic),CPRD_SLE.csv,ICD_SLE.csv, Macular degeneration,CPRD_macula_degen.csv,ICD_macula_degen.csv, Male infertility,CPRD_male_infertility.csv,ICD_male_infertility.csv, Meniere disease,CPRD_meniere.csv,ICD_meniere.csv, Meningitis,,ICD_meningitis.csv, Menorrhagia and polymenorrhoea,CPRD_menorrhagia.csv,ICD_menorrhagia.csv, Migraine,CPRD_migraine.csv,ICD_migraine.csv, Monoclonal gammopathy of undetermined significance (MGUS),CPRD_MGUS.csv,ICD_MGUS.csv, Motor neuron disease,CPRD_MND.csv,ICD_MND.csv, Multiple myeloma and malignant plasma cell neoplasms,CPRD_plasmacell.csv,ICD_plasmacell.csv, Multiple sclerosis,CPRD_MS.csv,ICD_MS.csv, Multiple valve dz,CPRD_mult_valve.csv,ICD_mult_valve.csv, Myasthenia gravis,CPRD_myasthenia.csv,ICD_myasthenia.csv, Mycoses,,ICD_mycoses.csv, Myelodysplastic syndromes,CPRD_MDS.csv,ICD_MDS.csv, Myocardial infarction,CPRD_myocardial_infarction.csv,ICD_myocardial_infarction.csv, Nasal polyp,CPRD_nasal_polyp.csv,ICD_nasal_polyp.csv, Neonatal jaundice (excl haemolytic dz of the newborn),CPRD_neo_jaundice.csv,ICD_neo_jaundice.csv, Neuromuscular dysfunction of bladder,CPRD_neuro_bladder.csv,ICD_neuro_bladder.csv, Non-Hodgkin Lymphoma,CPRD_NHL.csv,ICD_NHL.csv, Non-acute cystitis,CPRD_chr_cystitis.csv,ICD_chr_cystitis.csv, Nonrheumatic aortic valve disorders,CPRD_nonRh_aortic.csv,ICD_nonRh_aortic.csv, Nonrheumatic mitral valve disorders,CPRD_nonRh_mitral.csv,ICD_nonRh_mitral.csv, Obesity,CPRD_obesity.csv,ICD_obesity.csv, Obsessive-compulsive disorder,CPRD_ocd.csv,ICD_ocd.csv, Obstructive and reflux uropathy,CPRD_obstr_reflux.csv,ICD_obstr_reflux.csv, Oesophageal varices,CPRD_varices.csv,ICD_varices.csv,OPCS_varices.csv Oesophagitis and oesophageal ulcer,CPRD_oesoph_ulc.csv,ICD_oesoph_ulc.csv, Osteoarthritis (excl spine),CPRD_OA.csv,ICD_OA.csv, Osteoporosis,CPRD_osteoporosis.csv,ICD_osteoporosis.csv, Other Cardiomyopathy,CPRD_cardiomyo_oth.csv,ICD_cardiomyo_oth.csv, Other anaemias,CPRD_oth_anaemia.csv,ICD_oth_anaemia.csv, Other haemolytic anaemias,CPRD_oth_haem_anaemia.csv,ICD_oth_haem_anaemia.csv, Other interstitial pulmonary diseases with fibrosis,CPRD_pulm_fibrosis.csv,ICD_pulm_fibrosis.csv, Other nervous system infections,,ICD_oth_nerv_sys.csv, Other or unspecified infectious organisms,,ICD_oth_organisms.csv, Other psychoactive substance misuse,CPRD_substance_misuse.csv,ICD_substance_misuse.csv, Pancreatitis,CPRD_pancreatitis.csv,ICD_pancreatitis.csv, Parasitic infections,,ICD_parasitic.csv, Parkinson's disease,CPRD_Parkinsons.csv,ICD_Parkinsons.csv, Patent ductus arteriosus,CPRD_PDA.csv,ICD_PDA.csv,OPCS_PDA.csv Peptic ulcer disease,CPRD_ulcer_peptic.csv,ICD_ulcer_peptic.csv,OPCS_ulcer_peptic.csv Pericardial effusion (noninflammatory),CPRD_pericardial_effusion.csv,ICD_pericardial_effusion.csv, Peripheral arterial disease,CPRD_peripheral_arterial_disease.csv,ICD_peripheral_arterial_disease.csv,OPCS_peripheral_arterial_disease.csv Peripheral neuropathies (excluding cranial nerve and carpal tunnel syndromes),CPRD_periph_neuro.csv,ICD_periph_neuro.csv, Peritonitis,CPRD_peritonitis.csv,ICD_peritonitis.csv,OPCS_peritonitis.csv Personality disorders,CPRD_PD.csv,ICD_PD.csv, Pilonidal cyst/sinus,CPRD_pilonidal.csv,ICD_pilonidal.csv,OPCS_pilonidal.csv Pleural effusion,CPRD_pleural_effusion.csv,ICD_pleural_effusion.csv, Pleural plaque,CPRD_pleural_plaque.csv,ICD_pleural_plaque.csv, Pneumothorax,CPRD_pneumothorax.csv,ICD_pneumothorax.csv, Polycystic ovarian syndrome,CPRD_PCOS.csv,ICD_PCOS.csv, Polycythaemia vera,CPRD_PCV.csv,ICD_PCV.csv, Polymyalgia Rheumatica,CPRD_PMR.csv,ICD_PMR.csv, Portal hypertension,CPRD_portal_htn.csv,ICD_portal_htn.csv, Post-term infant,CPRD_post_term.csv,ICD_post_term.csv, Postcoital and contact bleeding,CPRD_PCB.csv,ICD_PCB.csv, Posterior Uveitis,CPRD_post_uveitis.csv,ICD_post_uveitis.csv, Postinfective and reactive arthropathies,CPRD_reactive.csv,ICD_reactive.csv, Postmenopausal bleeding,CPRD_PMB.csv,ICD_PMB.csv, "Postviral fatigue syndrome, neurasthenia and fibromyalgia",CPRD_chronic_fatigue.csv,ICD_chronic_fatigue.csv, Prematurity,CPRD_prematurity.csv,ICD_prematurity.csv, Primary Malignancy_Bladder,CPRD_pri_bladder.csv,ICD_pri_bladder.csv, Primary Malignancy_Bone and articular cartilage,CPRD_pri_bone.csv,ICD_pri_bone.csv, "Primary Malignancy_Brain, Other CNS and Intracranial",CPRD_pri_brain.csv,ICD_pri_brain.csv, Primary Malignancy_Breast,CPRD_pri_breast.csv,ICD_pri_breast.csv, Primary Malignancy_Cervical,CPRD_pri_cervical.csv,ICD_pri_cervical.csv, Primary Malignancy_Kidney and Ureter,CPRD_pri_kidney.csv,ICD_pri_kidney.csv, Primary Malignancy_Liver,CPRD_pri_liver.csv,ICD_pri_liver.csv, Primary Malignancy_Lung and trachea,CPRD_pri_lung.csv,ICD_pri_lung.csv, Primary Malignancy_Malignant Melanoma,CPRD_pri_melanoma.csv,ICD_pri_melanoma.csv, Primary Malignancy_Mesothelioma,CPRD_pri_mesothelioma.csv,ICD_pri_mesothelioma.csv, Primary Malignancy_Multiple independent sites,CPRD_pri_multindep.csv,ICD_pri_multindep.csv, Primary Malignancy_Oesophageal,CPRD_pri_oesoph.csv,ICD_pri_oesoph.csv, Primary Malignancy_Oro-pharyngeal,CPRD_pri_oroph.csv,ICD_pri_oroph.csv, Primary Malignancy_Other Organs,CPRD_pri_other.csv,ICD_pri_other.csv, Primary Malignancy_Other Skin and subcutaneous tissue,CPRD_pri_skin.csv,ICD_pri_skin.csv, Primary Malignancy_Ovarian,CPRD_pri_ovarian.csv,ICD_pri_ovarian.csv, Primary Malignancy_Pancreatic,CPRD_pri_pancr.csv,ICD_pri_pancr.csv, Primary Malignancy_Prostate,CPRD_pri_prost.csv,ICD_pri_prost.csv, Primary Malignancy_Stomach,CPRD_pri_stomach.csv,ICD_pri_stomach.csv, Primary Malignancy_Testicular,CPRD_pri_testis.csv,ICD_pri_testis.csv, Primary Malignancy_Thyroid,CPRD_pri_thyroid.csv,ICD_pri_thyroid.csv, Primary Malignancy_Uterine,CPRD_pri_uterine.csv,ICD_pri_uterine.csv, Primary Malignancy_biliary tract,CPRD_pri_biliary.csv,ICD_pri_biliary.csv, Primary Malignancy_colorectal and anus,CPRD_pri_bowel.csv,ICD_pri_bowel.csv, Primary or Idiopathic Thrombocytopaenia,CPRD_pri_thrombocytopaenia.csv,ICD_pri_thrombocytopaenia.csv, Primary pulmonary hypertension,CPRD_prim_pulm_htn.csv,ICD_prim_pulm_htn.csv, Psoriasis,CPRD_psoriasis.csv,ICD_psoriasis.csv, Psoriatic arthropathy,CPRD_PSA.csv,ICD_PSA.csv, Ptosis of eyelid,CPRD_ptosis.csv,ICD_ptosis.csv,OPCS_ptosis.csv Pulmonary collapse (excl pneumothorax),CPRD_pulm_collapse.csv,ICD_pulm_collapse.csv, Pulmonary embolism,CPRD_PE.csv,ICD_PE.csv, Raynaud's syndrome,CPRD_raynauds.csv,ICD_raynauds.csv, Respiratory distress of newborn,CPRD_RDN.csv,ICD_RDN.csv, Respiratory failure,CPRD_resp_failure.csv,ICD_resp_failure.csv, Retinal detachments and breaks,CPRD_retinal_detach.csv,ICD_retinal_detach.csv,OPCS_retinal_detach.csv Retinal vascular occlusions,CPRD_retinal_vasc_occl.csv,ICD_retinal_vasc_occl.csv, Rheumatic fever,CPRD_rh_fever.csv,ICD_rh_fever.csv, Rheumatic valve dz,CPRD_Rh_valve.csv,ICD_Rh_valve.csv, Rheumatoid Arthritis,CPRD_RhA.csv,ICD_RhA.csv, Right bundle branch block,CPRD_RBBB.csv,ICD_RBBB.csv, Rosacea,CPRD_rosacea.csv,ICD_rosacea.csv, Sarcoidosis,CPRD_sarcoid.csv,ICD_sarcoid.csv, "Schizophrenia, schizotypal and delusional disorders",CPRD_schizo.csv,ICD_schizo.csv, Scleritis and episcleritis,CPRD_scleritis.csv,ICD_scleritis.csv, Scoliosis,CPRD_scoliosis.csv,ICD_scoliosis.csv, Seborrheic dermatitis,CPRD_seb_derm.csv,ICD_seb_derm.csv, Secondary Malignancy_Adrenal gland,CPRD_sec_adrenal.csv,ICD_sec_adrenal.csv, Secondary Malignancy_Bone,CPRD_sec_bone.csv,ICD_sec_bone.csv, Secondary Malignancy_Bowel,CPRD_sec_bowel.csv,ICD_sec_bowel.csv, "Secondary Malignancy_Brain, Other CNS and Intracranial",CPRD_sec_brain.csv,ICD_sec_brain.csv, Secondary Malignancy_Lung,CPRD_sec_lung.csv,ICD_sec_lung.csv, Secondary Malignancy_Lymph Nodes,CPRD_sec_LN.csv,ICD_sec_LN.csv, Secondary Malignancy_Other organs,CPRD_sec_other.csv,ICD_sec_other.csv, Secondary Malignancy_Pleura,CPRD_sec_pleura.csv,ICD_sec_pleura.csv, Secondary Malignancy_retroperitoneum and peritoneum,CPRD_sec_peritoneum.csv,ICD_sec_peritoneum.csv, Secondary malignancy_Liver and intrahepatic bile duct,CPRD_sec_liver.csv,ICD_sec_liver.csv, Secondary or other Thrombocytopaenia,CPRD_sec_oth_thrombocytopaenia.csv,ICD_sec_oth_thrombocytopaenia.csv, Secondary polycythaemia,CPRD_2ry_polycythaemia.csv,ICD_2ry_polycythaemia.csv, Secondary pulmonary hypertension,CPRD_sec_pulm_htn.csv,ICD_sec_pulm_htn.csv, Septicaemia,,ICD_sepsis.csv, Sick sinus syndrome,CPRD_sick_sinus.csv,ICD_sick_sinus.csv, Sickle-cell anaemia,CPRD_sickle_cell.csv,ICD_sickle_cell.csv, Sickle-cell trait,CPRD_sickle_trait.csv,ICD_sickle_trait.csv, Sjogren's disease,CPRD_sjogren.csv,ICD_sjogren.csv, Sleep apnoea,CPRD_sleep_apnoea.csv,ICD_sleep_apnoea.csv, Slow fetal growth or low birth weight,CPRD_LBW.csv,ICD_LBW.csv, Spina bifida,CPRD_spina_bifida.csv,ICD_spina_bifida.csv,OPCS_spina_bifida.csv Spinal stenosis,CPRD_spinal_stenosis.csv,ICD_spinal_stenosis.csv, Splenomegaly,CPRD_splenomegaly.csv,ICD_splenomegaly.csv, Spondylolisthesis,CPRD_spondylolisthesis.csv,ICD_spondylolisthesis.csv, Spondylosis,CPRD_spondylosis.csv,ICD_spondylosis.csv, Stable angina,CPRD_stable_angina.csv,ICD_stable_angina.csv, Stroke NOS,CPRD_Stroke_NOS.csv,ICD_Stroke_NOS.csv, Subarachnoid haemorrhage,CPRD_Subarach.csv,ICD_Subarach.csv, Subdural haematoma - nontraumatic,CPRD_subdural_haem.csv,ICD_subdural_haem.csv, Supraventricular tachycardia,CPRD_SVT.csv,ICD_SVT.csv, Syndrome of inappropriate secretion of antidiuretic hormone,,ICD_SIADH.csv, Systemic sclerosis,CPRD_sys_sclerosis.csv,ICD_sys_sclerosis.csv, Thalassaemia,CPRD_thala.csv,ICD_thala.csv, Thalassaemia trait,CPRD_thal_trait.csv,ICD_thal_trait.csv, Thrombophilia,CPRD_thrombophilia.csv,ICD_thrombophilia.csv, Tinnitus,CPRD_tinnitus.csv,ICD_tinnitus.csv, Transient ischaemic attack,CPRD_TIA.csv,ICD_TIA.csv, Trifascicular block,CPRD_trifasc_block.csv,ICD_trifasc_block.csv, Trigeminal neuralgia,CPRD_trigem_neur.csv,ICD_trigem_neur.csv, Tuberculosis,CPRD_TB.csv,ICD_TB.csv, Tubulo-interstitial nephritis,CPRD_TIN.csv,ICD_TIN.csv, Ulcerative colitis,CPRD_ulc_colitis.csv,ICD_ulc_colitis.csv, Undescended testicle,CPRD_undescended_testis.csv,ICD_undescended_testis.csv, Unstable Angina,CPRD_unstable_angina.csv,ICD_unstable_angina.csv, Urinary Incontinence,CPRD_urine_incont.csv,ICD_urine_incont.csv, Urinary Tract Infections,,ICD_uti.csv, Urolithiasis,CPRD_urolithiasis.csv,ICD_urolithiasis.csv,OPCS_urolithiasis.csv Urticaria,CPRD_urticaria.csv,ICD_urticaria.csv, Venous thromboembolic disease (Excl PE),CPRD_vte_ex_pe.csv,ICD_vte_ex_pe.csv, Ventricular tachycardia,CPRD_VT.csv,ICD_VT.csv, Viral diseases (excl chronic hepatitis/HIV),,ICD_viral.csv, Visual impairment and blindness,CPRD_blind.csv,ICD_blind.csv, Vitamin B12 deficiency anaemia,CPRD_b12_def.csv,ICD_b12_def.csv, Vitiligo,CPRD_vitiligo.csv,ICD_vitiligo.csv, Volvulus,CPRD_volvulus.csv,ICD_volvulus.csv,OPCS_volvulus.csv Chronic Kidney Disease,,, Low HDL-C,,, Raised LDL-C,,, Raised Total Cholesterol,,, Raised Triglycerides,,,""" import io import pandas as pd dictionary = pd.read_csv(io.StringIO(dictionary)) # COMMAND ---------- # MAGIC %md # MAGIC ## 1.2 Transform to match TRE layout # MAGIC # MAGIC 1. Map `.csv` to TRE tables: # MAGIC 1. Strip `.csv` # MAGIC 2. Add `caliber_` prefix # MAGIC 2. Account for conversion of Read/Med codes -> SNOMED within TRE: # MAGIC 1. Add snomedct column: copy of CPRD with suffix `_snomedct` # MAGIC 2. Phenotype regexps: # MAGIC 1. Strip from phenotypes, as early as possible: # MAGIC 1. Apostrophes/single quotes from phenotype names, e.g. `Crohn's disease` which can cause errors when parameterised into SQL queries # MAGIC 1. Brackets e.g. `Lupus erythematosus (local and systemic)` # MAGIC 2. Commas e.g. `Postviral fatigue syndrome, neurasthenia and fibromyalgia` # MAGIC 3. Ampersand e.g. `Enthesopathies & synovial disorders` # MAGIC 4. Forward slash e.g. `Dermatitis (atopc/contact/other/unspecified)` -> underscore # MAGIC 2. Consistency: # MAGIC 1. lower case # MAGIC 2. whitespace -> underscore # MAGIC 3. Specify database params # MAGIC 1. Add `database` # MAGIC 2. Create full `path` # MAGIC 4. `spark`-ify # MAGIC # MAGIC # MAGIC ### Target: # MAGIC # MAGIC | Phenotype | Terminology | Table | Database | Path | # MAGIC | ----------- | ----------- | # MAGIC | `Abdominal aortic aneurysm` | `SNOMED` | `caliber_cprd_aaa_snomedct` | `bhf_cvd_covid_uk_byod` | `bhf_cvd_covid_uk_byod.caliber_cprd_aaa_snomedct` | # COMMAND ---------- # 1. Map .csv to TRE tables dictionary = dictionary.stack().str.replace('\\.csv', "").unstack() dictionary['SNOMEDCT'] = dictionary['CPRD'].apply(lambda x: "{}{}".format(x, '_snomedct')) dictionary = dictionary.melt(id_vars='phenotype', value_vars=['CPRD', 'ICD', 'OPCS', 'SNOMEDCT'], var_name='terminology', value_name='table') dictionary = dictionary.replace('nan_snomedct', None) dictionary = dictionary.dropna() dictionary['table'] = dictionary['table'].str.lower() dictionary['table'] = dictionary['table'].apply(lambda x: "{}{}".format('caliber_', x)) # 3. Phenotype REGEX dictionary['phenotype'] = dictionary['phenotype'].str.replace("\\'", "") dictionary['phenotype'] = dictionary['phenotype'].str.replace("\\(", "") dictionary['phenotype'] = dictionary['phenotype'].str.replace("\\)", "") dictionary['phenotype']
test_one_arg_encoder(self): import _codecs def search_function(encoding): def encode_one(u): return (b'foo', len(u)) def decode_one(u): return (u'foo', len(u)) if encoding == 'onearg': return (encode_one, decode_one, None, None) return None _codecs.register(search_function) assert u"hello".encode("onearg") == b'foo' assert b"hello".decode("onearg") == u'foo' assert _codecs.encode(u"hello", "onearg") == b'foo' assert _codecs.decode(b"hello", "onearg") == u'foo' def test_cpytest_decode(self): import codecs assert codecs.decode(b'\xe4\xf6\xfc', 'latin-1') == '\xe4\xf6\xfc' raises(TypeError, codecs.decode) assert codecs.decode(b'abc') == 'abc' exc = raises(UnicodeDecodeError, codecs.decode, b'\xff', 'ascii') exc = raises(UnicodeDecodeError, codecs.decode, b'\xe0\x00', 'utf-8') assert 'invalid continuation byte' in exc.value.reason def test_bad_errorhandler_return(self): import codecs def baddecodereturn1(exc): return 42 codecs.register_error("test.baddecodereturn1", baddecodereturn1) raises(TypeError, b"\xff".decode, "ascii", "test.baddecodereturn1") raises(TypeError, b"\\".decode, "unicode-escape", "test.baddecodereturn1") raises(TypeError, b"\\x0".decode, "unicode-escape", "test.baddecodereturn1") raises(TypeError, b"\\x0y".decode, "unicode-escape", "test.baddecodereturn1") raises(TypeError, b"\\Uffffeeee".decode, "unicode-escape", "test.baddecodereturn1") raises(TypeError, b"\\uyyyy".decode, "raw-unicode-escape", "test.baddecodereturn1") def test_cpy_bug1175396(self): import codecs, io s = [ '<%!--===================================================\r\n', ' BLOG index page: show recent articles,\r\n', ' today\'s articles, or articles of a specific date.\r\n', '========================================================--%>\r\n', '<%@inputencoding="ISO-8859-1"%>\r\n', '<%@pagetemplate=TEMPLATE.y%>\r\n', '<%@import=import frog.util, frog%>\r\n', '<%@import=import frog.objects%>\r\n', '<%@import=from frog.storageerrors import StorageError%>\r\n', '<%\r\n', '\r\n', 'import logging\r\n', 'log=logging.getLogger("Snakelets.logger")\r\n', '\r\n', '\r\n', 'user=self.SessionCtx.user\r\n', 'storageEngine=self.SessionCtx.storageEngine\r\n', '\r\n', '\r\n', 'def readArticlesFromDate(date, count=None):\r\n', ' entryids=storageEngine.listBlogEntries(date)\r\n', ' entryids.reverse() # descending\r\n', ' if count:\r\n', ' entryids=entryids[:count]\r\n', ' try:\r\n', ' return [ frog.objects.BlogEntry.load(storageEngine, date, Id) for Id in entryids ]\r\n', ' except StorageError,x:\r\n', ' log.error("Error loading articles: "+str(x))\r\n', ' self.abort("cannot load articles")\r\n', ] stream = io.BytesIO("".join(s).encode("utf7")) assert b"aborrt" not in stream.getvalue() reader = codecs.getreader("utf7")(stream) for (i, line) in enumerate(reader): assert line == s[i] def test_buffer_encode(self): import _codecs, array assert (_codecs.readbuffer_encode(array.array('b', b'spam')) == (b'spam', 4)) assert _codecs.readbuffer_encode(u"test") == (b'test', 4) assert _codecs.readbuffer_encode("") == (b"", 0) def test_utf8sig(self): import codecs d = codecs.getincrementaldecoder("utf-8-sig")() s = "spam" assert d.decode(s.encode("utf-8-sig")) == s def test_incremental_errors(self): # Test that the incremental decoder can fail with final=False. # See bpo #24214 import _codecs for encoding in ('utf-8', 'utf-16'): cases = [b'\x80', b'\xBF', b'\xC0', b'\xC1', b'\xF5', b'\xF6', b'\xFF'] for prefix in (b'\xC2', b'\xDF', b'\xE0', b'\xE0\xA0', b'\xEF', b'\xEF\xBF', b'\xF0', b'\xF0\x90', b'\xF0\x90\x80', b'\xF4', b'\xF4\x8F', b'\xF4\x8F\xBF'): for suffix in b'\x7F', b'\xC0': cases.append(prefix + suffix) cases.extend((b'\xE0\x80', b'\xE0\x9F', b'\xED\xA0\x80', b'\xED\xBF\xBF', b'\xF0\x80', b'\xF0\x8F', b'\xF4\x90')) for data in cases: dec = _codecs.lookup("utf-8").incrementaldecoder() raises(UnicodeDecodeError, dec.decode, data) def test_incremental_surrogatepass(self): # Test incremental decoder for surrogatepass handler: # see bpo #24214 # High surrogate import codecs for encoding in ('utf-8', 'utf-16'): data = u'\uD901'.encode(encoding, 'surrogatepass') for i in range(1, len(data)): dec = codecs.getincrementaldecoder(encoding)('surrogatepass') assert dec.decode(data[:i]) == '' assert dec.decode(data[i:], True) == '\uD901' # Low surrogate data = '\uDC02'.encode(encoding, 'surrogatepass') for i in range(1, len(data)): dec = codecs.getincrementaldecoder(encoding)('surrogatepass') assert dec.decode(data[:i]) == '' assert dec.decode(data[i:], False) == '\uDC02' def test_decoder_state(self): import codecs encoding = 'utf16' u = 'abc123' s = u.encode(encoding) for i in range(len(u) + 1): d = codecs.getincrementalencoder(encoding)() part1 = d.encode(u[:i]) state = d.getstate() d = codecs.getincrementalencoder(encoding)() d.setstate(state) part2 = d.encode(u[i:], True) assert s == part1 + part2 def test_utf_8_decode1(self): import _codecs # 'åäö'.encode('iso-8859-1') utf8 = b'\xe5\xe4\xf6' uval, lgt = _codecs.utf_8_decode(utf8, 'replace') assert lgt == 3 assert [ord(x) for x in uval] == [65533, 65533, 65533] def test_utf_8_decode2(self): import _codecs # issue 3348 utf8 = b'abcdef \xc4' uval, lgt = _codecs.utf_8_decode(utf8, 'ignore', False) assert lgt == 7 def test_escape_decode_escaped_newline(self): import _codecs s = b'\\\n' decoded = _codecs.unicode_escape_decode(s)[0] assert decoded == '' def test_charmap_decode_1(self): import codecs assert codecs.charmap_encode(u'xxx') == (b'xxx', 3) assert codecs.charmap_encode(u'xxx', 'strict', {ord('x'): b'XX'}) == (b'XXXXXX', 3) res = codecs.charmap_decode(b"\x00\x01\x02", "replace", u"ab") assert res == ("ab\ufffd", 3) res = codecs.charmap_decode(b"\x00\x01\x02", "replace", u"ab\ufffe") assert res == ('ab\ufffd', 3) def test_errors(self): import codecs assert codecs.replace_errors(UnicodeEncodeError( "ascii", u"\u3042", 0, 1, "ouch")) == (u"?", 1) assert codecs.replace_errors(UnicodeDecodeError( "ascii", b"\xff", 0, 1, "ouch")) == (u"\ufffd", 1) assert codecs.replace_errors(UnicodeTranslateError( "\u3042", 0, 1, "ouch")) == ("\ufffd", 1) assert codecs.replace_errors(UnicodeEncodeError( "ascii", "\u3042\u3042", 0, 2, "ouch")) == (u"??", 2) assert codecs.replace_errors(UnicodeDecodeError( "ascii", b"\xff\xff", 0, 2, "ouch")) == (u"\ufffd", 2) assert codecs.replace_errors(UnicodeTranslateError( "\u3042\u3042", 0, 2, "ouch")) == ("\ufffd\ufffd", 2) class BadStartUnicodeEncodeError(UnicodeEncodeError): def __init__(self): UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad") self.start = [] # A UnicodeEncodeError object with a bad object attribute class BadObjectUnicodeEncodeError(UnicodeEncodeError): def __init__(self): UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad") self.object = [] # A UnicodeDecodeError object without an end attribute class NoEndUnicodeDecodeError(UnicodeDecodeError): def __init__(self): UnicodeDecodeError.__init__(self, "ascii", b"", 0, 1, "bad") del self.end # A UnicodeDecodeError object with a bad object attribute class BadObjectUnicodeDecodeError(UnicodeDecodeError): def __init__(self): UnicodeDecodeError.__init__(self, "ascii", b"", 0, 1, "bad") self.object = [] # A UnicodeTranslateError object without a start attribute class NoStartUnicodeTranslateError(UnicodeTranslateError): def __init__(self): UnicodeTranslateError.__init__(self, u"", 0, 1, "bad") del self.start # A UnicodeTranslateError object without an end attribute class NoEndUnicodeTranslateError(UnicodeTranslateError): def __init__(self): UnicodeTranslateError.__init__(self, u"", 0, 1, "bad") del self.end # A UnicodeTranslateError object without an object attribute class NoObjectUnicodeTranslateError(UnicodeTranslateError): def __init__(self): UnicodeTranslateError.__init__(self, u"", 0, 1, "bad") del self.object import codecs raises(TypeError, codecs.replace_errors, BadObjectUnicodeEncodeError()) raises(TypeError, codecs.replace_errors, 42) # "replace" complains about the wrong exception type raises(TypeError, codecs.replace_errors, UnicodeError("ouch")) raises(TypeError, codecs.replace_errors, BadObjectUnicodeEncodeError()) raises(TypeError, codecs.replace_errors, BadObjectUnicodeDecodeError() ) # With the correct exception, "replace" returns an "?" or u"\ufffd" replacement def test_decode_ignore(self): assert b'\xff'.decode('utf-7', 'ignore') == '' def test_backslashreplace(self): import sys, codecs sin = u"a\xac\u1234\u20ac\u8000\U0010ffff" if sys.maxunicode > 65535: expected_ascii = b"a\\xac\\u1234\\u20ac\\u8000\\U0010ffff" expected_8859 = b"a\xac\\u1234\xa4\\u8000\\U0010ffff" else: expected_ascii = b"a\\xac\\u1234\\u20ac\\u8000\\udbff\\udfff" expected_8859 = b"a\xac\\u1234\xa4\\u8000\\udbff\\udfff" assert sin.encode('ascii', 'backslashreplace') == expected_ascii assert sin.encode("iso-8859-15", "backslashreplace") == expected_8859 assert 'a\xac\u1234\u20ac\u8000'.encode('ascii', 'backslashreplace') == b'a\\xac\u1234\u20ac\u8000' assert b'\x00\x60\x80'.decode( 'ascii', 'backslashreplace') == u'\x00\x60\\x80' assert codecs.charmap_decode( b"\x00\x01\x02", "backslashreplace", "ab") == ("ab\\x02", 3) def test_namereplace(self): assert 'a\xac\u1234\u20ac\u8000'.encode('ascii', 'namereplace') == ( b'a\\N{NOT SIGN}\\N{ETHIOPIC SYLLABLE SEE}\\N{EURO SIGN}' b'\\N{CJK UNIFIED IDEOGRAPH-8000}') assert '[\uDC80]'.encode('utf-8', 'namereplace') == b'[\\udc80]' def test_surrogateescape(self): uni = b"\xed\xb0\x80".decode("utf-8", "surrogateescape") assert uni == "\udced\udcb0\udc80" assert "\udce4\udceb\udcef\udcf6\udcfc".encode("latin-1", "surrogateescape") == b"\xe4\xeb\xef\xf6\xfc" assert b'a\x80b'.decode('utf-8', 'surrogateescape') == 'a\udc80b' assert 'a\udc80b'.encode('utf-8', 'surrogateescape') == b'a\x80b' for enc in ('utf-8', 'ascii', 'latin-1', 'charmap'): assert '\udcc3'.encode(enc, 'surrogateescape') == b'\xc3' def test_surrogatepass_handler(self): import _codecs assert _codecs.lookup_error("surrogatepass") assert ("abc\ud800def".encode("utf-8", "surrogatepass") == b"abc\xed\xa0\x80def") assert (b"abc\xed\xa0\x80def".decode("utf-8", "surrogatepass") == "abc\ud800def") assert ('surrogate:\udcff'.encode("utf-8", "surrogatepass") == b'surrogate:\xed\xb3\xbf') assert (b'surrogate:\xed\xb3\xbf'.decode("utf-8", "surrogatepass") == 'surrogate:\udcff') raises(UnicodeDecodeError, b"abc\xed\xa0".decode, "utf-8", "surrogatepass") raises(UnicodeDecodeError, b"abc\xed\xa0z".decode, "utf-8", "surrogatepass") assert u'\ud8ae'.encode('utf_16_be', 'surrogatepass') == b'\xd8\xae' assert (u'\U0000d8ae'.encode('utf-32-be', 'surrogatepass') == b'\x00\x00\xd8\xae') assert (u'\x80\ud800'.encode('utf8', 'surrogatepass') == b'\xc2\x80\xed\xa0\x80') assert b'\xd8\x03\xdf\xff\xdc\x80\x00A'.decode('utf_16_be', 'surrogatepass') == u'\U00010fff\udc80A' def test_badandgoodsurrogatepassexceptions(self): import codecs surrogatepass_errors = codecs.lookup_error('surrogatepass') # "surrogatepass" complains about a non-exception passed in raises(TypeError, surrogatepass_errors, 42) # "surrogatepass" complains about the wrong exception types raises(TypeError, surrogatepass_errors, UnicodeError("ouch")) # "surrogatepass" can not be used for translating raises(TypeError, surrogatepass_errors, UnicodeTranslateError("\ud800", 0, 1, "ouch")) # Use the correct exception for enc in ("utf-8", "utf-16le", "utf-16be", "utf-32le", "utf-32be"): raises(UnicodeEncodeError, surrogatepass_errors, UnicodeEncodeError(enc, "a", 0, 1, "ouch")) raises(UnicodeDecodeError, surrogatepass_errors, UnicodeDecodeError(enc, "a".encode(enc), 0, 1, "ouch")) for s in ("\ud800", "\udfff", "\ud800\udfff"): raises(UnicodeEncodeError, surrogatepass_errors, UnicodeEncodeError("ascii", s, 0, len(s), "ouch")) tests = [ ("utf-8", "\ud800", b'\xed\xa0\x80', 3), ("utf-16le", "\ud800", b'\x00\xd8', 2), ("utf-16be", "\ud800", b'\xd8\x00', 2), ("utf-32le", "\ud800", b'\x00\xd8\x00\x00', 4), ("utf-32be", "\ud800", b'\x00\x00\xd8\x00', 4), ("utf-8", "\udfff", b'\xed\xbf\xbf', 3), ("utf-16le", "\udfff", b'\xff\xdf', 2), ("utf-16be", "\udfff", b'\xdf\xff', 2), ("utf-32le", "\udfff", b'\xff\xdf\x00\x00', 4), ("utf-32be", "\udfff", b'\x00\x00\xdf\xff', 4), ("utf-8", "\ud800\udfff", b'\xed\xa0\x80\xed\xbf\xbf', 3), ("utf-16le", "\ud800\udfff", b'\x00\xd8\xff\xdf', 2), ("utf-16be", "\ud800\udfff", b'\xd8\x00\xdf\xff', 2), ("utf-32le", "\ud800\udfff", b'\x00\xd8\x00\x00\xff\xdf\x00\x00', 4), ("utf-32be", "\ud800\udfff", b'\x00\x00\xd8\x00\x00\x00\xdf\xff', 4), ] for enc, s, b, n in tests: assert surrogatepass_errors( UnicodeEncodeError(enc, "a" + s + "b", 1, 1 + len(s), "ouch") ) == (b, 1 + len(s)) assert surrogatepass_errors( UnicodeDecodeError(enc, bytearray(b"a" + b[:n] + b"b"), 1, 1 + n, "ouch") ) == (s[:1], 1 + n) def test_badhandler(self): import codecs results = ( 42, u"foo", (1,2,3), (u"foo", 1, 3), (u"foo", None), (u"foo",), ("foo", 1, 3), ("foo", None), ("foo",) ) encs = ("ascii", "latin-1", "iso-8859-1", "iso-8859-15") for res in results: codecs.register_error("test.badhandler", lambda x: res) for enc in encs: raises( TypeError, "\u3042".encode, enc, "test.badhandler" ) for (enc, bytes) in ( ("utf-8", b"\xff"), ("ascii", b"\xff"), ("utf-7", b"+x-"), ): raises( TypeError, bytes.decode, enc, "test.badhandler" ) def test_badhandler_longindex(self): import codecs import sys errors = 'test.badhandler_longindex' codecs.register_error(errors, lambda x: (u'', sys.maxsize + 1)) # CPython raises OverflowError here raises((IndexError, OverflowError), b'apple\x92ham\x93spam'.decode, 'utf-8', errors) def test_badhandler_returns_unicode(self): import codecs import sys errors = 'test.badhandler_unicode' codecs.register_error(errors, lambda x: (chr(100000), x.end)) # CPython raises OverflowError here raises(UnicodeEncodeError, u'\udc80\ud800\udfff'.encode, 'utf-8', errors) def test_encode_error_bad_handler(self): import codecs codecs.register_error("test.bad_handler", lambda e: (repl, 1)) assert u"xyz".encode("latin-1", "test.bad_handler") == b"xyz" repl = u"\u1234" raises(UnicodeEncodeError, u"\u5678".encode, "latin-1", "test.bad_handler") repl = u"\u00E9" s = u"\u5678".encode("latin-1", "test.bad_handler") assert s ==
self.assertEqual(b.shape[2], a.shape[1]) self.assertEqual(b.shape[3], a.shape[2]) self.assertEqual(b.lshape[0], a.shape[0]) self.assertEqual(b.lshape[1], 1) self.assertEqual(b.lshape[2], a.shape[1]) self.assertLessEqual(b.lshape[3], a.shape[2]) self.assertIs(b.split, 3) # exceptions with self.assertRaises(TypeError): ht.expand_dims("(3, 4, 5,)", 1) with self.assertRaises(TypeError): ht.empty((3, 4, 5)).expand_dims("1") with self.assertRaises(ValueError): ht.empty((3, 4, 5)).expand_dims(4) with self.assertRaises(ValueError): ht.empty((3, 4, 5)).expand_dims(-5) def test_flatten(self): a = ht.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) res = ht.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=a.dtype) self.assertTrue(ht.equal(ht.flatten(a), res)) self.assertEqual(a.dtype, res.dtype) self.assertEqual(a.device, res.device) a = ht.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], split=0, dtype=ht.int8) res = ht.array([1, 2, 3, 4, 5, 6, 7, 8], split=0, dtype=ht.int8) self.assertTrue(ht.equal(ht.flatten(a), res)) self.assertEqual(a.dtype, res.dtype) self.assertEqual(a.device, res.device) a = ht.array([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]], split=1) res = ht.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], split=0) self.assertTrue(ht.equal(ht.flatten(a), res)) self.assertEqual(a.dtype, res.dtype) self.assertEqual(a.device, res.device) a = ht.array( [[[False, False], [False, True]], [[True, False], [True, True]]], split=2, dtype=ht.bool ) res = ht.array([False, False, False, True, True, False, True, True], split=0, dtype=a.dtype) self.assertTrue(ht.equal(ht.flatten(a), res)) self.assertEqual(a.dtype, res.dtype) self.assertEqual(a.device, res.device) def test_flip(self): a = ht.array([1, 2]) r_a = ht.array([2, 1]) self.assertTrue(ht.equal(ht.flip(a, 0), r_a)) a = ht.array([[1, 2], [3, 4]]) r_a = ht.array([[4, 3], [2, 1]]) self.assertTrue(ht.equal(ht.flip(a), r_a)) a = ht.array([[2, 3], [4, 5], [6, 7], [8, 9]], split=1, dtype=ht.float32) r_a = ht.array([[9, 8], [7, 6], [5, 4], [3, 2]], split=1, dtype=ht.float32) self.assertTrue(ht.equal(ht.flip(a, [0, 1]), r_a)) a = ht.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]], split=0, dtype=ht.uint8) r_a = ht.array([[[3, 2], [1, 0]], [[7, 6], [5, 4]]], split=0, dtype=ht.uint8) self.assertTrue(ht.equal(ht.flip(a, [1, 2]), r_a)) def test_fliplr(self): b = ht.array([[1, 2], [3, 4]]) r_b = ht.array([[2, 1], [4, 3]]) self.assertTrue(ht.equal(ht.fliplr(b), r_b)) # splitted c = ht.array( [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]], [[12, 13], [14, 15]]], split=0 ) r_c = ht.array( [[[2, 3], [0, 1]], [[6, 7], [4, 5]], [[10, 11], [8, 9]], [[14, 15], [12, 13]]], split=0 ) self.assertTrue(ht.equal(ht.fliplr(c), r_c)) c = ht.array( [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]], [[12, 13], [14, 15]]], split=1, dtype=ht.float32, ) self.assertTrue(ht.equal(ht.resplit(ht.fliplr(c), 0), r_c)) c = ht.array( [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]], [[12, 13], [14, 15]]], split=2, dtype=ht.int8, ) self.assertTrue(ht.equal(ht.resplit(ht.fliplr(c), 0), r_c)) # test exception a = ht.arange(10) with self.assertRaises(IndexError): ht.fliplr(a) def test_flipud(self): a = ht.array([1, 2]) r_a = ht.array([2, 1]) self.assertTrue(ht.equal(ht.flipud(a), r_a)) b = ht.array([[1, 2], [3, 4]]) r_b = ht.array([[3, 4], [1, 2]]) self.assertTrue(ht.equal(ht.flipud(b), r_b)) # splitted c = ht.array( [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]], [[12, 13], [14, 15]]], split=0 ) r_c = ht.array( [[[12, 13], [14, 15]], [[8, 9], [10, 11]], [[4, 5], [6, 7]], [[0, 1], [2, 3]]], split=0 ) self.assertTrue(ht.equal(ht.flipud(c), r_c)) c = ht.array( [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]], [[12, 13], [14, 15]]], split=1, dtype=ht.float32, ) self.assertTrue(ht.equal(ht.resplit(ht.flipud(c), 0), r_c)) c = ht.array( [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]], [[12, 13], [14, 15]]], split=2, dtype=ht.int8, ) self.assertTrue(ht.equal(ht.resplit(ht.flipud(c), 0), r_c)) def test_hsplit(self): # for further testing, see test_split # 1-dimensional array (as forbidden in split) data_ht = ht.arange(24) data_np = data_ht.numpy() # indices_or_sections = int result = ht.hsplit(data_ht, 2) comparison = np.hsplit(data_np, 2) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) # indices_or_sections = tuple result = ht.hsplit(data_ht, (0, 1)) comparison = np.hsplit(data_np, (0, 1)) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) # indices_or_sections = list result = ht.hsplit(data_ht, [0, 1]) comparison = np.hsplit(data_np, [0, 1]) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) # indices_or_sections = undistributed DNDarray result = ht.hsplit(data_ht, ht.array([0, 1])) comparison = np.hsplit(data_np, np.array([0, 1])) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) # indices_or_sections = distributed DNDarray result = ht.hsplit(data_ht, ht.array([0, 1], split=0)) comparison = np.hsplit(data_np, np.array([0, 1])) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) data_ht = ht.arange(24).reshape((2, 4, 3)) data_np = data_ht.numpy() # indices_or_sections = int result = ht.hsplit(data_ht, 2) comparison = np.hsplit(data_np, 2) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) # indices_or_sections = tuple result = ht.hsplit(data_ht, (0, 1)) comparison = np.hsplit(data_np, (0, 1)) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) # indices_or_sections = list result = ht.hsplit(data_ht, [0, 1]) comparison = np.hsplit(data_np, [0, 1]) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) # indices_or_sections = undistributed DNDarray result = ht.hsplit(data_ht, ht.array([0, 1])) comparison = np.hsplit(data_np, np.array([0, 1])) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) # indices_or_sections = distributed DNDarray result = ht.hsplit(data_ht, ht.array([0, 1], split=0)) comparison = np.hsplit(data_np, np.array([0, 1])) self.assertTrue(len(result) == len(comparison)) for i in range(len(result)): self.assertIsInstance(result[i], ht.DNDarray) self.assert_array_equal(result[i], comparison[i]) def test_hstack(self): # cases to test: # MM=================================== # NN, a = ht.ones((10, 12), split=None) b = ht.ones((10, 12), split=None) res = ht.hstack((a, b)) self.assertEqual(res.shape, (10, 24)) # 11, a = ht.ones((10, 12), split=1) b = ht.ones((10, 12), split=1) res = ht.hstack((a, b)) self.assertEqual(res.shape, (10, 24)) # VM=================================== # NN, a = ht.ones((12,), split=None) b = ht.ones((12, 10), split=None) res = ht.hstack((a, b)) self.assertEqual(res.shape, (12, 11)) # 00 a = ht.ones((12,), split=0) b = ht.ones((12, 10), split=0) res = ht.hstack((a, b)) self.assertEqual(res.shape, (12, 11)) # MV=================================== # NN, a = ht.ones((12, 10), split=None) b = ht.ones((12,), split=None) res = ht.hstack((a, b)) self.assertEqual(res.shape, (12, 11)) # 00 a = ht.ones((12, 10), split=0) b = ht.ones((12,), split=0) res = ht.hstack((a, b)) self.assertEqual(res.shape, (12, 11)) # VV=================================== # NN, a = ht.ones((12,), split=None) b = ht.ones((12,), split=None) res = ht.hstack((a, b)) self.assertEqual(res.shape, (24,)) # 00 a = ht.ones((12,), split=0) b = ht.ones((12,), split=0) res = ht.hstack((a, b)) self.assertEqual(res.shape, (24,)) def test_pad(self): # ====================================== # test padding of non-distributed tensor # ====================================== data = torch.arange(2 * 3 * 4, device=self.device.torch_device).reshape(2, 3, 4) data_ht = ht.array(data, device=self.device) data_np = data_ht.numpy() # padding with default (0 for all dimensions) pad_torch = torch.nn.functional.pad(data, (1, 2, 1, 0, 2, 1)) pad_ht = ht.pad(data_ht, pad_width=((2, 1), (1, 0), (1, 2))) self.assert_array_equal(pad_ht, pad_torch) self.assertIsInstance(pad_ht, ht.DNDarray) # padding with other values than default pad_numpy = np.pad( data_np, pad_width=((2, 1), (1, 0), (1, 2)), mode="constant", constant_values=((0, 3), (1, 4), (2, 5)), ) pad_ht = ht.pad( data_ht, pad_width=((2, 1), (1, 0), (1, 2)), mode="constant", constant_values=((0, 3), (1, 4), (2, 5)), ) self.assert_array_equal(pad_ht, pad_numpy) # shortcuts pad_width=================================== pad_numpy = np.pad( data_np, pad_width=((2, 1),), mode="constant", constant_values=((0, 3), (1, 4), (2, 5)) ) pad_ht = ht.pad( data_ht, pad_width=((2, 1),), mode="constant", constant_values=((0, 3), (1, 4), (2, 5)) ) self.assert_array_equal(pad_ht, pad_numpy) pad_numpy = np.pad( data_np, pad_width=(2, 1), mode="constant", constant_values=((0, 3), (1, 4), (2, 5)) ) pad_ht = ht.pad( data_ht, pad_width=(2, 1), mode="constant", constant_values=((0, 3), (1, 4), (2, 5)) ) self.assert_array_equal(pad_ht, pad_numpy) pad_numpy = np.pad( data_np, pad_width=(2,), mode="constant", constant_values=((0, 3), (1, 4), (2, 5)) ) pad_ht = ht.pad( data_ht, pad_width=(2,), mode="constant", constant_values=((0, 3), (1, 4), (2, 5)) ) self.assert_array_equal(pad_ht, pad_numpy) pad_numpy = np.pad( data_np, pad_width=2, mode="constant", constant_values=((0, 3), (1, 4), (2, 5)) ) pad_ht = ht.pad( data_ht, pad_width=2, mode="constant", constant_values=((0, 3), (1, 4), (2, 5)) ) self.assert_array_equal(pad_ht, pad_numpy) # pad_width datatype list=================================== # padding with default (0 for all dimensions) pad_torch = torch.nn.functional.pad(data, (1, 2, 1, 0, 2, 1)) pad_ht = ht.pad(data_ht, pad_width=((2, 1), [1, 0], [1, 2])) self.assert_array_equal(pad_ht, pad_torch) # padding with other values than default pad_numpy = np.pad( data_np, pad_width=((2, 1), (1, 0), (1, 2)), mode="constant", constant_values=((0, 3), (1, 4), (2, 5)), ) pad_ht = ht.pad( data_ht, pad_width=[(2, 1), (1, 0), (1, 2)], mode="constant", constant_values=((0, 3), (1, 4), (2, 5)), ) self.assert_array_equal(pad_ht, pad_numpy) # shortcuts constant_values=================================== pad_numpy = np.pad( data_np, pad_width=((2, 1), (1, 0), (1, 2)), mode="constant", constant_values=((0, 3),) ) pad_ht = ht.pad( data_ht, pad_width=((2, 1), (1, 0), (1, 2)), mode="constant", constant_values=((0, 3),) ) self.assert_array_equal(pad_ht, pad_numpy) pad_numpy = np.pad( data_np, pad_width=((2, 1), (1, 0), (1, 2)), mode="constant", constant_values=(0, 3) ) pad_ht = ht.pad( data_ht, pad_width=((2, 1), (1, 0), (1, 2)), mode="constant", constant_values=(0, 3) )
#!/usr/bin/env python # -*- coding: utf-8 -*- ## Project: Simple4All - January 2013 - www.simple4all.org ## Contact: <NAME> - <EMAIL> ## Contact: <NAME> - <EMAIL> import sys import os import re from util.xpath_extensions_for_ossian import * ## These imports now handled by xpath_extensions_for_ossian:-- # import lxml # from lxml import etree # from lxml.etree import * import numpy from naive.naive_util import * ## now includes helper functions: fix_data_type, final_attribute_name from util.speech_manip import get_speech, spline_smooth_fzero import util.acoustic_stats as ac_stats import default.const as c # See http://lxml.de/1.3/element_classes.html on using custom Element classes: # -- can't have an __init__ for UtteranceElement(etree.ElementBase) or any # subclass of etree.ElementBase. from distutils.spawn import find_executable # to check if required executables are available class UtteranceElement(etree.ElementBase): """ Specialised Element class for utterances, has safe_xpath method. See here: http://lxml.de/1.3/element_classes.html on using custom Element classes """ def safe_xpath(self, path, default_value='_NA_'): """ Provide padding for e.g. end-of-sentence contexts if xpath doesn't find anything. In order to handle different padding types (e.g. mean vector for VSM features). The default padding is _NA_ -- this will be used for e.g. end-of-sentence phone contexts. For count based features, xpath gives 0 in sentence-edge positions, which is fine. """ try: if type(path) == XPath: ## precompiled xpath data = path(self) else: data = self.xpath(path) ## string representation of xpath except lxml.etree.XPathEvalError: sys.exit('Problem evaluating this XPATH: ' + path) if data == []: ## Xpath found nothing, so now try looking for _PADDING for this attribute : attribute_name = final_attribute_name(path) # print 'ancestor::utt[1]/attribute::%s_PADDING'%(attribute_name) data = self.xpath('ancestor::utt[1]/attribute::%s_PADDING' % (attribute_name)) if data == []: ## No padding attribute was found, use the default _NA_: data = [default_value] ## Data should be either a float (from count() xpath) or boolean assert type(data) in [list, float, bool] ## or else a list with single entry: if type(data) == list: assert type(data) == list assert len(data) == 1 # Take that single entry: data = data[0] ## convert it to an integer if possible, else ## to a string (otherwise class of returned data is: <class ## 'lxml.etree._ElementStringResult'>): data = fix_data_type(data) return data def get_context_vector(self, context_list): """ Get values for list of contexts at an utterance node. :param context_list: e.g.: [('name1', 'xpath1'), ('name2', 'xpath2'), ... ] :return: vector of features made by concatenating the output of calls to xpath on this node. Return list of items like ((name1, value1), (name2, value2), ... ) """ return [(name, self.safe_xpath(path)) for (name, path) in context_list] def get_context_dict(self, context_list): """ Get dict of features made by concatenatting the output of calls to xpath on this node. Return dict like {feature_name: feature_value, ... } """ data = dict([(name, self.safe_xpath(path)) for \ (name, path) in context_list]) assert len(context_list) == len( data), "Problem with context list: are there duplicate feature names? These should be unique" return data def has_attribute(self, attribute): return (attribute in self.attrib) def has_children(self): """Does this UtteranceElement have any child nodes?""" return bool(sum([1 for child in self])) def pretty_print(self): print tostring(ElementTree(self), pretty_print=True) def utterance(self): """Get the top-level utterance node of an ``UtteranceElement``.""" utt = self.xpath("ancestor::utt") assert len(utt) == 1 ## node must only have 1 utt return utt[0] def add_child(self, child_node): """Add child to utterance node.""" self.append(child_node) def remove_children(self): """Remove any child nodes this UtteranceElement has""" for child in self: self.remove(child) # NB: The following lines need to be in this location (i.e. between the definitions of # UtteranceElement and Utterance) # ## See http://lxml.de/1.3/element_classes.html --- ## "If you use a parser at the module level, you can easily redirect a module ## level Element() factory to the parser method by adding code like this:" MODULE_PARSER = etree.XMLParser() lookup = etree.ElementDefaultClassLookup(element=UtteranceElement) MODULE_PARSER.setElementClassLookup(lookup) Element = MODULE_PARSER.makeelement class Utterance(object): """ -self.data holds xml structure of the utterance. .. warning:: external data? see add_external_data """ def __init__(self, string, data_type=None, speech_file=None, utterance_location=None, \ speech_location=None, check_single_text_line=True): """ There are 3 modes by which utterances can be initialised: - ``txt`` mode, in which ``string`` argument treated as file containing text of utterance - ``utt``mode, in which ``string`` argument treated as file containing existing XML structure of utterance - ``str``mode, in which ``string`` argument treated as text of the utterance to be initiliased. :param string: if ``string`` is the name of an existing file, choose initialisation mode ``txt`` or ``utt`` based on its extension. If not a filename, use ``str`` mode. :keyword data_type: use this to manually specify mode: must be ``txt``, ``utt`` or ``str``. :keyword speech_file: if given, is assumed to point to file containing natural waveform of utterance -- ``waveform`` attribute added to utterance structure. :keyword utterance_location: **XXX** :keyword speech_location: **XXX** :keyword check_single_text_line: **XXX** .. warning:: UPDATE f utt_location is not None, utt filename is assumed to be relative to this, and only partial path is stored in utt structure. .. warning:: UPDATE If speech_location is not None, speech_file is assumed to be relative to this, and only partial path is stored in utt structure. """ ## These paths are free to change between sessions -- don't hardcode in config or utt structure: self.utterance_location = utterance_location self.speech_location = speech_location self.acoustic_features = None # First set data_type if none is specified: if data_type == None: try: ## non-ascii characters in string is_a_filename = os.path.isfile(string) except: is_a_filename = False if is_a_filename: if string.endswith('.txt'): data_type = 'txt' elif string.endswith('.utt'): data_type = 'utt' else: sys.exit('Unknown file extension for initialising an utterance: %s' % (string[-4:])) else: data_type = 'str' if data_type not in ['str', 'txt', 'utt']: sys.exit('Data type %s for initialising utterance is unrecognised' % (data_type)) # Now use the data_type to initialise the utterance in the right way: if data_type == 'utt': ## Set the UtteranceElement Element as a default element class ## (http://lxml.de/element_classes.html): parser_lookup = etree.ElementDefaultClassLookup(element=UtteranceElement) ## Ensure pretty printing ## (http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output): parser = XMLParser(remove_blank_text=True) parser.set_element_class_lookup(parser_lookup) tree = parse(string, parser) self.data = tree.getroot() # if "utterance_location" not in dir(self): location, name = os.path.split(string) self.utterance_location = location if not self.has_attribute("utterance_name"): self.data.set("utterance_name", get_basename(string)) elif data_type == 'txt': text = readlist(string) """.. todo:: ever really necessary to check single line when init'ing utterance from text?""" if check_single_text_line: if len(text) != 1: sys.exit( 'Cannot initialise an utterance from a text file with mutliple lines: %s' % (''.join(text))) string_data = text[0] else: string_data = ' '.join(text) self.make_from_string(string_data, speech_file=speech_file) try: self.data.set("utterance_name", get_basename(string)) except ValueError: print '---' print string print get_basename(string) print '---' sys.exit("Couldn't set utterance name") elif data_type == 'str': self.make_from_string(string, speech_file=speech_file) else: print 'Data type %s for initialising utterance is unrecognised' % (data_type) ## reroute attributes from self.data -> self self.attrib = self.data.attrib def make_from_string(self, string, speech_file=None): """Instantiate an utterance from the a string representing the utterance's text""" self.data = Element("utt") ## encoding="utf-8") self.data.attrib["text"] = string self.data.set("status", "OK") ## OK means use it -- change this if the utt is to be held out if speech_file != None: self.data.set("waveform", speech_file) def get_dirname(self, file_type): """ Get the default name for a filetype directory from an utterance's "utterance_filename". If utterance_filename is ``<PATH>/utt/name.utt`` the dirname for type lab will be ``<PATH>/lab/``. Make the directory if it does not exist already. """ utt_fname = self.get_utterance_filename() (utt_dir, fname) = os.path.split(utt_fname) (corpus_dir, utt_dir_name) = os.path.split(utt_dir) assert utt_dir_name == "utt" dirname = os.path.join(corpus_dir, file_type) if not os.path.isdir(dirname): os.mkdir(dirname) return dirname def get_utterance_filename(self): """ Get the absolute path of the utt file where this structure is stored. Absolute paths are not stored directly in the structure so that files are portable. """ assert self.utterance_location, "No utterance_location defined for utt -- initialise with utterance_location kw arg" assert self.has_attribute("utterance_name") return os.path.join(self.utterance_location, self.get("utterance_name") + ".utt") def get_filename(self, file_type): """ Get the default name for a filetype from an utterance's ``utterance_filename``. If utterance_filename is ``<PATH>/utt/name.utt`` the filename for type lab will be ``<PATH>/lab/name.lab``. """ direc = self.get_dirname(file_type) base = get_basename(self.get_utterance_filename()) absolute = os.path.join(direc, base + "." + file_type) return absolute ###### This (add_external_data) is not in use -- currently filename for new data is got by get_filename. ###### The data is not explicitly attached to the utt
not False) \ and include_derivs_dataset_description: self._download_derivative_descriptions( include_derivs, directory) results = [delayed(sub.download)( directory=directory, include_derivs=include_derivs, suffix=suffix, overwrite=overwrite, pbar=pbar, pbar_idx=idx, ) for idx, sub in enumerate(self.subjects)] compute(*results, scheduler='threads') class HBNSite(S3BIDSStudy): """An HBN study site See Also -------- AFQ.data.S3BIDSStudy """ def __init__(self, site, study_id='HBN', bucket='fcp-indi', s3_prefix='data/Projects/HBN/MRI', subjects=None, use_participants_tsv=False, random_seed=None): """Initialize the HBN site Parameters ---------- site : ["Site-SI", "Site-RU", "Site-CBIC", "Site-CUNY"] The HBN site study_id : str An identifier string for the site bucket : str The S3 bucket that contains the study data s3_prefix : str The S3 prefix common to all of the study objects on S3 subjects : str, sequence(str), int, or None If int, retrieve S3 keys for the first `subjects` subjects. If "all", retrieve all subjects. If str or sequence of strings, retrieve S3 keys for the specified subjects. If None, retrieve S3 keys for the first subject. Default: None use_participants_tsv : bool If True, use the particpants tsv files to retrieve subject identifiers. This is faster but may not catch all subjects. Sometimes the tsv files are outdated. Default: False random_seed : int or None Random seed for selection of subjects if `subjects` is an integer. Use the same random seed for reproducibility. Default: None """ valid_sites = ["Site-SI", "Site-RU", "Site-CBIC", "Site-CUNY"] if site not in valid_sites: raise ValueError( "site must be one of {}.".format(valid_sites) ) self._site = site super().__init__( study_id=study_id, bucket=bucket, s3_prefix='/'.join([s3_prefix, site]), subjects=subjects, use_participants_tsv=use_participants_tsv, random_seed=random_seed, _subject_class=HBNSubject ) @property def site(self): """The HBN site""" return self._site def _get_subject(self, subject_id): """Return a Subject instance from a subject-ID""" return self._subject_class(subject_id=subject_id, study=self, site=self.site) def _get_derivative_types(self): """Return a list of available derivatives pipelines The HBN dataset is not BIDS compliant so to go a list of available derivatives, we must peak inside every directory in `derivatives/sub-XXXX/` Returns ------- list list of available derivatives pipelines """ s3_prefix = '/'.join([self.bucket, self.s3_prefix]).rstrip("/") nonsub_keys = _ls_s3fs(s3_prefix=s3_prefix, anon=self.anon)['other'] derivatives_prefix = '/'.join([s3_prefix, 'derivatives']) if any([derivatives_prefix in key for key in nonsub_keys]): deriv_subs = _ls_s3fs( s3_prefix=derivatives_prefix, anon=self.anon )['subjects'] deriv_types = [] for sub_key in deriv_subs: deriv_types += [ s.split(sub_key)[-1].lstrip('/') for s in _ls_s3fs( s3_prefix=sub_key, anon=self.anon )['subjects'] ] return list(set(deriv_types)) else: return [] def _get_non_subject_s3_keys(self): """Return a list of 'non-subject' files In this context, a 'non-subject' file is any file or directory that is not a subject ID folder. This method is different from AFQ.data.S3BIDSStudy because the HBN dataset is not BIDS compliant Returns ------- dict dict with keys 'raw' and 'derivatives' and whose values are lists of S3 keys for non-subject files See Also -------- AFQ.data.S3BIDSStudy._get_non_subject_s3_keys """ non_sub_s3_keys = {} s3_prefix = '/'.join([self.bucket, self.s3_prefix]).rstrip("/") nonsub_keys = _ls_s3fs(s3_prefix=s3_prefix, anon=self.anon)['other'] nonsub_keys = [k for k in nonsub_keys if not k.endswith('derivatives')] nonsub_deriv_keys = _ls_s3fs( s3_prefix='/'.join([ self.bucket, self.s3_prefix, 'derivatives' ]), anon=self.anon )['other'] non_sub_s3_keys = { 'raw': nonsub_keys, 'derivatives': nonsub_deriv_keys, } return non_sub_s3_keys def download(self, directory, include_modality_agnostic=False, include_derivs=False, overwrite=False, pbar=True): """Download files for each subject in the study Parameters ---------- directory : str Directory to which to download subject files include_modality_agnostic : bool, "all" or any subset of ["dataset_description.json", "CHANGES", "README", "LICENSE"] If True or "all", download all keys in self.non_sub_s3_keys also. If a subset of ["dataset_description.json", "CHANGES", "README", "LICENSE"], download only those files. This is useful if the non_sub_s3_keys contain files common to all subjects that should be inherited. Default: False include_derivs : bool or str If True, download all derivatives files. If False, do not. If a string or sequence of strings is passed, this will only download derivatives that match the string(s) (e.g. ["dmriprep", "afq"]). Default: False overwrite : bool If True, overwrite files for each subject. Default: False pbar : bool If True, include progress bar. Default: True See Also -------- AFQ.data.S3BIDSSubject.download """ super().download( directory=directory, include_modality_agnostic=include_modality_agnostic, include_derivs=include_derivs, overwrite=overwrite, pbar=pbar ) to_bids_description( directory, **{"BIDSVersion": "1.0.0", "Name": "HBN Study, " + self.site, "DatasetType": "raw", "Subjects": [s.subject_id for s in self.subjects]}) # +--------------------------------------------------+ # | End S3BIDSStudy classes and supporting functions | # +--------------------------------------------------+ def fetch_hcp(subjects, hcp_bucket='hcp-openaccess', profile_name="hcp", path=None, study='HCP_1200', aws_access_key_id=None, aws_secret_access_key=None): """ Fetch HCP diffusion data and arrange it in a manner that resembles the BIDS [1]_ specification. Parameters ---------- subjects : list Each item is an integer, identifying one of the HCP subjects hcp_bucket : string, optional The name of the HCP S3 bucket. Default: "hcp-openaccess" profile_name : string, optional The name of the AWS profile used for access. Default: "hcp" path : string, optional Path to save files into. Default: '~/AFQ_data' study : string, optional Which HCP study to grab. Default: 'HCP_1200' aws_access_key_id : string, optional AWS credentials to HCP AWS S3. Will only be used if `profile_name` is set to False. aws_secret_access_key : string, optional AWS credentials to HCP AWS S3. Will only be used if `profile_name` is set to False. Returns ------- dict with remote and local names of these files, path to BIDS derivative dataset Notes ----- To use this function with its default setting, you need to have a file '~/.aws/credentials', that includes a section: [hcp] AWS_ACCESS_KEY_ID=<KEY> AWS_SECRET_ACCESS_KEY=<KEY> The keys are credentials that you can get from HCP (see https://wiki.humanconnectome.org/display/PublicData/How+To+Connect+to+Connectome+Data+via+AWS) # noqa Local filenames are changed to match our expected conventions. .. [1] <NAME> al. (2016). The brain imaging data structure, a format for organizing and describing outputs of neuroimaging experiments. Scientific Data, 3::160044. DOI: 10.1038/sdata.2016.44. """ if profile_name: boto3.setup_default_session(profile_name=profile_name) elif aws_access_key_id is not None and aws_secret_access_key is not None: boto3.setup_default_session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) else: raise ValueError("Must provide either a `profile_name` or ", "both `aws_access_key_id` and ", "`aws_secret_access_key` as input to 'fetch_hcp'") s3 = boto3.resource('s3') bucket = s3.Bucket(hcp_bucket) if path is None: if not op.exists(afq_home): os.mkdir(afq_home) my_path = afq_home else: my_path = path base_dir = op.join(my_path, study, 'derivatives', 'dmriprep') if not os.path.exists(base_dir): os.makedirs(base_dir, exist_ok=True) data_files = {} for subject in subjects: # We make a single session folder per subject for this case, because # AFQ api expects session structure: sub_dir = op.join(base_dir, f'sub-{subject}') sess_dir = op.join(sub_dir, "ses-01") if not os.path.exists(sub_dir): os.makedirs(os.path.join(sess_dir, 'dwi'), exist_ok=True) os.makedirs(os.path.join(sess_dir, 'anat'), exist_ok=True) data_files[op.join(sess_dir, 'dwi', f'sub-{subject}_dwi.bval')] =\ f'{study}/{subject}/T1w/Diffusion/bvals' data_files[op.join(sess_dir, 'dwi', f'sub-{subject}_dwi.bvec')] =\ f'{study}/{subject}/T1w/Diffusion/bvecs' data_files[op.join(sess_dir, 'dwi', f'sub-{subject}_dwi.nii.gz')] =\ f'{study}/{subject}/T1w/Diffusion/data.nii.gz' data_files[op.join(sess_dir, 'anat', f'sub-{subject}_T1w.nii.gz')] =\ f'{study}/{subject}/T1w/T1w_acpc_dc.nii.gz' data_files[op.join(sess_dir, 'anat', f'sub-{subject}_aparc+aseg_seg.nii.gz')] =\ f'{study}/{subject}/T1w/aparc+aseg.nii.gz' for k in data_files.keys(): if not op.exists(k): bucket.download_file(data_files[k], k) # Create the BIDS dataset description file text hcp_acknowledgements = """Data were provided by the Human Connectome Project, WU-Minn Consortium (Principal Investigators: <NAME> and <NAME>; 1U54MH091657) funded by the 16 NIH Institutes and Centers that support the NIH Blueprint for Neuroscience Research; and by the McDonnell Center for Systems Neuroscience at Washington University.""", # noqa to_bids_description(op.join(my_path, study), **{"Name": study, "Acknowledgements": hcp_acknowledgements, "Subjects": subjects}) # Create the BIDS derivatives description file text to_bids_description(base_dir, **{"Name": study, "Acknowledgements": hcp_acknowledgements, "PipelineDescription": {'Name': 'dmriprep'}}) return data_files, op.join(my_path, study) stanford_hardi_tractography_remote_fnames = ["5325715", "5325718", "25289735"] stanford_hardi_tractography_hashes = ['6f4bdae702031a48d1cd3811e7a42ef9', 'f20854b4f710577c58bd01072cfb4de6', '294bfd1831861e8635eef8834ff18892'] stanford_hardi_tractography_fnames = ['mapping.nii.gz', 'tractography_subsampled.trk', 'full_segmented_cleaned_tractography.trk'] fetch_stanford_hardi_tractography = _make_fetcher( "fetch_stanford_hardi_tractography", op.join(afq_home, 'stanford_hardi_tractography'), baseurl, stanford_hardi_tractography_remote_fnames, stanford_hardi_tractography_fnames, md5_list=stanford_hardi_tractography_hashes, doc="""Download Stanford HARDI tractography and mapping. For testing purposes""") def read_stanford_hardi_tractography(): """ Reads a minimal tractography from the Stanford dataset. """ files, folder = fetch_stanford_hardi_tractography() files_dict = {} files_dict['mapping.nii.gz'] = nib.load( op.join(afq_home, 'stanford_hardi_tractography', 'mapping.nii.gz')) # We need the original data as reference dwi_img, gtab = dpd.read_stanford_hardi() files_dict['tractography_subsampled.trk'] = load_trk( op.join(afq_home, 'stanford_hardi_tractography', 'tractography_subsampled.trk'), dwi_img, bbox_valid_check=False, trk_header_check=False).streamlines files_dict['full_segmented_cleaned_tractography.trk'] = load_trk( op.join( afq_home, 'stanford_hardi_tractography', 'full_segmented_cleaned_tractography.trk'), dwi_img).streamlines return files_dict def to_bids_description(path, fname='dataset_description.json', BIDSVersion="1.4.0", **kwargs): """Dumps a dict into a bids description at the given location""" kwargs.update({"BIDSVersion": BIDSVersion}) desc_file = op.join(path, fname) with open(desc_file, 'w') as outfile: json.dump(kwargs, outfile) def organize_cfin_data(path=None): """ Create the expected file-system structure for the CFIN multi b-value diffusion data-set. """ dpd.fetch_cfin_multib() if path is None: os.makedirs(afq_home, exist_ok=True) path = afq_home bids_path = op.join(path, 'cfin_multib',) derivatives_path = op.join(bids_path, 'derivatives') dmriprep_folder = op.join(derivatives_path, 'dmriprep') if not op.exists(derivatives_path): anat_folder = op.join(dmriprep_folder, 'sub-01', 'ses-01', 'anat') os.makedirs(anat_folder, exist_ok=True) dwi_folder = op.join(dmriprep_folder, 'sub-01', 'ses-01', 'dwi') os.makedirs(dwi_folder, exist_ok=True) t1_img = dpd.read_cfin_t1() nib.save(t1_img, op.join(anat_folder, 'sub-01_ses-01_T1w.nii.gz')) dwi_img, gtab = dpd.read_cfin_dwi() nib.save(dwi_img, op.join(dwi_folder, 'sub-01_ses-01_dwi.nii.gz')) np.savetxt(op.join(dwi_folder, 'sub-01_ses-01_dwi.bvec'), gtab.bvecs) np.savetxt(op.join(dwi_folder, 'sub-01_ses-01_dwi.bval'), gtab.bvals) to_bids_description( bids_path, **{"BIDSVersion": "1.0.0", "Name": "CFIN", "Subjects": ["sub-01"]}) to_bids_description( dmriprep_folder, **{"Name": "CFIN", "PipelineDescription": {"Name": "dipy"}}) def organize_stanford_data(path=None, clear_previous_afq=False): """ If
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import paddle from ...fluid.layer_helper import LayerHelper from ...fluid.data_feeder import check_variable_and_dtype import paddle.fluid as fluid # TODO: define loss functions of neural network import numpy as np import paddle import paddle.fluid as fluid from ...fluid.framework import core, in_dygraph_mode from ...fluid.layers.nn import _elementwise_op_in_dygraph from ...fluid.layers import dice_loss #DEFINE_ALIAS from ...fluid.layers import log_loss #DEFINE_ALIAS from ...fluid.layers import npair_loss #DEFINE_ALIAS from ...fluid.layers import reshape from ...fluid.layers import softmax_with_cross_entropy #DEFINE_ALIAS from ...fluid.layers import square_error_cost #DEFINE_ALIAS from ...fluid.layers import edit_distance #DEFINE_ALIAS from ...fluid.layers import huber_loss from ...fluid.layer_helper import LayerHelper from ...fluid.framework import in_dygraph_mode from ...fluid.framework import _varbase_creator from ...fluid.framework import Variable __all__ = [ 'binary_cross_entropy', 'binary_cross_entropy_with_logits', 'cross_entropy', 'dice_loss', 'hsigmoid_loss', 'kl_div', 'l1_loss', 'log_loss', 'mse_loss', 'margin_ranking_loss', # 'nce', 'nll_loss', 'npair_loss', 'sigmoid_focal_loss', 'smooth_l1_loss', 'softmax_with_cross_entropy', 'square_error_cost', 'ctc_loss', ] def binary_cross_entropy(input, label, weight=None, reduction='mean', name=None): """ This op measures the binary_cross_entropy loss between input predictions ``input`` and target labels ``label`` . The binary_cross_entropy loss can be described as: If :attr:`weight` is set, the loss is: .. math:: Out = -1 * weight * (label * log(input) + (1 - label) * log(1 - input)) If :attr:`weight` is None, the loss is: .. math:: Out = -1 * (label * log(input) + (1 - label) * log(1 - input)) If :attr:`reduction` set to ``'none'``, the interface will return the original loss `Out`. If :attr:`reduction` set to ``'mean'``, the reduced mean loss is: .. math:: Out = MEAN(Out) If :attr:`reduction` set to ``'sum'``, the reduced sum loss is: .. math:: Out = SUM(Out) Note that the input predictions ``input`` always be the output of sigmoid, and the target labels ``label`` should be numbers between 0 and 1. Parameters: input (Tensor): The input predications tensor. 2-D tensor with shape: [N, *], N is batch_size, `*` means number of additional dimensions. The ``input`` should always be the output of sigmod. Available dtype is float32, float64. label (Tensor): The target labels tensor. 2-D tensor with the same shape as ``input``. The target labels which values should be numbers between 0 and 1. Available dtype is float32, float64. weight (Tensor, optional): A manual rescaling weight given to the loss of each batch element. If given, has to be a Tensor of size nbatch and the data type is float32, float64. Default is ``'None'``. reduction (str, optional): Indicate how to average the loss by batch_size, the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. If :attr:`reduction` is ``'none'``, the unreduced loss is returned; If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; If :attr:`reduction` is ``'sum'``, the summed loss is returned. Default is ``'mean'``. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: output (Tensor): If ``reduction`` is ``'none'``, the shape of output is same as ``input`` , else the shape of output is scalar. Examples: .. code-block:: python import paddle input = paddle.to_tensor([0.5, 0.6, 0.7], 'float32') label = paddle.to_tensor([1.0, 0.0, 1.0], 'float32') output = paddle.nn.functional.binary_cross_entropy(input, label) print(output) # [0.65537095] """ if reduction not in ['sum', 'mean', 'none']: raise ValueError( "The value of 'reduction' in binary_cross_entropy should be 'sum', " "'mean' or 'none', but received %s, which is not allowed." % reduction) if in_dygraph_mode(): out = core.ops.bce_loss(input, label) if weight is not None: out = core.ops.elementwise_mul(out, weight, 'axis', -1) if reduction == 'sum': return core.ops.reduce_sum(out, 'dim', [0], 'keep_dim', False, "reduce_all", True) elif reduction == 'mean': return core.ops.mean(out) else: return out fluid.data_feeder.check_variable_and_dtype( input, 'input', ['float32', 'float64'], 'binary_cross_entropy') fluid.data_feeder.check_variable_and_dtype( label, 'label', ['float32', 'float64'], 'binary_cross_entropy') sub_name = name if weight is None and reduction is 'none' else None helper = LayerHelper("binary_cross_entropy", name=sub_name) out = helper.create_variable_for_type_inference(dtype=input.dtype) helper.append_op( type='bce_loss', inputs={ 'X': [input], 'Label': [label], }, outputs={'Out': [out]}) if weight is not None: if isinstance(weight, paddle.static.Variable): weight_name = name if reduction is 'none' else None out = paddle.multiply(out, weight, name=weight_name) else: raise ValueError( "The weight is not a Tensor, please convert to Tensor.") if reduction == 'sum': return paddle.sum(out, name=name) elif reduction == 'mean': return paddle.mean(out, name=name) else: return out def binary_cross_entropy_with_logits(logit, label, weight=None, reduction='mean', pos_weight=None, name=None): r""" This operator combines the sigmoid layer and the :ref:`api_nn_loss_BCELoss` layer. Also, we can see it as the combine of ``sigmoid_cross_entropy_with_logits`` layer and some reduce operations. This measures the element-wise probability error in classification tasks in which each class is independent. This can be thought of as predicting labels for a data-point, where labels are not mutually exclusive. For example, a news article can be about politics, technology or sports at the same time or none of these. First this operator calculate loss function as follows: .. math:: Out = -Labels * \\log(\\sigma(Logit)) - (1 - Labels) * \\log(1 - \\sigma(Logit)) We know that :math:`\\sigma(Logit) = \\frac{1}{1 + e^{-Logit}}`. By substituting this we get: .. math:: Out = Logit - Logit * Labels + \\log(1 + e^{-Logit}) For stability and to prevent overflow of :math:`e^{-Logit}` when Logit < 0, we reformulate the loss as follows: .. math:: Out = \\max(Logit, 0) - Logit * Labels + \\log(1 + e^{-\|Logit\|}) Then, if ``weight`` or ``pos_weight`` is not None, this operator multiply the weight tensor on the loss `Out`. The ``weight`` tensor will attach different weight on every items in the batch. The ``pos_weight`` will attach different weight on the positive label of each class. Finally, this operator applies reduce operation on the loss. If :attr:`reduction` set to ``'none'``, the operator will return the original loss `Out`. If :attr:`reduction` set to ``'mean'``, the reduced mean loss is :math:`Out = MEAN(Out)`. If :attr:`reduction` set to ``'sum'``, the reduced sum loss is :math:`Out = SUM(Out)`. Note that the target labels ``label`` should be numbers between 0 and 1. Args: logit (Tensor): The input predications tensor. 2-D tensor with shape: [N, *], N is batch_size, `*` means number of additional dimensions. The ``logit`` is usually the output of Linear layer. Available dtype is float32, float64. label (Tensor): The target labels tensor. 2-D tensor with the same shape as ``logit``. The target labels which values should be numbers between 0 and 1. Available dtype is float32, float64. weight (Tensor, optional): A manual rescaling weight given to the loss of each batch element. If given, it has to be a 1D Tensor whose size is `[N, ]`, The data type is float32, float64. Default is ``'None'``. reduction (str, optional): Indicate how to average the loss by batch_size, the candicates are ``'none'`` | ``'mean'`` | ``'sum'``. If :attr:`reduction` is ``'none'``, the unreduced loss is returned; If :attr:`reduction` is ``'mean'``, the reduced mean loss is returned; If :attr:`reduction` is ``'sum'``, the summed loss is returned. Default is ``'mean'``. pos_weight (Tensor, optional): A weight of positive examples. Must be a vector with length equal to the number of classes. The data type is float32, float64. Default is ``'None'``. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Returns: output (Tensor): If ``reduction`` is ``'none'``, the shape of output is same as ``logit`` , else the shape of output is scalar. Examples: .. code-block:: python import paddle logit = paddle.to_tensor([5.0, 1.0, 3.0]) label = paddle.to_tensor([1.0, 0.0, 1.0]) output = paddle.nn.functional.binary_cross_entropy_with_logits(logit, label) print(output) # [0.45618808] """ if reduction not in ['sum', 'mean', 'none']: raise ValueError( "The value of 'reduction' in binary_cross_entropy_with_logits " "should be 'sum', 'mean' or 'none', but received %s, which is not allowed." % reduction) if in_dygraph_mode(): one = _varbase_creator(dtype=logit.dtype) core.ops.fill_constant(one, 'value', float(1.0), 'force_cpu', False, 'dtype', one.dtype, 'str_value', '1.0', 'shape', [1]) out = core.ops.sigmoid_cross_entropy_with_logits(logit, label) if pos_weight
<filename>nativecompile/x86_reader.py # Copyright 2015 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import binascii from itertools import islice from .pyinternals import read_address,raw_addresses from .dinterval import * DEBUG_PRINT = False # how many bytes to scan in memory before giving up SEARCH_LIMIT = 0x10000 # maximum number of non-matching instructions allowed between a "pair" of # instructions INSTR_ADJACENCY_FUZZ = 8 MODE_16 = 0 MODE_32 = 1 MODE_64 = 2 class MachineCodeParseError(Exception): pass class InvalidOpCodeError(MachineCodeParseError): pass class SearchLimitReachedError(MachineCodeParseError): pass MOD_ANY = True # enforcing the memory-only and register-only variants of the ModRM byte are # not necessary for parsing, but it was easy to implement and having a stricter # parser makes it easier to verify correctness MEM_ONLY = True + 1 REG_ONLY = True + 2 def mod_rm_size(mode,data,mod_type=MOD_ANY): mod = data >> 6 rm = data & 0b111 size = 1 if mod_type == MEM_ONLY: if mod == 3: raise InvalidOpCodeError() elif mod_type == REG_ONLY: if mod != 3: raise InvalidOpCodeError() if mode != MODE_16: # address displacement if (mod == 0 and rm == 0b101) or mod == 2: size += 4 elif mod == 1: size += 1 # SIB byte if mod != 3 and rm == 0b100: size += 1 else: # address displacement if (mod == 0 and rm == 0b110) or mod == 2: size += 2 elif mod == 1: size += 1 return size class MemReader: def __init__(self,position=0): self.position = position self.__scanned = 0 def advance(self,amount=1): self.position += amount self.__scanned += amount if self.__scanned > SEARCH_LIMIT: raise SearchLimitReachedError() def read(self,amount): r = read_address(self.position,amount) self.advance(amount) return r @property def current(self): return read_address(self.position,1)[0] class Address: def __init__(self,base=None,index=None,scale=1,offset=0,rip_rel=False): self.base = base self.index = index self.scale = scale self.offset = offset self.rip_rel = rip_rel def normalize(self,position): if self.rip_rel: self.offset += position self.rip_rel = False def __repr__(self): return "Address({!r},{!r},{!r},{!r},{!r})".format(self.base,self.index,self.scale,self.offset,self.rip_rel) def rex_bit(b): b = 1 << b return property(lambda self: bool(self.val & b)) class Rex: def __init__(self,val): self.val = val w = rex_bit(3) r = rex_bit(2) x = rex_bit(1) b = rex_bit(0) def split_byte_332(x): return x & 0b111, (x >> 3) & 0b111, x >> 6 def to_int(x): return int.from_bytes(x,'little',signed=True) def read_mod_rm(mode,data,rex): assert mode != MODE_16 if rex is None: rex = Rex(0) rm,reg,mod = split_byte_332(data.current) data.advance() reg |= rex.r << 3 if mod != 3: if mod == 0 and rm == 0b101: arg_b = Address(offset=to_int(data.read(4)),rip_rel=mode==MODE_64) else: if rm == 0b100: arg_b = Address(*split_byte_332(data.current)) data.advance() if arg_b.base == 0b101 and mod == 0: arg_b.base = None arg_b.offset = to_int(data.read(4)) else: arg_b.base |= rex.b << 3 arg_b.index |= rex.x << 3 if arg_b.index == 0b100: arg_b.index = None else: arg_b = Address(rm) if mod == 1: arg_b.offset = to_int(data.read(1)) elif mod == 2: arg_b.offset = to_int(data.read(4)) else: arg_b = rm | (rex.b << 3) return reg,arg_b # immediate value sizes: BYTE_OR_WORD = -1 WORD_OR_DWORD = -2 SEG_AND_NATIVE = -3 NATIVE_SIZE = -4 def immediate_size(type,op_size): if type == BYTE_OR_WORD: return 2 if op_size != MODE_16 else 1 if type == WORD_OR_DWORD: return 4 if op_size != MODE_16 else 2 if type == SEG_AND_NATIVE: return 2 + (2 << op_size) if type == NATIVE_SIZE: return 2 << op_size return type class Format: def __init__(self,modrm,imm): self.modrm = modrm self.imm = imm MX = Format(True,0) X = Format(False,0) MB = Format(True,1) B = Format(False,1) W = Format(False,2) E = Format(False,3) rX = Format(REG_ONLY,0) rB = Format(REG_ONLY,1) MV = Format(True,WORD_OR_DWORD) V = Format(False,WORD_OR_DWORD) mX = Format(MEM_ONLY,0) mV = Format(MEM_ONLY,WORD_OR_DWORD) S = Format(False,SEG_AND_NATIVE) N = Format(False,NATIVE_SIZE) _ = None one_byte_map = [ # 0 1 2 3 4 5 6 7 8 9 A B C D E F MX, MX, MX, MX, B, V, X, X, MX, MX, MX, MX, B, V, X, _, # 0 MX, MX, MX, MX, B, V, X, X, MX, MX, MX, MX, B, V, X, X, # 1 MX, MX, MX, MX, B, V, _, X, MX, MX, MX, MX, B, V, _, X, # 2 MX, MX, MX, MX, B, V, _, X, MX, MX, MX, MX, B, V, _, X, # 3 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, # 4 X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, # 5 X, X, mV, MX, _, _, _, _, V, MV, B, MB, X, X, X, X, # 6 B, B, B, B, B, B, B, B, B, B, B, B, B, B, B, B, # 7 MB, MV, MB, MB, MX, MX, MX, MX, MX, MX, MX, MX, MX, mX, MX, MX, # 8 X, X, X, X, X, X, X, X, X, X, S, X, X, X, X, X, # 9 B, V, B, V, X, X, X, X, B, V, X, X, X, X, X, X, # A B, B, B, B, B, B, B, B, N, N, N, N, N, N, N, N, # B MB, MB, W, X, mX, mX, MB, MV, E, X, W, X, X, B, X, X, # C MX, MX, MX, MX, B, B, _, X, MX, MX, MX, MX, MX, MX, MX, MX, # D B, B, B, B, B, B, B, B, V, V, S, B, X, X, X, X, # E _, _, _, _, X, X, MX, MX, X, X, X, X, X, X, MX, MX # F ] # 0F is for AMD 3DNow! opcodes # when used without a prefix, B8 represents the JMPE instruction, which is not # supported here (because it is used to switch to IA-64 mode which is not # useful for applications and is not supported by native x86 processors anyway) two_byte_map = [ # 0 1 2 3 4 5 6 7 8 9 A B C D E F MX, MX, MX, MX, _, _, X, _, X, X, _, _, _, MX, X, MB, # 0 MX, MX, MX, MX, MX, MX, MX, MX, mX, MX, MX, MX, MX, MX, MX, MX, # 1 rX, rX, rX, rX, _, _, _, _, MX, MX, MX, MX, MX, MX, MX, MX, # 2 X, X, X, X, X, X, _, X, _, _, _, _, _, _, _, _, # 3 MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, # 4 MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, # 5 MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, # 6 MB, rB, rB, rB, MX, MX, MX, X, MX, MX, _, _, MX, MX, MX, MX, # 7 V, V, V, V, V, V, V, V, V, V, V, V, V, V, V, V, # 8 MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, # 9 X, X, X, MX, MB, MX, _, _, X, X, X, MX, MB, MX, MX, MX, # A MX, MX, mX, MX, mX, mX, MX, MX, MX, _, MB, MX, MX, MX, MX, MX, # B MX, MX, MB, mX, MB, rB, MB, mX, X, X, X, X, X, X, X, X, # C MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, # D MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, # E mX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, _ # F ] three_byte_map_0x38 = [ # 0 1 2 3 4 5 6 7 8 9 A B C D E F MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX, MX,
"""This module contains the `Edb` class. This module is implicitily loaded in HFSS 3D Layout when launched. """ import os import sys import traceback import warnings import gc import pyaedt.edb_core.EDB_Data import time try: import ScriptEnv ScriptEnv.Initialize("Ansoft.ElectronicsDesktop") inside_desktop = True except: inside_desktop = False try: import clr from System.Collections.Generic import List, Dictionary from System import Convert, String import System from System import Double, Array from System.Collections.Generic import List _ironpython = False if "IronPython" in sys.version or ".NETFramework" in sys.version: _ironpython = True edb_initialized = True except ImportError: warnings.warn( "The clr is missing. Install Python.NET or use an IronPython version if you want to use the EDB module.") edb_initialized = False from .application.MessageManager import EDBMessageManager from .edb_core import * from .generic.general_methods import get_filename_without_extension, generate_unique_name, aedt_exception_handler, \ env_path, env_value, env_path_student, env_value_student from .generic.process import SiwaveSolve class Edb(object): """Provides the EDB application interface. This module inherits all objects that belong to EDB. Parameters ---------- edbpath : str, optional Full path to the ``aedb`` folder. The variable can also contain the path to a layout to import. Allowed formarts are BRD, XML (IPC2581), GDS, and DXF. The default is ``None``. cellname : str, optional Name of the cell to select. The default is ``None``. isreadonly : bool, optional Whether to open ``edb_core`` in read-only mode when it is owned by HFSS 3D Layout. The default is ``False``. edbversion : str, optional Version of ``edb_core`` to use. The default is ``"2021.1"``. isaedtowned : bool, optional Whether to launch ``edb_core`` from HFSS 3D Layout. The default is ``False``. oproject : optional Reference to the AEDT project object. student_version : bool, optional Whether to open the AEDT student version. The default is ``False.`` Examples -------- Create an `Edb` object and a new EDB cell. >>> from pyaedt import Edb >>> app = Edb() Create an `Edb` object and open the specified project. >>> app = Edb("myfile.aedb") """ def __init__(self, edbpath=None, cellname=None, isreadonly=False, edbversion="2021.1", isaedtowned=False, oproject=None, student_version=False): self._clean_variables() if _ironpython and inside_desktop: self.standalone = False else: self.standalone = True if edb_initialized: self.oproject = oproject if isaedtowned: self._main = sys.modules['__main__'] self._messenger = self._main.oMessenger else: if not edbpath or not os.path.exists(edbpath): self._messenger = EDBMessageManager() elif os.path.exists(edbpath): self._messenger = EDBMessageManager(os.path.dirname(edbpath)) self.student_version = student_version self._messenger.add_info_message("Messenger Initialized in EDB") self.edbversion = edbversion self.isaedtowned = isaedtowned self._init_dlls() self._db = None # self._edb.Database.SetRunAsStandAlone(not isaedtowned) self.isreadonly = isreadonly self.cellname = cellname self.edbpath = edbpath if edbpath[-3:] in ["brd", "gds", "xml", "dxf", "tgz"]: self.edbpath = edbpath[-3:] + ".aedb" working_dir = os.path.dirname(edbpath) self.import_layout_pcb(edbpath, working_dir) elif not os.path.exists(os.path.join(self.edbpath, "edb.def")): self.create_edb() elif ".aedb" in edbpath: self.edbpath = edbpath if isaedtowned and "isoutsideDesktop" in dir(self._main) and not self._main.isoutsideDesktop: self.open_edb_inside_aedt() else: self.open_edb() if self.builder: self._messenger.add_info_message("Edb Initialized") else: self._messenger.add_info_message("Failed to initialize Dlls") else: warnings.warn("Failed to initialize Dlls") def _clean_variables(self): """Initialize internal variables and perform garbage collection.""" self._components = None self._core_primitives = None self._stackup = None self._padstack = None self._siwave = None self._hfss = None self._nets = None self._db = None self._edb = None self.builder = None gc.collect() @aedt_exception_handler def _init_objects(self): self._components = Components(self) self._stackup = EdbStackup(self) self._padstack = EdbPadstacks(self) self._siwave = EdbSiwave(self) self._hfss = Edb3DLayout(self) self._nets = EdbNets(self) self._core_primitives = EdbLayout(self) self._messenger.add_info_message("Objects Initialized") @aedt_exception_handler def add_info_message(self, message_text): """Add a type 0 "Info" message to the active design level of the Message Manager tree. Also add an info message to the logger if the handler is present. Parameters ---------- message_text : str Text to display as the info message. Returns ------- bool ``True`` when successful, ``False`` when failed. Examples -------- >>> from pyaedt import Edb >>> edb = Edb() >>> edb.add_info_message("Design info message") """ self._messenger.add_info_message(message_text) return True @aedt_exception_handler def add_warning_message(self, message_text): """Add a type 0 "Warning" message to the active design level of the Message Manager tree. Also add an info message to the logger if the handler is present. Parameters ---------- message_text : str Text to display as the warning message. Returns ------- bool ``True`` when successful, ``False`` when failed. Examples -------- >>> from pyaedt import Edb >>> edb = Edb() >>> edb.add_warning_message("Design warning message") """ self._messenger.add_warning_message(message_text) return True @aedt_exception_handler def add_error_message(self, message_text): """Add a type 0 "Error" message to the active design level of the Message Manager tree. Also add an error message to the logger if the handler is present. Parameters ---------- message_text : str Text to display as the error message. Returns ------- bool ``True`` when successful, ``False`` when failed. Examples -------- >>> from pyaedt import Edb >>> edb = Edb() >>> edb.add_error_message("Design error message") """ self._messenger.add_error_message(message_text) return True @aedt_exception_handler def _init_dlls(self): """Initialize DLLs.""" sys.path.append(os.path.join(os.path.dirname(__file__), "dlls", "EDBLib")) if os.name == 'posix': if env_value(self.edbversion) in os.environ: self.base_path = env_path(self.edbversion) sys.path.append(self.base_path) else: main = sys.modules["__main__"] if "oDesktop" in dir(main): self.base_path = main.oDesktop.GetExeDir() sys.path.append(main.oDesktop.GetExeDir()) os.environ[env_value(self.edbversion)] = self.base_path clr.AddReferenceToFile('Ansys.Ansoft.Edb.dll') clr.AddReferenceToFile('Ansys.Ansoft.EdbBuilderUtils.dll') clr.AddReferenceToFile('EdbLib.dll') clr.AddReferenceToFile('DataModel.dll') clr.AddReferenceToFileAndPath(os.path.join( self.base_path, 'Ansys.Ansoft.SimSetupData.dll')) else: if self.student_version: self.base_path = env_path_student(self.edbversion) else: self.base_path = env_path( self.edbversion) sys.path.append(self.base_path) clr.AddReference('Ansys.Ansoft.Edb') clr.AddReference('Ansys.Ansoft.EdbBuilderUtils') clr.AddReference('EdbLib') clr.AddReference('DataModel') clr.AddReference('Ansys.Ansoft.SimSetupData') os.environ["ECAD_TRANSLATORS_INSTALL_DIR"] = self.base_path oaDirectory = os.path.join(self.base_path, 'common', 'oa') os.environ['ANSYS_OADIR'] = oaDirectory os.environ['PATH'] = '{};{}'.format(os.environ['PATH'], self.base_path) edb = __import__('Ansys.Ansoft.Edb') self.edb = edb.Ansoft.Edb edbbuilder = __import__('Ansys.Ansoft.EdbBuilderUtils') self.edblib = __import__('EdbLib') self.edbutils = edbbuilder.Ansoft.EdbBuilderUtils self.simSetup = __import__('Ansys.Ansoft.SimSetupData') self.layout_methods = self.edblib.Layout.LayoutMethods self.simsetupdata = self.simSetup.Ansoft.SimSetupData.Data @aedt_exception_handler def open_edb(self, init_dlls=False): """Open EDB. Parameters ---------- init_dlls : bool, optional Whether to initialize DLLs. The default is ``False``. Returns ------- """ if init_dlls: self._init_dlls() self._messenger.add_info_message("EDB Path {}".format(self.edbpath)) self._messenger.add_info_message("EDB Version {}".format(self.edbversion)) self.edb.Database.SetRunAsStandAlone(self.standalone) self._messenger.add_info_message("EDB Standalone {}".format(self.standalone)) db = self.edb.Database.Open(self.edbpath, self.isreadonly) if not db: self._messenger.add_warning_message("Error Opening db") self._db = None self._active_cell = None self.builder = None return None self._db = db self._messenger.add_info_message("Database Opened") self._active_cell = None if self.cellname: for cell in list(self._db.TopCircuitCells): if cell.GetName() == self.cellname: self._active_cell = cell # if self._active_cell is still None, set it to default cell if self._active_cell is None: self._active_cell = list(self._db.TopCircuitCells)[0] self._messenger.add_info_message("Cell {} Opened".format(self._active_cell.GetName())) if self._db and self._active_cell: time.sleep(1) dllpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), "dlls", "EDBLib", "DataModel.dll") self._messenger.add_info_message(dllpath) self.layout_methods.LoadDataModel(dllpath) self.builder = self.layout_methods.GetBuilder(self._db, self._active_cell, self.edbpath, self.edbversion, self.standalone) self._init_objects() self._messenger.add_info_message("Builder Initialized") else: self.builder = None self._messenger.add_error_message("Builder Not Initialized") return self.builder @aedt_exception_handler def open_edb_inside_aedt(self, init_dlls=False): """Open EDB inside of AEDT. Parameters ---------- init_dlls : bool, optional Whether to initialize DLLs. The default is ``False``. Returns ------- """ if init_dlls: self._init_dlls() self._messenger.add_info_message("Opening EDB from HDL") self.edb.Database.SetRunAsStandAlone(False) if self.oproject.GetEDBHandle(): hdl = Convert.ToUInt64(self.oproject.GetEDBHandle()) db = self.edb.Database.Attach(hdl) if not db: self._messenger.add_warning_message("Error Getting db") self._db = None self._active_cell = None self.builder = None return None self._db = db self._active_cell = self.edb.Cell.Cell.FindByName( self.db, self.edb.Cell.CellType.CircuitCell, self.cellname) if self._active_cell is None: self._active_cell = list(self._db.TopCircuitCells)[0] dllpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), "dlls", "EDBLib", "DataModel.dll") if self._db and self._active_cell: self.layout_methods.LoadDataModel(dllpath) self.builder = self.layout_methods.GetBuilder(self._db, self._active_cell, self.edbpath, self.edbversion, self.standalone, True) self._init_objects() return self.builder else: self.builder = None return None else: self._db = None self._active_cell = None self.builder = None return None @aedt_exception_handler def create_edb(self, init_dlls=False): """Create EDB. Parameters ---------- init_dlls : bool, optional Whether to initialize DLLs. The default is ``False``. Returns ------- """ if init_dlls: self._init_dlls() self.edb.Database.SetRunAsStandAlone(self.standalone) db = self.edb.Database.Create(self.edbpath) if not db: self._messenger.add_warning_message("Error Creating db") self._db = None self._active_cell = None self.builder = None return None self._db = db if not self.cellname: self.cellname = generate_unique_name("Cell") self._active_cell = self.edb.Cell.Cell.Create( self._db, self.edb.Cell.CellType.CircuitCell, self.cellname) dllpath = os.path.join(os.path.dirname(__file__), "dlls", "EDBLib", "DataModel.dll") if self._db and self._active_cell: self.layout_methods.LoadDataModel(dllpath) self.builder = self.layout_methods.GetBuilder( self._db, self._active_cell, self.edbpath, self.edbversion, self.standalone) self._init_objects() return self.builder self.builder = None return None @aedt_exception_handler def import_layout_pcb(self, input_file, working_dir, init_dlls=False, anstranslator_full_path=None): """Import a BRD file and generate an ``edb.def`` file in the working directory. Parameters ---------- input_file : str Full path to the BRD file. working_dir : str Directory in which to create the ``aedb`` folder. The AEDB file name will be the same as the BRD file name. init_dlls : bool Whether to initialize DLLs. The default is ``False``. Returns ------- str Full path to the AEDB file. """ self._components = None self._core_primitives = None self._stackup = None self._padstack = None self._siwave = None self._hfss = None self._nets = None self._db = None if init_dlls: self._init_dlls() aedb_name = os.path.splitext(os.path.basename(input_file))[0] + ".aedb" if anstranslator_full_path and os.path.exists(anstranslator_full_path): command = anstranslator_full_path else: command = os.path.join(self.base_path, "anstranslator") if os.name != "posix": command += ".exe" if not working_dir: working_dir = os.path.dirname(input_file) translatorSetup = self.edbutils.AnsTranslatorRunner( input_file,
# if taxid not in taxid_2_rank__taxid_set: # line2write = str(taxid) + "\t" + rank + "\n" # fh_out_taxid_2_rank.write(line2write) # taxid_2_rank__taxid_set.update([taxid]) # # def write_Child_2_Parent_table_Taxa_for_SQL(self, fn_out): # # type_number = "-3" # entity type = "DOID diseases" from Lars's Entities and types system # with open(fn_out, "w") as fh: # for taxid_child in sorted(self.taxid_2_parent_taxid_dict.keys()): # taxid_parent = self.taxid_2_parent_taxid_dict[taxid_child] # line2write = str(taxid_child) + "\t" + str(taxid_parent) + "\n" # fh.write(line2write) # class NCBI_taxonomy_R(object): # """ # given a TaxID (e.g. 9606), retrieve parent, getrank, scientific name # interfaces with R and R-package 'CHNOSZ' to access NCBI-tax-files # """ # def __init__(self, taxdump_directory=None): # homedir = os.path.expanduser("~") # self.taxid2taxnamesfl_dict = {} # key=TaxID, val=String(Full Lineage of TaxNames for LEfSe analysis) # self.taxid2parent_of_rank_dict = {} # key=TaxID_Rank, val=TaxID # self.taxid2rank_closest_classified_dict = {1: 'root'} # key=TaxID, val=Rank (String) # self.taxid2taxid_closest_classified_dict = {1: 1} # self.set2break = {131567, 1} # TaxIDs of CellularOrganisms and Root # # self.taxid2superkingdom_dict = {} # key=TaxID, val= # # self.child2parent_dict_fn = os.path.join(homedir, "modules/cpr/metaprot/taxdump/NCBI_taxonomy_child2parent_dict.p") # if os.path.exists(self.child2parent_dict_fn): # self.load_child2parent_dict() # else: # self.child2parent_dict = {} # key = taxid_child_taxid_parent, val = Bool; e.g. {'3218_33090': True, '3218_33634': False, ...} # # rpackages.importr('CHNOSZ') # if not taxdump_directory: # taxdump_directory = os.path.join(homedir, "modules/cpr/metaprot/taxdump") # # taxdump = """taxdir <- ('/Users/dblyon/modules/cpr/metaprot/taxdump')""" # # else: # taxdump = """taxdir <- ('{}')""".format(taxdump_directory) # robjects.r(taxdump) # robjects.r(""" # nodes <- getnodes(taxdir=taxdir) # names <- getnames(taxdir=taxdir) # """) # # def __del__(self): # self.save_child2parent_dict() # # def get_parent(self, taxid, rank=None): # """ # produces taxid of parent or of given rank # :param taxid: Integer # :return: Integer # """ # if rank: # string2r = """parent({}, nodes=nodes, rank='{}')""".format(taxid, rank) # else: # string2r = """parent({}, nodes=nodes, rank=NULL)""".format(taxid) # try: # tax2return = int(robjects.r(string2r)[0]) # except TypeError: # tax2return = -1 # # except IndexError: # # tax2return = -1 # return tax2return # # def get_allparents(self, taxid): # """ # sorted (ascending) list of TaxID-parents of given TaxID (including given TaxID) # :param taxid: Integer # :return: List of Integer # """ # return [int(taxid) for taxid in robjects.r("""allparents({}, nodes=nodes)""".format(taxid))] # # def info_ranks(self): # """ # produce ascending taxonomic ranks (name of ranks) # :return: List of String # """ # # return ["domain", "superkingdom", "kingdom", "phylum (division)", # # "class", "subclass", "order", "superfamily", "family", # # "subfamily", "tribe", "subtribe", "genus", "subgenus", # # "species", "subspecies"] # return ["domain", "superkingdom", "kingdom", "subkingdom", # "phylum", 'subphylum', "division", # "class", "subclass", # 'superorder', "order", 'suborder', 'infraorder', 'parvorder', # "superfamily", "family", "subfamily", # "tribe", "subtribe", # "genus", "subgenus", # "species", "subspecies"] # # def get_rank(self, taxid): # return robjects.r("""getrank({}, nodes=nodes)""".format(taxid))[0] # # def get_sciname(self, taxid): # return robjects.r("""sciname({}, names=names)""".format(taxid))[0] # # def get_infos_taxid(self, taxid): # """ # produce given TaxID, scientific name, rank, parent_TaxID # :param taxid: Int # :return: Tuple(Int, Str, Str, Int) # """ # parent = self.get_parent(taxid) # rank = self.get_rank(taxid) # sciname = self.get_sciname(taxid) # return taxid, sciname, rank, parent # # def get_genus_or_higher(self, taxid, rank='genus'): # """ # get genus is possible (if on genus level or lower) # else return given taxid # return: taxid (String) # """ # parent = self.get_parent(taxid, rank=rank) # if rank == self.get_rank(parent): # return parent # else: # return taxid # # def is_taxid_child_of_parent_taxid(self, taxid_child, taxid_parent): # try: # parents_of_taxid_child = self.get_allparents(taxid_child) # except: # print("{} taxid_child, throws Error".format(taxid_child)) # if taxid_parent in set(parents_of_taxid_child): # return True # else: # return False # # def is_taxid_child_of_parent_taxid_speed(self, taxid_child, taxid_parent): # try: # return self.child2parent_dict[str(taxid_child) + "_" + str(taxid_parent)] # except KeyError: # is_child = self.is_taxid_child_of_parent_taxid(taxid_child, taxid_parent) # self.child2parent_dict[str(taxid_child) + "_" + str(taxid_parent)] = is_child # return is_child # # def filter_include_taxid_child_of_parent_taxid(self, child_taxid_list, parent=2759): # """ # batch process list of child_taxids against the same parent_taxid # if child had the given parent --> include in return list # :param child_taxid_list: List of Integers # :param parent: Integer (default Eukaryota) # :return: List of Integers # """ # taxid_list2return = [] # for taxid in child_taxid_list: # if self.is_taxid_child_of_parent_taxid_speed(taxid_child=taxid, taxid_parent=parent): # taxid_list2return.append(taxid) # return taxid_list2return # # def filter_exclude_taxid_child_of_parent_taxid(self, child_taxid_list, parent): # """ # if child had the given parent --> exclude in return list # :param child_taxid_list: List of Integers # :param parent: Integer # :return: List of Integers # """ # taxid_list2return = [] # for taxid in child_taxid_list: # if not self.is_taxid_child_of_parent_taxid_speed(taxid_child=taxid, taxid_parent=parent): # taxid_list2return.append(taxid) # return taxid_list2return # # def save_child2parent_dict(self): # pickle.dump(self.child2parent_dict, open(self.child2parent_dict_fn, "wb")) # # def load_child2parent_dict(self): # self.child2parent_dict = pickle.load(open(self.child2parent_dict_fn, "rb")) # # def TaxID_lineage_info(self, taxid): # """ # prints TaxID, SciName, Rank of given TaxID and all parents # :param taxid: TaxID (String or Int) # :return: None # """ # print(taxid, "#", self.get_sciname(taxid), "#", self.get_rank(taxid)) # parent_old = False # while True: # parent = self.get_parent(taxid) # parent_new = parent # if parent_old == parent_new: # break # print(parent, "#", self.get_sciname(parent), "#", self.get_rank(parent)) # parent_old = parent # taxid = parent # # def unpickle_taxid2taxnamesfl_dict_from_file(self, fn): # self.taxid2taxnamesfl_dict = pickle.load(open(fn, "rb")) # # def get_full_lineage_from_taxnames(self, taxid, sep='|'): # """ # produce full taxonomic lineage as TaxName of parents of given TaxID, # separated by sep # for LEfSe analysis # http://huttenhower.sph.harvard.edu/galaxy # TaxID: 131567 # cellular organisms # no rank # :param taxid: TaxID(Integer) # :param sep: separator # :return: String # """ # try: # return self.taxid2taxnamesfl_dict[taxid] # except KeyError: # taxid_orig = taxid # taxid_list = [] # taxid_list.append(self.get_sciname(taxid)) # while True: # parent = self.get_parent(taxid) # if parent in self.set2break: # cellular organisms or root # break # taxid_list.append(self.get_sciname(parent)) # taxid = parent # taxid_list = taxid_list[::-1] # taxnames = "|".join(taxid_list) # self.taxid2taxnamesfl_dict[taxid_orig] = taxnames # return taxnames # # def get_parent_of_rank(self, taxid, rank): # """ # produce TaxID of given rank of given taxid # :param taxid: String or Int # :param rank: String # :return: Int # """ # taxid_rank = str(taxid) + "_" + rank # try: # return self.taxid2parent_of_rank_dict[taxid_rank] # except KeyError: # parent = self.get_parent(taxid, rank=rank) # self.taxid2parent_of_rank_dict[taxid_rank] = parent # return parent # # def unpickle_taxid2parent_of_rank_dict_from_file(self, fn): # self.taxid2parent_of_rank_dict = pickle.load(open(fn, "rb")) # # def get_rank_of_closest_classified(self, taxid): # """ # produce rank of taxid or next highest rank that is NOT 'no rank' # :param taxid: TaxID (String or Int) # :return: String # """ # try: # return self.taxid2rank_closest_classified_dict[taxid] # except KeyError: # rank = self.get_rank(taxid) # if not rank == "no rank": # self.taxid2rank_closest_classified_dict[taxid] = rank # return rank # else: # taxid = self.get_parent(taxid) # return self.get_rank_of_closest_classified(taxid) # # def unpickle_taxid2rank_closest_classified_dict_from_file(self, fn): # self.taxid2rank_closest_classified_dict = pickle.load(open(fn, "rb")) # # def get_taxid_of_closest_classified(self, taxid): # try: # return self.taxid2taxid_closest_classified_dict[taxid] # except KeyError: # rank = self.get_rank(taxid) # if not rank == "no rank": # self.taxid2taxid_closest_classified_dict[taxid] = taxid # return taxid # else: # taxid = self.get_parent(taxid) # return self.get_taxid_of_closest_classified(taxid) # # def unpickle_taxid2taxid_closest_classified_dict_from_file(self, fn): # self.taxid2taxid_closest_classified_dict = pickle.load(open(fn, "rb")) # # # class RankGOH(object): # """ # use-case A.) find 'family' or higher TaxID for given TaxID # RankGOH = taxonomy.RankGOH(rank_='family') # initialize object and set rank Genus Or Higher to 'family' level # taxid_list = sorted(set(df['TaxID_LCA'].tolist())) # get list of TaxIDs to to initial lookup for # RankGOH.fill_dicts(taxid_list) --> has table for speed # df['TaxID_GOH'] = df['TaxID_LCA'].apply(RankGOH.get_genus_or_higher, 1) # get the 'family' level TaxID # use-case B.) is given TaxID child of TaxID # RankGOH = taxonomy.RankGOH(rank_='genus') # fast default due to pickled files # RankGOH.fill_parent_dict(df, taxid2compare_column='TaxID_LCA') # for speed # RankGOH.is_taxid_child_of_parentTaxID(df, taxid2compare_column='TaxID_LCA', taxid_parent=314295, colname_new='Hominoidea') # # also: # df["Rank_LCA"] = df["TaxID_LCA"].apply(RankGOH.get_rank, 1) # df['TaxID_GOH'] = df['TaxID_LCA'].apply(RankGOH.get_genus_or_higher, 1) # # performs in-place changes to DataFrame (evidence.txt) # adds Rank of TaxID and counts genus_or_higher per rawfile # interacts with taxonomy module and R # speed up: perform lookup of set of TaxIDs --> PyDict, instead of individual lookups # if other rank than 'genus' is chosen. disable lookup in taxid2taxidGOH_dict # since this is prefilled with 'genus' parents and will give wrong answers. # TaxIDs throwing Errors: # 5563 # 41402 # 451834 # 929613 # 73900 # 406678 # 1400050 # 227529 # 115136 # 117573 # Viridiplantae 33090 # Bacteria 2 # Viruses 10239 # Mammalia 40674 # """ # def __init__(self, pickled_dicts_fn=None, tax_=None, rank_="species"): # if tax_: # self.tax_ = tax_ # else: # # self.tax_ = NCBI_taxonomy() # self.tax_ = NCBI_taxonomy_py() # self.rank = rank_ # self.taxid2sciname_dict = {} # self.taxid2rank_dict = {} # self.taxid2taxidGOH_dict = {} # self.taxid2parents_dict = {} # key=TaxID, val=set(TaxIDs) # self.taxid2parent_of_rank_dict = {} # key=TaxID_Rank, val=TaxID # self.taxid2rank_closest_classified_dict = {1: 'root'} # key=TaxID, val=Rank (String) # self.homedir = os.path.expanduser("~") # if self.rank == "species": # if not pickled_dicts_fn: # self.pickled_dicts_fn = os.path.join(self.homedir, "modules/cpr/metaprot/RankGOH_pickled_dicts.p") # else: # self.pickled_dicts_fn = pickled_dicts_fn # if os.path.exists(self.pickled_dicts_fn): # pickled_dicts = pickle.load( open(self.pickled_dicts_fn, "rb" ) ) # self.taxid2sciname_dict = pickled_dicts['taxid2sciname_dict'] # self.taxid2rank_dict = pickled_dicts['taxid_2_rank_dict'] # self.taxid2taxidGOH_dict = pickled_dicts['taxid2taxidGOH_dict'] # self.taxid2sciname_dict[-1] = 'alien' # self.taxid2rank_dict[-1] = 'no rank' # self.taxid2taxidGOH_dict[-1] = -1 # # def set_df(self, df): # self.df = df # # def taxid_list2pickle(self, taxid_list, pickle_fn=None): # """ # e.g. # taxid2taxname_fn = r'/Users/dblyon/CloudStation/CPR/Ancient_Proteins_Project/fasta/TaxID/TaxID2TaxName_COMPLETE.txt' # taxid_2_taxname_dict = parse_taxid2taxname(taxid2taxname_fn) # taxid_list = taxid_2_taxname_dict.keys() # # """ # if pickle_fn: # self.pickled_dicts_fn = pickle_fn # for taxid in taxid_list: # try: # self.fill_dicts([taxid]) # except: # print("#"*5) # print("Taxid: ", taxid) # print("#"*5) # # dict2pickle = { # "taxid2sciname_dict": self.taxid2sciname_dict, # "taxid_2_rank_dict": self.taxid2rank_dict, # "taxid2taxidGOH_dict": self.taxid2taxidGOH_dict # } # pickle.dump(dict2pickle, open(os.path.join(self.homedir, 'modules/cpr/metaprot/RankGOH_pickled_dicts.p'), "wb")) # # def yield_trsp_from_taxid_list(self, taxid_list): # for taxid in taxid_list: # if taxid == -1: # rank = 'no rank' # sciname = 'alien' # taxid_goh = -1 # else: # rank = self.tax_.get_rank(taxid) # sciname = self.tax_.get_sciname(taxid) # taxid_goh = self.tax_.get_parent(taxid, rank=self.rank) # if taxid_goh == taxid: # rank_goh = rank # sciname_goh = sciname # else: # rank_goh = self.tax_.get_rank(taxid_goh) # sciname_goh = self.tax_.get_sciname(taxid_goh) # yield taxid, rank, sciname, taxid_goh, rank_goh, sciname_goh # # def fill_dicts(self, taxid_list): # for taxid_rank_sciname_parenttaxid in self.yield_trsp_from_taxid_list(taxid_list): # taxid, rank, sciname, taxid_goh, rank_goh, sciname_goh = taxid_rank_sciname_parenttaxid # # if not self.taxid2sciname_dict.has_key(taxid): # self.taxid2sciname_dict[taxid] = sciname # if not self.taxid2sciname_dict.has_key(taxid_goh): # self.taxid2sciname_dict[taxid_goh] = sciname_goh # # if not self.taxid2rank_dict.has_key(taxid): # self.taxid2rank_dict[taxid]
the positions history to refill if animating this process <<<< needs updating for DOFtype # ------------------------- perform linearization -------------------------------- if solveOption==0: # ::: forward difference approach ::: for i in range(n): # loop through each DOF X2 = np.array(X1, dtype=np.float_) X2[i] += dX[i] # perturb positions by dx in each DOF in turn F2p = self.mooringEq(X2, DOFtype=DOFtype, lines_only=lines_only, tol=lineTol) # system net force/moment vector from positive perturbation if self.display > 2: print(F2p) if plots > 0: self.freeDOFs.append(X2) K[:,i] = -(F2p-F1)/dX[i] # take finite difference of force w.r.t perturbation elif solveOption==1: # ::: adaptive central difference approach ::: nTries = 3 # number of refinements to allow -1 for i in range(n): # loop through each DOF dXi = 1.0*dX[i] # potentially iterate with smaller step sizes if we're at a taut-slack transition (but don't get too small, or else numerical errors) for j in range(nTries): if self.display > 2: print(" ") X2 = np.array(X1, dtype=np.float_) X2[i] += dXi # perturb positions by dx in each DOF in turn F2p = self.mooringEq(X2, DOFtype=DOFtype, lines_only=lines_only, tol=lineTol) # system net force/moment vector from positive perturbation if self.display > 2: printVec(self.pointList[0].r) printVec(self.lineList[0].rB) if plots > 0: self.freeDOFs.append(X2.copy()) X2[i] -= 2.0*dXi F2m = self.mooringEq(X2, DOFtype=DOFtype, lines_only=lines_only, tol=lineTol) # system net force/moment vector from negative perturbation if self.display > 2: printVec(self.pointList[0].r) printVec(self.lineList[0].rB) if plots > 0: self.freeDOFs.append(X2.copy()) if self.display > 2: print(f"i={i}, j={j} and dXi={dXi}. F2m, F1, and F2p are {F2m[i]:6.2f} {F1[i]:6.2f} {F2p[i]:6.2f}") printVec(F2p-F1) printVec(F1-F2m) printVec(F2m) printVec(F1) printVec(F2p) # Break if the force is zero or the change in the first derivative is small if abs(F1[i]) == 0 or abs(F2m[i]-2.0*F1[i]+F2p[i]) < 0.1*np.abs(F1[i]): # note: the 0.1 is the adjustable tolerance break elif j == nTries-1: if self.display > 2: print("giving up on refinement") else: # Otherwise, we're at a tricky point and should stay in the loop to keep narrowing the step size # until the derivatives agree better. Decrease the step size by 10X. dXi = 0.1*dXi K[:,i] = -0.5*(F2p-F2m)/dXi # take finite difference of force w.r.t perturbation else: raise ValueError("getSystemStiffness was called with an invalid solveOption (only 0 and 1 are supported)") # ----------------- restore the system back to previous positions ------------------ self.setPositions(X1, DOFtype=DOFtype) # show an animation of the stiffness perturbations if applicable if plots > 0: self.animateSolution() return K def getCoupledStiffness(self, dx=0.1, dth=0.1, solveOption=1, lines_only=False, tensions=False, nTries=3, plots=0): '''Calculates the stiffness matrix for coupled degrees of freedom of a mooring system with free uncoupled degrees of freedom equilibrated. Parameters ---------- dx : float, optional The change in displacement to be used for calculating the change in force. The default is 0.1. dth : float, optional The change in rotation to be used for calculating the change in force. The default is 0.1. solveOption : boolean, optional Indicator of which solve option to use. The default is 1. plots : boolean, optional Determines whether the stiffness calculation process is plotted and/or animated or not. The default is 0. lines_only : boolean Whether to consider only line forces and ignore body/point properties. tensions : boolean Whether to also compute and return mooring line tension jacobians Raises ------ ValueError If the solveOption is not a 1 or 0 Returns ------- K : matrix nCpldDOF x nCpldDOF stiffness matrix of the system ''' self.nDOF, self.nCpldDOF = self.getDOFs() if self.display > 2: print("Getting mooring system stiffness matrix...") lineTol = 0.05*dx # manually specify an adaptive catenary solve tolerance <<<< eqTol = 0.05*dx # manually specify an adaptive tolerance for when calling solveEquilibrium # ------------------ get the positions to linearize about ----------------------- # get the positions about which the system is linearized, and an array containting # the perturbation size in each coupled DOF of the system X1, dX = self.getPositions(DOFtype="coupled", dXvals=[dx, dth]) self.solveEquilibrium(tol=eqTol) # let the system settle into equilibrium F1 = self.getForces(DOFtype="coupled", lines_only=lines_only) # get mooring forces/moments about linearization point K = np.zeros([self.nCpldDOF, self.nCpldDOF]) # allocate stiffness matrix if tensions: T1 = self.getTensions() J = np.zeros([len(T1), self.nCpldDOF]) # allocate Jacobian of tensions w.r.t. coupled DOFs if plots > 0: self.cpldDOFs.clear() # clear the positions history to refill if animating this process # ------------------------- perform linearization -------------------------------- if solveOption==0: # ::: forward difference approach ::: for i in range(self.nCpldDOF): # loop through each DOF X2 = np.array(X1, dtype=np.float_) X2[i] += dX[i] # perturb positions by dx in each DOF in turn self.setPositions(X2, DOFtype="coupled") # set the perturbed coupled DOFs self.solveEquilibrium() # let the system settle into equilibrium F2p = self.getForces(DOFtype="coupled", lines_only=lines_only) # get resulting coupled DOF net force/moment response if tensions: T2p = self.getTensions() if self.display > 2: print(F2p) if plots > 0: self.cpldDOFs.append(X2) K[:,i] = -(F2p-F1)/dX[i] # take finite difference of force w.r.t perturbation if tensions: J[:,i] = (T2p-T1)/dX[i] elif solveOption==1: # ::: adaptive central difference approach ::: #nTries = 1 # number of refinements to allow -1 for i in range(self.nCpldDOF): # loop through each DOF dXi = 1.0*dX[i] #print(f'__________ nCpldDOF = {i+1} __________') # potentially iterate with smaller step sizes if we're at a taut-slack transition (but don't get too small, or else numerical errors) for j in range(nTries): #print(f'-------- nTries = {j+1} --------') X2 = np.array(X1, dtype=np.float_) X2[i] += dXi # perturb positions by dx in each DOF in turn self.setPositions(X2, DOFtype="coupled") # set the perturbed coupled DOFs #print(f'solving equilibrium {i+1}+_{self.nCpldDOF}') self.solveEquilibrium(tol=eqTol) # let the system settle into equilibrium F2p = self.getForces(DOFtype="coupled", lines_only=lines_only) # get resulting coupled DOF net force/moment response if tensions: T2p = self.getTensions() if plots > 0: self.cpldDOFs.append(X2.copy()) X2[i] -= 2.0*dXi # now perturb from original to -dx self.setPositions(X2, DOFtype="coupled") # set the perturbed coupled DOFs #print(f'solving equilibrium {i+1}-_{self.nCpldDOF}') self.solveEquilibrium(tol=eqTol) # let the system settle into equilibrium F2m = self.getForces(DOFtype="coupled", lines_only=lines_only) # get resulting coupled DOF net force/moment response if tensions: T2m = self.getTensions() if plots > 0: self.cpldDOFs.append(X2.copy()) if j==0: F2pi = F2p F2mi = F2m if self.display > 2: print(f"j = {j} and dXi = {dXi}. F2m, F1, and F2p are {F2m[i]:6.2f} {F1[i]:6.2f} {F2p[i]:6.2f}") print(abs(F2m[i]-2.0*F1[i]+F2p[i])) #print(0.1*np.abs(F1[i])) print(0.1*np.abs(F2pi[i]-F2mi[i])) print(abs(F1[i])<1) #print(abs(F2m[i]-2.0*F1[i]+F2p[i]) < 0.1*np.abs(F1[i])) print(abs(F2m[i]-2.0*F1[i]+F2p[i]) < 0.1*np.abs(F2pi[i]-F2mi[i])) # Break if the force is zero or the change in the first derivative is small #if abs(F1[i]) < 1 or abs(F2m[i]-2.0*F1[i]+F2p[i]) < 0.1*np.abs(F1[i]): # note: the 0.1 is the adjustable tolerance if abs(F1[i]) < 1 or abs(F2m[i]-2.0*F1[i]+F2p[i]) < 0.1*np.abs(F2pi[i]-F2mi[i]): # note: the 0.1 is the adjustable tolerance break elif j == nTries-1: if self.display > 2: print("giving up on refinement") else: # Otherwise, we're at a tricky point and should stay in the loop to keep narrowing the step size # untill the derivatives agree better. Decrease the step size by 10X. dXi = 0.1*dXi K[:,i] = -0.5*(F2p-F2m)/dXi # take finite difference of force w.r.t perturbation if tensions: J[:,i] = 0.5*(T2p-T2m)/dX[i] else: raise ValueError("getSystemStiffness was called with an invalid solveOption (only 0 and 1 are supported)") # ----------------- restore the system back to previous positions ------------------ self.mooringEq(X1, DOFtype="coupled", tol=lineTol) self.solveEquilibrium(tol=eqTol) # show an animation of the stiffness perturbations if applicable if plots > 0: self.animateSolution() if tensions: return K, J else: return K def getSystemStiffnessA(self, DOFtype="free", lines_only=False, rho=1025, g=9.81): '''A method to calculate the system's stiffness matrix based entirely on analytic gradients from catenary Parameters ---------- DOFtype : string, optional specifies whether to consider 'free' DOFs, 'coupled' DOFs, or 'both'. The default is "free". hydro : bool, optional <<<<< replaced this with
<gh_stars>1-10 # coding: utf-8 from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from ks_api_client.api_client import ApiClient from ks_api_client.exceptions import ( # noqa: F401 ApiTypeError, ApiValueError ) class SuperMultipleOrderApi(object): def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def cancel_sm_order(self, consumerKey, sessionToken, orderId, **kwargs): # noqa: E501 """Cancel an Super Multiple order # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.cancel_sm_order(consumerKey, sessionToken, orderId, async_req=True) >>> result = thread.get() :param consumerKey: (required) :type consumerKey: str :param sessionToken: (required) :type sessionToken: str :param orderId: Order ID to cancel. (required) :type orderId: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True return self.cancel_sm_order_with_http_info(consumerKey, sessionToken, orderId, **kwargs) # noqa: E501 def cancel_sm_order_with_http_info(self, consumerKey, sessionToken, orderId, **kwargs): # noqa: E501 """Cancel an Super Multiple order # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.cancel_sm_order_with_http_info(consumerKey, sessionToken, orderId, async_req=True) >>> result = thread.get() :param consumerKey: (required) :type consumerKey: str :param sessionToken: (required) :type sessionToken: str :param orderId: Order ID to cancel. (required) :type orderId: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ local_var_params = locals() all_params = [ 'consumerKey', 'sessionToken', 'orderId' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method cancel_sm_order" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'consumerKey' is set if self.api_client.client_side_validation and ('consumerKey' not in local_var_params or # noqa: E501 local_var_params['consumerKey'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `consumerKey` when calling `cancel_sm_order`") # noqa: E501 # verify the required parameter 'sessionToken' is set if self.api_client.client_side_validation and ('sessionToken' not in local_var_params or # noqa: E501 local_var_params['sessionToken'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `sessionToken` when calling `cancel_sm_order`") # noqa: E501 # verify the required parameter 'orderId' is set if self.api_client.client_side_validation and ('orderId' not in local_var_params or # noqa: E501 local_var_params['orderId'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `orderId` when calling `cancel_sm_order`") # noqa: E501 collection_formats = {} path_params = {} if 'orderId' in local_var_params: path_params['orderId'] = local_var_params['orderId'] # noqa: E501 query_params = [] header_params = {} if 'consumerKey' in local_var_params: header_params['consumerKey'] = local_var_params['consumerKey'] # noqa: E501 if 'sessionToken' in local_var_params: header_params['sessionToken'] = local_var_params['sessionToken'] # noqa: E501 form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['bearerAuth'] # noqa: E501 return self.api_client.call_api( '/orders/1.0/order/supermultiple/{orderId}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='object', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def modify_sm_order(self, consumerKey, sessionToken, ExistingSMOrder, **kwargs): # noqa: E501 """Modify an existing super multiple order # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.modify_sm_order(consumerKey, sessionToken, ExistingSMOrder, async_req=True) >>> result = thread.get() :param consumerKey: Unique ID for your application (required) :type consumerKey: str :param sessionToken: Session ID for your application (required) :type sessionToken: str :param ExistingSMOrder: (required) :type ExistingSMOrder: ExistingSMOrder :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True return self.modify_sm_order_with_http_info(consumerKey, sessionToken, ExistingSMOrder, **kwargs) # noqa: E501 def modify_sm_order_with_http_info(self, consumerKey, sessionToken, ExistingSMOrder, **kwargs): # noqa: E501 """Modify an existing super multiple order # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.modify_sm_order_with_http_info(consumerKey, sessionToken, ExistingSMOrder, async_req=True) >>> result = thread.get() :param consumerKey: Unique ID for your application (required) :type consumerKey: str :param sessionToken: Session ID for your application (required) :type sessionToken: str :param ExistingSMOrder: (required) :type ExistingSMOrder: ExistingSMOrder :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ local_var_params = locals() all_params = [ 'consumerKey', 'sessionToken', 'ExistingSMOrder' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method modify_sm_order" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'consumerKey' is set if self.api_client.client_side_validation and ('consumerKey' not in local_var_params or # noqa: E501 local_var_params['consumerKey'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `consumerKey` when calling `modify_sm_order`") # noqa: E501 # verify the required parameter 'sessionToken' is set if self.api_client.client_side_validation and ('sessionToken' not in local_var_params or # noqa: E501 local_var_params['sessionToken'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `sessionToken` when calling `modify_sm_order`") # noqa: E501 # verify the required parameter 'ExistingSMOrder' is set if self.api_client.client_side_validation and ('ExistingSMOrder' not in local_var_params or # noqa: E501 local_var_params['ExistingSMOrder'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `ExistingSMOrder` when calling `modify_sm_order`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] header_params = {} if 'consumerKey' in local_var_params: header_params['consumerKey'] = local_var_params['consumerKey'] # noqa: E501 if 'sessionToken' in local_var_params: header_params['sessionToken'] = local_var_params['sessionToken'] # noqa: E501 form_params = [] local_var_files = {} body_params = None if 'ExistingSMOrder' in local_var_params: body_params = local_var_params['ExistingSMOrder'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['bearerAuth'] # noqa: E501 return self.api_client.call_api( '/orders/1.0/order/supermultiple', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='object', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) def place_new_sm_order(self,
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # ======================================================= """engine_common * SearchEngine Classから呼び出す、各検索エンジンで共通の処理を保持させる継承用Classである `CommonEngine` を持つモジュール. """ import requests import os import pickle # selenium driver auto install packages import chromedriver_autoinstaller import geckodriver_autoinstaller # seleniumrequests from seleniumrequests import Chrome, Firefox # selenium from selenium import webdriver from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.firefox.options import Options as FirefoxOptions from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from urllib import parse from fake_useragent import UserAgent from bs4 import BeautifulSoup from datetime import datetime from .common import Color, Message # 各検索エンジン用class共通の処理を記述した継承用class class CommonEngine: """CommonEngine 検索エンジンごとの処理を記述するClassのための、継承用Class. """ # Class作成時の処理 def __init__(self): # headless browserの利用有無フラグ(デフォルト: False) self.USE_SELENIUM = False self.USE_SPLASH = False # 初期値の作成 self.LOCK = None self.COOKIE_FILE = '' self.SPLASH_URI = '' self.PROXY = '' self.USER_AGENT = '' self.LANG = '' self.LOCALE = '' self.IS_DEBUG = False self.IS_COMMAND = False self.IS_DISABLE_HEADLESS = False self.MESSAGE = False # ReCaptcha画面かどうかの識別用(初期値(ブランク)) self.RECAPTCHA_SITEKEY = '' self.SOUP_RECAPTCHA_TAG = '' self.SOUP_RECAPTCHA_SITEKEY = '' # 検索エンジンにわたす言語・国の設定を受け付ける def set_lang(self, lang: str, locale: str): """set_lang 検索エンジンで指定する言語・国の設定を行う関数 Args: lang (str): 検索エンジンのパラメータで指定する言語を指定する([ja,en]) locale (str): 検索エンジンのパラメータで指定する国を指定する([JP,US]) """ self.LANG = lang self.LOCALE = locale # 検索時の日時範囲を指定 def set_range(self, start: datetime, end: datetime): """set_range 検索エンジンで指定する日付範囲を指定する Args: start (datetime): 検索対象ページの対象範囲開始日時(datetime) end (datetime): 検索対象ページの対象範囲終了日時(datetime) """ self.RANGE_START = start self.RANGE_END = end # user_agentの設定値を受け付ける(引数がない場合はランダム。Seleniumの際は自動的に使用したbrowserのagentを指定) def set_user_agent(self, user_agent: str = None, browser: str = None): """set_user_agent user_agentの値を受け付ける. user_agentの指定がない場合、 Chromeを使用したものとする. また、もし`browser`が指定されている場合はそのブラウザのUser Agentを指定する. 注) seleniumを利用する場合、事前に有効にする必要がある。 Args: user_agent (str, optional): User Agentを指定する. Defaults to None. browser (str, optional): Seleniumで使用するBrowserを指定する([chrome, firefox]). Defaults to None. """ if user_agent is None: # seleniumが有効になっている場合、そのままSeleniumで利用するブラウザのUAを使用する if self.USE_SELENIUM: user_agent = '' else: try: ua = UserAgent(verify_ssl=False, use_cache_server=True) if user_agent is None: if browser is None: user_agent = ua.firefox elif browser == 'chrome': user_agent = ua.chrome elif browser == 'firefox': user_agent = ua.chrome except Exception: user_agent = 'Mozilla/5.0 (Linux; Android 10; SM-A205U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Mobile Safari/537.36.' self.USER_AGENT = user_agent # seleniumを有効にする # - splashより優先 # - host, browserは、指定がない場合はそれぞれデフォルト設定(hostは指定なし、browserはchrome)での動作 # - browserは `chrome` or `firefox` のみ受け付ける def set_selenium(self, uri: str = None, browser: str = None): """set_selenium 検索時にSelenium経由で通信を行う. 他のHeadless Browserと比較して最優先(Splash等が有効でもこちらが優先される). Args: uri (str, optional): APIのURIを指定(localhost:4444). Defaults to None. browser (str, optional): 使用するブラウザを指定([chrome, firefox]). Defaults to None. """ # 入力値検証(browser: chrome or firefox) if browser is None: browser = 'chrome' # USE_SELENIUM to True self.USE_SELENIUM = True self.SELENIUM_URI = uri self.SELENIUM_BROWSER = browser # proxyの設定を受け付ける def set_proxy(self, proxy: str): """set_proxy 検索時に使用するProxyを指定する(uri指定) Args: proxy (str): ProxyのURIを指定する(socks5://localhost:11080, http://hogehoge:8080) """ self.PROXY = proxy # splash urlの値を受け付ける def set_splash(self, splash_url: str): """set_splash 検索時にSplashを有効にする. (Seleniumと同時に有効化されている場合、Seleniumを優先する) Args: splash_url (str): Splashのアクセス先URIを指定する(ex: `localhost:8050`) """ self.USE_SPLASH = True self.SPLASH_URI = splash_url # common.Messageを受け付ける def set_messages(self, message: Message): self.MESSAGE = message # cookieをcookiefileから取得する def read_cookies(self): """read_cookies `self.COOKIE_FILE` からcookieを読み込む. 現時点ではSeleniumでのみ動作. """ # cookieファイルのサイズを取得 file_size = os.path.getsize(self.COOKIE_FILE) # cookieファイルのサイズが0以上の場合 if file_size > 0: # cookie fileからcookieの取得 cookies = pickle.load(open(self.COOKIE_FILE, "rb")) # seleniumを使う場合 if self.USE_SELENIUM: # 事前アクセスが必要になるため、検索対象ドメインのTOPページにアクセスしておく self.driver.get(self.ENGINE_TOP_URL) # cookieを設定していく for cookie in cookies: try: self.driver.add_cookie(cookie) except Exception: pass # splashを使う場合 elif self.USE_SPLASH: # NOTE: 動作しないためコメントアウト # TODO: 確認して修正 # self.session.cookies.update(cookies) None # requestを使う場合 else: # NOTE: 動作しないためコメントアウト # TODO: 確認して修正 # self.session.cookies.update(cookies) None # cookieをcookiefileに書き込む def write_cookies(self): """write_cookies cookiesを `self.COOKIE_FILE` に書き込む. """ cookies = None # seleniumを使う場合 if self.USE_SELENIUM: cookies = self.driver.get_cookies() # splashを使う場合 elif self.USE_SPLASH: cookies = self.session.cookies # requestを使う場合 else: cookies = self.session.cookies # cookieを書き込み with open(self.COOKIE_FILE, 'wb') as f: pickle.dump(cookies, f) # seleniumのOptionsを作成 def create_selenium_options(self): """create_selenium_options Seleniumのoptionsを生成して返す. Returns: Options: 指定されたブラウザに応じたSeleniumのOptionsを返す. """ if self.SELENIUM_BROWSER == 'chrome': options = ChromeOptions() elif self.SELENIUM_BROWSER == 'firefox': options = FirefoxOptions() # set headless option if not self.IS_DISABLE_HEADLESS: options.add_argument('--headless') # set user_agent option if self.USER_AGENT != '': options.add_argument('--user-agent=%s' % self.USER_AGENT) return options # selenium driverの作成 def create_selenium_driver(self): """create_selenium_driver Seleniumで使用するDriverを作成する関数. Optionsもこの関数で作成する. """ # optionsを取得する options = self.create_selenium_options() # proxyを追加 if self.PROXY != '': options.add_argument('--proxy-server=%s' % self.PROXY) # debug: 投げてるリクエストの調査のため # options.add_argument('--proxy-server=%s' % 'http://localhost:8080') # browserに応じてdriverを作成していく if self.SELENIUM_BROWSER == 'chrome': chromedriver_autoinstaller.install() self.driver = Chrome(options=options) elif self.SELENIUM_BROWSER == 'firefox': # profileを作成する profile = webdriver.FirefoxProfile() profile.set_preference('devtools.jsonview.enabled', False) profile.set_preference('plain_text.wrap_long_lines', False) profile.set_preference('view_source.wrap_long_lines', False) # debug comment out. # capabilities = webdriver.DesiredCapabilities().FIREFOX # capabilities['acceptSslCerts'] = True geckodriver_autoinstaller.install() self.driver = Firefox(options=options, firefox_profile=profile) # NOTE: # User Agentを確認する場合、↓の処理で実施可能(Chrome/Firefoxともに)。 # ```python # user_agent = self.driver.execute_script("return navigator.userAgent") # print(user_agent) # ``` return # selenium経由でリクエストを送信する def request_selenium(self, url: str, method='GET', data=None): """[summary] Selenium経由でGETリクエストを投げて、その結果をhtml(文字列)で返す. Args: url (str): リクエストを投げるurl. method (str): リクエストメソッド. data (str): POSTメソッド時に利用するdata. Returns: str: htmlの文字列. """ if method == 'GET': response = self.driver.get(url) # wait all elements WebDriverWait(self.driver, 15).until( EC.presence_of_all_elements_located) # wait 5 seconds(wait DOM) if self.NAME in ('Bing', 'Baidu', 'DuckDuckGo'): self.driver.implicitly_wait(20) # get result result = self.driver.page_source elif method == 'POST': response = self.driver.request('POST', url, data=data) # wait all elements WebDriverWait(self.driver, 15).until( EC.presence_of_all_elements_located) # wait 5 seconds(wait DOM) if self.NAME in ('Bing', 'Baidu', 'DuckDuckGo'): self.driver.implicitly_wait(20) # get result result = response.text return result # splash経由でのリクエストを送信する def request_splash(self, url: str, method='GET', data=None): """request_splash Splash経由でGETリクエストを投げて、その結果をhtml(文字列)で返す. Args: url (str): リクエストを投げるurl. method (str): リクエストメソッド. data (str): POSTメソッド時に利用するdata. Returns: str: htmlの文字列. """ # urlを生成する splash_url = 'http://' + self.SPLASH_URI + '/render.html' # param params = { 'url': url } # Proxy指定をする場合 if self.PROXY != '': params['proxy'] = self.PROXY # リクエストを投げてレスポンスを取得する if method == 'GET': result = self.session.get(splash_url, params=params).text # NOTE: Googleの画像検索のPOSTがSplashではレンダリングできないので、特例対応でrequestsを使用する. # TODO: Splashでもレンダリングできるようになったら書き換える. elif method == 'POST' and self.NAME == 'Google' and self.IMAGE_URL in url: # create session session = requests.session() # proxyを設定 if self.PROXY != '': proxies = { 'http': self.PROXY, 'https': self.PROXY } session.proxies = proxies # user-agentを設定 if self.USER_AGENT != '': session.headers.update( { 'User-Agent': self.USER_AGENT, 'Accept-Language': 'ja,en-US;q=0.7,en;q=0.3' } ) result = session.post(url, data=data).text elif method == 'POST': headers = {'Content-Type': 'application/json'} params['http_method'] = 'POST' params['body'] = parse.urlencode(data) result = self.session.post( splash_url, headers=headers, json=params ).text return result # seleniumやsplushなどのヘッドレスブラウザ、request.sessionの作成・設定、cookieの読み込みを行う def create_session(self): """create_session 指定された接続方式(Seleniumなどのヘッドレスブラウザの有無)に応じて、driverやsessionを作成する. cookiesの読み込みやproxyの設定が必要な場合、この関数内で処理を行う. """ # seleniumを使う場合 if self.USE_SELENIUM: self.create_selenium_driver() # splashを使う場合 elif self.USE_SPLASH: # create session self.session = requests.session() # user-agentを設定 if self.USER_AGENT != '': self.session.headers.update( { 'User-Agent': self.USER_AGENT, 'Accept-Language': 'ja,en-US;q=0.7,en;q=0.3' } ) # requestを使う場合 else: # create session self.session = requests.session() # リダイレクトの上限を60にしておく(baidu対策) self.session.max_redirects = 60 # proxyを設定 if self.PROXY != '': proxies = { 'http': self.PROXY, 'https': self.PROXY } self.session.proxies = proxies # user-agentを設定 if self.USER_AGENT != '': self.session.headers.update( { 'User-Agent': self.USER_AGENT, 'Accept-Language': 'ja,en-US;q=0.7,en;q=0.3' } ) # cookiefileが指定されている場合、読み込みを行う if self.COOKIE_FILE != '': self.read_cookies() return # sessionをcloseする def close_session(self): if self.USE_SELENIUM: self.driver.quit() else: self.session.close() # リクエストを投げてhtmlを取得する(selenium/splash/requestで分岐してリクエストを投げるwrapperとして動作させる) def get_result(self, url: str, method='GET', data=None): """get_result 接続方式に応じて、urlへGETリクエストを投げてhtmlを文字列で返す関数. Args: url (str): リクエストを投げるurl. method (str): リクエストメソッド. data (str): POSTメソッド時に利用するdata. Returns: str: htmlの文字列. """ # 優先度1: Selenium経由でのアクセス if self.USE_SELENIUM: result = self.request_selenium(url, method=method, data=data) # 優先度2: Splash経由でのアクセス(Seleniumが有効になってない場合はこちら) elif self.USE_SPLASH: # create splash url result = self.request_splash(url, method=method, data=data) # 優先度3: request.sessionからのリクエスト(SeleniumもSplashも有効でない場合) else: if method == 'GET': result = self.session.get(url).text elif method == 'POST': result = self.session.post(url, data=data).text return result # 検索用のurlを生成 def gen_search_url(self, keyword: str, type: str): """gen_search_url 検索用のurlを生成する. 各検索エンジンで上書きする用の関数. Args: keyword (str): 検索クエリ. type (str): 検索タイプ. Returns: dict: method dict: 検索用url dict: data """ result = {} return 'GET', result, None # テキスト、画像検索の結果からlinksを取得するための集約function def get_links(self, html: str, type: str): """get_links 受け付けたhtmlを解析し、検索結果をlistに加工して返す関数. Args: html (str): 解析する検索結果のhtml. type (str): 検索タイプ([text, image]).現時点ではtextのみ対応. Returns: list: 検索結果(`[{'title': 'title...', 'link': 'https://hogehoge....'}, {...}]`) """ # BeautifulSoupでの解析を実施 soup = BeautifulSoup(html, 'lxml') if type == 'text': # link, titleの組み合わせを取得する elinks, etitles, etexts = self.get_text_links(soup) # before processing elists self.MESSAGE.print_text( ','.join(elinks), header=self.MESSAGE.HEADER + ': ' + Color.BLUE + '[BeforeProcessing elinks]' + Color.END, separator=" :", mode="debug", ) # before processing etitles self.MESSAGE.print_text( ','.join(etitles), header=self.MESSAGE.HEADER + ': ' + Color.BLUE + '[BeforeProcessing etitles]' + Color.END, separator=" :", mode="debug", ) # 加工処理を行う関数に渡す(各エンジンで独自対応) elinks, etitles, etexts = self.processings_elist( elinks, etitles, etexts) # after processing elists self.MESSAGE.print_text( ','.join(elinks), header=self.MESSAGE.HEADER + ': ' + Color.GREEN + '[AfterProcessing elinks]' + Color.END, separator=" :", mode="debug", ) # after processing etitles self.MESSAGE.print_text( ','.join(etitles), header=self.MESSAGE.HEADER + ': ' + Color.GREEN + '[AfterProcessing etitles]' + Color.END, separator=" :", mode="debug", ) # dictに加工してリスト化する # [{'title': 'title...', 'link': 'https://hogehoge....'}, {...}] links = self.create_text_links(elinks, etitles, etexts) return links elif type == 'image': links = self.get_image_links(soup) return links # テキスト検索ページの検索結果(links([{link: ..., title: ...},...]))を生成するfunction def get_text_links(self, soup: BeautifulSoup): """get_text_links BeautifulSoupからテキスト検索ページを解析して結果を返す関数. Args: soup (BeautifulSoup): 解析するBeautifulSoupオブジェクト. Returns: list: linkの検索結果([xxx,xxx,xxx...) list: titleの検索結果([xxx,xxx,xxx...) """ # linkのurlを取得する elements = soup.select(self.SOUP_SELECT_URL) elinks = [e['href'] for e in elements] # linkのtitleを取得する elements = soup.select(self.SOUP_SELECT_TITLE) etitles = [e.text
"nullable": True, "alias": "是否自愈", "description": "是否自愈", "dim": "self_healing", "type": "BOOLEAN" }, { "buildIn": True, "field": "weight", "nullable": True, "alias": "健康权重", "description": "健康权重", "dim": "weight", "type": "INTEGER" }] }, { "metaReq": { "description": "异常实例模型(增量分区)", "tableAlias": "dwd_stability_incident_instance_di", "layer": "dwd", "tableName": "<dwd_stability_incident_instance_di_{now/d}>", "buildIn": True, "lifecycle": 7, "name": "INCIDENT_INSTANCE", "alias": "异常实例", "partitionFormat": "d", "domainId": 1, "dataMode": "di" }, "fieldsReq": [{ "buildIn": True, "field": "appComponentInstanceId", "nullable": True, "alias": "应用组件实例ID", "description": "应用组件实例ID", "dim": "app_component_instance_id", "type": "STRING" }, { "buildIn": True, "field": "appComponentName", "nullable": True, "alias": "应用组件名称", "description": "应用组件名称", "dim": "app_component_name", "type": "STRING" }, { "buildIn": True, "field": "appId", "nullable": False, "alias": "应用ID", "description": "应用ID", "dim": "app_id", "type": "STRING" }, { "buildIn": True, "field": "appInstanceId", "nullable": False, "alias": "应用实例ID", "description": "应用实例ID", "dim": "app_instance_id", "type": "STRING" }, { "buildIn": True, "field": "appName", "nullable": True, "alias": "应用名称", "description": "应用名称", "dim": "app_name", "type": "STRING" }, { "buildIn": True, "field": "cause", "nullable": True, "alias": "异常产生原因", "description": "异常产生原因", "dim": "cause", "type": "STRING" }, { "buildIn": True, "field": "defId", "nullable": False, "alias": "关联定义ID", "description": "异常实例所属的定义ID", "dim": "def_id", "type": "STRING" }, { "buildIn": True, "field": "defName", "nullable": False, "alias": "关联定义名称", "description": "异常实例所属的定义名称", "dim": "def_name", "type": "STRING" }, { "buildIn": True, "field": "description", "nullable": True, "alias": "说明", "description": "备注说明信息", "dim": "description", "type": "STRING" }, { "buildIn": True, "field": "gmtCreate", "nullable": True, "alias": "创建时间", "description": "异常实例创建时间", "dim": "gmt_create", "type": "DATE" }, { "buildIn": True, "field": "gmtLastOccur", "nullable": True, "alias": "最近发生时间", "description": "最近发生时间", "dim": "gmt_last_occur", "type": "DATE" }, { "buildIn": True, "field": "gmtModified", "nullable": True, "alias": "修改时间", "description": "异常实例最近修改时间", "dim": "gmt_modified", "type": "DATE" }, { "buildIn": True, "field": "gmtOccur", "nullable": True, "alias": "发生时间", "description": "异常发生时间", "dim": "gmt_occur", "type": "DATE" }, { "buildIn": True, "field": "gmtRecovery", "nullable": True, "alias": "恢复时间", "description": "异常恢复时间", "dim": "gmt_recovery", "type": "DATE" }, { "buildIn": True, "field": "gmtSelfHealingEnd", "nullable": True, "alias": "自愈结束时间", "description": "自愈结束时间", "dim": "gmt_self_healing_end", "type": "DATE" }, { "buildIn": True, "field": "gmtSelfHealingStart", "nullable": True, "alias": "自愈开始时间", "description": "自愈开始时间", "dim": "gmt_self_healing_start", "type": "DATE" }, { "buildIn": True, "field": "id", "nullable": False, "alias": "异常实例ID", "description": "主键", "dim": "id", "type": "STRING" }, { "buildIn": True, "field": "occurTimes", "nullable": True, "alias": "最近连续发生次数", "description": "最近连续发生次数", "dim": "occur_times", "type": "INTEGER" }, { "buildIn": True, "field": "options", "nullable": True, "alias": "扩展信息", "description": "用户自定义参数", "dim": "options", "type": "STRING" }, { "buildIn": True, "field": "selfHealingStatus", "nullable": True, "alias": "自愈状态", "description": "自愈状态", "dim": "self_healing_status", "type": "STRING" }, { "buildIn": True, "field": "source", "nullable": True, "alias": "异常来源", "description": "异常来源", "dim": "source", "type": "STRING" }, { "buildIn": True, "field": "spanId", "nullable": False, "alias": "层次ID", "description": "层次ID", "dim": "span_id", "type": "STRING" }, { "buildIn": True, "field": "traceId", "nullable": False, "alias": "任务链ID", "description": "任务链ID", "dim": "trace_id", "type": "STRING" }, { "buildIn": True, "field": "typeId", "nullable": False, "alias": "异常类型ID", "description": "异常类型ID", "dim": "type_id", "type": "INTEGER" }, { "buildIn": True, "field": "typeName", "nullable": False, "alias": "异常类型名称", "description": "异常类型名称", "dim": "type_name", "type": "STRING" }] }, { "metaReq": { "description": "故障定义模型(全量分区)", "tableAlias": "dwd_stability_failure_df", "layer": "dwd", "tableName": "<dwd_stability_failure_df_{now/d}>", "buildIn": True, "lifecycle": 7, "name": "FAILURE", "alias": "故障定义", "partitionFormat": "d", "domainId": 1, "dataMode": "df" }, "fieldsReq": [{ "buildIn": True, "field": "appComponentName", "nullable": True, "alias": "应用组件名称", "description": "应用组件名称", "dim": "app_component_name", "type": "STRING" }, { "buildIn": True, "field": "appId", "nullable": False, "alias": "归属应用ID", "description": "故障所属的应用ID", "dim": "app_id", "type": "STRING" }, { "buildIn": True, "field": "appName", "nullable": True, "alias": "应用名称", "description": "归属应用名称", "dim": "app_name", "type": "STRING" }, { "buildIn": True, "field": "category", "nullable": False, "alias": "类型", "description": "类型(failure)", "dim": "category", "type": "STRING" }, { "buildIn": True, "field": "creator", "nullable": True, "alias": "创建人", "description": "创建人", "dim": "creator", "type": "STRING" }, { "buildIn": True, "field": "description", "nullable": True, "alias": "说明", "description": "备注说明信息", "dim": "description", "type": "STRING" }, { "buildIn": True, "field": "failureLevelRule", "nullable": False, "alias": "故障等级定义规则", "description": "故障等级定义规则", "dim": "failure_level_rule", "type": "OBJECT" }, { "buildIn": True, "field": "gmtCreate", "nullable": True, "alias": "创建时间", "description": "创建时间", "dim": "gmt_create", "type": "DATE" }, { "buildIn": True, "field": "gmtModified", "nullable": True, "alias": "修改时间", "description": "最近修改时间", "dim": "gmt_modified", "type": "DATE" }, { "buildIn": True, "field": "id", "nullable": False, "alias": "故障ID", "description": "主键", "dim": "id", "type": "STRING" }, { "buildIn": True, "field": "lastModifier", "nullable": True, "alias": "最近修改人", "description": "最近修改人", "dim": "last_modifier", "type": "STRING" }, { "buildIn": True, "field": "name", "nullable": False, "alias": "故障名称", "description": "故障名称", "dim": "name", "type": "STRING" }, { "buildIn": True, "field": "refIncidentDefId", "nullable": False, "alias": "关联异常ID", "description": "关联异常ID", "dim": "ref_incident_def_id", "type": "STRING" }, { "buildIn": True, "field": "refIncidentDefName", "nullable": False, "alias": "关联异常名称", "description": "关联异常名称", "dim": "ref_incident_def_name", "type": "STRING" }] }, { "metaReq": { "description": "故障实例模型(增量分区)", "tableAlias": "dwd_stability_failure_instance_di", "layer": "dwd", "tableName": "<dwd_stability_failure_instance_di_{now/d}>", "buildIn": True, "lifecycle": 7, "name": "FAILURE_INSTANCE", "alias": "故障实例", "partitionFormat": "d", "domainId": 1, "dataMode": "di" }, "fieldsReq": [{ "buildIn": True, "field": "appComponentInstanceId", "nullable": True, "alias": "应用组件实例ID", "description": "应用组件实例ID", "dim": "app_component_instance_id", "type": "STRING" }, { "buildIn": True, "field": "appComponentName", "nullable": True, "alias": "应用组件名称", "description": "应用组件名称", "dim": "app_component_name", "type": "STRING" }, { "buildIn": True, "field": "appId", "nullable": False, "alias": "应用ID", "description": "应用ID", "dim": "app_id", "type": "STRING" }, { "buildIn": True, "field": "appInstanceId", "nullable": False, "alias": "应用实例ID", "description": "应用实例ID", "dim": "app_instance_id", "type": "STRING" }, { "buildIn": True, "field": "appName", "nullable": True, "alias": "应用名称", "description": "应用名称", "dim": "app_name", "type": "STRING" }, { "buildIn": True, "field": "defId", "nullable": False, "alias": "关联定义ID", "description": "故障实例所属的定义ID", "dim": "def_id", "type": "STRING" }, { "buildIn": True, "field": "defName", "nullable": False, "alias": "关联定义名称", "description": "故障实例所属的定义名称", "dim": "def_name", "type": "STRING" }, { "buildIn": True, "field": "gmtCreate", "nullable": True, "alias": "创建时间", "description": "故障实例创建时间", "dim": "gmt_create", "type": "DATE" }, { "buildIn": True, "field": "gmtModified", "nullable": True, "alias": "修改时间", "description": "故障实例最近修改时间", "dim": "gmt_modified", "type": "DATE" }, { "buildIn": True, "field": "gmtOccur", "nullable": True, "alias": "发生时间", "description": "故障发生时间", "dim": "gmt_occur", "type": "DATE" }, { "buildIn": True, "field": "id", "nullable": False, "alias": "故障实例ID", "description": "主键", "dim": "id", "type": "STRING" }, { "buildIn": True, "field": "incidentId", "nullable": False, "alias": "异常实例ID", "description": "异常实例ID", "dim": "incident_id", "type": "STRING" }, { "buildIn": True, "field": "level", "nullable": False, "alias": "故障等级", "description": "故障等级", "dim": "level", "type": "STRING" }, { "buildIn": True, "field": "name", "nullable": False, "alias": "故障名称", "description": "故障名称", "dim": "name", "type": "STRING" }, { "buildIn": True, "field": "refIncidentDefId", "nullable": False, "alias": "关联异常ID", "description": "关联异常ID", "dim": "ref_incident_def_id", "type": "STRING" }, { "buildIn": True, "field": "refIncidentDefName", "nullable": False, "alias": "关联异常名称", "description": "关联异常名称", "dim": "ref_incident_def_name", "type": "STRING" }, { "buildIn": True, "field": "refIncidentTypeId", "nullable": False, "alias": "关联异常类型ID", "description": "关联异常类型ID", "dim": "ref_incident_type_id", "type": "INTEGER" }, { "buildIn": True, "field": "refIncidentTypeLabel", "nullable": False, "alias": "关联异常类型标识", "description": "关联异常类型标识", "dim": "ref_incident_type_label", "type": "STRING" }, { "buildIn": True, "field": "refIncidentTypeName", "nullable": False, "alias": "关联异常类型名称", "description": "关联异常类型名称", "dim": "ref_incident_type_name", "type": "STRING" }] }, { "metaReq": { "description": "异常类型维度模型", "tableAlias": "dim_stability_incident_type", "layer": "dim", "tableName": "<dim_stability_incident_type_{now/d}>", "buildIn": True, "lifecycle": 7, "name": "INCIDENT_TYPE", "alias": "异常类型", "partitionFormat": "d", "domainId": 1 }, "fieldsReq": [{ "buildIn": True, "field": "creator", "nullable": True, "alias": "创建人", "description": "创建人", "dim": "creator", "type": "STRING" }, { "buildIn": True, "field": "description", "nullable": True, "alias": "说明", "description": "备注说明信息", "dim": "description", "type": "STRING" }, { "buildIn": True, "field": "gmt_create", "nullable": True, "alias": "创建时间", "description": "创建时间", "dim": "gmt_create", "type": "DATE" }, { "buildIn": True, "field": "gmt_modified", "nullable": True, "alias": "修改时间", "description": "最近修改时间", "dim": "gmt_modified", "type": "DATE" }, { "buildIn": True, "field": "id", "nullable": False, "alias": "异常类型ID", "description": "主键", "dim": "id", "type": "STRING" }, { "buildIn": True, "field": "label", "nullable": False, "alias": "异常类型标识", "description": "唯一标识", "dim": "label", "type": "STRING" }, { "buildIn": True, "field": "last_modifier", "nullable": True, "alias": "最近修改人", "description": "最近修改人", "dim": "last_modifier", "type": "STRING" }, { "buildIn": True, "field": "mq_topic", "nullable": False, "alias": "消息队列topic", "description": "消息队列topic", "dim": "mq_topic", "type": "STRING" }, { "buildIn": True, "field": "name", "nullable": False, "alias": "异常类型名称", "description": "异常类型名称", "dim": "name", "type": "STRING" }] }, { "metaReq": { "description": "命名空间维度模型", "tableAlias": "dim_business_namespace", "layer": "dim", "tableName": "<dim_business_namespace_{now/d}>", "buildIn": True, "lifecycle": 7, "name": "NAMESPACE", "alias": "命名空间", "partitionFormat": "d", "domainId": 9 }, "fieldsReq": [{ "buildIn": True, "field": "id", "nullable": False, "alias": "命名空间ID", "description": "主键", "dim": "id", "type": "STRING" }] }, { "metaReq": { "description": "租户维度模型", "tableAlias": "dim_business_tenant", "layer": "dim", "tableName": "<dim_business_tenant_{now/d}>", "buildIn": True, "lifecycle": 7, "name": "TENANT", "alias": "租户", "partitionFormat": "d", "domainId": 9 }, "fieldsReq": [{ "buildIn": True, "field": "id", "nullable": False, "alias": "租户ID",
int]]) def test_err_union_with_custom_type(self, typ): with pytest.raises(TypeError) as rec: msgspec.msgpack.Decoder(typ) assert "custom type" in str(rec.value) assert repr(typ) in str(rec.value) @pytest.mark.parametrize("typ", [Union[dict, Person], Union[Person, dict]]) def test_err_union_with_struct_and_dict(self, typ): with pytest.raises(TypeError) as rec: msgspec.msgpack.Decoder(typ) assert "both a Struct type and a dict type" in str(rec.value) assert repr(typ) in str(rec.value) @pytest.mark.parametrize("typ", [Union[PersonAA, list], Union[tuple, PersonAA]]) def test_err_union_with_struct_asarray_and_array(self, typ): with pytest.raises(TypeError) as rec: msgspec.msgpack.Decoder(typ) assert "asarray=True" in str(rec.value) assert "Type unions containing" in str(rec.value) assert repr(typ) in str(rec.value) @pytest.mark.parametrize("typ", [Union[FruitInt, int], Union[int, FruitInt]]) def test_err_union_with_intenum_and_int(self, typ): with pytest.raises(TypeError) as rec: msgspec.msgpack.Decoder(typ) assert "int and an IntEnum" in str(rec.value) assert repr(typ) in str(rec.value) @pytest.mark.parametrize("typ", [Union[FruitStr, str], Union[str, FruitStr]]) def test_err_union_with_enum_and_str(self, typ): with pytest.raises(TypeError) as rec: msgspec.msgpack.Decoder(typ) assert "str and an Enum" in str(rec.value) assert repr(typ) in str(rec.value) @pytest.mark.parametrize( "typ,kind", [ (Union[Person, PersonAA], "Struct"), (Union[Person, Node], "Struct"), (Union[FruitInt, VeggieInt], "IntEnum"), (Union[FruitStr, VeggieStr], "Enum"), (Union[Dict[int, float], dict], "dict"), (Union[List[int], List[float]], "array-like"), (Union[List[int], tuple], "array-like"), (Union[set, tuple], "array-like"), (Union[Tuple[int, ...], list], "array-like"), (Union[Tuple[int, float, str], set], "array-like"), (Union[Deque, int, Point], "custom"), ], ) def test_err_union_conflicts(self, typ, kind): with pytest.raises(TypeError) as rec: msgspec.msgpack.Decoder(typ) assert f"more than one {kind}" in str(rec.value) assert repr(typ) in str(rec.value) def test_decode_with_trailing_characters_errors(self): dec = msgspec.msgpack.Decoder() msg = msgspec.msgpack.encode([1, 2, 3]) + b"trailing" with pytest.raises(msgspec.DecodeError): dec.decode(msg) class TestTypedDecoder: def check_unexpected_type(self, dec_type, val, msg): dec = msgspec.msgpack.Decoder(dec_type) s = msgspec.msgpack.Encoder().encode(val) with pytest.raises(msgspec.DecodeError, match=msg): dec.decode(s) def test_any(self): dec = msgspec.msgpack.Decoder(Any) assert dec.decode(msgspec.msgpack.encode([1, 2, 3])) == [1, 2, 3] # A union that includes `Any` is just `Any` dec = msgspec.msgpack.Decoder(Union[Any, float, int, None]) assert dec.decode(msgspec.msgpack.encode([1, 2, 3])) == [1, 2, 3] def test_none(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(None) assert dec.decode(enc.encode(None)) is None with pytest.raises(msgspec.DecodeError, match="Expected `null`"): assert dec.decode(enc.encode(1)) @pytest.mark.parametrize("x", [False, True]) def test_bool(self, x): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(bool) assert dec.decode(enc.encode(x)) is x def test_bool_unexpected_type(self): self.check_unexpected_type(bool, "a", "Expected `bool`") @pytest.mark.parametrize("x", INTS) def test_int(self, x): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(int) assert dec.decode(enc.encode(x)) == x def test_int_unexpected_type(self): self.check_unexpected_type(int, "a", "Expected `int`") @pytest.mark.parametrize("x", FLOATS + INTS) def test_float(self, x): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(float) res = dec.decode(enc.encode(x)) sol = float(x) if math.isnan(sol): assert math.isnan(res) else: assert res == sol def test_float_unexpected_type(self): self.check_unexpected_type(float, "a", "Expected `float`") def test_decode_float4(self): x = 1.2 packed = struct.pack(">f", x) # Loss of resolution in float32 leads to some rounding error x4 = struct.unpack(">f", packed)[0] msg = b"\xca" + packed assert msgspec.msgpack.decode(msg) == x4 assert msgspec.msgpack.decode(msg, type=float) == x4 @pytest.mark.parametrize("size", SIZES) def test_str(self, size): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(str) x = "a" * size res = dec.decode(enc.encode(x)) assert res == x def test_str_unexpected_type(self): self.check_unexpected_type(str, 1, "Expected `str`") @pytest.mark.parametrize("size", SIZES) def test_bytes(self, size): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(bytes) x = b"a" * size res = dec.decode(enc.encode(x)) assert isinstance(res, bytes) assert res == x def test_bytes_unexpected_type(self): self.check_unexpected_type(bytes, 1, "Expected `bytes`") @pytest.mark.parametrize("size", SIZES) def test_bytearray(self, size): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(bytearray) x = bytearray(size) res = dec.decode(enc.encode(x)) assert isinstance(res, bytearray) assert res == x def test_bytearray_unexpected_type(self): self.check_unexpected_type(bytearray, 1, "Expected `bytes`") def test_datetime(self): dec = msgspec.msgpack.Decoder(datetime.datetime) x = datetime.datetime.now(UTC) res = dec.decode(msgspec.msgpack.encode(x)) assert x == res def test_datetime_unexpected_type(self): self.check_unexpected_type(datetime.datetime, 1, "Expected `datetime`") self.check_unexpected_type( datetime.datetime, msgspec.msgpack.Ext(1, b"test"), "Expected `datetime`" ) @pytest.mark.parametrize("size", SIZES) def test_list_lengths(self, size): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(list) x = list(range(size)) res = dec.decode(enc.encode(x)) assert res == x @pytest.mark.parametrize("typ", [list, List, List[Any]]) def test_list_any(self, typ): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(typ) x = [1, "two", b"three"] res = dec.decode(enc.encode(x)) assert res == x with pytest.raises(msgspec.DecodeError, match="Expected `array`"): dec.decode(enc.encode(1)) def test_list_typed(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(List[int]) x = [1, 2, 3] res = dec.decode(enc.encode(x)) assert res == x with pytest.raises( msgspec.DecodeError, match=r"Expected `int`, got `str` - at `\$\[2\]`", ): dec.decode(enc.encode([1, 2, "three"])) @pytest.mark.parametrize("size", SIZES) def test_set_lengths(self, size): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(set) x = set(range(size)) res = dec.decode(enc.encode(x)) assert res == x @pytest.mark.parametrize("typ", [set, Set, Set[Any]]) def test_set_any(self, typ): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(typ) x = {1, "two", b"three"} res = dec.decode(enc.encode(x)) assert res == x with pytest.raises(msgspec.DecodeError, match="Expected `array`"): dec.decode(enc.encode(1)) def test_set_typed(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(Set[int]) x = {1, 2, 3} res = dec.decode(enc.encode(x)) assert res == x with pytest.raises( msgspec.DecodeError, match=r"Expected `int`, got `str` - at `\$\[2\]`", ): dec.decode(enc.encode([1, 2, "three"])) @pytest.mark.parametrize("size", SIZES) def test_vartuple_lengths(self, size): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(tuple) x = tuple(range(size)) res = dec.decode(enc.encode(x)) assert res == x @pytest.mark.parametrize("typ", [tuple, Tuple, Tuple[Any, ...]]) def test_vartuple_any(self, typ): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(typ) x = (1, "two", b"three") res = dec.decode(enc.encode(x)) assert res == x with pytest.raises(msgspec.DecodeError, match="Expected `array`, got `int`"): dec.decode(enc.encode(1)) def test_vartuple_typed(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(Tuple[int, ...]) x = (1, 2, 3) res = dec.decode(enc.encode(x)) assert res == x with pytest.raises( msgspec.DecodeError, match=r"Expected `int`, got `str` - at `\$\[2\]`", ): dec.decode(enc.encode((1, 2, "three"))) def test_fixtuple_any(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(Tuple[Any, Any, Any]) x = (1, "two", b"three") res = dec.decode(enc.encode(x)) assert res == x with pytest.raises(msgspec.DecodeError, match="Expected `array`, got `int`"): dec.decode(enc.encode(1)) with pytest.raises( msgspec.DecodeError, match="Expected `array` of length 3, got 2" ): dec.decode(enc.encode((1, 2))) def test_fixtuple_typed(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(Tuple[int, str, bytes]) x = (1, "two", b"three") res = dec.decode(enc.encode(x)) assert res == x with pytest.raises(msgspec.DecodeError, match="Expected `bytes`"): dec.decode(enc.encode((1, "two", "three"))) with pytest.raises( msgspec.DecodeError, match="Expected `array` of length 3, got 2" ): dec.decode(enc.encode((1, 2))) @pytest.mark.parametrize("size", SIZES) def test_dict_lengths(self, size): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(dict) x = {i: i for i in range(size)} res = dec.decode(enc.encode(x)) assert res == x @pytest.mark.parametrize("typ", [dict, Dict, Dict[Any, Any]]) def test_dict_any_any(self, typ): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(typ) x = {1: "one", "two": 2, b"three": 3.0} res = dec.decode(enc.encode(x)) assert res == x with pytest.raises( msgspec.DecodeError, match=r"Expected `object`, got `int`" ): dec.decode(enc.encode(1)) def test_dict_any_val(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(Dict[str, Any]) x = {"a": 1, "b": "two", "c": b"three"} res = dec.decode(enc.encode(x)) assert res == x with pytest.raises( msgspec.DecodeError, match=r"Expected `str`, got `int` - at `key` in `\$`" ): dec.decode(enc.encode({1: 2})) def test_dict_any_key(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(Dict[Any, str]) x = {1: "a", "two": "b", b"three": "c"} res = dec.decode(enc.encode(x)) assert res == x with pytest.raises( msgspec.DecodeError, match=r"Expected `str`, got `int` - at `\$\[...\]`" ): dec.decode(enc.encode({1: 2})) def test_dict_typed(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(Dict[str, int]) x = {"a": 1, "b": 2} res = dec.decode(enc.encode(x)) assert res == x with pytest.raises( msgspec.DecodeError, match=r"Expected `str`, got `int` - at `key` in `\$`" ): dec.decode(enc.encode({1: 2})) with pytest.raises( msgspec.DecodeError, match=r"Expected `int`, got `str` - at `\$\[...\]`" ): dec.decode(enc.encode({"a": "two"})) def test_enum(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(FruitStr) a = enc.encode(FruitStr.APPLE) assert enc.encode("APPLE") == a assert dec.decode(a) == FruitStr.APPLE with pytest.raises(msgspec.DecodeError, match="truncated"): dec.decode(a[:-2]) with pytest.raises(msgspec.DecodeError, match="Invalid enum value 'MISSING'"): dec.decode(enc.encode("MISSING")) with pytest.raises( msgspec.DecodeError, match=r"Invalid enum value 'MISSING' - at `\$\[0\]`" ): msgspec.msgpack.decode(enc.encode(["MISSING"]), type=List[FruitStr]) with pytest.raises(msgspec.DecodeError): dec.decode(enc.encode(1)) def test_int_enum(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(FruitInt) a = enc.encode(FruitInt.APPLE) assert enc.encode(1) == a assert dec.decode(a) == FruitInt.APPLE with pytest.raises(msgspec.DecodeError, match="truncated"): dec.decode(a[:-2]) with pytest.raises(msgspec.DecodeError, match="Invalid enum value `1000`"): dec.decode(enc.encode(1000)) with pytest.raises( msgspec.DecodeError, match=r"Invalid enum value `1000` - at `\$\[0\]`" ): msgspec.msgpack.decode(enc.encode([1000]), type=List[FruitInt]) with pytest.raises(msgspec.DecodeError): dec.decode(enc.encode("INVALID")) def test_struct(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(Person) x = Person(first="harry", last="potter", age=13) a = enc.encode(x) assert ( enc.encode( {"first": "harry", "last": "potter", "age": 13, "prefect": False} ) == a ) assert dec.decode(a) == x with pytest.raises(msgspec.DecodeError, match="truncated"): dec.decode(a[:-2]) with pytest.raises(msgspec.DecodeError, match="Expected `object`, got `int`"): dec.decode(enc.encode(1)) with pytest.raises( msgspec.DecodeError, match=r"Expected `str`, got `int` - at `key` in `\$`" ): dec.decode(enc.encode({1: "harry"})) def test_struct_field_wrong_type(self): enc = msgspec.msgpack.Encoder() dec = msgspec.msgpack.Decoder(Person) bad = enc.encode({"first": "harry", "last": "potter", "age": "thirteen"}) with pytest.raises( msgspec.DecodeError, match=r"Expected `int`, got `str` - at `\$.age`" ): dec.decode(bad) def test_struct_missing_fields(self): bad = msgspec.msgpack.encode({"first": "harry", "last": "potter"}) with pytest.raises( msgspec.DecodeError, match="Object missing required field `age`" ): msgspec.msgpack.decode(bad, type=Person) bad = msgspec.msgpack.encode({}) with pytest.raises( msgspec.DecodeError, match="Object missing required field `first`" ): msgspec.msgpack.decode(bad, type=Person) bad = msgspec.msgpack.encode([{"first": "harry", "last": "potter"}]) with pytest.raises( msgspec.DecodeError, match=r"Object missing required field `age` - at `\$\[0\]`", ): msgspec.msgpack.decode(bad, type=List[Person]) @pytest.mark.parametrize( "extra", [ None, False, True, 1, 2.0, "three", b"four",
""" CRAR Neural network using Keras """ import numpy as np from keras import backend as K from keras.models import Model from keras.layers import Input, Layer, Dense, Flatten, Activation, Conv2D, MaxPooling2D, UpSampling2D, Reshape, Permute, Add, Subtract, Dot, Multiply, Average, Lambda, Concatenate, BatchNormalization, merge, RepeatVector, AveragePooling2D from keras import regularizers import tensorflow as tf #np.random.seed(111111) from keras.layers import Lambda @tf.custom_gradient def cap_divide(x): def grad(dy): return dy x = tf.math.divide(x, tf.fill(tf.shape(x), 10.0)) return x, grad @tf.custom_gradient def cap(x): def grad(dy): return dy x = tf.abs(x) x = Subtract()([x, tf.ones_like(x)]) x = tf.math.maximum(x, tf.zeros_like(x)) # x = Subtract()([x,tf.ones_like(x)]) # result = tf.abs(x) return x, grad @tf.custom_gradient def binairy_STE_after_sigmoid(x): def grad(dy): return dy result = tf.round(x) #Tensor("model_2/model/dense_4/Round:0", shape=(32, 1), dtype=float32) return result, grad #use with tanh activation @tf.custom_gradient def binairy_STE_after_tanh(x): def grad(dy): return dy result = tf.sign(x) return result, grad #https://stackoverflow.com/questions/58223640/ #https://stackoverflow.com/questions/56657993/ #only difference is, below i take a sample with the given probability distribution (given by sigmoid). which results in noise @tf.custom_gradient def straight_through_estimator(x): def grad(dy): return dy # print(x) rnd = tf.random.uniform(shape=[]) #tf.shape(x)\ cons0 = tf.constant(0, dtype=tf.float32) cons1 = tf.constant(1, dtype=tf.float32) def f1(): return cons0 def f2(): return cons1 result = tf.map_fn(lambda a: tf.cond(tf.less( a, rnd), f1, f2), x) #appears to be (32,) result = Reshape(target_shape=(1,))(result) return result, grad def binairy_sigmoid(x): result = tf.round(K.sigmoid(x)) return result # @tf.custom_gradient # def straight_through_estimator1(x): # def grad(dy): # return dy # # print(x) # # x = Reshape((31,))(x) # print(x) # x = tf.squeeze(x, [1]) # print(x) # rnd = tf.random.uniform(tf.shape(x)) #tf.shape(x)\ # print(rnd) # x = K.sigmoid(x) # print(x) # cons0 = tf.constant(0, dtype=tf.float32) # cons1 = tf.constant(1, dtype=tf.float32) # def f1(): return cons0 # def f2(): return cons1 # # tf.cond(tf.less(x[0], x[1]), f1, f2) # result = tf.map_fn(lambda a: tf.cond(tf.less(a[0], a[1]), f1, f2), (x,rnd), dtype=(tf.float32, tf.float32)) # # result = tf.map_fn(lambda a: tf.cond(tf.less( K.sigmoid(a), rnd), f1, f2), x) #appears to be (32,) # result = Reshape(target_shape=(1,))(result) # return result, grad class NN(): """ Deep Q-learning network using Keras Parameters ----------- batch_size : int Number of tuples taken into account for each iteration of gradient descent input_dimensions : n_actions : random_state : numpy random number generator high_int_dim : Boolean Whether the abstract state should be high dimensional in the form of frames/vectors or whether it should be low-dimensional """ def __init__(self, batch_size, input_dimensions, n_actions, random_state, **kwargs): self._input_dimensions=input_dimensions self._batch_size=batch_size self._random_state=random_state self._n_actions=n_actions self._high_int_dim=kwargs["high_int_dim"] if(self._high_int_dim==True): self.n_channels_internal_dim=kwargs["internal_dim"] #dim[-3] else: self.internal_dim=kwargs["internal_dim"] #2 for laby #3 for catcher def encoder_model(self): """ Instantiate a Keras model for the encoder of the CRAR learning algorithm. The model takes the following as input s : list of objects Each object is a numpy array that relates to one of the observations with size [batch_size * history size * size of punctual observation (which is 2D,1D or scalar)]). Parameters ----------- Returns ------- Keras model with output x (= encoding of s) """ outs_conv=[] inputs=[] for i, dim in enumerate(self._input_dimensions): # - observation[i] is a FRAME if len(dim) == 3 or len(dim) == 4: if(len(dim) == 4): input = Input(shape=(dim[-4],dim[-3],dim[-2],dim[-1])) inputs.append(input) input = Reshape((dim[-4]*dim[-3],dim[-2],dim[-1]), input_shape=(dim[-4],dim[-3],dim[-2],dim[-1]))(input) x=Permute((2,3,1), input_shape=(dim[-4]*dim[-3],dim[-2],dim[-1]))(input) #data_format='channels_last' else: input = Input(shape=(dim[-3],dim[-2],dim[-1])) inputs.append(input) x=Permute((2,3,1), input_shape=(dim[-3],dim[-2],dim[-1]))(input) #data_format='channels_last' if(dim[-2]>12 and dim[-1]>12): self._pooling_encoder=6 x = Conv2D(8, (2, 2), padding='same', activation='tanh')(x) x = Conv2D(16, (2, 2), padding='same', activation='tanh')(x) x = MaxPooling2D(pool_size=(2, 2), strides=None, padding='same')(x) x = Conv2D(32, (3, 3), padding='same', activation='tanh')(x) x = MaxPooling2D(pool_size=(3, 3), strides=None, padding='same')(x) else: self._pooling_encoder=1 if(self._high_int_dim==True): x = Conv2D(self.n_channels_internal_dim, (1, 1), padding='same')(x) #1by1 conv used for dim reduction out = x else: out = Flatten()(x) # - observation[i] is a VECTOR elif len(dim) == 2: if dim[-3] > 3: input = Input(shape=(dim[-3],dim[-2])) inputs.append(input) reshaped=Reshape((dim[-3],dim[-2],1), input_shape=(dim[-3],dim[-2]))(input) #data_format='channels_last' x = Conv2D(16, (2, 1), activation='relu', border_mode='valid')(reshaped) #Conv on the history x = Conv2D(16, (2, 2), activation='relu', border_mode='valid')(x) #Conv on the history & features if(self._high_int_dim==True): out = x else: out = Flatten()(x) else: input = Input(shape=(dim[-3],dim[-2])) inputs.append(input) out = Flatten()(input) # - observation[i] is a SCALAR - else: if dim[-3] > 3: # this returns a tensor input = Input(shape=(dim[-3],)) inputs.append(input) reshaped=Reshape((1,dim[-3],1), input_shape=(dim[-3],))(input) #data_format='channels_last' x = Conv2D(8, (1,2), activation='relu', border_mode='valid')(reshaped) #Conv on the history x = Conv2D(8, (1,2), activation='relu', border_mode='valid')(x) #Conv on the history if(self._high_int_dim==True): out = x else: out = Flatten()(x) else: input = Input(shape=(dim[-3],)) inputs.append(input) out=input outs_conv.append(out) if(self._high_int_dim==True): model = Model(inputs=inputs, outputs=outs_conv) if(self._high_int_dim==False): if len(outs_conv)>1: x = merge(outs_conv, mode='concat') else: x= outs_conv [0] # we stack a deep fully-connected network on top x = Dense(200, activation='tanh')(x) x = Dense(100, activation='tanh')(x) x = Dense(50, activation='tanh')(x) x = Dense(10, activation='tanh')(x) x = Dense(self.internal_dim)(x) # ----- categorical head ---- #TODO test 3 setups with reward model only. 1) numerical neurons, 2) straight through estimater, 3) sigmoid + sampling without identity gradient #binary step function as activation #numerical: # x = Dense(self.internal_dim)(x)#, activity_regularizer=regularizers.l2(0.00001))(x) #, activation='relu' #categorical #internal.dim is amount of output neurons, so used to amount of numerical variables, now its categorical variables # x = Dense(self.internal_dim, activation='sigmoid')(x) # x.numpy() # x = [1 if a > 0.5 else 0 for a in x] # x = tf.map_fn(lambda a: 1 if a > 0.5 else 0, x) #straight through estimator # x = Dense(self.internal_dim, activation=custom_activation)(x) #finally works :D # x = Dense(self.internal_dim, activation='sigmoid')(x) x = Lambda(binairy_STE_after_sigmoid)(x) #tanh STE # x = Dense(self.internal_dim, activation='tanh')(x) # x = Lambda(binairy_STE2)(x) #in the case of more categorical classes/levels than 2, use softmax with different heads per category/variable # classes = 4 # output1 = Dense(classes, activation='softmax')(x) # output2 = Dense(classes, activation='softmax')(x) # model = Model(inputs=input, outputs=[output1, output2]) #first sample from it?! model = Model(inputs=inputs, outputs=x) return model def encoder_cap_model(self,encoder_model): """ Instantiate a Keras model that provides the difference between two encoded pseudo-states The model takes the two following inputs: s1 : list of objects Each object is a numpy array that relates to one of the observations with size [batch_size * history size * size of punctual observation (which is 2D,1D or scalar)]). s2 : list of objects Each object is a numpy array that relates to one of the observations with size [batch_size * history size * size of punctual observation (which is 2D,1D or scalar)]). Parameters ----------- encoder_model: instantiation of a Keras model for the encoder Returns ------- model with output the difference between the encoding of s1 and the encoding of s2 """ inputs=[] for i, dim in enumerate(self._input_dimensions): if(len(dim) == 4): input = Input(shape=(dim[-4],dim[-3],dim[-2],dim[-1])) inputs.append(input) input = Reshape((dim[-4]*dim[-3],dim[-2],dim[-1]), input_shape=(dim[-4],dim[-3],dim[-2],dim[-1]))(input) elif(len(dim) == 3): input = Input(shape=(dim[-3],dim[-2],dim[-1])) inputs.append(input) elif len(dim) == 2: input = Input(shape=(dim[-3],dim[-2])) inputs.append(input) else: input = Input(shape=(dim[-3],)) inputs.append(input) x = encoder_model(inputs[:]) #s --> x x = tf.abs(x) x = Subtract()([x, tf.ones_like(x)]) x = tf.math.maximum(x, tf.zeros_like(x)) x = Lambda(cap)(x) # x = tf.math.divide(x, tf.fill(tf.shape(x), 10.0)) # def f1(): return tf.math.maximum(Subtract()([x,tf.ones_like(x)]) ,tf.zeros_like(x)) # def f2(): reutnr # tf.cond(tf.less(tf.zeros_like(x), x), f1, f2) # result = tf.map_fn(lambda a: tf.cond(tf.less( a, rnd), f1, f2), x) #tf cond #positive -2 #maybe wrap this in ste # cons0 = tf.constant(0, dtype=tf.float32) # cons1 = tf.constant(1, dtype=tf.float32) # def f1(): return cons0 # def f2(): return x # x = tf.cond(tf.less(x, 0), f1, f2) # half = len(inputs)//2 # x1 = encoder_model(inputs[:half]) # x2 = encoder_model(inputs[half:]) # if (self._high_int_dim==True): # x1=Flatten()(x1) # x2=Flatten()(x2) # x = Subtract()([x1,x2]) model = Model(inputs=inputs, outputs=x) return model def encoder_diff_model(self,encoder_model): """ Instantiate a Keras model that provides the difference between two encoded pseudo-states The model takes the two following inputs: s1 : list of objects Each object is a numpy array that relates to one of the observations with size [batch_size * history size * size of punctual observation (which is 2D,1D or scalar)]). s2 : list of objects Each object is a numpy array that relates to one of the observations with size [batch_size * history size * size of punctual observation (which is 2D,1D or scalar)]). Parameters ----------- encoder_model: instantiation of a Keras model for the encoder Returns ------- model with output the difference between the
an emphasis on converting raw user intent into more organized structures rather than producing string output. The top-level :class:`.CompileState` for the statement being executed is also accessible when the execution context works with invoking the statement and collecting results. The production of :class:`.CompileState` is specific to the compiler, such as within the :meth:`.SQLCompiler.visit_insert`, :meth:`.SQLCompiler.visit_select` etc. methods. These methods are also responsible for associating the :class:`.CompileState` with the :class:`.SQLCompiler` itself, if the statement is the "toplevel" statement, i.e. the outermost SQL statement that's actually being executed. There can be other :class:`.CompileState` objects that are not the toplevel, such as when a SELECT subquery or CTE-nested INSERT/UPDATE/DELETE is generated. .. versionadded:: 1.4 """ __slots__ = ("statement",) plugins = {} @classmethod def create_for_statement(cls, statement, compiler, **kw): # factory construction. if statement._propagate_attrs: plugin_name = statement._propagate_attrs.get( "compile_state_plugin", "default" ) klass = cls.plugins.get( (plugin_name, statement._effective_plugin_target), None ) if klass is None: klass = cls.plugins[ ("default", statement._effective_plugin_target) ] else: klass = cls.plugins[ ("default", statement._effective_plugin_target) ] if klass is cls: return cls(statement, compiler, **kw) else: return klass.create_for_statement(statement, compiler, **kw) def __init__(self, statement, compiler, **kw): self.statement = statement @classmethod def get_plugin_class(cls, statement): plugin_name = statement._propagate_attrs.get( "compile_state_plugin", "default" ) try: return cls.plugins[ (plugin_name, statement._effective_plugin_target) ] except KeyError: return None @classmethod def _get_plugin_class_for_plugin(cls, statement, plugin_name): try: return cls.plugins[ (plugin_name, statement._effective_plugin_target) ] except KeyError: return None @classmethod def plugin_for(cls, plugin_name, visit_name): def decorate(cls_to_decorate): cls.plugins[(plugin_name, visit_name)] = cls_to_decorate return cls_to_decorate return decorate class Generative(HasMemoized): """Provide a method-chaining pattern in conjunction with the @_generative decorator.""" def _generate(self): skip = self._memoized_keys cls = self.__class__ s = cls.__new__(cls) if skip: s.__dict__ = { k: v for k, v in self.__dict__.items() if k not in skip } else: s.__dict__ = self.__dict__.copy() return s class InPlaceGenerative(HasMemoized): """Provide a method-chaining pattern in conjunction with the @_generative decorator that mutates in place.""" def _generate(self): skip = self._memoized_keys for k in skip: self.__dict__.pop(k, None) return self class HasCompileState(Generative): """A class that has a :class:`.CompileState` associated with it.""" _compile_state_plugin = None _attributes = util.immutabledict() _compile_state_factory = CompileState.create_for_statement class _MetaOptions(type): """metaclass for the Options class.""" def __init__(cls, classname, bases, dict_): cls._cache_attrs = tuple( sorted( d for d in dict_ if not d.startswith("__") and d not in ("_cache_key_traversal",) ) ) type.__init__(cls, classname, bases, dict_) def __add__(self, other): o1 = self() if set(other).difference(self._cache_attrs): raise TypeError( "dictionary contains attributes not covered by " "Options class %s: %r" % (self, set(other).difference(self._cache_attrs)) ) o1.__dict__.update(other) return o1 class Options(util.with_metaclass(_MetaOptions)): """A cacheable option dictionary with defaults.""" def __init__(self, **kw): self.__dict__.update(kw) def __add__(self, other): o1 = self.__class__.__new__(self.__class__) o1.__dict__.update(self.__dict__) if set(other).difference(self._cache_attrs): raise TypeError( "dictionary contains attributes not covered by " "Options class %s: %r" % (self, set(other).difference(self._cache_attrs)) ) o1.__dict__.update(other) return o1 def __eq__(self, other): # TODO: very inefficient. This is used only in test suites # right now. for a, b in util.zip_longest(self._cache_attrs, other._cache_attrs): if getattr(self, a) != getattr(other, b): return False return True def __repr__(self): # TODO: fairly inefficient, used only in debugging right now. return "%s(%s)" % ( self.__class__.__name__, ", ".join( "%s=%r" % (k, self.__dict__[k]) for k in self._cache_attrs if k in self.__dict__ ), ) @classmethod def isinstance(cls, klass): return issubclass(cls, klass) @hybridmethod def add_to_element(self, name, value): return self + {name: getattr(self, name) + value} @hybridmethod def _state_dict(self): return self.__dict__ _state_dict_const = util.immutabledict() @_state_dict.classlevel def _state_dict(cls): return cls._state_dict_const @classmethod def safe_merge(cls, other): d = other._state_dict() # only support a merge with another object of our class # and which does not have attrs that we don't. otherwise # we risk having state that might not be part of our cache # key strategy if ( cls is not other.__class__ and other._cache_attrs and set(other._cache_attrs).difference(cls._cache_attrs) ): raise TypeError( "other element %r is not empty, is not of type %s, " "and contains attributes not covered here %r" % ( other, cls, set(other._cache_attrs).difference(cls._cache_attrs), ) ) return cls + d @classmethod def from_execution_options( cls, key, attrs, exec_options, statement_exec_options ): """process Options argument in terms of execution options. e.g.:: ( load_options, execution_options, ) = QueryContext.default_load_options.from_execution_options( "_sa_orm_load_options", { "populate_existing", "autoflush", "yield_per" }, execution_options, statement._execution_options, ) get back the Options and refresh "_sa_orm_load_options" in the exec options dict w/ the Options as well """ # common case is that no options we are looking for are # in either dictionary, so cancel for that first check_argnames = attrs.intersection( set(exec_options).union(statement_exec_options) ) existing_options = exec_options.get(key, cls) if check_argnames: result = {} for argname in check_argnames: local = "_" + argname if argname in exec_options: result[local] = exec_options[argname] elif argname in statement_exec_options: result[local] = statement_exec_options[argname] new_options = existing_options + result exec_options = util.immutabledict().merge_with( exec_options, {key: new_options} ) return new_options, exec_options else: return existing_options, exec_options class CacheableOptions(Options, HasCacheKey): @hybridmethod def _gen_cache_key(self, anon_map, bindparams): return HasCacheKey._gen_cache_key(self, anon_map, bindparams) @_gen_cache_key.classlevel def _gen_cache_key(cls, anon_map, bindparams): return (cls, ()) @hybridmethod def _generate_cache_key(self): return HasCacheKey._generate_cache_key_for_object(self) class ExecutableOption(HasCopyInternals, HasCacheKey): _annotations = util.EMPTY_DICT __visit_name__ = "executable_option" def _clone(self, **kw): """Create a shallow copy of this ExecutableOption.""" c = self.__class__.__new__(self.__class__) c.__dict__ = dict(self.__dict__) return c class Executable(roles.StatementRole, Generative): """Mark a :class:`_expression.ClauseElement` as supporting execution. :class:`.Executable` is a superclass for all "statement" types of objects, including :func:`select`, :func:`delete`, :func:`update`, :func:`insert`, :func:`text`. """ supports_execution = True _execution_options = util.immutabledict() _bind = None _with_options = () _with_context_options = () _executable_traverse_internals = [ ("_with_options", InternalTraversal.dp_executable_options), ("_with_context_options", ExtendedInternalTraversal.dp_plain_obj), ("_propagate_attrs", ExtendedInternalTraversal.dp_propagate_attrs), ] is_select = False is_update = False is_insert = False is_text = False is_delete = False is_dml = False @property def _effective_plugin_target(self): return self.__visit_name__ @_generative def options(self, *options): """Apply options to this statement. In the general sense, options are any kind of Python object that can be interpreted by the SQL compiler for the statement. These options can be consumed by specific dialects or specific kinds of compilers. The most commonly known kind of option are the ORM level options that apply "eager load" and other loading behaviors to an ORM query. However, options can theoretically be used for many other purposes. For background on specific kinds of options for specific kinds of statements, refer to the documentation for those option objects. .. versionchanged:: 1.4 - added :meth:`.Generative.options` to Core statement objects towards the goal of allowing unified Core / ORM querying capabilities. .. seealso:: :ref:`deferred_options` - refers to options specific to the usage of ORM queries :ref:`relationship_loader_options` - refers to options specific to the usage of ORM queries """ self._with_options += tuple( coercions.expect(roles.HasCacheKeyRole, opt) for opt in options ) @_generative def _set_compile_options(self, compile_options): """Assign the compile options to a new value. :param compile_options: appropriate CacheableOptions structure """ self._compile_options = compile_options @_generative def _update_compile_options(self, options): """update the _compile_options with new keys.""" self._compile_options += options @_generative def _add_context_option(self, callable_, cache_args): """Add a context option to this statement. These are callable functions that will be given the CompileState object upon compilation. A second argument cache_args is required, which will be combined with the identity of the function itself in order to produce a cache key. """ self._with_context_options += ((callable_, cache_args),) @_generative def execution_options(self, **kw): """Set non-SQL options for the statement which take effect during execution. Execution options can be set on a per-statement or per :class:`_engine.Connection` basis. Additionally, the :class:`_engine.Engine` and ORM :class:`~.orm.query.Query` objects provide access to execution options which they in turn configure upon connections. The :meth:`execution_options` method is generative. A new instance of this statement is returned that contains the options:: statement = select(table.c.x, table.c.y) statement = statement.execution_options(autocommit=True) Note that only a subset of possible execution options can be applied to a statement - these include "autocommit" and "stream_results", but not "isolation_level" or "compiled_cache". See :meth:`_engine.Connection.execution_options` for a full list of possible options. .. seealso:: :meth:`_engine.Connection.execution_options` :meth:`_query.Query.execution_options` :meth:`.Executable.get_execution_options` """ if "isolation_level" in kw: raise exc.ArgumentError( "'isolation_level' execution option may only be specified " "on Connection.execution_options(), or " "per-engine using the isolation_level " "argument to create_engine()." ) if "compiled_cache" in kw: raise exc.ArgumentError( "'compiled_cache' execution option may only be specified " "on Connection.execution_options(), not per statement." ) self._execution_options = self._execution_options.union(kw) def get_execution_options(self): """Get the non-SQL options which will take effect during execution. ..
table') if category_names != '' and category_names != None: try: ds.GetRasterBand(1).SetRasterCategoryNames(category_names) except: print ('Could not write category names') print(('Writing: ' + output_name.split('/')[-1])) print(('Datatype of ' + output_name.split('/')[-1] + ' is: ' + dt)) for band in range(bands): print(('Stacking band:', image_list[band])) if array_list == False: array = raster(image_list[band], dt = numpy_dt) elif array_list == True: array = image_list[band] if out_no_data != '' and out_no_data != None: ds.GetRasterBand(band + 1).SetNoDataValue(out_no_data) ds.GetRasterBand(band + 1).WriteArray(array) if report and array_list == False: stack_report(image_list, output_name) return output_name ds = None array = None rast = None ##Dir = 'C:/Users/ihousman/Downloads/20e71921f819ee7ac81687c4c43ba3a8/' ##tifs = glob(Dir, '.tif') ##out = Dir + 'test_stack.img' ##stack(tifs,out,tifs[0]) ##brick_info(out, True) ###################################################################################### #Stack function to handle large rasters def stack_robust(image_list,output_name): ri = raster_info(image_list[0]) ti = tiled_image(output_name,image_list[0], width = '', height = '', bands = len(image_list), size_limit_kb = 10000,outline_tiles = True) tn = 1 for xo,yo,w,h in ti.chunk_list: print(('Stacking tile number',tn,'/',len(ti.chunk_list))) b = brick(image_list, dt = '', xoffset = xo, yoffset = yo, width = w, height = h, image_list = True) ti.add_tile(b,xo,yo) tn+= 1 ti.rm() ## brick_info(output_name,True) stack_report(image_list, output_name) ###################################################################################### #Restacks a specified list of bands from a stack into the specified order in the list def restack(stack = '', output_name = '', template = '', band_list = [], df = 'HFA', dt = '', width = '', height = '', projection = '', transform = '', out_no_data = '',guiable = True): if stack == '': stack = str(askopenfilename(title = 'Select Stack to Rearrange',filetypes=[("IMAGINE","*.img"),("tif","*.tif")])) if output_name == '': output_name = str(asksaveasfilename(title = 'Select output image name',initialdir = cwd,filetypes=[("IMAGINE","*.img"),("tif","*.tif")])) if band_list == []: temp = askstring('Bands to rearrange', 'Please enter band number in order to rearrange separated by commas (ex. 6,4,3)') temp = temp.split(',') sample_no_temp = [] for sample in temp: index = 0 sample_temp = '' for char in sample: if char != ' ': sample_temp += char sample_no_temp.append(int(sample_temp)) band_list = sample_no_temp info = raster_info(stack) if dt == '': dt = info['dt'] if numpy_or_gdal(dt) == 'numpy': dt = dt_converter(dt) numpy_dt = dt_converter(dt) gdal_dt = 'gdal.GDT_' + dt print (gdal_dt) if template != '': rast = gdal.Open(template) width = rast.RasterXSize height = rast.RasterYSize projection = rast.GetProjection() else: width = info['width'] height = info['height'] projection = info['projection'] bands = len(band_list) if transform == '': transform = info['transform'] driver = gdal.GetDriverByName(df) ds = driver.Create(output_name, width, height, bands, eval(gdal_dt)) ds.SetProjection(projection) ds.SetGeoTransform(transform) print(('Writing: ' + output_name.split('/')[-1])) print(( 'Datatype of ' + output_name.split('/')[-1] + ' is: ' + dt)) for band in range(bands): print(('Stacking band:', band_list[band])) array = raster(stack, band_no = band_list[band], dt = numpy_dt) if out_no_data != '': ds.GetRasterBand(band + 1).SetNoDataValue(out_no_data) ds.GetRasterBand(band + 1).WriteArray(array) if template != '' and template != None: color_table, category_names, b1, rast = color_table_and_names(template, band = 1) else: color_table,category_names = None,None if color_table != '' and color_table != None: try: ds.GetRasterBand(1).SetRasterColorTable(color_table) except: print ('Could not write color table') if category_names != '' and category_names != None: try: ds.GetRasterBand(1).SetRasterCategoryNames(category_names) except: print ('Could not write category names') ds = None array = None rast = None return output_name ###################################################################################### def shift_raster(in_raster, shift_x, shift_y): rast = gdal.Open(in_raster, gdal.GA_Update) info = raster_info(in_raster) coords = info['coords'] transform = info['transform'] transform = [transform[0] + shift_x, transform[1], transform[2], transform[3] + shift_y, transform[4], transform[5]] rast.SetGeoTransform(transform) rast = None #image = 'A:/IansPlayground/vj_play/fid_49/zone40_Path29Row26_tcc_masked_RF_9030_CorrBias_TCC_Grouped_NoDups_surface_reflectance_albers_float_30m_shift_30.img' #shift_raster(image,30,0) ###################################################################################### #Returns an array of zeros with the exact dimensions and datatype of the given template raster #Datatype can be manually defined #u1,u2,u4, i1,i2,i4, float32, float64 def empty_raster(Template_Raster, dt = ''): if dt == '': info = raster_info(Template_Raster) dt = info['dt'] if numpy_or_gdal(dt) == 'gdal': dt = dt_converter(dt) print('Creating empty raster from: ' + Template_Raster.split('/')[-1]) rast = gdal.Open(Template_Raster) width = rast.RasterXSize height = rast.RasterYSize band1 = numpy.zeros([height, width]).astype(dt) print('Datatype of empty raster is: ' + str(type(band1))) rast = None return band1 band1 = None ###################################################################################### def logit_apply(wd, predictors, coefficients, out_file): i = 0 for predictor in predictors: r(predictor + '= ' + coefficients[i + 1] + '* raster("'+ wd + predictor + '")') i += 1 ## pred = gdal.Open(wd + predictor) ## pred_pixels = pred.ReadAsArray() ## print predictor, pred_pixels ## pred = None ## pred_pixels = None ###################################################################################### #Finds the intersection coordinates of a list of images #All images must be the same projection def intersection_coords(image_list): extent_list = [] for pred in image_list: #print 'Processing: ' + pred if os.path.splitext(pred)[1] == '.shp': coords = shape_info(pred)['coords'] else: coords = raster_info(pred)['coords'] extent_list.append(coords) extent_list = numpy.array(extent_list) mins = numpy.amin(extent_list, axis = 0) maxes = numpy.amax(extent_list, axis = 0) intersection = [maxes[0],maxes[1],mins[2],mins[3]] print('The intersection coords of are', intersection) return intersection ###################################################################################### def new_clip(image, output, clip_to_file, out_no_data = '', band_list = [], Buffer = 0, ct = '',names = '',dt = ''): if os.path.exists(output) == False: if type(clip_to_file) == list: try: clip_coords = intersection_coords(clip_to_file) except: clip_coords = clip_to_file print('Already have the clip coords') print('They are', clip_coords) elif os.path.splitext(clip_to_file)[1] == '.shp': clip_info = shape_info(clip_to_file) clip_coords = clip_info['coords'] else: clip_info = raster_info(clip_to_file) clip_coords = clip_info['coords'] if Buffer != None and Buffer != '' and Buffer != 0: clip_coords = [clip_coords[0] - Buffer, clip_coords[1] -Buffer, clip_coords[2] + Buffer, clip_coords[3] + Buffer] if type(image) == list: r_info = raster_info(image[0]) ctt, namest, b1, rast = color_table_and_names(image[0], band = 1) else: r_info = raster_info(image) ctt, namest, b1, rast = color_table_and_names(image, band = 1) orig_coords = r_info['coords'] res = r_info['res'] orig_width = r_info['width'] orig_height = r_info['height'] xo = int(math.floor((clip_coords[0] - orig_coords[0])/res)) yo = int(math.floor((orig_coords[-1] - clip_coords[-1])/res)) if xo < 0: xo = 0 if yo < 0: yo = 0 if xo == 0: w = int(math.floor((clip_coords[2] - clip_coords[0])/res)) else: w = int(math.floor((clip_coords[2] - clip_coords[0])/res)) if yo == 0: h = int(math.floor((orig_coords[-1] - clip_coords[1])/res)) else: h = int(math.floor((clip_coords[-1] - clip_coords[1])/res)) if h + yo > orig_height: h = orig_height-yo if w + xo > orig_width: w = orig_width - xo if out_no_data == '': out_no_data = r_info['no_data'] print('clip to coords', clip_coords) print('Out no data value:', out_no_data) print('Res:', res) print('xo,yo,w,h:',xo,yo,w,h) print('Orig width and height:',orig_width, orig_height) print('Output name:', output) out_transform = [orig_coords[0] + (xo * res), r_info['res'], 0.0, orig_coords[-1] - (yo * res), 0.0, -1 * r_info['res']] if ct == '' or ct == None: ct = ctt print('The color table is', ct) if dt == '' or dt == None: dt = r_info['dt'] if names == '' or names == None: names = namest print('The datatype is', dt) if band_list == []: band_list = list(range(1,r_info['bands'] + 1)) ti = tiled_image(output, bands = len(band_list),dt =dt, width = w, height = h, projection = r_info['projection'], transform = out_transform, out_no_data = out_no_data,ct = ct, names = names) if type(image) == list: #b = brick(image,dt,xo,yo,w,h,image_list = True ) for img in image: r = raster(img,dt,b,xo,yo,w,h) ti.add_tile(r,0,0,b) r = None else: for b in band_list: r = raster(image,dt,b,xo,yo,w,h) ti.add_tile(r,0,0,b) r = None #b = brick(image, dt, xo,yo, w, h, band_list = band_list) ti.rm() #stack(b, output, dt =dt, width = w, height = h, projection = r_info['projection'], transform = out_transform, array_list = True, color_table = ct, category_names = names, out_no_data = out_no_data) #b = None ## else: ## print 'Output:', output, 'already exists' ##in_raster = '//172.16.31.10/Working/RTFD_TDD/MZ_13_fix_mask/mz13_fix_t.tif' ##clip_extent ='//172.16.31.10/Working/RTFD_TDD/TDD_Processing/2014/121/linear_fit_outputs_121_post_processing/2014_121_8_14_tdd_persistence_3class.img' ## ##out_raster = '//172.16.31.10/Working/RTFD_TDD/MZ_13_fix_mask/mz13_fix_t_clip.tif' ##out_raster_recode = '//172.16.31.10/Working/RTFD_TDD/MZ_13_fix_mask/mz13_fix_t_clip_recode.tif' ##r = raster(out_raster) ##r[r == 255] = 254 ##r[r == 0] = 255 ##r[r == 1] = 0 ## ##write_raster(r,out_raster_recode,out_raster, dt = 'Byte') ##r = None ##new_clip(in_raster,out_raster,clip_extent) ###################################################################################### def batch_new_clip(images, out_dir, study_area= '',out_extension = '_clip.img', no_data = '',band_list = [],dt = ''): #if study_area == '' or study_area == None: #study_area = images if study_area == '' or study_area == None: study_area = intersection_coords(images) #print 'Study area:', study_area out_list = [] for image in images: if os.path.splitext(image)[1] != '.shp': out_image = out_dir + base(image) + out_extension out_list.append(out_image) if os.path.exists(out_image) == False: print('Clipping', base(image)) new_clip(image,out_image,study_area, no_data, band_list = band_list) print('Computing stats for', out_image) #brick_info(out_image, True) return out_list ###################################################################################### def clip_set_proj(in_image, out_image, wkt,clip_no = 50, out_no_data = 255): if os.path.exists(out_image) == False: try: od = os.path.dirname(out_image) check_dir(od) rit = raster_info(in_image) width,height = rit['width'], rit['height'] oh= height - clip_no b = brick(in_image, '', 0,0, width, oh) #ct, names, b1, rast = color_table_and_names(pi) stack(b, out_image, dt = rit['dt'], width = width, height =oh, projection = wkt, transform = rit['transform'], array_list = True,out_no_data = out_no_data)#, color_table = ct) except: print('Could not clip and set
value = 'CKM2x2*Ru2x2', texname = '\\text{I63x22}') I63x33 = Parameter(name = 'I63x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3', texname = '\\text{I63x33}') I63x36 = Parameter(name = 'I63x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3', texname = '\\text{I63x36}') I64x33 = Parameter(name = 'I64x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*complexconjugate(yd3x3)', texname = '\\text{I64x33}') I64x36 = Parameter(name = 'I64x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*complexconjugate(yd3x3)', texname = '\\text{I64x36}') I65x33 = Parameter(name = 'I65x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x6*yu3x3', texname = '\\text{I65x33}') I65x36 = Parameter(name = 'I65x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x6*yu3x3', texname = '\\text{I65x36}') I66x11 = Parameter(name = 'I66x11', nature = 'internal', type = 'complex', value = 'CKM1x1*Ru1x1*complexconjugate(Rd1x1)', texname = '\\text{I66x11}') I66x22 = Parameter(name = 'I66x22', nature = 'internal', type = 'complex', value = 'CKM2x2*Ru2x2*complexconjugate(Rd2x2)', texname = '\\text{I66x22}') I66x33 = Parameter(name = 'I66x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*complexconjugate(Rd3x3)', texname = '\\text{I66x33}') I66x36 = Parameter(name = 'I66x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*complexconjugate(Rd3x3)', texname = '\\text{I66x36}') I66x63 = Parameter(name = 'I66x63', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*complexconjugate(Rd6x3)', texname = '\\text{I66x63}') I66x66 = Parameter(name = 'I66x66', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*complexconjugate(Rd6x3)', texname = '\\text{I66x66}') I67x33 = Parameter(name = 'I67x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*complexconjugate(Rd3x6)*complexconjugate(yd3x3)', texname = '\\text{I67x33}') I67x36 = Parameter(name = 'I67x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*complexconjugate(Rd3x6)*complexconjugate(yd3x3)', texname = '\\text{I67x36}') I67x63 = Parameter(name = 'I67x63', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*complexconjugate(Rd6x6)*complexconjugate(yd3x3)', texname = '\\text{I67x63}') I67x66 = Parameter(name = 'I67x66', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*complexconjugate(Rd6x6)*complexconjugate(yd3x3)', texname = '\\text{I67x66}') I68x33 = Parameter(name = 'I68x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*complexconjugate(Rd3x6)*complexconjugate(td3x3)', texname = '\\text{I68x33}') I68x36 = Parameter(name = 'I68x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*complexconjugate(Rd3x6)*complexconjugate(td3x3)', texname = '\\text{I68x36}') I68x63 = Parameter(name = 'I68x63', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*complexconjugate(Rd6x6)*complexconjugate(td3x3)', texname = '\\text{I68x63}') I68x66 = Parameter(name = 'I68x66', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*complexconjugate(Rd6x6)*complexconjugate(td3x3)', texname = '\\text{I68x66}') I69x33 = Parameter(name = 'I69x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x6*tu3x3*complexconjugate(Rd3x3)', texname = '\\text{I69x33}') I69x36 = Parameter(name = 'I69x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x6*tu3x3*complexconjugate(Rd3x3)', texname = '\\text{I69x36}') I69x63 = Parameter(name = 'I69x63', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x6*tu3x3*complexconjugate(Rd6x3)', texname = '\\text{I69x63}') I69x66 = Parameter(name = 'I69x66', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x6*tu3x3*complexconjugate(Rd6x3)', texname = '\\text{I69x66}') I7x11 = Parameter(name = 'I7x11', nature = 'internal', type = 'complex', value = 'Rd1x1*complexconjugate(CKM1x1)', texname = '\\text{I7x11}') I7x22 = Parameter(name = 'I7x22', nature = 'internal', type = 'complex', value = 'Rd2x2*complexconjugate(CKM2x2)', texname = '\\text{I7x22}') I7x33 = Parameter(name = 'I7x33', nature = 'internal', type = 'complex', value = 'Rd3x3*complexconjugate(CKM3x3)', texname = '\\text{I7x33}') I7x36 = Parameter(name = 'I7x36', nature = 'internal', type = 'complex', value = 'Rd6x3*complexconjugate(CKM3x3)', texname = '\\text{I7x36}') I70x33 = Parameter(name = 'I70x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*yd3x3*complexconjugate(Rd3x3)*complexconjugate(yd3x3)', texname = '\\text{I70x33}') I70x36 = Parameter(name = 'I70x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*yd3x3*complexconjugate(Rd3x3)*complexconjugate(yd3x3)', texname = '\\text{I70x36}') I70x63 = Parameter(name = 'I70x63', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*yd3x3*complexconjugate(Rd6x3)*complexconjugate(yd3x3)', texname = '\\text{I70x63}') I70x66 = Parameter(name = 'I70x66', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*yd3x3*complexconjugate(Rd6x3)*complexconjugate(yd3x3)', texname = '\\text{I70x66}') I71x33 = Parameter(name = 'I71x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*yu3x3*complexconjugate(Rd3x3)*complexconjugate(yu3x3)', texname = '\\text{I71x33}') I71x36 = Parameter(name = 'I71x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*yu3x3*complexconjugate(Rd3x3)*complexconjugate(yu3x3)', texname = '\\text{I71x36}') I71x63 = Parameter(name = 'I71x63', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x3*yu3x3*complexconjugate(Rd6x3)*complexconjugate(yu3x3)', texname = '\\text{I71x63}') I71x66 = Parameter(name = 'I71x66', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x3*yu3x3*complexconjugate(Rd6x3)*complexconjugate(yu3x3)', texname = '\\text{I71x66}') I72x33 = Parameter(name = 'I72x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x6*yu3x3*complexconjugate(Rd3x3)', texname = '\\text{I72x33}') I72x36 = Parameter(name = 'I72x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x6*yu3x3*complexconjugate(Rd3x3)', texname = '\\text{I72x36}') I72x63 = Parameter(name = 'I72x63', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x6*yu3x3*complexconjugate(Rd6x3)', texname = '\\text{I72x63}') I72x66 = Parameter(name = 'I72x66', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x6*yu3x3*complexconjugate(Rd6x3)', texname = '\\text{I72x66}') I73x33 = Parameter(name = 'I73x33', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x6*yu3x3*complexconjugate(Rd3x6)*complexconjugate(yd3x3)', texname = '\\text{I73x33}') I73x36 = Parameter(name = 'I73x36', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x6*yu3x3*complexconjugate(Rd3x6)*complexconjugate(yd3x3)', texname = '\\text{I73x36}') I73x63 = Parameter(name = 'I73x63', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru3x6*yu3x3*complexconjugate(Rd6x6)*complexconjugate(yd3x3)', texname = '\\text{I73x63}') I73x66 = Parameter(name = 'I73x66', nature = 'internal', type = 'complex', value = 'CKM3x3*Ru6x6*yu3x3*complexconjugate(Rd6x6)*complexconjugate(yd3x3)', texname = '\\text{I73x66}') I74x11 = Parameter(name = 'I74x11', nature = 'internal', type = 'complex', value = 'Ru1x1*complexconjugate(Ru1x1)', texname = '\\text{I74x11}') I74x22 = Parameter(name = 'I74x22', nature = 'internal', type = 'complex', value = 'Ru2x2*complexconjugate(Ru2x2)', texname = '\\text{I74x22}') I74x33 = Parameter(name = 'I74x33', nature = 'internal', type = 'complex', value = 'Ru3x3*complexconjugate(Ru3x3)', texname = '\\text{I74x33}') I74x36 = Parameter(name = 'I74x36', nature = 'internal', type = 'complex', value = 'Ru6x3*complexconjugate(Ru3x3)', texname = '\\text{I74x36}') I74x63 = Parameter(name = 'I74x63', nature = 'internal', type = 'complex', value = 'Ru3x3*complexconjugate(Ru6x3)', texname = '\\text{I74x63}') I74x66 = Parameter(name = 'I74x66', nature = 'internal', type = 'complex', value = 'Ru6x3*complexconjugate(Ru6x3)', texname = '\\text{I74x66}') I75x33 = Parameter(name = 'I75x33', nature = 'internal', type = 'complex', value = 'Ru3x6*complexconjugate(Ru3x6)', texname = '\\text{I75x33}') I75x36 = Parameter(name = 'I75x36', nature = 'internal', type = 'complex', value = 'Ru6x6*complexconjugate(Ru3x6)', texname = '\\text{I75x36}') I75x44 = Parameter(name = 'I75x44', nature = 'internal', type = 'complex', value = 'Ru4x4*complexconjugate(Ru4x4)', texname = '\\text{I75x44}') I75x55 = Parameter(name = 'I75x55', nature = 'internal', type = 'complex', value = 'Ru5x5*complexconjugate(Ru5x5)', texname = '\\text{I75x55}') I75x63 = Parameter(name = 'I75x63', nature = 'internal', type = 'complex', value = 'Ru3x6*complexconjugate(Ru6x6)', texname = '\\text{I75x63}') I75x66 = Parameter(name = 'I75x66', nature = 'internal', type = 'complex', value = 'Ru6x6*complexconjugate(Ru6x6)', texname = '\\text{I75x66}') I76x33 = Parameter(name = 'I76x33', nature = 'internal', type = 'complex', value = 'Ru3x3*complexconjugate(Ru3x6)*complexconjugate(yu3x3)', texname = '\\text{I76x33}') I76x36 = Parameter(name = 'I76x36', nature = 'internal', type = 'complex', value = 'Ru6x3*complexconjugate(Ru3x6)*complexconjugate(yu3x3)', texname = '\\text{I76x36}') I76x63 = Parameter(name = 'I76x63', nature = 'internal', type = 'complex', value = 'Ru3x3*complexconjugate(Ru6x6)*complexconjugate(yu3x3)', texname = '\\text{I76x63}') I76x66 = Parameter(name = 'I76x66', nature = 'internal', type = 'complex', value = 'Ru6x3*complexconjugate(Ru6x6)*complexconjugate(yu3x3)', texname = '\\text{I76x66}') I77x33 = Parameter(name = 'I77x33', nature = 'internal', type = 'complex', value = 'Ru3x3*complexconjugate(Ru3x6)*complexconjugate(tu3x3)', texname = '\\text{I77x33}') I77x36 = Parameter(name = 'I77x36', nature = 'internal', type = 'complex', value = 'Ru6x3*complexconjugate(Ru3x6)*complexconjugate(tu3x3)', texname = '\\text{I77x36}') I77x63 = Parameter(name = 'I77x63', nature = 'internal', type = 'complex', value = 'Ru3x3*complexconjugate(Ru6x6)*complexconjugate(tu3x3)', texname = '\\text{I77x63}') I77x66 = Parameter(name = 'I77x66', nature = 'internal', type = 'complex', value = 'Ru6x3*complexconjugate(Ru6x6)*complexconjugate(tu3x3)', texname = '\\text{I77x66}') I78x33 = Parameter(name = 'I78x33', nature = 'internal', type = 'complex', value = 'Ru3x6*tu3x3*complexconjugate(Ru3x3)', texname = '\\text{I78x33}') I78x36 = Parameter(name = 'I78x36', nature = 'internal', type = 'complex', value = 'Ru6x6*tu3x3*complexconjugate(Ru3x3)', texname = '\\text{I78x36}') I78x63 = Parameter(name = 'I78x63', nature = 'internal', type = 'complex', value = 'Ru3x6*tu3x3*complexconjugate(Ru6x3)', texname = '\\text{I78x63}') I78x66 = Parameter(name = 'I78x66', nature = 'internal', type = 'complex', value = 'Ru6x6*tu3x3*complexconjugate(Ru6x3)', texname = '\\text{I78x66}') I79x33 = Parameter(name = 'I79x33', nature = 'internal', type = 'complex', value = 'Ru3x6*yu3x3*complexconjugate(Ru3x3)', texname = '\\text{I79x33}') I79x36 = Parameter(name = 'I79x36', nature = 'internal', type = 'complex', value = 'Ru6x6*yu3x3*complexconjugate(Ru3x3)', texname = '\\text{I79x36}') I79x63 = Parameter(name = 'I79x63', nature = 'internal', type = 'complex', value = 'Ru3x6*yu3x3*complexconjugate(Ru6x3)', texname = '\\text{I79x63}') I79x66 = Parameter(name = 'I79x66', nature = 'internal', type = 'complex', value = 'Ru6x6*yu3x3*complexconjugate(Ru6x3)', texname = '\\text{I79x66}') I8x33 = Parameter(name = 'I8x33', nature = 'internal', type = 'complex', value = 'Rd3x3*complexconjugate(CKM3x3)*complexconjugate(yu3x3)', texname = '\\text{I8x33}') I8x36 = Parameter(name = 'I8x36', nature = 'internal', type = 'complex', value = 'Rd6x3*complexconjugate(CKM3x3)*complexconjugate(yu3x3)', texname = '\\text{I8x36}') I80x33 = Parameter(name = 'I80x33', nature = 'internal', type = 'complex', value = 'Ru3x3*yu3x3*complexconjugate(Ru3x3)*complexconjugate(yu3x3)', texname = '\\text{I80x33}') I80x36 = Parameter(name = 'I80x36', nature = 'internal', type = 'complex', value = 'Ru6x3*yu3x3*complexconjugate(Ru3x3)*complexconjugate(yu3x3)', texname = '\\text{I80x36}') I80x63 = Parameter(name = 'I80x63', nature = 'internal', type = 'complex', value = 'Ru3x3*yu3x3*complexconjugate(Ru6x3)*complexconjugate(yu3x3)', texname = '\\text{I80x63}') I80x66 = Parameter(name = 'I80x66', nature = 'internal', type = 'complex', value = 'Ru6x3*yu3x3*complexconjugate(Ru6x3)*complexconjugate(yu3x3)', texname = '\\text{I80x66}') I81x33 = Parameter(name = 'I81x33', nature = 'internal', type = 'complex', value = 'Ru3x6*yu3x3*complexconjugate(Ru3x6)*complexconjugate(yu3x3)', texname = '\\text{I81x33}') I81x36 = Parameter(name = 'I81x36', nature = 'internal', type = 'complex',
<filename>eddy/fit_cube.py """ Class to load up a velocity map and fit a Keplerian profile to it. The main functions of interest are: disk_coords: Given geometrical properties of the disk and the emission surface, will deproject the data into a face-on view in either polar or cartesian coordaintes. keplerian: Builds a Keplerian rotation pattern with the provided geometrical properties and emission surface. Does not account for any deviations due to pressure gradients or self gravity. fit_keplerian: Fits a Keplerian profile to the data. It is possible to hold various parameters constant or let them vary. Also allows for a flared emission surface which can be constrained with good quality data. TODO: 1) Include bounds for the initial optimization. 2) More robust plotting for the residual maps. A separate function maybe? 3) Can we do the deprojection analytically rather than iteratively? """ import numpy as np from astropy.io import fits import scipy.constants as sc import warnings warnings.filterwarnings("ignore") class rotationmap: msun = 1.988e30 fwhm = 2. * np.sqrt(2 * np.log(2)) def __init__(self, path, uncertainty=None, clip=None, downsample=None): """Initialize the class.""" # Read in the data and position axes. self.data = np.squeeze(fits.getdata(path)) self.header = fits.getheader(path) if uncertainty is not None: self.error = np.squeeze(fits.getdata(uncertainty)) else: print("No uncertainties found, assuming uncertainties of 10%.") self.error = 0.1 * self.data self.error = np.where(np.isnan(self.error), 0.0, self.error) # Make sure this is in [km/s]. if np.nanmedian(self.data) > 10.0: self.data /= 1e3 self.error /= 1e3 self.xaxis = self._read_position_axis(a=1) self.yaxis = self._read_position_axis(a=2) self.dpix = abs(np.diff(self.xaxis)).mean() # Clip and downsample the cube to speed things up. if clip is not None: self._clip_cube(clip) if downsample is not None: self._downsample_cube(downsample) self.dpix = abs(np.diff(self.xaxis)).mean() self.mask = np.isfinite(self.data) # Estimate the systemic velocity. self.vlsr = np.nanmedian(self.data) # Beam parameters. TODO: Make sure CASA beam tables work. try: self.bmaj = self.header['bmaj'] * 3600. self.bmin = self.header['bmin'] * 3600. self.bpa = self.header['bpa'] except KeyError: self.bmaj = None self.bmin = None self.bpa = None # -- Fitting functions. -- # def fit_keplerian(self, p0, params, r_min=None, r_max=None, optimize=True, nwalkers=None, nburnin=300, nsteps=100, scatter=1e-3, plot_walkers=True, plot_corner=True, plot_bestfit=True, plot_residual=True, return_samples=False): """ Fit a Keplerian rotation profile to the data. Args: p0 (list): List of the free parameters to fit. params (dictionary): Dictionary of the parameters used for the Keplerian model. If the value is fixed, specify the values: params['x0'] = 0.45 while if it is a free parameter, provide the index in p0: params['x0'] = 0 making sure the value is an integer. The values needed are: 'x0', 'y0', 'inc', 'PA', 'mstar', 'vlsr', 'dist'. If a flared emission surface is wanted then you can add 'z0', 'psi' and 'tilt' with their descriptions found in disk_coords(). To include a convolution with the beam stored in the header use params['beam'] = True, where this must be a boolean, not an integer. r_min (Optional[float]): Inner radius to fit in (arcsec). r_max (Optional[float]): Outer radius to fit in (arcsec). Note that for the masking the default p0 and params values are used for the deprojection, or those found from the optimization. optimize (Optional[bool]): Use scipy.optimize to find the p0 values which maximize the likelihood. Better results will likely be found. nwalkers (Optional[int]): Number of walkers to use for the MCMC. scatter (Optional[float]): Scatter used in distributing walker starting positions around the initial p0 values. plot_walkers (Optional[bool]): Plot the samples taken by the walkers. plot_corner (Optional[bool]): Plot the covariances of the posteriors. plot_bestfit (Optional[bool]): Plot the best fit model. plot_residual (Optional[bool]): Plot the residual from the data and the best fit model. return_samples (Optional[bool]): If true, return all the samples of the posterior distribution after the burn in period, otherwise just return the 16th, 50th and 84th percentiles of each posterior distribution. Returns: samples (ndarray): If return_sample = True, return all the samples of the posterior distribution after the burn in period, otherwise just return the 16th, 50th and 84th percentiles of each posterior distribution. """ # Load up emcee. try: import emcee except ImportError: raise ImportError("Cannot find emcee.") # Check the dictionary. May need some more work. params = self._verify_dictionary(params) # Calculate the inverse variance mask. r_min = r_min if r_min is not None else 0.0 r_max = r_max if r_max is not None else 1e5 temp = rotationmap._populate_dictionary(p0, params) self.ivar = self._calc_ivar(x0=temp['x0'], y0=temp['y0'], inc=temp['inc'], PA=temp['PA'], z0=temp['z0'], psi=temp['psi'], tilt=temp['tilt'], r_min=r_min, r_max=r_max) # Check what the parameters are. labels = rotationmap._get_labels(params) if len(labels) != len(p0): raise ValueError("Mismatch in labels and p0. Check for integers.") print("Assuming:\n\tp0 = [%s]." % (', '.join(labels))) # Run an initial optimization using scipy.minimize. Recalculate the # inverse variance mask. if optimize: p0 = self._optimize_p0(p0, params) temp = rotationmap._populate_dictionary(p0, params) self.ivar = self._calc_ivar(x0=temp['x0'], y0=temp['y0'], inc=temp['inc'], PA=temp['PA'], z0=temp['z0'], psi=temp['psi'], tilt=temp['tilt'], r_min=r_min, r_max=r_max) # Plot the data to show where the mask is. self.plot_data(ivar=self.ivar) # Make sure all starting positions are valid. # COMING SOON. # Set up and run the MCMC. ndim = len(p0) nwalkers = 4 * ndim if nwalkers is None else nwalkers p0 = rotationmap._random_p0(p0, scatter, nwalkers) sampler = emcee.EnsembleSampler(nwalkers, ndim, self._ln_probability, args=[params, np.nan]) sampler.run_mcmc(p0, nburnin + nsteps) samples = sampler.chain[:, -int(nsteps):] samples = samples.reshape(-1, samples.shape[-1]) bestfit = np.median(samples, axis=0) bestfit = rotationmap._populate_dictionary(bestfit, params) # Diagnostic plots. if plot_walkers: rotationmap.plot_walkers(sampler.chain.T, nburnin, labels) if plot_corner: rotationmap.plot_corner(samples, labels) if plot_bestfit: self.plot_bestfit(bestfit, ivar=self.ivar) if plot_residual: self.plot_residual(bestfit, ivar=self.ivar) # Return the posterior distributions. if return_samples: return samples return np.percentile(samples, [16, 60, 84], axis=0) def _optimize_p0(self, theta, params): """Optimize the initial starting positions.""" from scipy.optimize import minimize # Negative log-likelihood function. def nlnL(theta): return -self._ln_probability(theta, params) # TODO: think of a way to include bounds. res = minimize(nlnL, x0=theta, method='TNC', options={'maxiter': 100000, 'ftol': 1e-3}) theta = res.x if res.success: print("Optimized starting positions:") else: print("WARNING: scipy.optimize did not converge.") print("Starting positions:") print('\tp0 =', ['%.4e' % t for t in theta]) return theta @staticmethod def _random_p0(p0, scatter, nwalkers): """Get the starting positions.""" p0 = np.squeeze(p0) dp0 = np.random.randn(nwalkers * len(p0)).reshape(nwalkers, len(p0)) dp0 = np.where(p0 == 0.0, 1.0, p0)[None, :] * (1.0 + scatter * dp0) return np.where(p0[None, :] == 0.0, dp0 - 1.0, dp0) def _ln_likelihood(self, params): """Log-likelihood function. Simple chi-squared likelihood.""" model = self._make_model(params) * 1e-3 lnx2 = np.where(self.mask, np.power((self.data - model), 2), 0.0) lnx2 = -0.5 * np.sum(lnx2 * self.ivar) return lnx2 if np.isfinite(lnx2) else -np.inf def _ln_probability(self, theta, *params_in): """Log-probablility function.""" model = rotationmap._populate_dictionary(theta, params_in[0]) if np.isfinite(self._ln_prior(model)): return self._ln_likelihood(model) return -np.inf def _ln_prior(self, params): """Log-priors. Uniform and uninformative.""" if abs(params['x0']) > 0.5: return -np.inf if abs(params['y0']) > 0.5: return -np.inf if not 0. < params['inc'] < 90.: return -np.inf if not -360. < params['PA'] < 360.: return -np.inf if not 0.0 < params['mstar'] < 5.0: return -np.inf if abs(self.vlsr - params['vlsr'] / 1e3) > 1.0: return -np.inf if not 0.0 <= params['z0'] < 1.0: return -np.inf if not 0.0 < params['psi'] < 2.0: return -np.inf if not -1.0 < params['tilt'] < 1.0: return -np.inf return 0.0 def _calc_ivar(self, x0=0.0, y0=0.0, inc=0.0, PA=0.0, z0=0.0, psi=0.0, tilt=0.0, r_min=0.0, r_max=1e5): """Calculate the inverse variance including radius mask.""" try: assert self.error.shape == self.data.shape except AttributeError: self.error = self.error * np.ones(self.data.shape) rvals = self.disk_coords(x0=x0, y0=y0, inc=inc, PA=PA, z0=z0, psi=psi, tilt=tilt)[0] mask = np.logical_and(rvals >= r_min, rvals <= r_max) mask = np.logical_and(mask, self.error > 0.0) return np.where(mask, np.power(self.error, -2.0), 0.0) @staticmethod def _get_labels(params): """Return the labels of the parameters to fit.""" idxs, labs = [], [] for k in params.keys(): if isinstance(params[k], int): if not isinstance(params[k], bool): idxs.append(params[k]) labs.append(k) return np.array(labs)[np.argsort(idxs)] @staticmethod def _populate_dictionary(theta, dictionary_in): """Populate the dictionary of free parameters.""" dictionary = dictionary_in.copy() for key in dictionary.keys(): if isinstance(dictionary[key], int): if not isinstance(dictionary[key], bool): dictionary[key] = theta[dictionary[key]] return dictionary def _verify_dictionary(self, params): """Check there are the the correct keys.""" if params.get('x0') is None: params['x0'] = 0.0 if params.get('y0') is None: params['y0'] = 0.0 if params.get('z0') is None: params['z0'] = 0.0 if params.get('psi') is None: params['psi'] = 1.0 if params.get('dist') is None: params['dist'] = 100. if params.get('tilt') is None: params['tilt'] = 0.0 if params.get('vlsr') is None:
<filename>src/specific_models/bot-iot/attack_identification/lstm.py # Author: <NAME> # github.com/kaylani2 # kaylani AT gta DOT ufrj DOT br ### K: Model: LSTM import sys import time import pandas as pd import os import math import numpy as np from numpy import mean, std from unit import remove_columns_with_one_value, remove_nan_columns, load_dataset from unit import display_general_information, display_feature_distribution from collections import Counter #from imblearn.over_sampling import RandomOverSampler, RandomUnderSampler import sklearn from sklearn import set_config from sklearn.impute import SimpleImputer from sklearn.svm import SVC, LinearSVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LinearRegression from sklearn.naive_bayes import GaussianNB from sklearn.preprocessing import LabelEncoder, OneHotEncoder, OrdinalEncoder from sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler from sklearn.metrics import confusion_matrix, precision_score, recall_score from sklearn.metrics import f1_score, classification_report, accuracy_score from sklearn.metrics import cohen_kappa_score, mean_squared_error from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split, PredefinedSplit, RandomizedSearchCV from sklearn.model_selection import GridSearchCV, RepeatedStratifiedKFold from sklearn.model_selection import cross_val_score from sklearn.decomposition import PCA from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif, chi2, mutual_info_classif from sklearn.utils import class_weight from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from tensorflow.keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor import keras.utils from keras import metrics from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Dense, Dropout from keras.layers import Conv2D, MaxPooling2D, Flatten, LSTM from keras.optimizers import RMSprop, Adam from keras.constraints import maxnorm ############################################################################### ## Define constants ############################################################################### pd.set_option ('display.max_rows', None) pd.set_option ('display.max_columns', 5) BOT_IOT_DIRECTORY = '../../../../datasets/bot-iot/' BOT_IOT_FEATURE_NAMES = 'UNSW_2018_IoT_Botnet_Dataset_Feature_Names.csv' BOT_IOT_FILE_5_PERCENT_SCHEMA = 'UNSW_2018_IoT_Botnet_Full5pc_{}.csv' # 1 - 4 FIVE_PERCENT_FILES = 4 BOT_IOT_FILE_FULL_SCHEMA = 'UNSW_2018_IoT_Botnet_Dataset_{}.csv' # 1 - 74 FULL_FILES = 74 FILE_NAME = BOT_IOT_DIRECTORY + BOT_IOT_FILE_5_PERCENT_SCHEMA FEATURES = BOT_IOT_DIRECTORY + BOT_IOT_FEATURE_NAMES NAN_VALUES = ['?', '.'] TARGET = 'attack' INDEX_COLUMN = 'pkSeqID' LABELS = ['attack', 'category', 'subcategory'] STATE = 0 try: STATE = int (sys.argv [1]) except: pass #for STATE in [1, 2, 3, 4, 5]: np.random.seed (STATE) print ('STATE:', STATE) ############################################################################### ## Load dataset ############################################################################### df = load_dataset (FILE_NAME, FIVE_PERCENT_FILES, INDEX_COLUMN, NAN_VALUES) ############################################################################### ## Clean dataset ############################################################################### ############################################################################### ### Remove columns with only one value df, log = remove_columns_with_one_value (df, verbose = False) print (log) ############################################################################### ### Remove redundant columns, useless columns and unused targets ### K: _number columns are numerical representations of other existing columns. ### K: category and subcategory are other labels. ### K: saddr and daddr may specialize the model to a single network redundant_columns = ['state_number', 'proto_number', 'flgs_number'] other_targets = ['category', 'subcategory'] misc_columns = ['saddr', 'daddr'] print ('Removing redundant columns:', redundant_columns) print ('Removing useless targets:', other_targets) print ('Removing misc columns:', misc_columns) columns_to_remove = redundant_columns + other_targets + misc_columns df.drop (axis = 'columns', columns = columns_to_remove, inplace = True) ############################################################################### ### Remove NaN columns (with a lot of NaN values) df, log = remove_nan_columns (df, 1/2, verbose = False) print (log) ############################################################################### ### Encode categorical features print ('Encoding categorical features (ordinal encoding).') my_encoder = OrdinalEncoder () df ['flgs'] = my_encoder.fit_transform (df ['flgs'].values.reshape (-1, 1)) df ['proto'] = my_encoder.fit_transform (df ['proto'].values.reshape (-1, 1)) df ['sport'] = my_encoder.fit_transform (df ['sport'].astype (str).values.reshape (-1, 1)) df ['dport'] = my_encoder.fit_transform (df ['dport'].astype (str).values.reshape (-1, 1)) df ['state'] = my_encoder.fit_transform (df ['state'].values.reshape (-1, 1)) print ('Objects:', list (df.select_dtypes ( ['object']).columns)) ############################################################################### ## Quick sanity check ############################################################################### display_general_information (df) ############################################################################### ## Split dataset into train and test sets ############################################################################### ### K: Dataset is too big? Drop. # drop_indices = np.random.choice (df.index, int (df.shape [0] * 0.5), # replace = False) # df = df.drop (drop_indices) TEST_SIZE = 3/10 VALIDATION_SIZE = 1/4 print ('Splitting dataset (test/train):', TEST_SIZE) X_train_df, X_test_df, y_train_df, y_test_df = train_test_split ( df.loc [:, df.columns != TARGET], df [TARGET], test_size = TEST_SIZE, random_state = STATE,) print ('Splitting dataset (validation/train):', VALIDATION_SIZE) X_train_df, X_val_df, y_train_df, y_val_df = train_test_split ( X_train_df, y_train_df, test_size = VALIDATION_SIZE, random_state = STATE,) X_train_df.sort_index (inplace = True) y_train_df.sort_index (inplace = True) X_val_df.sort_index (inplace = True) y_val_df.sort_index (inplace = True) X_test_df.sort_index (inplace = True) y_test_df.sort_index (inplace = True) print ('X_train_df shape:', X_train_df.shape) print ('y_train_df shape:', y_train_df.shape) print ('X_val_df shape:', X_val_df.shape) print ('y_val_df shape:', y_val_df.shape) print ('X_test_df shape:', X_test_df.shape) print ('y_test_df shape:', y_test_df.shape) ############################################################################### ## Convert dataframe to a numpy array ############################################################################### print ('\nConverting dataframe to numpy array.') X_train = X_train_df.values y_train = y_train_df.values X_val = X_val_df.values y_val = y_val_df.values X_test = X_test_df.values y_test = y_test_df.values print ('X_train shape:', X_train.shape) print ('y_train shape:', y_train.shape) print ('X_val shape:', X_val.shape) print ('y_val shape:', y_val.shape) print ('X_test shape:', X_test.shape) print ('y_test shape:', y_test.shape) ############################################################################### ## Apply normalization ############################################################################### ### K: NOTE: Only use derived information from the train set to avoid leakage. print ('\nApplying normalization.') startTime = time.time () scaler = StandardScaler () #scaler = MinMaxScaler (feature_range = (0, 1)) scaler.fit (X_train) X_train = scaler.transform (X_train) X_val = scaler.transform (X_val) X_test = scaler.transform (X_test) print (str (time.time () - startTime), 'to normalize data.') ############################################################################### ## Perform feature selection ############################################################################### NUMBER_OF_FEATURES = 9 #'all' print ('\nSelecting top', NUMBER_OF_FEATURES, 'features.') startTime = time.time () #fs = SelectKBest (score_func = mutual_info_classif, k = NUMBER_OF_FEATURES) ### K: ~30 minutes to FAIL fit mutual_info_classif to 5% bot-iot #fs = SelectKBest (score_func = chi2, k = NUMBER_OF_FEATURES) # X must be >= 0 ### K: ~4 seconds to fit chi2 to 5% bot-iot (MinMaxScaler (0, 1)) fs = SelectKBest (score_func = f_classif, k = NUMBER_OF_FEATURES) ### K: ~4 seconds to fit f_classif to 5% bot-iot fs.fit (X_train, y_train) X_train = fs.transform (X_train) X_val = fs.transform (X_val) X_test = fs.transform (X_test) print (str (time.time () - startTime), 'to select features.') print ('X_train shape:', X_train.shape) print ('y_train shape:', y_train.shape) print ('X_val shape:', X_val.shape) print ('y_val shape:', y_val.shape) print ('X_test shape:', X_test.shape) print ('y_test shape:', y_test.shape) bestFeatures = [] for feature in range (len (fs.scores_)): bestFeatures.append ({'f': feature, 's': fs.scores_ [feature]}) bestFeatures = sorted (bestFeatures, key = lambda k: k ['s']) for feature in bestFeatures: print ('Feature %d: %f' % (feature ['f'], feature ['s'])) ############################################################################### ## Rearrange samples for RNN ############################################################################### print ('\nRearranging dataset for the RNN.') print ('X_train shape:', X_train.shape) print ('y_train shape:', y_train.shape) print ('X_val shape:', X_val.shape) print ('y_val shape:', y_val.shape) print ('y_test shape:', y_test.shape) STEPS = 3 FEATURES = X_train.shape [1] def window_stack (a, stride = 1, numberOfSteps = 3): return np.hstack ( [ a [i:1+i-numberOfSteps or None:stride] for i in range (0,numberOfSteps) ]) X_train = window_stack (X_train, stride = 1, numberOfSteps = STEPS) X_train = X_train.reshape (X_train.shape [0], STEPS, FEATURES) X_val = window_stack (X_val, stride = 1, numberOfSteps = STEPS) X_val = X_val.reshape (X_val.shape [0], STEPS, FEATURES) X_test = window_stack (X_test, stride = 1, numberOfSteps = STEPS) X_test = X_test.reshape (X_test.shape [0], STEPS, FEATURES) y_train = y_train [ (STEPS - 1):] y_val = y_val [ (STEPS - 1):] y_test = y_test [ (STEPS - 1):] print ('X_train shape:', X_train.shape) print ('y_train shape:', y_train.shape) print ('X_val shape:', X_val.shape) print ('y_val shape:', y_val.shape) print ('X_test shape:', X_test.shape) print ('y_test shape:', y_test.shape) ############################################################################### ## Create learning model and tune hyperparameters ############################################################################### ### -1 indices -> train ### 0 indices -> validation test_fold = np.repeat ( [-1, 0], [X_train.shape [0], X_val.shape [0]]) myPreSplit = PredefinedSplit (test_fold) ''' def create_model (learn_rate = 0.01, dropout_rate = 0.0, weight_constraint = 0, units = 50): model = Sequential () model.add (LSTM (units = units, activation = 'relu' , input_shape= (X_train.shape [1], X_train.shape [2]))) model.add (Dense (1, activation = 'sigmoid')) model.compile (optimizer = 'adam', loss = 'binary_crossentropy',) return model model = KerasClassifier (build_fn = create_model, verbose = 2) batch_size = [5000, 1000]#10, 30, 50] epochs = [5]#, 5, 10] learn_rate = [0.001, 0.01, 0.1] dropout_rate = [0.0]#, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] weight_constraint = [0]#, 2, 3, 4, 5] units = [10, 50, 100] param_grid = dict (batch_size = batch_size, epochs = epochs, dropout_rate = dropout_rate, learn_rate = learn_rate, weight_constraint = weight_constraint, units = units) grid = GridSearchCV (estimator = model, param_grid = param_grid, scoring = 'f1_weighted', cv = myPreSplit, verbose = 2, n_jobs = -1) grid_result = grid.fit (np.concatenate ( (X_train, X_val), axis = 0), np.concatenate ( (y_train, y_val), axis = 0)) print (grid_result.best_params_) print ("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) means = grid_result.cv_results_ ['mean_test_score'] stds = grid_result.cv_results_ ['std_test_score'] params = grid_result.cv_results_ ['params'] for mean, stdev, param in zip (means, stds, params): print ("%f (%f) with: %r" % (mean, stdev, param)) sys.exit () ''' ############################################################################### ## Finished model METRICS = [keras.metrics.TruePositives (name = 'TP'), keras.metrics.FalsePositives (name = 'FP'), keras.metrics.TrueNegatives (name = 'TN'), keras.metrics.FalseNegatives (name = 'FN'), keras.metrics.BinaryAccuracy (name = 'Acc.'), keras.metrics.Precision (name = 'Prec.'), keras.metrics.Recall (name = 'Recall'), keras.metrics.AUC (name = 'AUC'),] BATCH_SIZE = 5000 NUMBER_OF_EPOCHS = 3 LEARNING_RATE = 0.1 DROPOUT_RATE = 0.2 clf = Sequential () clf.add (LSTM (100, activation = 'relu', #return_sequences = True, input_shape = (X_train.shape [1], X_train.shape [2]))) clf.add (Dropout (DROPOUT_RATE)) #clf.add (LSTM (50, activation='relu')) clf.add (Dense (1, activation = 'sigmoid')) print ('Model summary:') clf.summary () ############################################################################### ## Compile the network ############################################################################### print ('\nCompiling the network.') clf.compile (optimizer = 'adam', loss = 'binary_crossentropy', metrics = METRICS) ############################################################################### ## Fit the network ############################################################################### print ('\nFitting the network.') startTime = time.time () history = clf.fit (X_train, y_train, batch_size = BATCH_SIZE, epochs = NUMBER_OF_EPOCHS, verbose = 2, #1 = progress bar, not useful for logging workers = 0, use_multiprocessing = True, #class_weight = 'auto', validation_data = (X_val, y_val)) print (str (time.time () - startTime), 's to train model.') ############################################################################### ## Analyze results ############################################################################### print ('\nPerformance on TRAIN set:') y_pred = clf.predict (X_train) y_pred = y_pred.round () my_confusion_matrix = confusion_matrix (y_train, y_pred, labels = df [TARGET].unique ()) tn, fp, fn, tp = my_confusion_matrix.ravel () print ('Confusion matrix:') print (my_confusion_matrix) print ('Accuracy:', accuracy_score (y_train, y_pred)) print ('Precision:', precision_score (y_train, y_pred, average = 'macro')) print ('Recall:', recall_score (y_train, y_pred, average = 'macro')) print ('F1:', f1_score (y_train, y_pred, average = 'macro')) print ('Cohen Kappa:', cohen_kappa_score (y_train, y_pred, labels = df [TARGET].unique ())) print ('TP:', tp) print
+ response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_bandwidth_profile_peak_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_bandwidth_profile_peak_information_rate_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/available-capacity/bandwidth-profile/peak-information-rate/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/available-capacity/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_total_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_total_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/available-capacity/total-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_composed_rule_grouptopology_uuidcomposed_rule_group_node_uuidcomposed_rule_group_node_rule_group_uuid_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_composed_rule_grouptopology_uuidcomposed_rule_group_node_uuidcomposed_rule_group_node_rule_group_uuid_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/composed-rule-group={topology-uuid},{composed-rule-group-node-uuid},{composed-rule-group-node-rule-group-uuid}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', topology_uuid='topology_uuid_example', composed_rule_group_node_uuid='composed_rule_group_node_uuid_example', composed_rule_group_node_rule_group_uuid='composed_rule_group_node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_cost_characteristiccost_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_cost_characteristiccost_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/cost-characteristic={cost-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', cost_name='cost_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_associated_node_rule_grouptopology_uuidassociated_node_rule_group_node_uuidassociated_node_rule_group_node_rule_group_uuid_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_associated_node_rule_grouptopology_uuidassociated_node_rule_group_node_uuidassociated_node_rule_group_node_rule_group_uuid_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/associated-node-rule-group={topology-uuid},{associated-node-rule-group-node-uuid},{associated-node-rule-group-node-rule-group-uuid}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example', topology_uuid='topology_uuid_example', associated_node_rule_group_node_uuid='associated_node_rule_group_node_uuid_example', associated_node_rule_group_node_rule_group_uuid='associated_node_rule_group_node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_committed_burst_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_committed_burst_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/available-capacity/bandwidth-profile/committed-burst-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_committed_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_committed_information_rate_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/available-capacity/bandwidth-profile/committed-information-rate/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/available-capacity/bandwidth-profile/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_peak_burst_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_peak_burst_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/available-capacity/bandwidth-profile/peak-burst-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_peak_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_bandwidth_profile_peak_information_rate_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/available-capacity/bandwidth-profile/peak-information-rate/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/available-capacity/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_total_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_available_capacity_total_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/available-capacity/total-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_cost_characteristiccost_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_cost_characteristiccost_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/cost-characteristic={cost-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example', cost_name='cost_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_latency_characteristictraffic_property_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_latency_characteristictraffic_property_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/latency-characteristic={traffic-property-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example', traffic_property_name='traffic_property_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_namevalue_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_namevalue_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/name={value-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example', value_name='value_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_risk_characteristicrisk_characteristic_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_risk_characteristicrisk_characteristic_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/risk-characteristic={risk-characteristic-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example', risk_characteristic_name='risk_characteristic_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_rulelocal_id_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_rulelocal_id_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/rule={local-id}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example', local_id='local_id_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_rulelocal_id_namevalue_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_rulelocal_id_namevalue_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/rule={local-id}/name={value-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example', local_id='local_id_example', value_name='value_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_committed_burst_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_committed_burst_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/total-potential-capacity/bandwidth-profile/committed-burst-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_committed_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_committed_information_rate_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/total-potential-capacity/bandwidth-profile/committed-information-rate/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/total-potential-capacity/bandwidth-profile/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_peak_burst_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_peak_burst_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/total-potential-capacity/bandwidth-profile/peak-burst-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_peak_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_bandwidth_profile_peak_information_rate_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/total-potential-capacity/bandwidth-profile/peak-information-rate/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/total-potential-capacity/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_total_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_total_potential_capacity_total_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/inter-rule-group={inter-rule-group-uuid}/total-potential-capacity/total-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', inter_rule_group_uuid='inter_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_latency_characteristictraffic_property_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_latency_characteristictraffic_property_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/latency-characteristic={traffic-property-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', traffic_property_name='traffic_property_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_namevalue_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_namevalue_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/name={value-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', value_name='value_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_node_edge_pointtopology_uuidnode_edge_point_node_uuidnode_edge_point_uuid_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_node_edge_pointtopology_uuidnode_edge_point_node_uuidnode_edge_point_uuid_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/node-edge-point={topology-uuid},{node-edge-point-node-uuid},{node-edge-point-uuid}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', topology_uuid='topology_uuid_example', node_edge_point_node_uuid='node_edge_point_node_uuid_example', node_edge_point_uuid='node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_risk_characteristicrisk_characteristic_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_risk_characteristicrisk_characteristic_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/risk-characteristic={risk-characteristic-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', risk_characteristic_name='risk_characteristic_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_rulelocal_id_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_rulelocal_id_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/rule={local-id}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', local_id='local_id_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_rulelocal_id_namevalue_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_rulelocal_id_namevalue_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/rule={local-id}/name={value-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example', local_id='local_id_example', value_name='value_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_committed_burst_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_committed_burst_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/total-potential-capacity/bandwidth-profile/committed-burst-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_committed_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_committed_information_rate_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/total-potential-capacity/bandwidth-profile/committed-information-rate/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/total-potential-capacity/bandwidth-profile/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_peak_burst_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_peak_burst_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/total-potential-capacity/bandwidth-profile/peak-burst-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_peak_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_bandwidth_profile_peak_information_rate_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/total-potential-capacity/bandwidth-profile/peak-information-rate/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/total-potential-capacity/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_total_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_total_potential_capacity_total_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/node-rule-group={node-rule-group-uuid}/total-potential-capacity/total-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', node_rule_group_uuid='node_rule_group_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_aggregated_node_edge_pointtopology_uuidaggregated_node_edge_point_node_uuidnode_edge_point_uuid_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_aggregated_node_edge_pointtopology_uuidaggregated_node_edge_point_node_uuidnode_edge_point_uuid_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/aggregated-node-edge-point={topology-uuid},{aggregated-node-edge-point-node-uuid},{node-edge-point-uuid}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example', topology_uuid='topology_uuid_example', aggregated_node_edge_point_node_uuid='aggregated_node_edge_point_node_uuid_example', node_edge_point_uuid='node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_committed_burst_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_committed_burst_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/available-capacity/bandwidth-profile/committed-burst-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_committed_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_committed_information_rate_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/available-capacity/bandwidth-profile/committed-information-rate/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/available-capacity/bandwidth-profile/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_peak_burst_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_peak_burst_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/available-capacity/bandwidth-profile/peak-burst-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_peak_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_bandwidth_profile_peak_information_rate_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/available-capacity/bandwidth-profile/peak-information-rate/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/available-capacity/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_total_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_available_capacity_total_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/available-capacity/total-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_mapped_service_interface_pointservice_interface_point_uuid_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_mapped_service_interface_pointservice_interface_point_uuid_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/mapped-service-interface-point={service-interface-point-uuid}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example', service_interface_point_uuid='service_interface_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_namevalue_name_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_namevalue_name_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/name={value-name}/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example', value_name='value_name_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_total_potential_capacity_bandwidth_profile_committed_burst_size_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_total_potential_capacity_bandwidth_profile_committed_burst_size_get """ response = self.client.open( '/data/context/topology-context/topology={uuid}/node={node-uuid}/owned-node-edge-point={owned-node-edge-point-uuid}/total-potential-capacity/bandwidth-profile/committed-burst-size/'.format(uuid='uuid_example', node_uuid='node_uuid_example', owned_node_edge_point_uuid='owned_node_edge_point_uuid_example'), method='GET') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) def test_data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_total_potential_capacity_bandwidth_profile_committed_information_rate_get(self): """Test case for data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_total_potential_capacity_bandwidth_profile_committed_information_rate_get """ response
#!/usr/bin/env python3 # need this to generate randomness import random # defining the text lists # list of scientific fields fieldList = ['physics', 'biology', 'chemistry', 'economics', 'history', 'sociology', 'mathematics'] # list of journals journalList = ["Journal of {}", "{} Review Letters", "Annals of {}", "Modern {}", "Review of {}", "{} Direct", "{} Chronicle", "{} Today", "Society of {}", "Contemporary {}", "{} Communications", "Applied {}", "{} Gazette", "Journal of Recent {}", "Applied {} Review", "Developments in {}", "Review of Recent {}", "{} Today"] # list of months monthList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] # list of connector types comparerList = ['with', 'in', 'versus', 'against', 'and'] # list of article types workTypeGeneric = ['study', 'report', 'overview', 'theory', 'analysis', 'summary', 'review', 'survey', 'investigation', 'model', 'foundations'] workTypeSTEM = ['technical note', 'Monte Carlo', 'simulation', 'computation', 'trial', 'document', 'test', 'determination', 'proof'] optionalWorkPrefix = ['follow-up', 'preliminary', 'improved', 'initial', 'first', 'complete', 'comprehensive', 'interim', 'concept', 'proposed', 'empirical', 'internal', 'novel', 'new', 'inductive', 'in-depth', 'final', 'revised'] # list of comparison work comparisonList = ['comparison', 'benchmark'] # list of measurement tools and reports types toolTypeGeneric = ['laboratory', 'tabletop', 'field'] toolTypePhysics = ['collider', 'accelerator', 'passive'] toolTypeChemistry = ['spectrographic', 'X-ray', 'laser'] toolTypeBiology = ['chemical', 'bioreactor', 'microscope'] toolReport = ['scan', 'probe', 'experiment', 'study', 'measurement', 'imaging'] # other ways to address the study addressWork = ['on', 'about', 'concerning', 'regarding', 'reevaluating', 'addressing'] # broken down by fields for better lists # prefix = adjectives babblePrefixGeneric = ['repeated', 'rare', 'unique', 'common', 'induced', 'hypothetical', 'dual', 'deep', 'networked', 'recursive', 'layered', 'recurring', 'singular', 'structured', 'embedded', 'regular', 'artificial', 'monadic', 'speculative', 'convoluted', 'inferred', 'fabricated', 'inhibited', 'hidden', 'algorithmic', 'observable', 'additive', 'parallel', 'adversarial', 'stochastic', 'statistical', 'stable', 'critical', 'fragile', 'generative', 'dominant', 'material', 'affected', 'static', 'decayed', 'inverted', 'latent', 'fundamental', 'ambient', 'cyclic', 'recurring', 'aligned', 'separated', 'ordered', 'universal', 'restricted', 'recent', 'effective', 'apparent', 'balanced', 'specific', 'connected'] babblePrefixPhysics = ['massive', 'manifold', 'light', 'accelerated', 'subtractive', 'weak', 'strong', 'scalar', 'nuclear', 'commutating', 'bayesian', 'cosmic', 'degenerate', 'strange', 'symmetric', 'fractal', 'vectorised', 'generalised', 'gravitational', 'elastic', 'radiative', 'warped', 'energetic', 'kinematic' ] babblePrefixBiology = ['viral', 'endemic', 'pathological', 'genetic', 'soluable', 'expressive', 'mutable', 'sequenced', 'methylated', 'dense', 'bacterial', 'cellular', 'soluable', 'suspended', 'emulsified', 'sustained', 'clinical', 'cultivated', 'living', 'vitrified', 'calcified', 'active', 'activated', 'tubular'] babblePrefixChemistry = ['soluable', 'suspended', 'emulsified', 'crystalline', 'planar', 'manifold', 'massive', 'light', 'symmetric', 'asymmetric', 'dissolved', 'fractional', 'bonded','computational','plastic', 'sustained', 'sublimated', 'vaporised', 'aerolised', 'frozen', 'molten', 'metallic', 'lathanic', 'pulverised'] babblePrefixHistory = ['medieval','european','political', 'national', 'global', 'local', 'important', 'far-reaching', 'memorial', 'falsified', 'verified', 'sourced', 'memetic', 'classical', 'ancient', 'sourced', 'reported', 'documented', 'military', 'civilian', 'recorded', 'coastal', 'urban', 'forgotten', 'pivotal', 'crucial', 'essential'] babblePrefixEconomics = ['national', 'global', 'local', 'fungible', 'political', 'digital', 'motivated', 'technical', 'visionary', 'sustainable', 'ethical', 'fake', 'memetic', 'volatile', 'predictive', 'trusted', 'optimal', 'leveraged', 'valuable', 'essential', 'key'] babblePrefixSociology = ['national', 'global', 'local', 'social', 'compelled', 'deliberate', 'political', 'fake', 'ethical', 'accidental', 'predictable', 'formative', 'memetic', 'economic', 'testable', 'academic', 'distributed', 'normative', 'developmental', 'normalised', 'creative'] babblePrefixMathematics = ['manifold', 'subtractive', 'geometric', 'distributed', 'factorised', 'commutating', 'bayesian', 'frequentist', 'hyperbolic', 'symmetric', 'orthogonal' 'fractal', 'normal', 'generalised', 'Gaussian', 'Laplacian', 'Riemannian', 'Lorentzian', 'Abelian', 'axiomatic', 'complex', 'finite', 'null', 'chaotic', 'linear', 'quadratic', 'higher-order', 'approximate', 'quantised', 'integrated', 'derivative', 'affine', 'random', 'functional', 'computable', 'warped', 'curved', 'linearised'] # first part of the noun (some sort of prefix) babbleGeneric1 = ['meta', 'super', 'inter', 'omni', 'intra', 'ultra', 'proto', 'anti', 'hyper', 'un', 'mono', 'pre', 'poly', 'multi', 'co-', 'sub', 'endo', 'macro', 'nano', 'micro', 'exo', 'para', 'homo', 'trans', 'quasi'] babblePhysics1 = ['uni', 'radio', 'quantum ', 'bulk ', 'phase ', 'tensor', 'block ', 'cross', 'n-', 'z-', 's-', 'r-', 'holo', 'chromo', 'electro'] babbleChemistry1 = ['cryo', 'radio', 'quantum ', 'bulk ', 'phase ', 'hydro', 'nitro', 'sodium', 'n-', 'geo', 'litho', 'lipo'] babbleBiology1 = ['cardio', 'neuro', 'sucra', 'angio', 'immuno', 'oleo', 'myo', 'amino', 'pheno', 'bio', 'phyto', 'meso'] babbleHistory1 = ['war ', 'peace ', 'land ', 'ocean ', 'meso', 'post', 'state ', 'imperial ', 'royal ', 'forest ', 'desert ', 'city '] babbleEconomics1 = ['socio', 'cyber', 'eco', 'neo', 'geo', 'market ', 'block-', 'cross', 'post'] babbleSociology1 = ['socio','cyber', 'eco', 'neo', 'retro', 'ethno', 'block-', 'cross', 'post'] babbleMathematics1 = ['ρ-','σ-','α-', 'bulk ', 'phase ', 'φ-', 'block ', 'ortho', 'n-', 'z-', 's-', 'r-', 'λ-', 'crypto', 'pseudo', 'holo', 'denso', 'chromo'] # second part of the noun babbleGeneric2 = ['points', 'sequences', 'devices', 'types', 'chains', 'potentials', 'clusters', 'actions', 'buffers', 'reactions', 'processes', 'patterns', 'mappings'] babblePhysics2 = ['particles', 'emissions', 'projections', 'calculations', 'cavitations', 'conductors', 'trajectories', 'arrays', 'cascades', 'bosons', 'leptons', 'hadrons', 'mesons', 'poles', 'quarks', 'rings', 'events', 'fluids', 'matter', 'lattices', 'remnants', 'surfaces', 'excitations', 'topologies', 'resonances', 'coefficients', 'oscillations', 'plasmas', 'condensates', 'states', 'collisions', 'impacts', 'amplitudes', 'dynamics', 'spectra', 'violations', 'dimensions', 'strings', 'systems'] babbleChemistry2 = ['structures', 'chlorates', 'formations', 'rings', 'oxides', 'solvents', 'lubricants', 'depositions', 'growths', 'fluids', 'phosphates' , 'conductors', 'calculations', 'carbons', 'magnets', 'ferrites', 'solids', 'bonds', 'films', 'chlorides', 'fluids', 'filters', 'excitations', 'surfaces', 'resonances', 'coefficients', 'minerals', 'phthalates', 'glasses', 'gases', 'aromatics', 'solutions', 'emulsions'] babbleBiology2 = ['structures', 'rhizomes', 'formations', 'rings', 'oxides', 'solvents', 'secretions', 'depositions', 'growths', 'fluids', 'cavitations' , 'matrices', 'plasmids', 'cascades', 'ribosomes', 'peptides', 'solids', 'bonds', 'fluids', 'lattices', 'films', 'coefficients', 'cultures', 'scaffolds', 'signalling', 'saccharids', 'acids', 'compounds', 'toxins', 'proteins', 'pathways', 'organelles', 'glands'] babbleHistory2 = ['settlements', 'narratives', 'timelines', 'aggressions', 'trends', 'events', 'conflicts', 'populations', 'excavations', 'histories', 'protests', 'migrations', 'remnants', 'ruins', 'artifacts', 'cultures', 'societies', 'civilisations', 'communes', 'locations', 'museums'] babbleEconomics2 = ['investments', 'narratives', 'timelines', 'fluctuations', 'trends', 'predictions', 'events', 'populations', 'crashes', 'histories', 'collapses', 'movements', 'indicators', 'signals', 'warnings', 'funds', 'accounts', 'treasuries'] babbleSociology2 = ['media', 'narratives', 'timelines', 'fluctuations', 'trends', 'assignations', 'teachings', 'populations', 'linguistics', 'histories', 'modernism', 'movements', 'cultures', 'societies', 'identities', 'journalism', 'events', 'messaging'] babbleMathematics2 = ['metrics', 'manifolds', 'toplogies', 'projections', 'algebras', 'relationships', 'connections', 'tensors', 'vectors', 'scalars', 'numbers', 'primes', 'tuples', 'orders', 'infinities', 'calculus', 'integrals', 'sets', 'dimensions', 'fields', 'solutions'] # Loop to make several of these... for x in range(1, 21): # Decide scientific field fieldType = random.choice(fieldList) # Use this to create the appropriate pools to draw from if fieldType == 'physics': toolType = toolTypePhysics + toolTypeGeneric workType = workTypeGeneric + workTypeSTEM babblePrefix = babblePrefixGeneric + babblePrefixPhysics babble1 = babbleGeneric1 + babblePhysics1 babble2 = babbleGeneric2 + babblePhysics2 if fieldType == 'chemistry': toolType = toolTypeChemistry + toolTypeGeneric workType = workTypeGeneric + workTypeSTEM babblePrefix = babblePrefixGeneric + babblePrefixChemistry babble1 = babbleGeneric1 + babbleChemistry1 babble2 = babbleGeneric2 + babbleChemistry2 if fieldType == 'biology': toolType = toolTypeBiology + toolTypeGeneric workType = workTypeGeneric + workTypeSTEM babblePrefix = babblePrefixGeneric + babblePrefixBiology babble1 = babbleGeneric1 + babbleBiology1 babble2 = babbleGeneric2 + babbleBiology2 if fieldType == 'history': workType = workTypeGeneric babblePrefix = babblePrefixGeneric + babblePrefixHistory babble1 = babbleGeneric1 + babbleHistory1 babble2 = babbleGeneric2 + babbleHistory2 if fieldType == 'economics': workType = workTypeGeneric babblePrefix = babblePrefixGeneric + babblePrefixEconomics babble1 = babbleGeneric1 + babbleEconomics1 babble2 = babbleGeneric2 + babbleEconomics2 if fieldType == 'sociology': workType = workTypeGeneric babblePrefix = babblePrefixGeneric + babblePrefixSociology babble1 = babbleGeneric1 + babbleSociology1 babble2 = babbleGeneric2 + babbleSociology2 if fieldType == 'mathematics': workType = workTypeGeneric babblePrefix = babblePrefixGeneric + babblePrefixMathematics babble1 = babbleGeneric1 + babbleMathematics1 babble2 = babbleGeneric2 + babbleMathematics2 # Randomly determining the title type # 1: type + babble prefix + babble # 2: type prefix + type + babble prefix + babble # 3: type prefix + type + babble # 4: address + babble prefix + babble # 5: field + of + babble prefix + babble # 6: type of babble1 in babble2 # 7: comparison of babble and babble prefix + babble # 8: type + babble1 + babble prefix + babble # 9: tool + work type + babble # 10: tool + work type + babble prefix + babble if fieldType == 'physics' or fieldType == 'chemistry' or fieldType == 'biology': titleType = random.randint(1,11) else: titleType = random.randint(1,8) # Build title depending on random result if titleType == 1: workTitle = ((random.choice(workType)).title() + " of " + random.choice(babblePrefix).title() + " " + (random.choice(babble1) + random.choice(babble2)).title()) elif titleType == 2: workTitle = ((random.choice(optionalWorkPrefix) + " " + random.choice(workType)).title() + " of " + random.choice(babblePrefix).title() + " " + (random.choice(babble1)+random.choice(babble2)).title()) elif titleType == 3: workTitle = ((random.choice(optionalWorkPrefix) + " " + random.choice(workType)).title() + " of " + (random.choice(babble1)+random.choice(babble2)).title()) elif titleType == 4: workTitle = ((random.choice(addressWork) + " " + random.choice(babblePrefix) + " " + random.choice(babble1) + random.choice(babble2)).title()) elif titleType == 5: workTitle = (fieldType.title() + " of " + (random.choice(babblePrefix) + " " + random.choice(babble1) + random.choice(babble2)).title()) elif titleType == 6: workTitle = (random.choice(workType).title() + " of " + (random.choice(babble1) + random.choice(babble2)).title() + " in " + (random.choice(babble1) + random.choice(babble2)).title()) elif titleType == 7: workTitle = (random.choice(comparisonList).title() + " of " + (random.choice(babblePrefix) + " " + random.choice(babble2)).title() + " " + random.choice(comparerList) +
out_score, det_point[0][1], det_point[0][0]]) # print([i, 0, out_score, det_point[1][1], det_point[1][0]]) true_res[i] = point # [num_guidewire, num_point, 2] # print(point) print('avg_infer_time:' + str(inference_time / self.inference_num)) return true_res, pred_res def compute_aps(self, true_res, pred_res, threshold): APs = {} for cls in range(self.num_classes): pred_res_cls = [x for x in pred_res if x[1] == cls] if len(pred_res_cls) == 0: APs[cls] = 0 continue true_res_cls = {} npos = 0 for index in true_res: # index is the image_id guidewires = true_res[index] # [num_guidewire, num_point, 2] guidewires = np.reshape(guidewires, [guidewires.shape[0] * guidewires.shape[1], 1, 2]) npos += len(guidewires) # compute recall point_pos = np.array([x[cls] for x in guidewires]) # [num_guidewire, 2] true_res_cls[index] = { 'point_pos': point_pos, } ids = [x[0] for x in pred_res_cls] scores = np.array([x[2] for x in pred_res_cls]) points = np.array([x[3:] for x in pred_res_cls]) sorted_ind = np.argsort(-scores) points = points[sorted_ind, :] # sorted ids = [ids[x] for x in sorted_ind] # sorted nd = len(ids) tp = np.zeros(nd) fp = np.zeros(nd) for j in range(nd): ture_point = true_res_cls[ids[j]] point1 = points[j, :] # [2] dis_min = np.inf PGT = ture_point['point_pos'] # [num_guidewire, 2] if len(PGT) > 0: dis_square = np.square(PGT[:, 0] - point1[0]) + np.square(PGT[:, 1] - point1[1]) dis_min = np.min(dis_square) if dis_min < threshold * threshold: tp[j] = 1. else: fp[j] = 1. fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / np.maximum(float(npos), np.finfo(np.float64).eps) prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = self._voc_ap(rec, prec) APs[cls] = ap return APs def makeGaussian(height, width, sigma=3, center=None): """ make一个高斯核,是生成heatmap的一个部分 """ x = np.arange(0, width, 1, float) y = np.arange(0, height, 1, float)[:, np.newaxis] if center is None: x0 = width // 2 y0 = height // 2 else: x0 = center[0] y0 = center[1] return np.exp(-4 * np.log(2) * ((x - x0) ** 2 + (y - y0) ** 2) / (sigma ** 2)) class MAPCallbackBox: def __init__(self, model, val_dataset, class_names, inference_num=50, batch_size=1): super(MAPCallbackBox, self).__init__() self.model = model self.inference_num = inference_num self.class_names = class_names self.num_classes = len(class_names) self.val_dataset = val_dataset self.batch_size = batch_size def _voc_ap(self, rec, prec): # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def calculate_result(self): true_res = {} pred_res = [] inference_time = 0 for i in range(self.inference_num): image, class_ids, bbox, point = modellib.load_image_gt_eval(self.val_dataset, i) start = time.time() results = self.model.detect([image])[0] end = time.time() inference_time = inference_time + (end - start) out_boxes = results['rois'] out_scores = results['scores'] if len(out_boxes) > 0: for out_box, out_score in zip( out_boxes, out_scores): pred_res.append([i, 0, out_score, out_box]) # print([i, 0, out_score, out_box]) true_res[i] = bbox # [num_guidewire, 4] # print(bbox) print('avg_infer_time:' + str(inference_time / self.inference_num)) return true_res, pred_res def compute_iou(self, box, boxes, box_area, boxes_area): # Calculate intersection areas y1 = np.maximum(box[0], boxes[:, 0]) y2 = np.minimum(box[2], boxes[:, 2]) x1 = np.maximum(box[1], boxes[:, 1]) x2 = np.minimum(box[3], boxes[:, 3]) intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0) union = box_area + boxes_area[:] - intersection[:] iou = intersection / union return iou def compute_aps(self, true_res, pred_res): APs = {} for cls in range(self.num_classes): pred_res_cls = [x for x in pred_res if x[1] == cls] if len(pred_res_cls) == 0: APs[cls] = 0 continue true_res_cls = {} npos = 0 for index in true_res: # index is the image_id guidewires = true_res[index] # [num_guidewire, 4] npos += len(guidewires) # compute recall point_pos = np.array([x for x in guidewires]) # [num_guidewire, 4] true_res_cls[index] = { 'point_pos': point_pos, } ids = [x[0] for x in pred_res_cls] scores = np.array([x[2] for x in pred_res_cls]) points = np.array([x[3] for x in pred_res_cls]) sorted_ind = np.argsort(-scores) points = points[sorted_ind, :] # sorted ids = [ids[x] for x in sorted_ind] # sorted nd = len(ids) tp = np.zeros(nd) fp = np.zeros(nd) for j in range(nd): ture_point = true_res_cls[ids[j]] box = points[j, :] # [4] PGT = ture_point['point_pos'] # [num_guidewire, 4] box_area = (box[2] - box[0]) * (box[3] - box[1]) boxes_area = (PGT[:, 2] - PGT[:, 0]) * (PGT[:, 3] - PGT[:, 1]) if len(PGT) > 0: IOU = self.compute_iou(box, PGT, box_area, boxes_area) iou_max = np.max(IOU) if iou_max > 0.5: tp[j] = 1. else: fp[j] = 1. fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / np.maximum(float(npos), np.finfo(np.float64).eps) prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = self._voc_ap(rec, prec) APs[cls] = ap return APs def on_epoch_end(self, logs=None): logs = logs or {} K.set_learning_phase(0) # For BN true_res, pred_res = self.calculate_result() APs = self.compute_aps(true_res, pred_res) for cls in range(self.num_classes): if cls in APs: print(self.class_names[cls] + ' ap: ', APs[cls]) mAP = np.mean([APs[cls] for cls in APs]) print('mAP: ', mAP) logs['mAP'] = mAP class MAPCallbackPCK: def __init__(self, model, val_dataset, class_names, inference_num=50, batch_size=1): super(MAPCallbackPCK, self).__init__() self.model = model self.inference_num = inference_num self.class_names = class_names self.num_classes = len(class_names) self.val_dataset = val_dataset self.batch_size = batch_size def _voc_ap(self, rec, prec): # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def check_dt(self, box, gtbox): box_area = (box[2] - box[0]) * (box[3] - box[1]) boxes_area = (gtbox[:, 2] - gtbox[:, 0]) * (gtbox[:, 3] - gtbox[:, 1]) IOU = self.compute_iou(box, gtbox, box_area, boxes_area) iou_max = np.max(IOU) if iou_max > 0.5: return True else: return False def calculate_result(self): true_res = {} pred_res = [] inference_time = 0 for i in range(self.inference_num): image, class_ids, bbox, point = modellib.load_image_gt_eval(self.val_dataset, i) start = time.time() out_masks = self.model.localization([image], [bbox])[0] # print(out_masks.shape) end = time.time() inference_time = inference_time + (end - start) for out_mask in out_masks: det_point = np.unravel_index(out_mask[:, :, 0].argmax(), out_mask[:, :, 0].shape) pred_res.append([i, 0, det_point[1] + 1, det_point[0] + 1]) # print([i, 0, det_point[1] + 1, det_point[0] + 1]) det_point = np.unravel_index(out_mask[:, :, 1].argmax(), out_mask[:, :, 1].shape) pred_res.append([i, 1, det_point[1] + 1, det_point[0] + 1]) # print([i, 1, det_point[1] + 1, det_point[0] + 1]) true_res[i] = point # [num_guidewire, num_point, 2] print('avg_infer_time:' + str(inference_time / self.inference_num)) return true_res, pred_res def compute_iou(self, box, boxes, box_area, boxes_area): # Calculate intersection areas y1 = np.maximum(box[0], boxes[:, 0]) y2 = np.minimum(box[2], boxes[:, 2]) x1 = np.maximum(box[1], boxes[:, 1]) x2 = np.minimum(box[3], boxes[:, 3]) intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0) union = box_area + boxes_area[:] - intersection[:] iou = intersection / union return iou def compute_pck(self, true_res, pred_res, threshold): APs = {} for cls in range(self.num_classes): true_num = 0 pred_res_cls = [x for x in pred_res if x[1] == cls] num_all = len(pred_res_cls) if num_all == 0: APs[cls] = 0 continue true_res_cls = {} for index in true_res: # index is the image_id guidewires = true_res[index] # [num_guidewire, num_point, 2] point_pos = np.array([x[cls] for x in guidewires]) # [num_guidewire, 2] true_res_cls[index] = { 'point_pos': point_pos, } for j in pred_res_cls: ture_point = true_res_cls[j[0]] point1 = j[2:] # [2] PGT = ture_point['point_pos'] # [num_guidewire, 2] if len(PGT) > 0: dis_square = np.square(PGT[:, 0] - point1[0]) + np.square(PGT[:, 1] - point1[1]) dis_min = np.min(dis_square) if dis_min < threshold * threshold: true_num += 1 print(true_num, num_all) APs[cls] = true_num / num_all return APs def on_epoch_end(self, logs=None): logs = logs or {} K.set_learning_phase(0) # For BN true_res, pred_res
from __future__ import division import ogr import glob import gdal import osr import osgeo import numpy as np import os, os.path, shutil import osgeo.ogr import osgeo.osr from gdalconst import * import csv import xlrd from osgeo import ogr from TEST1.TASTE1.gis.vector.write import * from math import radians, cos, sin, asin, sqrt, atan2, degrees,ceil def get_extent(fn): ds = gdal.Open(fn) gt = ds.GetGeoTransform() return (gt[0], gt[3], gt[0] + gt[1] * ds.RasterXSize, gt[3] + gt[5] * ds.RasterYSize) def mosiac(path): print ("Fetching all files from directory") file_path = str(path) os.chdir(file_path) file=glob.glob('*.tif') #print file min_x, max_y, max_x, min_y = get_extent(file[0]) for fn in file[1:]: minx, maxy, maxx, miny = get_extent(fn) min_x = min(min_x,minx) max_y = max(max_y,maxy) max_x = max(max_x,maxx) min_y = min(min_y,miny) in_ds = gdal.Open(file[0]) gt = list(in_ds.GetGeoTransform()) rows = ceil((max_y-min_y)/-gt[5]) col = ceil((max_x - min_x) / gt[1]) folderLocation, folderName = creating_directory() print ("Please Provide Information Regarding New Dataset which will store all Final Information") name = input("Enter Dataset Name") dstPath = os.path.join(folderLocation, "%s.tif" % name) fileformat = in_ds.GetDriver().ShortName driver = gdal.GetDriverByName(str(fileformat)) dst_ds = driver.Create(dstPath, int(col), int(rows), in_ds.RasterCount, GDT_Int16) dst_ds.SetProjection(in_ds.GetProjection()) gt[0],gt[3]=min_x,max_y dst_ds.SetGeoTransform(gt) out_band=dst_ds.GetRasterBand(1) for fn in file: in_ds = gdal.Open(fn) trans=gdal.Transformer(in_ds,dst_ds,[]) sucess,xyz=trans.TransformPoint(False,0,0) x,y,z = map(int,xyz) data = in_ds.GetRasterBand(1).ReadAsArray() out_band.WriteArray(data,x,y) dst_ds.FlushCache() for i in range(dst_ds.RasterCount): i = i + 1 dst_ds.GetRasterBand(i).ComputeStatistics(False) dst_ds.BuildOverviews('average', [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]) out_band.FlushCache() dst_ds = None dst_ds = None in_ds=None out_band=None return dstPath def xls (filePath): with open(filePath, 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') coord=[] for (row) in(spamreader): a = row[0].split(',') #as row is list containing all column element as single string eg: ['col,col2,co3,...,coln'], hence row[0] means first element of list. tuple=(a[1], a[2]) coord.append(tuple) return coord def open_File_1(path): if path is None: filePath = str(input("file path")) else: filePath=path datasource = ogr.Open(filePath,0) return datasource def route(finalroute): spatialReference = osgeo.osr.SpatialReference() spatialReference.SetWellKnownGeogCS("WGS84") driver = osgeo.ogr.GetDriverByName("ESRI Shapefile") folderLocation, folderName = creating_directory () name = input("enter name") dstPath = os.path.join(folderLocation, "%s.shp" % name) dstFile = driver.CreateDataSource("%s" % dstPath) dstLayer = dstFile.CreateLayer("resulting layer", spatialReference) out_row = ogr.Feature(dstLayer.GetLayerDefn()) multipoint = ogr.Geometry(ogr.wkbMultiPoint) for k in range(len(finalroute)): print (finalroute[k].GetGeometryRef()) multipoint.AddGeometry(finalroute[k].GetGeometryRef()) poly = {} for i in range(len(finalroute)): poly[i] = multipoint.GetGeometryRef(i) line = {} line[0] = poly[0] for i in range(len(finalroute) - 1): line[i + 1] = poly[i + 1].Union(line[i]) out_row.SetGeometry(line[len(finalroute) - 1]) dstLayer.CreateFeature(out_row) dstFile.Destroy() def create_a_point(w,filePath) : coord=xls(filePath) long= (coord[w][0]) lat=coord[w][1] point = ogr.Geometry(ogr.wkbPoint) point.AddPoint(float(long),float(lat)) return point.ExportToWkt() def creating_directory(): folderName = input("Enter Folder Name") folderPath = input("Where you want to save folder ") path = folderPath + '\\' + folderName print (path) if os.path.exists("%s" % path): shutil.rmtree("%s" % path) os.mkdir("%s" % path) return (path, folderName) def csvtoshp (filePath): spatialReference = osgeo.osr.SpatialReference() spatialReference.SetWellKnownGeogCS("WGS84") driver = osgeo.ogr.GetDriverByName("ESRI Shapefile") print ("Creating Directory For ShapeFile ") folderLocation, folderName = creating_directory() name = input("enter shape file name") dstPath = os.path.join(folderLocation, "%s.shp" % name) dstFile = driver.CreateDataSource("%s" % dstPath) dstLayer = dstFile.CreateLayer("layer", spatialReference) numField = input("Enter the required number of fields\ attributes in a layer other than FieldID, Longitude, Latitude") fieldDef = osgeo.ogr.FieldDefn("FieldID", osgeo.ogr.OFTInteger) fieldDef.SetWidth(10) dstLayer.CreateField(fieldDef) fieldDef = osgeo.ogr.FieldDefn("Longitude", osgeo.ogr.OFTReal) fieldDef.SetWidth(30) dstLayer.CreateField(fieldDef) fieldDef = osgeo.ogr.FieldDefn("Latitude", osgeo.ogr.OFTReal) fieldDef.SetWidth(30) dstLayer.CreateField(fieldDef) fieldDef = osgeo.ogr.FieldDefn("WEIGHT", osgeo.ogr.OFTReal) fieldDef.SetWidth(30) dstLayer.CreateField(fieldDef) list = {"Integer": 1, "IntegerList": 2, "Real": 3, "RealList": 4, "String": 5, "StringList": 6, "WideString": 7, "WideStringList": 8, "Binary": 9, "Date": 10, "Time": 11, "DateTime": 12, "Integer64": 13, "Integer64List": 14} print (list) fieldList = [] for i in range(numField): ftype = input("please enter number corresponding to the type of field you want to make (integer value)") if ftype == 1: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTInteger) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 2: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTIntegerList) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 3: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTReal) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 4: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTRealList) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 5: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTString) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 6: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTStringList) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 7: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTWideString) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 8: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTWideStringList) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 9: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTBinary) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 10: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTDate) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 11: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTTime) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 12: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTDateTime) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 13: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTInteger64) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) elif ftype == 14: fieldName = str(input("enter feild name")) fieldDef = osgeo.ogr.FieldDefn("%s" % fieldName, osgeo.ogr.OFTInteger64List) width = int(input("Enter field width")) fieldDef.SetWidth(width) dstLayer.CreateField(fieldDef) fieldList.append(fieldName) j = 0 num = input("enter number of point") for w in range(num+1): w+=1 j = j + 1 Q=create_a_point(w, filePath) point = ogr.CreateGeometryFromWkt(Q) print (w) feature = osgeo.ogr.Feature(dstLayer.GetLayerDefn()) feature.SetGeometry(point) feature.SetField("FieldID", j) feature.SetField("Longitude", point.GetX()) feature.SetField("Latitude", point.GetY()) feature.SetField("WEIGHT", 1) dstLayer.CreateFeature(feature) feature.Destroy() dstFile.Destroy() def haversine(pointA, pointB): if (type(pointA) != tuple) or (type(pointB) != tuple): raise TypeError("Only tuples are supported as arguments") lat1 = pointA[1] lon1 = pointA[0] lat2 = pointB[1] lon2 = pointB[0] # convert decimal degrees to radians lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 # Radius of earth in kilometers. Use 3956 for miles return c * r def open_File(): filePath = str(input("file path")) print ("Entered File Path is %s" % filePath) datasource = ogr.Open(filePath) return datasource def num_of_layers_in_file(source): datasource = source numLayers = datasource.GetLayerCount() print ("the number of Layers in the file on the entered file path is %d" % numLayers) return numLayers def creating_an_empty_shape_file(geom): spatialReference = osgeo.osr.SpatialReference() spatialReference.SetWellKnownGeogCS("WGS84") driver = osgeo.ogr.GetDriverByName("ESRI Shapefile") print ("Creating Directory For ShapeFile ") folderLocation, folderName = creating_directory() name = input("enter shape file name") dstPath = os.path.join(folderLocation, "%s.shp" % name) dstFile = driver.CreateDataSource("%s" % dstPath) dstLayer = dstFile.CreateLayer("layer", spatialReference) numField = input( "Enter the required number of fields\ attributes in a layer other than FieldID, Longitude, Latitude") fieldDef = osgeo.ogr.FieldDefn("FieldID", osgeo.ogr.OFTInteger) fieldDef.SetWidth(10) dstLayer.CreateField(fieldDef) print ("point geometry") for i in range(len(geom)): point = ogr.CreateGeometryFromWkt(geom[i]) feature = osgeo.ogr.Feature(dstLayer.GetLayerDefn()) feature.SetGeometry(point) feature.SetField("FieldID", i) dstLayer.CreateFeature(feature) feature.Destroy() dstFile.Destroy() return dstPath def creating_test_shape_file(centroid,count): q=[] spatialReference = osgeo.osr.SpatialReference() spatialReference.SetWellKnownGeogCS("WGS84") driver = osgeo.ogr.GetDriverByName("ESRI Shapefile") print ("Creating Directory For ShapeFile ") folderLocation, folderName = creating_directory() name = input("enter shape file name") dstPath = os.path.join(folderLocation, "%s.shp" % name) dstFile = driver.CreateDataSource("%s" % dstPath) dstLayer = dstFile.CreateLayer("layer", spatialReference) numField = input("Enter the required number of fields\ attributes in a layer other than FieldID, Longitude, Latitude") fieldDef = osgeo.ogr.FieldDefn("ROW", osgeo.ogr.OFTInteger64) fieldDef.SetWidth(50) dstLayer.CreateField(fieldDef) fieldDef = osgeo.ogr.FieldDefn("COLUMN", osgeo.ogr.OFTInteger64) fieldDef.SetWidth(50) dstLayer.CreateField(fieldDef) fieldDef = osgeo.ogr.FieldDefn("COUNT", osgeo.ogr.OFTInteger) fieldDef.SetWidth(50) dstLayer.CreateField(fieldDef) fieldDef = osgeo.ogr.FieldDefn("CENTROID", osgeo.ogr.OFTInteger) fieldDef.SetWidth(10) dstLayer.CreateField(fieldDef) for key, value in centroid.iteritems(): q.append(key) print ("point geometry") for i in range(len(q)): point = ogr.Geometry(ogr.wkbPoint) point.AddPoint(centroid[q[i]][0],centroid[q[i]][1]) feature = osgeo.ogr.Feature(dstLayer.GetLayerDefn()) feature.SetGeometry(point) feature.SetField("COLUMN", q[i][0]) feature.SetField("ROW", q[i][1]) feature.SetField("COUNT", count[q[i]]) dstLayer.CreateFeature(feature) feature.Destroy() dstFile.Destroy() return dstPath def making_one_from_all(file_path): list=[] os.chdir(file_path) file = glob.glob('*.shp') for i in range(len(file)): datasource = open_File_1(file[i]) numLayers = num_of_layers_in_file(datasource) for layerIndex in range(numLayers): layer = datasource.GetLayerByIndex(layerIndex) numFeatures = num_of_features_in_layer(datasource, numLayers) for featureIndex in range(numFeatures): print ("feature number %d" % featureIndex) feature = layer.GetFeature(featureIndex) geometry = feature.GetGeometryRef().ExportToWkt() list.append(geometry) path=creating_an_empty_shape_file(list) return
<filename>python/RLrecon/environments/fixed_environment.py from __future__ import print_function import numpy as np from environment import BaseEnvironment from RLrecon import math_utils class FixedEnvironmentV0(BaseEnvironment): def __init__(self, world_bounding_box, random_reset=True, radius=7.0, height=3.0, angle_amount=math_utils.degrees_to_radians(180. / 8.), yaw_amount=math_utils.degrees_to_radians(180. / 8.), **kwargs): """Initialize environment. Args: world_bounding_box (BoundingBox): Overall bounding box of the world to restrict motion. engine (BaseEngine): Simulation engine (i.e. Unreal Engine wrapper). mapper: Occupancy mapper (i.e. OctomapExt interface). clear_size (float): Size of bounding box to clear in the occupancy map on reset. random_reset (bool): Use random pose when resetting. radius (float): Radius of orbit. height (float): Height of orbit. yaw_amount (float): Scale of yaw rotations. angle_amount (float): Scale of orbital motion. use_ros (bool): Whether to use ROS and publish on some topics. ros_pose_topic (str): If ROS is used publish agent poses on this topic. ros_world_frame (str): If ROS is used this is the id of the world frame. """ self._random_reset = random_reset self._radius = radius self._height = height self._angle_amount = angle_amount self._yaw_amount = yaw_amount index1_range = 6 index2_range = 1 def _action_function(index1, index2, pose): new_theta = 2 * np.pi * index1 / float(index1_range) new_location = self._get_orbit_location(new_theta) new_yaw = new_theta + np.pi new_yaw += (index2 - index2_range / 2) * np.pi / 2. new_orientation_rpy = np.array([0, 0, new_yaw]) # print("new_theta:", new_theta) # print("new_yaw:", new_yaw) new_pose = self.Pose(new_location, new_orientation_rpy) valid = True return valid, new_pose action_list = [] update_map_flags = [] action_rewards = [] for index1 in xrange(index1_range): for index2 in xrange(index2_range): # Need to create a new scope here to capture index1, index2 by value def create_lambda(idx1, idx2): def lambda_fn(pose): return _action_function(idx1, idx2, pose) return lambda_fn action_list.append(create_lambda(index1, index2)) update_map_flags.append(True) action_rewards.append(-100.0) self._obs_level = 2 self._obs_size_x = 8 self._obs_size_y = self._obs_size_x self._obs_size_z = self._obs_size_x super(FixedEnvironmentV0, self).__init__( world_bounding_box, action_list, update_map_flags=update_map_flags, action_rewards=action_rewards, terminal_score_threshold=0.6, **kwargs) def _get_orbit_angle(self, pose): theta = np.arctan2(pose.location()[1], pose.location()[0]) return theta def _get_orbit_location(self, theta): x = self._radius * np.cos(theta) y = self._radius * np.sin(theta) z = self._height location = np.array([x, y, z]) return location def get_observation_shapes(self): return [(self.get_num_of_actions(),)] def _get_observation(self, pose): return [np.array(self._action_counter)] # location = self.get_location() # # orientation_rpy = self.get_orientation_rpy() # orientation_quat = self.get_orientation_quat() # # return [location, orientation_quat, occupancies_3d] # # return [location, orientation_quat, grid_3d] # previous_state_orientation_quat = math_utils.convert_rpy_to_quat(self._previous_state.orientation_rpy()) # orientation_quat *= np.sign(orientation_quat[3]) # previous_state_orientation_quat *= np.sign(previous_state_orientation_quat[3]) # return [location, orientation_quat, self._previous_state.location(), previous_state_orientation_quat] def perform_action(self, action_index, pose=None): observation, reward, terminal, info = super(FixedEnvironmentV0, self).perform_action(action_index, pose) self._action_counter[action_index] += 0.1 # self._action_counter[action_index] = np.min([self._action_counter[action_index], 1]) print("self._action_counter:", self._action_counter) return observation, reward, terminal, info def reset(self, **kwargs): """Resets the environment. Orbit angle is set to zero or randomly initialized.""" # if pose is None: # pose = self.get_pose() # theta = self._get_orbit_angle(pose) # pose = self._get_orbit_pose(theta) if self._random_reset: theta = 2 * np.pi * np.random.rand() if np.random.rand() < 0.25: yaw = 2 * np.pi * np.random.rand() else: d_yaw = np.pi / 4 * (np.random.rand() - 0.5) yaw = theta + np.pi + d_yaw else: theta = 0 yaw = theta + np.pi location = self._get_orbit_location(theta) roll = 0 pitch = 0 orientation_rpy = np.array([roll, pitch, yaw]) pose = self.Pose(location, orientation_rpy) self._action_counter = np.zeros((self.get_num_of_actions())) if self._random_reset: action_index = np.random.randint(0, self.get_num_of_actions()) else: action_index = 0 _, pose = self._action_list[action_index](pose) # pose = self.simulate_action_on_pose(pose, action_index) return super(FixedEnvironmentV0, self).reset(pose, **kwargs) def is_action_allowed_on_pose(self, pose, action_index): return True class FixedEnvironmentV1(BaseEnvironment): def __init__(self, world_bounding_box, random_reset=True, radius=7.0, height=3.0, angle_amount=math_utils.degrees_to_radians(180. / 8.), yaw_amount=math_utils.degrees_to_radians(180. / 8.), **kwargs): """Initialize environment. Args: world_bounding_box (BoundingBox): Overall bounding box of the world to restrict motion. engine (BaseEngine): Simulation engine (i.e. Unreal Engine wrapper). mapper: Occupancy mapper (i.e. OctomapExt interface). clear_size (float): Size of bounding box to clear in the occupancy map on reset. random_reset (bool): Use random pose when resetting. radius (float): Radius of orbit. height (float): Height of orbit. yaw_amount (float): Scale of yaw rotations. angle_amount (float): Scale of orbital motion. use_ros (bool): Whether to use ROS and publish on some topics. ros_pose_topic (str): If ROS is used publish agent poses on this topic. ros_world_frame (str): If ROS is used this is the id of the world frame. """ self._random_reset = random_reset self._radius = radius self._height = height self._angle_amount = angle_amount self._yaw_amount = yaw_amount index1_range = 6 index2_range = 1 def _action_function(index1, index2, pose): new_theta = 2 * np.pi * index1 / float(index1_range) new_location = self._get_orbit_location(new_theta) new_yaw = new_theta + np.pi new_yaw += (index2 - index2_range / 2) * np.pi / 2. new_orientation_rpy = np.array([0, 0, new_yaw]) # print("new_theta:", new_theta) # print("new_yaw:", new_yaw) new_pose = self.Pose(new_location, new_orientation_rpy) valid = True return valid, new_pose action_list = [] update_map_flags = [] action_rewards = [] for index1 in xrange(index1_range): for index2 in xrange(index2_range): # Need to create a new scope here to capture index1, index2 by value def create_lambda(idx1, idx2): def lambda_fn(pose): return _action_function(idx1, idx2, pose) return lambda_fn action_list.append(create_lambda(index1, index2)) update_map_flags.append(True) action_rewards.append(-100.0) self._obs_level = 2 self._obs_size_x = 8 self._obs_size_y = self._obs_size_x self._obs_size_z = self._obs_size_x super(FixedEnvironmentV1, self).__init__( world_bounding_box, action_list, update_map_flags=update_map_flags, action_rewards=action_rewards, terminal_score_threshold=0.6, **kwargs) def _get_orbit_angle(self, pose): theta = np.arctan2(pose.location()[1], pose.location()[0]) return theta def _get_orbit_location(self, theta): x = self._radius * np.cos(theta) y = self._radius * np.sin(theta) z = self._height location = np.array([x, y, z]) return location def get_observation_shapes(self): return [ (self._obs_size_x, self._obs_size_y, self._obs_size_z, 2) ] def _get_observation(self, pose): level = self._obs_level size_x = self._obs_size_x size_y = self._obs_size_y size_z = self._obs_size_z # center = self.get_location() # orientation_rpy = self.get_orientation_rpy() center = np.array([0, 0, 0]) orientation_rpy = np.array([0, 0, 0]) # We query a subvolume of the occupancy map so that z-axis is aligned with gravity (roll = pitch = 0) # query_orientation_rpy = np.array([0, 0, orientation_rpy[2]]) query_orientation_rpy = np.array([0, orientation_rpy[1], orientation_rpy[2]]) # TODO: Should be exposed in environment res = self._mapper.perform_query_subvolume_rpy( center, query_orientation_rpy, level, size_x, size_y, size_z) occupancies = np.asarray(res.occupancies, dtype=np.float32) occupancies_3d = np.reshape(occupancies, (size_x, size_y, size_z)) observation_certainties = np.asarray(res.observation_certainties, dtype=np.float32) observation_certainties_3d = np.reshape(observation_certainties, (size_x, size_y, size_z)) grid_3d = np.stack([occupancies_3d, observation_certainties_3d], axis=-1) return [np.array(grid_3d)] # location = self.get_location() # # orientation_rpy = self.get_orientation_rpy() # orientation_quat = self.get_orientation_quat() # # return [location, orientation_quat, occupancies_3d] # # return [location, orientation_quat, grid_3d] # previous_state_orientation_quat = math_utils.convert_rpy_to_quat(self._previous_state.orientation_rpy()) # orientation_quat *= np.sign(orientation_quat[3]) # previous_state_orientation_quat *= np.sign(previous_state_orientation_quat[3]) # return [location, orientation_quat, self._previous_state.location(), previous_state_orientation_quat] def reset(self, **kwargs): """Resets the environment. Orbit angle is set to zero or randomly initialized.""" # if pose is None: # pose = self.get_pose() # theta = self._get_orbit_angle(pose) # pose = self._get_orbit_pose(theta) if self._random_reset: theta = 2 * np.pi * np.random.rand() if np.random.rand() < 0.25: yaw = 2 * np.pi * np.random.rand() else: d_yaw = np.pi / 4 * (np.random.rand() - 0.5) yaw = theta + np.pi + d_yaw else: theta = 0 yaw = theta + np.pi location = self._get_orbit_location(theta) roll = 0 pitch = 0 orientation_rpy = np.array([roll, pitch, yaw]) pose = self.Pose(location, orientation_rpy) if self._random_reset: action_index = np.random.randint(0, self.get_num_of_actions()) else: action_index = 0 _, pose = self._action_list[action_index](pose) # pose = self.simulate_action_on_pose(pose, action_index) print("action_index:", action_index) print("pose:", pose) return super(FixedEnvironmentV1, self).reset(pose, **kwargs) def is_action_allowed_on_pose(self, pose, action_index): return True class FixedEnvironmentV2(BaseEnvironment): def __init__(self, world_bounding_box, random_reset=True, radius=7.0, height=3.0, **kwargs): """Initialize environment. Args: world_bounding_box (BoundingBox): Overall bounding box of the world to restrict motion. engine (BaseEngine): Simulation engine (i.e. Unreal Engine wrapper). mapper: Occupancy mapper (i.e. OctomapExt interface). clear_size (float): Size of bounding box to clear in the occupancy map on reset. random_reset (bool): Use random pose when resetting. radius (float): Radius of orbit. height (float): Height of orbit. yaw_amount (float): Scale of yaw rotations. angle_amount (float): Scale of orbital motion. use_ros (bool): Whether to use ROS and publish on some topics. ros_pose_topic (str): If ROS is used publish agent poses on this topic. ros_world_frame (str): If ROS is used this is the id of the world frame. """ self._random_reset = random_reset self._radius = radius self._height = height index1_range = 6 index2_range = 3 def _action_function(index1, index2): new_theta = 2 * np.pi * index1 / float(index1_range) new_location = self._get_orbit_location(new_theta) new_yaw = new_theta + np.pi new_yaw += (index2 - index2_range / 2) * np.pi / 2. new_orientation_rpy = np.array([0, 0, new_yaw]) # print("new_theta:", new_theta) # print("new_yaw:", new_yaw) new_pose = self.Pose(new_location, new_orientation_rpy) valid = True
# base functions originally from https://github.com/pclucas14/pixel-cnn-pp/blob/master/utils.py#L34 import pdb import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn.utils import weight_norm as wn import numpy as np from IPython import embed def to_scalar(arr): if type(arr) == list: return [x.cpu().data.tolist() for x in arr] else: return arr.cpu().data.tolist() def get_cuts(length,window_size): if window_size<length: st_pts = list(np.arange(0,length,window_size,dtype=np.int)) end_pts = st_pts[1:] if end_pts[-1] != length: end_pts.append(length) else: print("cutting start") st_pts = st_pts[:-1] return zip(st_pts, end_pts) else: return zip([0], [length]) def concat_elu(x): """ like concatenated ReLU (http://arxiv.org/abs/1603.05201), but then with ELU """ # Pytorch ordering axis = len(x.size()) - 3 return F.elu(torch.cat([x, -x], dim=axis)) def log_sum_exp(x): """ numerically stable log_sum_exp implementation that prevents overflow """ # TF ordering axis = len(x.size()) - 1 m, _ = torch.max(x, dim=axis) m2, _ = torch.max(x, dim=axis, keepdim=True) return m + torch.log(torch.sum(torch.exp(x - m2), dim=axis)) def log_prob_from_logits(x): """ numerically stable log_softmax implementation that prevents overflow """ # TF ordering axis = len(x.size()) - 1 m, _ = torch.max(x, dim=axis, keepdim=True) return x - m - torch.log(torch.sum(torch.exp(x - m), dim=axis, keepdim=True)) def discretized_mix_logistic_loss(prediction, target, nr_mix=10, use_cuda=False): """ log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to [-1,1] interval """ # Pytorch ordering l = prediction x = target x = x.permute(0, 2, 3, 1) l = l.permute(0, 2, 3, 1) xs = [int(y) for y in x.size()] ls = [int(y) for y in l.size()] # here and below: unpacking the params of the mixture of logistics #nr_mix = int(ls[-1] / 10) # l is prediction logit_probs = l[:, :, :, :nr_mix] l = l[:, :, :, nr_mix:].contiguous().view(xs + [nr_mix*2]) # 3--changed to 1 for mean, scale, coef means = l[:, :, :, :, :nr_mix] # log_scales = torch.max(l[:, :, :, :, nr_mix:2 * nr_mix], -7.) log_scales = torch.clamp(l[:, :, :, :, nr_mix:2 * nr_mix], min=-7.) #coeffs = F.tanh(l[:, :, :, :, 2 * nr_mix:3 * nr_mix]) # here and below: getting the means and adjusting them based on preceding # sub-pixels x = x.contiguous() if use_cuda: x = x.unsqueeze(-1) + Variable(torch.zeros(xs + [nr_mix]).cuda(), requires_grad=False) else: x = x.unsqueeze(-1) + Variable(torch.zeros(xs + [nr_mix]), requires_grad=False) # ugggghhh # m2 = (means[:, :, :, 1, :] + coeffs[:, :, :, 0, :] # * x[:, :, :, 0, :]).view(xs[0], xs[1], xs[2], 1, nr_mix) # m3 = (means[:, :, :, 2, :] + coeffs[:, :, :, 1, :] * x[:, :, :, 0, :] + # coeffs[:, :, :, 2, :] * x[:, :, :, 1, :]).view(xs[0], xs[1], xs[2], 1, nr_mix) # # means = torch.cat((means[:, :, :, 0, :].unsqueeze(3), m2, m3), dim=3) centered_x = x - means inv_stdv = torch.exp(-log_scales) plus_in = inv_stdv * (centered_x + 1. / 255.) cdf_plus = F.sigmoid(plus_in) min_in = inv_stdv * (centered_x - 1. / 255.) cdf_min = F.sigmoid(min_in) # log probability for edge case of 0 (before scaling) log_cdf_plus = plus_in - F.softplus(plus_in) # log probability for edge case of 255 (before scaling) log_one_minus_cdf_min = -F.softplus(min_in) cdf_delta = cdf_plus - cdf_min # probability for all other cases mid_in = inv_stdv * centered_x # log probability in the center of the bin, to be used in extreme cases # (not actually used in our code) log_pdf_mid = mid_in - log_scales - 2. * F.softplus(mid_in) # now select the right output: left edge case, right edge case, normal # case, extremely low prob case (doesn't actually happen for us) # this is what we are really doing, but using the robust version below for extreme cases in other applications and to avoid NaN issue with tf.select() # log_probs = tf.select(x < -0.999, log_cdf_plus, tf.select(x > 0.999, log_one_minus_cdf_min, tf.log(cdf_delta))) # robust version, that still works if probabilities are below 1e-5 (which never happens in our code) # tensorflow backpropagates through tf.select() by multiplying with zero instead of selecting: this requires use to use some ugly tricks to avoid potential NaNs # the 1e-12 in tf.maximum(cdf_delta, 1e-12) is never actually used as output, it's purely there to get around the tf.select() gradient issue # if the probability on a sub-pixel is below 1e-5, we use an approximation # based on the assumption that the log-density is constant in the bin of # the observed sub-pixel value inner_inner_cond = (cdf_delta > 1e-5).float() inner_inner_out = inner_inner_cond * torch.log(torch.clamp(cdf_delta, min=1e-12)) + (1. - inner_inner_cond) * (log_pdf_mid - np.log(127.5)) inner_cond = (x > 0.999).float() inner_out = inner_cond * log_one_minus_cdf_min + (1. - inner_cond) * inner_inner_out cond = (x < -0.999).float() log_probs = cond * log_cdf_plus + (1. - cond) * inner_out log_probs = torch.sum(log_probs, dim=3) + log_prob_from_logits(logit_probs) lse = log_sum_exp(log_probs) # hacky hack mask to weight cars and frogs masked = (target[:,0,:,:]>-.98).float()*lse out = lse+masked return -out.mean() def discretized_mix_logistic_loss_1d(x, l, use_cuda=False): # Pytorch ordering x = x.permute(0, 2, 3, 1) l = l.permute(0, 2, 3, 1) xs = [int(y) for y in x.size()] ls = [int(y) for y in l.size()] """ log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to [-1,1] interval """ # Pytorch ordering l = prediction x = target embed() x = x.permute(0, 2, 3, 1) l = l.permute(0, 2, 3, 1) xs = [int(y) for y in x.size()] ls = [int(y) for y in l.size()] # here and below: unpacking the params of the mixture of logistics nr_mix = int(ls[-1] / 3) logit_probs = l[:, :, :, :nr_mix] l = l[:, :, :, nr_mix:].contiguous().view(xs + [nr_mix * 2]) # 2 for mean, scale means = l[:, :, :, :, :nr_mix] log_scales = torch.clamp(l[:, :, :, :, nr_mix:2 * nr_mix], min=-7.) # here and below: getting the means and adjusting them based on preceding # sub-pixels x = x.contiguous() if use_cuda: x = x.unsqueeze(-1) + Variable(torch.zeros(xs + [nr_mix]).cuda(), requires_grad=False) else: x = x.unsqueeze(-1) + Variable(torch.zeros(xs + [nr_mix]), requires_grad=False) # means = torch.cat((means[:, :, :, 0, :].unsqueeze(3), m2, m3), dim=3) centered_x = x - means inv_stdv = torch.exp(-log_scales) plus_in = inv_stdv * (centered_x + 1. / 255.) cdf_plus = F.sigmoid(plus_in) min_in = inv_stdv * (centered_x - 1. / 255.) cdf_min = F.sigmoid(min_in) # log probability for edge case of 0 (before scaling) log_cdf_plus = plus_in - F.softplus(plus_in) # log probability for edge case of 255 (before scaling) log_one_minus_cdf_min = -F.softplus(min_in) cdf_delta = cdf_plus - cdf_min # probability for all other cases mid_in = inv_stdv * centered_x # log probability in the center of the bin, to be used in extreme cases # (not actually used in our code) log_pdf_mid = mid_in - log_scales - 2. * F.softplus(mid_in) inner_inner_cond = (cdf_delta > 1e-5).float() inner_inner_out = inner_inner_cond * torch.log(torch.clamp(cdf_delta, min=1e-12)) + (1. - inner_inner_cond) * (log_pdf_mid - np.log(127.5)) inner_cond = (x > 0.999).float() inner_out = inner_cond * log_one_minus_cdf_min + (1. - inner_cond) * inner_inner_out cond = (x < -0.999).float() log_probs = cond * log_cdf_plus + (1. - cond) * inner_out log_probs = torch.sum(log_probs, dim=3) + log_prob_from_logits(logit_probs) return -torch.sum(log_sum_exp(log_probs)) def to_one_hot(tensor, n, fill_with=1.): # we perform one hot encore with respect to the last axis one_hot = torch.FloatTensor(tensor.size() + (n,)).zero_() if tensor.is_cuda : one_hot = one_hot.cuda() one_hot.scatter_(len(tensor.size()), tensor.unsqueeze(-1), fill_with) return Variable(one_hot) def sample_from_discretized_mix_logistic_1d(l, nr_mix): # Pytorch ordering l = l.permute(0, 2, 3, 1) ls = [int(y) for y in l.size()] xs = ls[:-1] + [1] #[3] # unpack parameters logit_probs = l[:, :, :, :nr_mix] l = l[:, :, :, nr_mix:].contiguous().view(xs + [nr_mix * 2]) # for mean, scale # sample mixture indicator from softmax temp = torch.FloatTensor(logit_probs.size()) if l.is_cuda : temp = temp.cuda() temp.uniform_(1e-5, 1. - 1e-5) temp = logit_probs.data - torch.log(- torch.log(temp)) _, argmax = temp.max(dim=3) one_hot = to_one_hot(argmax, nr_mix) sel = one_hot.view(xs[:-1] + [1, nr_mix]) # select logistic parameters means = torch.sum(l[:, :, :, :, :nr_mix] * sel, dim=4) log_scales = torch.clamp(torch.sum( l[:, :, :, :, nr_mix:2 * nr_mix] * sel, dim=4), min=-7.) u = torch.FloatTensor(means.size()) if l.is_cuda : u = u.cuda() u.uniform_(1e-5, 1. - 1e-5) u = Variable(u) x = means + torch.exp(log_scales) * (torch.log(u) - torch.log(1.
<reponame>alexmerkel/ytarchiver #!/usr/bin/env python3 ''' ytapost - youtube archiver post processing steps ''' import os import sys import subprocess import argparse import shutil import sqlite3 import json import time from datetime import datetime, timezone from pycountry import languages import ytacommon as yta import ytameta import ytafix # --------------------------------------------------------------------------- # def postprocess(args): '''Postprocess a video file or a directory of video files :param args: The command line arguments given by the user :type args: list ''' #Get files files = [] parser = argparse.ArgumentParser(prog="ytapost", description="Perform the postprocessing steps on a downloaded video file") parser.add_argument("-c", "--check", action="store_const", dest="check", const=True, default=False, help="Check file integrity") parser.add_argument("-r", "--replace", action="store_const", dest="replace", const=True, default=False, help="Replace existing file") parser.add_argument("PATH", help="The file or the directory to work with") parser.add_argument("LANG", nargs='?', default="", help="The video language") args = parser.parse_args(args) path = os.path.normpath(os.path.abspath(args.PATH)) if os.path.isfile(path): dirPath = os.path.dirname(path) if path.lower().endswith((".m4v", ".mp4")): files.append(path) else: parser.error("Unsupported file format, only .mp4 and .m4v are supported") elif os.path.isdir(path): dirPath = path allf = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] for f in allf: if f.lower().endswith((".m4v", ".mp4")): files.append(os.path.join(path, f)) if not files: parser.error("No supported files in directory, only .mp4 and .m4v are supported") #Connect to database try: dbFile = os.path.join(dirPath, "archive.db") dbCon = createOrConnectDB(dbFile) db = dbCon.cursor() except sqlite3.Error as e: print(e) return for f in files: processFile(f, args.LANG, db, args.check, args.replace) yta.closeDB(dbCon) # ########################################################################### # # --------------------------------------------------------------------------- # def processFile(name, subLang, db, check, replace): '''Process a file :param name: The video file name :type name: string :param subLang: The subtitle language identifier :type subLang: string :param db: Connection to the metadata database :type db: sqlite3.Cursor :param check: Whether to perform an integrity check and calc the checksum :type check: boolean :param replace: Whether to replace a video already in the archive database :type replace: boolean :raises: :class:``sqlite3.Error: Unable to write to database ''' videoFileComp = os.path.splitext(name) #Get language for ffmpeg lang = languages.get(alpha_2=subLang).alpha_3 #If subtitles, read and embed them subs = None tmpFile = videoFileComp[0] + "_tmp" + videoFileComp[1] if subLang: subFile = videoFileComp[0] + ".{}.vtt".format(subLang) try: #Read subtitle file with open(subFile, 'r') as f: subs = f.read() cmd = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "panic", "-i", name, "-sub_charenc", "UTF-8", "-i", subFile, "-map", "0:v", "-map", "0:a", "-c", "copy", "-map", "1", "-c:s:0", "mov_text", "-metadata:s:s:0", "language=" + lang, "-metadata:s:a:0", "language=" + lang, tmpFile] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) process.wait() shutil.move(tmpFile, name) os.remove(subFile) except IOError: subs = None #If no subtitles added, change audio language at least if not subs: cmd = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "panic", "-i", name, "-map", "0:v", "-map", "0:a", "-c", "copy", "-metadata:s:a:0", "language=" + lang, tmpFile] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) process.wait() shutil.move(tmpFile, name) #Read description desc = None try: descFile = videoFileComp[0] + ".description" with open(descFile, 'r') as f: desc = f.read() os.remove(descFile) except IOError: pass #Read artist, title cmd = ["exiftool", "-api", "largefilesupport=1", "-m", "-Artist", name] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) process.wait() artist = process.stdout.read().decode("UTF-8").split(':', 1)[1].strip() cmd = ["exiftool", "-api", "largefilesupport=1", "-m", "-Title", name] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) process.wait() title = process.stdout.read().decode("UTF-8").split(':', 1)[1].strip() #Read image width hd, formatString, width, height = yta.readResolution(name) #Read date cmd = ["exiftool", "-api", "largefilesupport=1", "-m", "-ContentCreateDate", name] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) process.wait() r = process.stdout.read().decode("UTF-8").split(':', 1)[1].strip() dateTime = r[0:4] + ':' + r[4:6] + ':' + r[6:8] + " 00:00:00" date = r[0:4] + '-' + r[4:6] + '-' + r[6:8] oldName = os.path.basename(name) #Remove id from filename videoID = '' if oldName.startswith("ID") and '&' in oldName: [videoID, oldName] = oldName.split('&', 1) videoID = videoID[2:] #Download additional metadata timestamp = None duration = None tags = None apiDesc = None viewCount = None likeCount = None dislikeCount = None statisticsUpdated = None try: [timestamp, duration, tags, apiDesc, viewCount, likeCount, dislikeCount, statisticsUpdated] = ytameta.getMetadata(videoID) except yta.NoAPIKeyError: pass except OSError: print("ERROR: Unable to load metadata for {}".format(videoID)) if timestamp: dt = datetime.fromtimestamp(timestamp, tz=timezone.utc) dateTime = datetime.strftime(dt, "%Y:%m:%d %H:%M:%S+0") date = datetime.strftime(dt, "%Y-%m-%d") else: dateTime = r[0:4] + ':' + r[4:6] + ':' + r[6:8] + " 00:00:00+0" timestamp = datetime.timestamp(datetime.strptime(dateTime + "000", "%Y:%m:%d %H:%M:%S%z")) #Replace existing video if replace: try: dbfilename = db.execute("SELECT filename FROM videos WHERE youtubeID = ?;", (videoID,)).fetchone()[0] except (sqlite3.Error, IndexError): sys.exit("ERROR: Unable to replace video with ID \"{}\"".format(videoID)) dbfilename = os.path.join(os.path.dirname(name), dbfilename) replaceFilepath = dbfilename + ".bak" try: os.rename(dbfilename, replaceFilepath) except OSError: print("WARNING: File to replace not found") #Add date to file name (oldName, ext) = os.path.splitext(oldName) fileName = "{} {}{}".format(date, oldName, ext) #Check if file name already exists i = 1 while checkFilename(fileName, db, replace, videoID): i += 1 fileName = "{} {} {}{}".format(date, oldName, i, ext) #Rename file newName = os.path.join(os.path.dirname(name), fileName) os.rename(name, newName) #Set additional metadata cmd = ["exiftool", "-api", "largefilesupport=1", "-m", "-overwrite_original", "-ContentCreateDate='{}'".format(dateTime), "-Comment={}".format('YoutubeID: ' + videoID), "-Encoder=", newName] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) process.wait() cmd = ["exiftool", "-api", "largefilesupport=1", "-m", "--printConv", "-overwrite_original", "-HDVideo={}".format(hd), newName] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) process.wait() #Use description from API if available if apiDesc: desc = apiDesc config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "exiftool.config") cmd = ["exiftool", "-config", config, "-api", "largefilesupport=1", "-overwrite_original", "-ec", "-Description={}".format(desc), newName] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) process.wait() #Get chapter information chapters = yta.extractChapters(desc) #Check if fix required artist, title = ytafix.fixVideo(newName, videoID, fileArtist=artist) #Calculate checksum checksum = yta.calcSHA(newName) #Get filesize filesize = os.path.getsize(newName) #Check file integrity if check: cmd = ["ffmpeg", "-v", "error", "-i", newName, "-f", "null", "-"] out, _ = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate() if out: print("ERROR: File corrupt! SHA256: " + checksum) else: print("File check passed, SHA256: " + checksum) #Download thumbnail url = "https://i.ytimg.com/vi/{}/maxresdefault.jpg".format(videoID) try: [thumbData, thumbFormat] = yta.loadImage(url) except OSError: url = "https://i.ytimg.com/vi/{}/hqdefault.jpg".format(videoID) try: print("WARNING: Unable to download highres thumbnail for {}, getting lower res".format(videoID)) [thumbData, thumbFormat] = yta.loadImage(url) except OSError: print("ERROR: Unable to download thumbnail for {}".format(videoID)) thumbData = None thumbFormat = None #Save to database saveToDB(db, replace, title, artist, date, timestamp, desc, videoID, subs, fileName, checksum, thumbData, thumbFormat, duration, tags, formatString, width, height, subLang, viewCount, likeCount, dislikeCount, statisticsUpdated, chapters, filesize) #Remove replaced file: if replace: try: os.remove(replaceFilepath) except OSError: pass # ########################################################################### # # --------------------------------------------------------------------------- # def saveToDB(db, replace, name, artist, date, timestamp, desc, youtubeID, subs, filename, checksum, thumbData, thumbFormat, duration, tags, res, width, height, lang, viewCount, likeCount, dislikeCount, statisticsUpdated, chapters, filesize): '''Write info to database :param db: Connection to the database :type db: sqlite3.Cursor :param replace: Whether to replace a video already in the archive database :type replace: boolean :param name: The video title :type name: string :param artist: The creators name :type artist: string :param date: The release date in the format YYYY-MM-DD :type date: string :param timestamp: The unix timestamp of the video release :type timestamp: integer :param desc: The video description :type desc: string :param youtubeID: The youtube ID :type youtubeID: string :param subs: The subtitles :type subs: string :param filename: The name of the video file :type filename: string :param checksum: A sha256 checksum of the file :type checksum: string :param thumbData: Raw thumbnail image data :type thumbData: bytes :param thumbFormat: Thumbnail MIME type :type thumbFormat: string :param duration: The duration of the video in seconds :type duration: integer :param tags: String with one tag per line :type tags: strings :param res: Resolution string :type res: strings :param width: The video image width :type width: integer :param height: The video image height :type height: integer :param lang: Video language code :type lang: strings :param viewCount: The view count :type viewCount: integer :param likeCount: The like count :type likeCount: integer :param dislikeCount: The dislike count :type dislikeCount: integer :param statisticsUpdated: Timestamp of the last statistics update, None if one of the other statistics items is None :type statisticsUpdated: integer :param chapters: String containing one chapter per line in the format: hh:mm:ss.sss Chapter Name :type chapters: string :param filesize: The size of the video file in bytes :type filesize: Integer :raises: :class:``sqlite3.Error: Unable to write to database ''' if replace: #Get current and old title + description r = db.execute("SELECT id,title,description,oldtitles,olddescriptions FROM videos WHERE youtubeID = ?;", (youtubeID,)) info = r.fetchone() del r dbID = info[0] currentTitle = info[1] currentDesc = info[2] #Check if title
"""Module for univariate densities (see also :mod:`ddl.independent`).""" from __future__ import division, print_function import logging import warnings import numpy as np import scipy.stats from sklearn.base import BaseEstimator from sklearn.exceptions import DataConversionWarning, NotFittedError from sklearn.utils.validation import check_array, check_is_fitted, check_random_state, column_or_1d from .base import BoundaryWarning, ScoreMixin # noinspection PyProtectedMember from .utils import (_DEFAULT_SUPPORT, check_X_in_interval, make_finite, make_interior, make_interior_probability, make_positive) logger = logging.getLogger(__name__) SCIPY_RV_NON_NEGATIVE = ['expon', 'chi'] SCIPY_RV_STRICLTY_POSITIVE = ['gamma', 'invgamma', 'chi2', 'lognorm'] SCIPY_RV_UNIT_SUPPORT = ['rv_histgoram', 'uniform', 'beta'] def _check_univariate_X(X, support, inverse=False): X = check_array(X, ensure_2d=True) # ensure_2d=True is default but just making explicit # Check that X is a column vector but first ravel because check_estimator passes # a matrix to fit if X.shape[1] > 1: warnings.warn(DataConversionWarning( 'Input should be column vector with shape (n, 1) but found matrix. Converting to ' 'column vector via `np.mean(X, axis=1).reshape((-1, 1))`. ' 'Ideally, this would raise an error but in order to pass the checks in ' '`sklearn.utils.check_estimator`, we convert the data rather than raise an error. ' )) X = np.mean(X, axis=1).reshape((-1, 1)) # Check that values are within support or range(inverse) if inverse: X = check_X_in_interval(X, np.array([0, 1])) else: X = check_X_in_interval(X, support) return np.array(X) class ScipyUnivariateDensity(BaseEstimator, ScoreMixin): """Density estimator via random variables defined in :mod:`scipy.stats`. A univariate density estimator that can fit any distribution defined in :mod:`scipy.stats`. This includes common distributions such as Gaussian, laplace, beta, gamma and log-normal distributions but also many other distributions as well. Note that this density estimator is strictly univariate and therefore expects the input data to be a single array with shape (n_samples, 1). Parameters ---------- scipy_rv : object or None, default=None Default random variable is a Gaussian (i.e. :class:`scipy.stats.norm`) if `scipy_rv=None`. Other examples include :class:`scipy.stats.gamma` or :class:`scipy.stats.beta`. scipy_fit_kwargs : dict or None, optional Keyword arguments as a dictionary for the fit function of the scipy random variable (e.g. ``dict(floc=0, fscale=1)`` to fix the location and scale parameters to 0 and 1 respectively). Defaults are different depending on `scipy_rv` parameter. For example for the `scipy.stats.beta` we set `floc=0` and `fscale=1`, i.e. fix the location and scale of the beta distribution. Attributes ---------- rv_ : object Frozen :mod:`scipy.stats` random variable object. Fitted parameters of distribution can be accessed via `args` property. See Also -------- scipy.stats """ def __init__(self, scipy_rv=None, scipy_fit_kwargs=None): self.scipy_rv = scipy_rv self.scipy_fit_kwargs = scipy_fit_kwargs def fit(self, X, y=None, **fit_params): """Fit estimator to X. Parameters ---------- X : array-like, shape (n_samples, 1) Training data, where `n_samples` is the number of samples. Note that the shape must have a second dimension of 1 since this is a univariate density estimator. y : None, default=None Not used in the fitting process but kept for compatibility. fit_params : dict, optional Optional extra fit parameters. Returns ------- self : estimator Returns the instance itself. """ def _check_scipy_kwargs(kwargs, _scipy_rv): if kwargs is None: if self._is_special(_scipy_rv, SCIPY_RV_UNIT_SUPPORT): return dict(floc=0, fscale=1) elif self._is_special(_scipy_rv, SCIPY_RV_NON_NEGATIVE + SCIPY_RV_STRICLTY_POSITIVE): return dict(floc=0) else: return {} elif isinstance(kwargs, dict): return kwargs else: raise ValueError('`scipy_fit_kwargs` should be either None or a `dict` object.') # Input validation scipy_rv = self._get_scipy_rv_or_default() scipy_fit_kwargs = _check_scipy_kwargs(self.scipy_fit_kwargs, scipy_rv) X = self._check_X(X) # MLE fit based on scipy implementation if scipy_rv.numargs == 0 and 'floc' in scipy_fit_kwargs and 'fscale' in scipy_fit_kwargs: params = (scipy_fit_kwargs['floc'], scipy_fit_kwargs['fscale']) else: try: params = scipy_rv.fit(X.ravel(), **scipy_fit_kwargs) except RuntimeError as e: warnings.warn('Unable to fit to data using scipy_rv so attempting to use default ' 'parameters for the distribution. Original error:\n%s' % str(e)) params = self._get_default_params(scipy_rv) except ValueError: # warnings.warn( # 'Trying to use fixed parameters instead. Original error:\n%s' % str(e)) # try to extract fixed parameters in a certain order params = [] for k in ['fa', 'f0', 'fb', 'f1', 'floc', 'fscale']: try: params.append(scipy_fit_kwargs.pop(k)) except KeyError: pass # Avoid degenerate case when scale = 0 if len(params) >= 2 and params[-1] == 0: params = list(params) if isinstance(X.dtype, np.floating): params[-1] = np.finfo(X.dtype).eps else: params[-1] = 1 # Integer types params = tuple(params) # Create "frozen" version of random variable so that parameters do not need to be # specified self.rv_ = scipy_rv(*params) # Check for a fit error in the domain of the parameters try: self.rv_.rvs(1) except ValueError: warnings.warn('Parameters discovered by fit are not in the domain of the ' 'parameters so attempting to use default parameters for the ' 'distribution.') self.rv_ = scipy_rv(*self._get_default_params(scipy_rv)) return self @classmethod def create_fitted(cls, scipy_rv_params=None, **kwargs): """Create fitted density. Parameters ---------- scipy_rv : object or None, default=None Default random variable is a Gaussian (i.e. :class:`scipy.stats.norm`) if `scipy_rv=None`. Other examples include :class:`scipy.stats.gamma` or :class:`scipy.stats.beta`. scipy_rv_params : dict, optional Parameters to pass to scipy_rv when creating frozen random variable. Default parameters have been set for various distributions. **kwargs Other parameters to pass to object constructor. Returns ------- fitted_density : Density Fitted density. """ density = cls(**kwargs) # Get default if scipy_rv=None scipy_rv = density._get_scipy_rv_or_default() # Fit scipy random variable if scipy_rv_params is None: try: params = cls._get_default_params(scipy_rv) except NotImplementedError: params = [] rv = scipy_rv(*params) else: rv = scipy_rv(**scipy_rv_params) density.rv_ = rv return density @classmethod def _get_default_params(cls, scipy_rv): if cls._is_special(scipy_rv, ['beta']): return [1, 1] elif cls._is_special(scipy_rv, ['uniform', 'norm', 'expon', 'lognorm']): return [] # Empty since no parameters needed else: raise NotImplementedError('The distribution given by the `scipy_rv = %s` does not ' 'have any associated default parameters.' % str(scipy_rv)) def sample(self, n_samples=1, random_state=None): """Generate random samples from this density/destructor. Parameters ---------- n_samples : int, default=1 Number of samples to generate. Defaults to 1. random_state : int, RandomState instance or None, optional (default=None) If int, `random_state` is the seed used by the random number generator; If :class:`~numpy.random.RandomState` instance, `random_state` is the random number generator; If None, the random number generator is the :class:`~numpy.random.RandomState` instance used by :mod:`numpy.random`. Returns ------- X : array, shape (n_samples, n_features) Randomly generated sample. """ self._check_is_fitted() rng = check_random_state(random_state) return np.array(self.rv_.rvs(size=n_samples, random_state=rng)).reshape((n_samples, 1)) def score_samples(self, X, y=None): """Compute log-likelihood (or log(det(Jacobian))) for each sample. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples is the number of samples and n_features is the number of features. y : None, default=None Not used but kept for compatibility. Returns ------- log_likelihood : array, shape (n_samples,) Log likelihood of each data point in X. """ self._check_is_fitted() X = self._check_X(X) return self.rv_.logpdf(X.ravel()).reshape((-1, 1)) def cdf(self, X, y=None): """[Placeholder]. Parameters ---------- X : y : Returns ------- obj : object """ self._check_is_fitted() X = self._check_X(X) return self.rv_.cdf(X.ravel()).reshape((-1, 1)) def inverse_cdf(self, X, y=None): """[Placeholder]. Parameters ---------- X : y : Returns ------- obj : object """ self._check_is_fitted() X = self._check_X(X, inverse=True) return self.rv_.ppf(X.ravel()).reshape((-1, 1)) def get_support(self): """Get the support of this density (i.e. the positive density region). Returns ------- support : array-like, shape (2,) or shape (n_features, 2) If shape is (2, ), then ``support[0]`` is the minimum and ``support[1]`` is the maximum for all features. If shape is (`n_features`, 2), then each feature's support (which could be different for each feature) is given similar to the first case. """ # Assumes density is univariate try: self._check_is_fitted() except NotFittedError: # Get upper and lower bounds of support from scipy random variable properties if self.scipy_rv is None: default_rv = ScipyUnivariateDensity._get_default_scipy_rv() return np.array([[default_rv.a, default_rv.b]]) else: return np.array([[self.scipy_rv.a, self.scipy_rv.b]]) else: # Scale and shift if fitted try: loc = self.rv_.args[-2] except IndexError: try: loc = self.rv_.args[-1] except IndexError: loc = 0 scale = 1 else: scale = self.rv_.args[-1] if scale == 0: # Handle special degenerate case to avoid nans in domain scale += np.finfo(float).eps return loc + scale * np.array([[self.rv_.a, self.rv_.b]]) def _check_X(self, X, inverse=False): # Check that X is univariate or warn otherwise X = _check_univariate_X(X, self.get_support(), inverse=inverse) scipy_rv = self._get_scipy_rv_or_default() # Move away from support/domain boundaries if necessary if inverse and (np.any(X <= 0) or np.any(X >= 1)): warnings.warn(BoundaryWarning( 'Some probability values (input to inverse functions) are either 0 or 1. Bounding ' 'values away from 0 or 1 to avoid infinities in output. For example, the inverse ' 'cdf of a Gaussian at 0 will yield `-np.inf`.')) X
<gh_stars>10-100 # Author: <NAME>, Ph.D. candidate # Department of Civil and Systems Engineering, Johns Hopkins University # Last update: March 25, 2021 ####################################################################################################################### ####################################################################################################################### # Grassmannian Diffusion Maps PCE surrogates # ####################################################################################################################### ####################################################################################################################### # Import all necessary libraries from random import randrange import numpy as np import math from mpl_toolkits.mplot3d import Axes3D from UQpy.Distributions import Normal, Uniform, JointInd from sklearn.model_selection import train_test_split from UQpy.Surrogates import * from UQpy.SampleMethods import LHS from scipy.integrate import odeint from skopt.space import Real, Categorical, Integer from skopt.searchcv import BayesSearchCV # to install skopt run: $ pip install scikit-optimize import matplotlib.pyplot as plt from matplotlib import cm from sklearn.neighbors import NearestNeighbors from sklearn.cluster import KMeans import datafold.pcfold as pfold from datafold.dynfold import GeometricHarmonicsInterpolator as GHI import random import itertools as it import os, subprocess from matplotlib.ticker import MaxNLocator import time import sys sys.path.append('./data/') from DimensionReduction import Grassmann from DimensionReduction import DiffusionMaps from DiffusionEquation import diffusion from electric_potential import function from rand_cmap import rand_cmap from LoktaVoltera import LV ####################################################################################################################### # Step 1: Create dataset # ####################################################################################################################### # Provided ####################################################################################################################### # Step 2: Grassmannian Diffusion Maps # ####################################################################################################################### class GDMaps: """ Performs GDMaps for a given dataset. n_evecs must be greater than n_parsim """ def __init__(self, data, n_evecs, n_parsim, p, verbose=False): self.data = data self.n_evecs = n_evecs self.n_parsim = n_parsim self.p = p self.verbose = verbose def get(self): Gr = Grassmann(distance_method=Grassmann.grassmann_distance, kernel_method=Grassmann.projection_kernel, karcher_method=Grassmann.gradient_descent) Gr.manifold(p=self.p, samples=self.data) dfm = DiffusionMaps(alpha=0.5, n_evecs=self.n_evecs + 1, kernel_object=Gr, kernel_grassmann='prod') g, evals, evecs = dfm.mapping() # Parsimonious representation index, residuals = dfm.parsimonious(num_eigenvectors=self.n_evecs, visualization=False) coord = index[1:self.n_parsim + 1] g_k = g[:, coord] # g_k = g[:, 1:] # without parsimonious # coord = np.arange(1, g_k.shape[1]+1) # diffusion coordinates numbers print('Grassmann projection rank is: ', Gr.p) return g_k, coord, Gr, residuals, index, evals def plot_diff_coord(x, data, coord, labels): """ Plots the diffusion coordinates from the GDMaps. """ plt.rcParams.update({'font.size': 24}) nlabels = np.unique(labels).shape[0] cmap = rand_cmap(nlabels=nlabels, type='bright', first_color_black=False) comb1 = list(it.combinations(list(coord), 2)) comb2 = list(it.combinations([i for i in range(coord.shape[0])], 2)) if os.path.exists('figures'): command = ['rm', '-r', 'figures'] subprocess.run(command) command = ['mkdir', 'figures'] subprocess.run(command) for i in range(len(comb1)): plt.figure(figsize=(8, 6), constrained_layout=True) plt.scatter(data[:, comb2[i][0]], data[:, comb2[i][1]], s=30, c=labels, cmap=cmap) plt.xlabel(r'$\psi_{}$'.format(comb1[i][0]), fontsize=26) plt.ylabel(r'$\psi_{}$'.format(comb1[i][1]), fontsize=26) plt.grid(True) plt.savefig('figures/Psi_{},{}.png'.format(comb1[i][0], comb1[i][1]), bbox_inches='tight') # Plot first three plots if coord.shape[0] > 2: fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(22, 5), constrained_layout=True) for i in range(3): ax[i].scatter(data[:, comb2[i][0]], data[:, comb2[i][1]], s=30, c=labels, cmap=cmap) ax[i].set_xlabel(r'$\psi_{}$'.format(comb1[i][0]), fontsize=28) ax[i].set_ylabel(r'$\psi_{}$'.format(comb1[i][1]), fontsize=28) ax[i].grid('True') ax[i].ticklabel_format(style='sci', axis='both', scilimits=(0, 0)) # plt.legend() # ax[i].set_title('Training realizations: {}'.format(trunc[i])) plt.savefig('figures/Diffusion-coord.png', bbox_inches='tight', dpi=300) fig, ax = plt.subplots(figsize=(7, 5), constrained_layout=True) plt.scatter(x[:, 0], x[:, 1], c=labels, cmap=cmap) plt.xlabel(r'$x_1$', fontsize=22) plt.ylabel(r'$x_2$', fontsize=22) plt.title('Input parameters colored by \n the clusters on diffusion manifold') plt.savefig('figures/stochastic-inputs.png', bbox_inches='tight', dpi=300) ####################################################################################################################### # Step 3: PCE surrogate # ####################################################################################################################### class PceModel: """ Constructs a PCE surrogate on the Grassmannian diffusion manifold. """ def __init__(self, x, g, dist_obj, max_degree, verbose=False): self.x = x self.g = g self.dist_obj = dist_obj self.max_degree = max_degree self.verbose = verbose def get(self): # Polynomial basis dim_in = self.x.shape[1] polys = Polynomials(dist_object=self.dist_obj, degree=self.max_degree) n_basis = math.factorial(self.max_degree + dim_in) / \ (math.factorial(self.max_degree) * math.factorial(dim_in)) if self.verbose: print('Basis terms: ', int(n_basis)) # Regression method reg = PolyChaosLstsq(poly_object=polys) # reg = PolyChaosLasso(poly_object=polys, learning_rate=0.001, iterations=1000, penalty=0.05) # reg = PolyChaosRidge(poly_object=polys, learning_rate=0.001, iterations=10000, penalty=0) pce = PCE(method=reg) x_train, x_test, \ g_train, g_test = train_test_split(self.x, self.g, train_size=2 / 3, random_state=1) # Design matrix / conditioning D = polys.evaluate(self.x) cond_D = np.linalg.cond(D) if self.verbose: print('Condition number: ', cond_D) # Fit model pce.fit(x_train, g_train) error_val = ErrorEstimation(surr_object=pce).validation(x_test, g_test) if self.verbose: # Plot accuracy of PCE if os.path.exists('pce_accuracy'): command = ['rm', '-r', 'pce_accuracy'] subprocess.run(command) command = ['mkdir', 'pce_accuracy'] subprocess.run(command) print(g_test[0, :]) print(pce.predict(x_test)[0, :]) for i in range(5): r = random.randint(0, x_test.shape[0]) plt.figure() plt.plot(g_test[r, :], 'b-o', label='true') plt.plot(pce.predict(x_test)[r, :], 'r-*', label='pce') plt.legend() plt.savefig('pce_accuracy/pce_{}.png'.format(i), bbox_inches='tight') return pce, error_val ####################################################################################################################### # Step 4: Adaptive clustering # ####################################################################################################################### def AdaptClust(n_clust_max, Gr_object, data): """ Adaptive clustering to find the optimal number of clusters of the data onto the diffusion manifold """ Gr = Gr_object n_clust = 1 n_clust_max = n_clust_max clusters, error, mat_all, ind_all, kmeans_models, L_all = [0], [], [], [], [], [] while clusters[-1] < n_clust_max: if n_clust == 1: clusters.pop(-1) n_clust += 1 # K-means clustering kmeans = KMeans(n_clusters=n_clust, random_state=0).fit(data) C, L = kmeans.cluster_centers_, kmeans.labels_ # Get indices of clusters indices = [] cluster_num = [i for i in range(n_clust)] for i in cluster_num: indices.append(np.where(L == i)[0]) ind_all.append(indices) kmeans_models.append(kmeans) clusters.append(n_clust) L_all.append(L) n = np.array([ind_all[-1][i].shape[0] for i in range(len(ind_all[-1]))]) if np.any(n < 5): ind_all.pop(-1) kmeans_models.pop(-1) clusters.pop(-1) L_all.pop(-1) print('A cluster of less than 5 points was detected. The algorithm stopped.') break # Compute psi and phi matrices acc, mat_ = [], [] for k in range(n_clust): psi = np.array([Gr.psi[indices[k][i]] for i in range(len(indices[k]))]) phi = np.array([Gr.phi[indices[k][i]] for i in range(len(indices[k]))]) # Compute Karcher mean of points karcher_psi = Gr.karcher_mean(points_grassmann=psi, acc=False, tol=1e-3, maxiter=1000) karcher_phi = Gr.karcher_mean(points_grassmann=phi, acc=False, tol=1e-3, maxiter=1000) tan_psi = Gr.log_map(points_grassmann=psi, ref=karcher_psi) tan_phi = Gr.log_map(points_grassmann=phi, ref=karcher_phi) back_psi = Gr.exp_map(points_tangent=tan_psi, ref=karcher_psi) back_phi = Gr.exp_map(points_tangent=tan_phi, ref=karcher_phi) # Mean-squared error (MSE) mean_psi = np.mean( [(np.square(psi[i] - back_psi[i])).mean(axis=None) for i in range(indices[k].shape[0])]) mean_phi = np.mean( [(np.square(phi[i] - back_phi[i])).mean(axis=None) for i in range(indices[k].shape[0])]) mean_all = [mean_psi, mean_phi] acc.append(np.mean(mean_all)) mat_.append([tan_psi, tan_phi, karcher_psi, karcher_phi]) mat_all.append(mat_) error.append(np.mean(acc)) # print('Error for {} clusters:'.format(n_clust), error[-1]) if n_clust > 2: imp = (error[-2] - error[-1]) / error[-2] if imp < 0: error.pop(-1) clusters.pop(-1) mat_all.pop(-1) ind_all.pop(-1) kmeans_models.pop(-1) L_all.pop(-1) mat = mat_all[-1] indices = ind_all[-1] kmeans = kmeans_models[-1] L = L_all[-1] n_clust = len(mat) return mat, indices, kmeans, L, n_clust, error, clusters ####################################################################################################################### # Step 5: Geometric harmonics and PCE interpolators # ####################################################################################################################### def Interpolators(x, data, mat, indices, n_clust, Gr, joint): """ Constructs a GHI model to find a map between SVD matrices of knn points and diffusion coordinates on the GDMaps manifold. """ # Create GH and PCE models random_state = 1 models_all = [] for k in range(n_clust): models = [] # save GH for psi and phi for each cluster tan_psi, tan_phi, karcher_psi, karcher_phi = mat[k] # Convert lists to numpy arrays m1, m2 = np.array(tan_psi), np.array(tan_phi) l, m, n = m1.shape m1, m2 = m1.reshape(l, m * n), m2.reshape(l, m * n) M = [m1, m2] for i in range(2): p_train, p_test, \ g_train, g_test = train_test_split(M[i], data[indices[k]], train_size=2 / 3, random_state=random_state) pcm = pfold.PCManifold(g_train) pcm.optimize_parameters(random_state=random_state) train_indices, test_indices = train_test_split(np.random.permutation(p_train.shape[0]), train_size=2 / 3, test_size=1 / 3) # GH training (no Bayesian optimization) opt_epsilon = pcm.kernel.epsilon opt_cutoff = pcm.cut_off opt_n_eigenpairs = train_indices.shape[0] - 1 # test the interpolation quality with PCManifold optimization optimal_GHI = GHI(pfold.GaussianKernel(epsilon=opt_epsilon), n_eigenpairs=opt_n_eigenpairs, dist_kwargs=dict(cut_off=opt_cutoff)) optimal_GHI.fit(g_train[train_indices, :], p_train[train_indices, :]) # Get error and residual # residual = optimal_GHI.score(g_train, p_train) # error = optimal_GHI.score(g_test, p_test) models.append(optimal_GHI) models_all.append(models) dims = (m, n) # Construct PCE models for sigmas sigmas = np.array(Gr.sigma) max_degree = 2 polys = Polynomials(dist_object=joint, degree=max_degree) reg = PolyChaosLstsq(poly_object=polys) pce = PCE(method=reg) # Design matrix / conditioning D = polys.evaluate(x) cond_D = np.linalg.cond(D) # print('Condition number: ', cond_D) # Fit model pce.fit(x, sigmas) error_val2 = ErrorEstimation(surr_object=pce).validation(x, sigmas) print('Validation error of PCE of sigmas: ', error_val2) return models_all, pce, dims ####################################################################################################################### # Step 6: Out-of-sample predictions # ####################################################################################################################### def Prediction(x_pred, y_real, models_all, kmeans, mat, pce, pce_sigmas, Gr, dims): """ Out-of-sample predictions by using the GH and pce models of the clusters on the diffusion manifold """ # In case of one global pce # pce = pce[0] m, n = dims # dimensions of points onto the Grassmann manifold y_recon, l2, r2, diff = [], [], [], [] num = x_pred.shape[0] for k in range(num): # for one global PCE x_new = x_pred[k, :] # new sample y_pce = pce.predict(x_new.reshape(1, -1)) l = int(kmeans.predict(y_pce.reshape(1, -1))) # predicted label # For multiple PCEs # print('iteration of predictions: {}'.format(k)) # x_new = x_pred[k, :] # new sample # get_index = knn.kneighbors(x_new.reshape(1, -1), return_distance=False) # get = int(kmeans.labels_[get_index]) # print(get) # y_pce = pce[get].predict(x_new.reshape(1, -1)) # l = int(kmeans.predict(y_pce.reshape(1, -1))) # predicted label # print(l) # print('') # Return to ambient space psi_tan_point = models_all[l][0].predict(y_pce.reshape(1, -1)) phi_tan_point = models_all[l][1].predict(y_pce.reshape(1, -1)) sigma_grass = pce_sigmas.predict(x_new.reshape(1, -1)) sigma_grass = np.diag(sigma_grass.flatten()) # Project psi and phi back on Grassmann back_psi = np.squeeze(np.array(Gr.exp_map(points_tangent=[psi_tan_point.reshape(m, n)], ref=mat[l][2]))) back_phi = np.squeeze(np.array(Gr.exp_map(points_tangent=[phi_tan_point.reshape(m, n)], ref=mat[l][3]))) # Reconstruct sample with reverse SVD y_recon.append(np.dot(np.dot(back_psi, sigma_grass), back_phi.T)) # Relative L2 error error = np.linalg.norm(y_real[k] - y_recon[k]) / np.linalg.norm(y_real[k])
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities from . import outputs __all__ = [ 'ApplicationApi', 'ApplicationApiOauth2PermissionScope', 'ApplicationAppRole', 'ApplicationOauth2Permission', 'ApplicationOptionalClaims', 'ApplicationOptionalClaimsAccessToken', 'ApplicationOptionalClaimsIdToken', 'ApplicationRequiredResourceAccess', 'ApplicationRequiredResourceAccessResourceAccess', 'ApplicationWeb', 'ApplicationWebImplicitGrant', 'ServicePrincipalAppRole', 'ServicePrincipalOauth2Permission', 'ServicePrincipalOauth2PermissionScope', 'GetApplicationApiResult', 'GetApplicationApiOauth2PermissionScopeResult', 'GetApplicationAppRoleResult', 'GetApplicationOauth2PermissionResult', 'GetApplicationOptionalClaimsResult', 'GetApplicationOptionalClaimsAccessTokenResult', 'GetApplicationOptionalClaimsIdTokenResult', 'GetApplicationRequiredResourceAccessResult', 'GetApplicationRequiredResourceAccessResourceAccessResult', 'GetApplicationWebResult', 'GetApplicationWebImplicitGrantResult', 'GetDomainsDomainResult', 'GetServicePrincipalAppRoleResult', 'GetServicePrincipalOauth2PermissionResult', 'GetServicePrincipalOauth2PermissionScopeResult', 'GetUsersUserResult', ] @pulumi.output_type class ApplicationApi(dict): @staticmethod def __key_warning(key: str): suggest = None if key == "oauth2PermissionScopes": suggest = "oauth2_permission_scopes" if suggest: pulumi.log.warn(f"Key '{key}' not found in ApplicationApi. Access the value via the '{suggest}' property getter instead.") def __getitem__(self, key: str) -> Any: ApplicationApi.__key_warning(key) return super().__getitem__(key) def get(self, key: str, default = None) -> Any: ApplicationApi.__key_warning(key) return super().get(key, default) def __init__(__self__, *, oauth2_permission_scopes: Optional[Sequence['outputs.ApplicationApiOauth2PermissionScope']] = None): """ :param Sequence['ApplicationApiOauth2PermissionScopeArgs'] oauth2_permission_scopes: One or more `oauth2_permission_scope` blocks as documented below, to describe delegated permissions exposed by the web API represented by this Application. """ if oauth2_permission_scopes is not None: pulumi.set(__self__, "oauth2_permission_scopes", oauth2_permission_scopes) @property @pulumi.getter(name="oauth2PermissionScopes") def oauth2_permission_scopes(self) -> Optional[Sequence['outputs.ApplicationApiOauth2PermissionScope']]: """ One or more `oauth2_permission_scope` blocks as documented below, to describe delegated permissions exposed by the web API represented by this Application. """ return pulumi.get(self, "oauth2_permission_scopes") @pulumi.output_type class ApplicationApiOauth2PermissionScope(dict): @staticmethod def __key_warning(key: str): suggest = None if key == "adminConsentDescription": suggest = "admin_consent_description" elif key == "adminConsentDisplayName": suggest = "admin_consent_display_name" elif key == "userConsentDescription": suggest = "user_consent_description" elif key == "userConsentDisplayName": suggest = "user_consent_display_name" if suggest: pulumi.log.warn(f"Key '{key}' not found in ApplicationApiOauth2PermissionScope. Access the value via the '{suggest}' property getter instead.") def __getitem__(self, key: str) -> Any: ApplicationApiOauth2PermissionScope.__key_warning(key) return super().__getitem__(key) def get(self, key: str, default = None) -> Any: ApplicationApiOauth2PermissionScope.__key_warning(key) return super().get(key, default) def __init__(__self__, *, id: str, admin_consent_description: Optional[str] = None, admin_consent_display_name: Optional[str] = None, enabled: Optional[bool] = None, type: Optional[str] = None, user_consent_description: Optional[str] = None, user_consent_display_name: Optional[str] = None, value: Optional[str] = None): """ :param str id: The unique identifier of the app role. This attribute is computed and cannot be specified manually in this block. If you need to specify a custom `id`, it's recommended to use the ApplicationAppRole resource. :param str admin_consent_description: Delegated permission description that appears in all tenant-wide admin consent experiences, intended to be read by an administrator granting the permission on behalf of all users. :param str admin_consent_display_name: Display name for the delegated permission, intended to be read by an administrator granting the permission on behalf of all users. :param bool enabled: Determines if the app role is enabled: Defaults to `true`. :param str type: The type of the application: `webapp/api` or `native`. Defaults to `webapp/api`. For `native` apps type `identifier_uris` property can not be set. **This legacy property is deprecated and will be removed in version 2.0 of the provider**. :param str user_consent_description: Delegated permission description that appears in the end user consent experience, intended to be read by a user consenting on their own behalf. :param str user_consent_display_name: Display name for the delegated permission that appears in the end user consent experience. :param str value: The value that is used for the `roles` claim in ID tokens and OAuth 2.0 access tokens that are authenticating an assigned service or user principal. """ pulumi.set(__self__, "id", id) if admin_consent_description is not None: pulumi.set(__self__, "admin_consent_description", admin_consent_description) if admin_consent_display_name is not None: pulumi.set(__self__, "admin_consent_display_name", admin_consent_display_name) if enabled is not None: pulumi.set(__self__, "enabled", enabled) if type is not None: pulumi.set(__self__, "type", type) if user_consent_description is not None: pulumi.set(__self__, "user_consent_description", user_consent_description) if user_consent_display_name is not None: pulumi.set(__self__, "user_consent_display_name", user_consent_display_name) if value is not None: pulumi.set(__self__, "value", value) @property @pulumi.getter def id(self) -> str: """ The unique identifier of the app role. This attribute is computed and cannot be specified manually in this block. If you need to specify a custom `id`, it's recommended to use the ApplicationAppRole resource. """ return pulumi.get(self, "id") @property @pulumi.getter(name="adminConsentDescription") def admin_consent_description(self) -> Optional[str]: """ Delegated permission description that appears in all tenant-wide admin consent experiences, intended to be read by an administrator granting the permission on behalf of all users. """ return pulumi.get(self, "admin_consent_description") @property @pulumi.getter(name="adminConsentDisplayName") def admin_consent_display_name(self) -> Optional[str]: """ Display name for the delegated permission, intended to be read by an administrator granting the permission on behalf of all users. """ return pulumi.get(self, "admin_consent_display_name") @property @pulumi.getter def enabled(self) -> Optional[bool]: """ Determines if the app role is enabled: Defaults to `true`. """ return pulumi.get(self, "enabled") @property @pulumi.getter def type(self) -> Optional[str]: """ The type of the application: `webapp/api` or `native`. Defaults to `webapp/api`. For `native` apps type `identifier_uris` property can not be set. **This legacy property is deprecated and will be removed in version 2.0 of the provider**. """ return pulumi.get(self, "type") @property @pulumi.getter(name="userConsentDescription") def user_consent_description(self) -> Optional[str]: """ Delegated permission description that appears in the end user consent experience, intended to be read by a user consenting on their own behalf. """ return pulumi.get(self, "user_consent_description") @property @pulumi.getter(name="userConsentDisplayName") def user_consent_display_name(self) -> Optional[str]: """ Display name for the delegated permission that appears in the end user consent experience. """ return pulumi.get(self, "user_consent_display_name") @property @pulumi.getter def value(self) -> Optional[str]: """ The value that is used for the `roles` claim in ID tokens and OAuth 2.0 access tokens that are authenticating an assigned service or user principal. """ return pulumi.get(self, "value") @pulumi.output_type class ApplicationAppRole(dict): @staticmethod def __key_warning(key: str): suggest = None if key == "allowedMemberTypes": suggest = "allowed_member_types" elif key == "displayName": suggest = "display_name" elif key == "isEnabled": suggest = "is_enabled" if suggest: pulumi.log.warn(f"Key '{key}' not found in ApplicationAppRole. Access the value via the '{suggest}' property getter instead.") def __getitem__(self, key: str) -> Any: ApplicationAppRole.__key_warning(key) return super().__getitem__(key) def get(self, key: str, default = None) -> Any: ApplicationAppRole.__key_warning(key) return super().get(key, default) def __init__(__self__, *, allowed_member_types: Sequence[str], description: str, display_name: str, enabled: Optional[bool] = None, id: Optional[str] = None, is_enabled: Optional[bool] = None, value: Optional[str] = None): """ :param Sequence[str] allowed_member_types: Specifies whether this app role definition can be assigned to users and groups by setting to `User`, or to other applications (that are accessing this application in a standalone scenario) by setting to `Application`, or to both. :param str description: Description of the app role that appears when the role is being assigned and, if the role functions as an application permissions, during the consent experiences. :param str display_name: Display name for the app role that appears during app role assignment and in consent experiences. :param bool enabled: Determines if the app role is enabled: Defaults to `true`. :param str id: The unique identifier of the app role. This attribute is computed and cannot be specified manually in this block. If you need to specify a custom `id`, it's recommended to use the ApplicationAppRole resource. :param bool is_enabled: Determines if the permission is enabled: defaults to `true`. :param str value: The value that is used for the `roles` claim in ID tokens and OAuth 2.0 access tokens that are authenticating an assigned service or user principal. """ pulumi.set(__self__, "allowed_member_types", allowed_member_types) pulumi.set(__self__, "description", description) pulumi.set(__self__, "display_name", display_name) if enabled is not None: pulumi.set(__self__, "enabled", enabled) if id is not None: pulumi.set(__self__, "id", id) if is_enabled is not None: pulumi.set(__self__, "is_enabled", is_enabled) if value is not None: pulumi.set(__self__, "value", value) @property @pulumi.getter(name="allowedMemberTypes") def allowed_member_types(self) -> Sequence[str]: """ Specifies whether this app role definition can be assigned to users and groups by setting to `User`, or to other applications (that are accessing this application in a standalone scenario) by setting to `Application`, or to both. """ return pulumi.get(self, "allowed_member_types") @property @pulumi.getter def description(self) -> str: """ Description of the app role that appears when the role is being assigned and, if the role functions as an application permissions, during the consent experiences. """ return pulumi.get(self, "description") @property @pulumi.getter(name="displayName") def display_name(self) -> str: """ Display name for the
# -*- coding: utf-8 -*- from datetime import datetime import mock import pytest import random from django.utils import timezone from api.base.settings.defaults import API_BASE from api.nodes.serializers import NodeContributorsCreateSerializer from framework.auth.core import Auth from osf.models import PreprintLog from osf_tests.factories import ( fake_email, AuthUserFactory, PreprintFactory, UnconfirmedUserFactory, UserFactory, ) from osf.utils import permissions from osf.utils.workflows import DefaultStates from rest_framework import exceptions from tests.base import capture_signals, fake from tests.utils import assert_latest_log, assert_equals from website.project.signals import contributor_added, contributor_removed from api_tests.utils import disconnected_from_listeners @pytest.mark.django_db class NodeCRUDTestCase: @pytest.fixture() def user(self): return AuthUserFactory() @pytest.fixture() def user_two(self): return AuthUserFactory() @pytest.fixture() def preprint_published(self, user): return PreprintFactory(creator=user, is_published=True) @pytest.fixture() def preprint_unpublished(self, user): return PreprintFactory(creator=user, is_published=False) @pytest.fixture() def title(self): return 'Cool Preprint' @pytest.fixture() def title_new(self): return 'Super Cool Preprint' @pytest.fixture() def description(self): return 'A Properly Cool Preprint' @pytest.fixture() def description_new(self): return 'An even cooler preprint' @pytest.fixture() def url_published(self, preprint_published): return '/{}preprints/{}/'.format(API_BASE, preprint_published._id) @pytest.fixture() def url_unpublished(self, preprint_unpublished): return '/{}preprints/{}/'.format(API_BASE, preprint_unpublished._id) @pytest.fixture() def url_fake(self): return '/{}preprints/{}/'.format(API_BASE, '12345') @pytest.fixture() def make_contrib_id(self): def contrib_id(preprint_id, user_id): return '{}-{}'.format(preprint_id, user_id) return contrib_id @pytest.mark.django_db @pytest.mark.enable_quickfiles_creation @pytest.mark.enable_implicit_clean class TestPreprintContributorList(NodeCRUDTestCase): @pytest.fixture() def url_published(self, preprint_published): return '/{}preprints/{}/contributors/'.format( API_BASE, preprint_published._id) @pytest.fixture() def url_unpublished(self, preprint_unpublished): return '/{}preprints/{}/contributors/'.format(API_BASE, preprint_unpublished._id) def test_concatenated_id(self, app, user, preprint_published, url_published): res = app.get(url_published) assert res.status_code == 200 assert res.json['data'][0]['id'].split('-')[0] == preprint_published._id assert res.json['data'][0]['id'] == '{}-{}'.format( preprint_published._id, user._id) def test_permissions_work_with_many_users( self, app, user, preprint_unpublished, url_unpublished): users = { permissions.ADMIN: [user._id], permissions.WRITE: [], permissions.READ: [] } for i in range(0, 25): perm = random.choice(list(users.keys())) user_two = AuthUserFactory() preprint_unpublished.add_contributor(user_two, permissions=perm) users[perm].append(user_two._id) res = app.get(url_unpublished, auth=user.auth) data = res.json['data'] for user in data: api_perm = user['attributes']['permission'] user_id = user['id'].split('-')[1] assert user_id in users[api_perm], 'Permissions incorrect for {}. Should not have {} permission.'.format( user_id, api_perm) def test_return( self, app, user, user_two, preprint_published, preprint_unpublished, url_published, url_unpublished, make_contrib_id): # test_return_published_contributor_list_logged_in res = app.get(url_published, auth=user_two.auth) assert res.status_code == 200 assert res.content_type == 'application/vnd.api+json' assert len(res.json['data']) == 1 assert res.json['data'][0]['id'] == make_contrib_id( preprint_published._id, user._id) # test_return_unpublished_contributor_list_logged_out res = app.get(url_unpublished, expect_errors=True) assert res.status_code == 401 assert 'detail' in res.json['errors'][0] # test_return_unpublished_contributor_list_logged_in_non_contributor res = app.get(url_unpublished, auth=user_two.auth, expect_errors=True) assert res.status_code == 403 assert 'detail' in res.json['errors'][0] # test_return_unpublished_contributor_list_logged_in_read_contributor read_contrib = AuthUserFactory() preprint_unpublished.add_contributor(read_contrib, permissions=permissions.READ, save=True) res = app.get(url_unpublished, auth=read_contrib.auth, expect_errors=True) assert res.status_code == 403 assert 'detail' in res.json['errors'][0] def test_return_published_contributor_list_logged_out( self, app, user, user_two, preprint_published, url_published, make_contrib_id): preprint_published.add_contributor(user_two, save=True) res = app.get(url_published) assert res.status_code == 200 assert res.content_type == 'application/vnd.api+json' assert len(res.json['data']) == 2 assert res.json['data'][0]['id'] == make_contrib_id( preprint_published._id, user._id) assert res.json['data'][1]['id'] == make_contrib_id( preprint_published._id, user_two._id) def test_return_unpublished_contributor_list_logged_in_contributor( self, app, user, user_two, preprint_unpublished, url_unpublished, make_contrib_id): preprint_unpublished.add_contributor(user_two) preprint_unpublished.save() res = app.get(url_unpublished, auth=user.auth) assert res.status_code == 200 assert res.content_type == 'application/vnd.api+json' assert len(res.json['data']) == 2 assert res.json['data'][0]['id'] == make_contrib_id( preprint_unpublished._id, user._id) assert res.json['data'][1]['id'] == make_contrib_id( preprint_unpublished._id, user_two._id) def test_return_preprint_contributors_private_preprint( self, app, user, user_two, preprint_published, url_published): preprint_published.is_public = False preprint_published.save() # test_private_preprint_contributors_logged_out res = app.get(url_published, expect_errors=True) assert res.status_code == 401 # test private_preprint_contributor_non_contrib res = app.get(url_published, auth=user_two.auth, expect_errors=True) assert res.status_code == 403 # test private_preprint_contributors_read_contrib_logged_out preprint_published.add_contributor(user_two, permissions.READ, save=True) res = app.get(url_published, auth=user_two.auth) assert res.status_code == 200 # test private_preprint_contributors_admin res = app.get(url_published, auth=user.auth) assert res.status_code == 200 def test_return_preprint_contributors_deleted_preprint( self, app, user, user_two, preprint_published, url_published): preprint_published.deleted = timezone.now() preprint_published.save() # test_deleted_preprint_contributors_logged_out res = app.get(url_published, expect_errors=True) assert res.status_code == 404 # test_deleted_preprint_contributor_non_contrib res = app.get(url_published, auth=user_two.auth, expect_errors=True) assert res.status_code == 404 # test_deleted_preprint_contributors_read_contrib_logged_out preprint_published.add_contributor(user_two, permissions.READ, save=True) res = app.get(url_published, auth=user_two.auth, expect_errors=True) assert res.status_code == 404 # test_deleted_preprint_contributors_admin res = app.get(url_published, auth=user.auth, expect_errors=True) assert res.status_code == 404 def test_return_preprint_contributors_abandoned_preprint( self, app, user, user_two, preprint_published, url_published): preprint_published.machine_state = DefaultStates.INITIAL.value preprint_published.save() # test_abandoned_preprint_contributors_logged_out res = app.get(url_published, expect_errors=True) assert res.status_code == 401 # test_abandoned_preprint_contributor_non_contrib res = app.get(url_published, auth=user_two.auth, expect_errors=True) assert res.status_code == 403 # test_abandoned_preprint_contributors_read_contrib_logged_out preprint_published.add_contributor(user_two, permissions.READ, save=True) res = app.get(url_published, auth=user_two.auth, expect_errors=True) assert res.status_code == 403 # test_abandoned_preprint_contributors_admin res = app.get(url_published, auth=user.auth, expect_errors=True) assert res.status_code == 200 def test_filtering_on_obsolete_fields(self, app, user, url_published): # regression test for changes in filter fields url_fullname = '{}?filter[fullname]=foo'.format(url_published) res = app.get(url_fullname, auth=user.auth, expect_errors=True) assert res.status_code == 400 errors = res.json['errors'] assert len(errors) == 1 assert errors[0]['detail'] == '\'fullname\' is not a valid field for this endpoint.' # middle_name is now middle_names url_middle_name = '{}?filter[middle_name]=foo'.format(url_published) res = app.get(url_middle_name, auth=user.auth, expect_errors=True) assert res.status_code == 400 errors = res.json['errors'] assert len(errors) == 1 assert errors[0]['detail'] == '\'middle_name\' is not a valid field for this endpoint.' def test_disabled_contributors_contain_names_under_meta( self, app, user, user_two, preprint_published, url_published, make_contrib_id): preprint_published.add_contributor(user_two, save=True) user_two.is_disabled = True user_two.save() res = app.get(url_published) assert res.status_code == 200 assert res.content_type == 'application/vnd.api+json' assert len(res.json['data']) == 2 assert res.json['data'][0]['id'] == make_contrib_id( preprint_published._id, user._id) assert res.json['data'][1]['id'] == make_contrib_id( preprint_published._id, user_two._id) assert res.json['data'][1]['embeds']['users']['errors'][0]['meta']['full_name'] == user_two.fullname assert res.json['data'][1]['embeds']['users']['errors'][0]['detail'] == 'The requested user is no longer available.' def test_total_bibliographic_contributor_count_returned_in_metadata( self, app, user_two, preprint_published, url_published): non_bibliographic_user = UserFactory() preprint_published.add_contributor( non_bibliographic_user, visible=False, auth=Auth(preprint_published.creator)) preprint_published.save() res = app.get(url_published, auth=user_two.auth) assert res.status_code == 200 assert res.json['links']['meta']['total_bibliographic'] == len( preprint_published.visible_contributor_ids) def test_unregistered_contributor_field_is_null_if_account_claimed( self, app, user): preprint = PreprintFactory(creator=user, is_published=True) url = '/{}preprints/{}/contributors/'.format(API_BASE, preprint._id) res = app.get(url, auth=user.auth, expect_errors=True) assert res.status_code == 200 assert len(res.json['data']) == 1 assert res.json['data'][0]['attributes'].get( 'unregistered_contributor') is None def test_unregistered_contributors_show_up_as_name_associated_with_preprint( self, app, user): preprint = PreprintFactory(creator=user, is_published=True) preprint.add_unregistered_contributor( '<NAME>', '<EMAIL>', auth=Auth(user), save=True) url = '/{}preprints/{}/contributors/'.format(API_BASE, preprint._id) res = app.get(url, auth=user.auth, expect_errors=True) assert res.status_code == 200 assert len(res.json['data']) == 2 assert res.json['data'][1]['embeds']['users']['data']['attributes']['full_name'] == '<NAME>' assert res.json['data'][1]['attributes'].get( 'unregistered_contributor') == '<NAME>' preprint_two = PreprintFactory(creator=user, is_published=True) preprint_two.add_unregistered_contributor( '<NAME>', '<EMAIL>', auth=Auth(user), save=True) url = '/{}preprints/{}/contributors/'.format(API_BASE, preprint_two._id) res = app.get(url, auth=user.auth, expect_errors=True) assert res.status_code == 200 assert len(res.json['data']) == 2 assert res.json['data'][1]['embeds']['users']['data']['attributes']['full_name'] == '<NAME>' assert res.json['data'][1]['attributes'].get( 'unregistered_contributor') == '<NAME>' def test_contributors_order_is_the_same_over_multiple_requests( self, app, user, preprint_published, url_published): preprint_published.add_unregistered_contributor( '<NAME>', '<EMAIL>', auth=Auth(user), save=True ) for i in range(0, 10): new_user = AuthUserFactory() if i % 2 == 0: visible = True else: visible = False preprint_published.add_contributor( new_user, visible=visible, auth=Auth(preprint_published.creator), save=True ) req_one = app.get( '{}?page=2'.format(url_published), auth=Auth(preprint_published.creator)) req_two = app.get( '{}?page=2'.format(url_published), auth=Auth(preprint_published.creator)) id_one = [item['id'] for item in req_one.json['data']] id_two = [item['id'] for item in req_two.json['data']] for a, b in zip(id_one, id_two): assert a == b @pytest.mark.django_db @pytest.mark.enable_quickfiles_creation @pytest.mark.enable_implicit_clean class TestPreprintContributorAdd(NodeCRUDTestCase): @pytest.fixture() def user_three(self): return AuthUserFactory() @pytest.fixture() def url_unpublished(self, preprint_unpublished): return '/{}preprints/{}/contributors/?send_email=false'.format( API_BASE, preprint_unpublished._id) @pytest.fixture() def url_published(self, preprint_published): return '/{}preprints/{}/contributors/?send_email=false'.format( API_BASE, preprint_published._id) @pytest.fixture() def data_user_two(self, user_two): return { 'data': { 'type': 'contributors', 'attributes': { 'bibliographic': True, }, 'relationships': { 'users': { 'data': { 'type': 'users', 'id': user_two._id, } } } } } @pytest.fixture() def data_user_three(self, user_three): return { 'data': { 'type': 'contributors', 'attributes': { 'bibliographic': True, }, 'relationships': { 'users': { 'data': { 'type': 'users', 'id': user_three._id, } } } } } def test_add_contributors_errors( self, app, user, user_two, user_three, url_published): # test_add_preprint_contributors_relationships_is_a_list data = { 'data': { 'type': 'contributors', 'attributes': { 'bibliographic': True }, 'relationships': [{'contributor_id': user_three._id}] } } res = app.post_json_api( url_published, data, auth=user.auth, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == exceptions.ParseError.default_detail # test_add_contributor_no_relationships data = { 'data': { 'type': 'contributors', 'attributes': { 'bibliographic': True } } } res = app.post_json_api( url_published, data, auth=user.auth, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'A user ID or full name must be provided to add a contributor.' # test_add_contributor_empty_relationships data = { 'data': { 'type': 'contributors', 'attributes': { 'bibliographic': True }, 'relationships': {} } } res = app.post_json_api( url_published, data, auth=user.auth, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'A user ID or full name must be provided to add a contributor.' # test_add_contributor_no_user_key_in_relationships data = { 'data': { 'type': 'contributors', 'attributes': { 'bibliographic': True }, 'relationships': { 'id': user_two._id, 'type': 'users' } } } res = app.post_json_api( url_published, data, auth=user.auth, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == exceptions.ParseError.default_detail # test_add_contributor_no_data_in_relationships data = { 'data': { 'type': 'contributors', 'attributes': { 'bibliographic': True }, 'relationships': { 'users': { 'id': user_two._id } } } } res = app.post_json_api( url_published, data, auth=user.auth, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'Request must include /data.' # test_add_contributor_no_target_type_in_relationships data = { 'data': { 'type': 'contributors', 'attributes': { 'bibliographic': True }, 'relationships': { 'users': { 'data': { 'id': user_two._id } } } } } res = app.post_json_api( url_published, data, auth=user.auth, expect_errors=True) assert res.status_code == 400 assert res.json['errors'][0]['detail'] == 'Request must include /type.' # test_add_contributor_no_target_id_in_relationships data = { 'data': { 'type': 'contributors', 'attributes': { 'bibliographic': True }, 'relationships': { 'users':
in %s is managed by system '%s'. Are you sure you want to modify it? [y/n]: " % (p.prefix, vrf_format(p.vrf), p.authoritative_source)) # If the user declines, short-circuit... if res.lower() not in [ 'y', 'yes' ]: print("Operation aborted.") return try: p.save() except NipapError as exc: print("Could not save prefix changes: %s" % str(exc), file=sys.stderr) sys.exit(1) print("Prefix %s in %s saved." % (p.display_prefix, vrf_format(p.vrf))) def prefix_attr_add(arg, opts, shell_opts): """ Add attributes to a prefix """ spec = { 'prefix': arg } v = get_vrf(opts.get('vrf_rt'), abort=True) spec['vrf_rt'] = v.rt res = Prefix.list(spec) if len(res) == 0: print("Prefix %s not found in %s." % (arg, vrf_format(v)), file=sys.stderr) return p = res[0] for avp in opts.get('extra-attribute', []): try: key, value = avp.split('=', 1) except ValueError: print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr) sys.exit(1) if key in p.avps: print("Unable to add extra-attribute: '%s' already exists." % key, file=sys.stderr) sys.exit(1) p.avps[key] = value try: p.save() except NipapError as exc: print("Could not save prefix changes: %s" % str(exc), file=sys.stderr) sys.exit(1) print("Prefix %s in %s saved." % (p.display_prefix, vrf_format(p.vrf))) def prefix_attr_remove(arg, opts, shell_opts): """ Remove attributes from a prefix """ spec = { 'prefix': arg } v = get_vrf(opts.get('vrf_rt'), abort=True) spec['vrf_rt'] = v.rt res = Prefix.list(spec) if len(res) == 0: print("Prefix %s not found in %s." % (arg, vrf_format(v)), file=sys.stderr) return p = res[0] for key in opts.get('extra-attribute', []): if key not in p.avps: print("Unable to remove extra-attribute: '%s' does not exist." % key, file=sys.stderr) sys.exit(1) del p.avps[key] try: p.save() except NipapError as exc: print("Could not save prefix changes: %s" % str(exc), file=sys.stderr) sys.exit(1) print("Prefix %s in %s saved." % (p.display_prefix, vrf_format(p.vrf))) def vrf_attr_add(arg, opts, shell_opts): """ Add attributes to a VRF """ if arg is None: print("ERROR: Please specify the RT of the VRF to view.", file=sys.stderr) sys.exit(1) # interpret as default VRF (ie, RT = None) if arg.lower() in ('-', 'none'): arg = None try: v = VRF.search({ 'val1': 'rt', 'operator': 'equals', 'val2': arg } )['result'][0] except (KeyError, IndexError): print("VRF with [RT: %s] not found." % str(arg), file=sys.stderr) sys.exit(1) for avp in opts.get('extra-attribute', []): try: key, value = avp.split('=', 1) except ValueError: print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr) sys.exit(1) if key in v.avps: print("Unable to add extra-attribute: '%s' already exists." % key, file=sys.stderr) sys.exit(1) v.avps[key] = value try: v.save() except NipapError as exc: print("Could not save VRF changes: %s" % str(exc), file=sys.stderr) sys.exit(1) print("%s saved." % vrf_format(v)) def vrf_attr_remove(arg, opts, shell_opts): """ Remove attributes from a prefix """ if arg is None: print("ERROR: Please specify the RT of the VRF to view.", file=sys.stderr) sys.exit(1) # interpret as default VRF (ie, RT = None) if arg.lower() in ('-', 'none'): arg = None try: v = VRF.search({ 'val1': 'rt', 'operator': 'equals', 'val2': arg } )['result'][0] except (KeyError, IndexError): print("VRF with [RT: %s] not found." % str(arg), file=sys.stderr) sys.exit(1) for key in opts.get('extra-attribute', []): if key not in v.avps: print("Unable to remove extra-attribute: '%s' does not exist." % key, file=sys.stderr) sys.exit(1) del v.avps[key] try: v.save() except NipapError as exc: print("Could not save VRF changes: %s" % str(exc), file=sys.stderr) sys.exit(1) print("%s saved." % vrf_format(v)) def pool_attr_add(arg, opts, shell_opts): """ Add attributes to a pool """ res = Pool.list({ 'name': arg }) if len(res) < 1: print("No pool with name '%s' found." % arg, file=sys.stderr) sys.exit(1) p = res[0] for avp in opts.get('extra-attribute', []): try: key, value = avp.split('=', 1) except ValueError: print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr) sys.exit(1) if key in p.avps: print("Unable to add extra-attribute: '%s' already exists." % key, file=sys.stderr) sys.exit(1) p.avps[key] = value try: p.save() except NipapError as exc: print("Could not save pool changes: %s" % str(exc), file=sys.stderr) sys.exit(1) print("Pool '%s' saved." % p.name) def pool_attr_remove(arg, opts, shell_opts): """ Remove attributes from a prefix """ res = Pool.list({ 'name': arg }) if len(res) < 1: print("No pool with name '%s' found." % arg, file=sys.stderr) sys.exit(1) p = res[0] for key in opts.get('extra-attribute', []): if key not in p.avps: print("Unable to remove extra-attribute: '%s' does not exist." % key, file=sys.stderr) sys.exit(1) del p.avps[key] try: p.save() except NipapError as exc: print("Could not save pool changes: %s" % str(exc), file=sys.stderr) sys.exit(1) print("Pool '%s' saved." % p.name) """ COMPLETION FUNCTIONS """ def _complete_string(key, haystack): """ Returns valid string completions Takes the string 'key' and compares it to each of the strings in 'haystack'. The ones which beginns with 'key' are returned as result. """ if len(key) == 0: return haystack match = [] for straw in haystack: if string.find(straw, key) == 0: match.append(straw) return match def complete_bool(arg): """ Complete strings "true" and "false" """ return _complete_string(arg, valid_bools) def complete_country(arg): """ Complete country codes ("SE", "DE", ...) """ return _complete_string(arg, valid_countries) def complete_family(arg): """ Complete inet family ("ipv4", "ipv6") """ return _complete_string(arg, valid_families) def complete_tags(arg): """ Complete NIPAP prefix type """ search_string = '^' if arg is not None: search_string += arg res = Tag.search({ 'operator': 'regex_match', 'val1': 'name', 'val2': search_string }) ret = [] for t in res['result']: ret.append(t.name) return ret def complete_pool_members(arg): """ Complete member prefixes of pool """ # pool should already be globally set res = [] for member in Prefix.list({ 'pool_id': pool.id }): res.append(member.prefix) return _complete_string(arg, res) def complete_prefix_type(arg): """ Complete NIPAP prefix type """ return _complete_string(arg, valid_prefix_types) def complete_prefix_status(arg): """ Complete NIPAP prefix status """ return _complete_string(arg, valid_prefix_status) def complete_priority(arg): """ Complete NIPAP alarm priority """ return _complete_string(arg, valid_priorities) def complete_node(arg): """ Complete node hostname This function is currently a bit special as it looks in the config file for a command to use to complete a node hostname from an external system. It is configured by setting the config attribute "complete_node_cmd" to a shell command. The string "%search_string%" in the command will be replaced by the current search string. """ # get complete command from config try: cmd = cfg.get('global', 'complete_node_cmd') except configparser.NoOptionError: return [ '', ] cmd = re.sub('%search_string%', pipes.quote(arg), cmd) args = shlex.split(cmd) p = subprocess.Popen(args, stdout=subprocess.PIPE) res, err = p.communicate() nodes = res.split('\n') return nodes def complete_pool_name(arg): """ Returns list of matching pool names """ search_string = '^' if arg is not None: search_string += arg res = Pool.search({ 'operator': 'regex_match', 'val1': 'name', 'val2': search_string }) ret = [] for p in res['result']: ret.append(p.name) return ret def complete_vrf(arg): """ Returns list of matching VRFs """ search_string = '' if arg is not None: search_string = '^%s' % arg res = VRF.search({ 'operator': 'regex_match', 'val1': 'rt', 'val2': search_string }, { 'max_result': 100000 } ) ret = [] for v in res['result']: ret.append(v.rt) if re.match(search_string, 'none'): ret.append('none') return ret def complete_vrf_virtual(arg): """ Returns list of matching VRFs Includes "virtual" VRF 'all' which is used in search operations """ ret = complete_vrf(arg) search_string = '' if arg is not None: search_string = '^%s' % arg if re.match(search_string, 'all'): ret.append('all') return ret """ The NIPAP command tree """ cmds = { 'type': 'command', 'children': { 'address': { 'type': 'command', 'children': { # add 'add': { 'type': 'command', 'exec': add_prefix, 'children': { 'add-hosts': { 'type': 'option', 'argument': { 'type': 'value', 'content_type': str, } }, 'comment': { 'type': 'option', 'argument': { 'type': 'value', 'content_type': str, } }, 'country': { 'type': 'option', 'argument': { 'type': 'value', 'content_type': str, 'complete': complete_country, } }, 'description': { 'type': 'option', 'argument': { 'type': 'value', 'content_type': str, } }, 'family': { 'type': 'option', 'argument': { 'type': 'value', 'content_type': str, 'complete': complete_family, } }, 'status': { 'type': 'option', 'argument': { 'type': 'value', 'description': 'Prefix status: %s' % ' | '.join(valid_prefix_status), 'content_type': str, 'complete': complete_prefix_status, } }, 'type': { 'type': 'option', 'argument': { 'type': 'value', 'description': 'Prefix type: reservation | assignment | host', 'content_type': str, 'complete': complete_prefix_type, } }, 'from-pool': { 'type': 'option', 'argument': { 'type': 'value', 'content_type': str, 'complete': complete_pool_name, } }, 'from-prefix': { 'type': 'option', 'argument': { 'type': 'value', 'content_type': str, } }, 'node': { 'type': 'option', 'content_type': str, 'argument': { 'type': 'value', 'content_type': str, 'complete': complete_node, } }, 'order_id': { 'type': 'option', 'argument': { 'type': 'value', 'content_type':
= Box(children=row, layout=box_layout) name_btn = Button(description='exhausted_macrophage_death_rat', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float574 = FloatText(value='0.01', step='0.001', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' description_btn = Button(description='', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'lightgreen' row = [name_btn, self.float574, units_btn, description_btn] box614 = Box(children=row, layout=box_layout) name_btn = Button(description='ability_to_phagocytose_infected_cell', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float575 = FloatText(value='0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='dimensionless', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' description_btn = Button(description='Boolean for whether macrophages can phagocytose infected cells', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'tan' row = [name_btn, self.float575, units_btn, description_btn] box615 = Box(children=row, layout=box_layout) name_btn = Button(description='time_of_DC_departure', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float576 = FloatText(value='0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' description_btn = Button(description='Time DC leaves tissue after activation', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'lightgreen' row = [name_btn, self.float576, units_btn, description_btn] box616 = Box(children=row, layout=box_layout) name_btn = Button(description='phagocytosis_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float577 = FloatText(value='0.117', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' description_btn = Button(description='', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'tan' row = [name_btn, self.float577, units_btn, description_btn] box617 = Box(children=row, layout=box_layout) name_btn = Button(description='sensitivity_to_debris_chemotaxis', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float578 = FloatText(value='1.0', step='0.1', style=style, layout=widget_layout) units_btn = Button(description='dimensionless', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' description_btn = Button(description='relative sensitivity to debris in chemotaxis', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'lightgreen' row = [name_btn, self.float578, units_btn, description_btn] box618 = Box(children=row, layout=box_layout) name_btn = Button(description='sensitivity_to_chemokine_chemotaxis', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float579 = FloatText(value='10.0', step='1', style=style, layout=widget_layout) units_btn = Button(description='dimensionless', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' description_btn = Button(description='relative sensitivity to chemokine in chemotaxis', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'tan' row = [name_btn, self.float579, units_btn, description_btn] box619 = Box(children=row, layout=box_layout) name_btn = Button(description='activated_speed', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float580 = FloatText(value='0.4', step='0.1', style=style, layout=widget_layout) units_btn = Button(description='micron/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' description_btn = Button(description='speed after activation', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'lightgreen' row = [name_btn, self.float580, units_btn, description_btn] box620 = Box(children=row, layout=box_layout) name_btn = Button(description='activated_cytokine_secretion_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float581 = FloatText(value='0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' description_btn = Button(description='rate of secreting pro-inflamatory cytokine after activation', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'tan' row = [name_btn, self.float581, units_btn, description_btn] box621 = Box(children=row, layout=box_layout) name_btn = Button(description='activated_immune_cell', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float582 = FloatText(value='0.0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='dimensionless', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' description_btn = Button(description='used internally to track activation state', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'lightgreen' row = [name_btn, self.float582, units_btn, description_btn] box622 = Box(children=row, layout=box_layout) name_btn = Button(description='antiinflammatory_cytokine_secretion_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float583 = FloatText(value='15', step='1', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' description_btn = Button(description='secretion rate of anti-inflammatory from infected epithelium cell', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'tan' row = [name_btn, self.float583, units_btn, description_btn] box623 = Box(children=row, layout=box_layout) name_btn = Button(description='collagen_secretion_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float584 = FloatText(value='1', step='0.1', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' description_btn = Button(description='secretion rate of collagen from fibroblast', disabled=True, layout=desc_button_layout) description_btn.style.button_color = 'lightgreen' row = [name_btn, self.float584, units_btn, description_btn] box624 = Box(children=row, layout=box_layout) self.cell_def_vbox4 = VBox([ div_row33, box500, box501, box502, box503, div_row34, death_model1,box504, box505, box506, box507, box508, box509, box510, death_model2,box511, box512, box513, box514, box515, box516, box517, div_row35, box518, box519, box520, box521, box522, box523, box524, box525, box526, div_row36, box527, box528, box529, box530, box531, div_row37, box532,box533,box534,self.bool22,self.bool23,chemotaxis_btn,self.bool24,box535,box536,div_row38, box537,box538,box539,box540,box541,box542,box543,box544,box545,box546,box547,box548,box549,box550,box551,box552,box553,box554,div_row39, div_row40, box555, box556, box557, box558, box559, box560, box561, box562, box563, box564, box565, box566, box567, box568, box569, box570, box571, box572, box573, box574, box575, box576, box577, box578, box579, box580, box581, box582, box583, box584, box585, box586, box587, box588, box589, box590, box591, box592, box593, box594, box595, box596, box597, box598, box599, box600, box601, box602, box603, box604, box605, box606, box607, box608, box609, box610, box611, box612, box613, box614, box615, box616, box617, box618, box619, box620, box621, box622, box623, box624, ]) # ------------------------------------------ self.cell_def_vboxes.append(self.cell_def_vbox4) # >>>>>>>>>>>>>>>>> <cell_definition> = DC # ------------------------- div_row41 = Button(description='phenotype:cycle (model: flow_cytometry_separated_cycle_model; code=6)', disabled=True, layout=divider_button_layout) div_row41.style.button_color = 'orange' name_btn = Button(description='Phase 0 -> Phase 1 transition rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float585 = FloatText(value='0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' row = [name_btn, self.float585, units_btn, ] box625 = Box(children=row, layout=box_layout) name_btn = Button(description='Phase 1 -> Phase 2 transition rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float586 = FloatText(value='0.00208333', step='0.0001', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' row = [name_btn, self.float586, units_btn, ] box626 = Box(children=row, layout=box_layout) name_btn = Button(description='Phase 2 -> Phase 3 transition rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float587 = FloatText(value='0.00416667', step='0.001', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' row = [name_btn, self.float587, units_btn, ] box627 = Box(children=row, layout=box_layout) name_btn = Button(description='Phase 3 -> Phase 0 transition rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float588 = FloatText(value='0.0166667', step='0.001', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' row = [name_btn, self.float588, units_btn, ] box628 = Box(children=row, layout=box_layout) # ------------------------- div_row42 = Button(description='phenotype:death', disabled=True, layout=divider_button_layout) div_row42.style.button_color = 'orange' death_model1 = Button(description='model: apoptosis', disabled=True, layout={'width':'30%'}) death_model1.style.button_color = '#ffde6b' name_btn = Button(description='death rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float589 = FloatText(value='8.9e-4', step='0.0001', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' row = [name_btn, self.float589, units_btn, ] box629 = Box(children=row, layout=box_layout) name_btn = Button(description='unlysed_fluid_change_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float590 = FloatText(value='0.05', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' row = [name_btn, self.float590, units_btn, ] box630 = Box(children=row, layout=box_layout) name_btn = Button(description='lysed_fluid_change_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float591 = FloatText(value='0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' row = [name_btn, self.float591, units_btn, ] box631 = Box(children=row, layout=box_layout) name_btn = Button(description='cytoplasmic_biomass_change_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float592 = FloatText(value='1.66667e-02', step='0.001', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' row = [name_btn, self.float592, units_btn, ] box632 = Box(children=row, layout=box_layout) name_btn = Button(description='nuclear_biomass_change_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float593 = FloatText(value='5.83333e-03', step='0.001', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' row = [name_btn, self.float593, units_btn, ] box633 = Box(children=row, layout=box_layout) name_btn = Button(description='calcification_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float594 = FloatText(value='0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' row = [name_btn, self.float594, units_btn, ] box634 = Box(children=row, layout=box_layout) name_btn = Button(description='relative_rupture_volume', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float595 = FloatText(value='2.0', step='0.1', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' row = [name_btn, self.float595, units_btn, ] box635 = Box(children=row, layout=box_layout) death_model2 = Button(description='model: necrosis', disabled=True, layout={'width':'30%'}) death_model2.style.button_color = '#ffde6b' name_btn = Button(description='death rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float596 = FloatText(value='0.0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' row = [name_btn, self.float596, units_btn, ] box636 = Box(children=row, layout=box_layout) name_btn = Button(description='unlysed_fluid_change_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float597 = FloatText(value='0.05', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' row = [name_btn, self.float597, units_btn, ] box637 = Box(children=row, layout=box_layout) name_btn = Button(description='lysed_fluid_change_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float598 = FloatText(value='0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' row = [name_btn, self.float598, units_btn, ] box638 = Box(children=row, layout=box_layout) name_btn = Button(description='cytoplasmic_biomass_change_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float599 = FloatText(value='1.66667e-02', step='0.001', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' row = [name_btn, self.float599, units_btn, ] box639 = Box(children=row, layout=box_layout) name_btn = Button(description='nuclear_biomass_change_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float600 = FloatText(value='5.83333e-03', step='0.001', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' row = [name_btn, self.float600, units_btn, ] box640 = Box(children=row, layout=box_layout) name_btn = Button(description='calcification_rate', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'lightgreen' self.float601 = FloatText(value='0', step='0.01', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'lightgreen' row = [name_btn, self.float601, units_btn, ] box641 = Box(children=row, layout=box_layout) name_btn = Button(description='relative_rupture_volume', disabled=True, layout=name_button_layout) name_btn.style.button_color = 'tan' self.float602 = FloatText(value='2.0', step='0.1', style=style, layout=widget_layout) units_btn = Button(description='1/min', disabled=True, layout=name_button_layout) units_btn.style.button_color = 'tan' row = [name_btn, self.float602, units_btn, ] box642 = Box(children=row, layout=box_layout) # ------------------------- div_row43 = Button(description='phenotype:volume', disabled=True, layout=divider_button_layout) div_row43.style.button_color = 'orange' name_btn
#!/usr/bin/env python # Copyright (c) 2018, DIANA-HEP # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import codecs import collections import numbers try: from collections.abc import Iterable except ImportError: from collections import Iterable import awkward.array.base import awkward.array.indexed import awkward.array.jagged import awkward.array.masked import awkward.array.objects import awkward.array.table import awkward.array.union import awkward.type import awkward.util def typeof(obj): if obj is None: return None elif isinstance(obj, (bool, awkward.util.numpy.bool_, awkward.util.numpy.bool)): return BoolFillable elif isinstance(obj, (numbers.Number, awkward.util.numpy.number)): return NumberFillable elif isinstance(obj, bytes): return BytesFillable elif isinstance(obj, awkward.util.string): return StringFillable elif isinstance(obj, dict): if any(not isinstance(x, str) for x in obj): raise TypeError("only dicts with str-typed keys may be converted") if len(obj) == 0: return None else: return set(obj) elif isinstance(obj, tuple) and hasattr(obj, "_fields") and obj._fields is type(obj)._fields: return obj._fields, type(obj) elif isinstance(obj, Iterable): return JaggedFillable else: return set(n for n in obj.__dict__ if not n.startswith("_")), type(obj) class Fillable(object): @staticmethod def make(tpe): if tpe is None: return MaskedFillable(UnknownFillable(), 0) elif isinstance(tpe, type): return tpe() elif isinstance(tpe, set): return TableFillable(tpe) elif isinstance(tpe, tuple) and len(tpe) == 2 and isinstance(tpe[0], set): if len(tpe[0]) == 0: return ObjectFillable(JaggedFillable(), tpe[1]) else: return ObjectFillable(TableFillable(tpe[0]), tpe[1]) elif isinstance(tpe, tuple) and len(tpe) == 2 and isinstance(tpe[0], tuple): if len(tpe[0]) == 0: return NamedTupleFillable(JaggedFillable(), tpe[1]) else: return NamedTupleFillable(TableFillable(tpe[0]), tpe[1]) else: raise AssertionError(tpe) def matches(self, tpe): return type(self) is tpe class UnknownFillable(Fillable): __slots__ = ["count"] def __init__(self): self.count = 0 def __len__(self): return self.count def clear(self): self.count = 0 def append(self, obj, tpe): if tpe is None: self.count += 1 return self else: fillable = Fillable.make(tpe) if self.count == 0: return fillable.append(obj, tpe) else: return MaskedFillable(fillable.append(obj, tpe), self.count) def finalize(self, **options): if self.count == 0: return awkward.util.numpy.empty(0, dtype=awkward.array.base.AwkwardArray.DEFAULTTYPE) else: mask = awkward.util.numpy.zeros(self.count, dtype=awkward.array.masked.MaskedArray.MASKTYPE) return awkward.array.masked.MaskedArray(mask, mask, maskedwhen=False) class SimpleFillable(Fillable): __slots__ = ["data"] def __init__(self): self.data = [] def __len__(self): return len(self.data) def clear(self): self.data = [] def append(self, obj, tpe): if tpe is None: return MaskedFillable(self, 0).append(obj, tpe) if self.matches(tpe): self.data.append(obj) return self else: return UnionFillable(self).append(obj, tpe) class BoolFillable(SimpleFillable): def finalize(self, **options): return awkward.util.numpy.array(self.data, dtype=awkward.array.base.AwkwardArray.BOOLTYPE) class NumberFillable(SimpleFillable): def finalize(self, **options): return awkward.util.numpy.array(self.data) class BytesFillable(SimpleFillable): def finalize(self, **options): dictencoding = options.get("dictencoding", False) if (callable(dictencoding) and dictencoding(self.data)) or (not callable(dictencoding) and dictencoding): dictionary, index = awkward.util.numpy.unique(self.data, return_inverse=True) return awkward.array.indexed.IndexedArray(index, awkward.array.objects.StringArray.fromiter(dictionary, encoding=None)) else: return awkward.array.objects.StringArray.fromiter(self.data, encoding=None) class StringFillable(SimpleFillable): def finalize(self, **options): dictencoding = options.get("dictencoding", False) if (callable(dictencoding) and dictencoding(self.data)) or (not callable(dictencoding) and dictencoding): dictionary, index = awkward.util.numpy.unique(self.data, return_inverse=True) return awkward.array.indexed.IndexedArray(index, awkward.array.objects.StringArray.fromiter(dictionary, encoding="utf-8")) else: return awkward.array.objects.StringArray.fromiter(self.data, encoding="utf-8") class JaggedFillable(Fillable): __slots__ = ["content", "offsets"] def __init__(self): self.content = UnknownFillable() self.offsets = [0] def __len__(self): return len(self.offsets) - 1 def clear(self): self.content.clear() self.offsets = [0] def append(self, obj, tpe): if tpe is None: return MaskedFillable(self, 0).append(obj, tpe) if self.matches(tpe): for x in obj: self.content = self.content.append(x, typeof(x)) self.offsets.append(len(self.content)) return self else: return UnionFillable(self).append(obj, tpe) def finalize(self, **options): return awkward.array.jagged.JaggedArray.fromoffsets(self.offsets, self.content.finalize(**options)) class TableFillable(Fillable): __slots__ = ["fields", "contents", "count"] def __init__(self, fields): assert len(fields) > 0 self.fields = fields self.contents = {n: UnknownFillable() for n in fields} self.count = 0 def __len__(self): return self.count def clear(self): for content in self.contents.values(): content.clear() self.count = 0 def matches(self, tpe): return self.fields == tpe def append(self, obj, tpe): if tpe is None: return MaskedFillable(self, 0).append(obj, tpe) if self.matches(tpe): for n in self.fields: x = obj[n] self.contents[n] = self.contents[n].append(x, typeof(x)) self.count += 1 return self else: return UnionFillable(self).append(obj, tpe) def finalize(self, **options): return awkward.array.table.Table.frompairs((n, self.contents[n].finalize(**options)) for n in sorted(self.fields)) class ObjectFillable(Fillable): __slots__ = ["content", "cls"] def __init__(self, content, cls): self.content = content self.cls = cls def __len__(self): return len(self.content) def clear(self): self.content.clear() def matches(self, tpe): return isinstance(tpe, tuple) and len(tpe) == 2 and tpe[1] is self.cls and (len(tpe[0]) == 0 or self.content.matches(tpe[0])) def append(self, obj, tpe): if tpe is None: return MaskedFillable(self, 0).append(obj, tpe) if self.matches(tpe): if len(tpe[0]) == 0: self.content.append([], JaggedFillable) else: self.content.append(obj.__dict__, tpe[0]) return self else: return UnionFillable(self).append(obj, tpe) def finalize(self, **options): def make(x): out = self.cls.__new__(self.cls) out.__dict__.update(x.tolist()) return out return awkward.array.objects.ObjectArray(self.content.finalize(**options), make) class NamedTupleFillable(ObjectFillable): def append(self, obj, tpe): if tpe is None: return MaskedFillable(self, 0).append(obj, tpe) if self.matches(tpe): if len(tpe[0]) == 0: self.content.append([], JaggedFillable) else: self.content.append({n: x for n, x in zip(obj._fields, obj)}, tpe[0]) return self else: return UnionFillable(self).append(obj, tpe) def finalize(self, **options): def make(x): asdict = x.tolist() return self.cls(*[asdict[n] for n in self.cls._fields]) return awkward.array.objects.ObjectArray(self.content.finalize(**options), make) class MaskedFillable(Fillable): __slots__ = ["content", "nullpos"] def __init__(self, content, count): self.content = content self.nullpos = list(range(count)) def matches(self, tpe): return tpe is None def __len__(self): return len(self.content) + len(self.nullpos) def clear(self): self.content.clear() self.nullpos = [] def append(self, obj, tpe): if tpe is None: self.nullpos.append(len(self)) else: self.content = self.content.append(obj, tpe) return self def finalize(self, **options): if isinstance(self.content, (TableFillable, ObjectFillable, UnionFillable)): index = awkward.util.numpy.zeros(len(self), dtype=awkward.array.masked.IndexedMaskedArray.INDEXTYPE) index[self.nullpos] = -1 index[index == 0] = awkward.util.numpy.arange(len(self.content)) return awkward.array.masked.IndexedMaskedArray(index, self.content.finalize(**options)) valid = awkward.util.numpy.ones(len(self), dtype=awkward.array.masked.MaskedArray.MASKTYPE) valid[self.nullpos] = False if isinstance(self.content, (BoolFillable, NumberFillable)): compact = self.content.finalize(**options) expanded = awkward.util.numpy.empty(len(self), dtype=compact.dtype) expanded[valid] = compact return awkward.array.masked.MaskedArray(valid, expanded, maskedwhen=False) elif isinstance(self.content, (BytesFillable, StringFillable)): compact = self.content.finalize(**options) if isinstance(compact, awkward.array.indexed.IndexedArray): index = awkward.util.numpy.zeros(len(self), dtype=compact.index.dtype) index[valid] = compact.index expanded = awkward.array.indexed.IndexedArray(index, compact.content) else: counts = awkward.util.numpy.zeros(len(self), dtype=compact.counts.dtype) counts[valid] = compact.counts expanded = awkward.array.objects.StringArray.fromcounts(counts, compact.content, encoding=compact.encoding) return awkward.array.masked.MaskedArray(valid, expanded, maskedwhen=False) elif isinstance(self.content, JaggedFillable): compact = self.content.finalize(**options) counts = awkward.util.numpy.zeros(len(self), dtype=compact.counts.dtype) counts[valid] = compact.counts expanded = awkward.array.jagged.JaggedArray.fromcounts(counts, compact.content) return awkward.array.masked.MaskedArray(valid, expanded, maskedwhen=False) else: raise AssertionError(self.content) class UnionFillable(Fillable): __slots__ = ["contents", "tags", "index"] def __init__(self, content): self.contents = [content] self.tags = [0] * len(content) self.index = list(range(len(content))) def __len__(self): return len(self.tags) def clear(self): for content in self.contents: content.clear() self.tags = [] self.index = [] def append(self, obj, tpe): if tpe is None: return MaskedFillable(self, 0).append(obj, tpe) else: for tag, content in enumerate(self.contents): if content.matches(tpe): self.tags.append(tag) self.index.append(len(content)) content.append(obj, tpe) break else: fillable = Fillable.make(tpe) self.tags.append(len(self.contents)) self.index.append(len(fillable)) self.contents.append(fillable.append(obj, tpe)) return self def finalize(self, **options): return awkward.array.union.UnionArray(self.tags, self.index, [x.finalize(**options) for x in self.contents]) def _checkoptions(options): unrecognized = set(options).difference(["dictencoding"]) if len(unrecognized) != 0: raise TypeError("unrecognized options: {0}".format(", ".join(sorted(unrecognized)))) def fromiter(iterable, **options): _checkoptions(options) fillable = UnknownFillable() for obj in iterable: fillable = fillable.append(obj, typeof(obj)) return fillable.finalize(**options) def fromiterchunks(iterable, chunksize, **options): if not isinstance(chunksize, (numbers.Integral, awkward.util.numpy.integer)) or chunksize <= 0: raise TypeError("chunksize must be a positive integer") _checkoptions(options) fillable = UnknownFillable() count = 0 tpe = None for obj in iterable: fillable = fillable.append(obj, typeof(obj)) count += 1 if count == chunksize: out = fillable.finalize(**options) outtpe = awkward.type.fromarray(out).to if tpe is None: tpe = outtpe elif tpe != outtpe: raise TypeError("data type has changed after the first chunk (first chunk is not large enough to see the full generality of the data):\n\n{0}\n\nversus\n\n{1}".format(awkward.type._str(tpe, indent=" "), awkward.type._str(outtpe, indent=" "))) yield out fillable.clear() count = 0 if count != 0: out = fillable.finalize(**options) outtpe = awkward.type.fromarray(out).to if tpe is None: tpe = outtpe elif tpe != outtpe: raise TypeError("data type has changed after the first chunk (first chunk
provided. Note that this is a folder name, not a path, defaults to 'None' :type m1_val_images_folder: str, optional :param m2_val_images_folder: Folder name that contains the validation images for the second modality. This folder should be contained in the dataset path provided. Note that this is a folder name, not a path, defaults to 'None' :return: Returns stats regarding the last evaluation ran. :rtype: dict """ dataset_location = os.path.join(self.datasetargs.dataset_root, self.datasetargs.dataset_name) if m1_train_edataset is None: m1_train_edataset = ExternalDataset(dataset_location, 'coco') if m2_train_edataset is None: m2_train_edataset = ExternalDataset(dataset_location, 'coco') if m1_val_edataset is None: m1_val_edataset = ExternalDataset(dataset_location, 'coco') if m2_val_edataset is None: m2_val_edataset = ExternalDataset(dataset_location, 'coco') if annotations_folder is None: annotations_folder = self.datasetargs.annotations_folder if m1_train_annotations_file is None: m1_train_annotations_file = self.datasetargs.m1_train_annotations_file if m2_train_annotations_file is None: m2_train_annotations_file = self.datasetargs.m2_train_annotations_file if m1_train_images_folder is None: m1_train_images_folder = self.datasetargs.m1_train_images_folder if m2_train_images_folder is None: m2_train_images_folder = self.datasetargs.m2_train_images_folder if m1_val_annotations_file is None: m1_val_annotations_file = self.datasetargs.m1_val_annotations_file if m2_val_annotations_file is None: m2_val_annotations_file = self.datasetargs.m2_val_annotations_file if m1_val_images_folder is None: m1_val_images_folder = self.datasetargs.m1_val_images_folder if m2_val_images_folder is None: m2_val_images_folder = self.datasetargs.m2_val_images_folder if silent: verbose = False train_stats = {} test_stats = {} coco_evaluator = None if trial_dir is not None: output_dir = os.path.join(out_dir, trial_dir) if not os.path.exists(output_dir): os.makedirs(output_dir) else: current_time = datetime.datetime.now().strftime("%m-%d-%Y-%H-%M-%S") output_dir = os.path.join(out_dir, trial_dir + '_' + current_time) os.makedirs(output_dir) if logging_path != '' and logging_path is not None: logging = True if not os.path.exists(logging_path): os.mkdir(logging_path) writer = SummaryWriter(logging_path) else: logging = False writer = None if self.model is None: self.__create_model() if not silent and verbose: print('number of params:', self.n_parameters) if self.postprocessors is None: self.__create_postprocessors() self.__create_criterion() self.__create_optimizer() self.__create_scheduler() if self.args.frozen_weights is not None: checkpoint = torch.load(self.args.frozen_weights, map_location=self.device) self.model_without_ddp.detr.load_state_dict(checkpoint['model']) if self.checkpoint_load_iter != 0: checkpoint = output_dir / f'checkpoint{self.checkpoint_load_iter:04}.pth' self.__load_checkpoint(checkpoint) if not silent: print("Loaded" + f'checkpoint{self.checkpoint_load_iter:04}.pth') device = torch.device(self.device) m1_dataset_train = self.__prepare_dataset( m1_train_edataset, image_set="m1_train", images_folder_name=m1_train_images_folder, annotations_folder_name=annotations_folder, annotations_file_name=m1_train_annotations_file ) train_seed = m1_dataset_train.set_seed() m1_sampler_train_main = RandomSampler(m1_dataset_train) m1_sampler_seed = m1_sampler_train_main.set_seed() m2_dataset_train = self.__prepare_dataset( m2_train_edataset, image_set="m2_train", images_folder_name=m2_train_images_folder, annotations_folder_name=annotations_folder, annotations_file_name=m2_train_annotations_file, seed=train_seed ) m2_sampler_train_main = RandomSampler(m2_dataset_train, m1_sampler_seed) if m1_val_edataset is not None and m2_val_edataset is not None: m1_dataset_val = self.__prepare_dataset( m1_val_edataset, image_set="m1_val", images_folder_name=m1_val_images_folder, annotations_folder_name=annotations_folder, annotations_file_name=m1_val_annotations_file ) m1_sampler_val_main = SequentialSampler(m1_dataset_val) val_seed = m1_dataset_val.set_seed() m2_dataset_val = self.__prepare_dataset( m2_val_edataset, image_set="m2_val", images_folder_name=m2_val_images_folder, annotations_folder_name=annotations_folder, annotations_file_name=m2_val_annotations_file, seed=val_seed ) if not self.args.distributed: m1_sampler_train = m1_sampler_train_main m2_sampler_train = m2_sampler_train_main if m1_val_edataset is not None and m2_val_edataset is not None: m1_sampler_val = m1_sampler_val_main else: m1_sampler_train = DistributedSamplerWrapper(m1_sampler_train_main) m2_sampler_train = DistributedSamplerWrapper(m2_sampler_train_main) if m1_val_edataset is not None and m2_val_edataset is not None: m1_sampler_val = DistributedSamplerWrapper(m1_sampler_val_main) # Starting from here, code has been modified from https://github.com/facebookresearch/detr/blob/master/main.py m1_batch_sampler_train = torch.utils.data.BatchSampler( m1_sampler_train, self.batch_size, drop_last=True) m2_batch_sampler_train = torch.utils.data.BatchSampler( m2_sampler_train, self.batch_size, drop_last=True) m1_data_loader_train = DataLoader( m1_dataset_train, batch_sampler=m1_batch_sampler_train, collate_fn=utils.collate_fn, num_workers=self.args.num_workers ) m2_data_loader_train = DataLoader( m2_dataset_train, batch_sampler=m2_batch_sampler_train, collate_fn=utils.collate_fn, num_workers=self.args.num_workers ) if m1_val_edataset is not None and m2_val_edataset is not None: m1_data_loader_val = DataLoader( m1_dataset_val, self.batch_size, sampler=m1_sampler_val, drop_last=False, collate_fn=utils.collate_fn, num_workers=self.args.num_workers ) base_ds = get_coco_api_from_dataset(m1_dataset_val) if not silent: print("Start training") start_time = time.time() for self.epoch in range(self.checkpoint_load_iter, self.iters): train_stats = train_one_epoch( self.model, self.criterion, m1_data_loader_train, m2_data_loader_train, self.torch_optimizer, device, self.epoch, self.args.clip_max_norm, # verbose=verbose, silent=silent ) self.lr_scheduler.step() checkpoint_paths = [os.path.join(output_dir, 'checkpoint.pth')] # extra checkpoint every checkpoint_after_iter epochs if self.checkpoint_after_iter != 0 and (self.epoch + 1) % self.checkpoint_after_iter == 0: checkpoint_paths.append(output_dir / f'checkpoint{self.epoch:04}.pth') for checkpoint_path in checkpoint_paths: utils.save_on_master({ 'model': self.model_without_ddp.state_dict(), 'optimizer': self.torch_optimizer.state_dict(), 'lr_scheduler': self.lr_scheduler.state_dict(), 'epoch': self.epoch, 'args': self.args, }, checkpoint_path) if m1_val_edataset is not None: test_stats, coco_evaluator = evaluate( self.model, self.criterion, self.postprocessors, m1_data_loader_val, m1_data_loader_val, base_ds, device, self.temp_path, verbose=verbose, silent=silent) if logging: for k, v in train_stats.items(): if isinstance(v, list): v = v[0] writer.add_scalar(f'train_{k}', v, self.epoch + 1) if m1_val_edataset is not None: for k, v in test_stats.items(): if isinstance(v, list): v = v[0] writer.add_scalar(f'test_{k}', v, self.epoch + 1) new_train_seed = m1_dataset_train.set_seed() m2_dataset_train.set_seed(new_train_seed) if m1_val_edataset is not None and m2_val_edataset is not None: new_val_seed = m1_dataset_val.set_seed() m2_dataset_val.set_seed(new_val_seed) total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) if logging: writer.close() if not silent: print('Training time {}'.format(total_time_str)) if m1_val_edataset is not None: return {"train_stats": train_stats, "test_stats": test_stats} return train_stats def eval(self, m1_edataset=None, m2_edataset=None, m1_images_folder='m1_val2017', m2_images_folder='m2_val2017', annotations_folder='Annotations', m1_annotations_file='m1_instances_val2017.json', m2_annotations_file='m2_instances_val2017.json', verbose=True, ): """ This method is used to evaluate a trained model on an evaluation dataset. :param m1_edataset: Object that holds the evaluation dataset for the first modality, defaults to 'None' :type m1_edataset: ExternalDataset class object or DatasetIterator class object, optional :param m2_edataset: Object that holds the evaluation dataset for the second modality, defaults to 'None' :type m2_edataset: ExternalDataset class object or DatasetIterator class object, optional :param m1_images_folder: Folder name that contains the dataset images for the first modality. This folder should be contained in the dataset path provided. Note that this is a folder name, not a path, defaults to 'm1_val2017' :type m1_images_folder: str, optional :param m2_images_folder: Folder name that contains the dataset images for the second modality. This folder should be contained in the dataset path provided. Note that this is a folder name, not a path, defaults to 'm2_val2017' :type m2_images_folder: str, optional :param annotations_folder: Folder name of the annotations json file. This file should be contained in the dataset path provided, defaults to 'Annotations' :type annotations_folder: str, optional :param m1_annotations_file: Filename of the annotations json file for the first modality. This file should be contained in the dataset path provided, defaults to 'm1_instances_val2017' :type m1_annotations_file: str, optional :param m2_annotations_file: Filename of the annotations json file for the second modality. This file should be contained in the dataset path provided, defaults to 'm2_instances_val2017 :type m2_annotations_file: str, optional :param verbose: If 'True', maximum verbosity is enabled, defaults to 'True' :type verbose: bool, optional :return: Returns stats regarding evaluation. :rtype: dict """ if self.model is None: raise UserWarning('A model should be loaded first') dataset_location = os.path.join(self.datasetargs.dataset_root, self.datasetargs.dataset_name) if m1_edataset is None: m1_edataset = ExternalDataset(dataset_location, 'coco') if m2_edataset is None: m2_edataset = ExternalDataset(dataset_location, 'coco') if annotations_folder is None: annotations_folder = self.datasetargs.annotations_folder if m1_annotations_file is None: m1_annotations_file = self.datasetargs.m1_val_annotations_file if m2_annotations_file is None: m2_annotations_file = self.datasetargs.m2_val_annotations_file if m1_images_folder is None: m1_images_folder = self.datasetargs.m1_val_images_folder if m2_images_folder is None: m2_images_folder = self.datasetargs.m2_val_images_folder if self.postprocessors is None: self.__create_postprocessors() self.__create_criterion() device = torch.device(self.device) m1_dataset = self.__prepare_dataset( m1_edataset, image_set="m1_val", images_folder_name=m1_images_folder, annotations_folder_name=annotations_folder, annotations_file_name=m1_annotations_file ) m1_sampler_main = SequentialSampler(m1_dataset) m1_eval_seed = m1_dataset.set_seed() m2_dataset = self.__prepare_dataset( m2_edataset, image_set="m2_val", images_folder_name=m2_images_folder, annotations_folder_name=annotations_folder, annotations_file_name=m2_annotations_file, seed=m1_eval_seed ) m2_sampler_main = SequentialSampler(m2_dataset) if not self.args.distributed: m1_sampler = m1_sampler_main m2_sampler = m2_sampler_main else: m1_sampler = DistributedSamplerWrapper(m1_sampler_main) m2_sampler = DistributedSamplerWrapper(m2_sampler_main) m1_data_loader = DataLoader( m1_dataset, self.batch_size, sampler=m1_sampler, drop_last=False, collate_fn=utils.collate_fn, num_workers=self.args.num_workers ) m2_data_loader = DataLoader( m2_dataset, self.batch_size, sampler=m2_sampler, drop_last=False, collate_fn=utils.collate_fn, num_workers=self.args.num_workers ) if isinstance(m1_edataset, ExternalDataset): base_ds = get_coco_api_from_dataset(m1_dataset) else: base_ds = None test_stats, _ = evaluate( self.model, self.criterion, self.postprocessors, m1_data_loader, m2_data_loader, base_ds, device, self.temp_path, verbose=verbose ) return test_stats def infer(self, m1_image, m2_image): """ This method is used to perform object detection on two images with different modalities. :param m1_image: Image from the first modality to run inference on :type m1_image: engine.data.Image class object or numpy.ndarray :param m2_image: Image from the second modality to run inference on :type m2_image: engine.data.Image class object or numpy.ndarray :return: Bounding box list, first modality weight, second modality weight :rtype: engine.target.BoundingBoxList, float, float """ if not (isinstance(m1_image, Image) or isinstance(m2_image, Image)): m1_image = Image(m1_image) m2_image = Image(m2_image) m1_img = im.fromarray(m1_image.convert("channels_last", "rgb")) m2_img = im.fromarray(m2_image.convert("channels_last", "rgb")) scores, boxes, segmentations, contrib = detect(m1_img, m2_img, self.infer_transform, self.model, self.postprocessors, self.device, self.threshold, self.ort_session, ) weight1 = contrib[0].data weight1 = weight1.cpu().detach().numpy() weight2 = contrib[1].data weight2 = weight2.cpu().detach().numpy() normed_weight1 = weight1 / (weight1 + weight2) normed_weight2 = weight2 / (weight1 + weight2) boxlist = [] if len(segmentations) == len(scores): for p, (xmin, ymin, xmax, ymax), segmentation in zip(scores.tolist(), boxes.tolist(), segmentations): cl = np.argmax(p) box = CocoBoundingBox(cl, xmin, ymin, xmax - xmin, ymax - ymin, score=p[cl], segmentation=segmentation) boxlist.append(box) else: for p, (xmin, ymin, xmax, ymax) in zip(scores.tolist(), boxes.tolist()): cl = np.argmax(p) box = CocoBoundingBox(cl, xmin, ymin, xmax - xmin, ymax - ymin, score=p[cl]) boxlist.append(box) return BoundingBoxList(boxlist), normed_weight1, normed_weight2 def optimize(self): """This method is not used in this implementation.""" return NotImplementedError def reset(self): """This method is not used in this implementation.""" return NotImplementedError def download(self, path=None, mode="pretrained_gem", verbose=False): """
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from builtins import object import datetime import sys from django_auth_ldap import backend as django_auth_ldap_backend from django.db.utils import DataError from django.conf import settings from django.test.client import Client from nose.plugins.skip import SkipTest from nose.tools import assert_true, assert_false, assert_equal, assert_raises from hadoop.test_base import PseudoHdfsTestBase from hadoop import pseudo_hdfs4 from useradmin import ldap_access from useradmin.models import get_default_user_group, User, Group, get_profile from useradmin.tests import LdapTestConnection from useradmin.views import import_ldap_groups from desktop import conf, middleware from desktop.auth import backend from desktop.auth.backend import create_user from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import add_to_group if sys.version_info[0] > 2: from unittest.mock import patch, Mock, MagicMock else: from mock import patch, Mock, MagicMock def get_mocked_config(): return { 'mocked_ldap': { 'users': {}, 'groups': {} } } class TestLoginWithHadoop(PseudoHdfsTestBase): integration = True reset = [] test_username = 'test_login_with_hadoop' @classmethod def setup_class(cls): # Simulate first login ever User.objects.all().delete() PseudoHdfsTestBase.setup_class() cls.auth_backends = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = ('desktop.auth.backend.AllowFirstUserDjangoBackend',) @classmethod def teardown_class(cls): settings.AUTHENTICATION_BACKENDS = cls.auth_backends def setUp(self): self.c = Client() self.reset.append( conf.AUTH.BACKEND.set_for_testing(['desktop.auth.backend.AllowFirstUserDjangoBackend']) ) self.reset.append(conf.LDAP.SYNC_GROUPS_ON_LOGIN.set_for_testing(False)) def tearDown(self): User.objects.all().delete() for finish in self.reset: finish() if self.cluster.fs.do_as_user(self.test_username, self.cluster.fs.exists, "/user/%s" % self.test_username): self.cluster.fs.do_as_superuser(self.cluster.fs.rmtree, "/user/%s" % self.test_username) def test_login(self): response = self.c.get('/hue/accounts/login/') assert_equal(200, response.status_code, "Expected ok status.") assert_true(response.context[0]['first_login_ever']) response = self.c.post('/hue/accounts/login/', dict(username=self.test_username, password="<PASSWORD>")) assert_equal(302, response.status_code, "Expected ok redirect status.") assert_equal(response.url, "/") assert_true(self.cluster.fs.do_as_user(self.test_username, self.fs.exists, "/user/%s" % self.test_username)) def test_login_old(self): response = self.c.get('/accounts/login/') assert_equal(200, response.status_code, "Expected ok status.") assert_true(response.context[0]['first_login_ever']) response = self.c.post('/accounts/login/', dict(username=self.test_username, password="<PASSWORD>"), follow=True) assert_equal(200, response.status_code, "Expected ok status.") assert_true(self.cluster.fs.do_as_user(self.test_username, self.fs.exists, "/user/%s" % self.test_username)) response = self.c.get('/accounts/login/') assert_equal(302, response.status_code, "Expected ok redirect status.") assert_equal(response.url, "/") def test_login_home_creation_failure(self): response = self.c.get('/hue/accounts/login/') assert_equal(200, response.status_code, "Expected ok status.") assert_true(response.context[0]['first_login_ever']) # Create home directory as a file in order to fail in the home creation later cluster = pseudo_hdfs4.shared_cluster() fs = cluster.fs assert_false(cluster.fs.exists("/user/%s" % self.test_username)) fs.do_as_superuser(fs.create, "/user/%s" % self.test_username) response = self.c.post('/hue/accounts/login/', { 'username': self.test_username, 'password': "<PASSWORD>", }, follow=True) assert_equal(200, response.status_code, "Expected ok status.") assert_true('/about' in response.content, response.content) # Custom login process should not do 'http-equiv="refresh"' but call the correct view # 'Could not create home directory.' won't show up because the messages are consumed before def test_login_expiration(self): response = self.c.post('/hue/accounts/login/', { 'username': self.test_username, 'password': "<PASSWORD>", }, follow=True) assert_equal(200, response.status_code, "Expected ok status.") self.reset.append(conf.AUTH.EXPIRES_AFTER.set_for_testing(10000)) user = User.objects.get(username=self.test_username) user.last_login = datetime.datetime.now() + datetime.timedelta(days=-365) user.save() # Deactivate user old_settings = settings.ADMINS settings.ADMINS = [] response = self.c.post('/hue/accounts/login/', { 'username': self.test_username, 'password': "<PASSWORD>", }, follow=True) assert_equal(200, response.status_code, "Expected ok status.") assert_true("Account deactivated. Please contact an administrator." in response.content, response.content) settings.ADMINS = old_settings # Activate user user = User.objects.get(username=self.test_username) user.is_active = True user.save() response = self.c.post('/hue/accounts/login/', dict(username=self.test_username, password="<PASSWORD>")) assert_equal(200, response.status_code, "Expected ok status.") class TestLdapLogin(PseudoHdfsTestBase): reset = [] test_username = 'test_ldap_login' @classmethod def setup_class(cls): # Simulate first login ever User.objects.all().delete() PseudoHdfsTestBase.setup_class() cls.ldap_backend = django_auth_ldap_backend.LDAPBackend django_auth_ldap_backend.LDAPBackend = MockLdapBackend # Override auth backend, settings are only loaded from conf at initialization so we can't use set_for_testing cls.auth_backends = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = ('desktop.auth.backend.LdapBackend',) # Need to recreate LdapBackend class with new monkey patched base class reload(backend) @classmethod def teardown_class(cls): django_auth_ldap_backend.LDAPBackend = cls.ldap_backend settings.AUTHENTICATION_BACKENDS = cls.auth_backends reload(backend) def setUp(self): self.c = Client() self.reset.append( conf.AUTH.BACKEND.set_for_testing(['desktop.auth.backend.LdapBackend']) ) self.reset.append(conf.LDAP.LDAP_URL.set_for_testing('does not matter')) self.reset.append(conf.LDAP.SYNC_GROUPS_ON_LOGIN.set_for_testing(False)) def tearDown(self): User.objects.all().delete() for finish in self.reset: finish() if self.cluster.fs.do_as_user(self.test_username, self.cluster.fs.exists, "/user/%s" % self.test_username): self.cluster.fs.do_as_superuser(self.cluster.fs.rmtree, "/user/%s" % self.test_username) if self.cluster.fs.do_as_user("curly", self.cluster.fs.exists, "/user/curly"): self.cluster.fs.do_as_superuser(self.cluster.fs.rmtree, "/user/curly") def test_login(self): response = self.c.get('/hue/accounts/login/') assert_equal(200, response.status_code, "Expected ok status.") assert_false(response.context[0]['first_login_ever']) response = self.c.post('/hue/accounts/login/', { 'username': self.test_username, 'password': "<PASSWORD>", 'server': "LDAP" }) assert_equal(302, response.status_code, "Expected ok redirect status.") assert_equal(response.url, "/") assert_true(self.cluster.fs.do_as_user(self.test_username, self.fs.exists, "/user/%s" % self.test_username)) def test_login_failure_for_bad_username(self): self.reset.append(conf.LDAP.LDAP_SERVERS.set_for_testing(get_mocked_config())) response = self.c.get('/hue/accounts/login/') assert_equal(200, response.status_code, "Expected ok status.") response = self.c.post('/hue/accounts/login/', dict(username="test1*)(&(objectClass=*)", password="<PASSWORD>")) assert_equal(200, response.status_code, "Expected ok status.") assert_true('Invalid username or password' in response.content, response) def test_login_does_not_reset_groups(self): client = make_logged_in_client(username=self.test_username, password="<PASSWORD>") user = User.objects.get(username=self.test_username) test_group, created = Group.objects.get_or_create(name=self.test_username) default_group = get_default_user_group() user.groups.all().delete() assert_false(user.groups.exists()) # No groups response = client.post('/hue/accounts/login/', dict(username=self.test_username, password="<PASSWORD>"), follow=True) assert_equal(200, response.status_code, "Expected ok status.") assert_equal([default_group.name], [i for i in user.groups.values_list('name', flat=True)]) add_to_group(self.test_username, self.test_username) # Two groups client.get('/accounts/logout') response = client.post('/hue/accounts/login/', dict(username=self.test_username, password="<PASSWORD>"), follow=True) assert_equal(200, response.status_code, "Expected ok status.") assert_equal(set([default_group.name, test_group.name]), set(user.groups.values_list('name', flat=True))) user.groups.filter(name=default_group.name).delete() assert_equal(set([test_group.name]), set(user.groups.values_list('name', flat=True))) # Keep manual group only, don't re-add default group client.get('/accounts/logout') response = client.post('/hue/accounts/login/', dict(username=self.test_username, password="<PASSWORD>"), follow=True) assert_equal(200, response.status_code, "Expected ok status.") assert_equal([test_group.name], list(user.groups.values_list('name', flat=True))) user.groups.remove(test_group) assert_false(user.groups.exists()) # Re-add default group client.get('/accounts/logout') response = client.post('/hue/accounts/login/', dict(username=self.test_username, password="<PASSWORD>"), follow=True) assert_equal(200, response.status_code, "Expected ok status.") assert_equal([default_group.name], list(user.groups.values_list('name', flat=True))) def test_login_home_creation_failure(self): response = self.c.get('/hue/accounts/login/') assert_equal(200, response.status_code, "Expected ok status.") assert_false(response.context[0]['first_login_ever']) # Create home directory as a file in order to fail in the home creation later cluster = pseudo_hdfs4.shared_cluster() fs = cluster.fs assert_false(self.cluster.fs.do_as_user(self.test_username, cluster.fs.exists, "/user/%s" % self.test_username)) fs.do_as_superuser(fs.create, "/user/%s" % self.test_username) response = self.c.post('/hue/accounts/login/', { 'username': self.test_username, 'password': "<PASSWORD>", 'server': "LDAP" }, follow=True) assert_equal(200, response.status_code, "Expected ok status.") assert_true('/about' in response.content, response.content) # Custom login process should not do 'http-equiv="refresh"' but call the correct view # 'Could not create home directory.' won't show up because the messages are consumed before def test_login_ignore_case(self): self.reset.append(conf.LDAP.IGNORE_USERNAME_CASE.set_for_testing(True)) response = self.c.post('/hue/accounts/login/', { 'username': self.test_username.upper(), 'password': "<PASSWORD>", 'server': "LDAP" }) assert_equal(302, response.status_code, "Expected ok redirect status.") assert_equal(1, len(User.objects.all())) assert_equal(self.test_username, User.objects.all()[0].username) self.c.logout() response = self.c.post('/hue/accounts/login/', { 'username': self.test_username, 'password': "<PASSWORD>", 'server': "LDAP" }) assert_equal(302, response.status_code, "Expected ok redirect status.") assert_equal(1, len(User.objects.all())) assert_equal(self.test_username, User.objects.all()[0].username) def test_login_force_lower_case(self): self.reset.append(conf.LDAP.FORCE_USERNAME_LOWERCASE.set_for_testing(True)) response = self.c.post('/hue/accounts/login/', { 'username': self.test_username.upper(), 'password': "<PASSWORD>", 'server': "LDAP" }) assert_equal(302, response.status_code, "Expected ok redirect status.") assert_equal(1, len(User.objects.all())) self.c.logout() response = self.c.post('/hue/accounts/login/', { 'username': self.test_username, 'password': "<PASSWORD>", 'server': "LDAP" }) assert_equal(302, response.status_code, "Expected ok redirect status.") assert_equal(1, len(User.objects.all())) assert_equal(self.test_username, User.objects.all()[0].username) def test_login_force_lower_case_and_ignore_case(self): self.reset.append(conf.LDAP.IGNORE_USERNAME_CASE.set_for_testing(True)) self.reset.append(conf.LDAP.FORCE_USERNAME_LOWERCASE.set_for_testing(True)) response = self.c.post('/hue/accounts/login/', { 'username': self.test_username.upper(), 'password': "<PASSWORD>", 'server': "LDAP" }) assert_equal(302, response.status_code, "Expected ok redirect status.") assert_equal(1, len(User.objects.all())) assert_equal(self.test_username, User.objects.all()[0].username) self.c.logout() response = self.c.post('/hue/accounts/login/', { 'username': self.test_username, 'password': "<PASSWORD>", 'server': "LDAP" }) assert_equal(302, response.status_code, "Expected ok redirect status.") assert_equal(1, len(User.objects.all())) assert_equal(self.test_username, User.objects.all()[0].username) def test_import_groups_on_login(self): self.reset.append(conf.LDAP.SYNC_GROUPS_ON_LOGIN.set_for_testing(True)) ldap_access.CACHED_LDAP_CONN = LdapTestConnection() # Make sure LDAP groups exist or they won't sync import_ldap_groups(ldap_access.CACHED_LDAP_CONN, 'TestUsers', import_members=False, import_members_recursive=False, sync_users=False, import_by_dn=False) import_ldap_groups(ldap_access.CACHED_LDAP_CONN, 'Test Administrators', import_members=False, import_members_recursive=False, sync_users=False, import_by_dn=False) response = self.c.post('/hue/accounts/login/', { 'username': "curly", 'password': "<PASSWORD>", 'server': "TestUsers" }) assert_equal(302, response.status_code, response.status_code) assert_equal(1, len(User.objects.all())) # The two curly are a part of in LDAP and the default group. assert_equal(3, User.objects.all()[0].groups.all().count(), User.objects.all()[0].groups.all()) class TestRemoteUserLogin(PseudoHdfsTestBase): reset = [] test_username = "test_remote_user_login" @classmethod def setup_class(cls): # Simulate first login ever User.objects.all().delete() PseudoHdfsTestBase.setup_class() cls.auth_backends = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = ('desktop.auth.backend.RemoteUserDjangoBackend',) cls.remote_user_middleware_header = middleware.HueRemoteUserMiddleware.header middleware.HueRemoteUserMiddleware.header = conf.AUTH.REMOTE_USER_HEADER.get() @classmethod def teardown_class(cls): middleware.HueRemoteUserMiddleware.header = cls.remote_user_middleware_header settings.AUTHENTICATION_BACKENDS = cls.auth_backends def setUp(self): self.reset.append( conf.AUTH.BACKEND.set_for_testing(['desktop.auth.backend.RemoteUserDjangoBackend']) ) self.reset.append( conf.AUTH.REMOTE_USER_HEADER.set_for_testing('REMOTE_USER') ) # Set for middleware self.c = Client() def tearDown(self): for finish in self.reset: finish() User.objects.all().delete() if self.cluster.fs.do_as_user(self.test_username, self.fs.exists, "/user/%s" % self.test_username): self.cluster.fs.do_as_superuser(self.cluster.fs.rmtree, "/user/%s" % self.test_username) if self.cluster.fs.do_as_user(self.test_username, self.fs.exists, "/user/%s_%s" % (self.test_username, '2')): self.cluster.fs.do_as_superuser(self.cluster.fs.rmtree, "/user/%s_%s" % (self.test_username, '2')) def test_normal(self): response = self.c.get('/hue/accounts/login/') assert_equal(200, response.status_code, "Expected ok status.") assert_false(response.context[0]['first_login_ever']) assert_equal(0, len(User.objects.all())) response = self.c.post('/hue/accounts/login/', {}, **{"REMOTE_USER": self.test_username}) assert_equal(200, response.status_code, "Expected ok status.") assert_equal(1, len(User.objects.all())) assert_equal(self.test_username, User.objects.all()[0].username) def test_ignore_case(self): self.reset.append( conf.AUTH.IGNORE_USERNAME_CASE.set_for_testing(True) ) response = self.c.get('/hue/accounts/login/') assert_equal(200, response.status_code, "Expected ok status.") assert_false(response.context[0]['first_login_ever']) response = self.c.post('/hue/accounts/login/', {}, **{"REMOTE_USER": self.test_username}) assert_equal(200, response.status_code, "Expected ok status.") assert_equal(1, len(User.objects.all())) assert_equal(self.test_username, User.objects.all()[0].username) response = self.c.post('/hue/accounts/login/', {}, **{"REMOTE_USER": self.test_username.upper()}) assert_equal(200, response.status_code, "Expected ok status.") assert_equal(1, len(User.objects.all())) assert_equal(self.test_username, User.objects.all()[0].username) response = self.c.post('/hue/accounts/login/', {}, **{"REMOTE_USER": "%s_%s" % (self.test_username.upper(), '2')}) assert_equal(200, response.status_code, "Expected ok status.") assert_equal(2, len(User.objects.all().order_by('username'))) assert_equal("%s_%s" % (self.test_username, '2'), User.objects.all().order_by('username')[1].username) response = self.c.post('/hue/accounts/login/', {}, **{"REMOTE_USER": "%s_%s" % (self.test_username, '2')}) assert_equal(200, response.status_code, "Expected ok status.") assert_equal(2, len(User.objects.all())) assert_equal("%s_%s" % (self.test_username, '2'), User.objects.all().order_by('username')[1].username) def test_force_lower_case(self): self.reset.append( conf.AUTH.FORCE_USERNAME_LOWERCASE.set_for_testing(True) ) response = self.c.get('/hue/accounts/login/') assert_equal(200, response.status_code, "Expected ok status.") assert_false(response.context[0]['first_login_ever']) response = self.c.post('/hue/accounts/login/', {},
show_docx(self, event): self.docx_frame.setVisible(True) self.docx_frame.toFront() self.docx_frame.setAlwaysOnTop(True) def create_summary(self): self.summary_frame = JFrame("Summary") self.summary_frame.setLayout(BorderLayout()) self.summary_frame.setSize(800, 600) self.summary_frame.setLocationRelativeTo(None) colNames = ("Index", "Report?", "Issue type", "Host", "Unique endpoint" ) c = GridBagConstraints() c.gridx = 0 c.gridy = 0 c.weightx = 1 c.weighty = 1 c.fill = GridBagConstraints.BOTH self.unique_endpoints_summary_model = SummaryTableModel([[123,False,"asdfl", "qewr", "zxcv"]], colNames) summary_unique_table = JTable(self.unique_endpoints_summary_model) c.fill = GridBagConstraints.HORIZONTAL c.gridy += 1 c.fill = GridBagConstraints.BOTH c.gridy += 1 self.all_endpoints_summary_model = SummaryTableModel([[234,True,"asadfdfl", "xxx", "vvv"]], colNames) summary_all_table = JTable(self.all_endpoints_summary_model) north_panel = JPanel(GridBagLayout()) c = GridBagConstraints() c.anchor = GridBagConstraints.WEST north_panel.add(JButton("Update"), c) c.weightx = 1 checkbox_missing_security = JCheckBox("Missing security headers") checkbox_potentially_dangerous = JCheckBox("Potentially Dangerous headers") checkbox_dangerous = JCheckBox("Dangerous or verbose headers") north_panel.add(checkbox_missing_security, c) north_panel.add(checkbox_potentially_dangerous, c) north_panel.add(checkbox_dangerous, c) self.summary_frame.add(north_panel, BorderLayout.NORTH) split = JSplitPane(JSplitPane.VERTICAL_SPLIT, JScrollPane(summary_unique_table), JScrollPane(summary_all_table)) split.setDividerLocation(200) self.summary_frame.add(split, BorderLayout.CENTER) south_panel = JPanel(GridBagLayout()) c = GridBagConstraints() c.fill = GridBagConstraints.HORIZONTAL c.anchor = GridBagConstraints.WEST c.weightx = 0 south_panel.add(JButton("Choose output file"), c) c.weightx = 1 south_panel.add(JTextField("Output file"), c) c.anchor = GridBagConstraints.WEST c.weightx = 0 south_panel.add(JButton(".docx report", actionPerformed = self.show_docx), c) self.summary_frame.add(south_panel, BorderLayout.SOUTH) def printxx(self, event): print('down xx') def show_summary(self, event): self.summary_frame.setVisible(True) self.summary_frame.toFront() self.summary_frame.setAlwaysOnTop(True) def getUiComponent(self): """Builds the interface of the extension tab.""" self.create_summary() panel = JPanel(GridBagLayout()) # ================== Add button and filter ===================== # JPanel1 = JPanel(GridBagLayout()) c = GridBagConstraints() c.gridx = 0 y_pos = 0 c.gridy = y_pos c.anchor = GridBagConstraints.WEST self.filter_but = JButton('<html><b><font color="white">Update table</font></b></html>', actionPerformed = self.filter_entries) self.filter_but.setBackground(Color(210,101,47)) JPanel1.add( self.filter_but, c ) self.preset_filters = DefaultComboBoxModel() self.preset_filters.addElement("Request + Response + <meta>") self.preset_filters.addElement("Request + Response") self.preset_filters.addElement("In scope only (se puede acceder al scope???)") self.preset_filters.addElement("Security headers only") self.preset_filters.addElement("Potentially dangerous headers only") self.preset_filters.addElement("Dangerous or unnecessary headers only") c.fill = GridBagConstraints.HORIZONTAL c.weightx = 1 c.gridx += 1 self.filterComboBox = JComboBox(self.preset_filters) JPanel1.add(self.filterComboBox , c ) c.weightx = 8 c.gridx += 1 self.filter = JTextField('To filter headers enter keywords (separated by a comma)') dim = Dimension(500,23) self.filter.setPreferredSize(dim) self.filter.addActionListener(self.filter_entries) JPanel1.add(self.filter , c ) c.weightx = 8 c.gridx += 1 # en este y el anterior intentaba meter las hints en la textbox con la clase de arriba, pero no va y es complicado, la converti de java y seguro que falta algo #self.filter_endpoints = HintTextField('To filter endpoints enter keywords (separated by a comma)', True) self.filter_endpoints = JTextField('To filter endpoints enter keywords (separated by a comma)') dim = Dimension(500,23) self.filter_endpoints.setPreferredSize(dim) self.filter_endpoints.addActionListener(self.call_filter_endpoints) JPanel1.add(self.filter_endpoints , c ) c.weightx = 0 c.gridx += 1 c.gridy = y_pos a=os.getcwd() + '\\gear_2.png' image_path=a.encode('string-escape') #ver si esto falla al coger en linux el icono self.advanced_config_button = JButton(ImageIcon(image_path)) self.advanced_config_button.addActionListener(self.show_advanced_config) self.advanced_config_button.setPreferredSize(Dimension(23, 23)) JPanel1.add(self.advanced_config_button, c) c = GridBagConstraints() y_pos =0 c.gridy = y_pos c.fill = GridBagConstraints.HORIZONTAL c.anchor = GridBagConstraints.WEST panel.add(JPanel1 , c) # ================== Add small separation between filter and tables (Consider removing) ===================== # c = GridBagConstraints() y_pos += 1 c.gridy = y_pos c.fill = GridBagConstraints.HORIZONTAL c.anchor = GridBagConstraints.WEST text1 = JLabel("<html><hr></html> ") panel.add( text1 , c) # ================== Add table ===================== # c = GridBagConstraints() y_pos += 1 c.gridy = y_pos c.weighty = 2 c.weightx = 2 c.fill = GridBagConstraints.BOTH #todas las columnas del archivo: header name && description && example && (permanent, no se que es esto) && self.colNames = ('<html><b>Header name</b></html>','<html><b>Appears in Host:</b></html>') self.colNames_meta = ('<html><b>Meta header identifier</b></html>','<html><b>Meta header content</b></html>') self.model_tab_req = IssueTableModel([["",""]], self.colNames) self.table_tab_req = IssueTable(self.model_tab_req, "tab") #im = self.table_tab_req.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) #im.put(KeyStroke.getKeyStroke("DOWN"), self.printxx) #im.put(KeyStroke.getKeyStroke("DOWN", 0), self.printxx) self.table_tab_req.getColumnModel().getColumn(0).setPreferredWidth(100) self.table_tab_req.getColumnModel().getColumn(1).setPreferredWidth(100) self.model_tab_resp = IssueTableModel([["",""]], self.colNames) self.table_tab_resp = IssueTable(self.model_tab_resp, "tab") self.table_tab_resp.getColumnModel().getColumn(0).setPreferredWidth(100) self.table_tab_resp.getColumnModel().getColumn(1).setPreferredWidth(100) self.model_tab_meta = IssueTableModel([["",""]], self.colNames_meta) self.table_tab_meta = IssueTable(self.model_tab_meta, "meta") self.table_tab_meta.getColumnModel().getColumn(0).setPreferredWidth(100) self.table_tab_meta.getColumnModel().getColumn(1).setPreferredWidth(100) # IMPORTANT: tables must be inside a JScrollPane so that the Table headers (that is, the columns names) are visible!!! panelTab_req = JPanel(BorderLayout()) panelTab_req.add(JScrollPane(self.table_tab_req)) panelTab_resp = JPanel(BorderLayout()) panelTab_resp.add(JScrollPane(self.table_tab_resp)) panelTab_meta = JPanel(BorderLayout()) panelTab_meta.add(JScrollPane(self.table_tab_meta)) self.tab_tabs = JTabbedPane() self.tab_tabs.addTab('Requests', panelTab_req) self.tab_tabs.addTab('Responses', panelTab_resp) self.tab_tabs.addTab('<meta>', panelTab_meta) # ================== Add endpoints table ===================== # self.model_unique_endpoints = IssueTableModel([[""]], ["Unique endpoints for selected host"]) self.table_unique_endpoints = IssueTable(self.model_unique_endpoints, "endpoints") self.model_all_endpoints = IssueTableModel([[""]], ["All endpoints for selected host"]) self.table_all_endpoints = IssueTable(self.model_all_endpoints, "endpoints") self.endpoint_tabs = JTabbedPane() self.endpoint_tabs.addTab('Unique endpoints', JScrollPane(self.table_unique_endpoints)) self.endpoint_tabs.addTab('All endpoints', JScrollPane(self.table_all_endpoints)) self.header_summary = JEditorPane("text/html", "") self.scroll_summary = JScrollPane(self.header_summary) self.summary_summary = JEditorPane("text/html", "") self.scroll_summary_summary = JScrollPane(self.summary_summary) self.summary_panel = JPanel() self.summary_panel.setLayout(BorderLayout()) self.summary_panel.add(self.scroll_summary, BorderLayout.CENTER) self.splt_2 = JSplitPane(JSplitPane.HORIZONTAL_SPLIT,self.endpoint_tabs, self.summary_panel) self.splt_1 = JSplitPane(JSplitPane.HORIZONTAL_SPLIT,JScrollPane(self.tab_tabs), self.splt_2) panel.add(self.splt_1, c) # ================== Add saving to file ===================== # JPanel2 = JPanel(GridBagLayout()) c = GridBagConstraints() c.gridx = 0 c.gridy = y_pos c.anchor = GridBagConstraints.WEST self.save_but = JButton('<html><b><font color="white">Save headers</font></b></html>', actionPerformed = self.save_json) self.save_but.setBackground(Color(10,101,247)) JPanel2.add( self.save_but, c ) c.gridx += 1 c.gridy = y_pos c.anchor = GridBagConstraints.WEST self.save_format = DefaultComboBoxModel() self.save_format.addElement("Choose output format") self.save_format.addElement("TXT: Host -> Header") self.save_format.addElement("TXT: Header -> Host") self.save_format.addElement("TXT: Host -> Endpoint -> Headers") self.save_format.addElement("TXT: Only security headers") self.save_format.addElement("TXT: Only potentially dangerous headers") self.save_format.addElement("TXT: Only dangerous or verbose headers") self.save_format.addElement("JSON: Host -> Header") self.save_format.addElement("JSON: Header -> Host ") self.save_format.addElement("JSON: Header -> Host -> Endpoint") self.save_format.addElement("JSON: Only security headers") self.save_format.addElement("JSON: Only potentially dangerous headers") self.save_format.addElement("JSON: Only dangerous or verbose headers") self.save_ComboBox = JComboBox(self.save_format) JPanel2.add( self.save_ComboBox, c ) c.gridx += 1 c.gridy = y_pos self.choose_file_but = JButton('<html><b><font color="white">Choose output file</font></b></html>', actionPerformed = self.choose_output_file) JPanel2.add( self.choose_file_but, c ) c.fill = GridBagConstraints.HORIZONTAL c.weightx = 1 c.gridx += 1 c.gridy = y_pos self.save_path = JTextField('Save headers to... (write full path or click "Choose output file". The file will be created)') JPanel2.add(self.save_path , c ) c.gridx += 1 c.weightx = 0 c.gridy = y_pos c.anchor = GridBagConstraints.EAST self.save_but = JButton('<html><b><font color="white">Summary</font></b></html>', actionPerformed = self.show_summary) self.save_but.setBackground(Color(10,101,247)) JPanel2.add( self.save_but, c ) c = GridBagConstraints() y_pos += 1 c.gridy = y_pos c.fill = GridBagConstraints.HORIZONTAL c.anchor = GridBagConstraints.WEST panel.add( JPanel2 , c) return panel def clear_table(self): """Clears the Header-Host table. It is also called every time a filter is applied.""" self.model_tab_req.setRowCount(0) self.model_tab_resp.setRowCount(0) self.model_tab_meta.setRowCount(0) self.for_table = [] self.header_host_table = [] self.for_req_table = [] self.for_resp_table = [] self.for_table_meta = [] self.req_header_dict = {} self.resp_header_dict = {} self.headers_already_in_table = [] self.meta_headers_already_in_table = [] self.last_row = 0 self.last_len = 0 self.last_row_meta = 0 self.last_len_meta = 0 return def get_meta_tags(self): global history2 history2 = [] history2 = self._callbacks.getProxyHistory() self.meta_table = [] keywords = self.filter.getText().lower().split(',') for item in history2: ''' This try / except is because for some reason some entries fail somewhere here. also happens for the normal request responses, not only metas''' try: response = self._helpers.bytesToString(item.getResponse()).split('\r\n\r\n')[0] resp_headers = response.split('\r\n') for resp_head in resp_headers[1:]: if "Content-Type: text/html" in resp_head: resp_html_head = self._helpers.bytesToString(item.getResponse()).split('\r\n\r\n')[1].split('</head>')[0] metas = self.meta.findall(resp_html_head) for meta in metas: if meta not in self.meta_table: request = self._helpers.bytesToString(item.getRequest()).split('\r\n\r\n')[0] req_headers = request.split('\r\n') host = self.find_host(req_headers) endpoint = req_headers[0] self.meta_table.append([host, endpoint, meta]) break except: pass self.for_table_meta = [] # the two columns that appear on the meta tag in the left table meta_header_item = [] for metax in self.meta_table: meta_values = metax[2].split(" ") host = metax[0] if len(meta_values[1:]) == 1: # if the meta tag has two items. val = [meta_values[1], ""] if val not in self.for_table_meta: self.for_table_meta.append(val) meta_header_item.append(meta_values[1]) #only meta header first item, used below else: # if the meta tag has more than two items val = [meta_values[1], host] if val not in self.for_table_meta: self.for_table_meta.append(val) meta_header_item.append(meta_values[1]) self.for_table_meta_uniques = sorted([list(x) for x in list({tuple(i) for i in self.for_table_meta})]) self.meta_headers_already_in_table = [] last_meta = '' k = 0 for table_entry_meta in self.for_table_meta_uniques: for keyword in keywords: # Apply filter to meta headers if keyword.lower().strip() in table_entry_meta[0] or keyword.lower().strip() in table_entry_meta[1] or self.filter.getText() == "To filter headers enter keywords (separated by a comma)" or self.filter.getText() == "": if last_meta != table_entry_meta[0] and k > 0: self.model_tab_meta.insertRow(self.last_row_meta, ['<html><b><font color="{}">'.format(self.color1) + '-' * 300 + '</font></b></html>', '<html><b><font color="{}">'.format(self.color1) + '-' * 300 + '</font></b></html>' * 300]) self.last_row_meta += 1 if table_entry_meta[0] not in self.meta_headers_already_in_table: self.meta_headers_already_in_table.append(table_entry_meta[0]) self.model_tab_meta.insertRow(self.last_row_meta, table_entry_meta) self.last_row_meta += 1 else: self.model_tab_meta.insertRow(self.last_row_meta, ["",table_entry_meta[1]]) self.last_row_meta += 1 last_meta = table_entry_meta[0] k += 1 self.last_len_meta = len(history2) return def filter_entries(self, event): """Applies the supplied filter(s) to the Header-Host table. If no filters are applied, all available entries are shown.""" self.clear_table() self.read_headers() #if True: if
from twisted.internet.defer import Deferred from twisted.internet.protocol import Factory, ClientFactory from twisted.internet.task import LoopingCall from twisted.protocols.amp import AMP, Command, Integer, String, Boolean, AmpList, ListOf, IncompatibleVersions from twisted.python import log from twisted.words.protocols import irc from txircd.channel import IRCChannel from txircd.utils import CaseInsensitiveDictionary, epoch, irc_lower, now, IPV4_MAPPED_ADDR from datetime import datetime protocol_version = 200 # Protocol version 0.2.0 # The protocol version should be incremented with changes of the protocol # Breaking changes should be avoided except for major version upgrades or when it's otherwise unavoidable # Keep a list of versions the current protocol is compatible with # This list must include the current protocol version compatible_versions = [ 200 ] class RemoteUser(object): class RemoteSocket(object): class RemoteTransport(object): def loseConnection(self): pass def __init__(self, secure): self.transport = self.RemoteTransport() self.secure = secure def __init__(self, ircd, uuid, nick, ident, host, realhost, gecos, ip, password, server, secure, signonTime, nickTime): self.ircd = ircd self.socket = self.RemoteSocket(secure) self.uuid = uuid self.password = password self.nickname = nick self.username = ident self.realname = gecos self.hostname = host self.realhost = realhost self.ip = ip self.server = server self.signon = signonTime self.nicktime = nickTime self.lastactivity = now() self.disconnected = Deferred() self.mode = {} self.registered = 0 self.metadata = { # split into metadata key namespaces, see http://ircv3.atheme.org/specification/metadata-3.2 "server": {}, "user": {}, "client": {}, "ext": {}, "private": {} } self.cache = {} def callConnectHooks(self): tryagain = [] for action in self.ircd.actions["connect"]: result = action(self) if result == "again": tryagain.append(action) elif not result: self.disconnect("Connection lost") return for action in tryagain: if not action(self): self.disconnect("Connection lost") return tryagain = [] for action in self.ircd.actions["register"]: result = action(self) if result == "again": tryagain.append(action) elif not result: self.disconnect("Connection lost") return for action in tryagain: if not action(self): self.disconnect("Connection lost") return def disconnect(self, reason, sourceServer = None): del self.ircd.userid[self.uuid] if self.nickname: quitdest = set() exitChannels = [] for channel in self.ircd.channels.itervalues(): if self in channel.users: exitChannels.append(channel) for channel in exitChannels: del channel.users[self] # remove channel user entry if not channel.users: for modfunc in self.ircd.actions["chandestroy"]: modfunc(channel) del self.ircd.channels[channel.name] # destroy the empty channel for u in channel.users.iterkeys(): quitdest.add(u) udata = self.ircd.users[self.nickname] if udata == self: del self.ircd.users[self.nickname] for user in quitdest: user.sendMessage("QUIT", ":{}".format(reason), to=None, prefix=self.prefix()) for modfunc in self.ircd.actions["quit"]: modfunc(self, reason) self.disconnected.callback(None) for server in self.ircd.servers.itervalues(): if server.nearHop == self.ircd.name and server.name != sourceServer: server.callRemote(RemoveUser, user=self.uuid, reason=reason) def sendMessage(self, command, *parameter_list, **kw): if self.server not in self.ircd.servers: return if command in [ "JOIN", "MODE", "TOPIC", "QUIT", "NICK", "ERROR" ]: # some items should only be sent by the remote server via other s2s commands return if "prefix" in kw: if kw["prefix"] is None: prefix = "" else: prefix = kw["prefix"] else: prefix = self.ircd.name if "to" in kw: if kw["to"] is None: to = "" else: to = kw["to"] else: to = self.nickname if self.nickname else "*" d = self.ircd.servers[self.server].callRemote(SendAnnouncement, user=self.uuid, type=command, args=parameter_list, prefix=prefix, to=to) if d: # Apparently sometimes the deferred is actually None d.addErrback(lambda err: log.msg("Could not send message to user {}: {} {}".format(self.nickname, command, " ".join(parameter_list)))) def handleCommand(self, command, prefix, params): cmd = self.ircd.commands[command] cmd.updateActivity(self) data = cmd.processParams(self, params) if not data: return permData = self.commandPermission(command, data) if permData: cmd.onUse(self, permData) for action in self.ircd.actions["commandextra"]: action(command, permData) def commandPermission(self, command, data): tryagain = set() for modfunc in self.ircd.actions["commandpermission"]: permData = modfunc(self, command, data) if permData == "again": tryagain.add(modfunc) else: data = permData if "force" in data and data["force"]: return data if not data: return {} for modeset in self.ircd.channel_modes: for implementation in modeset.itervalues(): permData = implementation.checkPermission(self, command, data) if permData == "again": tryagain.add(implementation.checkPermission) else: data = permData if "force" in data and data["force"]: return data if not data: return {} for modeset in self.ircd.user_modes: for implementation in modeset.itervalues(): permData = implementation.checkPermission(self, command, data) if permData == "again": tryagain.add(implementation.checkPermission) else: data = permData if "force" in data and data["force"]: return data if not data: return {} for modfunc in tryagain: data = modfunc(self, command, data) if "force" in data and data["force"]: return data if not data: return {} return data def setMetadata(self, namespace, key, value, sourceServer = None): oldValue = self.metadata[namespace][key] if key in self.metadata[namespace] else "" self.metadata[namespace][key] = value for action in self.ircd.actions["metadataupdate"]: action(self, namespace, key, oldValue, value) for server in self.ircd.servers.itervalues(): if server.nearHop == self.ircd.name and server.name != sourceServer: server.callRemote(SetMetadata, target=self.uuid, targetts=epoch(self.signon), namespace=namespace, key=key, value=value) def delMetadata(self, namespace, key, sourceServer = None): oldValue = self.metadata[namespace][key] del self.metadata[namespace][key] for modfunc in self.ircd.actions["metadataupdate"]: modfunc(self, namespace, key, oldValue, "") for server in self.ircd.servers.itervalues(): if server.nearHop == self.ircd.name and server.name != sourceServer: server.callRemote(SetMetadata, target=self.uuid, targetts=epoch(self.signon), namespace=namespace, key=key, value="") def prefix(self): return "{}!{}@{}".format(self.nickname, self.username, self.hostname) def hasAccess(self, channel, level): if self not in channel.users or level not in self.ircd.prefixes: return None status = channel.users[self] if not status: return False return self.ircd.prefixes[status[0]][1] >= self.ircd.prefixes[level][1] def setUsername(self, newUsername, sourceServer = None): self.username = newUsername if self.registered == 0: for server in self.ircd.servers.itervalues(): if server.nearHop == self.ircd.name and server.name != sourceServer: server.callRemote(SetIdent, user=self.uuid, ident=newUsername) def setHostname(self, newHostname, sourceServer = None): self.hostname = newHostname if self.registered == 0: for server in self.ircd.servers.itervalues(): if server.nearHop == self.ircd.name and server.name != sourceServer: server.callRemote(SetHost, user=self.uuid, host=newHostname) def setRealname(self, newRealname, sourceServer = None): self.realname = newRealname if self.registered == 0: for server in self.ircd.servers.itervalues(): if server.nearHop == self.ircd.name and server.name != sourceServer: server.callRemote(SetName, user=self.uuid, gecos=newRealname) def setMode(self, user, modes, params, displayPrefix = None): if user: source = user.prefix() elif displayPrefix: source = displayPrefix else: source = self.ircd.name self.ircd.servers[self.server].callRemote(RequestSetMode, user=self.uuid, source=source, modestring=modes, params=params) def modeString(self, user): modes = [] # Since we're appending characters to this string, it's more efficient to store the array of characters and join it rather than keep making new strings params = [] for mode, param in self.mode.iteritems(): modetype = self.ircd.user_mode_type[mode] if modetype > 0: modes.append(mode) if param: params.append(self.ircd.user_modes[modetype][mode].showParam(user, self, param)) return ("+{} {}".format("".join(modes), " ".join(params)) if params else "+{}".format("".join(modes))) def join(self, channel): if self in channel.users: return self.ircd.servers[self.server].callRemote(RequestJoinChannel, channel=channel.name, user=self.uuid) def leave(self, channel, sourceServer = None): del channel.users[self] # remove channel user entry if not channel.users: for modfunc in self.ircd.actions["chandestroy"]: modfunc(channel) del self.ircd.channels[channel.name] # destroy the empty channel for server in self.ircd.servers.itervalues(): if server.nearHop == self.ircd.name and server.name != sourceServer: server.callRemote(LeaveChannel, channel=channel.name, user=self.uuid) def nick(self, newNick): if newNick in self.ircd.users: return self.ircd.servers[self.server].callRemote(RequestNick, user=self.uuid, newnick=newNick) class RemoteServer(object): def __init__(self, ircd, name, desc, nearestServer, hopCount): self.ircd = ircd self.name = name self.description = desc self.nearHop = nearestServer self.burstComplete = True self.remoteServers = set() self.hopCount = hopCount def callRemote(self, command, *args, **kw): server = self while server.nearHop != self.ircd.name and server.nearHop in self.ircd.servers: server = self.ircd.servers[server.nearHop] if server.name in self.ircd.servers: server.callRemote(command, *args, **kw) # If the parameters are such that they indicate the target properly, this will be forwarded to the proper server. # ERRORS class HandshakeAlreadyComplete(Exception): pass class HandshakeNotYetComplete(Exception): pass class ServerAlreadyConnected(Exception): pass class ServerMismatchedIP(Exception): pass class ServerPasswordIncorrect(Exception): pass class ServerNoLink(Exception): pass class ModuleMismatch(Exception): pass class ServerNotConnected(Exception): pass class UserAlreadyConnected(Exception): pass class NoSuchTarget(Exception): pass class NoSuchUser(Exception): pass class NoSuchServer(Exception): pass class NoSuchChannel(Exception): pass # TODO: errbacks to handle all of these # COMMANDS class IntroduceServer(Command): arguments = [ ("name", String()), # server name ("password", String()), # server password specified in configuration ("description", String()), # server description ("version", Integer()), # protocol version ("commonmodules", ListOf(String())) ] errors = { HandshakeAlreadyComplete: "HANDSHAKE_ALREADY_COMPLETE" } fatalErrors = { ServerAlreadyConnected: "SERVER_ALREADY_CONNECTED", ServerMismatchedIP: "SERVER_MISMATCHED_IP", ServerPasswordIncorrect: "<PASSWORD>", ServerNoLink: "SERVER_NO_LINK", ModuleMismatch: "MODULE_MISMATCH" } requiresAnswer = False class AddNewServer(Command): arguments = [ ("name", String()), ("description", String()), ("hopcount", Integer()), ("nearhop", String()) ] errors = { HandshakeNotYetComplete: "HANDSHAKE_NOT_COMPLETE", ServerAlreadyConnected: "SERVER_ALREADY_CONNECTED", NoSuchServer: "NO_SUCH_SERVER" } requiresAnswer = False class DisconnectServer(Command): arguments = [ ("name", String()) ] errors = { HandshakeNotYetComplete: "HANDSHAKE_NOT_COMPLETE" } fatalErrors = { ServerNotConnected: "NO_SUCH_SERVER" } requiresAnswer = False class ConnectUser(Command): arguments = [ ("uuid", String()), ("ip", String()), ("server", String()), ("secure", Boolean()), ("signon", Integer()) ] errors = { HandshakeNotYetComplete: "HANDSHAKE_NOT_COMPLETE", NoSuchServer: "NO_SUCH_SERVER", UserAlreadyConnected: "UUID_ALREADY_CONNECTED" } requiresAnswer = False class RegisterUser(Command): arguments = [ ("uuid", String()), ("nick", String()), ("ident", String()), ("host", String()), ("realhost", String()), ("gecos", String()), ("ip", String()), ("password", String()), ("server", String()), ("secure", Boolean()), ("signon", Integer()),
virtual global IPv6 IP address **type**\: list of :py:class:`GlobalIpv6Address <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv6.SlaveVirtualRouters.SlaveVirtualRouter.GlobalIpv6Addresses.GlobalIpv6Address>` """ _prefix = 'ipv4-vrrp-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.global_ipv6_address = YList() self.global_ipv6_address.parent = self self.global_ipv6_address.name = 'global_ipv6_address' class GlobalIpv6Address(object): """ A VRRP virtual global IPv6 IP address .. attribute:: ip_address <key> VRRP virtual global IPv6 address **type**\: one of the below types: **type**\: str **pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)? ---- **type**\: str **pattern:** ((\:\|[0\-9a\-fA\-F]{0,4})\:)([0\-9a\-fA\-F]{0,4}\:){0,5}((([0\-9a\-fA\-F]{0,4}\:)?(\:\|[0\-9a\-fA\-F]{0,4}))\|(((25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])\\.){3}(25[0\-5]\|2[0\-4][0\-9]\|[01]?[0\-9]?[0\-9])))(%[\\p{N}\\p{L}]+)? ---- """ _prefix = 'ipv4-vrrp-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.ip_address = None @property def _common_path(self): if self.parent is None: raise YPYModelError('parent is not set . Cannot derive path.') if self.ip_address is None: raise YPYModelError('Key property ip_address is None') return self.parent._common_path +'/Cisco-IOS-XR-ipv4-vrrp-cfg:global-ipv6-address[Cisco-IOS-XR-ipv4-vrrp-cfg:ip-address = ' + str(self.ip_address) + ']' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.ip_address is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ipv4_vrrp_cfg as meta return meta._meta_table['Vrrp.Interfaces.Interface.Ipv6.SlaveVirtualRouters.SlaveVirtualRouter.GlobalIpv6Addresses.GlobalIpv6Address']['meta_info'] @property def _common_path(self): if self.parent is None: raise YPYModelError('parent is not set . Cannot derive path.') return self.parent._common_path +'/Cisco-IOS-XR-ipv4-vrrp-cfg:global-ipv6-addresses' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.global_ipv6_address is not None: for child_ref in self.global_ipv6_address: if child_ref._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ipv4_vrrp_cfg as meta return meta._meta_table['Vrrp.Interfaces.Interface.Ipv6.SlaveVirtualRouters.SlaveVirtualRouter.GlobalIpv6Addresses']['meta_info'] @property def _common_path(self): if self.parent is None: raise YPYModelError('parent is not set . Cannot derive path.') if self.slave_virtual_router_id is None: raise YPYModelError('Key property slave_virtual_router_id is None') return self.parent._common_path +'/Cisco-IOS-XR-ipv4-vrrp-cfg:slave-virtual-router[Cisco-IOS-XR-ipv4-vrrp-cfg:slave-virtual-router-id = ' + str(self.slave_virtual_router_id) + ']' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.slave_virtual_router_id is not None: return True if self.accept_mode_disable is not None: return True if self.follow is not None: return True if self.global_ipv6_addresses is not None and self.global_ipv6_addresses._has_data(): return True if self.link_local_ipv6_address is not None and self.link_local_ipv6_address._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ipv4_vrrp_cfg as meta return meta._meta_table['Vrrp.Interfaces.Interface.Ipv6.SlaveVirtualRouters.SlaveVirtualRouter']['meta_info'] @property def _common_path(self): if self.parent is None: raise YPYModelError('parent is not set . Cannot derive path.') return self.parent._common_path +'/Cisco-IOS-XR-ipv4-vrrp-cfg:slave-virtual-routers' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.slave_virtual_router is not None: for child_ref in self.slave_virtual_router: if child_ref._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ipv4_vrrp_cfg as meta return meta._meta_table['Vrrp.Interfaces.Interface.Ipv6.SlaveVirtualRouters']['meta_info'] @property def _common_path(self): if self.parent is None: raise YPYModelError('parent is not set . Cannot derive path.') return self.parent._common_path +'/Cisco-IOS-XR-ipv4-vrrp-cfg:ipv6' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.slave_virtual_routers is not None and self.slave_virtual_routers._has_data(): return True if self.version3 is not None and self.version3._has_data(): return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ipv4_vrrp_cfg as meta return meta._meta_table['Vrrp.Interfaces.Interface.Ipv6']['meta_info'] class Delay(object): """ Minimum and Reload Delay .. attribute:: min_delay Minimum delay in seconds **type**\: int **range:** 0..10000 **units**\: second .. attribute:: reload_delay Reload delay in seconds **type**\: int **range:** 0..10000 **units**\: second """ _prefix = 'ipv4-vrrp-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.min_delay = None self.reload_delay = None @property def _common_path(self): if self.parent is None: raise YPYModelError('parent is not set . Cannot derive path.') return self.parent._common_path +'/Cisco-IOS-XR-ipv4-vrrp-cfg:delay' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.min_delay is not None: return True if self.reload_delay is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ipv4_vrrp_cfg as meta return meta._meta_table['Vrrp.Interfaces.Interface.Delay']['meta_info'] class Ipv4(object): """ IPv4 VRRP configuration .. attribute:: slave_virtual_routers The VRRP slave group configuration table **type**\: :py:class:`SlaveVirtualRouters <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.SlaveVirtualRouters>` .. attribute:: version2 Version 2 VRRP configuration **type**\: :py:class:`Version2 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.Version2>` .. attribute:: version3 Version 3 VRRP configuration **type**\: :py:class:`Version3 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.Version3>` """ _prefix = 'ipv4-vrrp-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.slave_virtual_routers = Vrrp.Interfaces.Interface.Ipv4.SlaveVirtualRouters() self.slave_virtual_routers.parent = self self.version2 = Vrrp.Interfaces.Interface.Ipv4.Version2() self.version2.parent = self self.version3 = Vrrp.Interfaces.Interface.Ipv4.Version3() self.version3.parent = self class Version3(object): """ Version 3 VRRP configuration .. attribute:: virtual_routers The VRRP virtual router configuration table **type**\: :py:class:`VirtualRouters <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters>` """ _prefix = 'ipv4-vrrp-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.virtual_routers = Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters() self.virtual_routers.parent = self class VirtualRouters(object): """ The VRRP virtual router configuration table .. attribute:: virtual_router The VRRP virtual router being configured **type**\: list of :py:class:`VirtualRouter <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter>` """ _prefix = 'ipv4-vrrp-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.virtual_router = YList() self.virtual_router.parent = self self.virtual_router.name = 'virtual_router' class VirtualRouter(object): """ The VRRP virtual router being configured .. attribute:: vr_id <key> VRID Virtual Router Identifier **type**\: int **range:** 1..255 .. attribute:: accept_mode_disable Disable Accept Mode for this virtual IPAddress **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: bfd Enable use of Bidirectional Forwarding Detection for this IP **type**\: str **pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)? .. attribute:: preempt Preempt Master router if higher priority **type**\: int **range:** 0..3600 **default value**\: 0 .. attribute:: primary_ipv4_address The Primary VRRP IPv4 address **type**\: str **pattern:** (([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])\\.){3}([0\-9]\|[1\-9][0\-9]\|1[0\-9][0\-9]\|2[0\-4][0\-9]\|25[0\-5])(%[\\p{N}\\p{L}]+)? .. attribute:: priority Priority value **type**\: int **range:** 1..254 **default value**\: 100 .. attribute:: secondary_ipv4_addresses The table of VRRP secondary IPv4 addresses **type**\: :py:class:`SecondaryIpv4Addresses <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.SecondaryIpv4Addresses>` .. attribute:: session_name VRRP Session Name **type**\: str **length:** 0..16 .. attribute:: timer Set advertisement timer **type**\: :py:class:`Timer <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.Timer>` .. attribute:: tracked_objects Track an object, reducing priority if it goes down **type**\: :py:class:`TrackedObjects <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.TrackedObjects>` .. attribute:: tracks Track an item, reducing priority if it goes down **type**\: :py:class:`Tracks <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.Tracks>` """ _prefix = 'ipv4-vrrp-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.vr_id = None self.accept_mode_disable = None self.bfd = None self.preempt = None self.primary_ipv4_address = None self.priority = None self.secondary_ipv4_addresses = Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.SecondaryIpv4Addresses() self.secondary_ipv4_addresses.parent = self self.session_name = None self.timer = Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.Timer() self.timer.parent = self self.tracked_objects = Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.TrackedObjects() self.tracked_objects.parent = self self.tracks = Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.Tracks() self.tracks.parent = self class Timer(object): """ Set advertisement timer .. attribute:: advertisement_time_in_msec Advertisement time in milliseconds **type**\: int **range:** 100..3000 **units**\: millisecond .. attribute:: advertisement_time_in_sec Advertisement time in seconds **type**\: int **range:** 1..40 **units**\: second .. attribute:: forced TRUE \- Force configured timer values to be used, required when configured in milliseconds **type**\: bool **default value**\: false .. attribute:: in_msec TRUE \- Advertise time configured in milliseconds, FALSE \- Advertise time configured in seconds **type**\: bool **default value**\: false """ _prefix = 'ipv4-vrrp-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.advertisement_time_in_msec = None self.advertisement_time_in_sec = None self.forced = None self.in_msec = None @property def _common_path(self): if self.parent is None: raise YPYModelError('parent is not set . Cannot derive path.') return self.parent._common_path +'/Cisco-IOS-XR-ipv4-vrrp-cfg:timer' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.advertisement_time_in_msec is not None: return True if self.advertisement_time_in_sec is not None: return True if self.forced is not None: return True if self.in_msec is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ipv4_vrrp_cfg as meta return meta._meta_table['Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.Timer']['meta_info'] class SecondaryIpv4Addresses(object): """ The table of VRRP secondary IPv4 addresses .. attribute:: secondary_ipv4_address A VRRP secondary IPv4 address **type**\: list of :py:class:`SecondaryIpv4Address <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ipv4_vrrp_cfg.Vrrp.Interfaces.Interface.Ipv4.Version3.VirtualRouters.VirtualRouter.SecondaryIpv4Addresses.SecondaryIpv4Address>` """ _prefix = 'ipv4-vrrp-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.secondary_ipv4_address = YList() self.secondary_ipv4_address.parent = self self.secondary_ipv4_address.name = 'secondary_ipv4_address' class
#!/usr/bin/env python3 class Dummy(object): pass def getWidth(xmlfile): from xml.etree.ElementTree import ElementTree xmlfp = None try: xmlfp = open(xmlfile,'r') print('reading file width from: {0}'.format(xmlfile)) xmlx = ElementTree(file=xmlfp).getroot() #width = int(xmlx.find("component[@name='coordinate1']/property[@name='size']/value").text) tmp = xmlx.find("component[@name='coordinate1']/property[@name='size']/value") if tmp == None: tmp = xmlx.find("component[@name='Coordinate1']/property[@name='size']/value") width = int(tmp.text) print("file width: {0}".format(width)) except (IOError, OSError) as strerr: print("IOError: %s" % strerr) return [] finally: if xmlfp is not None: xmlfp.close() return width def getLength(xmlfile): from xml.etree.ElementTree import ElementTree xmlfp = None try: xmlfp = open(xmlfile,'r') print('reading file length from: {0}'.format(xmlfile)) xmlx = ElementTree(file=xmlfp).getroot() #length = int(xmlx.find("component[@name='coordinate2']/property[@name='size']/value").text) tmp = xmlx.find("component[@name='coordinate2']/property[@name='size']/value") if tmp == None: tmp = xmlx.find("component[@name='Coordinate2']/property[@name='size']/value") length = int(tmp.text) print("file length: {0}".format(length)) except (IOError, OSError) as strerr: print("IOError: %s" % strerr) return [] finally: if xmlfp is not None: xmlfp.close() return length def getInfo(xmlfile, propertyName): from xml.etree.ElementTree import ElementTree xmlfp = None content = None try: xmlfp = open(xmlfile,'r') xmlx = ElementTree(file=xmlfp).getroot() #search each possible propertyName propertyNameList = [propertyName, propertyName.lower(), propertyName.upper(), propertyName.capitalize()] for propertyNameX in propertyNameList: route = "property[@name='{}']/value".format(propertyNameX) contentAll = xmlx.find(route) if contentAll != None: content = contentAll.text content = content.strip("'") #remove the leading and trailing quote content = content.strip('"') #remove the leading and trailing quote #print("{}: {}".format(propertyName, content)) break except (IOError, OSError) as strerr: print("IOError: %s" % strerr) return None finally: if xmlfp is not None: xmlfp.close() return content def get_content(xmlfile, properties, names): from xml.etree.ElementTree import ElementTree xmlfp = None content = None propertylist = properties.split('.') namelist = names.split('.') #get route if len(propertylist) != len(namelist): raise Exception('property list length not equal to name list length!') else: route = '' for i in range(len(propertylist)): route += propertylist[i] if namelist[i] != '': route += "[@name='{}']".format(namelist[i]) if i != len(propertylist) - 1: route += "/" #find content try: xmlfp = open(xmlfile,'r') root = ElementTree(file=xmlfp).getroot() content0 = root.find(route) if content0 != None: content = content0.text content = content.strip("'") #remove the possible leading and trailing quote content = content.strip('"') #remove the possible leading and trailing quote except (IOError, OSError) as strerr: print("IOError: %s" % strerr) return None finally: if xmlfp is not None: xmlfp.close() return content def changeXmlName(xmlFile, xmlFileNew): import os import isce import isceobj from imageMath import IML #currently, only sure about supporting SLC xml file xmlFileNew=xmlFileNew.rstrip('.xml') img, dataName, metaName = IML.loadImage(xmlFile) img.filename = xmlFileNew #img.setAccessMode('READ') os.remove(xmlFile) img.renderHdr() def writeSARconfig_ALOS2(filename, leader, slc, output): a = '''<component name="sar"> <property name="OUTPUT"> <value>{output}</value> </property> <property name="LEADERFILE"> <value>'{leader}'</value> </property> <property name="IMAGEFILE"> <value>'{slc}'</value> </property> </component> '''.format( output = output, leader = leader, slc = slc ) with open(filename, 'w') as f: f.write(a) def create_xml(fileName, width, length, fileType): import isce import isceobj if fileType == 'slc': image = isceobj.createSlcImage() elif fileType == 'int': image = isceobj.createIntImage() elif fileType == 'amp': image = isceobj.createAmpImage() elif fileType == 'rmg' or fileType == 'unw': image = isceobj.Image.createUnwImage() elif fileType == 'float': image = isceobj.createImage() image.setDataType('FLOAT') else: raise Exception('format not supported yet!\n') image.setFilename(fileName) image.setWidth(width) image.setLength(length) #image.setAccessMode('read') #image.createImage() image.renderHdr() #image.finalizeImage() def renderParXml(frame, name): import math import numpy as np import isce import isceobj from isceobj.Constants import SPEED_OF_LIGHT catalog = isceobj.Catalog.createCatalog(name) par = 'frame' catalog.addItem('facility', frame.getProcessingFacility(), par + '.slcProcessingSoftware') catalog.addItem('system', frame.getProcessingSystem(), par + '.slcProcessingSoftware') catalog.addItem('version', frame.getProcessingSoftwareVersion(), par + '.slcProcessingSoftware') catalog.addItem('mission', frame.instrument.platform.getMission(), par) catalog.addItem('passDirection', frame.getPassDirection(), par) catalog.addItem('antennaLength', frame.instrument.platform.getAntennaLength(), par) if frame.getInstrument().getPlatform().pointingDirection == -1: pointingDirection = 'right' else: pointingDirection = 'left' catalog.addItem('antennaPointingDirection', pointingDirection, par) catalog.addItem('radarWavelegth', frame.instrument.radarWavelength, par) catalog.addItem('polarization', frame.getPolarization(), par) catalog.addItem('sensingStart', frame.getSensingStart(), par) catalog.addItem('sensingStop', frame.getSensingStop(), par) catalog.addItem('startingRange', frame.getStartingRange(), par) catalog.addItem('numberOfLines', frame.getNumberOfLines(), par) catalog.addItem('numberOfSamples', frame.getNumberOfSamples(), par) catalog.addItem('rangeSamplingRate', frame.instrument.rangeSamplingRate, par) catalog.addItem('rangeBandWidth', math.fabs(frame.instrument.pulseLength * frame.instrument.chirpSlope), par) catalog.addItem('PRF', frame.instrument.PRF, par) width=frame.getNumberOfSamples() if hasattr(frame, 'dopCoeff'): catalog.addItem('DopplerCoefficients', frame.dopCoeff, par) doppler = [] for i in [0, (width-1.0)/2.0, width-1.0]: doppler += [frame.PRF*(frame.dopCoeff[3] * math.pow(i, 3) + frame.dopCoeff[2] * math.pow(i, 2) + frame.dopCoeff[1] * math.pow(i, 1) + frame.dopCoeff[0])] catalog.addItem('DopplerNearMidFar', doppler, par) if hasattr(frame, 'fmrateCoeff'): catalog.addItem('azimuthFmRateCoefficients', frame.fmrateCoeff, par) fmrate = [] for i in [0, (width-1.0)/2.0, width-1.0]: fmrate += [frame.fmrateCoeff[2] * i**2 + frame.fmrateCoeff[1] * i**1 + frame.fmrateCoeff[0]] catalog.addItem('azimuthFmRateNearMidFar', fmrate, par) ###################################################################################################### #calculate pixel size orbit = frame.getOrbit() numberOfOrbit = len(orbit) orbitMid = orbit[int(numberOfOrbit/2)] vn = np.sqrt(orbitMid.velocity[0]**2 + orbitMid.velocity[1]**2 + orbitMid.velocity[2]**2) h = np.sqrt(orbitMid.position[0]**2 + orbitMid.position[1]**2 + orbitMid.position[2]**2) #earth radius in meters r = 6371 * 1000.0; #slant range pixel size slantRangePixelSize = 0.5 * SPEED_OF_LIGHT / frame.rangeSamplingRate #azimuth pixel size azi = 1.0 / frame.PRF #azimuth pixel size on track azimuthPixelSizeOnTrack = vn * azi #azimuth pixel size on ground azimuthPixelSizeOnGround = vn * azi * r / h catalog.addItem('slantRangePixelSize', slantRangePixelSize, par) catalog.addItem('azimuthPixelSizeOnTrack', azimuthPixelSizeOnTrack, par) catalog.addItem('azimuthPixelSizeOnGround', azimuthPixelSizeOnGround, par) ###################################################################################################### orbitElementsDesignator = {'0':'preliminary', '1':'decision', '2':'high precision'} catalog.addItem('orbitQuality', orbit.orbitQuality, par) for i in range(numberOfOrbit): catalog.addItem('time', orbit[i].getTime(), par+'.orbit_{}'.format(i+1)) catalog.addItem('position', orbit[i].getPosition(), par+'.orbit_{}'.format(i+1)) catalog.addItem('velocity', orbit[i].getVelocity(), par+'.orbit_{}'.format(i+1)) catalog.renderXml() def runCmd(cmd, silent=0): import os if silent == 0: print("{}".format(cmd)) if not cmd.strip(): print("EMPTY CMD") return status = os.system(cmd) if status != 0: raise Exception('error when running:\n{}\n'.format(cmd)) def run_record_cmd(cmd_all, start_step, end_step, cmdfile): import os import datetime #find starting and ending index step = start_step start_step_index = [i for i, step_cmd in enumerate(cmd_all) if step in step_cmd] step = end_step end_step_index = [i for i, step_cmd in enumerate(cmd_all) if step in step_cmd] #check index if len(start_step_index) != 0: start_step_index = start_step_index[0] else: raise Exception('wrong start step') if len(end_step_index) != 0: end_step_index = end_step_index[0] else: raise Exception('wrong end step') if start_step_index > end_step_index: raise Exception('start step > end step') #record header with open(cmdfile, 'a') as f: header = '###################################################################\n' header = header + '# processing commands started at: {}\n'.format(datetime.datetime.now()) header = header + '###################################################################\n' f.write(header) #get absolute directory in order to always write to this file when change directory cmdfile = os.path.abspath(cmdfile) print("CMDFILE : {}".format(cmdfile)) #run and record commands for i in range(start_step_index, end_step_index+1): with open(cmdfile, 'a') as f: f.write('\n##STEP: {}\n'.format(cmd_all[i][0])) for j in range(1, len(cmd_all[i])): with open(cmdfile, 'a') as f: f.write(cmd_all[i][j] + '\n') #if change directory, it only changes bash process's directory, it wont change python process's directory. so use python's os.chdir instead. NOT WORK WITH DIRECTORY NAME WITH SPACE YET! if cmd_all[i][j].split()[0]=='cd': os.chdir(cmd_all[i][j].split()[1]) else: runCmd(cmd_all[i][j]) #add some blank lines with open(cmdfile, 'a') as f: f.write('\n\n\n') #os.system cannot capture status of the primary commands. so it still has problems. def run_record_cmd2(cmd_all, start_step, end_step, cmdfile, outputfile): import os import datetime #find starting and ending index step = start_step start_step_index = [i for i, step_cmd in enumerate(cmd_all) if step in step_cmd] step = end_step end_step_index = [i for i, step_cmd in enumerate(cmd_all) if step in step_cmd] #check index if len(start_step_index) != 0: start_step_index = start_step_index[0] else: raise Exception('wrong start step') if len(end_step_index) != 0: end_step_index = end_step_index[0] else: raise Exception('wrong end step') if start_step_index > end_step_index: raise Exception('start step > end step') time = datetime.datetime.now() header = '###################################################################\n' header += '# processing commands started at: {}\n'.format(time) header += '###################################################################\n' #record header for command and output file with open(cmdfile, 'a') as f: f.write(header) with open(outputfile, 'a') as f: f.write(header) #get absolute directory in order to always write to this file when change directory cmdfile = os.path.abspath(cmdfile) outputfile = os.path.abspath(outputfile) #run and record commands for i in range(start_step_index, end_step_index+1): #record step header_step = '\n##STEP: {}\n'.format(cmd_all[i][0]) with open(cmdfile, 'a') as f: f.write(header_step) with open(outputfile, 'a') as f: f.write(header_step) #run commands for j in range(1, len(cmd_all[i])): #record commands with open(cmdfile, 'a') as f: f.write(cmd_all[i][j] + '\n') print("{}".format(cmd_all[i][j])) #run commands and record output #if change directory, it only changes bash process's directory, it wont change python process's directory. so use python's os.chdir instead. NOT WORK WITH DIRECTORY NAME WITH SPACE YET! if cmd_all[i][j].split()[0]=='cd': os.chdir(cmd_all[i][j].split()[1]) else: #os.system cannot capture status of the primary commands. so it still has problems. status = os.system('{} 2>&1 | tee -a {}'.format(cmd_all[i][j], outputfile)) #status = os.system('{} >> {} 2>&1'.format(cmd_all[i][j], outputfile)) if status != 0: raise Exception('error when running:\n{}\n'.format(cmd_all[i][j])) #add some blank lines tail = '\n\n\n' with open(cmdfile, 'a') as f: f.write(tail) with open(outputfile, 'a') as f: f.write(tail) def writeOffset(offset, fileName): offsetsPlain = '' for offsetx in offset: offsetsPlainx = "{}".format(offsetx) offsetsPlainx = offsetsPlainx.split() offsetsPlain = offsetsPlain + "{:8d} {:10.3f} {:8d} {:12.3f} {:11.5f} {:11.6f} {:11.6f} {:11.6f}\n".format( int(offsetsPlainx[0]), float(offsetsPlainx[1]), int(offsetsPlainx[2]), float(offsetsPlainx[3]), float(offsetsPlainx[4]), float(offsetsPlainx[5]), float(offsetsPlainx[6]), float(offsetsPlainx[7])
import tkinter from tkinter import ttk import random import time import tkinter.messagebox class SortingVisualizer: """ Main GUI """ def __init__(self, main): """ Init GUI :param main: tkinter.Tk() """ self.FINISHED_SORTING = False self.box_color = "#5555ff" ###### Basic Layout ###### """_______________________________________ | Frame: Buttons and Labels | |---------------------------------------| | | | Frame: Canvas + Scrollbar | | | |_______________________________________| """ ### Init root self.main = main self.main.bind("<Key>", self._main_window_action) self.main.title("Sorting Algorithm Visualization") self.main.maxsize(1500, 600) self.main.config(bg="#000000") ### Icon icon_main = tkinter.PhotoImage(file="icons/icons8-ascending-sorting-48.png") self.main.iconphoto(False, icon_main) ### Frame: Canvas + Scrollbar self.lower_part = tkinter.Frame(self.main, bg="#ddddff") ### Bind/Unbind the mousewheel for scrolling self.lower_part.bind('<Enter>', self._bound_to_mousewheel) self.lower_part.bind('<Leave>', self._unbound_to_mousewheel) self.lower_part.grid(row=1, column=0, padx=10, pady=10) ### Control-panel self.control_panel = tkinter.Frame(self.main, width=1200, height=180, bg="#444444", highlightbackground="#ffffff", highlightthickness=2) self.control_panel.grid(row=0, column=0, padx=20, pady=10) ### Canvas self.canvas = tkinter.Canvas(self.lower_part, width=1100, height=380, bg="#ffffff", scrollregion=(0,0,2000,1000)) self.canvas.grid(row=0, column=0, padx=10, pady=10) ###### Basic Layout End ###### ###### Labels, Buttons, ... ###### ### Label self.label_algorithm = tkinter.Label(self.control_panel, text="Algorithm", height=1, font=("italic", 13, "normal"), bg="#ddddff") self.label_algorithm.grid(row=0, column=0, sticky=tkinter.W, padx=(15,2), pady=5) ### Combobox to select algorithm from self.algorithm_selection = ttk.Combobox(self.control_panel, textvariable=tkinter.StringVar(), values=["Bubble Sort", "Selection Sort", "Insertion Sort", "Merge Sort"], width=15, font=("italic", 13, "normal")) self.algorithm_selection.grid(row=0, column=1, padx=(2,15), pady=5) self.algorithm_selection.current(0) ### Seperator self.seperator1 = ttk.Separator(self.control_panel) self.seperator1.grid(row=0, column=2, sticky="ns") ### Label self.number_samples_label = tkinter.Label(self.control_panel, text="Number of elements", height=1, font=("italic", 13, "normal"), bg="#ddddff") self.number_samples_label.grid(row=0, column=3, padx=(15,2), pady=5) ### Combobox to select the number of random elements self.number_samples = ttk.Combobox(self.control_panel, textvariable=tkinter.StringVar(), values=list(range(2, 11)), width=5, font=("italic", 13, "normal")) self.number_samples.grid(row=0, column=4, padx=(2,15), pady=5) self.number_samples.current(0) ### Seperator self.seperator1 = ttk.Separator(self.control_panel) self.seperator1.grid(row=0, column=5, sticky="ns") ### Label self.speed_label = tkinter.Label(self.control_panel, text="Sorting speed", font=("italic", 13, "normal"), bg="#ddddff") self.speed_label.grid(row=0, column=6, padx=(15,2), pady=5) ### Combobox to select sorting speed self.speed = ttk.Combobox(self.control_panel, textvariable=tkinter.StringVar(), values=["Slow", "Normal", "Fast"], width=10, font=("italic", 13, "normal")) self.speed.grid(row=0, column=7, padx=(2,15), pady=5) self.speed.current(0) ### Seperator self.seperator1 = ttk.Separator(self.control_panel) self.seperator1.grid(row=0, column=8, sticky="ns") ### Button to generate a sequence of random numbers self.button_generate = tkinter.Button(self.control_panel, command=self.setup_sorting, text="Generate numbers", font=("italic", 13, "normal"), pady=0) self.button_generate.bind("<Enter>", self._button_generate_enter) self.button_generate.bind("<Leave>", self._button_generate_leave) self.button_generate.grid(row=0, column=9, padx=(15,2), pady=5) ### Button to start sorting self.button_sort = tkinter.Button(self.control_panel, command=self.sort, text="Start sorting", font=("italic", 13, "normal"), pady=0) self.button_sort.bind("<Enter>", self._button_start_enter) self.button_sort.bind("<Leave>", self._button_start_leave) self.button_sort.grid(row=0, column=10, padx=(2,15), pady=5) ### Debug Button self.button_debug = tkinter.Button(self.control_panel, command=self.debug, text="DEBUG") #self.button_debug.grid(row=0, column=11, padx=5, pady=5) ### Make the Canvas scrollable ### Horizontal scrollbar self.hbar = tkinter.Scrollbar(self.lower_part, orient=tkinter.HORIZONTAL) self.hbar.grid(row=1, column=0) self.hbar.config(command=self.canvas.xview) self.canvas.config(xscrollcommand=self.hbar.set) ### Vertical scrollbar self.vbar = tkinter.Scrollbar(self.lower_part, orient=tkinter.VERTICAL) self.vbar.grid(row=0, column=1) self.vbar.config(command=self.canvas.yview) self.canvas.config(yscrollcommand=self.vbar.set) ### Helper param self.new_boxes = list() ######### Event handling functions ######### ### Quit GUI with q; Display help with h def _main_window_action(self, event): if event.char == 'q': self.main.quit() elif event.char == 'h': tkinter.messagebox.showinfo(title="Help", message="1. Select algorithm\n" "2. Select number of elements\n" "3. Select speed\n" "4. Generate sequence\n" "5. Start sorting") ### Change start-button color on <Enter> def _button_start_enter(self, event): self.button_sort.config(bg="#55ff55") ### Change start-button color on <Leave> def _button_start_leave(self, event): self.button_sort.config(bg="#ffffff") ### Change generate-button color on <Enter> def _button_generate_enter(self, event): self.button_generate.config(bg=self.box_color, font=("italic", 13, "normal")) ### Change generate-button color on <Leave> def _button_generate_leave(self, event): self.button_generate.config(bg="#ffffff", font=("italic", 13, "normal")) ### Enable scrolling canvas on <Enter> def _bound_to_mousewheel(self, event): self.canvas.bind("<MouseWheel>", self._on_vertical) self.canvas.bind('<Shift-MouseWheel>', self._on_horizontal) ### Disbale scrolling canvas on <Leave> def _unbound_to_mousewheel(self, event): self.canvas.unbind_all("<MouseWheel>") ### Scroll vertical when using the MouseWheel def _on_vertical(self, event): self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") ### Scroll horizontal when using Shift + MouseWheel def _on_horizontal(self, event): self.canvas.xview_scroll(int(-1 * (event.delta / 120)), "units") ###################################################################### def setup_sorting(self): """ This function generates a sequence of random numbers on the canvas depending on the chosen length. The function is called when clicking the "Generate" button. :return: None """ ### Reset variable when generating a new sequence self.FINISHED_SORTING = False ### Check if the number of elements is not between 2 and 10 ### If True: Show warning and set deafult value 10 if ((n := int(self.number_samples.get())) > 10) or n < 2: tkinter.messagebox.showwarning(title="Warning", message=f"'{n}' is not a valid number of elements!") self.number_samples.set(str(10)) return ### CLear the canvas self.canvas.delete("all") ### Parameters for boxes self.start_x = 200 self.start_y = 100 self.boxSize_x = 50 self.boxSize_y = 50 self.spacing = 25 ### combobox.get() returns a string n = int(self.number_samples.get()) x_tl = self.start_x y_tl = self.start_y x_br = self.start_x + self.boxSize_x y_br = self.start_y + self.boxSize_y self.boxes = list() ### Create multiple canvas objects in loop ### One "box" is a 3-tuple with: (value, box, text_box) ... ### ... where value is a generated random value, box and text_box are IDs to recognize the objects on the canvas for i in range(n): value = random.randint(0,100) box = self.canvas.create_rectangle(x_tl, y_tl, x_br, y_br, fill=self.box_color) text_box = self.canvas.create_text(x_tl + self.boxSize_x / 2, y_tl + self.boxSize_y / 2, text=value, font=("italic",15,"bold")) self.boxes.append((value, box, text_box)) x_tl = x_tl + self.boxSize_x + self.spacing x_br = x_br + self.boxSize_x + self.spacing ### Set the number of comparisons back to 0 self.comparison_label = self.canvas.create_text(100, 20, text="Number of comparisons:", font=("italic", 11, "normal")) self.comparison_number = self.canvas.create_text(200, 20, text="0", font=("italic", 11, "normal")) def swap(self, box_left, box_right, index_left, index_right): """ This function swaps the position of two boxes. Box object: (Value, Rectangle-ID, Text-ID) :param box_left: Box object on the left :param box_right: Box object on the right :param index_left: Index left :param index_right: Index right :return: None """ box1 = box_left box2 = box_right speed = self.get_speed() ### Get the coordinates of the rectangle box1_x_tl, box1_y_tl, box1_x_br, box1_y_br = self.canvas.coords(box1[1]) box2_x_tl, box2_y_tl, box2_x_br, box2_y_br = self.canvas.coords(box2[1]) ### Get the coordinates of the text text1_x_tl, text1_y_tl = self.canvas.coords(box1[2]) text2_x_tl, text2_y_tl = self.canvas.coords(box2[2]) ### Color the boxes red before being swapped self.canvas.itemconfig(box1[1], fill="#ee0000") self.canvas.itemconfig(box2[1], fill="#ee0000") ### An arrow showing the swap switch_arrow = self.canvas.create_line(box1_x_br, box1_y_br - self.boxSize_y/2, box2_x_tl, box2_y_tl + self.boxSize_y/2, arrow="both") self.canvas.update() ### Pause before the swap to help understanding the algorithm time.sleep(speed) ### Move each rectangle to the x position of the other; y remains unchanged self.canvas.move(box1[1], box2_x_tl - box1_x_tl, 0) ### Move the left box by +xy to the right self.canvas.move(box2[1], box1_x_tl - box2_x_tl, 0) ### Move the right box by -xy to the left ### Repeat for the text self.canvas.move(box1[2], text2_x_tl - text1_x_tl, 0) self.canvas.move(box2[2], text1_x_tl - text2_x_tl, 0) ### Pause time.sleep(speed) ### Change the colors back and remove the arrow self.canvas.itemconfig(box1[1], fill=self.box_color) self.canvas.itemconfig(box2[1], fill=self.box_color) self.canvas.delete(switch_arrow) self.canvas.update() ### Switch boxes in self.boxes to keep the right order self.boxes[index_left], self.boxes[index_right] = self.boxes[index_right], self.boxes[index_left] time.sleep(speed) def no_swap(self, box_left, box_right, index_left, index_right): """ This function is called when two boxes should not switched according to the sorting algorithm. :param box_left: Box object on the left :param box_right: Box object on the right :param index_left: Index left :param index_right: Index right :return: None """ speed = self.get_speed() ### Color the boxes green self.canvas.itemconfig(box_left[1], fill="#55cc55") self.canvas.itemconfig(box_right[1], fill="#55cc55") self.canvas.update() ### Pause time.sleep(speed) ### Color the boxes back to blue self.canvas.itemconfig(box_left[1], fill=self.box_color) self.canvas.itemconfig(box_right[1], fill=self.box_color) self.canvas.update() time.sleep(speed) def finished(self): """ This function marks the end of the sorting algorithm by shortly coloring all boxes green in ascending order :return: None """ ### Color boxes green for a short time in ascending order for box in self.boxes: ### Color green self.canvas.itemconfig(box[1], fill="#00ff00") self.canvas.update() ### Pause time.sleep(self.get_speed()/2) ### Color back self.canvas.itemconfig(box[1], fill=self.box_color) self.canvas.update() time.sleep(0.5) ### Color all boxes green to indicate the end for box in self.boxes: ### Color green self.canvas.itemconfig(box[1], fill="#00ff00") self.canvas.update() self.FINISHED_SORTING = True def copy(self): """ This function creates a list with a copy of the existing boxes and moves them below the existing boxes Needed for MergeSort later on :return: List of newly created boxes """ new_boxes = list() ### Create copies for box in self.boxes: box_x_tl, box_y_tl, box_x_br, box_y_br = self.canvas.coords(box[1]) text_x_tl, text_y_tl = self.canvas.coords(box[2]) new_box = self.canvas.create_rectangle(box_x_tl, box_y_tl, box_x_br, box_y_br, fill=self.box_color) new_text = self.canvas.create_text(text_x_tl, text_y_tl, text=box[0], font=("italic",15,"bold")) new_boxes.append((box[0], new_box, new_text)) ### Move new boxes downwards for box in new_boxes: self.canvas.move(box[1], 0, 75) self.canvas.move(box[2], 0, 75) self.canvas.update() return new_boxes def split(self, boxes): """ Helper function for MergeSort. Splits a given array of boxes into two, by moving one half to the left and the other half to the right. :param boxes: The given array of boxes :return: None """ len_arr = len(boxes) mid = len_arr // 2
to complexes, surfaces, chains, ligands, and interfaces. A complete hierarchy of all possible PyMOL groups and objects is shown below: <PDBFileRoot> .Complex .Complex .Surface .Chain<ID> .Complex .Complex .Surface .Chain .Chain .NonInterface .Chain .Surface .Surface .Hydrophobicity .Hydrophobicity_Charge .Vacuum_Electrostatics .Contact_Potentials .Map .Legend .Volume .Solvent .Inorganic .Ligand<ID> .Ligand .Ligand .BallAndStick .Ligand<ID> .Ligand ... ... ... .Chain<ID> ... ... ... .Ligand<ID> ... ... ... .Ligand<ID> ... ... ... .Chain<ID> ... ... ... <PDBFileRoot> .Complex ... ... ... .Chain<ID> ... ... ... .Ligand<ID> ... ... ... .Ligand<ID> ... ... ... .Chain<ID> ... ... ... <Interfaces> .Chain<IDs1>_Chain<IDs2> .Polar_Contacts .Hydrophobic_Contacts .Chain<ID> or Chain<ID>_<PDBFileRoot> .Chain .Residues .Aromatic .Residues .Surface .Hydrophobic .Residues .Surface .Polar .Residues .Surface .Positively_Charged .Residues .Surface .Negatively_Charged .Residues .Surface .Other .Residues .Surface .Surface .Surface .Hydrophobicity .Hydrophobicity_Charge .Vacuum_Electrostatics .Contact_Potentials .Map .Legend .Volume .Chain<ID> or <PDBFileRoot>_Chain<ID> .Chain .Residues ... ... ... .Surface ... ... ... .Chain<IDs>_Chain<IDs> .Polar_Contacts .Hydrophobic_Contacts .Chain<ID> or Chain<ID>_<PDBFileRoot> .Chain .Residues ... ... ... .Surface ... ... ... .Chain<ID> or Chain<ID>_<PDBFileRoot> .Chain .Residues ... ... ... .Surface ... ... ... The hydrophobic and electrostatic surfaces are not created for complete complex and chain complex in input file(s) by default. A word to the wise: The creation of surface objects may slow down loading of PML file and generation of PSE file, based on the size of input complexes. The generation of PSE file may also fail. Options: --allowEmptyObjects <yes or no> [default: no] Allow creation of empty PyMOL objects corresponding to interface, solvent, and inorganic atom selections across chains and ligands in input file(s). By default, the empty objects are marked for deletion. -c, --chainIDs <ChainID1,ChainD2,...> [default: Auto] Pairwise comma delimited list of chain IDs for the identification of macromolecular interfaces. All chain IDs must be present in the same file for a single input file. Otherwise, the first and second chain ID(s) in a pair belong to the first and second input file. The default values for interface chain IDs depend on the number of input files as shown below: One input file: First two chains Two input files: First chain in each input file Each chain may contain multiple chain IDs delimited by a plus sign. For example, A+B,C+D chain pair specifies interface between chain complexes A+B and C+D in first input file or across two input files. -e, --examples Print examples. -h, --help Print this help message. -i, --infiles <infile or infile1,infile2> Name of an input file or a comma delmited list of names for two input files. --interfaceLabelColor <text> [default: magenta] Color for drawing residue or atom level labels for residues in an interface. The specified value must be valid color. No validation is performed. --interfaceContactsCutoff <number> [default: 4.0] Distance in Angstroms for identifying polar and hyrdophobic contacts between atoms in interface reisudes. --interfaceHydrophobicContacts <yes or no> [default: yes] Hydrophobic contacts between residues in an interface. The hydrophobic contacts are shown between pairs of carbon atoms not connected to hydrogen bond donor or acceptors atoms as identified by PyMOL. --interfaceHydrophobicContactsColor <text> [default: purpleblue] Color for drawing hydrophobic contacts between residues in an interface. The specified value must be valid color. No validation is performed. --interfacePolarContacts <yes or no> [default: yes] Polar contacts between residues in an interface. --interfacePolarContactsColor <text> [default: orange] Color for drawing polar contacts between residues in an interface. The specified value must be valid color. No validation is performed. --interfaceResidueTypes <yes or no> [default: auto] Interface residue types. The residue groups are generated using residue types, colors, and names specified by '--residueTypes' option. It is only valid for amino acids. By default, the residue type groups are automatically created for interfaces containing amino acids and skipped for chains only containing nucleic acids. --interfaceSurface <yes or no> [default: auto] Surfaces around interface residues colored by hydrophobicity alone and both hydrophobicity and charge. The hydrophobicity surface is colored at residue level using Eisenberg hydrophobicity scale for residues and color gradient specified by '--surfaceColorPalette' option. The hydrophobicity and charge surface is colored [ REF 140 ] at atom level using colors specified for groups of atoms by '--surfaceAtomTypesColors' option. This scheme allows simultaneous mapping of hyrophobicity and charge values on the surfaces. This option is only valid for amino acids. By default, both surfaces are automatically created for pockets containing amino acids and skipped for pockets containing only nucleic acids. In addition, generic surfaces colored by '--surfaceColors' are always created for interface residues containing amino acids and nucleic acids. --interfaceSurfaceElectrostatics <yes or no> [default: auto] Vacuum electrostatics contact potential surface around interface residues. A word to the wise from PyMOL documentation: The computed protein contact potentials are only qualitatively useful, due to short cutoffs, truncation, and lack of solvent "screening". This option is only valid for amino acids. By default, the electrostatics surface is automatically created for chains containing amino acids and skipped for chains containing only nucleic acids. --labelFontID <number> [default: 7] Font ID for drawing labels. Default: 7 (Sans Bold). Valid values: 5 to 16. The specified value must be a valid PyMOL font ID. No validation is performed. The complete lists of valid font IDs is available at: pymolwiki.org/index.php/Label_font_id. Examples: 5 - Sans; 7 - Sans Bold; 9 - Serif; 10 - Serif Bold. -l, --ligandIDs <Largest, All, None or ID1,ID2...> [default: All] List of ligand IDs to show in chains during visualization of interfaces. Possible values: Largest, All, None, or a comma delimited list of ligand IDs. The default is to show all ligands present in chains involved in interfaces. Ligands are identified using organic selection operator available in PyMOL. It'll also identify buffer molecules as ligands. The largest ligand contains the highest number of heavy atoms. -m, --method <text> [default: BySASAChange] Methodology for the identification of interface residues between a pair of chains in an input file. The interface residues may be identified by change in solvent accessible surface area (SASA) for a residue between a chain and chains complex, distance between heavy atoms in two chains, or distance between CAlpha atoms. Possible values: BySASAChange, ByHeavyAtomsDistance, or ByCAlphaAtomsDistance. --methodCutoff <number> [default: auto] Cutoff value used by different methodologies during the identification of interface residues between a pair of chains. The default values are shown below: BySASAChange: 1.0; Units: Angstrom**2 [ Ref 141 ] ByHeavyAtomsDistance: 5.0; Units: Angstrom [ Ref 142 ] ByCAlphaAtomsDistance: 8.0; Units: Angstrom [ Ref 143 ] -o, --outfile <outfile> Output file name. -p, --PMLOut <yes or no> [default: yes] Save PML file during generation of PSE file. -r, --residueTypes <Type,Color,ResNames,...> [default: auto] Residue types, colors, and names to generate for residue groups during and '--residueTypesChain' option. It is only valid for amino acids. It is a triplet of comma delimited list of amino acid residues type, residues color, and a space delimited list three letter residue names. The default values for residue type, color, and name triplets are shown below: Aromatic,brightorange,HIS PHE TRP TYR, Hydrophobic,orange,ALA GLY VAL LEU ILE PRO MET, Polar,palegreen,ASN GLN SER THR CYS, Positively_Charged,marine,ARG LYS, Negatively_Charged,red,ASP GLU The color name must be a valid PyMOL name. No validation is performed. An amino acid name may appear across multiple residue types. All other residues are grouped under 'Other'. --surfaceChain <yes or no> [default: auto] Surfaces around non-interface residues in individual chain colored by hydrophobicity alone and both hydrophobicity and charge. The hydrophobicity surface is colored at residue level using Eisenberg hydrophobicity scale for residues and color gradient specified by '--surfaceColorPalette' option. The hydrophobicity and charge surface is colored [ REF 140 ] at atom level using colors specified for groups of atoms by '--surfaceAtomTypesColors' option. This scheme allows simultaneous mapping of hyrophobicity and charge values on the surfaces. This option is only valid for amino acids.
= self.master.cell cell.add_node(srv_1) cell.add_node(srv_2) cell.add_node(srv_3) cell.add_node(srv_4) app1 = scheduler.Application('app1', 4, [1, 1, 1], 'app', schedule_once=True) app2 = scheduler.Application('app2', 3, [2, 2, 2], 'app') cell.add_app(cell.partitions[None].allocation, app1) cell.add_app(cell.partitions[None].allocation, app2) # At this point app1 is on server 1, app2 on server 2. self.master.reschedule() treadmill.zkutils.put.assert_has_calls([ mock.call( mock.ANY, '/placement/1/app1', {'expires': 500, 'identity': None, 'identity_count': None}, acl=mock.ANY ), mock.call( mock.ANY, '/placement/2/app2', {'expires': 500, 'identity': None, 'identity_count': None}, acl=mock.ANY ), ], any_order=True) srv_1.state = scheduler.State.down self.master.reschedule() treadmill.zkutils.ensure_deleted.assert_has_calls([ mock.call(mock.ANY, '/placement/1/app1'), mock.call(mock.ANY, '/scheduled/app1'), ]) @mock.patch('kazoo.client.KazooClient.get', mock.Mock()) @mock.patch('kazoo.client.KazooClient.exists', mock.Mock()) @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_exists', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_deleted', mock.Mock()) @mock.patch('treadmill.zkutils.put', mock.Mock()) def test_load_allocation(self): """Tests loading allocation.""" zk_content = { 'allocations': { '.data': """ - name: foo partition: p rank: 100 rank_adjustment: 10 max_utilization: 1.1 """ } } self.make_mock_zk(zk_content) self.master.load_allocations() partition = self.master.cell.partitions['p'] alloc = partition.allocation.get_sub_alloc('foo') self.assertEqual(alloc.rank, 100) self.assertEqual(alloc.rank_adjustment, 10) self.assertEqual(alloc.max_utilization, 1.1) @unittest.skip('Randomly fails with "AssertionError: 21 != 22" line 660') @mock.patch('kazoo.client.KazooClient.get', mock.Mock()) @mock.patch('kazoo.client.KazooClient.exists', mock.Mock()) @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_exists', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_deleted', mock.Mock()) @mock.patch('treadmill.zkutils.put', mock.Mock()) def test_load_partition(self): """Tests loading partition.""" # Access to protected member warning. # # pylint: disable=W0212 zk_content = { 'partitions': { 'test': { '.data': """ partition: test cell: foo memory: 10G cpu: 300% disk: 10G reboot-schedule: 5: [23, 59, 59] 6: [23, 59, 59] """ } } } self.make_mock_zk(zk_content) self.master.load_partitions() partition = self.master.cell.partitions['test'] # 2 days a week times 3 weeks plus one as a sentinel self.assertEqual(len(partition._reboot_buckets), 2 * 3 + 1) zk_content = { 'partitions': { 'test': { '.data': """ partition: test cell: foo memory: 10G cpu: 300% disk: 10G """ } } } self.make_mock_zk(zk_content) self.master.load_partitions() partition = self.master.cell.partitions['test'] # 7 days a week times 3 weeks plus one as a sentinel self.assertEqual(len(partition._reboot_buckets), 7 * 3 + 1) zk_content = { 'partitions': { 'test': { '.data': """ partition: test cell: foo memory: 10G cpu: 300% disk: 10G reboot-schedule: 1: [10, 0, 0] """ } } } self.make_mock_zk(zk_content) self.master.load_partitions() partition = self.master.cell.partitions['test'] # 1 day a week times 3 weeks plus one as a sentinel self.assertEqual(len(partition._reboot_buckets), 1 * 3 + 1) @mock.patch('kazoo.client.KazooClient.get', mock.Mock()) @mock.patch('kazoo.client.KazooClient.exists', mock.Mock()) @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_exists', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_deleted', mock.Mock()) @mock.patch('treadmill.zkutils.put', mock.Mock()) @mock.patch('treadmill.zkutils.update', mock.Mock()) @mock.patch('time.time', mock.Mock(return_value=123.34)) def test_restore_placement(self): """Tests application placement.""" zk_content = { 'placement': { 'test1.xx.com': { '.data': """ state: up since: 100 """, 'xxx.app1#1234': { '.metadata': {'created': 100}, '.data': """ expires: 300 identity: 1 """, }, 'xxx.app2#2345': { '.metadata': {'created': 101}, '.data': """ expires: 300 """, }, }, 'test2.xx.com': { '.data': """ state: up since: 100 """, 'xxx.app3#3456': { '.metadata': {'created': 100}, '.data': """ expires: 300 """, }, 'xxx.app4#4567': { '.metadata': {'created': 101}, '.data': """ expires: 300 """, }, }, 'test3.xx.com': { '.data': """ state: down since: 100 """, 'xxx.app5#5678': { '.metadata': {'created': 100}, '.data': """ expires: 300 """, }, }, }, 'server.presence': { 'test1.xx.com': { '.metadata': {'created': 100}, }, 'test2.xx.com': { '.metadata': {'created': 200}, }, }, 'cell': { 'pod:pod1': {}, 'pod:pod2': {}, }, 'buckets': { 'pod:pod1': { 'traits': None, }, 'pod:pod2': { 'traits': None, }, 'rack:1234': { 'traits': None, 'parent': 'pod:pod1', }, }, 'servers': { 'test1.xx.com': { 'memory': '16G', 'disk': '128G', 'cpu': '400%', 'parent': 'rack:1234', }, 'test2.xx.com': { 'memory': '16G', 'disk': '128G', 'cpu': '400%', 'parent': 'rack:1234', }, 'test3.xx.com': { 'memory': '16G', 'disk': '128G', 'cpu': '400%', 'parent': 'rack:1234', }, }, 'scheduled': { 'xxx.app1#1234': { 'affinity': 'app1', 'memory': '1G', 'disk': '1G', 'cpu': '100%', 'identity_group': 'xxx.app1', }, 'xxx.app2#2345': { 'affinity': 'app2', 'memory': '1G', 'disk': '1G', 'cpu': '100%', 'schedule_once': True, }, 'xxx.app3#3456': { 'affinity': 'app3', 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, 'xxx.app4#4567': { 'affinity': 'app4', 'memory': '1G', 'disk': '1G', 'cpu': '100%', 'schedule_once': True, }, 'xxx.app5#5678': { 'affinity': 'app5', 'memory': '1G', 'disk': '1G', 'cpu': '100%', 'schedule_once': True, }, }, 'identity-groups': { 'xxx.app1': { 'count': 5, } } } self.make_mock_zk(zk_content) self.master.load_buckets() self.master.load_cell() self.master.load_servers() self.master.load_apps() self.master.load_identity_groups() self.master.restore_placements() # Severs test1.xx.com and test2.xx.com are up, test3.xx.com is down. self.assertTrue( self.master.servers['test1.xx.com'].state is scheduler.State.up ) self.assertTrue( self.master.servers['test2.xx.com'].state is scheduler.State.up ) self.assertTrue( self.master.servers['test3.xx.com'].state is scheduler.State.down ) # xxx.app1#1234 restored on test1.xx.com with the same placement expiry self.assertEqual( self.master.cell.apps['xxx.app1#1234'].server, 'test1.xx.com' ) self.assertEqual( self.master.cell.apps['xxx.app1#1234'].placement_expiry, 300 ) # xxx.app2#2345 restored on test2.xx.com with the same placement expiry self.assertEqual( self.master.cell.apps['xxx.app2#2345'].server, 'test1.xx.com' ) self.assertEqual( self.master.cell.apps['xxx.app2#2345'].placement_expiry, 300 ) # xxx.app3#3456 restored on test2.xx.com with new placement expiry self.assertEqual( self.master.cell.apps['xxx.app3#3456'].server, 'test2.xx.com' ) self.assertEqual( self.master.cell.apps['xxx.app3#3456'].placement_expiry, 123.34 ) # xxx.app4#4567 removed (server presence changed, schedule once app) self.assertNotIn('xxx.app4#4567', self.master.cell.apps) treadmill.zkutils.ensure_deleted.assert_any_call( mock.ANY, '/placement/test2.xx.com/xxx.app4#4567' ) treadmill.zkutils.put.assert_any_call( mock.ANY, '/finished/xxx.app4#4567', { 'state': 'terminated', 'host': 'test2.xx.com', 'when': 123.34, 'data': 'schedule_once', }, acl=mock.ANY ) treadmill.zkutils.ensure_deleted.assert_any_call( mock.ANY, '/scheduled/xxx.app4#4567' ) # xxx.app5#5678 removed (server down, schedule once app) self.assertNotIn('xxx.app5#5678', self.master.cell.apps) treadmill.zkutils.ensure_deleted.assert_any_call( mock.ANY, '/placement/test3.xx.com/xxx.app5#5678' ) treadmill.zkutils.put.assert_any_call( mock.ANY, '/finished/xxx.app5#5678', { 'state': 'terminated', 'host': 'test3.xx.com', 'when': 123.34, 'data': 'schedule_once', }, acl=mock.ANY ) treadmill.zkutils.ensure_deleted.assert_any_call( mock.ANY, '/scheduled/xxx.app5#5678' ) # Reschedule should produce no events. treadmill.zkutils.ensure_deleted.reset_mock() treadmill.zkutils.ensure_exists.reset_mock() self.master.reschedule() self.assertFalse(treadmill.zkutils.ensure_deleted.called) self.assertFalse(treadmill.zkutils.ensure_exists.called) # Restore identity self.assertEqual(self.master.cell.apps['xxx.app1#1234'].identity, 1) self.assertEqual( self.master.cell.apps['xxx.app1#1234'].identity_group, 'xxx.app1' ) self.assertEqual( self.master.cell.identity_groups['xxx.app1'].available, set([0, 2, 3, 4]) ) @mock.patch('kazoo.client.KazooClient.get', mock.Mock()) @mock.patch('kazoo.client.KazooClient.exists', mock.Mock()) @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_exists', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_deleted', mock.Mock()) @mock.patch('treadmill.zkutils.put', mock.Mock()) @mock.patch('treadmill.zkutils.update', mock.Mock()) def test_restore_with_integrity_err(self): """Tests application placement.""" zk_content = { 'placement': { 'test1.xx.com': { '.data': """ state: up since: 100 """, 'xxx.app1#1234': { '.metadata': {'created': 100}, }, 'xxx.app2#2345': { '.metadata': {'created': 101}, }, }, 'test2.xx.com': { '.data': """ state: up since: 100 """, 'xxx.app1#1234': { '.metadata': {'created': 100}, }, } }, 'server.presence': { 'test1.xx.com': { '.metadata': {'created': 100}, }, 'test2.xx.com': { '.metadata': {'created': 100}, }, }, 'cell': { 'pod:pod1': {}, 'pod:pod2': {}, }, 'buckets': { 'pod:pod1': { 'traits': None, }, 'pod:pod2': { 'traits': None, }, 'rack:1234': { 'traits': None, 'parent': 'pod:pod1', }, }, 'servers': { 'test1.xx.com': { 'memory': '16G', 'disk': '128G', 'cpu': '400%', 'parent': 'rack:1234', }, 'test2.xx.com': { 'memory': '16G', 'disk': '128G', 'cpu': '400%', 'parent': 'rack:1234', }, }, 'scheduled': { 'xxx.app1#1234': { 'affinity': 'app1', 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, 'xxx.app2#2345': { 'affinity': 'app2', 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, } } self.make_mock_zk(zk_content) self.master.load_buckets() self.master.load_cell() self.master.load_servers() self.master.load_apps() self.master.restore_placements() self.assertIn('xxx.app2#2345', self.master.servers['test1.xx.com'].apps) self.assertIsNone(self.master.cell.apps['xxx.app1#1234'].server) @mock.patch('kazoo.client.KazooClient.get', mock.Mock()) @mock.patch('kazoo.client.KazooClient.exists', mock.Mock()) @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock()) @mock.patch('kazoo.client.KazooClient.set', mock.Mock()) @mock.patch('kazoo.client.KazooClient.create', mock.Mock()) @mock.patch('kazoo.client.KazooClient.exists', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_deleted', mock.Mock()) @mock.patch('treadmill.zkutils.put', mock.Mock()) @mock.patch('time.time', mock.Mock(return_value=100)) def test_apps_blacklist_events(self): """Tests apps_blacklist events.""" zk_content = { 'scheduled': { 'xxx.app1#1234': { 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, 'xxx.app2#2345': { 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, 'yyy.app3#3456': { 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, 'yyy.app4#4567': { 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, 'zzz.app5#5678': { 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, }, 'events': { '000-apps_blacklist-12345': None, }, } self.make_mock_zk(zk_content) self.master.load_apps() self.assertFalse(self.master.cell.apps['xxx.app1#1234'].blacklisted) self.assertFalse(self.master.cell.apps['xxx.app2#2345'].blacklisted) self.assertFalse(self.master.cell.apps['yyy.app3#3456'].blacklisted) self.assertFalse(self.master.cell.apps['yyy.app4#4567'].blacklisted) self.assertFalse(self.master.cell.apps['zzz.app5#5678'].blacklisted) zk_content['blackedout.apps'] = { '.data': """ xxx.*: {reason: test, when: 1234567890.0} yyy.app3: {reason: test, when: 1234567890.0} """ } self.master.process_events(['000-apps_blacklist-12345']) self.assertTrue(self.master.cell.apps['xxx.app1#1234'].blacklisted) self.assertTrue(self.master.cell.apps['xxx.app2#2345'].blacklisted) self.assertTrue(self.master.cell.apps['yyy.app3#3456'].blacklisted) self.assertFalse(self.master.cell.apps['yyy.app4#4567'].blacklisted) self.assertFalse(self.master.cell.apps['zzz.app5#5678'].blacklisted) @mock.patch('kazoo.client.KazooClient.get', mock.Mock()) @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_exists', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_deleted', mock.Mock()) @mock.patch('treadmill.zkutils.put', mock.Mock()) @mock.patch('treadmill.scheduler.master.Master.load_allocations', mock.Mock()) @mock.patch('treadmill.scheduler.master.Master.load_apps', mock.Mock()) @mock.patch('treadmill.scheduler.master.Master.load_app', mock.Mock()) def test_app_events(self): """Tests application placement.""" zk_content = { 'events': { '001-allocations-12345': {}, '000-apps-12346': { '.data': """ - xxx.app1#1234 - xxx.app2#2345 """ }, }, } self.make_mock_zk(zk_content) self.master.watch('/events') while True: try: event = self.master.queue.popleft() self.master.process(event) except IndexError: break self.assertTrue(master.Master.load_allocations.called) self.assertTrue(master.Master.load_apps.called) master.Master.load_app.assert_has_calls([ mock.call('xxx.app1#1234'), mock.call('xxx.app2#2345'), ]) @mock.patch('kazoo.client.KazooClient.get', mock.Mock()) @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_exists', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_deleted', mock.Mock()) @mock.patch('treadmill.zkutils.put', mock.Mock()) @mock.patch('treadmill.scheduler.master.Master.load_allocations', mock.Mock()) @mock.patch('treadmill.scheduler.master.Master.load_apps', mock.Mock()) @mock.patch('treadmill.scheduler.master.Master.load_app', mock.Mock()) def test_alloc_events(self): """Tests allocation events.""" zk_content = { 'events': { '001-allocations-12345': {}, }, } self.make_mock_zk(zk_content) self.master.watch('/events') while True: try: event = self.master.queue.popleft() self.master.process(event) except IndexError: break self.assertTrue(master.Master.load_allocations.called) self.assertTrue(master.Master.load_apps.called) @mock.patch('kazoo.client.KazooClient.get', mock.Mock()) @mock.patch('kazoo.client.KazooClient.exists', mock.Mock()) @mock.patch('kazoo.client.KazooClient.get_children', mock.Mock()) @mock.patch('kazoo.client.KazooClient.set', mock.Mock()) @mock.patch('kazoo.client.KazooClient.create', mock.Mock()) @mock.patch('kazoo.client.KazooClient.exists', mock.Mock()) @mock.patch('treadmill.zkutils.ensure_deleted', mock.Mock()) @mock.patch('treadmill.zkutils.put', mock.Mock()) @mock.patch('time.time', mock.Mock(return_value=100)) def test_server_state_events(self): """Tests server_state events.""" zk_content = { 'placement': { 'test.xx.com': { '.data': """ state: up since: 100 """, 'xxx.app1#1234': { '.metadata': {'created': 100}, }, 'xxx.app2#2345': { '.metadata': {'created': 101}, }, }, }, 'server.presence': { 'test.xx.com': { '.metadata': {'created': 100}, }, }, 'cell': { 'pod:pod1': {}, }, 'buckets': { 'pod:pod1': { 'traits': None, }, 'rack:1234': { 'traits': None, 'parent': 'pod:pod1', }, }, 'servers': { 'test.xx.com': { 'memory': '16G', 'disk': '128G', 'cpu': '400%', 'parent': 'rack:1234', }, }, 'scheduled': { 'xxx.app1#1234': { 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, 'xxx.app2#2345': { 'memory': '1G', 'disk': '1G', 'cpu': '100%', }, }, 'events': { '000-server_state-12345': { '.data': """ - test.xx.com - frozen - [xxx.app1#1234] """ }, }, } self.make_mock_zk(zk_content) self.master.load_buckets() self.master.load_cell() self.master.load_servers() self.master.load_apps() self.master.restore_placements() #
<gh_stars>0 #!/usr/bin/env python import os import argparse from plantcv import plantcv as pcv # Parse command-line arguments def options(): parser = argparse.ArgumentParser(description="Imaging processing with opencv") parser.add_argument("-i", "--image", help="Input image file.", required=True) parser.add_argument("-o", "--outdir", help="Output directory for image files.", required=False) parser.add_argument("-r", "--result", help="result file.", required=False) parser.add_argument("-w", "--writeimg", help="write out images.", default=False, action="store_true") parser.add_argument("-D", "--debug", help="can be set to 'print' or None (or 'plot' if in jupyter) prints intermediate images.", default=None) args = parser.parse_args() return args def main(): # Initialize options args = options() # Set PlantCV debug mode to input debug method pcv.params.debug = args.debug # Use PlantCV to read in the input image. The function outputs an image as a NumPy array, the path to the file, # and the image filename img, path, filename = pcv.readimage(filename=args.image) # ## Segmentation # ### Saturation channel # Convert the RGB image to HSV colorspace and extract the saturation channel s = pcv.rgb2gray_hsv(rgb_img=img, channel='s') # Use a binary threshold to set an inflection value where all pixels in the grayscale saturation image below the # threshold get set to zero (pure black) and all pixels at or above the threshold get set to 255 (pure white) s_thresh = pcv.threshold.binary(gray_img=s, threshold=80, max_value=255, object_type='light') # ### Blue-yellow channel # Convert the RGB image to LAB colorspace and extract the blue-yellow channel b = pcv.rgb2gray_lab(rgb_img=img, channel='b') # Use a binary threshold to set an inflection value where all pixels in the grayscale blue-yellow image below the # threshold get set to zero (pure black) and all pixels at or above the threshold get set to 255 (pure white) b_thresh = pcv.threshold.binary(gray_img=b, threshold=134, max_value=255, object_type='light') # ### Green-magenta channel # Convert the RGB image to LAB colorspace and extract the green-magenta channel a = pcv.rgb2gray_lab(rgb_img=img, channel='a') # In the green-magenta image the plant pixels are darker than the background. Setting object_type="dark" will # invert the image first and then use a binary threshold to set an inflection value where all pixels in the # grayscale green-magenta image below the threshold get set to zero (pure black) and all pixels at or above the # threshold get set to 255 (pure white) a_thresh = pcv.threshold.binary(gray_img=a, threshold=122, max_value=255, object_type='dark') # Combine the binary images for the saturation and blue-yellow channels. The "or" operator returns a binary image # that is white when a pixel was white in either or both input images bs = pcv.logical_or(bin_img1=s_thresh, bin_img2=b_thresh) # Combine the binary images for the combined saturation and blue-yellow channels and the green-magenta channel. # The "or" operator returns a binary image that is white when a pixel was white in either or both input images bsa = pcv.logical_or(bin_img1=bs, bin_img2=a_thresh) # The combined binary image labels plant pixels well but the background still has pixels labeled as foreground. # Small white noise (salt) in the background can be removed by filtering white objects in the image by size and # setting a size threshold where smaller objects can be removed bsa_fill1 = pcv.fill(bin_img=bsa, size=15) # Fill small noise # Before more stringent size filtering is done we want to connect plant parts that may still be disconnected from # the main plant. Use a dilation to expand the boundary of white regions. Ksize is the size of a box scanned # across the image and i is the number of times a scan is done bsa_fill2 = pcv.dilate(gray_img=bsa_fill1, ksize=3, i=3) # Remove small objects by size again but use a higher threshold bsa_fill3 = pcv.fill(bin_img=bsa_fill2, size=250) # Use the binary image to identify objects or connected components. id_objects, obj_hierarchy = pcv.find_objects(img=img, mask=bsa_fill3) # Because the background still contains pixels labeled as foreground, the object list contains background. # Because these images were collected in an automated system the plant is always centered in the image at the # same position each time. Define a region of interest (ROI) to set the area where we expect to find plant # pixels. PlantCV can make simple ROI shapes like rectangles, circles, etc. but here we use a custom ROI to fit a # polygon around the plant area roi_custom, roi_hier_custom = pcv.roi.custom(img=img, vertices=[[1085, 1560], [1395, 1560], [1395, 1685], [1890, 1744], [1890, 25], [600, 25], [615, 1744], [1085, 1685]]) # Use the ROI to filter out objects found outside the ROI. When `roi_type = "cutto"` objects outside the ROI are # cropped out. The default `roi_type` is "partial" which allows objects to overlap the ROI and be retained roi_objects, hierarchy, kept_mask, obj_area = pcv.roi_objects(img=img, roi_contour=roi_custom, roi_hierarchy=roi_hier_custom, object_contour=id_objects, obj_hierarchy=obj_hierarchy, roi_type='cutto') # Filter remaining objects by size again to remove any remaining background objects filled_mask1 = pcv.fill(bin_img=kept_mask, size=350) # Use a closing operation to first dilate (expand) and then erode (shrink) the plant to fill in any additional # gaps in leaves or stems filled_mask2 = pcv.closing(gray_img=filled_mask1) # Remove holes or dark spot noise (pepper) in the plant binary image filled_mask3 = pcv.fill_holes(filled_mask2) # With the clean binary image identify the contour of the plant id_objects, obj_hierarchy = pcv.find_objects(img=img, mask=filled_mask3) # Because a plant or object of interest may be composed of multiple contours, it is required to combine all # remaining contours into a single contour before measurements can be done obj, mask = pcv.object_composition(img=img, contours=id_objects, hierarchy=obj_hierarchy) # ## Measurements PlantCV has several built-in measurement or analysis methods. Here, basic measurements of size # and shape are done. Additional typical modules would include plant height (`pcv.analyze_bound_horizontal`) and # color (`pcv.analyze_color`) shape_img = pcv.analyze_object(img=img, obj=obj, mask=mask) # Save the shape image if requested if args.writeimg: outfile = os.path.join(args.outdir, filename[:-4] + "_shapes.png") pcv.print_image(img=shape_img, filename=outfile) # ## Morphology workflow # Update a few PlantCV parameters for plotting purposes pcv.params.text_size = 1.5 pcv.params.text_thickness = 5 pcv.params.line_thickness = 15 # Convert the plant mask into a "skeletonized" image where each path along the stem and leaves are a single pixel # wide skel = pcv.morphology.skeletonize(mask=mask) # Sometimes wide parts of leaves or stems are skeletonized in the direction perpendicular to the main path. These # "barbs" or "spurs" can be removed by pruning the skeleton to remove small paths. Pruning will also separate the # individual path segments (leaves and stem parts) pruned, segmented_img, segment_objects = pcv.morphology.prune(skel_img=skel, size=30, mask=mask) pruned, segmented_img, segment_objects = pcv.morphology.prune(skel_img=pruned, size=3, mask=mask) # Leaf and stem segments above are separated but only into individual paths. We can sort the segments into stem # and leaf paths by identifying primary segments (stems; those that end in a branch point) and secondary segments # (leaves; those that begin at a branch point and end at a tip point) leaf_objects, other_objects = pcv.morphology.segment_sort(skel_img=pruned, objects=segment_objects, mask=mask) # Label the segment unique IDs segmented_img, labeled_id_img = pcv.morphology.segment_id(skel_img=pruned, objects=leaf_objects, mask=mask) # Measure leaf insertion angles. Measures the angle between a line fit through the stem paths and a line fit # through the first `size` points of each leaf path labeled_angle_img = pcv.morphology.segment_insertion_angle(skel_img=pruned, segmented_img=segmented_img, leaf_objects=leaf_objects, stem_objects=other_objects, size=22) # Save leaf angle image if requested if args.writeimg: outfile = os.path.join(args.outdir, filename[:-4] + "_leaf_insertion_angles.png") pcv.print_image(img=labeled_angle_img, filename=outfile) # ## Other potential morphological measurements There are many other functions that extract data from within the # morphology sub-package of PlantCV. For our purposes, we are most interested in the relative angle between each # leaf and the stem which we measure with `plantcv.morphology.segment_insertion_angle`. However, the following # cells show some of the other traits that we are able to measure from images that can be succesfully sorted into # primary and secondary segments. # Segment the plant binary mask using the leaf and stem segments. Allows for the measurement of individual leaf # areas # filled_img = pcv.morphology.fill_segments(mask=mask, objects=leaf_objects) # Measure the path length of each leaf (geodesic distance) # labeled_img2 = pcv.morphology.segment_path_length(segmented_img=segmented_img, objects=leaf_objects) # Measure the straight-line, branch point to tip distance (Euclidean) for each leaf # labeled_img3 = pcv.morphology.segment_euclidean_length(segmented_img=segmented_img, objects=leaf_objects) #
- x1: not used - x2: not used 3. triangle - x1: not used - x2: not used 4. expon_min - x1: slope {0 = no slope -> 10 = sharp slope} - x2: not used 5. expon_max - x1: slope {0 = no slope -> 10 = sharp slope} - x2: not used 6. biexpon - x1: bandwidth {0 = huge bandwidth -> 10 = narrow bandwidth} - x2: not used 7. cauchy - x1: bandwidth {0 = narrow bandwidth -> 10 = huge bandwidth} - x2: not used 8. weibull - x1: mean location {0 -> 1} - x2: shape {0.5 = linear min, 1.5 = expon min, 3.5 = gaussian} 9. gaussian - x1: mean location {0 -> 1} - x2: bandwidth {0 = narrow bandwidth -> 10 = huge bandwidth} 10. poisson - x1: gravity center {0 = low values -> 10 = high values} - x2: compress/expand range {0.1 = full compress -> 4 full expand} 11. walker - x1: maximum value {0.1 -> 1} - x2: maximum step {0.1 -> 1} 12. loopseg - x1: maximum value {0.1 -> 1} - x2: maximum step {0.1 -> 1} >>> s = Server().boot() >>> s.start() >>> l = Phasor(.4) >>> rnd = XnoiseMidi('loopseg', freq=8, x1=1, x2=l, scale=0, mrange=(60,96)) >>> freq = Snap(rnd, choice=[0, 2, 3, 5, 7, 8, 11], scale=1) >>> jit = Randi(min=0.99, max=1.01, freq=[2.33,3.41]) >>> a = SineLoop(freq*jit, feedback=0.03, mul=.2).out() """ def __init__(self, dist=0, freq=1.0, x1=0.5, x2=0.5, scale=0, mrange=(0, 127), mul=1, add=0): pyoArgsAssert(self, "OOOixOO", freq, x1, x2, scale, mrange, mul, add) PyoObject.__init__(self, mul, add) self._dist = dist self._freq = freq self._x1 = x1 self._x2 = x2 self._scale = scale self._mrange = mrange dist, freq, x1, x2, scale, mrange, mul, add, lmax = convertArgsToLists( dist, freq, x1, x2, scale, mrange, mul, add ) for i, t in enumerate(dist): if type(t) in [bytes_t, unicode_t]: dist[i] = XNOISE_DICT.get(t, 0) self._base_objs = [ XnoiseMidi_base( wrap(dist, i), wrap(freq, i), wrap(x1, i), wrap(x2, i), wrap(scale, i), wrap(mrange, i), wrap(mul, i), wrap(add, i), ) for i in range(lmax) ] self._init_play() def setDist(self, x): """ Replace the `dist` attribute. :Args: x: string or int new `dist` attribute. """ self._dist = x x, lmax = convertArgsToLists(x) for i, t in enumerate(x): if type(t) in [bytes_t, unicode_t]: x[i] = XNOISE_DICT.get(t, 0) [obj.setType(wrap(x, i)) for i, obj in enumerate(self._base_objs)] def setScale(self, x): """ Replace the `scale` attribute. Possible values are: 0. Midi notes 1. Hertz 2. transposition factor (centralkey is (`minrange` + `maxrange`) / 2 :Args: x: int {0, 1, 2} new `scale` attribute. """ pyoArgsAssert(self, "i", x) self._scale = x x, lmax = convertArgsToLists(x) [obj.setScale(wrap(x, i)) for i, obj in enumerate(self._base_objs)] def setRange(self, mini, maxi): """ Replace the `mrange` attribute. :Args: mini: int minimum output midi range. maxi: int maximum output midi range. """ pyoArgsAssert(self, "ii", mini, maxi) self._mrange = (mini, maxi) mini, maxi, lmax = convertArgsToLists(mini, maxi) [obj.setRange(wrap(mini, i), wrap(maxi, i)) for i, obj in enumerate(self._base_objs)] def setX1(self, x): """ Replace the `x1` attribute. :Args: x: float or PyoObject new `x1` attribute. """ pyoArgsAssert(self, "O", x) self._x1 = x x, lmax = convertArgsToLists(x) [obj.setX1(wrap(x, i)) for i, obj in enumerate(self._base_objs)] def setX2(self, x): """ Replace the `x2` attribute. :Args: x: float or PyoObject new `x2` attribute. """ pyoArgsAssert(self, "O", x) self._x2 = x x, lmax = convertArgsToLists(x) [obj.setX2(wrap(x, i)) for i, obj in enumerate(self._base_objs)] def setFreq(self, x): """ Replace the `freq` attribute. :Args: x: float or PyoObject new `freq` attribute. """ pyoArgsAssert(self, "O", x) self._freq = x x, lmax = convertArgsToLists(x) [obj.setFreq(wrap(x, i)) for i, obj in enumerate(self._base_objs)] def ctrl(self, map_list=None, title=None, wxnoserver=False): self._map_list = [ SLMap(0, 12, "lin", "dist", self._dist, res="int", dataOnly=True), SLMap(0.001, 200.0, "log", "freq", self._freq), SLMap(0, 1, "lin", "x1", self._x1), SLMap(0, 1, "lin", "x2", self._x2), SLMap(0, 2, "lin", "scale", self._scale, res="int", dataOnly=True), ] PyoObject.ctrl(self, map_list, title, wxnoserver) @property def dist(self): """string or int. Distribution type.""" return self._dist @dist.setter def dist(self, x): self.setDist(x) @property def freq(self): """float or PyoObject. Polling frequency.""" return self._freq @freq.setter def freq(self, x): self.setFreq(x) @property def x1(self): """float or PyoObject. First parameter.""" return self._x1 @x1.setter def x1(self, x): self.setX1(x) @property def x2(self): """float or PyoObject. Second parameter.""" return self._x2 @x2.setter def x2(self, x): self.setX2(x) @property def scale(self): """int. Output format.""" return self._scale @scale.setter def scale(self, x): self.setScale(x) class XnoiseDur(PyoObject): """ Recursive time varying X-class pseudo-random generator. Xnoise implements a few of the most common noise distributions. Each distribution generates values in the range 0 to 1, which are then rescaled between `min` and `max` arguments. The object uses the generated value to set the delay time before the next generation. XnoiseDur will hold the value until next generation. :Parent: :py:class:`PyoObject` :Args: dist: string or int, optional Distribution type. Can be the name of the distribution as a string or its associated number. Defaults to 0. min: float or PyoObject, optional Minimum value for the random generation. Defaults to 0. max: float or PyoObject, optional Maximum value for the random generation. Defaults to 1. x1: float or PyoObject, optional First parameter. Defaults to 0.5. x2: float or PyoObject, optional Second parameter. Defaults to 0.5. .. note:: Available distributions are: 0. uniform 1. linear minimum 2. linear maximum 3. triangular 4. exponential minimum 5. exponential maximum 6. double (bi)exponential 7. cauchy 8. weibull 9. gaussian 10. poisson 11. walker (drunk) 12. loopseg (drunk with looped segments) Depending on the distribution, `x1` and `x2` parameters are applied as follow (names as string, or associated number can be used as `dist` parameter): 0. uniform - x1: not used - x2: not used 1. linear_min - x1: not used - x2: not used 2. linear_max - x1: not used - x2: not used 3. triangle - x1: not used - x2: not used 4. expon_min - x1: slope {0 = no slope -> 10 = sharp slope} - x2: not used 5. expon_max - x1: slope {0 = no slope -> 10 = sharp slope} - x2: not used 6. biexpon - x1: bandwidth {0 = huge bandwidth -> 10 = narrow bandwidth} - x2: not used 7. cauchy - x1: bandwidth {0 = narrow bandwidth -> 10 = huge bandwidth} - x2: not used 8. weibull - x1: mean location {0 -> 1} - x2: shape {0.5 = linear min, 1.5 = expon min, 3.5 = gaussian} 9. gaussian - x1: mean location {0 -> 1} - x2: bandwidth {0 = narrow bandwidth -> 10 = huge bandwidth} 10. poisson - x1: gravity center {0 = low values -> 10 = high values} - x2: compress/expand range {0.1 = full compress -> 4 full expand} 11. walker - x1: maximum value {0.1 -> 1} - x2: maximum step {0.1 -> 1} 12. loopseg - x1: maximum value {0.1 -> 1} - x2: maximum step {0.1 -> 1} >>> s = Server().boot() >>> s.start() >>> dur = XnoiseDur(dist="expon_min", min=[.05,0.1], max=[.4,.5], x1=3) >>> trig = Change(dur) >>> amp = TrigEnv(trig, table=HannTable(), dur=dur, mul=.2) >>> freqs = midiToHz([60,63,67,70,72]) >>> freq = TrigChoice(trig, choice=freqs) >>> a = LFO(freq=freq, type=2, mul=amp).out() """ def __init__(self, dist=0, min=0.0, max=1.0, x1=0.5, x2=0.5, mul=1, add=0): pyoArgsAssert(self, "OOOOOO", min, max, x1, x2, mul, add) PyoObject.__init__(self, mul, add) self._dist = dist self._min = min self._max = max self._x1 = x1 self._x2 = x2 dist, min, max, x1, x2, mul, add, lmax = convertArgsToLists(dist, min, max, x1, x2, mul, add) for i, t in enumerate(dist): if type(t) in [bytes_t, unicode_t]: dist[i] = XNOISE_DICT.get(t, 0) self._base_objs = [ XnoiseDur_base( wrap(dist, i), wrap(min, i), wrap(max, i), wrap(x1, i), wrap(x2, i), wrap(mul, i), wrap(add, i) ) for i in range(lmax) ] self._init_play() def setDist(self, x): """ Replace the `dist` attribute. :Args: x: string or int new `dist` attribute. """ self._dist = x x, lmax = convertArgsToLists(x) for i, t in enumerate(x): if type(t) in [bytes_t, unicode_t]: x[i]
<gh_stars>1-10 from __future__ import absolute_import, print_function from PyDSTool.common import * from PyDSTool.errors import * from PyDSTool.utils import remain, info from PyDSTool.Points import Point, Pointset from numpy import array, asarray, NaN, Inf, isfinite from PyDSTool.matplotlib_import import gca, plt from copy import copy _classes = ['connection', 'node', 'simulator', 'composed_map1D', 'map', 'map1D', 'map2D', 'identity_map', 'delay_map'] _functions = ['extract_digraph'] _instances = ['idmap'] __all__ = _classes + _functions + _instances # ------------------------------------------------------------------------------ class connection(object): def __init__(self, name): self.name = name # input is a node object self.input = None # output is for informational purposes only # (nodes keyed by name) self.outputs = {} # map is of type map (defaults to identity) self.map = idmap def poll(self): # poll input return self.map(self.input.last_t) def __repr__(self): return "connection(%s)" % self.name __str__ = __repr__ class node(object): def __init__(self, name): self.name = name # inputs are connection objects self.inputs = {} # output is for informational purposes only # (connections keyed by name) self.outputs = {} # projected state self.next_t = 0 # last state (set by simulator.set_state) self.last_t = 0 # current input values self.in_vals = {} # map attribute will be of type map self.map = None def poll(self, state): #print "\n ** ", self.name, "received state:", state self.in_vals.update(state) # poll inputs for name, connxn in self.inputs.items(): self.in_vals[connxn.input.name] = connxn.poll() #print "... passing input values", self.in_vals self.next_t = self.map(self.in_vals) return self.next_t def __repr__(self): return "node(%s)" % self.name __str__ = __repr__ class FIFOqueue_uniquenode(object): """Only one entry per node is allowed. !! Does not allow for simultaneous events !! """ def __init__(self, node_names): self.nodes = node_names self.reset() def push(self, t, node_name): old_t = self.by_node[node_name] if t != old_t: self.by_node[node_name] = t self.by_time[t] = node_name if isfinite(old_t): del self.by_time[old_t] self.next_t = min(self.by_time.keys()) def reset(self): self.by_time = {Inf: None} self.next_t = Inf self.by_node = dict.fromkeys(self.nodes, Inf) def pop(self): t = self.next_t if isfinite(t): val = (t, self.by_time[t]) del self.by_time[t] self.by_node[val[1]] = Inf self.next_t = min(self.by_time.keys()) return val else: raise PyDSTool_UndefinedError("Empty queue") def extract_digraph(mspec, node_types, connxn_types): """Extract directed graph of connections from a ModelSpec description of a dynamical systems model, using the node and connection types provided. The name attributes of those types are used to search the ModelSpec. """ connxn_names = mspec.search(connxn_types) node_names = mspec.search(node_types) # declare connection and node objects connxns = {} nodes = {} for c in connxn_names: cobj = mspec.components[c] new_connxn = connection(c) connxns[c] = new_connxn for n in node_names: nobj = mspec.components[n] new_node = node(n) nodes[n] = new_node # fill in inputs and outputs dictionaries for each type for cn, c in connxns.items(): cobj = mspec.components[cn] targs = [head(t) for t in cobj.connxnTargets] c.outputs = dict(zip(targs, [nodes[t] for t in targs])) for t in targs: nodes[t].inputs[cn] = c for nn, n in nodes.items(): nobj = mspec.components[nn] targs = [head(t) for t in nobj.connxnTargets] n.outputs = dict(zip(targs, [connxns[t] for t in targs])) for t in targs: connxns[t].input = n return nodes, connxns def head(hier_name): if '.' in hier_name: return hier_name.split('.')[0] else: return hier_name def tail(hier_name): if '.' in hier_name: return hier_name.split('.')[-1] else: return hier_name # maps' inputs and output are absolute times -- # for dealing with relative times they must be passed a reference # time value to add to a relative time. class map(object): pass class map2D(map): pass class map1D(map): pass class delay_map(map1D): def __init__(self, delay): self.delay = delay def __call__(self, t): return t + self.delay class identity_map(map1D): def __call__(self, t): return t # default instance of identity class idmap = identity_map() class composed_map1D(map1D): def __init__(self, m1, m2): self.m1 = m1 self.m2 = m2 def __call__(self, t): return self.m1(self.m2(t)) # ----------------------------------------------------------------------------- class simulator(object): """Mapping-based, event-driven simulator for dynamical systems reductions. """ def __init__(self, nodes, connections, state=None): self.nodes = nodes # don't really need the connections, but just as a reference self.connections = connections if state is None: self.state = dict(zip(nodes.keys(), [NaN for n in nodes])) else: self.state = state self.curr_t = 0 self.history = {} self.verbosity = 0 self.Q = FIFOqueue_uniquenode(list(nodes.keys())) def set_node_state(self): for name, n in self.nodes.items(): n.last_t = self.state[name] def validate(self): for name, n in self.nodes.items(): assert isinstance(n, node) for name, connxn in self.connections.items(): assert isinstance(connxn, connection) assert sortedDictKeys(self.state) == sortedDictKeys(self.nodes), \ "Invalid or missing node state in history argument" def run(self, history, t_end): """history is a dictionary of t -> (event node name, {node name: state}) values. Initial time of simulator will be the largest t in this dictionary. """ self.curr_t = max(history.keys()) assert t_end > self.curr_t, "t_end too small" self.state = history[self.curr_t][1].copy() # structural validation of model self.validate() node_names = sortedDictKeys(self.state) self.history = history.copy() done = False while not done: last_state = self.state.copy() print("\n ***", self.curr_t, self.history[self.curr_t][0], self.state) next_t = Inf iters = 1 nodes = self.nodes.copy() # set the last_t of each node self.set_node_state() try: proj_state = self.compile_next_state(nodes) except PyDSTool_BoundsError: print("Maps borked at", self.curr_t) done = True break print("Projected:", proj_state) for node, t in proj_state.items(): if t > self.curr_t: self.Q.push(t, node) # self.state[next_node] = self.Q.next_t if self.verbosity > 0: print("Took %i iterations to stabilize" % iters) self.display() t, next_node = self.Q.pop() while self.curr_t > t: t, next_node = self.Q.pop() self.curr_t = t self.history[self.curr_t] = (next_node, last_state) ##print " * last state =", last_state next_state = last_state next_state[next_node] = self.curr_t # must copy here to ensure history elements don't get # overwritten self.state = next_state.copy() if self.verbosity > 0: print("Next node is", next_node, "at time ", self.curr_t) done = self.curr_t >= t_end continue ## vals = sortedDictValues(projected_states) filt_vals = [] min_val = Inf min_ix = None for i, v in enumerate(vals): if v > self.curr_t: if v < min_val: min_val = v min_ix = i ## else: ## # do not ignore projected times that are in the past relative to ## # curr_t! Must retrgrade curr_t to the earliest newly projected time. ## if v not in self.history: ## if v < min_val: ## min_val = v ## min_ix = i if min_ix is None: # no further events possible print("No further events possible, stopping!") break ## if min_val < self.curr_t: ## # clear later history ## print "Clearing later history items that are invalid" ## for t, s in sortedDictItems(self.history): ## if t > min_val: ## del self.history[t] self.curr_t = min_val next_state = self.state[1].copy() next_node = node_names[min_ix] next_state[next_node] = min_val self.history[min_val] = (next_node, next_state) self.state = (next_node, next_state) if self.verbosity > 0: print("Next node is", next_node, "at time ", self.curr_t) done = self.curr_t >= t_end ts, state_dicts = sortedDictLists(self.history, byvalue=False) vals = [] for (evnode, vd) in state_dicts: vals.append([vd[nname] for nname in node_names]) self.result = Pointset(indepvararray=ts, indepvarname='t', coordnames = node_names, coordarray = array(vals).T) def compile_next_state(self, nodes): vals = {} for name, n in nodes.items(): vals[name] = n.poll(self.state) return vals def display(self): print("\n****** t =", self.curr_t) info(self.state, "known state") print("\nNodes:") for name, n in self.nodes.items(): #n.poll(self.state) print(name) for in_name, in_val in n.in_vals.items(): print(" Input", in_name, ": ", in_val) def extract_history_events(self): node_names = list(self.nodes.keys()) node_events = dict(zip(node_names, [None]*len(node_names))) ts = sortedDictKeys(self.history) old_node, old_state = self.history[ts[0]] # deal with initial conditions first for nn in node_names: node_events[nn] = [old_state[nn]] # do the rest for t in ts: node, state = self.history[t] node_events[node].append(t) return node_events def display_raster(self, new_figure=True): h = self.history ts = sortedDictKeys(h) node_names = list(self.nodes.keys()) print("\n\nNode order in plot (bottom to top) is", node_names) if new_figure: plt.figure() t0 = ts[0] node, state = h[t0] # show all initial conditions for ni, n in enumerate(node_names): plt.plot(state[n], ni, 'ko') # plot the rest for t in ts: node, state = h[t] plt.plot(t, node_names.index(node), 'ko') a = gca() a.set_ylim(-0.5, len(node_names)-0.5) def sequences_to_eventlist(seq_dict): """seq_dict maps string symbols to increasing-ordered sequences of times. Returns a single list of (symbol, time) pairs ordered by time.""" out_seq = [] symbs = list(seq_dict.keys()) next_s = None indices = {} for s in symbs: indices[s] = 0 remaining_symbs = symbs while remaining_symbs != []: #print "\n***", remaining_symbs to_remove = [] #print indices #print out_seq, "\n" next_t = Inf for s in remaining_symbs: try: t = seq_dict[s][indices[s]] except IndexError: # no times remaining for this symbol #print "No more symbols for ", s to_remove.append(s) else: #print s, t if t < next_t: next_s = s next_t =
import os import sys import csv import json import math import enum import numpy as np import matplotlib.pyplot as plt from matplotlib import colors from os import listdir from os.path import isfile, join from skimage import measure from skimage import filters from scipy import ndimage class OutputShapeType(enum.Enum): Constant = 1 Input = 2 Unknown = 3 class HypothesisType(enum.Enum): SymbolTx = 1 BG_SYMBOL = 0 NUM_SYMBOLS = 10 def get_symbol_cmap_and_norm(): cmap = colors.ListedColormap( ['#000000', '#0074D9','#FF4136','#2ECC40','#FFDC00', '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25']) norm = colors.Normalize(vmin=0, vmax=9) return cmap, norm # https://towardsdatascience.com/canny-edge-detection-step-by-step-in-python-computer-vision-b49c3a2d8123 def gaussian_kernel(size, sigma=1): size = int(size) // 2 x, y = np.mgrid[-size:size+1, -size:size+1] normal = 1 / (2.0 * np.pi * sigma**2) g = np.exp(-((x**2 + y**2) / (2.0*sigma**2))) * normal return g def sobel_filters(img): Kx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.float32) Ky = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], np.float32) Ix = ndimage.filters.convolve(img, Kx) Iy = ndimage.filters.convolve(img, Ky) G = np.hypot(Ix, Iy) G = G / G.max() * 255 theta = np.arctan2(Iy, Ix) return (G, theta) def non_max_suppression(img, D): M, N = img.shape Z = np.zeros((M,N), dtype=np.int32) angle = D * 180. / np.pi angle[angle < 0] += 180 for i in range(1,M-1): for j in range(1,N-1): try: q = 255 r = 255 #angle 0 if (0 <= angle[i,j] < 22.5) or (157.5 <= angle[i,j] <= 180): q = img[i, j+1] r = img[i, j-1] #angle 45 elif (22.5 <= angle[i,j] < 67.5): q = img[i+1, j-1] r = img[i-1, j+1] #angle 90 elif (67.5 <= angle[i,j] < 112.5): q = img[i+1, j] r = img[i-1, j] #angle 135 elif (112.5 <= angle[i,j] < 157.5): q = img[i-1, j-1] r = img[i+1, j+1] if (img[i,j] >= q) and (img[i,j] >= r): Z[i,j] = img[i,j] else: Z[i,j] = 0 except IndexError as e: pass return Z def plot_one(task,ax, i,train_or_test,input_or_output): cmap, norm = get_symbol_cmap_and_norm() input_matrix = task[train_or_test][i][input_or_output] ax.imshow(input_matrix, cmap=cmap, norm=norm) ax.grid(True,which='both',color='lightgrey', linewidth=0.5) ax.set_yticks([x-0.5 for x in range(1+len(input_matrix))]) ax.set_xticks([x-0.5 for x in range(1+len(input_matrix[0]))]) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_title(train_or_test + ' '+input_or_output) def plot_ans(ans,ax): cmap, norm = get_symbol_cmap_and_norm() ax.imshow(ans, cmap=cmap, norm=norm) ax.grid(True,which='both',color='lightgrey', linewidth=0.5) ax.set_yticks([x-0.5 for x in range(1+len(ans))]) ax.set_xticks([x-0.5 for x in range(1+len(ans[0]))]) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_title('Hypothesis') def plot_task(task, ans=None): """ Plots the first train and test pairs of a specified task, using same color scheme as the ARC app """ num_train = len(task['train']) print('num_train',num_train) fig, axs = plt.subplots(2, num_train, figsize=(3*num_train,3*2)) for i in range(num_train): plot_one(task,axs[0,i],i,'train','input') plot_one(task,axs[1,i],i,'train','output') plt.tight_layout() plt.show() num_test = len(task['test']) print('num_test',num_test) num_subplots = 2 if ans is not None: num_subplots = 3 fig, axs = plt.subplots(num_subplots, num_test, figsize=(3*num_test,3*num_subplots)) if num_test==1: plot_one(task,axs[0],0,'test','input') plot_one(task,axs[1],0,'test','output') else: for i in range(num_test): plot_one(task,axs[0,i],i,'test','input') plot_one(task,axs[1,i],i,'test','output') if ans is not None: plot_ans(ans,axs[2]) plt.tight_layout() plt.show() def plot_components(symbols, component_labels, bb_image): # https://matplotlib.org/3.1.3/api/_as_gen/matplotlib.pyplot.subplot.html # Either a 3-digit integer or three separate integers describing the position of the subplot. # If the three integers are nrows, ncols, and index in order, the subplot will take the index # position on a grid with nrows rows and ncols columns. index starts at 1 in the upper # left corner and increases to the right. cmap, norm = get_symbol_cmap_and_norm() plt.figure(figsize=(9, 3.5)) ax1 = plt.subplot(131) plt.imshow(symbols, cmap=cmap, norm=norm) ax1.title.set_text('symbols') plt.axis('off') ax2 = plt.subplot(132) plt.imshow(component_labels, cmap='nipy_spectral') ax2.title.set_text('all labels') plt.axis('off') ax3 = plt.subplot(133) plt.imshow(bb_image, cmap='nipy_spectral') ax3.title.set_text('bounding boxes') plt.axis('off') plt.tight_layout() plt.show() def find_output_shape(input_shapes,output_shapes): num_shapes = len(input_shapes) assert(num_shapes > 0) # constant shape h0 = output_shapes[0][0] w0 = output_shapes[0][1] # all hypotheses are true until proven false constant_shape = True input_shape = True for i in range(0,num_shapes): h = output_shapes[i][0] w = output_shapes[i][1] if (h != h0) or (w != w0): constant_shape = False #print('w/h',w,h) hi = input_shapes[i][0] wi = input_shapes[i][1] if (h != hi) or (w != wi): input_shape = False if constant_shape: return OutputShapeType.Constant, None elif input_shape: return OutputShapeType.Input, None return OutputShapeType.Unknown, None def get_percentage(n, total): return 100.0*(float(n)/float(total)) # Colours # 0 and 5 seem to have special meanings. 0 is background. # 5 may be some sort of separator structure. # How preserved is this? # 0 1 2 3 4 # ['#000000', '#0074D9','#FF4136','#2ECC40','#FFDC00', # 5 6 7 8 9 # '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25']) def rgb_2_grey(rgb): """A "grid" is a rectangular matrix (list of lists) of integers between 0 and 9 (inclusive). The smallest possible grid size is 1x1 and the largest is 30x30.""" # symbol (integer between 0 and 9, which are visualized as colors). #rgb_weights = [0.2989, 0.5870, 0.1140] rgb_weights = [0.333, 0.333, 0.333] grey = np.dot(rgb[...,:3], rgb_weights) return grey def symbol_2_grey(symbols): """A "grid" is a rectangular matrix (list of lists) of integers between 0 and 9 (inclusive). The smallest possible grid size is 1x1 and the largest is 30x30.""" # symbol (integer between 0 and 9, which are visualized as colors). # all symbol values are equally different. So to convert, make a series of masks. # e.g. * --> 1 for symbol in range(0,9): is_true = 1.0 is_false = 0.0 x = symbols.where(symbols == 0, is_true, is_false) def symbol_2_edges(symbols): # 0 1 2 # a b # 0 1 2 3 # a b c h = symbols.shape[0] w = symbols.shape[1] eh = h + h -1 ew = w + w -1 edges = np.zeros((eh,ew)) for y in range(0,h): for x in range(0,w): #is_edge = 0.0 s = symbols[y][x] for dy in range(-1,2): for dx in range(-1,2): y2 = y+dy x2 = x+dx if (x2 == x) and (y2 == y): continue # Non edge if (y2 < 0) or (x2 < 0) or (y2 >= h) or (x2 >= w): continue # ignore image edges - non edge s2 = symbols[y2][x2] if s2 != s: #is_edge = 1.0 # 1 2 < 3*2=6 # 1 2 < 2*2=4 # 0 1 2 3 4 5 # a b c d e # 0123456789 ey = y * 2 + dy ex = x * 2 + dx edges[ey][ex] = 1.0 return edges def find_density(symbols): h = symbols.shape[0] w = symbols.shape[1] mass = 0.0 for y in range(0,h): for x in range(0,w): #is_edge = 0.0 s = symbols[y][x] if s != 0: mass += 1 area = h * w density = mass / area return density def find_bounding_boxes(component_labels, num_labels): bounding_boxes = {} bb_image = np.zeros(component_labels.shape) h = component_labels.shape[0] w = component_labels.shape[1] mass = 0.0 symbols = [] for y in range(0,h): for x in range(0,w): label_value = component_labels[y][x] # if label_value == 0: # print('has bg') # has_background = True if label_value in bounding_boxes.keys(): bounding_box = bounding_boxes[label_value] x_min = bounding_box[0] y_min = bounding_box[1] x_max = bounding_box[2] y_max = bounding_box[3] x_min = min(x,x_min) y_min = min(y,y_min) x_max = max(x,x_max) y_max = max(y,y_max) bounding_box[0] = x_min bounding_box[1] = y_min bounding_box[2] = x_max bounding_box[3] = y_max else: symbols.append(label_value) bounding_box = [x,y,x,y] bounding_boxes[label_value] = bounding_box # if has_background: # num_labels += 1 print('all BBs ', bounding_boxes) num_symbols = len(symbols) for i in range(0, num_symbols): label = symbols[i] if label == 0: continue # don't draw bounding_box = bounding_boxes[label] #print('bb of label', label, bounding_box) x_min = bounding_box[0] y_min = bounding_box[1] x_max = bounding_box[2] y_max = bounding_box[3] bw = x_max - x_min +1 bh = y_max - y_min +1 for x in range(0,bw): bb_image[y_min][x+x_min] = 1.0 bb_image[y_max][x+x_min] = 1.0 for y in range(0,bh): bb_image[y+y_min][x_min] = 1.0 bb_image[y+y_min][x_max] = 1.0 return bounding_boxes, bb_image def find_symmetry(image): plt.figure() plt.imshow(image, cmap='gray') plt.tight_layout() plt.show() class Hypothesis: def __init__(self): pass def apply(self, example_input, output_shape_type, output_shape): output = np.zeros(output_shape) return output class SymbolTxHypo(Hypothesis): def __init__(self, s1, s2): self.s1 = s1 self.s2 = s2 def apply(self, example_input, output_shape_type, output_shape): if output_shape_type != OutputShapeType.Input: print('shape mismatch') return output = np.zeros(example_input.shape) h = example_input.shape[0] w = example_input.shape[1] for y in range(0,h): for x in range(0,w): s1 = example_input[y][x] s2 = s1 if s1 == float(self.s1): #print('$$$', self.s2) s2 = int(self.s2) output[y][x] = s2 return output def evaluate_output(example_output, hypo_output): errors = 0 h = example_output.shape[0] w = example_output.shape[1] if hypo_output is None: return h*w
request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_amendment_swagger_with_http_info(query_string, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str query_string: The query string used to search. (required) :param list[str] organizations: A list of organization-IDs used to restrict the scope of API calls. :param int offset: The starting index of the search results. :param int records: The number of search results to return. :param bool wildcard: Toggle if we search for full words or whether a wildcard is used. :param bool entity: Is an entity returned with the search results. :return: SwaggerTypeList If the method is called asynchronously, returns the request thread. """ all_params = ['query_string', 'organizations', 'offset', 'records', 'wildcard', 'entity'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_amendment_swagger" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'query_string' is set if ('query_string' not in params) or (params['query_string'] is None): raise ValueError("Missing the required parameter `query_string` when calling `get_amendment_swagger`") resource_path = '/amendments/swagger-end-point/{query-string}'.replace('{format}', 'json') path_params = {} if 'query_string' in params: path_params['query-string'] = params['query_string'] query_params = {} if 'organizations' in params: query_params['organizations'] = params['organizations'] if 'offset' in params: query_params['offset'] = params['offset'] if 'records' in params: query_params['records'] = params['records'] if 'wildcard' in params: query_params['wildcard'] = params['wildcard'] if 'entity' in params: query_params['entity'] = params['entity'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['text/plain']) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SwaggerTypeList', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only')) def get_amendments_by_actioning_time(self, lower_threshold, upper_threshold, **kwargs): """ Returns a collection of amendment objects with an actioning-time within the period specified by the lower-threshold and upper-threshold parameters. By default 10 values are returned. Records are returned in natural order. {\"nickname\":\"Retrieve by actioning\",\"response\":\"getAmendmentByActioningTime.html\"} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_amendments_by_actioning_time(lower_threshold, upper_threshold, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str lower_threshold: The UTC DateTime specifying the start of the result period. (required) :param str upper_threshold: The UTC DateTime specifying the end of the result period. (required) :param list[str] organizations: A list of organization-IDs used to restrict the scope of API calls. :param int offset: The offset from the first amendment to return. :param int records: The maximum number of amendments to return. :param str order_by: Specify a field used to order the result set. :param str order: Ihe direction of any ordering, either ASC or DESC. :return: AmendmentPagedMetadata If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_amendments_by_actioning_time_with_http_info(lower_threshold, upper_threshold, **kwargs) else: (data) = self.get_amendments_by_actioning_time_with_http_info(lower_threshold, upper_threshold, **kwargs) return data def get_amendments_by_actioning_time_with_http_info(self, lower_threshold, upper_threshold, **kwargs): """ Returns a collection of amendment objects with an actioning-time within the period specified by the lower-threshold and upper-threshold parameters. By default 10 values are returned. Records are returned in natural order. {\"nickname\":\"Retrieve by actioning\",\"response\":\"getAmendmentByActioningTime.html\"} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_amendments_by_actioning_time_with_http_info(lower_threshold, upper_threshold, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str lower_threshold: The UTC DateTime specifying the start of the result period. (required) :param str upper_threshold: The UTC DateTime specifying the end of the result period. (required) :param list[str] organizations: A list of organization-IDs used to restrict the scope of API calls. :param int offset: The offset from the first amendment to return. :param int records: The maximum number of amendments to return. :param str order_by: Specify a field used to order the result set. :param str order: Ihe direction of any ordering, either ASC or DESC. :return: AmendmentPagedMetadata If the method is called asynchronously, returns the request thread. """ all_params = ['lower_threshold', 'upper_threshold', 'organizations', 'offset', 'records', 'order_by', 'order'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_amendments_by_actioning_time" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'lower_threshold' is set if ('lower_threshold' not in params) or (params['lower_threshold'] is None): raise ValueError("Missing the required parameter `lower_threshold` when calling `get_amendments_by_actioning_time`") # verify the required parameter 'upper_threshold' is set if ('upper_threshold' not in params) or (params['upper_threshold'] is None): raise ValueError("Missing the required parameter `upper_threshold` when calling `get_amendments_by_actioning_time`") resource_path = '/amendments/actioning-time/{lower-threshold}/{upper-threshold}'.replace('{format}', 'json') path_params = {} if 'lower_threshold' in params: path_params['lower-threshold'] = params['lower_threshold'] if 'upper_threshold' in params: path_params['upper-threshold'] = params['upper_threshold'] query_params = {} if 'organizations' in params: query_params['organizations'] = params['organizations'] if 'offset' in params: query_params['offset'] = params['offset'] if 'records' in params: query_params['records'] = params['records'] if 'order_by' in params: query_params['order_by'] = params['order_by'] if 'order' in params: query_params['order'] = params['order'] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type([]) # Authentication setting auth_settings = [] return self.api_client.call_api(resource_path, 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AmendmentPagedMetadata', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only')) def get_amendments_by_created_date(self, lower_threshold, upper_threshold, **kwargs): """ Returns a collection of amendment objects with created times within the period specified by the lower-threshold and upper-threshold parameters. By default 10 values are returned. Records are returned in natural order. {\"nickname\":\"Retrieve by creation\",\"response\":\"getAmendmentByCreated.html\"} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_amendments_by_created_date(lower_threshold, upper_threshold, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str lower_threshold: The UTC DateTime specifying the start of the result period. (required) :param str upper_threshold: The UTC DateTime specifying the end of the result period. (required) :param list[str] organizations: A list of organization-IDs used to restrict the scope of API calls. :param int offset: The offset from the first amendment to return. :param int records: The maximum number of amendments to return. :param str order_by: Specify a field used to order the result set. :param str order: Ihe direction of any ordering, either ASC or DESC. :return: AmendmentPagedMetadata If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_amendments_by_created_date_with_http_info(lower_threshold, upper_threshold, **kwargs) else: (data) = self.get_amendments_by_created_date_with_http_info(lower_threshold, upper_threshold, **kwargs) return data def get_amendments_by_created_date_with_http_info(self, lower_threshold, upper_threshold, **kwargs): """ Returns a collection of amendment objects with created times within the period specified by the lower-threshold and upper-threshold parameters. By default 10 values are returned. Records are returned in natural order. {\"nickname\":\"Retrieve by creation\",\"response\":\"getAmendmentByCreated.html\"} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_amendments_by_created_date_with_http_info(lower_threshold, upper_threshold, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str lower_threshold: The UTC DateTime specifying the start of the result period. (required) :param str upper_threshold: The UTC DateTime specifying the end of the result period. (required) :param list[str] organizations: A list of organization-IDs used to restrict the scope of API calls. :param int offset: The offset from the first amendment to return. :param int records: The maximum number of amendments to return. :param str order_by: Specify a field used to order the result set. :param str order: Ihe direction of any ordering, either ASC or DESC.
import time import pytest from py_ecc import ( bn128, optimized_bn128, bls12_381, optimized_bls12_381, ) from py_ecc.fields import ( bls12_381_FQ, bls12_381_FQ2, bls12_381_FQ12, bn128_FQ, bn128_FQ2, bn128_FQ12, optimized_bls12_381_FQ, optimized_bls12_381_FQ2, optimized_bls12_381_FQ12, optimized_bn128_FQ, optimized_bn128_FQ2, optimized_bn128_FQ12, ) from py_ecc.fields.field_properties import ( field_properties, ) @pytest.fixture(params=[bn128, optimized_bn128, bls12_381, optimized_bls12_381]) def lib(request): return request.param @pytest.fixture def FQ(lib): if lib == bn128: return bn128_FQ elif lib == optimized_bn128: return optimized_bn128_FQ elif lib == bls12_381: return bls12_381_FQ elif lib == optimized_bls12_381: return optimized_bls12_381_FQ else: raise Exception("Library Not Found") @pytest.fixture def FQ2(lib): if lib == bn128: return bn128_FQ2 elif lib == optimized_bn128: return optimized_bn128_FQ2 elif lib == bls12_381: return bls12_381_FQ2 elif lib == optimized_bls12_381: return optimized_bls12_381_FQ2 else: raise Exception("Library Not Found") @pytest.fixture def FQ12(lib): if lib == bn128: return bn128_FQ12 elif lib == optimized_bn128: return optimized_bn128_FQ12 elif lib == bls12_381: return bls12_381_FQ12 elif lib == optimized_bls12_381: return optimized_bls12_381_FQ12 else: raise Exception("Library Not Found") @pytest.fixture def field_modulus(lib): if lib == bn128 or lib == optimized_bn128: return field_properties["bn128"]["field_modulus"] elif lib == bls12_381 or lib == optimized_bls12_381: return field_properties["bls12_381"]["field_modulus"] else: raise Exception("Library Not Found") @pytest.fixture def G1(lib): return lib.G1 @pytest.fixture def G2(lib): return lib.G2 @pytest.fixture def G12(lib): return lib.G12 @pytest.fixture def Z1(lib): return lib.Z1 @pytest.fixture def Z2(lib): return lib.Z2 @pytest.fixture def b(lib): return lib.b @pytest.fixture def b2(lib): return lib.b2 @pytest.fixture def b12(lib): return lib.b12 @pytest.fixture def is_inf(lib): return lib.is_inf @pytest.fixture def is_on_curve(lib): return lib.is_on_curve @pytest.fixture def eq(lib): return lib.eq @pytest.fixture def add(lib): return lib.add @pytest.fixture def double(lib): return lib.double @pytest.fixture def curve_order(lib): return lib.curve_order @pytest.fixture def multiply(lib): return lib.multiply @pytest.fixture def pairing(lib): return lib.pairing @pytest.fixture def neg(lib): return lib.neg @pytest.fixture def twist(lib): return lib.twist def test_FQ_object(FQ, field_modulus): assert FQ(2) * FQ(2) == FQ(4) assert FQ(2) / FQ(7) + FQ(9) / FQ(7) == FQ(11) / FQ(7) assert FQ(2) * FQ(7) + FQ(9) * FQ(7) == FQ(11) * FQ(7) assert FQ(9) ** field_modulus == FQ(9) assert FQ(-1).n > 0 def test_FQ2_object(FQ2, field_modulus): x = FQ2([1, 0]) f = FQ2([1, 2]) fpx = FQ2([2, 2]) one = FQ2.one() z1, z2 = FQ2([-1, -1]).coeffs assert x + f == fpx assert f / f == one assert one / f + x / f == (one + x) / f assert one * f + x * f == (one + x) * f assert x ** (field_modulus ** 2 - 1) == one if isinstance(z1, int): assert z1 > 0 assert z2 > 0 else: assert z1.n > 0 assert z2.n > 0 def test_FQ12_object(FQ12, field_modulus): x = FQ12([1] + [0] * 11) f = FQ12([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) fpx = FQ12([2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) one = FQ12.one() zs = FQ12([-1]*12).coeffs assert x + f == fpx assert f / f == one assert one / f + x / f == (one + x) / f assert one * f + x * f == (one + x) * f if isinstance(zs[0], int): assert all(z > 0 for z in zs) else: assert all(z.n > 0 for z in zs) # This check takes too long # assert x ** (field_modulus ** 12 - 1) == one def test_G1_object(G1, eq, double, add, multiply, curve_order, is_inf): assert eq(add(add(double(G1), G1), G1), double(double(G1))) assert not eq(double(G1), G1) assert eq(add(multiply(G1, 9), multiply(G1, 5)), add(multiply(G1, 12), multiply(G1, 2))) assert is_inf(multiply(G1, curve_order)) def test_G2_object(G2, b2, eq, add, double, multiply, is_inf, curve_order, field_modulus, is_on_curve): assert eq(add(add(double(G2), G2), G2), double(double(G2))) assert not eq(double(G2), G2) assert eq(add(multiply(G2, 9), multiply(G2, 5)), add(multiply(G2, 12), multiply(G2, 2))) assert is_inf(multiply(G2, curve_order)) assert not is_inf(multiply(G2, 2 * field_modulus - curve_order)) assert is_on_curve(multiply(G2, 9), b2) def test_G12_object(G12, b12, eq, add, double, multiply, is_on_curve, is_inf, curve_order): assert eq(add(add(double(G12), G12), G12), double(double(G12))) assert not eq(double(G12), G12) assert eq(add(multiply(G12, 9), multiply(G12, 5)), add(multiply(G12, 12), multiply(G12, 2))) assert is_on_curve(multiply(G12, 9), b12) assert is_inf(multiply(G12, curve_order)) def test_Z1_object(add, eq, double, FQ, G1, is_inf, multiply, neg, twist, Z1): assert eq(G1, add(G1, Z1)) assert eq(Z1, double(Z1)) assert eq(Z1, multiply(Z1, 0)) assert eq(Z1, multiply(Z1, 1)) assert eq(Z1, multiply(Z1, 2)) assert eq(Z1, multiply(Z1, 3)) assert is_inf(neg(Z1)) def test_Z2_object(add, eq, double, FQ2, G2, is_inf, multiply, neg, twist, Z2): assert eq(G2, add(G2, Z2)) assert eq(Z2, double(Z2)) assert eq(Z2, multiply(Z2, 0)) assert eq(Z2, multiply(Z2, 1)) assert eq(Z2, multiply(Z2, 2)) assert eq(Z2, multiply(Z2, 3)) assert is_inf(neg(Z2)) assert is_inf(twist(Z2)) def test_none_point(lib, neg, twist): if lib not in [optimized_bn128, optimized_bls12_381]: pytest.skip() with pytest.raises(Exception): neg(None) with pytest.raises(Exception): twist(None) def test_pairing_negative_G1(pairing, G1, G2, FQ12, curve_order, multiply, neg): p1 = pairing(G2, G1) pn1 = pairing(G2, neg(G1)) assert p1 * pn1 == FQ12.one() def test_pairing_negative_G2(pairing, G1, G2, FQ12, curve_order, multiply, neg): p1 = pairing(G2, G1) pn1 = pairing(G2, neg(G1)) np1 = pairing(neg(G2), G1) assert p1 * np1 == FQ12.one() assert pn1 == np1 def test_pairing_output_order(G1, G2, FQ12, pairing, curve_order): p1 = pairing(G2, G1) assert p1 ** curve_order == FQ12.one() def test_pairing_bilinearity_on_G1(G1, G2, neg, multiply, pairing): p1 = pairing(G2, G1) p2 = pairing(G2, multiply(G1, 2)) np1 = pairing(neg(G2), G1) assert p1 * p1 == p2 def test_pairing_is_non_degenerate(G1, G2, neg, pairing, multiply): p1 = pairing(G2, G1) p2 = pairing(G2, multiply(G1, 2)) np1 = pairing(neg(G2), G1) assert p1 != p2 and p1 != np1 and p2 != np1 def test_pairing_bilinearity_on_G2(G1, G2, pairing, multiply): p1 = pairing(G2, G1) po2 = pairing(multiply(G2, 2), G1) assert p1 * p1 == po2 def test_pairing_composit_check(G1, G2, multiply, pairing): p3 = pairing(multiply(G2, 27), multiply(G1, 37)) po3 = pairing(G2, multiply(G1, 999)) assert p3 == po3 """ for lib in (bn128, optimized_bn128): FQ, FQ2, FQ12, field_modulus = lib.FQ, lib.FQ2, lib.FQ12, lib.field_modulus assert FQ(2) * FQ(2) == FQ(4) assert FQ(2) / FQ(7) + FQ(9) / FQ(7) == FQ(11) / FQ(7) assert FQ(2) * FQ(7) + FQ(9) * FQ(7) == FQ(11) * FQ(7) assert FQ(9) ** field_modulus == FQ(9) print('FQ works fine') x = FQ2([1, 0]) f = FQ2([1, 2]) fpx = FQ2([2, 2]) one = FQ2.one() assert x + f == fpx assert f / f == one assert one / f + x / f == (one + x) / f assert one * f + x * f == (one + x) * f assert x ** (field_modulus ** 2 - 1) == one print('FQ2 works fine') x = FQ12([1] + [0] * 11) f = FQ12([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) fpx = FQ12([2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) one = FQ12.one() assert x + f == fpx assert f / f == one assert one / f + x / f == (one + x) / f assert one * f + x * f == (one + x) * f # This check takes too long # assert x ** (field_modulus ** 12 - 1) == one print('FQ12 works fine') G1, G2, G12, b, b2, b12, is_inf, is_on_curve, eq, add, double, curve_order, multiply = \ lib.G1, lib.G2, lib.G12, lib.b, lib.b2, lib.b12, lib.is_inf, lib.is_on_curve, lib.eq, lib.add, lib.double, lib.curve_order, lib.multiply assert eq(add(add(double(G1), G1), G1), double(double(G1))) assert not eq(double(G1), G1) assert eq(add(multiply(G1, 9), multiply(G1, 5)), add(multiply(G1, 12), multiply(G1, 2))) assert is_inf(multiply(G1, curve_order)) print('G1 works fine') assert eq(add(add(double(G2), G2), G2), double(double(G2))) assert not eq(double(G2), G2) assert eq(add(multiply(G2, 9), multiply(G2, 5)), add(multiply(G2, 12), multiply(G2, 2))) assert is_inf(multiply(G2, curve_order)) assert not is_inf(multiply(G2, 2 * field_modulus - curve_order)) assert is_on_curve(multiply(G2, 9), b2) print('G2 works fine') assert eq(add(add(double(G12), G12), G12), double(double(G12))) assert not eq(double(G12), G12) assert eq(add(multiply(G12, 9), multiply(G12, 5)), add(multiply(G12, 12), multiply(G12, 2))) assert is_on_curve(multiply(G12, 9), b12) assert is_inf(multiply(G12, curve_order)) print('G12 works fine') pairing, neg = lib.pairing, lib.neg print('Starting pairing tests') a = time.time() p1 = pairing(G2, G1) pn1 = pairing(G2, neg(G1)) assert p1 * pn1 == FQ12.one() print('Pairing check against negative in G1 passed') np1 = pairing(neg(G2), G1) assert p1 * np1 == FQ12.one() assert pn1 == np1 print('Pairing check against negative in G2 passed') assert p1 ** curve_order == FQ12.one() print('Pairing output has correct order') p2 = pairing(G2, multiply(G1, 2)) assert p1 * p1 == p2 print('Pairing bilinearity in G1 passed') assert p1 != p2 and p1 != np1 and p2 != np1 print('Pairing is non-degenerate') po2 = pairing(multiply(G2, 2), G1) assert p1 * p1 == po2 print('Pairing bilinearity in G2 passed') p3 = pairing(multiply(G2, 27), multiply(G1, 37)) po3 = pairing(G2, multiply(G1, 999)) assert p3 == po3 print('Composite check passed') print('Total time for pairings: %.3f' % (time.time() -
<reponame>fchapoton/sage r""" Subcrystals These are the crystals that are subsets of a larger ambient crystal. AUTHORS: - <NAME> (2013-10-16): Initial implementation """ #***************************************************************************** # Copyright (C) 2013 <NAME> <tscrim at ucdavis.edu> # # Distributed under the terms of the GNU General Public License (GPL) # # This code 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. # # The full text of the GPL is available at: # # http://www.gnu.org/licenses/ #**************************************************************************** from sage.misc.lazy_attribute import lazy_attribute from sage.structure.unique_representation import UniqueRepresentation from sage.structure.parent import Parent from sage.structure.element_wrapper import ElementWrapper from sage.categories.crystals import Crystals from sage.categories.finite_crystals import FiniteCrystals from sage.categories.supercrystals import SuperCrystals from sage.combinat.root_system.cartan_type import CartanType from sage.rings.integer import Integer from sage.rings.infinity import infinity from sage.structure.richcmp import richcmp class Subcrystal(UniqueRepresentation, Parent): r""" A subcrystal `X` of an ambient crystal `Y` is a crystal formed by taking a subset of `Y` and whose crystal structure is induced by `Y`. INPUT: - ``ambient`` -- the ambient crystal - ``contained`` -- (optional) a set (or function) which specifies when an element is contained in the subcrystal; the default is everything possible is included - ``generators`` -- (optional) the generators for the subcrystal; the default is the generators for the ambient crystal - ``virtualization``, ``scaling_factors`` -- (optional) dictionaries whose key `i` corresponds to the sets `\sigma_i` and `\gamma_i` respectively used to define virtual crystals; see :class:`~sage.combinat.crystals.virtual_crystal.VirtualCrystal` - ``cartan_type`` -- (optional) the Cartan type for the subcrystal; the default is the Cartan type for the ambient crystal - ``index_set`` -- (optional) the index set for the subcrystal; the default is the index set for the Cartan type - ``category`` -- (optional) the category for the subcrystal; the default is the :class:`~sage.categories.crystals.Crystals` category .. SEEALSO:: :meth:`~sage.categories.crystals.Crystals.ParentMethods.subcrystal` EXAMPLES: We build out a subcrystal starting from an element and only going to the lowest weight:: sage: B = crystals.Tableaux(['A',3], shape=[2,1]) sage: S = B.subcrystal(generators=[B(3,1,2)], direction='lower') sage: S.cardinality() 11 Here we build out in both directions starting from an element, but we also have restricted ourselves to type `A_2`:: sage: T = B.subcrystal(index_set=[1,2], generators=[B(3,1,1)]) sage: T.cardinality() 8 sage: list(T) [[[1, 1], [3]], [[1, 2], [3]], [[1, 1], [2]], [[2, 2], [3]], [[1, 2], [2]], [[2, 3], [3]], [[1, 3], [2]], [[1, 3], [3]]] Now we take the crystal corresponding to the intersection of the previous two subcrystals:: sage: U = B.subcrystal(contained=lambda x: x in S and x in T, generators=B) sage: list(U) [[[2, 3], [3]], [[1, 2], [3]], [[2, 2], [3]]] .. TODO:: Include support for subcrystals which only contains certain arrows. TESTS: Check that the subcrystal respects being in the category of supercrystals (:trac:`27368`):: sage: T = crystals.Tableaux(['A',[1,1]], [2,1]) sage: S = T.subcrystal(max_depth=3) sage: S.category() Category of finite super crystals """ @staticmethod def __classcall_private__(cls, ambient, contained=None, generators=None, virtualization=None, scaling_factors=None, cartan_type=None, index_set=None, category=None): """ Normalize arguments to ensure a (relatively) unique representation. EXAMPLES:: sage: B = crystals.Tableaux(['A',4], shape=[2,1]) sage: S1 = B.subcrystal(generators=(B(2,1,1), B(5,2,4)), index_set=[1,2]) sage: S2 = B.subcrystal(generators=[B(2,1,1), B(5,2,4)], cartan_type=['A',4], index_set=(1,2)) sage: S1 is S2 True """ if isinstance(contained, (list, tuple, set, frozenset)): contained = frozenset(contained) #elif contained in Sets(): if cartan_type is None: cartan_type = ambient.cartan_type() else: cartan_type = CartanType(cartan_type) if index_set is None: index_set = cartan_type.index_set if generators is None: generators = ambient.module_generators category = Crystals().or_subcategory(category) if ambient in SuperCrystals(): category = category & SuperCrystals() if ambient in FiniteCrystals() or isinstance(contained, frozenset): category = category.Finite() if virtualization is not None: if scaling_factors is None: scaling_factors = {i:1 for i in index_set} from sage.combinat.crystals.virtual_crystal import VirtualCrystal return VirtualCrystal(ambient, virtualization, scaling_factors, contained, generators, cartan_type, index_set, category) if scaling_factors is not None: # virtualization must be None virtualization = {i:(i,) for i in index_set} from sage.combinat.crystals.virtual_crystal import VirtualCrystal return VirtualCrystal(ambient, virtualization, scaling_factors, contained, generators, cartan_type, index_set, category) # We need to give these as optional arguments so it unpickles correctly return super(Subcrystal, cls).__classcall__(cls, ambient, contained, tuple(generators), cartan_type=cartan_type, index_set=tuple(index_set), category=category) def __init__(self, ambient, contained, generators, cartan_type, index_set, category): """ Initialize ``self``. EXAMPLES:: sage: B = crystals.Tableaux(['A',4], shape=[2,1]) sage: S = B.subcrystal(generators=(B(2,1,1), B(5,2,4)), index_set=[1,2]) sage: TestSuite(S).run() """ self._ambient = ambient self._contained = contained self._cardinality = None # ``None`` means currently unknown self._cartan_type = cartan_type self._index_set = tuple(index_set) Parent.__init__(self, category=category) self.module_generators = tuple(self.element_class(self, g) for g in generators if self._containing(g)) if isinstance(contained, frozenset): self._cardinality = Integer(len(contained)) self._list = [self.element_class(self, x) for x in contained] def _repr_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: B = crystals.Tableaux(['A',4], shape=[2,1]) sage: B.subcrystal(generators=(B(2,1,1), B(5,2,4)), index_set=[1,2]) Subcrystal of The crystal of tableaux of type ['A', 4] and shape(s) [[2, 1]] """ return "Subcrystal of {}".format(self._ambient) @lazy_attribute def _containing(self): """ Check if ``x`` is contained in ``self``. EXAMPLES:: sage: B = crystals.Tableaux(['A',4], shape=[2,1]) sage: S = B.subcrystal(generators=(B(2,1,1), B(5,2,4)), index_set=[1,2]) sage: S._containing(B(5,2,4)) True sage: S._containing(B(4,2,4)) True """ if self._contained is None: return lambda x: True if isinstance(self._contained, frozenset): return self._contained.__contains__ return self._contained # Otherwise it should be a function def __contains__(self, x): """ Check if ``x`` is in ``self``. EXAMPLES:: sage: B = crystals.Tableaux(['A',4], shape=[2,1]) sage: S = B.subcrystal(generators=(B(2,1,1), B(5,2,4)), index_set=[1,2]) sage: B(5,2,4) in S True sage: mg = B.module_generators[0] sage: mg in S True sage: mg.f(2).f(3) in S False """ if isinstance(x, Subcrystal.Element) and x.parent() == self: return True if x in self._ambient: if not self._containing(x): return False x = self.element_class(self, x) if self in FiniteCrystals(): return x in self.list() # TODO: make this work for infinite crystals import warnings warnings.warn("Testing containment in an infinite crystal" " defaults to returning True") return True def cardinality(self): """ Return the cardinality of ``self``. EXAMPLES:: sage: B = crystals.Tableaux(['A',4], shape=[2,1]) sage: S = B.subcrystal(generators=[B(2,1,1)], index_set=[1,2]) sage: S.cardinality() 8 sage: B = crystals.infinity.Tableaux(['A',2]) sage: S = B.subcrystal(max_depth=4) sage: S.cardinality() 22 TESTS: Check that :trac:`19481` is fixed:: sage: from sage.combinat.crystals.virtual_crystal import VirtualCrystal sage: A = crystals.infinity.Tableaux(['A',3]) sage: V = VirtualCrystal(A, {1:(1,3), 2:(2,)}, {1:1, 2:2}, cartan_type=['C',2]) sage: V.cardinality() Traceback (most recent call last): ... NotImplementedError: unknown cardinality """ if self._cardinality is not None: return self._cardinality try: card = Integer(len(self._list)) self._cardinality = card return self._cardinality except AttributeError: if self in FiniteCrystals(): return Integer(len(self.list())) try: card = super(Subcrystal, self).cardinality() except AttributeError: raise NotImplementedError("unknown cardinality") if card == infinity: self._cardinality = card return card self._cardinality = Integer(len(self.list())) return self._cardinality def index_set(self): """ Return the index set of ``self``. EXAMPLES:: sage: B = crystals.Tableaux(['A',4], shape=[2,1]) sage: S = B.subcrystal(generators=(B(2,1,1), B(5,2,4)), index_set=[1,2]) sage: S.index_set() (1, 2) """ return self._index_set class Element(ElementWrapper): """ An element of a subcrystal. Wraps an element in the ambient crystal. """ def _richcmp_(self, other, op): """ EXAMPLES: For == operator:: sage: A = crystals.KirillovReshetikhin(['C',2,1], 1,2).affinization() sage: S = A.subcrystal(max_depth=2) sage: sorted(S) [[[1, 1]](-1), [[1, 2]](-1), [](0), [[1, 1]](0), [[1, 2]](0), [[1, -2]](0), [[2, 2]](0), [](1), [[2, -1]](1), [[-2, -1]](1), [[-1, -1]](1), [[-1, -1]](2)] For != operator:: sage: ([(i,j) for i in range(len(S)) for j in range(len(S)) if S[i]!=S[j]] ....: == [(i,j) for i in range(len(S)) for j in range(len(S)) if ....: S[i].value!=S[j].value]) True For < operator:: sage: ([(i,j) for i in range(len(S)) for j in range(len(S)) if S[i]<S[j]] ....: == [(i,j) for i in range(len(S)) for j in range(len(S)) if ....: S[i].value<S[j].value]) True For <= operator:: sage: ([(i,j) for i in range(len(S)) for j in range(len(S)) if S[i]<=S[j]] ....: == [(i,j) for i in range(len(S)) for j in range(len(S)) if ....: S[i].value<=S[j].value]) True For > operator:: sage: ([(i,j) for i in range(len(S)) for j in range(len(S)) if S[i]>S[j]] ....: == [(i,j) for i in range(len(S)) for j in range(len(S)) if ....: S[i].value>S[j].value]) True For >= operator:: sage: ([(i,j) for i in range(len(S)) for j in range(len(S)) if S[i]>=S[j]] ....: == [(i,j) for i in range(len(S)) for j in range(len(S)) if ....: S[i].value>=S[j].value]) True """ return richcmp(self.value, other.value, op) def e(self, i): """ Return `e_i` of ``self``. EXAMPLES:: sage: B = crystals.Tableaux(['A',4], shape=[2,1]) sage: S = B.subcrystal(generators=(B(2,1,1), B(5,2,4)), index_set=[1,2]) sage: mg = S.module_generators[1] sage: mg.e(2) sage: mg.e(1) [[1, 4], [5]] """ ret = self.value.e(i) if ret is None or
<gh_stars>0 """ This contains the list of all drawn plots on the log plotting page """ from html import escape from bokeh.layouts import widgetbox from bokeh.models import Range1d from bokeh.models.widgets import Div, Button from bokeh.io import curdoc from scipy.interpolate import interp1d from config import * from helper import * from leaflet import ulog_to_polyline from pid_analysis import Trace, plot_pid_response from plotting import * from plotted_tables import ( get_logged_messages, get_changed_parameters, get_info_table_html, get_heading_html, get_error_labels_html, get_hardfault_html, get_corrupt_log_html ) #pylint: disable=cell-var-from-loop, undefined-loop-variable, #pylint: disable=consider-using-enumerate,too-many-statements def get_pid_analysis_plots(ulog, px4_ulog, db_data, link_to_main_plots): """ get all bokeh plots shown on the PID analysis page :return: list of bokeh plots """ def _resample(time_array, data, desired_time): """ resample data at a given time to a vector of desired_time """ data_f = interp1d(time_array, data, fill_value='extrapolate') return data_f(desired_time) page_intro = """ <p> This page shows step response plots for the PID controller. The step response is an objective measure to evaluate the performance of a PID controller, i.e. if the tuning gains are appropriate. In particular, the following metrics can be read from the plots: response time, overshoot and settling time. </p> <p> The step response plots are based on <a href="https://github.com/Plasmatree/PID-Analyzer"> PID-Analyzer</a>, originally written for Betaflight by <NAME>. Documentation with some examples can be found <a href="https://github.com/Plasmatree/PID-Analyzer/wiki/Influence-of-parameters">here</a>. </p> <p> Note: this page is somewhat experimental and if you have interesting results or other inputs, please do not hesitate to contact <a href="mailto:<EMAIL>"><EMAIL></a>. </p> <p> The analysis may take a while... </p> """ curdoc().template_variables['title_html'] = get_heading_html( ulog, px4_ulog, db_data, None, [('Open Main Plots', link_to_main_plots)], 'PID Analysis') + page_intro plots = [] data = ulog.data_list flight_mode_changes = get_flight_mode_changes(ulog) x_range_offset = (ulog.last_timestamp - ulog.start_timestamp) * 0.05 x_range = Range1d(ulog.start_timestamp - x_range_offset, ulog.last_timestamp + x_range_offset) # required PID response data pid_analysis_error = False try: rate_ctrl_status = ulog.get_dataset('rate_ctrl_status') gyro_time = rate_ctrl_status.data['timestamp'] vehicle_attitude = ulog.get_dataset('vehicle_attitude') attitude_time = vehicle_attitude.data['timestamp'] vehicle_rates_setpoint = ulog.get_dataset('vehicle_rates_setpoint') vehicle_attitude_setpoint = ulog.get_dataset('vehicle_attitude_setpoint') actuator_controls_0 = ulog.get_dataset('actuator_controls_0') throttle = _resample(actuator_controls_0.data['timestamp'], actuator_controls_0.data['control[3]'] * 100, gyro_time) time_seconds = gyro_time / 1e6 except (KeyError, IndexError, ValueError) as error: print(type(error), ":", error) pid_analysis_error = True div = Div(text="<p><b>Error</b>: missing topics or data for PID analysis " "(required topics: rate_ctrl_status, vehicle_rates_setpoint, " "vehicle_attitude, vehicle_attitude_setpoint and " "actuator_controls_0).</p>", width=int(plot_width*0.9)) plots.append(widgetbox(div, width=int(plot_width*0.9))) for index, axis in enumerate(['roll', 'pitch', 'yaw']): axis_name = axis.capitalize() # rate data_plot = DataPlot(data, plot_config, 'actuator_controls_0', y_axis_label='[deg/s]', title=axis_name+' Angular Rate', plot_height='small', x_range=x_range) thrust_max = 200 actuator_controls = data_plot.dataset if actuator_controls is None: # do not show the rate plot if actuator_controls is missing continue time_controls = actuator_controls.data['timestamp'] thrust = actuator_controls.data['control[3]'] * thrust_max # downsample if necessary max_num_data_points = 4.0*plot_config['plot_width'] if len(time_controls) > max_num_data_points: step_size = int(len(time_controls) / max_num_data_points) time_controls = time_controls[::step_size] thrust = thrust[::step_size] if len(time_controls) > 0: # make sure the polygon reaches down to 0 thrust = np.insert(thrust, [0, len(thrust)], [0, 0]) time_controls = np.insert(time_controls, [0, len(time_controls)], [time_controls[0], time_controls[-1]]) p = data_plot.bokeh_plot p.patch(time_controls, thrust, line_width=0, fill_color='#555555', fill_alpha=0.4, alpha=0, legend='Thrust [0, {:}]'.format(thrust_max)) data_plot.change_dataset('vehicle_attitude') data_plot.add_graph([lambda data: (axis+'speed', np.rad2deg(data[axis+'speed']))], colors3[0:1], [axis_name+' Rate Estimated'], mark_nan=True) data_plot.change_dataset('vehicle_rates_setpoint') data_plot.add_graph([lambda data: (axis, np.rad2deg(data[axis]))], colors3[1:2], [axis_name+' Rate Setpoint'], mark_nan=True, use_step_lines=True) axis_letter = axis[0].upper() rate_int_limit = '(*100)' # this param is MC/VTOL only (it will not exist on FW) rate_int_limit_param = 'MC_' + axis_letter + 'R_INT_LIM' if rate_int_limit_param in ulog.initial_parameters: rate_int_limit = '[-{0:.0f}, {0:.0f}]'.format( ulog.initial_parameters[rate_int_limit_param]*100) data_plot.change_dataset('rate_ctrl_status') data_plot.add_graph([lambda data: (axis, data[axis+'speed_integ']*100)], colors3[2:3], [axis_name+' Rate Integral '+rate_int_limit]) plot_flight_modes_background(data_plot, flight_mode_changes) if data_plot.finalize() is not None: plots.append(data_plot.bokeh_plot) # PID response if not pid_analysis_error: try: gyro_rate = np.rad2deg(rate_ctrl_status.data[axis+'speed']) setpoint = _resample(vehicle_rates_setpoint.data['timestamp'], np.rad2deg(vehicle_rates_setpoint.data[axis]), gyro_time) trace = Trace(axis, time_seconds, gyro_rate, setpoint, throttle) plots.append(plot_pid_response(trace, ulog.data_list, plot_config).bokeh_plot) except Exception as e: print(type(e), axis, ":", e) div = Div(text="<p><b>Error</b>: PID analysis failed. Possible " "error causes are: logged data rate is too low, there " "is not enough motion for the analysis or simply a bug " "in the code.</p>", width=int(plot_width*0.9)) plots.insert(0, widgetbox(div, width=int(plot_width*0.9))) pid_analysis_error = True # attitude if not pid_analysis_error: throttle = _resample(actuator_controls_0.data['timestamp'], actuator_controls_0.data['control[3]'] * 100, attitude_time) time_seconds = attitude_time / 1e6 # don't plot yaw, as yaw is mostly controlled directly by rate for index, axis in enumerate(['roll', 'pitch']): axis_name = axis.capitalize() # PID response if not pid_analysis_error: try: attitude_estimated = np.rad2deg(vehicle_attitude.data[axis]) setpoint = _resample(vehicle_attitude_setpoint.data['timestamp'], np.rad2deg(vehicle_attitude_setpoint.data[axis+'_d']), attitude_time) trace = Trace(axis, time_seconds, attitude_estimated, setpoint, throttle) plots.append(plot_pid_response(trace, ulog.data_list, plot_config, 'Angle').bokeh_plot) except Exception as e: print(type(e), axis, ":", e) div = Div(text="<p><b>Error</b>: PID analysis failed. Possible " "error causes are: logged data rate is too low, there " "is not enough motion for the analysis or simply a bug " "in the code.</p>", width=int(plot_width*0.9)) plots.insert(0, widgetbox(div, width=int(plot_width*0.9))) pid_analysis_error = True return plots def generate_plots(ulog, px4_ulog, db_data, vehicle_data, link_to_3d_page, link_to_pid_analysis_page): """ create a list of bokeh plots (and widgets) to show """ plots = [] data = ulog.data_list # COMPATIBILITY support for old logs if any(elem.name == 'vehicle_air_data' or elem.name == 'vehicle_magnetometer' for elem in data): baro_alt_meter_topic = 'vehicle_air_data' magnetometer_ga_topic = 'vehicle_magnetometer' else: # old baro_alt_meter_topic = 'sensor_combined' magnetometer_ga_topic = 'sensor_combined' for topic in data: if topic.name == 'system_power': # COMPATIBILITY: rename fields to new format if 'voltage5V_v' in topic.data: # old (prior to PX4/Firmware:213aa93) topic.data['voltage5v_v'] = topic.data.pop('voltage5V_v') if 'voltage3V3_v' in topic.data: # old (prior to PX4/Firmware:213aa93) topic.data['voltage3v3_v'] = topic.data.pop('voltage3V3_v') # initialize flight mode changes flight_mode_changes = get_flight_mode_changes(ulog) # VTOL state changes & vehicle type vtol_states = None is_vtol = False try: cur_dataset = ulog.get_dataset('vehicle_status') if np.amax(cur_dataset.data['is_vtol']) == 1: is_vtol = True vtol_states = cur_dataset.list_value_changes('in_transition_mode') # find mode after transitions (states: 1=transition, 2=FW, 3=MC) if 'vehicle_type' in cur_dataset.data: vehicle_type_field = 'vehicle_type' vtol_state_mapping = {2: 2, 1: 3} else: # COMPATIBILITY: old logs (https://github.com/PX4/Firmware/pull/11918) vehicle_type_field = 'is_rotary_wing' vtol_state_mapping = {0: 2, 1: 3} for i in range(len(vtol_states)): if vtol_states[i][1] == 0: t = vtol_states[i][0] idx = np.argmax(cur_dataset.data['timestamp'] >= t) + 1 vtol_states[i] = (t, vtol_state_mapping[ cur_dataset.data[vehicle_type_field][idx]]) vtol_states.append((ulog.last_timestamp, -1)) except (KeyError, IndexError) as error: vtol_states = None # Heading curdoc().template_variables['title_html'] = get_heading_html( ulog, px4_ulog, db_data, link_to_3d_page, additional_links=[("Open PID Analysis", link_to_pid_analysis_page)]) # info text on top (logging duration, max speed, ...) curdoc().template_variables['info_table_html'] = \ get_info_table_html(ulog, px4_ulog, db_data, vehicle_data, vtol_states) curdoc().template_variables['error_labels_html'] = get_error_labels_html() hardfault_html = get_hardfault_html(ulog) if hardfault_html is not None: curdoc().template_variables['hardfault_html'] = hardfault_html corrupt_log_html = get_corrupt_log_html(ulog) if corrupt_log_html: curdoc().template_variables['corrupt_log_html'] = corrupt_log_html # Position plot data_plot = DataPlot2D(data, plot_config, 'vehicle_local_position', x_axis_label='[m]', y_axis_label='[m]', plot_height='large') data_plot.add_graph('y', 'x', colors2[0], 'Estimated', check_if_all_zero=True) if not data_plot.had_error: # vehicle_local_position is required data_plot.change_dataset('vehicle_local_position_setpoint') data_plot.add_graph('y', 'x', colors2[1], 'Setpoint') # groundtruth (SITL only) data_plot.change_dataset('vehicle_local_position_groundtruth') data_plot.add_graph('y', 'x', color_gray, 'Groundtruth') # GPS + position setpoints plot_map(ulog, plot_config, map_type='plain', setpoints=True, bokeh_plot=data_plot.bokeh_plot) if data_plot.finalize() is not None: plots.append(data_plot.bokeh_plot) # Leaflet Map try: pos_datas, flight_modes = ulog_to_polyline(ulog, flight_mode_changes) curdoc().template_variables['pos_datas'] = pos_datas curdoc().template_variables['pos_flight_modes'] = flight_modes except: pass curdoc().template_variables['has_position_data'] = True # initialize parameter changes changed_params = None if not 'replay' in ulog.msg_info_dict: # replay can have many param changes if len(ulog.changed_parameters) > 0: changed_params = ulog.changed_parameters plots.append(None) # save space for the param change button ### Add all data plots ### x_range_offset = (ulog.last_timestamp - ulog.start_timestamp) * 0.05 x_range = Range1d(ulog.start_timestamp - x_range_offset, ulog.last_timestamp + x_range_offset) # Altitude estimate data_plot = DataPlot(data, plot_config, 'vehicle_gps_position', y_axis_label='[m]', title='Altitude Estimate', changed_params=changed_params, x_range=x_range) data_plot.add_graph([lambda data: ('alt', data['alt']*0.001)], colors8[0:1], ['GPS Altitude']) data_plot.change_dataset(baro_alt_meter_topic) data_plot.add_graph(['baro_alt_meter'], colors8[1:2], ['Barometer Altitude']) data_plot.change_dataset('vehicle_global_position') data_plot.add_graph(['alt'], colors8[2:3], ['Fused Altitude Estimation']) data_plot.change_dataset('position_setpoint_triplet') data_plot.add_circle(['current.alt'], [plot_config['mission_setpoint_color']], ['Altitude Setpoint']) data_plot.change_dataset('actuator_controls_0') data_plot.add_graph([lambda data: ('thrust', data['control[3]']*100)], colors8[6:7], ['Thrust [0, 100]']) plot_flight_modes_background(data_plot, flight_mode_changes, vtol_states) if data_plot.finalize() is not None: plots.append(data_plot) # Roll/Pitch/Yaw angle & angular rate for axis in ['roll', 'pitch', 'yaw']: # angle axis_name = axis.capitalize() data_plot = DataPlot(data, plot_config, 'vehicle_attitude', y_axis_label='[deg]', title=axis_name+' Angle', plot_height='small', changed_params=changed_params, x_range=x_range) data_plot.add_graph([lambda data: (axis, np.rad2deg(data[axis]))], colors3[0:1], [axis_name+' Estimated'], mark_nan=True) data_plot.change_dataset('vehicle_attitude_setpoint') data_plot.add_graph([lambda data: (axis+'_d', np.rad2deg(data[axis+'_d']))], colors3[1:2], [axis_name+' Setpoint'], use_step_lines=True) if axis == 'yaw': data_plot.add_graph( [lambda data: ('yaw_sp_move_rate', np.rad2deg(data['yaw_sp_move_rate']))], colors3[2:3], [axis_name+' FF Setpoint [deg/s]'], use_step_lines=True) data_plot.change_dataset('vehicle_attitude_groundtruth') data_plot.add_graph([lambda data: (axis, np.rad2deg(data[axis]))], [color_gray], [axis_name+' Groundtruth']) plot_flight_modes_background(data_plot, flight_mode_changes, vtol_states) if data_plot.finalize() is not None: plots.append(data_plot) # rate data_plot = DataPlot(data, plot_config, 'vehicle_attitude', y_axis_label='[deg/s]', title=axis_name+' Angular Rate', plot_height='small', changed_params=changed_params, x_range=x_range) data_plot.add_graph([lambda data: (axis+'speed', np.rad2deg(data[axis+'speed']))], colors3[0:1], [axis_name+' Rate Estimated'], mark_nan=True) data_plot.change_dataset('vehicle_rates_setpoint') data_plot.add_graph([lambda data: (axis, np.rad2deg(data[axis]))], colors3[1:2], [axis_name+' Rate Setpoint'], mark_nan=True, use_step_lines=True) axis_letter = axis[0].upper() rate_int_limit = '(*100)' # this param is MC/VTOL only (it will not exist on FW) rate_int_limit_param = 'MC_' + axis_letter + 'R_INT_LIM' if rate_int_limit_param in ulog.initial_parameters: rate_int_limit = '[-{0:.0f}, {0:.0f}]'.format( ulog.initial_parameters[rate_int_limit_param]*100) data_plot.change_dataset('rate_ctrl_status') data_plot.add_graph([lambda
# coding: utf-8 """ Thingsboard REST API For instructions how to authorize requests please visit <a href='http://thingsboard.io/docs/reference/rest-api/'>REST API documentation page</a>. OpenAPI spec version: 2.0 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..api_client import ApiClient class PluginControllerApi(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def activate_plugin_by_id_using_post(self, plugin_id, **kwargs): """ activatePluginById This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.activate_plugin_by_id_using_post(plugin_id, async=True) >>> result = thread.get() :param async bool :param str plugin_id: pluginId (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.activate_plugin_by_id_using_post_with_http_info(plugin_id, **kwargs) else: (data) = self.activate_plugin_by_id_using_post_with_http_info(plugin_id, **kwargs) return data def activate_plugin_by_id_using_post_with_http_info(self, plugin_id, **kwargs): """ activatePluginById This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.activate_plugin_by_id_using_post_with_http_info(plugin_id, async=True) >>> result = thread.get() :param async bool :param str plugin_id: pluginId (required) :return: None If the method is called asynchronously, returns the request thread. """ all_params = ['plugin_id'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method activate_plugin_by_id_using_post" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'plugin_id' is set if ('plugin_id' not in params) or (params['plugin_id'] is None): raise ValueError("Missing the required parameter `plugin_id` when calling `activate_plugin_by_id_using_post`") collection_formats = {} path_params = {} if 'plugin_id' in params: path_params['pluginId'] = params['plugin_id'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['*/*']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = ['X-Authorization'] return self.api_client.call_api('/api/plugin/{pluginId}/activate', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, auth_settings=auth_settings, async=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def delete_plugin_using_delete(self, plugin_id, **kwargs): """ deletePlugin This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_plugin_using_delete(plugin_id, async=True) >>> result = thread.get() :param async bool :param str plugin_id: pluginId (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.delete_plugin_using_delete_with_http_info(plugin_id, **kwargs) else: (data) = self.delete_plugin_using_delete_with_http_info(plugin_id, **kwargs) return data def delete_plugin_using_delete_with_http_info(self, plugin_id, **kwargs): """ deletePlugin This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_plugin_using_delete_with_http_info(plugin_id, async=True) >>> result = thread.get() :param async bool :param str plugin_id: pluginId (required) :return: None If the method is called asynchronously, returns the request thread. """ all_params = ['plugin_id'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method delete_plugin_using_delete" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'plugin_id' is set if ('plugin_id' not in params) or (params['plugin_id'] is None): raise ValueError("Missing the required parameter `plugin_id` when calling `delete_plugin_using_delete`") collection_formats = {} path_params = {} if 'plugin_id' in params: path_params['pluginId'] = params['plugin_id'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['*/*']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = ['X-Authorization'] return self.api_client.call_api('/api/plugin/{pluginId}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, auth_settings=auth_settings, async=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_plugin_by_id_using_get(self, plugin_id, **kwargs): """ getPluginById This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_plugin_by_id_using_get(plugin_id, async=True) >>> result = thread.get() :param async bool :param str plugin_id: pluginId (required) :return: PluginMetaData If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_plugin_by_id_using_get_with_http_info(plugin_id, **kwargs) else: (data) = self.get_plugin_by_id_using_get_with_http_info(plugin_id, **kwargs) return data def get_plugin_by_id_using_get_with_http_info(self, plugin_id, **kwargs): """ getPluginById This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_plugin_by_id_using_get_with_http_info(plugin_id, async=True) >>> result = thread.get() :param async bool :param str plugin_id: pluginId (required) :return: PluginMetaData If the method is called asynchronously, returns the request thread. """ all_params = ['plugin_id'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_plugin_by_id_using_get" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'plugin_id' is set if ('plugin_id' not in params) or (params['plugin_id'] is None): raise ValueError("Missing the required parameter `plugin_id` when calling `get_plugin_by_id_using_get`") collection_formats = {} path_params = {} if 'plugin_id' in params: path_params['pluginId'] = params['plugin_id'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['*/*']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = ['X-Authorization'] return self.api_client.call_api('/api/plugin/{pluginId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PluginMetaData', auth_settings=auth_settings, async=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_plugin_by_token_using_get(self, plugin_token, **kwargs): """ getPluginByToken This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_plugin_by_token_using_get(plugin_token, async=True) >>> result = thread.get() :param async bool :param str plugin_token: pluginToken (required) :return: PluginMetaData If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_plugin_by_token_using_get_with_http_info(plugin_token, **kwargs) else: (data) = self.get_plugin_by_token_using_get_with_http_info(plugin_token, **kwargs) return data def get_plugin_by_token_using_get_with_http_info(self, plugin_token, **kwargs): """ getPluginByToken This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_plugin_by_token_using_get_with_http_info(plugin_token, async=True) >>> result = thread.get() :param async bool :param str plugin_token: pluginToken (required) :return: PluginMetaData If the method is called asynchronously, returns the request thread. """ all_params = ['plugin_token'] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_plugin_by_token_using_get" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'plugin_token' is set if ('plugin_token' not in params) or (params['plugin_token'] is None): raise ValueError("Missing the required parameter `plugin_token` when calling `get_plugin_by_token_using_get`") collection_formats = {} path_params = {} if 'plugin_token' in params: path_params['pluginToken'] = params['plugin_token'] query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['*/*']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting auth_settings = ['X-Authorization'] return self.api_client.call_api('/api/plugin/token/{pluginToken}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PluginMetaData', auth_settings=auth_settings, async=params.get('async'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_plugins_using_get(self, **kwargs): """ getPlugins This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_plugins_using_get(async=True) >>> result = thread.get() :param async bool :return: list[PluginMetaData] If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return self.get_plugins_using_get_with_http_info(**kwargs) else: (data) = self.get_plugins_using_get_with_http_info(**kwargs) return data def get_plugins_using_get_with_http_info(self, **kwargs): """ getPlugins This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_plugins_using_get_with_http_info(async=True) >>> result = thread.get() :param async bool :return: list[PluginMetaData] If the method is called asynchronously, returns the request thread. """ all_params = [] all_params.append('async') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_plugins_using_get" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept']
request to stop the solution process. Otherwise, new request with updated solution process information. """ resp: dict = request.response # change the number of iterations if "n_iterations" in resp: # "expand" the numpy arrays used for storing information from iteration rounds if resp["n_iterations"] > self._n_iterations: extra_space = [None] * (resp["n_iterations"] - self._n_iterations) self._zs = np.array(np.concatenate((self._zs, extra_space), axis=None), dtype=object) self._xs = np.array(np.concatenate((self._xs, extra_space), axis=None), dtype=object) self._fs = np.array(np.concatenate((self._fs, extra_space), axis=None), dtype=object) self._ds = np.array(np.concatenate((self._ds, extra_space), axis=None), dtype=object) self._lower_bounds = np.array(np.concatenate((self._lower_bounds, extra_space), axis=None), dtype=object) self._upper_bounds = np.array(np.concatenate((self._upper_bounds, extra_space), axis=None), dtype=object) self._n_iterations_left = resp["n_iterations"] # last iteration, stop solution process if self._n_iterations_left <= 1: self._n_iterations_left = 0 return NautilusStopRequest(self._xs[self._step_number], self._fs[self._step_number]) # don't step back... if not resp["step_back"]: self._step_back = False self._n_iterations_left -= 1 self._step_number += 1 # ... and continue with same preferences if resp["use_previous_preference"]: # use the solution and objective of last step self._xs[self._step_number] = self._xs[self._step_number - 1] self._fs[self._step_number] = self._fs[self._step_number - 1] # ... and give new preferences else: # step 1 # set preference information self._preference_method: int = resp["preference_method"] self._preference_info: np.ndarray = resp["preference_info"] self._preferential_factors = self.calculate_preferential_factors(len(self._objective_names), self._preference_method, self._preference_info) # set reference point, initial values for decision variables and solve the problem self._q = self._zs[self._step_number - 1] x0 = self._problem.get_variable_upper_bounds() / 2 result = self.solve_asf(self._q, x0, self._preferential_factors, self._nadir, self._utopian, self._objectives, self._variable_bounds, method=self._method_de) # update current solution and objective function values self._xs[self._step_number] = result["x"] self._fs[self._step_number] = self._objectives(self._xs[self._step_number])[0] # continue from step 3 # calculate next iteration point self._zs[self._step_number] = self.calculate_iteration_point(self._n_iterations_left, self._zs[self._step_number - 1], self._fs[self._step_number]) # calculate new bounds and store the information new_lower_bounds = self.calculate_bounds(self._objectives, len(self._objective_names), self._problem.get_variable_upper_bounds() / 2, self._zs[self._step_number], self._variable_bounds, self._constraints, None) self._lower_bounds[self._step_number + 1] = new_lower_bounds self._upper_bounds[self._step_number + 1] = self._zs[self._step_number] # calculate distance from current iteration point to Pareto optimal set self._ds[self._step_number] = self.calculate_distance(self._zs[self._step_number], self._starting_point, self._fs[self._step_number]) # return the information from iteration round to be shown to the DM. return NautilusRequest( self._zs[self._step_number], self._nadir, self._lower_bounds[self._step_number + 1], self._upper_bounds[self._step_number + 1], self._ds[self._step_number] ) # take a step back... if resp["step_back"]: self._step_back = True # ... and take a short step if resp["short_step"]: self._short_step = True self._zs[self._step_number] = 0.5 * self._zs[self._step_number] + 0.5 * self._zs[self._step_number - 1] # calculate new bounds and store the information new_lower_bounds = self.calculate_bounds(self._objectives, len(self._objective_names), self._problem.get_variable_upper_bounds() / 2, self._zs[self._step_number], self._variable_bounds, self._constraints, None) self._lower_bounds[self._step_number + 1] = new_lower_bounds self._upper_bounds[self._step_number + 1] = self._zs[self._step_number] # calculate distance from current iteration point to Pareto optimal set self._ds[self._step_number] = self.calculate_distance(self._zs[self._step_number], self._starting_point, self._fs[self._step_number]) # return the information from iteration round to be shown to the DM. return NautilusRequest( self._zs[self._step_number], self._nadir, self._lower_bounds[self._step_number + 1], self._upper_bounds[self._step_number + 1], self._ds[self._step_number] ) # ... and use new preferences elif not resp["use_previous_preference"]: # set preference information self._preference_method: int = resp["preference_method"] self._preference_info: np.ndarray = resp["preference_info"] self._preferential_factors = self.calculate_preferential_factors(len(self._objective_names), self._preference_method, self._preference_info) # set reference point, initial values for decision variables and solve the problem self._q = self._zs[self._step_number - 1] x0 = self._problem.get_variable_upper_bounds() / 2 result = self.solve_asf(self._q, x0, self._preferential_factors, self._nadir, self._utopian, self._objectives, self._variable_bounds, method=self._method_de) # update current solution and objective function values self._xs[self._step_number] = result["x"] self._fs[self._step_number] = self._objectives(self._xs[self._step_number])[0] # calculate next iteration point self._zs[self._step_number] = self.calculate_iteration_point(self._n_iterations_left, self._zs[self._step_number - 1], self._fs[self._step_number]) # calculate new bounds and store the information new_lower_bounds = self.calculate_bounds(self._objectives, len(self._objective_names), x0, self._zs[self._step_number], self._variable_bounds, self._constraints, None) self._lower_bounds[self._step_number + 1] = new_lower_bounds self._upper_bounds[self._step_number + 1] = self._zs[self._step_number] # calculate distance from current iteration point to Pareto optimal set self._ds[self._step_number] = self.calculate_distance(self._zs[self._step_number], self._starting_point, self._fs[self._step_number]) # return the information from iteration round to be shown to the DM. return NautilusRequest( self._zs[self._step_number], self._nadir, self._lower_bounds[self._step_number + 1], self._upper_bounds[self._step_number + 1], self._ds[self._step_number] ) def calculate_preferential_factors(self, n_objectives: int, pref_method: int, pref_info: np.ndarray) -> np.ndarray: """ Calculate preferential factors based on decision maker's preference information. Args: n_objectives (int): Number of objectives in problem. pref_method (int): Preference information method, either: Direction of improvement (1), improvement ratios between a selected objective and rest of the objectives (2), or improvement ratios freely for some selected pairs of objectives (3). pref_info (np.ndarray): Preference information on how the DM wishes to improve the values of each objective function. **See the examples below**. Returns: np.ndarray: Direction of improvement. Used as weights assigned to each of the objective functions in the achievement scalarizing function. Examples: >>> n_objectives = 4 >>> pref_method = 1 # deltas directly >>> pref_info = np.array([1, 2, 1, 2]), # second and fourth objective are the most important to improve >>> calculate_preferential_factors(n_objectives, pref_method, pref_info) np.array([1, 2, 1, 2]) >>> n_objectives = 4 >>> pref_method = 2 # improvement ratios between one selected objective and each other objective >>> pref_info = np.array([1, 1.5, (7/3), 0.5]) # first objective's ratio is set to one >>> calculate_preferential_factors(n_objectives, pref_method, pref_info) np.array([1, 1.5, (7/3), 0.5]) >>> n_objectives = 4 >>> pref_method = 3 # improvement ratios between freely selected pairs of objectives # format the tuples like this: (('index of objective', 'index of objective'), 'improvement ratio between the objectives') >>> pref_info = np.array([((1, 2), 0.5), ((3, 4), 1), ((2, 3), 1.5)], dtype=object) >>> calculate_preferential_factors(n_objectives, pref_method, pref_info) np.array([1., 0.5, 0.75, 0.75]) Note: Remember to specify "dtype=object" in **pref_info** array when using preference method 3. """ if pref_method in [1, 2]: # deltas directly or improvement ratios return pref_info elif pref_method == 3: return self.calculate_doi(n_objectives, pref_info) def calculate_doi(self, n_objectives: int, pref_info: np.ndarray) -> np.ndarray: """ Calculate direction of improvement based on improvement ratios between pairs of objective functions. Args: n_objectives (int): Number of objectives. pref_info (np.ndarray): Preference information on how the DM wishes to improve the values of each objective function. Returns: np.ndarray: Direction of improvement. """ # initialize deltas = np.zeros(n_objectives) # direction of improvement for objective 1 is set to 1. deltas[0] = 1 # 1. starting search from pairs containing objective 1 for ind, elem in enumerate(pref_info): if elem[0][0] == 1: # delta for objective i delta_i = elem[1] # set delta for objective i, minus 1 because objective indeces start at 1, but deltas are stored # starting from index 0. deltas[elem[0][1] - 1] = delta_i elif elem[0][1] == 1: delta_i = 1 / elem[1] deltas[elem[0][0] - 1] = delta_i # 2. if all deltas not set # indeces of objectives for which deltas are still missing missing = [ind + 1 for ind, elem in enumerate(deltas) if elem == 0] while (0 in deltas): # go through the missing objectives for m in missing: for ind, elem in enumerate(pref_info): # if objective is included in the pair if elem[0][0] == m: if deltas[elem[0][1] - 1] != 0: deltas[elem[0][0] - 1] = deltas[elem[0][1] - 1] * (1 / elem[1]) elif elem[0][1] == m: if deltas[elem[0][0] - 1] != 0: deltas[elem[0][1] - 1] = deltas[elem[0][0] - 1] * elem[1] return deltas def solve_asf(self, ref_point: np.ndarray, x0: np.ndarray, preferential_factors: np.ndarray, nadir: np.ndarray, utopian: np.ndarray, objectives: Callable, variable_bounds: Optional[np.ndarray] = None, method: Union[ScalarMethod, str, None] = None ) -> dict: """ Solve achievement scalarizing function. Args: ref_point (np.ndarray): Reference point. x0 (np.ndarray): Initial values for decision variables. preferential_factors (np.ndarray): Preferential factors indicating how much would the decision maker wish to improve the values of each objective function. nadir (np.ndarray): Nadir vector. utopian (np.ndarray): Utopian vector. objectives (np.ndarray): The objective function values for each input vector. variable_bounds (Optional[np.ndarray]): Lower and upper bounds of each variable as a 2D numpy array. If undefined variables, None instead. method (Union[ScalarMethod, str, None]): The optimization method the scalarizer should be minimized with. Returns: Dict: A dictionary with at least the following entries: 'x' indicating the optimal variables found, 'fun' the optimal value of the optimized function, and 'success' a boolean indicating whether the optimization was conducted successfully. """ if variable_bounds is None: # set all bounds as [-inf, inf] variable_bounds = np.array([[-np.inf, np.inf]] * x0.shape[0]) # scalarize problem using reference point asf = ReferencePointASF([1 / preferential_factors], nadir, utopian, rho=1e-5) asf_scalarizer = Scalarizer( evaluator=objectives, scalarizer=asf, scalarizer_args={"reference_point": ref_point}) # minimize minimizer = ScalarMinimizer(asf_scalarizer, variable_bounds, method=method) return minimizer.minimize(x0) def calculate_iteration_point(self, itn: int, z_prev: np.ndarray,
# This routine computes the first-order # transit timing variations in Agol & Deck (2015). Please # cite the paper if you make use of this code in your research. import numpy as np import matplotlib.pyplot as plt class Planet(object): def __init__(self, mass_ratio=None, trans0=None, period=None, ecos=None, esin=None): self.mass_ratio = mass_ratio self.trans0 = trans0 self.period = period self.ecos = ecos self.esin = esin def call_ttv(jmax): """ This routine gives an example of a call of compute_ttv.py which computes the first-order eccentricity TTVs, from Agol & Deck (2015). It uses parameters appropriate for the outer two planets of Kepler-62e/f. Parameters ---------- jmax: maximum j to evaluate """ data = np.loadtxt('kepler62ef_planets.txt', delimiter=',') # Compute 40 transits of inner and 20 of outer planet nt1 = 40 nt2 = 20 # Set up uniform ephemeris to compute TTVs time1 = data[2] + np.arange(nt1) * data[1] time2 = data[7] + np.arange(nt2) * data[6] # Rearrange planet parameters for ingest to compute_ttv.py param = np.array(data) param[1] = data[2] param[2] = data[1] param[6] = data[7] param[7] = data[6] # Model contains the transit times model1, model2 = compute_ttv(time1, time2, param, jmax) # Subtract the transit times to only plot the TTVs plt.plot(time1, model1 - time1) plt.plot(time2, model2 - time2) plt.show() np.savetxt('inner_ttv.txt', model1) np.savetxt('outer_ttv.txt', model2) def compute_ttv(time1, time2, param, jmax): """ Computes transit-timing variations to linear order in eccentricity for non-resonant, plane-parallel planets to first order in mass ratio and eccentricity. Parameters ---------- time1: contains the times of transit of inner planet time2: contains the times of transit of outer planet jmax: maximum j to evaluate param: contains the (mass ratio,t0,period,e*cos(omega), e*sin(omega)) for each planet Returns ------- model1: Contains the transit timing model with the first set for the inner planet. model2: Contains the transit timing model with the first set for the outer planet. """ # Insert the parameters of the model into a structure for each planet p1 = Planet(mass_ratio=param[0], trans0=param[1], period=param[2], ecos=param[3], esin=param[4]) p2 = Planet(mass_ratio=param[5], trans0=param[6], period=param[7], ecos=param[8], esin=param[9]) twopi = 2.0 * np.pi # Compute the semi-major axis ratio of the planets alpha = abs(p1.period / p2.period) ** (2. / 3.) # Compute the longitudes of the planets at times of transit of # planet 1 (equation 32) lam11 = twopi * (time1 - p1.trans0) / p1.period + 2 * p1.esin lam21 = twopi * (time1 - p2.trans0) / p2.period + 2 * p2.esin # Compute the longitudes of the planets at times of transit of # planet 2 (equation 32) lam12 = twopi * (time2 - p1.trans0) / p1.period + 2 * p1.esin lam22 = twopi * (time2 - p2.trans0) / p2.period + 2 * p2.esin # Compute difference in longitudes at times of transit of planets 1 and 2 psi1 = lam11 - lam21 psi2 = lam12 - lam22 # Compute the coefficients (need one higher than jmax) f1, f2 = ttv_succinct(jmax + 1, alpha) ttv1 = np.zeros(time1.size) ttv2 = np.zeros(time2.size) # Compute TTVs for inner planet (equation 33) for j in range(1, jmax + 1): ttv1 += f1[j, 0] * np.sin(j * psi1) ttv1 += f1[j, 1] * (p1.ecos * np.sin((j - 1) * lam11 - j * lam21) + p1.esin * np.cos((j - 1) * lam11 - j * lam21)) ttv1 += f1[j, 2] * (p1.ecos * np.sin((j + 1) * lam11 - j * lam21) - p1.esin * np.cos((j + 1) * lam11 - j * lam21)) ttv1 += f1[j - 1, 3] * (p2.ecos * np.sin((j - 1) * lam11 - j * lam21) + p2.esin * np.cos((j - 1) * lam11 - j * lam21)) ttv1 += f1[j + 1, 4] * (p2.ecos * np.sin((j + 1) * lam11 - j * lam21) - p2.esin * np.cos((j + 1) * lam11 - j * lam21)) # Now multiply by the mass ratio and divide by mean motion ttv1 = ttv1 * p1.period * p2.mass_ratio / twopi # Compute TTVs for outer planet (equation 33) for j in range(1, jmax + 1): ttv2 += f2[j, 0] * np.sin(j * psi2) ttv2 += f2[j, 1] * (p2.ecos * np.sin(j * lam12 - (j + 1) * lam22) + p2.esin * np.cos(j * lam12 - (j + 1) * lam22)) ttv2 += f2[j, 2] * (p2.ecos * np.sin(j * lam12 - (j - 1) * lam22) - p2.esin * np.cos(j * lam12 - (j - 1) * lam22)) ttv2 += f2[j + 1, 3] * (p1.ecos * np.sin(j * lam12 - (j + 1) * lam22) + p1.esin * np.cos(j * lam12 - (j + 1) * lam22)) ttv2 += f2[j - 1, 4] * (p1.ecos * np.sin(j * lam12 - (j - 1) * lam22) - p1.esin * np.cos(j * lam12 - (j - 1) * lam22)) # Now multiply by the mass ratio and divide by mean motion ttv2 = ttv2 * p2.period * p1.mass_ratio / twopi # Add the TTVs to the ephemeris and return to user model1 = p1.trans0 + np.arange(time1.size) * p1.period + ttv1 model2 = p2.trans0 + np.arange(time2.size) * p2.period + ttv2 # The following lines can be used if only the TTVs are desired # model1= ttv1 # model2= ttv2 return model1, model2 # Define u & v functions (equation 34) def u(gamma, c1, c2): return (((3.0 + gamma ** 2) * c1 + 2.0 * gamma * c2) / gamma ** 2 / (1.0 - gamma ** 2)) def v(zeta, d1, d2, m): # m = +/-1 return ((m * (1.0 - zeta ** 2) + 6.0 * zeta) * d1 + (2.0 + zeta ** 2) * d2) / (zeta * (1.0 - zeta ** 2) * (zeta + m) * (zeta + 2.0 * m)) # The following routine computes the coefficients for the first-order # transit timing variations in Agol & Deck (2015). Please # cite the paper if you make use of this code in your research. def ttv_succinct(jmax, alpha): """ Succinct form for coefficients of first-order TTV formula Parameters ---------- jmax: maximum value of j over which to compute the coefficients alpha: a_1/a_2 of the two planets Returns ------- b: Matrix of Laplace coefficients. f1: Coefficients for the inner planet. For each value of j=0 to jmax, there are 5 coefficients: the f_{1,j}^(0), f_{1,j}^(+-1), and f_{1,j}^(+-2) coefficients. The +-1 coefficients correspond to j*(lam_1-lam_2)+-(lam_1-omega_1) arguments. The +-2 coefficients correspond to j*(lam_1-lam_2)+-(lam_1-omega_2) arguments. f2: Coefficients for the outer planet. For each value of j=0 to jmax, there are 5 coefficients: the f_{1,j}^(0), f_{1,j}^(+-2), and f_{1,j}^(+-1) coefficients. The +-1 coefficients correspond to j*(lam_1-lam_2)+-(lam_2-omega_1) arguments. The +-2 coefficients correspond to j*(lam_1-lam_2)+-(lam_2-omega_2) arguments. """ f1 = np.zeros((jmax + 1, 5)) f2 = np.zeros((jmax + 1, 5)) # Compute the Laplace coefficients b = laplace_coefficients3(jmax, alpha) # Now loop over j values for j in range(jmax + 1): if j == 1: dj1 = 1.0 else: dj1 = 0.0 beta = j * (1 - alpha ** 1.5) kappa = beta / alpha ** 1.5 # Compute the disturbing function coefficients A_jmn (equation 31) A_j00 = b[j, 0] A_j10 = alpha * b[j, 1] A_j01 = -(A_j10 + A_j00) A_j20 = alpha ** 2 * b[j, 2] A_j11 = -(2 * A_j10 + A_j20) A_j02 = 2 * A_j00 + 4 * A_j10 + A_j20 # Inner planet coefficients, in order k=0,-1,1,-2,2 (see Table 1) gamma = beta + np.array([0, -1, 1, -alpha ** 1.5, alpha ** 1.5]) c1 = alpha * j * (A_j00 * np.array([1, -j, j, j, -j]) - .5 * A_j01 * np.array([0, 0, 0, 1, 1]) - .5 * A_j10 * np.array([0, 1, 1, 0, 0]) - alpha * dj1 * np.array([1, -1.5, .5, 2, 0])) c2 = alpha * (A_j10 * np.array([1, -j, j, j, -j]) - .5 * A_j11 * np.array([0, 0, 0, 1, 1]) - .5 * A_j20 * np.array([0, 1, 1, 0, 0]) - alpha * dj1
= np.linalg.pinv(D_FDSP) print 'SPS - FDSP Rec:' print R_FDSP.shape if VISU == True: fig2, ax = plt.subplots() fig2.set_size_inches(12,4) #Rx and Ry are in radians. We want to show IM in microns RMS SURF of tilt #We found using DOS that a segment tilt of 47 mas is equivalent to 0.5 microns RMS of tilt on an M1 seg. AngleRadians_2_tiltcoeff = 0.5 / (47e-3*math.pi/180/3600) #angle in radians to microns RMS of tilt coeff imm = ax.pcolor(D_FDSP/AngleRadians_2_tiltcoeff) #in displaced pixels per microns RMS of M1 segment tilt ax.grid() ax.set_ylim([0,36]) ax.set_xticks(range(12)) ax.set_xticklabels(['S1 $R_x$','S1 $R_y$','S2 $R_x$','S2 $R_y$','S3 $R_x$','S3 $R_y$', 'S4 $R_x$','S4 $R_y$','S5 $R_x$','S5 $R_y$','S6 $R_x$','S6 $R_y$'], ha='left', fontsize=15, rotation=45, color='b') ax.set_yticks([0,12,24,36]) ax.tick_params(axis='y', labelsize=13) ax.text(-0.4,6,'SPS$_1$', rotation=45, ha='center', va='center', fontsize=15, color='b') ax.text(-0.4,18,'SPS$_2$', rotation=45, ha='center', va='center', fontsize=15, color='b') ax.text(-0.4,30,'SPS$_3$', rotation=45, ha='center', va='center', fontsize=15, color='b') fig2.colorbar(imm) # In[11]: # Combine Interaction Matrices of M1 segment piston AND FDSP. if simul_PS_control==True and simul_FDSP_control==True: D_PIST = np.concatenate((D_M1_PS, D_FDSP), axis=1) R_PIST = np.linalg.pinv(D_PIST) print 'Merged SPS - PISTON Rec:' print R_PIST.shape print 'PIST Condition number: %f'%np.linalg.cond(D_M1_PS) print 'FDSP Condition number: %f'%np.linalg.cond(D_FDSP) print 'Merged Condition number: %f'%np.linalg.cond(D_PIST) if VISU == True: plt.pcolor(D_PIST) plt.colorbar() # In[12]: ## INITIAL SCRAMBLE # Reset before starting if simul_onaxis_AO==True: gs.reset() if simul_SPS==True: gsps.reset() ongs.reset() gmt.reset() # Apply a known Tilt to a particular segment on M1 M1RotVecInit = np.array([ #arcsec [0,0,0] , # 200e-3 [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0]], dtype='float32') * math.pi/180/3600 # Apply a known segment piston/translation to a particular segment on M1 M1TrVecInit = np.array([ # meters surf [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0]], dtype='float32') # Apply a known Tilt to a particular segment on M2 M2RotVecInit = np.array([ #arcsec [0,0,0] , [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0]], dtype='float32') * math.pi/180/3600 # Apply a known segment piston/translation to a particular segment on M2 M2TrVecInit = np.array([ # meters surf [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0]], dtype='float32') # Initial Segment TT Scramble if scramble_tt==True: #TTscramble = np.float32(np.random.normal(loc=0.0, scale=1, size=12)) #TTscramble *= tt_scramble_rms*(math.pi/180/3600)/np.std(TTscramble) #TTscramble -= np.mean(TTscramble) TTscramble = np.array([ -1.26236118e-05, -8.71601696e-06, 1.03404554e-05, -7.36265883e-06, 8.89494913e-06, 6.71501175e-06, -1.40584075e-06, 1.25584484e-06, 5.25245332e-06, -7.25066275e-06, -5.69112842e-07, 5.46918909e-06], dtype='float32') M1RotVecInit[0:6,0:2] += TTscramble.reshape((6,2)) print "Initial M1 segment TT scramble RMS [mas]: %0.2f"%(np.std(TTscramble)*ceo.constants.RAD2MAS) print "Initial M1 segment TT scramble mean value [mas]: %0.2f"%(np.mean(TTscramble)*ceo.constants.RAD2MAS) # Initial Segment Piston Scramble if scramble_pist==True: pistscramble = np.float32(np.random.normal(loc=0.0, scale=1, size=7)) pistscramble *= pist_scramble_rms/np.std(pistscramble) pistscramble -= np.mean(pistscramble) pistscramble -= pistscramble[6] M1TrVecInit[:,2] += pistscramble print "Initial segment piston scramble RMS [micron]: %0.2f"%(np.std(pistscramble)*1e6) print "Initial segment piston scramble mean value [micron]: %0.2f"%(np.mean(pistscramble)*1e6) ### Set GMT M1 and M2 rigid-body scrambles for idx in range(7): gmt.M1.update(origin=M1TrVecInit[idx,:].tolist(), euler_angles=M1RotVecInit[idx,:].tolist(), idx=idx+1) for idx in range(7): gmt.M2.update(origin=M2TrVecInit[idx,:].tolist(), euler_angles=M2RotVecInit[idx,:].tolist(), idx=idx+1) """# Apply a Zernike vector to a particular segment on M1 mysegId = 2 a_M1 = np.zeros(gmt.M1.zernike.n_mode) #zernike coeffs, from piston Z1 to n_zern #a_M1[10] = 250e-9 # m RMS surf gmt.M1.zernike.a[mysegId-1,:] = a_M1 #for mmmm in range(6): gmt.M1.zernike.a[mmmm,:] = a_M1 gmt.M1.zernike.update()""" if VISU==True: ongs.reset() gmt.propagate(ongs) fig, ax = plt.subplots() fig.set_size_inches(20,5) imm = ax.imshow(ongs.phase.host(units='micron'), interpolation='None',cmap='RdYlBu',origin='lower') ax.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') clb = fig.colorbar(imm, ax=ax, fraction=0.012, pad=0.03,format="%.1f") clb.set_label('$\mu m$ WF', fontsize=25) clb.ax.tick_params(labelsize=15) ongs.reset() # In[12]: ## INIT VARIABLES AND ALLOCATE MEMORY FOR RESULTS totSimulIter = int(totSimulTime/Tsim) if simul_SPS==True: sps_exp_count = 0 sps_exp_count_max = int(exposureTime/Tsim) sps_exp_delay_count = 0 sps_sampl_count = 0 sps_sampl_count_max = int(samplingTime/exposureTime) kk = 1 # to keep the count of PS/FDSP commands applied. ps.camera.reset_rng(sps_seed) if eval_perf_sps==True: seg_pist_sps_iter = np.zeros((N_GS_PS,7,totSimulIter)) SPSmeas_iter = np.zeros((N_GS_PS*12,sps_sampl_iter+1)) SPSfft_images = np.zeros((ps.camera.N_PX_IMAGE,ps.camera.N_PX_IMAGE,N_GS_PS*12,sps_sampl_iter+1)) timeVec = np.arange(totSimulIter)*Tsim M1TrVec = M1TrVecInit #np.zeros((7,3)) M1RotVec = M1RotVecInit M2TrVec = M2TrVecInit M2RotVec = M2RotVecInit if simul_PS_control==True: M1PSresiter = np.zeros((7,sps_sampl_iter+1)) M1PSresiter[:,0] = M1TrVec[:,2] # kk=0 if simul_FDSP_control==True: M1TTresiter = np.zeros((7,2,sps_sampl_iter+1)) M1TTresiter[:,:,0] = M1RotVec[:,0:2] # kk=0 if simul_onaxis_AO==True: if onaxis_AO_modes=='zernikes': a_M2 = np.zeros(nzernall) a_M2_iter = np.zeros((nzernall,totSimulIter)) M2PSiter = np.zeros((7,totSimulIter)) myAOest1 = np.zeros(nzernall+7) #7x2 segments TTs + 7 outer segment piston elif onaxis_AO_modes=='TT': M2TTiter = np.zeros((7,2,totSimulIter)) M2PSiter = np.zeros((7,totSimulIter)) myAOest1 = np.zeros(14+7) #7x2 segments TTs + 6 outer segment pistons #myTTest1 = np.zeros(14+2) #7x2 segment TTs + global TT #M2gTTresiter = np.zeros((2,totSimulIter)) if eval_perf_onaxis==True: wfe_gs_iter = np.zeros(totSimulIter) seg_pist_onaxis_iter = np.zeros((7,totSimulIter)) if simul_turb==True: wfe_gs_tur_iter = np.zeros(totSimulIter) if eval_perf_modal==True: seg_aRes_gs_iter = np.zeros((Zobj.n_mode,7,totSimulIter)) if simul_turb==True: seg_aTur_gs_iter = np.zeros((Zobj.n_mode,7,totSimulIter)) if eval_perf_field == True: #wfe_sfgs_iter = np.zeros((sfgs.N_SRC, totSimulIter)) pist_sfgs_iter = np.zeros((sfgs.N_SRC, totSimulIter)) elapsedTime = np.zeros(totSimulIter) print 'Total simulation time [s]: %4.3f'%(totSimulTime) if simul_SPS == True: print ' DFS Sampling time [ms]: %4.2f'%(samplingTime*1e3) print ' DFS Exposure time [ms]: %4.2f'%(exposureTime*1e3) print 'Simulation time step [ms]: %4.2f'%(Tsim*1e3) # In[13]: ## CLOSE THE LOOP!! if simul_SPS==True: ps.reset() for jj in range(totSimulIter): tid.tic() if simul_SPS==True: gsps.reset() if simul_SH==True: gs.reset() if eval_perf_onaxis==True: ongs.reset() if eval_perf_field==True: sfgs.reset() #----- Update Turbulence -------------------------------------------- if simul_turb == True: if simul_SPS==True: atm.ray_tracing(gsps, p,nPx,p,nPx, jj*Tsim) if simul_onaxis_AO==True: atm.ray_tracing( gs, p,nPx,p,nPx, jj*Tsim) if eval_perf_onaxis==True: atm.ray_tracing(ongs, p,nPx,p,nPx, jj*Tsim) wfe_gs_tur_iter[jj] = ongs.wavefront.rms() if eval_perf_modal==True: PhaseTur = ongs.phase.host(units='nm')-ph_fda_on*1e3 seg_aTur_gs_iter[:,:,jj] = Zobj.fitting(PhaseTur) if eval_perf_field==True: atm.ray_tracing(sfgs, p,nPx,p,nPx, jj*Tsim) #----- Update M1 positions ------------------------------------- for idx in range(7): gmt.M1.update(origin = M1TrVec[idx,:].tolist(), euler_angles = M1RotVec[idx,:].tolist(), idx = idx+1) #----- Update M2 positions ------------------------------------- """for idx in range(7): gmt.M2.update(origin = M2TrVec[idx,:].tolist(), euler_angles = M2RotVec[idx,:].tolist(), idx = idx+1)""" if simul_onaxis_AO==True: if onaxis_AO_modes=='TT': gmt.M2.motion_CS.euler_angles[:,0:2] -= myAOest1[0:14].reshape((7,2)) gmt.M2.motion_CS.origin[:,2] -= myAOest1[14:] #gmt.M2.motion_CS.euler_angles[:,0:2] -= myTTest1[2:].reshape((7,2)) #gmt.M2.global_tiptilt(-myTTest1[0],-myTTest1[1]) gmt.M2.motion_CS.update() elif onaxis_AO_modes=='zernikes': gmt.M2.zernike.a[:,z_first_mode:] -= myAOest1[0:nzernall].reshape((7,-1)) gmt.M2.motion_CS.origin[:,2] -= myAOest1[nzernall:] gmt.M2.motion_CS.update() gmt.M2.zernike.update() #----- On-axis WFS measurement and correction ----------------------- if simul_onaxis_AO==True: gmt.propagate(gs) wfs.reset() wfs.analyze(gs) slopevec = wfs.valid_slopes.host().ravel() onpsvec = onps.piston(gs, segment='full').ravel() - onps_signal_ref AOmeasvec = np.concatenate((slopevec, onpsvec)) myAOest1 = gAO * np.dot(R_AO, AOmeasvec) if onaxis_AO_modes=='TT': """#--- segment TT correction (on M2) M2TTiter[:,:,jj] = M2RotVec[:,0:2] myTTest1 = gAO * np.dot(R_M2_TT, slopevec).reshape((7,2)) M2RotVec[:,0:2] -= myTTest1""" """#---- Global TT and Segment TT correction M2TTiter[:,:,jj] = M2RotVec[:,0:2] M2gTTresiter[:,jj] = -myTTest1[0:2] myTTest1 = gAO * np.dot(R_M2_TTm, slopevec) M2RotVec[:,0:2] -= myTTest1[2:].reshape((7,2))""" #---- Using the super-merger simplified AO rec: M2TTiter[:,:,jj] = M2RotVec[:,0:2] M2PSiter[:,jj] = M2TrVec[:,2] M2RotVec[:,0:2] -= myAOest1[0:14].reshape((7,2)) M2TrVec[:,2] -= myAOest1[14:] #--- segment Zernikes correction (on M2) elif onaxis_AO_modes=='zernikes': a_M2_iter[:,jj] = a_M2 M2PSiter[:,jj] = M2TrVec[:,2] a_M2 -= myAOest1[0:nzernall] M2TrVec[:,2] -= myAOest1[nzernall:] #----- On-axis performance evaluation --------------------------------- if eval_perf_onaxis==True: gmt.propagate(ongs) wfe_gs_iter[jj] = ongs.wavefront.rms() seg_pist_onaxis_iter[:,jj] = ongs.piston(where='segments', units_exponent=-9) - seg_pist_onaxis_ref if eval_perf_modal==True: PhaseRes = ongs.phase.host(units='nm')-ph_fda_on*1e3 seg_aRes_gs_iter[:,:,jj] = Zobj.fitting(PhaseRes) if eval_perf_field==True: gmt.propagate(sfgs) #wfe_sfgs_iter[:,jj] = sfgs.wavefront.rms() pist_sfgs_iter[:,jj] = np.std(sfgs.piston(where='segments', units_exponent=-9) - sf_pist0, axis=1) #----- Segment Piston Sensors measurement and correction ------------- if simul_SPS==True: gmt.propagate(gsps) if eval_perf_sps==True: seg_pist_sps_iter[:,:,jj] = gsps.piston(where='segments', units_exponent=-9) - seg_pist_sps_ref if sps_sampl_count == 0 and sps_exp_delay_count < sps_exp_delay_count_max: sps_exp_delay_count += 1 #print("SPS frame avoided at %3.1f ms"%((jj+1)*Tsim*1e3)) else: ps.propagate(gsps) if sps_exp_count == sps_exp_count_max-1: #--- Read-out the detector if simul_phot==True: if simul_bkgd==False: ps.camera.readOut(exposureTime,RONval) else: ps.readOut(exposureTime,RONval,bkgd_mag) #--- Compute and integrate FFTlet images: ps.fft() ps.camera.reset() sps_exp_count = 0 #print("SPS exposure completed at %3.1f ms"%((jj+1)*Tsim*1e3)) #--- Compute SPS signals: if sps_sampl_count == sps_sampl_count_max-1: ps.process() SPSmeas = ps.measurement - SPSmeas_ref SPSfft_images[:,:,:,kk] = ps.get_data_cube(data_type='fftlet') SPSmeas_iter[:,kk] = SPSmeas #--- segment piston AND FDSP control: if simul_PS_control==True and simul_FDSP_control==True: PISTvec = np.dot(R_PIST, SPSmeas) myPSest1 = gPS * PISTvec[0:6] M1TrVec[0:6,2] -= myPSest1 M1PSresiter[:,kk] = M1TrVec[:,2] myFDSPest1 = gFDSP * PISTvec[6:].reshape((6,2)) M1RotVec[0:6,0:2] -= myFDSPest1 M1TTresiter[:,:,kk] = M1RotVec[:,0:2] #--- ONLY segment piston control: elif simul_PS_control==True: PISTvec = np.dot(R_M1_PS, SPSmeas) myPSest1 = gPS * PISTvec M1TrVec[0:6,2] -= myPSest1 M1PSresiter[:,kk] = M1TrVec[:,2] #--- ONLY FDSP control: elif simul_FDSP_control==True: PISTvec = np.dot(R_FDSP, SPSmeas) myFDSPest1 = gFDSP * PISTvec.reshape((6,2)) M1RotVec[0:6,0:2] -= myFDSPest1 M1TTresiter[:,:,kk] = M1RotVec[:,0:2] if simul_PS_control==True: sys.stdout.write("\n seg piston RMS [microns]: %0.3f \n"%(np.std(M1PSresiter[:,kk])*1e6)) ps.fftlet.reset() sps_sampl_count = 0 sps_exp_delay_count = 0 kk += 1 #print("SPS command applied at %3.1f ms"%((jj+1)*Tsim*1e3)) else: sps_sampl_count += 1 else: sps_exp_count += 1 tid.toc() elapsedTime[jj] = tid.elapsedTime sys.stdout.write("\r iter: %d/%d, ET: %.2f, seg piston [nm WF RMS] on-axis: %0.1f"%(jj, totSimulIter, tid.elapsedTime, np.std(seg_pist_onaxis_iter[:,jj]))) sys.stdout.flush() if VISU == True: #ongs.reset() #gmt.propagate(ongs) fig, ax = plt.subplots() fig.set_size_inches(20,5) imm = ax.imshow(ongs.phase.host(units='micron'), interpolation='None',cmap='RdYlBu',origin='lower')#, vmin=-8, vmax=8) ax.tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') clb = fig.colorbar(imm, ax=ax, fraction=0.012, pad=0.03,format="%.1f") clb.set_label('$\mu m$ WF', fontsize=25) clb.ax.tick_params(labelsize=15) #ongs.reset() # In[135]: #### on-axis WFE vs. iteration number if VISU == True and eval_perf_onaxis==True: fig, ax = plt.subplots() fig.set_size_inches(15,5) ax.semilogy(timeVec*1e3, wfe_gs_iter*1e9, '-+') ax.grid() ax.set_xlabel('Time [ms]', fontsize=20) ax.set_ylabel('nm WF rms', fontsize=20) ax.tick_params(labelsize=15) # In[136]: #### on-axis segment WFE vs. iteration number if VISU == True and eval_perf_onaxis==True: fig, ax = plt.subplots() fig.set_size_inches(15,5) ax.semilogy(timeVec*1e3, seg_pist_onaxis_iter.T, '-+') ax.grid() ax.set_xlabel('Time [ms]', fontsize=20) ax.set_ylabel('nm WF rms', fontsize=20) ax.tick_params(labelsize=15) # In[137]: #### Residual segment piston analysis print 'Final M1 final piston (Tz) values
self.numValidStructsFound = 0 multiCmdFile = open(self.multiCmdFile, 'w+') multiCmdFile.write('_LINES = 10000\n') print("\nTelemetry Object List") for i in range(len(self.telemetryObjectList)): dataObjectName = self.telemetryObjectList[i][0] typeDefName = self.getTypeDefName(dataObjectName) try: print("%3i/%i: %-45s" % ( i + 1, len(self.telemetryObjectList), "%s ==> %s" % (dataObjectName, str(typeDefName)))) if typeDefName is not None: with open('dataStructure.cfg', "a") as openFile: # Instance Name, Typedef, VERSION MAJOR macro, VERSION MINOR macro, Pack, versionMajorName, versionMinorName, RNLBA, WNLBA openFile.write( ' [\'{0}\',\'{1}\',None,None,None,None,None,None,None],\n'.format(str(dataObjectName), str(typeDefName))) openFile.close() except: pass ### Add command to extRC to be executed in Multi Debugger if typeDefName is not None: fileName, typeDefStructName, lineNum = self.getTypeDefStruct(typeDefName) if (typeDefStructName is not None): self.numValidStructsFound += 1 #### Extracting version field if (self.options.verbose): print(str(fileName), str(typeDefStructName), str(lineNum)) verMajorMacro, versionMajor, verMinorMacro, versionMinor = self.searchVersionMajorMinor(fileName, typeDefStructName, lineNum) try: print(', %30s=0x%04X, %30s=0x%04X,' % ( verMajorMacro, versionMajor, verMinorMacro, versionMinor), ) except: pass multiCmdFile.write('mprintf(\"ObjectBegin==>%s\\n\")\n' % (dataObjectName)) multiCmdFile.write(typeDefStructName + '\n') multiCmdFile.write("sizeof(" + typeDefStructName + ")\n") multiCmdFile.write('mprintf(\"%s = 0x%%04X\\n\",%i)\n' % ('versionMajor', versionMajor)) multiCmdFile.write('mprintf(\"%s = 0x%%04X\\n\",%i)\n' % ('versionMinor', versionMinor)) multiCmdFile.write('mprintf(\"ObjectEnd==>%s\\n\")\n' % (dataObjectName)) if (self.telemetryObjectList[i][1] not in self.masterObjectList.keys()): if ('0X' in self.telemetryObjectList[i][1].upper()): self.masterObjectList[int(self.telemetryObjectList[i][1], 16)] = [ self.telemetryObjectList[i][0], typeDefStructName, self.telemetryObjectList[i][2]] elif re.search('^[a-zA-Z_]+', self.telemetryObjectList[i][1]): ### Got a macro for UID. Let scan the FW to get the value. macroUid = self.getFwMacroValue(self.telemetryObjectList[i][1]) # @todo unused else: self.masterObjectList[int(self.telemetryObjectList[i][1])] = [ self.telemetryObjectList[i][0], typeDefStructName, self.telemetryObjectList[i][2]] else: print("\n-E- UID (%i for %s) as specified by FW datacontrol.h is not unique!" % ( self.telemetryObjectList[i][1], self.telemetryObjectList[i][0])) if ENABLE_DEBUG_ENTER: quit(20) print('+') else: self.log.debug("Not able to extract %s" % (dataObjectName)) print('-') else: self.log.debug("Not able to extract %s" % (dataObjectName)) print('-') multiCmdFile.write('quitall\n') ### Exit multi gracefully multiCmdFile.close() if (self.options.debug): print("\nMaster Object List:") print("%8s: %-30s, %-30s, %2s" % ('Key', 'Object', 'Struct', 'DA')) for key in sorted(self.masterObjectList.keys()): print("%8i: %-30s, %-30s, %2s" % ( key, self.masterObjectList[key][0], self.masterObjectList[key][1], self.masterObjectList[key][2])) command = '%s %s -nodisplay -p %s -RO %s' % (self.multiExe, self.elfFile, self.multiCmdFile, self.structDefFile) self.executeMultiScript(command) self.recursive = False ### Set recursive flag to False to start a new recursive call self.extractArraySubStructs() self.getAllStructSizes() # self.deleteTempFiles() print("\nTotal valid structures found: %i/%i" % (self.numValidStructsFound, len(self.telemetryObjectList))) def deleteTempFiles(self): """Performs delete of temp files used in parsing.""" if os.path.exists(self.multiCmdFile): os.remove(self.multiCmdFile) if os.path.exists(self.subStructMultiCmdFile): os.remove(self.subStructMultiCmdFile) #################################################################################### #################################################################################### #################################################################################### #################################################################################### def createMasterObjectListUidValue(self): """Performs a key list creation for unique identifiers.""" for key in sorted(self.masterObjectList.keys()): self.masterObjectListUidValue[self.masterObjectList[key][0]] = key self.masterObjectListUidValue[self.masterObjectList[key][1]] = key if (self.options.verbose): print("\nMaster Object List w/ Data Object and Struct as keys:") print("%-30s: %-3s" % ('Key', 'UID')) for key in sorted(self.masterObjectListUidValue.keys()): print("%-30s: %3s" % (key, self.masterObjectListUidValue[key])) def getObjectsFromStructDefFile(self): """Performs an extraction of the definitions from GHS produced file.""" # Process through specified data object file to get list for scanning iFile = open(self.structDefFile, 'r') lines = iFile.readlines() iFile.close() myKeys = self.masterObjectListUidValue.keys() self.objectsInStructDefFile = [] for l in lines: if ('==>' not in l): continue line = l.strip() line = re.sub('^ +', '', line) line = re.sub(' +', '', line) line = re.sub('{', '', line) if matchSequence[3].match(line): m = matchSequence[3].match(line) fwObject = m.group(1) if fwObject in myKeys: uid = int(self.masterObjectListUidValue[fwObject]) fwStruct = self.masterObjectList[uid][1] self.objectsInStructDefFile.append([fwObject, fwStruct, uid]) if (self.options.verbose): print("\nActual structs found in the stuct definition file:") for i in range(len(self.objectsInStructDefFile)): print(i, self.objectsInStructDefFile[i][0], self.objectsInStructDefFile[i][1], self.objectsInStructDefFile[i][2]) def getStructSizeInBits(self, fwStruct): """Performs an extraction of the definitions from GHS produced file.""" iFile = open(self.structSizeFile, 'r') lines = iFile.readlines() iFile.close() sizeInBits = 0 for l in lines: if re.search('^sizeof\(%s\)=(\d+)' % fwStruct, l.strip()): m = re.search('^sizeof\(%s\)=(\d+)' % fwStruct, l.strip()) sizeInBits = eval(m.group(1)) * 8 break return sizeInBits def onlyHasSimpleSubstructures(self, obj): """Performs check to determine if fundamental type.""" if (len(obj.memberList) > 0): for o in obj.memberList: if (len(o.memberList) > 0): return False return True def determineObjectSizes(self, obj): """Performs an extraction of the definitions size from GHS.""" sizeInBits = 0 arrayDimString = str(obj.arrayDimList[0]) for i in range(1, len(obj.arrayDimList)): arrayDimString += "*" + str(obj.arrayDimList[i]) if (obj.fwStruct in list(self.cToPythonCtypeMap.keys())): obj.sizeInBits = ctypes.sizeof(eval(self.cToPythonCtypeMap[obj.fwStruct])) * 8 * eval(arrayDimString) obj.subStructSizeGood = 1 elif self.getStructSizeInBits(obj.fwStruct): sizeInBits = self.getStructSizeInBits(obj.fwStruct) * eval(arrayDimString) obj.sizeInBits = sizeInBits obj.subStructSizeGood = 1 elif re.search('^struct (.+)$', obj.fwStruct): m = re.search('^struct (.+)$', obj.fwStruct) sizeInBits = self.getStructSizeInBits(m.group(1)) * eval(arrayDimString) if (sizeInBits): obj.subStructSizeGood = 1 else: sizeInBits = obj.sizeInBits obj.sizeInBits = sizeInBits elif re.search('^union (.+)$', obj.fwStruct): m = re.search('^union (.+)$', obj.fwStruct) sizeInBits = self.getStructSizeInBits(m.group(1)) * eval(arrayDimString) if (sizeInBits): obj.subStructSizeGood = 1 else: sizeInBits = obj.sizeInBits obj.sizeInBits = sizeInBits elif re.search('^enum (.+)$', obj.fwStruct): m = re.search('^enum (.+)$', obj.fwStruct) sizeInBits = self.getStructSizeInBits(m.group(1)) * eval(arrayDimString) if (sizeInBits): obj.subStructSizeGood = 1 else: sizeInBits = obj.sizeInBits obj.sizeInBits = sizeInBits if obj.memberList == []: return else: for i in range(len(obj.memberList)): self.determineObjectSizes(obj.memberList[i]) def auditStructSizes(self, obj): """Performs an verification of definitions from GHS.""" if (len(obj.memberList) <= 0): return ### We do nothing here because I cannot be certain if the simple data object size is valid or not. if (obj.sizeInBits == 0): ### Dealing with unions of size 0 if (obj.structType in ['union']): ### Setting the size for a 0-size union for o in obj.memberList: if (o.structType not in ['union']) and (o.sizeInBits != 0): obj.sizeInBits = o.sizeInBits obj.subStructSizeGood = 1 break #### Set subStructSizeGood status for the union object's subStructs for o in obj.memberList: if (o.sizeInBits == obj.sizeInBits): o.subStructSizeGood = 1 else: o.subStructSizeGood = 0 o.sizeInBits = obj.sizeInBits ### Setting the size for a 0-size struct elif (obj.structType in ['struct']): for o in obj.memberList: obj.sizeInBits += o.sizeInBits obj.subStructSizeGood = 1 ### Setting the size for a 0-size struct elif (obj.structType in ['bitfield']) and self.onlyHasSimpleSubstructures(obj): for o in obj.memberList: if (o.structType not in ['union']) and (o.sizeInBits != 0): obj.sizeInBits = o.sizeInBits obj.subStructSizeGood = 1 o.subStructSizeGood = 0 break ### Setting the size for a 0-size struct elif (obj.structType in ['bitfield']): for o in obj.memberList: obj.sizeInBits += o.sizeInBits obj.subStructSizeGood = 1 ### Catching other 0-size data construct as error for further evaluation later. else: pprint(vars(obj)) pressReturnToContinue('1 getting obj.sizeInBits') ### Obtain size for unions and structs gotCalculatedUnionSize = False calculatedSubstructSizeTotal = 0 for o in obj.memberList: self.auditStructSizes(o) if (obj.structType in ['union']): if (not gotCalculatedUnionSize): calculatedSubstructSizeTotal = o.sizeInBits if obj.sizeInBits == o.sizeInBits: gotCalculatedUnionSize = True else: calculatedSubstructSizeTotal += o.sizeInBits ### Check the goodness of an object's size relative to its substructures if (obj.sizeInBits == calculatedSubstructSizeTotal): obj.subStructSizeGood = 1 ### Otherwise, something is not right about the size of the substructures ### Let's set the subStructSizeGood of all substructures to False elif ('bitfield' not in obj.structType) and \ ('unnamed type' not in obj.fwStruct) and \ (obj.depth > 1): for o in obj.memberList: o.subStructSizeGood = 0 # if ('transport' in o.fwObject): # print # pprint(vars(o)) # print # pprint(vars(obj)) # print # print "obj.sizeInBits", obj.sizeInBits # print "calculatedSubstructSizeTotal", calculatedSubstructSizeTotal # pressReturnToContinue('3.6') #### Set subStructSizeGood status for the any object's subStructs if (obj.structType and obj.fwStruct): if ('bitfield' not in obj.structType) and ('unnamed type' not in obj.fwStruct): for o in obj.memberList: if (not obj.subStructSizeGood): o.subStructSizeGood = 0 def printObjectInfo(self, obj, oFile, structNum=None): """Performs console print of the object information to a file.""" arrayDimString = '' arrayDimString = str(obj.arrayDimList[0]) for i in range(len(obj.arrayDimList)): if i > 0: arrayDimString += "*" + str(obj.arrayDimList[i]) if obj.memberList == []: oFile.write('%s,%s,%s,%s,%s,%s,0x%04X,0x%04X,%s,\"%s\",%s\n' % \ (obj.fwStruct, str(obj.fwObject), obj.structType, str(obj.sizeInBits), arrayDimString, str(obj.uid), int(obj.versionMajor), int(obj.versionMinor), str(obj.subStructSizeGood), str(obj.ancestryNames), '')) return else: if (obj.depth == 1): oFile.write('%s,%s,%s,%s,%s,%s,0x%04X,0x%04X,%s,\"%s\",%s\n' % \ (obj.fwStruct, str(obj.fwObject), obj.structType, str(obj.sizeInBits), arrayDimString, str(obj.uid), int(obj.versionMajor), int(obj.versionMinor), str(obj.subStructSizeGood), str(obj.ancestryNames), 'ObjectStart')) elif (obj.structType == 'union'): oFile.write('%s,%s,%s,%s,%s,%s,0x%04X,0x%04X,%s,\"%s\",%s\n' % \ (obj.fwStruct, str(obj.fwObject), obj.structType, str(obj.sizeInBits), arrayDimString, str(obj.uid), int(obj.versionMajor), int(obj.versionMinor), str(obj.subStructSizeGood), str(obj.ancestryNames), 'Union%i%iStart' % (obj.depth, structNum))) else: oFile.write('%s,%s,%s,%s,%s,%s,0x%04X,0x%04X,%s,\"%s\",%s\n' % \ (obj.fwStruct, str(obj.fwObject), obj.structType, str(obj.sizeInBits), arrayDimString, str(obj.uid), int(obj.versionMajor), int(obj.versionMinor), str(obj.subStructSizeGood), str(obj.ancestryNames), 'Struct%i%iStart' % (obj.depth, structNum))) for i in range(len(obj.memberList)): self.printObjectInfo(obj.memberList[i], oFile, i + 1) if (obj.depth == 1): oFile.write('%s,%s,%s,%s,%s,%s,0x%04X,0x%04X,%s,\"%s\",%s\n' % \ (obj.fwStruct, str(obj.fwObject), obj.structType, str(obj.sizeInBits), arrayDimString, str(obj.uid), int(obj.versionMajor), int(obj.versionMinor), str(obj.subStructSizeGood), str(obj.ancestryNames), 'ObjectEnd')) elif (obj.structType == 'union'): oFile.write('%s,%s,%s,%s,%s,%s,0x%04X,0x%04X,%s,\"%s\",%s\n' % \ (obj.fwStruct, str(obj.fwObject), obj.structType, str(obj.sizeInBits), arrayDimString, str(obj.uid), int(obj.versionMajor), int(obj.versionMinor), str(obj.subStructSizeGood), str(obj.ancestryNames), 'Union%i%iEnd' % (obj.depth, structNum))) else: oFile.write('%s,%s,%s,%s,%s,%s,0x%04X,0x%04X,%s,\"%s\",%s\n' % \ (obj.fwStruct, str(obj.fwObject), obj.structType, str(obj.sizeInBits), arrayDimString, str(obj.uid), int(obj.versionMajor), int(obj.versionMinor), str(obj.subStructSizeGood), str(obj.ancestryNames), 'Struct%i%iEnd' % (obj.depth, structNum))) def outputObjectCsv(self, obj): """Performs an collection of information to output CSV formated file.""" outFile = os.path.join(self.parsersFolder, obj.fwObject + '.csv') cannotOpenFileForWrite = False while (not cannotOpenFileForWrite): try: with open(outFile, "wb") as
'physical', 'pink', 'plain', 'planned', 'plastic', 'pleasant', 'pleased', 'poised', 'polish', 'polite', 'political', 'poor', 'popular', 'positive', 'possible', 'post-war', 'potential', 'powerful', 'practical', 'precious', 'precise', 'preferred', 'pregnant', 'preliminary', 'premier', 'prepared', 'present', 'presidential', 'pretty', 'previous', 'prickly', 'primary', 'prime', 'primitive', 'principal', 'printed', 'prior', 'private', 'probable', 'productive', 'professional', 'profitable', 'profound', 'progressive', 'prominent', 'promising', 'proper', 'proposed', 'prospective', 'protective', 'protestant', 'proud', 'provincial', 'psychiatric', 'psychological', 'public', 'puny', 'pure', 'purple', 'purring', 'puzzled', 'quaint', 'qualified', 'quick', 'quickest', 'quiet', 'racial', 'radical', 'rainy', 'random', 'rapid', 'rare', 'raspy', 'rational', 'ratty', 'raw', 'ready', 'real', 'realistic', 'rear', 'reasonable', 'recent', 'red', 'reduced', 'redundant', 'regional', 'registered', 'regular', 'regulatory', 'related', 'relative', 'relaxed', 'relevant', 'reliable', 'relieved', 'religious', 'reluctant', 'remaining', 'remarkable', 'remote', 'renewed', 'representative', 'repulsive', 'required', 'resident', 'residential', 'resonant', 'respectable', 'respective', 'responsible', 'resulting', 'retail', 'retired', 'revolutionary', 'rich', 'ridiculous', 'right', 'rigid', 'ripe', 'rising', 'rival', 'roasted', 'robust', 'rolling', 'roman', 'romantic', 'rotten', 'rough', 'round', 'royal', 'rubber', 'rude', 'ruling', 'running', 'rural', 'russian', 'sacred', 'sad', 'safe', 'salty', 'satisfactory', 'satisfied', 'scared', 'scary', 'scattered', 'scientific', 'scornful', 'scottish', 'scrawny', 'screeching', 'secondary', 'secret', 'secure', 'select', 'selected', 'selective', 'selfish', 'semantic', 'senior', 'sensible', 'sensitive', 'separate', 'serious', 'severe', 'sexual', 'shaggy', 'shaky', 'shallow', 'shared', 'sharp', 'sheer', 'shiny', 'shivering', 'shocked', 'short', 'short-term', 'shrill', 'shy', 'sick', 'significant', 'silent', 'silky', 'silly', 'similar', 'simple', 'single', 'skilled', 'skinny', 'sleepy', 'slight', 'slim', 'slimy', 'slippery', 'slow', 'small', 'smart', 'smiling', 'smoggy', 'smooth', 'so-called', 'social', 'socialist', 'soft', 'solar', 'sole', 'solid', 'sophisticated', 'sore', 'sorry', 'sound', 'sour', 'southern', 'soviet', 'spanish', 'spare', 'sparkling', 'spatial', 'special', 'specific', 'specified', 'spectacular', 'spicy', 'spiritual', 'splendid', 'spontaneous', 'sporting', 'spotless', 'spotty', 'square', 'squealing', 'stable', 'stale', 'standard', 'static', 'statistical', 'statutory', 'steady', 'steep', 'sticky', 'stiff', 'still', 'stingy', 'stormy', 'straight', 'straightforward', 'strange', 'strategic', 'strict', 'striking', 'striped', 'strong', 'structural', 'stuck', 'stupid', 'subjective', 'subsequent', 'substantial', 'subtle', 'successful', 'successive', 'sudden', 'sufficient', 'suitable', 'sunny', 'super', 'superb', 'superior', 'supporting', 'supposed', 'supreme', 'sure', 'surprised', 'surprising', 'surrounding', 'surviving', 'suspicious', 'sweet', 'swift', 'swiss', 'symbolic', 'sympathetic', 'systematic', 'tall', 'tame', 'tan', 'tart', 'tasteless', 'tasty', 'technical', 'technological', 'teenage', 'temporary', 'tender', 'tense', 'terrible', 'territorial', 'testy', 'then', 'theoretical', 'thick', 'thin', 'thirsty', 'thorough', 'thoughtful', 'thoughtless', 'thundering', 'tight', 'tiny', 'tired', 'top', 'tory', 'total', 'tough', 'toxic', 'traditional', 'tragic', 'tremendous', 'tricky', 'tropical', 'troubled', 'turkish', 'typical', 'ugliest', 'ugly', 'ultimate', 'unable', 'unacceptable', 'unaware', 'uncertain', 'unchanged', 'uncomfortable', 'unconscious', 'underground', 'underlying', 'unemployed', 'uneven', 'unexpected', 'unfair', 'unfortunate', 'unhappy', 'uniform', 'uninterested', 'unique', 'united', 'universal', 'unknown', 'unlikely', 'unnecessary', 'unpleasant', 'unsightly', 'unusual', 'unwilling', 'upper', 'upset', 'uptight', 'urban', 'urgent', 'used', 'useful', 'useless', 'usual', 'vague', 'valid', 'valuable', 'variable', 'varied', 'various', 'varying', 'vast', 'verbal', 'vertical', 'very', 'victorian', 'victorious', 'video-taped', 'violent', 'visible', 'visiting', 'visual', 'vital', 'vivacious', 'vivid', 'vocational', 'voiceless', 'voluntary', 'vulnerable', 'wandering', 'warm', 'wasteful', 'watery', 'weak', 'wealthy', 'weary', 'wee', 'weekly', 'weird', 'welcome', 'well', 'well-known', 'welsh', 'western', 'wet', 'whispering', 'white', 'whole', 'wicked', 'wide', 'wide-eyed', 'widespread', 'wild', 'willing', 'wise', 'witty', 'wonderful', 'wooden', 'working', 'working-class', 'worldwide', 'worried', 'worrying', 'worthwhile', 'worthy', 'written', 'wrong', 'yellow', 'young', 'yummy', 'zany', 'zealous'] b = ['abiding', 'accelerating', 'accepting', 'accomplishing', 'achieving', 'acquiring', 'acteding', 'activating', 'adapting', 'adding', 'addressing', 'administering', 'admiring', 'admiting', 'adopting', 'advising', 'affording', 'agreeing', 'alerting', 'alighting', 'allowing', 'altereding', 'amusing', 'analyzing', 'announcing', 'annoying', 'answering', 'anticipating', 'apologizing', 'appearing', 'applauding', 'applieding', 'appointing', 'appraising', 'appreciating', 'approving', 'arbitrating', 'arguing', 'arising', 'arranging', 'arresting', 'arriving', 'ascertaining', 'asking', 'assembling', 'assessing', 'assisting', 'assuring', 'attaching', 'attacking', 'attaining', 'attempting', 'attending', 'attracting', 'auditeding', 'avoiding', 'awaking', 'backing', 'baking', 'balancing', 'baning', 'banging', 'baring', 'bating', 'bathing', 'battling', 'bing', 'beaming', 'bearing', 'beating', 'becoming', 'beging', 'begining', 'behaving', 'beholding', 'belonging', 'bending', 'beseting', 'beting', 'biding', 'binding', 'biting', 'bleaching', 'bleeding', 'blessing', 'blinding', 'blinking', 'bloting', 'blowing', 'blushing', 'boasting', 'boiling', 'bolting', 'bombing', 'booking', 'boring', 'borrowing', 'bouncing', 'bowing', 'boxing', 'braking', 'branching', 'breaking', 'breathing', 'breeding', 'briefing', 'bringing', 'broadcasting', 'bruising', 'brushing', 'bubbling', 'budgeting', 'building', 'bumping', 'burning', 'bursting', 'burying', 'busting', 'buying', 'buzing', 'calculating', 'calling', 'camping', 'caring', 'carrying', 'carving', 'casting', 'cataloging', 'catching', 'causing', 'challenging', 'changing', 'charging', 'charting', 'chasing', 'cheating', 'checking', 'cheering', 'chewing', 'choking', 'choosing', 'choping', 'claiming', 'claping', 'clarifying', 'classifying', 'cleaning', 'clearing', 'clinging', 'cliping', 'closing', 'clothing', 'coaching', 'coiling', 'collecting', 'coloring', 'combing', 'coming', 'commanding', 'communicating', 'comparing', 'competing', 'compiling', 'complaining', 'completing', 'composing', 'computing', 'conceiving', 'concentrating', 'conceptualizing', 'concerning', 'concluding', 'conducting', 'confessing', 'confronting', 'confusing', 'connecting', 'conserving', 'considering', 'consisting', 'consolidating', 'constructing', 'consulting', 'containing', 'continuing', 'contracting', 'controling', 'converting', 'coordinating', 'copying', 'correcting', 'correlating', 'costing', 'coughing', 'counseling', 'counting', 'covering', 'cracking', 'crashing', 'crawling', 'creating', 'creeping', 'critiquing', 'crossing', 'crushing', 'crying', 'curing', 'curling', 'curving', 'cuting', 'cycling', 'daming', 'damaging', 'dancing', 'daring', 'dealing', 'decaying', 'deceiving', 'deciding', 'decorating', 'defining', 'delaying', 'delegating', 'delighting', 'delivering', 'demonstrating', 'depending', 'describing', 'deserting', 'deserving', 'designing', 'destroying', 'detailing', 'detecting', 'determining', 'developing', 'devising', 'diagnosing', 'diging', 'directing', 'disagreing', 'disappearing', 'disapproving', 'disarming', 'discovering', 'disliking', 'dispensing', 'displaying', 'disproving', 'dissecting', 'distributing', 'diving', 'diverting', 'dividing', 'doing', 'doubling', 'doubting', 'drafting', 'draging', 'draining', 'dramatizing', 'drawing', 'dreaming', 'dressing', 'drinking', 'driping', 'driving', 'dropping', 'drowning', 'druming', 'drying', 'dusting', 'dwelling', 'earning', 'eating', 'editeding', 'educating', 'eliminating', 'embarrassing', 'employing', 'emptying', 'enacteding', 'encouraging', 'ending', 'enduring', 'enforcing', 'engineering', 'enhancing', 'enjoying', 'enlisting', 'ensuring', 'entering', 'entertaining', 'escaping', 'establishing', 'estimating', 'evaluating', 'examining', 'exceeding', 'exciting', 'excusing', 'executing', 'exercising', 'exhibiting', 'existing', 'expanding', 'expecting', 'expediting', 'experimenting', 'explaining', 'exploding', 'expressing', 'extending', 'extracting', 'facing', 'facilitating', 'fading', 'failing', 'fancying', 'fastening', 'faxing', 'fearing', 'feeding', 'feeling', 'fencing', 'fetching', 'fighting', 'filing', 'filling', 'filming', 'finalizing', 'financing', 'finding', 'firing', 'fiting', 'fixing', 'flaping', 'flashing', 'fleing', 'flinging', 'floating', 'flooding', 'flowing', 'flowering', 'flying', 'folding', 'following', 'fooling', 'forbiding', 'forcing', 'forecasting', 'foregoing', 'foreseing', 'foretelling', 'forgeting', 'forgiving', 'forming', 'formulating', 'forsaking', 'framing', 'freezing', 'frightening', 'frying', 'gathering', 'gazing', 'generating', 'geting', 'giving', 'glowing', 'gluing', 'going', 'governing', 'grabing', 'graduating', 'grating', 'greasing', 'greeting', 'grinning', 'grinding', 'griping', 'groaning', 'growing', 'guaranteeing', 'guarding', 'guessing', 'guiding', 'hammering', 'handing', 'handling', 'handwriting', 'hanging', 'happening', 'harassing', 'harming', 'hating', 'haunting', 'heading', 'healing', 'heaping', 'hearing', 'heating', 'helping', 'hiding', 'hitting', 'holding', 'hooking', 'hoping', 'hopping', 'hovering', 'hugging', 'hmuming', 'hunting', 'hurrying', 'hurting', 'hypothesizing', 'identifying', 'ignoring', 'illustrating', 'imagining', 'implementing', 'impressing', 'improving', 'improvising', 'including', 'increasing', 'inducing', 'influencing', 'informing', 'initiating', 'injecting', 'injuring', 'inlaying', 'innovating', 'inputing', 'inspecting', 'inspiring', 'installing', 'instituting', 'instructing', 'insuring', 'integrating', 'intending', 'intensifying', 'interesting', 'interfering', 'interlaying', 'interpreting', 'interrupting', 'interviewing', 'introducing', 'inventing', 'inventorying', 'investigating', 'inviting', 'irritating', 'itching', 'jailing', 'jamming', 'jogging', 'joining', 'joking', 'judging', 'juggling', 'jumping', 'justifying', 'keeping', 'kepting', 'kicking', 'killing', 'kissing', 'kneeling', 'kniting', 'knocking', 'knotting', 'knowing', 'labeling', 'landing', 'lasting', 'laughing', 'launching', 'laying', 'leading', 'leaning', 'leaping', 'learning', 'leaving', 'lecturing', 'leding', 'lending', 'leting', 'leveling', 'licensing', 'licking', 'lying', 'lifteding', 'lighting', 'lightening', 'liking', 'listing', 'listening', 'living', 'loading', 'locating', 'locking', 'loging', 'longing', 'looking', 'losing', 'loving', 'maintaining', 'making', 'maning', 'managing', 'manipulating', 'manufacturing', 'mapping', 'marching', 'marking', 'marketing', 'marrying', 'matching', 'mating', 'mattering', 'meaning', 'measuring', 'meddling', 'mediating', 'meeting', 'melting', 'melting', 'memorizing', 'mending', 'mentoring', 'milking', 'mining', 'misleading', 'missing', 'misspelling', 'mistaking', 'misunderstanding', 'mixing', 'moaning', 'modeling', 'modifying', 'monitoring', 'mooring', 'motivating', 'mourning', 'moving', 'mowing', 'muddling', 'muging', 'multiplying', 'murdering', 'nailing', 'naming', 'navigating', 'needing', 'negotiating', 'nesting', 'noding', 'nominating', 'normalizing', 'noting', 'noticing', 'numbering', 'obeying', 'objecting', 'observing', 'obtaining', 'occuring', 'offending', 'offering', 'officiating', 'opening', 'operating', 'ordering', 'organizing', 'orienteding', 'originating', 'overcoming', 'overdoing', 'overdrawing', 'overflowing', 'overhearing', 'overtaking', 'overthrowing', 'owing', 'owning', 'packing', 'paddling', 'painting', 'parking', 'parting', 'participating', 'passing', 'pasting', 'pating', 'pausing', 'paying', 'pecking', 'pedaling', 'peeling', 'peeping', 'perceiving', 'perfecting', 'performing', 'permiting', 'persuading', 'phoning', 'photographing', 'picking', 'piloting', 'pinching', 'pining', 'pinpointing', 'pioneering', 'placing', 'planing', 'planting', 'playing', 'pleading', 'pleasing', 'plugging', 'pointing', 'poking', 'polishing', 'poping', 'possessing', 'posting', 'pouring', 'practicing', 'praiseding', 'praying', 'preaching', 'preceding', 'predicting', 'prefering', 'preparing', 'prescribing', 'presenting', 'preserving', 'preseting', 'presiding', 'pressing', 'pretending', 'preventing', 'pricking', 'printing', 'processing', 'procuring', 'producing', 'professing', 'programing', 'progressing', 'projecting', 'promising', 'promoting', 'proofreading', 'proposing', 'protecting', 'proving', 'providing', 'publicizing', 'pulling', 'pumping', 'punching', 'puncturing', 'punishing', 'purchasing', 'pushing', 'puting', 'qualifying', 'questioning', 'queuing', 'quiting', 'racing', 'radiating', 'raining', 'raising', 'ranking', 'rating', 'reaching', 'reading', 'realigning', 'realizing', 'reasoning', 'receiving', 'recognizing', 'recommending', 'reconciling', 'recording', 'recruiting', 'reducing', 'referring', 'reflecting', 'refusing', 'regreting', 'regulating', 'rehabilitating', 'reigning', 'reinforcing', 'rejecting', 'rejoicing', 'relating', 'relaxing', 'releasing', 'relying', 'remaining', 'remembering', 'reminding', 'removing', 'rendering', 'reorganizing', 'repairing', 'repeating', 'replacing', 'replying', 'reporting', 'representing', 'reproducing', 'requesting', 'rescuing', 'researching', 'resolving', 'responding', 'restoreding', 'restructuring', 'retiring', 'retrieving', 'returning', 'reviewing', 'revising', 'rhyming', 'riding', 'riding', 'ringing', 'rinsing', 'rising', 'risking', 'robing', 'rocking',
#!/usr/bin/env python # Copyright 2010,2011 Mozilla Foundation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE MOZILLA FOUNDATION ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE MOZILLA FOUNDATION OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation # are those of the authors and should not be interpreted as representing # official policies, either expressed or implied, of the Mozilla # Foundation. import difflib import os import shutil from StringIO import StringIO import subprocess import sys import tempfile import mozunit import unittest import xpt def get_output(bin, file): p = subprocess.Popen([bin, file], stdout=subprocess.PIPE) stdout, _ = p.communicate() return stdout if "MOZILLA_OBJDIR" in os.environ: class CheckXPTDump(unittest.TestCase): def test_xpt_dump_diffs(self): MOZILLA_OBJDIR = os.environ["MOZILLA_OBJDIR"] xptdump = os.path.abspath(os.path.join(MOZILLA_OBJDIR, "dist", "bin", "xpt_dump")) components = os.path.abspath(os.path.join(MOZILLA_OBJDIR, "dist", "bin", "components")) for f in os.listdir(components): if not f.endswith(".xpt"): continue fullpath = os.path.join(components, f) # read a Typelib and dump it to a string t = xpt.Typelib.read(fullpath) self.assert_(t is not None) outf = StringIO() t.dump(outf) out = outf.getvalue() # now run xpt_dump on it out2 = get_output(xptdump, fullpath) if out != out2: print "diff %s" % f for line in difflib.unified_diff(out2.split("\n"), out.split("\n"), lineterm=""): print line self.assert_(out == out2, "xpt_dump output should be identical for %s" % f) class TestIIDString(unittest.TestCase): def test_iid_str_roundtrip(self): iid_str = "11223344-5566-7788-9900-aabbccddeeff" iid = xpt.Typelib.string_to_iid(iid_str) self.assertEqual(iid_str, xpt.Typelib.iid_to_string(iid)) def test_iid_roundtrip(self): iid = "\x11\x22\x33\x44\x55\x66\x77\x88\x99\x00\xaa\xbb\xcc\xdd\xee\xff" iid_str = xpt.Typelib.iid_to_string(iid) self.assertEqual(iid, xpt.Typelib.string_to_iid(iid_str)) class TypelibCompareMixin: def assertEqualTypelibs(self, t1, t2): self.assert_(t1 is not None, "Should not be None") self.assert_(t2 is not None, "Should not be None") self.assertEqual(t1.version, t2.version, "Versions should be equal") self.assertEqual(len(t1.interfaces), len(t2.interfaces), "Number of interfaces should be equal") for i, j in zip(t1.interfaces, t2.interfaces): self.assertEqualInterfaces(i, j) def assertEqualInterfaces(self, i1, i2): self.assert_(i1 is not None, "Should not be None") self.assert_(i2 is not None, "Should not be None") self.assertEqual(i1.name, i2.name, "Names should be equal") self.assertEqual(i1.iid, i2.iid, "IIDs should be equal") self.assertEqual(i1.namespace, i2.namespace, "Namespaces should be equal") self.assertEqual(i1.resolved, i2.resolved, "Resolved status should be equal") if i1.resolved: if i1.parent or i2.parent: # Can't test exact equality, probably different objects self.assertEqualInterfaces(i1.parent, i2.parent) self.assertEqual(len(i1.methods), len(i2.methods)) for m, n in zip(i1.methods, i2.methods): self.assertEqualMethods(m, n) self.assertEqual(len(i1.constants), len(i2.constants)) for c, d in zip(i1.constants, i2.constants): self.assertEqualConstants(c, d) self.assertEqual(i1.scriptable, i2.scriptable, "Scriptable status should be equal") self.assertEqual(i1.function, i2.function, "Function status should be equal") def assertEqualMethods(self, m1, m2): self.assert_(m1 is not None, "Should not be None") self.assert_(m2 is not None, "Should not be None") self.assertEqual(m1.name, m2.name, "Names should be equal") self.assertEqual(m1.getter, m2.getter, "Getter flag should be equal") self.assertEqual(m1.setter, m2.setter, "Setter flag should be equal") self.assertEqual(m1.notxpcom, m2.notxpcom, "notxpcom flag should be equal") self.assertEqual(m1.constructor, m2.constructor, "constructor flag should be equal") self.assertEqual(m1.hidden, m2.hidden, "hidden flag should be equal") self.assertEqual(m1.optargc, m2.optargc, "optargc flag should be equal") self.assertEqual(m1.implicit_jscontext, m2.implicit_jscontext, "implicit_jscontext flag should be equal") for p1, p2 in zip(m1.params, m2.params): self.assertEqualParams(p1, p2) self.assertEqualParams(m1.result, m2.result) def assertEqualConstants(self, c1, c2): self.assert_(c1 is not None, "Should not be None") self.assert_(c2 is not None, "Should not be None") self.assertEqual(c1.name, c2.name) self.assertEqual(c1.value, c2.value) self.assertEqualTypes(c1.type, c2.type) def assertEqualParams(self, p1, p2): self.assert_(p1 is not None, "Should not be None") self.assert_(p2 is not None, "Should not be None") self.assertEqualTypes(p1.type, p2.type) self.assertEqual(p1.in_, p2.in_) self.assertEqual(p1.out, p2.out) self.assertEqual(p1.retval, p2.retval) self.assertEqual(p1.shared, p2.shared) self.assertEqual(p1.dipper, p2.dipper) self.assertEqual(p1.optional, p2.optional) def assertEqualTypes(self, t1, t2): self.assert_(t1 is not None, "Should not be None") self.assert_(t2 is not None, "Should not be None") self.assertEqual(type(t1), type(t2), "type types should be equal") self.assertEqual(t1.pointer, t2.pointer, "pointer flag should be equal for %s and %s" % (t1, t2)) self.assertEqual(t1.reference, t2.reference) if isinstance(t1, xpt.SimpleType): self.assertEqual(t1.tag, t2.tag) elif isinstance(t1, xpt.InterfaceType): self.assertEqualInterfaces(t1.iface, t2.iface) elif isinstance(t1, xpt.InterfaceIsType): self.assertEqual(t1.param_index, t2.param_index) elif isinstance(t1, xpt.ArrayType): self.assertEqualTypes(t1.element_type, t2.element_type) self.assertEqual(t1.size_is_arg_num, t2.size_is_arg_num) self.assertEqual(t1.length_is_arg_num, t2.length_is_arg_num) elif isinstance(t1, xpt.StringWithSizeType) or isinstance(t1, xpt.WideStringWithSizeType): self.assertEqual(t1.size_is_arg_num, t2.size_is_arg_num) self.assertEqual(t1.length_is_arg_num, t2.length_is_arg_num) class TestTypelibReadWrite(unittest.TestCase, TypelibCompareMixin): def test_read_file(self): """ Test that a Typelib can be read/written from/to a file. """ t = xpt.Typelib() # add an unresolved interface t.interfaces.append(xpt.Interface("IFoo")) fd, f = tempfile.mkstemp() os.close(fd) t.write(f) t2 = xpt.Typelib.read(f) os.remove(f) self.assert_(t2 is not None) self.assertEqualTypelibs(t, t2) #TODO: test flags in various combinations class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin): def checkRoundtrip(self, t): s = StringIO() t.write(s) s.seek(0) t2 = xpt.Typelib.read(s) self.assert_(t2 is not None) self.assertEqualTypelibs(t, t2) def test_simple(self): t = xpt.Typelib() # add an unresolved interface t.interfaces.append(xpt.Interface("IFoo")) self.checkRoundtrip(t) t = xpt.Typelib() # add an unresolved interface with an IID t.interfaces.append(xpt.Interface("IBar", "11223344-5566-7788-9900-aabbccddeeff")) self.checkRoundtrip(t) def test_parent(self): """ Test that an interface's parent property is correctly serialized and deserialized. """ t = xpt.Typelib() pi = xpt.Interface("IParent") t.interfaces.append(pi) t.interfaces.append(xpt.Interface("IChild", iid="11223344-5566-7788-9900-aabbccddeeff", parent=pi, resolved=True)) self.checkRoundtrip(t) def test_ifaceFlags(self): """ Test that an interface's flags are correctly serialized and deserialized. """ t = xpt.Typelib() t.interfaces.append(xpt.Interface("IFlags", iid="11223344-5566-7788-9900-aabbccddeeff", resolved=True, scriptable=True, function=True)) self.checkRoundtrip(t) def test_constants(self): c = xpt.Constant("X", xpt.SimpleType(xpt.Type.Tags.uint32), 0xF000F000) i = xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", constants=[c]) t = xpt.Typelib(interfaces=[i]) self.checkRoundtrip(t) # tack on some more constants i.constants.append(xpt.Constant("Y", xpt.SimpleType(xpt.Type.Tags.int16), -30000)) i.constants.append(xpt.Constant("Z", xpt.SimpleType(xpt.Type.Tags.uint16), 0xB0B0)) i.constants.append(xpt.Constant("A", xpt.SimpleType(xpt.Type.Tags.int32), -1000000)) self.checkRoundtrip(t) def test_methods(self): p = xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)) m = xpt.Method("Bar", p) i = xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", methods=[m]) t = xpt.Typelib(interfaces=[i]) self.checkRoundtrip(t) # add some more methods i.methods.append(xpt.Method("One", xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), params=[ xpt.Param(xpt.SimpleType(xpt.Type.Tags.int64)), xpt.Param(xpt.SimpleType(xpt.Type.Tags.float, pointer=True)) ])) self.checkRoundtrip(t) # test some other types (should really be more thorough) i.methods.append(xpt.Method("Two", xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), params=[ xpt.Param(xpt.SimpleType(xpt.Type.Tags.UTF8String, pointer=True)), xpt.Param(xpt.SimpleType(xpt.Type.Tags.wchar_t_ptr, pointer=True)) ])) self.checkRoundtrip(t) # add a method with an InterfaceType argument bar = xpt.Interface("IBar") t.interfaces.append(bar) i.methods.append(xpt.Method("IFaceMethod", xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), params=[ xpt.Param(xpt.InterfaceType(bar)) ])) self.checkRoundtrip(t) # add a method with an InterfaceIsType argument i.methods.append(xpt.Method("IFaceIsMethod", xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)), params=[ xpt.Param(xpt.InterfaceIsType(1)), xpt.Param(xpt.SimpleType(xpt.Type.Tags.nsIID)) ])) self.checkRoundtrip(t) # add a method with an ArrayType argument i.methods.append(xpt.Method("ArrayMethod", xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)), params=[ xpt.Param(xpt.ArrayType( xpt.SimpleType(xpt.Type.Tags.int32), 1, 2)), xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), ])) self.checkRoundtrip(t) # add a method with a StringWithSize and WideStringWithSize arguments i.methods.append(xpt.Method("StringWithSizeMethod", xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)), params=[ xpt.Param(xpt.StringWithSizeType( 1, 2)), xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), xpt.Param(xpt.WideStringWithSizeType( 4, 5)), xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), ])) self.checkRoundtrip(t) class TestInterfaceCmp(unittest.TestCase): def test_unresolvedName(self): """ Test comparison function on xpt.Interface by name. """ i1 = xpt.Interface("ABC") i2 = xpt.Interface("DEF") self.assert_(i1 < i2) self.assert_(i1 != i2) def test_unresolvedEqual(self): """ Test comparison function on xpt.Interface with equal names and IIDs. """ i1 = xpt.Interface("ABC") i2 = xpt.Interface("ABC") self.assert_(i1 == i2) def test_unresolvedIID(self): """ Test comparison function on xpt.Interface with different IIDs. """ # IIDs sort before names i1 = xpt.Interface("ABC", iid="22334411-5566-7788-9900-aabbccddeeff") i2 = xpt.Interface("DEF", iid="11223344-5566-7788-9900-aabbccddeeff") self.assert_(i2 < i1) self.assert_(i2 != i1) def test_unresolvedResolved(self): """ Test comparison function on xpt.Interface with interfaces with identical names and IIDs but different resolved status. """ i1 = xpt.Interface("ABC", iid="11223344-5566-7788-9900-aabbccddeeff") p = xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)) m = xpt.Method("Bar", p) i2 = xpt.Interface("ABC", iid="11223344-5566-7788-9900-aabbccddeeff", methods=[m]) self.assert_(i2 < i1) self.assert_(i2 != i1) def test_resolvedIdentical(self): """ Test comparison function on xpt.Interface with interfaces with identical names and IIDs, both of which are resolved. """ p = xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)) m = xpt.Method("Bar", p) i1 = xpt.Interface("ABC", iid="11223344-5566-7788-9900-aabbccddeeff", methods=[m]) i2 = xpt.Interface("ABC", iid="11223344-5566-7788-9900-aabbccddeeff", methods=[m]) self.assert_(i2 == i1) class TestXPTLink(unittest.TestCase): def test_mergeDifferent(self): """ Test that merging two typelibs with completely different interfaces produces the correctly merged typelib. """ t1 = xpt.Typelib() # add an unresolved interface t1.interfaces.append(xpt.Interface("IFoo")) t2 = xpt.Typelib() # add an unresolved interface t2.interfaces.append(xpt.Interface("IBar")) t3 = xpt.xpt_link([t1, t2]) self.assertEqual(2, len(t3.interfaces)) # Interfaces should wind up sorted self.assertEqual("IBar", t3.interfaces[0].name) self.assertEqual("IFoo", t3.interfaces[1].name) # Add some IID values t1 = xpt.Typelib() # add an unresolved interface t1.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff")) t2 = xpt.Typelib() # add an unresolved interface t2.interfaces.append(xpt.Interface("IBar", iid="44332211-6655-8877-0099-aabbccddeeff")) t3 =
= np.log(astroA.res_d['area']) times = astroA.res_d['time_s'] r, p = stat_utils.get_pearsonr(times, areas) df = pd.DataFrame({'Size': areas, 'Time': times}) title ='Size vs Time correlation plot' text = 'r = {}, p < {}'.format(general_utils.truncate(r, 2), p) for kind in ['reg', 'hex', 'kde']: plotly_utils.seaborn_joint_grid(df, 'Size', 'Time', kind=kind, text=text) plt.savefig(os.path.join(path, '{}.svg'.format(kind))) plt.savefig(os.path.join(path, '{}.png'.format(kind))) ''' ''' print('Split BEHAVIOUR GRIDS...') n_chunks = 3 for bh in ['default', 'running', 'rest']: event_grid_splits = aqua_utils.split_n_event_grids(astroA, bh=bh, n=n_chunks) path = os.path.join(output_experiment_path, 'plots', 'split_behaviour_grids') for i, event_grid_split in enumerate(event_grid_splits): plot = plotly_utils.plot_contour(event_grid_split, title='{}-split {}/{}'.format(bh, i+1, len(event_grid_splits))) saving_utils.save_plotly_fig(plot, os.path.join(path, 'bh_{}-split_{}-chunks_{}'.format(bh,i,n_chunks))) ''' ''' print('HEATMAPS V2_2... (each astro day scaled with random)') for dff_mode in ['False']: #for bh in ['default', 'running', 'rest', 'stick_run_ind_15', 'stick_rest']: for bh in ['default']: print('THIS REPETITION LOOP MUST BE ONCE') path = os.path.join(output_experiment_path, 'plots', 'behaviour_heatmaps_threshold_with_random') d = self.get_individual_heatmaps_threshold_scaled(astroA, bh=bh, threshold=0.7, num_samples=3, dff_mode=dff_mode) if d is None: continue saving_utils.save_plotly_fig(d['contour'], os.path.join(path, 'bh_{}-dff_{}'.format(bh, dff_mode))) for i, contour_random in enumerate(d['contour_random']): saving_utils.save_plotly_fig(contour_random, os.path.join(path, 'bh_{}-dff_{}-random_{}'.format(bh, dff_mode, i))) ''' ''' #Every 60 seconds, whole vid with_donwsample = True downsample_length = int(astroA.fr * 60) second_length = astroA.fr bh_l = ['default', 'rest', 'running'] end_t = -1 start_t = 0 for bh in bh_l: save_base_path = os.path.join(output_experiment_path, 'plots', 'video_plots-{}-d{}-e{}'.format(bh, downsample_length, end_t)) try: os.makedirs(save_base_path) except: print('Folder exists') self.make_event_appended_video(astroA, bh=bh, start_t=start_t, end_t=end_t, downsample_length=downsample_length, save_base_path=save_base_path) ''' ''' #Every 2 seconds, first 120 seconds with_donwsample = True downsample_length = int(astroA.fr * 2) end_t = int(1200 * astroA.fr) start_t = 0 second_length = astroA.fr #bh_l = ['default', 'rest', 'running'] bh_l = ['default', 'rest', 'running'] for bh in bh_l: save_base_path = os.path.join(output_experiment_path, 'plots', 'video_plots-{}-d{}-e{}'.format(bh, downsample_length, end_t)) try: os.makedirs(save_base_path) except: print('Folder exists') self.make_event_appended_video(astroA, bh=bh, start_t=start_t, end_t=end_t, downsample_length=downsample_length, save_base_path=save_base_path) ''' ''' bh_l = ['default', 'rest', 'running'] for bh in bh_l: end_t = int(120*astroA.fr) time_sorted_events_trunc = sorted((i for i,e in enumerate(astroA.res_d['tEnd']) if (e < frame_max))) save_base_path = os.path.join(output_experiment_path, 'plots', 'video_plots_precise-{}-d{}-e{}'.format(bh, downsample_length, end_t)) downsample_length = int(astroA.fr * 2) self.make_event_appended_video_precise(astroA, event_l=time_sorted_events_trunc, end_t=end_t, downsample_length=downsample_length, save_base_path=save_base_path) ''' ''' bh_l = ['rest', 'running'] for bh in bh_l: start_t = 0 end_t = int(1200 * astroA.fr) downsample_length = int(astroA.fr * 2) save_base_path = os.path.join(output_experiment_path, 'plots', 'video_plots_bh_frames-{}-d{}-e{}'.format(bh, downsample_length, end_t)) try: os.makedirs(save_base_path) except: print('Folder exists') self.make_event_appended_video_bh_frames(astroA, bh=bh, start_t=start_t, end_t=end_t, downsample_length=downsample_length, save_base_path=save_base_path) ''' def make_event_appended_video_bh_frames(self, astro, bh, start_t=0, end_t=-1, downsample_length=60, save_base_path=''): curr_indices = astro.indices_d[bh][start_t:end_t] if len(curr_indices) % downsample_length != 0: curr_indices_fix = curr_indices[:-(len(curr_indices) % downsample_length)] else: curr_indices_fix = curr_indices num_splits = len(curr_indices_fix) // downsample_length curr_indices_split = {i : curr_indices_fix[i*downsample_length:(i+1)*downsample_length] for i in range(num_splits)} curr_indices_split['default'] = astro.indices_d['default'] bh_event_subsets = aqua_utils.get_event_subsets(curr_indices_split, astro.res_d) x2d_all = np.zeros([astro.input_shape[0], astro.input_shape[1]]) for i in range(num_splits): print(i, '/', num_splits) x2d = aqua_utils.get_event_grid_from_x2D(astro.res_d['x2D'][bh_event_subsets[i]], (astro.input_shape[0], astro.input_shape[1])) x2d_all = x2d_all + x2d x2d_all_normalized = np.copy(x2d_all) / ((i+1) * (downsample_length)) * astro.minute_frames #Linearly rescale 0-1 x2d_all_normalized = (x2d_all_normalized - np.min(x2d_all_normalized)) / (np.max(x2d_all_normalized) - np.min(x2d_all_normalized)) fig = plotly_utils.plot_contour(x2d_all_normalized, title='', tick_x=[0.2, 0.4, 0.6, 0.8]) saving_utils.save_plotly_fig(fig, os.path.join(save_base_path, '{:05d}'.format(i)), save_svg=False) def make_event_appended_video(self, astro, bh='default', start_t=0, end_t=-1, downsample_length=60, save_base_path=''): # Create array of (end_t - start_t) values consisting of event indices (lists) inside each frame #Time sorted events [[time, event_id], ..] sorted by time with_downsample = False if downsample_length == 1 else True if end_t == -1: end_t = astro.total_indices time_sorted_events = deque(sorted((e,i) for i,e in enumerate(astro.res_d['tBegin'][astro.event_subsets[bh]]))) #Populate events over time: for each frame we have a list of event indices starting then events_ot_l = [] for t in range(start_t, end_t): events_ot_l.append([]) #As long as first element has same time, we pop to add to our list while(len(time_sorted_events) != 0 and t == time_sorted_events[0][0]): events_ot_l[t].append(time_sorted_events.popleft()[1]) ################################################################# #Downsample if with_downsample: new_events_ot_l = general_utils.merge_l_l(events_ot_l, downsample_length) else: # copy it, not really need to new_events_ot_l = [ev for ev in events_ot_l] # Generate plots over time x2d_all = np.zeros([astro.input_shape[0], astro.input_shape[1]]) for i, segment_events_l in enumerate(new_events_ot_l): x2d = aqua_utils.get_event_grid_from_x2D(astro.res_d['x2D'][segment_events_l], (astro.input_shape[0], astro.input_shape[1])) x2d_all = x2d_all + x2d #Normalize x2d_all_normalized = np.copy(x2d_all) / ((i+1) * (downsample_length if with_downsample else 1)) * astro.minute_frames #Linearly rescale 0-1 x2d_all_normalized = (x2d_all_normalized - np.min(x2d_all_normalized)) / (np.max(x2d_all_normalized) - np.min(x2d_all_normalized)) fig = plotly_utils.plot_contour(x2d_all_normalized, title='', tick_x=[0.2, 0.4, 0.6, 0.8]) saving_utils.save_plotly_fig(fig, os.path.join(save_base_path, '{:05d}'.format(i)), save_svg=False) #Pass event list to choose which events. E.g. events in first 2 minutes #Slow but potentially prettier method. You can see each individual event its duration def make_event_appended_video_precise(self, astro_curr, event_l, end_t, downsample_length, save_base_path): dim_1 = astro_curr.input_shape[0] dim_2 = astro_curr.input_shape[1] #dim_3 = np.sum([x[2] for x in astro_curr.input_shape_l]) dim_3 = end_t a = np.zeros([dim_1, dim_2, dim_3]) for i, event in enumerate(astro_curr.res_d['x3D'][event_l]): print(i) unraveled = np.unravel_index(event, [dim_1, dim_2, dim_3], order='F') begin_time = np.min(unraveled[2]) end_time = np.max(unraveled[2]) added_arr = np.zeros([dim_1, dim_2]) for u_i in range(len(unraveled[0])): c_0 = unraveled[0][u_i] c_1 = unraveled[1][u_i] t = unraveled[2][u_i] #print('begin {} end {}'.format(begin_time, end_time)) if added_arr[c_0, c_1] == 1: continue a[c_0, c_1, t:] += 1 added_arr[c_0, c_1] = 1 return a for i in range(a_3d.shape[2] // (downsample_length if with_downsample else 1)): print(i) x2d = np.sum(a_3d[:, :, i*downsample_length:(i+1)*downsample_length], axis=2) #Normalize x2d_all_normalized = np.copy(x2d) / ((i+1) * (downsample_length if with_downsample else 1)) * astro_curr.minute_frames #Linearly rescale 0-1 x2d_all_normalized = (x2d_all_normalized - np.min(x2d_all_normalized)) / (np.max(x2d_all_normalized) - np.min(x2d_all_normalized)) fig = plotly_utils.plot_contour(x2d_all_normalized, title='', tick_x=[0.2, 0.4, 0.6, 0.8]) saving_utils.save_plotly_fig(fig, os.path.join(save_base_path, '{:05d}'.format(i)), save_svg=False) #--------#--------#--------#--------#--------#--------#--------#--------#--------#-------- #Experiment_id/days def plot_comparisons(self, astroA_l): output_experiment_path_comparison, days_str, day_l_s, astroA_l_s = self.setup_comparison_vars(astroA_l, self.output_folder) print(output_experiment_path_comparison) #Setup folders self.setup_plot_folders_comparison(output_experiment_path_comparison) ''' #Behaviour contour plots compare for k in astroA_l[0].event_subsets.keys(): try: event_grids_l = [astroA.event_grids_compare[k] for astroA in astroA_l] fig_k = plotly_utils.plot_contour_multiple(event_grids_l, title=k + '_event grid comparison_' + days_str, height=500, width=600*len(astroA_l)) saving_utils.save_plotly_fig(fig_k , os.path.join(output_experiment_path_comparison, 'plots', 'behaviour_heatmaps', k), height=500, width=600*len(astroA_l)) except: continue for k in astroA_l[0].event_subsets.keys(): try: event_grids_dff_l = [astroA.event_grids_compare_dff[k] for astroA in astroA_l] fig_k = plotly_utils.plot_contour_multiple(event_grids_dff_l, title=k + '_event grid dff comparison_' + days_str, height=500, width=600*len(astroA_l)) saving_utils.save_plotly_fig(fig_k , os.path.join(output_experiment_path_comparison, 'plots', 'behaviour_heatmaps', k + '-dff'), height=500, width=600*len(astroA_l)) except: continue ''' ''' name = '{}-{}'.format(astroA_l[0].day, astroA_l[1].day) behaviour_l = ['default', 'running', 'rest'] p_l = [0.05, 0.1, 0.25] dff_mode_l = [False, True] for behaviour in behaviour_l: for dff_mode in dff_mode_l: for p in p_l: same_spots_prob, astro_filt_l, astro_all_filt, astro_nz_bool_l, astro_all_nz_bool = compare_astro_utils.get_astro_pair_same_spots_prob([astroA_l[0], astroA_l[1]], p=0.05, dff_mode=True) print('Plotting intersections...') top_five_perc_path = os.path.join(output_experiment_path_comparison, 'plots', 'intersection', name + 'bh_{}-dff_{}-top_{}'.format(behaviour, dff_mode, p)) nz_border_path = os.path.join(output_experiment_path_comparison, 'plots', 'intersection', name + 'nz_border') fig_perc = plotly_utils.plot_contour_multiple([astro_filt_l[0], astro_filt_l[1], astro_all_filt], subplot_titles=['top 5% values day {}'.format(astroA_l[0].day), 'top 5% values day {}'.format(astroA_l[1].day), 'intersection'], title='Probability to occur randomly {:.2e}'.format(same_spots_prob), color_bar_title='', line_width=0.1, font_size_individual=40, scale_equal=False) fig_bord = plotly_utils.plot_contour_multiple([astro_nz_bool_l[0].astype(int), astro_nz_bool_l[1].astype(int), astro_all_nz_bool.astype(int)], subplot_titles=['non-0 values day {}'.format(astroA_l[0].day), 'non-0 values day {}'.format(astroA_l[1].day), 'intersection'], title='Event activity borders', color_bar_title='', line_width=0.1, font_size_individual=40, scale_equal=False) saving_utils.save_plotly_fig(fig_perc, top_five_perc_path, width=2000, height=1000) saving_utils.save_plotly_fig(fig_bord, nz_border_path, width=2000, height=1000) ''' ''' behaviour_l = ['default', 'running', 'rest'] dff_mode_l = [False, True] p_l = [0.05, 0.10, 0.25] for behaviour in behaviour_l: print('Plotting intersections after alignment...') #move_vector = compare_astro_utils.get_move_vector_xcorr_default(astroA_l[0], astroA_l[1]) move_vector = [0, 0] #p_l = [0.05, 0.1, 0.25] for dff_mode in dff_mode_l: for p in p_l: same_spots_prob, astro_filt_l, astro_all_filt, astro_nz_bool_l, astro_all_nz_bool = compare_astro_utils.get_astro_pair_same_spots_prob([astroA_l[0], astroA_l[1]], p=0.05, move_vector=move_vector, dff_mode=True) print('Plotting intersections...') top_perc_path = os.path.join(output_experiment_path_comparison, 'plots', 'intersection_border_xcorr_aligned', name + 'bh_{}-dff_{}-top_{}'.format(behaviour, dff_mode, p)) fig_perc = plotly_utils.plot_contour_multiple([astro_filt_l[0], astro_filt_l[1], astro_all_filt], subplot_titles=['top 5% values day {}'.format(astroA_l[0].day), 'top 5% values day {}'.format(astroA_l[1].day), 'intersection'], title='Probability to occur randomly {:.2e}'.format(same_spots_prob), color_bar_title='', line_width=0.1, font_size_individual=40, scale_equal=False) saving_utils.save_plotly_fig(fig_perc, top_perc_path, width=2000, height=1000) ''' ''' print('Plotting correlations compare...') figs_compare_corrs = self.get_compare_max_corrs_plots(astroA_l) for pk in figs_compare_corrs.keys(): figs_compare_corrs_path = os.path.join(output_experiment_path_comparison, 'plots', 'correlations', 'max_correlations_compare_p={}'.format(pk)) saving_utils.save_plotly_fig(figs_compare_corrs[pk], figs_compare_corrs_path) print('Plotting compare alignments intersection sizes...') figs_compare_align = self.get_compare_align_plots(astroA_l) for setting in figs_compare_align.keys(): for pk in figs_compare_align[setting].keys(): figs_compare_align_path = os.path.join(output_experiment_path_comparison, 'plots', 'align', 'align_compare_s={}_p={}'.format(setting, pk)) saving_utils.save_plotly_fig(figs_compare_align[setting][pk], figs_compare_align_path) for behaviour in self.behaviours_list_small: if (behaviour in astroA_l[0].indices_d) and (behaviour in astroA_l[1].indices_d): print('Plotting compare alignments xcorr full... (Aligning borders then taking xcorr value of the 2 astrocytes. Then compare to random astrocyte plots)') figs_compare_align_xcorr = self.get_compare_align_plots_xcorr(astroA_l, align_setting='xcorr', dff_mode=False, behaviour=behaviour) figs_compare_align_xcorr_path = os.path.join(output_experiment_path_comparison, 'plots', 'align', 'align_compare_xcorr_values_full_{}'.format(behaviour)) saving_utils.save_plotly_fig(figs_compare_align_xcorr, figs_compare_align_xcorr_path) print('Plotting compare alignments dff xcorr full... (Aligning borders then taking xcorr value of the 2 astrocytes. Then compare to random astrocyte plots)') figs_compare_align_xcorr_dff = self.get_compare_align_plots_xcorr(astroA_l, align_setting='xcorr', dff_mode=True, behaviour=behaviour) figs_compare_align_xcorr_dff_path = os.path.join(output_experiment_path_comparison, 'plots', 'align', 'align_compare_xcorr_values_full_dff_{}'.format(behaviour)) saving_utils.save_plotly_fig(figs_compare_align_xcorr_dff, figs_compare_align_xcorr_dff_path) else: print('Behaviour {} not existent in astro'.format(behaviour)) print('Plotting sample for comparison') #Make contour plot of astro1, astro2, sample_1, sample_2, sample_3 figs_compare_samples = self.get_compare_corrs_samples_plots(astroA_l) for pk in figs_compare_samples.keys(): for s in figs_compare_samples[pk].keys(): path_s = os.path.join(output_experiment_path_comparison, 'plots', 'correlations', '{}_p={}'.format(s, pk)) saving_utils.save_plotly_fig(figs_compare_samples[pk][s], path_s) behaviour_corr_path = os.path.join(output_experiment_path_comparison, 'plots', 'correlations', 'behaviour_corr') fig_behaviour_corr =
as an empty list all_tags = [] if bool(use_tag_labels): # if use_tag_labels is 1, append the tags to all_tags list all_tags.extend([tag + "_tag" for tag in Dataset.tags]) if bool(use_malicious_labels): # if use_malicious_labels is 1, append malware label to all_tags list all_tags.append("malware") # crete temporary directory with tempfile.TemporaryDirectory() as tempdir: # for each tag in all_tags list, compute scores for tag in all_tags: output_filename = os.path.join(tempdir, tag + "_scores.csv") compute_scores(results_file=results_file, key=tag, dest_file=output_filename, zero_division=zero_division) # log output file as artifact mlflow.log_artifact(output_filename, "model_scores") def compute_run_mean_scores(results_file, # path to results.csv containing the output of a model run use_malicious_labels=1, # whether or not to compute malware/benignware label scores use_tag_labels=1, # whether or not to compute the tag label scores zero_division=1.0): # sets the value to return when there is a zero division """ Estimate some mean, per-sample, scores (jaccard similarity and mean per-sample accuracy) for a dataframe at specific False Positive Rates of interest. Args: results_file: Path to results.csv containing the output of a model run use_malicious_labels: Whether or not (1/0) to compute malware/benignware label scores (default: 1) use_tag_labels: Whether or not (1/0) to compute the tag label scores (default: 1) zero_division: Sets the value to return when there is a zero division. If set to “warn”, this acts as 0, but warnings are also raised (default: 1.0) """ # if use_tag_labels is set to 0, the mean scores cannot be computed -> return if not bool(use_tag_labels): logger.warning('"use_tag_labels" is set to 0 (false).' 'Jaccard score is not available outside of multi-label classification. Returning..') return # initialize all_tags as a list containing all tags all_tags = [tag + "_tag" for tag in Dataset.tags] # create run ID - filename correspondence dictionary (containing just one result file) id_to_resultfile_dict = {'run': results_file} # read csv result file and obtain a run ID - result dataframe dictionary id_to_dataframe_dict = collect_dataframes(id_to_resultfile_dict) # get labels, target fprs and predictions from current run results dataframe labels, target_fprs, predictions = get_all_predictions(id_to_dataframe_dict['run'], keys=all_tags) # compute jaccard scores at each target fpr jaccard_scores = np.asarray([jaccard_score(labels, predictions[i], average='samples', zero_division=zero_division) for i, fpr in enumerate(target_fprs)]) # compute accuracy scores at each target fpr accuracy_scores = np.asarray([accuracy_score(labels, predictions[i]) for i, fpr in enumerate(target_fprs)]) # create scores dataframe scores_df = pd.DataFrame({'fpr': target_fprs, 'mean jaccard similarity': jaccard_scores, 'mean per-sample accuracy': accuracy_scores}, index=list(range(1, len(target_fprs) + 1))) # create temporary directory with tempfile.TemporaryDirectory() as tempdir: output_filename = os.path.join(tempdir, "mean_per_sample_scores.csv") # open output file at the specified location with open(output_filename, "w") as output_file: # serialize scores_df dictionary as a json object and save it to file scores_df.to_csv(output_file) # log output file as artifact mlflow.log_artifact(output_filename, "model_mean_scores") def plot_run_results(results_file, # path to results.csv containing the output of a model run use_malicious_labels=1, # whether or not (1/0) to compute malware/benignware label scores use_tag_labels=1): # whether or not (1/0) to compute the tag label scores """ Takes a result file from a feedforward neural network model that includes all tags, and produces multiple overlaid ROC plots for each tag individually. Args: results_file: Path to results.csv containing the output of a model run use_malicious_labels: Whether or not (1/0) to compute malware/benignware label scores (default: 1) use_tag_labels: Whether or not (1/0) to compute the tag label scores (default: 1) """ # check use_malicious_labels and use_tag_labels, at least one of them should be 1, otherwise the tag # results cannot be calulated -> return if not bool(use_malicious_labels) and not bool(use_tag_labels): logger.warning('Both "use_malicious_labels" and "use_tag_labels" are set to 0 (false). Returning..') return # initialize all_tags as an empty list all_tags = [] if bool(use_tag_labels): # if use_tag_labels is 1, append the tags to all_tags list all_tags.extend([tag + "_tag" for tag in Dataset.tags]) if bool(use_malicious_labels): # if use_malicious_labels is 1, append malware label to all_tags list all_tags.append("malware") # create run ID - filename correspondence dictionary (containing just one result file) id_to_resultfile_dict = {'run': results_file} # read csv result file and obtain a run ID - result dataframe dictionary id_to_dataframe_dict = collect_dataframes(id_to_resultfile_dict) # create temporary directory with tempfile.TemporaryDirectory() as tempdir: output_filename = os.path.join(tempdir, "results.png") # produce multiple overlaid ROC plots (one for each tag individually) and save the overall figure to file plot_tag_results(id_to_dataframe_dict['run'], output_filename, tags=all_tags) # log output file as artifact mlflow.log_artifact(output_filename, "model_results") def plot_mean_results(run_to_filename_json, # A json file that contains a key-value map that links run # IDs to the full path to a results file (including the file name) all_tags): # list of all tags to plot results of """ Computes the mean of the TPR at a range of FPRS (the ROC curve) over several sets of results (at least 2 runs) for all tags (provided) and produces multiple overlaid ROC plots for each tag individually. The run_to_filename_json file must have the following format: {"run_id_0": "/full/path/to/results.csv/for/run/0/results.csv", "run_id_1": "/full/path/to/results.csv/for/run/1/results.csv", ... } Args: run_to_filename_json: A json file that contains a key-value map that links run IDs to the full path to a results file (including the file name) all_tags: List of all tags to plot results of """ # open json containing run ID - filename correspondences and decode it as json object id_to_resultfile_dict = json.load(open(run_to_filename_json, 'r')) # read csv result files and obtain a run ID - result dataframe dictionary id_to_dataframe_dict = collect_dataframes(id_to_resultfile_dict) # create temporary directory with tempfile.TemporaryDirectory() as tempdir: output_filename = os.path.join(tempdir, "all_mean_results.png") # produce multiple overlaid ROC plots (one for each tag individually) and save the overall figure to file plot_tag_mean_results(id_to_dataframe_dict, output_filename, tags=all_tags) # log output file as artifact mlflow.log_artifact(output_filename, "model_results") def plot_single_roc_distribution(run_to_filename_json, # A json file that contains a key-value map that links run # IDs to the full path to a results file (including the file name) tag_to_plot='malware', # the tag from the results to plot linestyle=None, # the linestyle to use in the plot (if None use some defaults) color=None, # the color to use in the plot (if None use some defaults) include_range=False, # plot the min/max value as well std_alpha=.2, # the alpha value for the shading for standard deviation range range_alpha=.1): # the alpha value for the shading for range, if plotted """ Compute the mean and standard deviation of the TPR at a range of FPRS (the ROC curve) over several sets of results (at least 2 runs) for a given tag. The run_to_filename_json file must have the following format: {"run_id_0": "/full/path/to/results.csv/for/run/0/results.csv", "run_id_1": "/full/path/to/results.csv/for/run/1/results.csv", ... } Args: run_to_filename_json: A json file that contains a key-value map that links run IDs to the full path to a results file (including the file name) tag_to_plot: The tag from the results to plot (default: "malware") linestyle: The linestyle to use in the plot (defaults to the tag value in plot.style_dict) color: The color to use in the plot (defaults to the tag value in plot.style_dict) include_range: Plot the min/max value as well (default False) std_alpha: The alpha value for the shading for standard deviation range (default .2) range_alpha: The alpha value for the shading for range, if plotted (default .1) """ # open json containing run ID - filename correspondences and decode it as json object id_to_resultfile_dict = json.load(open(run_to_filename_json, 'r')) # read csv result files and obtain a run ID - result dataframe dictionary id_to_dataframe_dict = collect_dataframes(id_to_resultfile_dict) if color is None or linestyle is None: # if either color or linestyle is None if not (color is None and linestyle is None): # if just one of them is None raise ValueError("both color and linestyle should either be specified or None") # raise an exception # otherwise select default style style = style_dict[tag_to_plot] else: # otherwise (both color and linestyle were specified) define the style as a tuple of color and linestyle style = (color, linestyle) with tempfile.TemporaryDirectory() as tempdir: output_filename = os.path.join(tempdir, tag_to_plot + "_results.png") # plot roc curve with confidence plot_roc_with_confidence(id_to_dataframe_dict, tag_to_plot, output_filename, include_range=include_range, style=style, std_alpha=std_alpha, range_alpha=range_alpha) # log output file as artifact mlflow.log_artifact(output_filename, "model_results") @baker.command def compute_all_run_results(results_file, # path to results.csv containing the output of a model
import os import yaml import zipfile import lmctl.files as files import lmctl.project.handlers.interface as handlers_api import lmctl.project.validation as project_validation import lmctl.utils.descriptors as descriptor_utils from .brent_content import BrentResourcePackageContentTree, BrentPkgContentTree class OpenstackTemplatesTree(files.Tree): def gen_tosca_template(self, file_name): return self.resolve_relative_path('{0}.yaml'.format(file_name)) OPENSTACK_EXAMPLE_TOSCA = '''\ heat_template_version: 2013-05-23 description: > Basic example to deploy a single VM parameters: key_name: type: string default: helloworld image: type: string default: xenial-server-cloudimg-amd64-disk1 resources: hello_world_server: type: OS::Nova::Server properties: flavor: ds2G user_data_format: SOFTWARE_CONFIG image: get_param: image key_name: get_param: key_name networks: - port: { get_resource: hello_world_server_port } hello_world_server_port: type: OS::Neutron::Port properties: network: private outputs: hello_world_private_ip: value: get_attr: - hello_world_server - networks - private - 0 description: The private IP address of the hello_world_server ''' class AnsibleLifecycleTree(files.Tree): CONFIG_DIR_NAME = 'config' SCRIPTS_DIR_NAME = 'scripts' CONFIG_INVENTORY_FILE_NAME = 'inventory' CONFIG_HOSTVARS_DIR_NAME = 'host_vars' @property def scripts_path(self): return self.resolve_relative_path(AnsibleLifecycleTree.SCRIPTS_DIR_NAME) def gen_script_file_path(self, lifecycle_name): return self.resolve_relative_path(AnsibleLifecycleTree.SCRIPTS_DIR_NAME, '{0}.yaml'.format(lifecycle_name)) @property def config_path(self): return self.resolve_relative_path(AnsibleLifecycleTree.CONFIG_DIR_NAME) @property def inventory_file_path(self): return self.resolve_relative_path(AnsibleLifecycleTree.CONFIG_DIR_NAME, AnsibleLifecycleTree.CONFIG_INVENTORY_FILE_NAME) @property def hostvars_path(self): return self.resolve_relative_path(AnsibleLifecycleTree.CONFIG_DIR_NAME, AnsibleLifecycleTree.CONFIG_HOSTVARS_DIR_NAME) def gen_hostvars_file_path(self, host_name): return self.resolve_relative_path(AnsibleLifecycleTree.CONFIG_DIR_NAME, AnsibleLifecycleTree.CONFIG_HOSTVARS_DIR_NAME, '{0}.yml'.format(host_name)) class Sol003LifecycleTree(files.Tree): SCRIPTS_DIR_NAME = 'scripts' CREATE_VNF_REQUEST_FILE_NAME = 'CreateVnfRequest.js' HEAL_VNF_REQUEST_FILE_NAME = 'HealVnfRequest.js' INSTANTIATE_VNF_REQUEST_FILE_NAME = 'InstantiateVnfRequest.js' OPERATE_VNF_REQUEST_START_FILE_NAME = 'OperateVnfRequest-Start.js' OPERATE_VNF_REQUEST_STOP_FILE_NAME = 'OperateVnfRequest-Stop.js' SCALE_VNF_REQUEST_FILE_NAME = 'ScaleVnfRequest.js' TERMINATE_VNF_REQUEST_FILE_NAME = 'TerminateVnfRequest.js' VNF_INSTANCE_FILE_NAME = 'VnfInstance.js' @property def scripts_path(self): return self.resolve_relative_path(Sol003LifecycleTree.SCRIPTS_DIR_NAME) class BrentSourceTree(files.Tree): DEFINITIONS_DIR_NAME = 'Definitions' INFRASTRUCTURE_DIR_NAME = 'infrastructure' INFRASTRUCTURE_MANIFEST_FILE_NAME = 'infrastructure.mf' LM_DIR_NAME = 'lm' DESCRIPTOR_FILE_NAME_YML = 'resource.yml' DESCRIPTOR_FILE_NAME_YAML = 'resource.yaml' LIFECYCLE_DIR_NAME = 'Lifecycle' LIFECYCLE_MANIFEST_FILE_NAME = 'lifecycle.mf' ANSIBLE_LIFECYCLE_DIR_NAME = 'ansible' SOL003_LIFECYCLE_DIR_NAME = 'sol003' @property def definitions_path(self): return self.resolve_relative_path(BrentSourceTree.DEFINITIONS_DIR_NAME) @property def infrastructure_definitions_path(self): return self.resolve_relative_path(BrentSourceTree.DEFINITIONS_DIR_NAME, BrentSourceTree.INFRASTRUCTURE_DIR_NAME) @property def infrastructure_manifest_file_path(self): return self.resolve_relative_path(BrentSourceTree.DEFINITIONS_DIR_NAME, BrentSourceTree.INFRASTRUCTURE_DIR_NAME, BrentSourceTree.INFRASTRUCTURE_MANIFEST_FILE_NAME) @property def lm_definitions_path(self): return self.resolve_relative_path(BrentSourceTree.DEFINITIONS_DIR_NAME, BrentSourceTree.LM_DIR_NAME) @property def descriptor_file_path(self): yaml_path = self.resolve_relative_path(BrentSourceTree.DEFINITIONS_DIR_NAME, BrentSourceTree.LM_DIR_NAME, BrentSourceTree.DESCRIPTOR_FILE_NAME_YAML) yml_path = self.resolve_relative_path(BrentSourceTree.DEFINITIONS_DIR_NAME, BrentSourceTree.LM_DIR_NAME, BrentSourceTree.DESCRIPTOR_FILE_NAME_YML) if os.path.exists(yml_path): if os.path.exists(yaml_path): raise handlers_api.InvalidSourceError('Project has both a {0} file and a {1} file when there should only be one'.format( BrentSourceTree.DESCRIPTOR_FILE_NAME_YAML, BrentSourceTree.DESCRIPTOR_FILE_NAME_YML)) return yml_path else: return yaml_path @property def lifecycle_path(self): return self.resolve_relative_path(BrentSourceTree.LIFECYCLE_DIR_NAME) @property def lifecycle_manifest_file_path(self): return self.resolve_relative_path(BrentSourceTree.LIFECYCLE_DIR_NAME, BrentSourceTree.LIFECYCLE_MANIFEST_FILE_NAME) @property def ansible_lifecycle_path(self): return self.resolve_relative_path(BrentSourceTree.LIFECYCLE_DIR_NAME, BrentSourceTree.ANSIBLE_LIFECYCLE_DIR_NAME) @property def sol003_lifecycle_path(self): return self.resolve_relative_path(BrentSourceTree.LIFECYCLE_DIR_NAME, BrentSourceTree.SOL003_LIFECYCLE_DIR_NAME) INFRASTRUCTURE_PARAM_NAME = 'inf' LIFECYCLE_PARAM_NAME = 'lifecycle' LIFECYCLE_TYPE_ANSIBLE = 'ansible' LIFECYCLE_TYPE_SOL003 = 'sol003' INFRASTRUCTURE_TYPE_OPENSTACK = 'openstack' SOL003_SCRIPT_NAMES = [] SOL003_SCRIPT_NAMES.append(Sol003LifecycleTree.CREATE_VNF_REQUEST_FILE_NAME) SOL003_SCRIPT_NAMES.append(Sol003LifecycleTree.HEAL_VNF_REQUEST_FILE_NAME) SOL003_SCRIPT_NAMES.append(Sol003LifecycleTree.INSTANTIATE_VNF_REQUEST_FILE_NAME) SOL003_SCRIPT_NAMES.append(Sol003LifecycleTree.OPERATE_VNF_REQUEST_START_FILE_NAME) SOL003_SCRIPT_NAMES.append(Sol003LifecycleTree.OPERATE_VNF_REQUEST_STOP_FILE_NAME) SOL003_SCRIPT_NAMES.append(Sol003LifecycleTree.SCALE_VNF_REQUEST_FILE_NAME) SOL003_SCRIPT_NAMES.append(Sol003LifecycleTree.TERMINATE_VNF_REQUEST_FILE_NAME) SOL003_SCRIPT_NAMES.append(Sol003LifecycleTree.VNF_INSTANCE_FILE_NAME) class BrentSourceCreatorDelegate(handlers_api.ResourceSourceCreatorDelegate): def __init__(self): super().__init__() def get_params(self, source_request): params = [] params.append(handlers_api.SourceParam(LIFECYCLE_PARAM_NAME, required=False, default_value=LIFECYCLE_TYPE_ANSIBLE, allowed_values=[LIFECYCLE_TYPE_ANSIBLE, LIFECYCLE_TYPE_SOL003])) params.append(handlers_api.SourceParam(INFRASTRUCTURE_PARAM_NAME, required=False, default_value=INFRASTRUCTURE_TYPE_OPENSTACK, allowed_values=[INFRASTRUCTURE_TYPE_OPENSTACK])) return params def create_source(self, journal, source_request, file_ops_executor): source_tree = BrentSourceTree() file_ops = [] descriptor = descriptor_utils.Descriptor({}, is_2_dot_1=True) descriptor.description = 'descriptor for {0}'.format(source_request.source_config.name) file_ops.append(handlers_api.CreateDirectoryOp(source_tree.definitions_path, handlers_api.EXISTING_IGNORE)) inf_type = source_request.param_values.get_value(INFRASTRUCTURE_PARAM_NAME) self.__create_infrastructure(journal, source_request, file_ops, source_tree, inf_type, descriptor) lifecycle_type = source_request.param_values.get_value(LIFECYCLE_PARAM_NAME) self.__create_lifecycle(journal, source_request, file_ops, source_tree, lifecycle_type, descriptor) self.__create_descriptor(journal, source_request, file_ops, source_tree, descriptor) file_ops_executor(file_ops) def __create_descriptor(self, journal, source_request, file_ops, source_tree, descriptor): file_ops.append(handlers_api.CreateDirectoryOp(source_tree.lm_definitions_path, handlers_api.EXISTING_IGNORE)) descriptor_content = descriptor_utils.DescriptorParser().write_to_str(descriptor) file_ops.append(handlers_api.CreateFileOp(source_tree.descriptor_file_path, descriptor_content, handlers_api.EXISTING_IGNORE)) def __create_infrastructure(self, journal, source_request, file_ops, source_tree, inf_type, descriptor): file_ops.append(handlers_api.CreateDirectoryOp(source_tree.infrastructure_definitions_path, handlers_api.EXISTING_IGNORE)) if inf_type == INFRASTRUCTURE_TYPE_OPENSTACK: descriptor.insert_lifecycle('Create') descriptor.insert_lifecycle('Delete') templates_tree = OpenstackTemplatesTree(source_tree.infrastructure_definitions_path) file_ops.append(handlers_api.CreateFileOp(templates_tree.gen_tosca_template('example'), OPENSTACK_EXAMPLE_TOSCA, handlers_api.EXISTING_IGNORE)) descriptor.insert_infrastructure_template('Openstack', 'example.yaml', template_type='HEAT') def __create_lifecycle(self, journal, source_request, file_ops, source_tree, lifecycle_type, descriptor): file_ops.append(handlers_api.CreateDirectoryOp(source_tree.lifecycle_path, handlers_api.EXISTING_IGNORE)) if lifecycle_type == LIFECYCLE_TYPE_ANSIBLE: file_ops.append(handlers_api.CreateDirectoryOp(source_tree.ansible_lifecycle_path, handlers_api.EXISTING_IGNORE)) ansible_tree = AnsibleLifecycleTree(source_tree.ansible_lifecycle_path) file_ops.append(handlers_api.CreateDirectoryOp(ansible_tree.config_path, handlers_api.EXISTING_IGNORE)) file_ops.append(handlers_api.CreateDirectoryOp(ansible_tree.hostvars_path, handlers_api.EXISTING_IGNORE)) file_ops.append(handlers_api.CreateDirectoryOp(ansible_tree.scripts_path, handlers_api.EXISTING_IGNORE)) install_content = '---\n- name: Install\n hosts: all\n gather_facts: False' file_ops.append(handlers_api.CreateFileOp(ansible_tree.gen_script_file_path('Install'), install_content, handlers_api.EXISTING_IGNORE)) descriptor.insert_lifecycle('Install') inventory_content = '[example]\nexample-host' file_ops.append(handlers_api.CreateFileOp(ansible_tree.inventory_file_path, inventory_content, handlers_api.EXISTING_IGNORE)) host_var_content = '---\nansible_host: {{ properties.host }}\nansible_ssh_user: {{ properties.ssh_user }}\nansible_ssh_pass: {{ properties.ssh_pass }}' file_ops.append(handlers_api.CreateFileOp(ansible_tree.gen_hostvars_file_path('example-host'), host_var_content, handlers_api.EXISTING_IGNORE)) descriptor.insert_default_driver('ansible', infrastructure_types=['*']) elif lifecycle_type == LIFECYCLE_TYPE_SOL003: file_ops.append(handlers_api.CreateDirectoryOp(source_tree.sol003_lifecycle_path, handlers_api.EXISTING_IGNORE)) sol003_tree = Sol003LifecycleTree(source_tree.sol003_lifecycle_path) file_ops.append(handlers_api.CreateDirectoryOp(sol003_tree.scripts_path, handlers_api.EXISTING_IGNORE)) current_path = os.path.abspath(__file__) dir_path = os.path.dirname(current_path) sol003_scripts_template_path = os.path.join(dir_path, 'sol003', 'scripts') for script_name in SOL003_SCRIPT_NAMES: orig_script_path = os.path.join(sol003_scripts_template_path, script_name) with open(orig_script_path, 'r') as f: content = f.read() file_ops.append(handlers_api.CreateFileOp(os.path.join(sol003_tree.scripts_path, script_name), content, handlers_api.EXISTING_IGNORE)) descriptor.insert_default_driver('sol003', infrastructure_types=['*']) descriptor.add_property('vnfdId', description='Identifier for the VNFD to use for this VNF instance', ptype='string', required=True) descriptor.add_property('vnfInstanceId', description='Identifier for the VNF instance, as provided by the vnfInstanceName', ptype='string', read_only=True) descriptor.add_property('vnfInstanceName', description='Name for the VNF instance', ptype='string', value='${name}') descriptor.add_property('vnfInstanceDescription', description='Optional description for the VNF instance', ptype='string') descriptor.add_property('vnfPkgId', description='Identifier for the VNF package to be used for this VNF instance', ptype='string', required=True) descriptor.add_property('vnfProvider', description='Provider of the VNF and VNFD', ptype='string', read_only=True) descriptor.add_property('vnfProductName', description='VNF Product Name', ptype='string', read_only=True) descriptor.add_property('vnfSoftwareVersion', description='VNF Software Version', ptype='string', read_only=True) descriptor.add_property('vnfdVersion', description='Version of the VNFD', ptype='string', read_only=True) descriptor.add_property('flavourId', description='Identifier of the VNF DF to be instantiated', ptype='string', required=True) descriptor.add_property('instantiationLevelId', description='Identifier of the instantiation level of the deployment flavour to be instantiated. If not present, the default instantiation level as declared in the VNFD is instantiated', \ ptype='string') descriptor.add_property('localizationLanguage', description='Localization language of the VNF to be instantiated', ptype='string') descriptor.insert_lifecycle('Install') descriptor.insert_lifecycle('Configure') descriptor.insert_lifecycle('Uninstall') class BrentSourceHandlerDelegate(handlers_api.ResourceSourceHandlerDelegate): def __init__(self, root_path, source_config): super().__init__(root_path, source_config) self.tree = BrentSourceTree(self.root_path) def validate_sources(self, journal, source_validator, validation_options): errors = [] warnings = [] self.__validate_definitions(journal, validation_options, errors, warnings) self.__validate_lifecycle(journal, validation_options, errors, warnings) return project_validation.ValidationResult(errors, warnings) def __find_or_error(self, journal, errors, warnings, path, artifact_type): if not os.path.exists(path): msg = 'No {0} found at: {1}'.format(artifact_type, path) journal.error_event(msg) errors.append(project_validation.ValidationViolation(msg)) return False else: journal.event('{0} found at: {1}'.format(artifact_type, path)) return True def __validate_definitions(self, journal, validation_options, errors, warnings): definitions_path = self.tree.definitions_path if self.__find_or_error(journal, errors, warnings, definitions_path, 'Definitions directory'): self.__validate_definitions_infrastructure(journal, validation_options, errors, warnings) self.__validate_definitions_lm(journal, errors, warnings) def __validate_definitions_infrastructure(self, journal, validation_options, errors, warnings): inf_path = self.tree.infrastructure_definitions_path if self.__find_or_error(journal, errors, warnings, inf_path, 'Infrastructure definitions directory'): self.__validate_unsupported_infrastructure_manifest(journal, validation_options, errors, warnings) def __validate_unsupported_infrastructure_manifest(self, journal, validation_options, errors, warnings): inf_manifest_path = self.tree.infrastructure_manifest_file_path if os.path.exists(inf_manifest_path): if validation_options.allow_autocorrect == True: journal.event('Found unsupported infrastructure manifest [{0}], attempting to autocorrect by moving contents to Resource descriptor'.format(inf_manifest_path)) managed_to_autocorrect = False autocorrect_error = None try: with open(inf_manifest_path, 'r') as f: inf_manifest_content = yaml.safe_load(f.read()) descriptor = descriptor_utils.DescriptorParser().read_from_file(self.get_main_descriptor()) descriptor.is_2_dot_1 = True if 'templates' in inf_manifest_content: for template_entry in inf_manifest_content['templates']: if 'infrastructure_type' in template_entry: infrastructure_type = template_entry['infrastructure_type'] template_file = template_entry.get('file', None) template_type = template_entry.get('template_type', None) descriptor.insert_infrastructure_template(infrastructure_type, template_file, template_type=template_type) if 'discover' in inf_manifest_content: for discover_entry in inf_manifest_content['discover']: if 'infrastructure_type' in discover_entry: infrastructure_type = discover_entry['infrastructure_type'] template_file = discover_entry.get('file', None) template_type = discover_entry.get('template_type', None) descriptor.insert_infrastructure_discover(infrastructure_type, template_file, template_type=template_type) descriptor_utils.DescriptorParser().write_to_file(descriptor, self.get_main_descriptor()) os.rename(inf_manifest_path, inf_manifest_path + '.bak') managed_to_autocorrect = True except Exception as e: autocorrect_error = e if not managed_to_autocorrect: msg = 'Found infrastructure manifest [{0}]: this file is no longer supported by the Brent Resource Manager. Unable to autocorrect this issue, please add this information to the Resource descriptor manually instead'.format(inf_manifest_path) if autocorrect_error is not None: msg += ' (autocorrect error={0})'.format(str(autocorrect_error)) journal.error_event(msg) errors.append(project_validation.ValidationViolation(msg)) return else: msg = 'Found infrastructure manifest [{0}]: this file is no longer supported by the Brent Resource Manager. Add this information to the Resource descriptor instead or enable the autocorrect option'.format(inf_manifest_path) journal.error_event(msg) errors.append(project_validation.ValidationViolation(msg)) return def __validate_definitions_lm(self, journal, errors, warnings): lm_def_path = self.tree.lm_definitions_path if self.__find_or_error(journal, errors, warnings, lm_def_path, 'LM definitions directory'): descriptor_file_path = self.tree.descriptor_file_path self.__find_or_error(journal, errors, warnings, descriptor_file_path, 'Resource descriptor') def __validate_lifecycle(self, journal, validation_options, errors, warnings): lifecycle_path = self.tree.lifecycle_path if self.__find_or_error(journal, errors, warnings, lifecycle_path, 'Lifecycle directory'): self.__validate_unsupported_lifecycle_manifest(journal, validation_options, errors, warnings) def __validate_unsupported_lifecycle_manifest(self, journal, validation_options, errors, warnings): lifecycle_manifest_path = self.tree.lifecycle_manifest_file_path if os.path.exists(lifecycle_manifest_path): if validation_options.allow_autocorrect == True: journal.event('Found unsupported lifecycle manifest [{0}], attempting to autocorrect by moving contents to Resource descriptor'.format(lifecycle_manifest_path)) managed_to_autocorrect = False autocorrect_error = None try: with open(lifecycle_manifest_path, 'r') as f: lifecycle_manifest_content = yaml.safe_load(f.read()) descriptor = descriptor_utils.DescriptorParser().read_from_file(self.get_main_descriptor()) descriptor.is_2_dot_1 = True if 'types' in lifecycle_manifest_content: for entry in lifecycle_manifest_content['types']: if 'lifecycle_type' in entry and 'infrastructure_type' in entry: lifecycle_type = entry['lifecycle_type'] infrastructure_type = entry['infrastructure_type'] if lifecycle_type in descriptor.default_driver and 'infrastructure-type' in descriptor.default_driver[lifecycle_type]: descriptor.default_driver[lifecycle_type]['infrastructure-type'].append(infrastructure_type) else: descriptor.insert_default_driver(lifecycle_type, [infrastructure_type]) descriptor_utils.DescriptorParser().write_to_file(descriptor, self.get_main_descriptor()) os.rename(lifecycle_manifest_path, lifecycle_manifest_path + '.bak') managed_to_autocorrect = True except Exception as e: autocorrect_error = e if not managed_to_autocorrect: msg = 'Found lifecycle manifest [{0}]: this file is no longer supported by the Brent Resource Manager. Unable to autocorrect this issue, please add this information to the Resource descriptor manually instead'.format(lifecycle_manifest_path) if autocorrect_error is not None: msg += ' (autocorrect error={0})'.format(str(autocorrect_error)) journal.error_event(msg) errors.append(project_validation.ValidationViolation(msg)) return else: msg = 'Found lifecycle manifest [{0}]: this file is no longer supported by the Brent Resource Manager. Add this information to the Resource descriptor instead or enable the autocorrect option'.format(lifecycle_manifest_path) journal.error_event(msg) errors.append(project_validation.ValidationViolation(msg)) return def get_main_descriptor(self): main_descriptor_path = self.tree.descriptor_file_path return main_descriptor_path def stage_sources(self, journal, source_stager): staging_tree = BrentResourcePackageContentTree() journal.event('Staging Resource descriptor for {0} at {1}'.format(self.source_config.full_name, self.get_main_descriptor())) source_stager.stage_descriptor(self.get_main_descriptor(), staging_tree.descriptor_file_path) included_items = [ {'path': self.tree.infrastructure_definitions_path, 'alias': staging_tree.infrastructure_definitions_path}, {'path': self.tree.lifecycle_path, 'alias': staging_tree.lifecycle_path} ] self.__stage_directories(journal, source_stager, included_items) def __stage_directories(self, journal, source_stager, items): for item in items: if os.path.exists(item['path']): journal.event('Staging directory {0}'.format(item['path'])) source_stager.stage_tree(item['path'], item['alias']) def build_staged_source_delegate(self, staging_path): return BrentStagedSourceHandlerDelegate(staging_path, self.source_config) class BrentStagedSourceHandlerDelegate(handlers_api.ResourceStagedSourceHandlerDelegate): def __init__(self, root_path, source_config): super().__init__(root_path, source_config) self.tree = BrentResourcePackageContentTree(self.root_path) def compile_sources(self, journal, source_compiler): pkg_tree = BrentPkgContentTree() self.__build_res_pkg(journal, source_compiler, pkg_tree) self.__add_root_descriptor(journal, source_compiler,
None)) def reconfig(self, *, shape=None, metric=None): """ Reconfig objective Arguments: shape: objective layer shape metric: loss metric """ if metric is not None: if 'loss' in metric or ('accuracy' or 'acc') in metric: if 'loss' in metric: self._evaluation['metric']['loss'] = 0 if ('accuracy' or 'acc') in metric or \ ('recall' or 'rc') in metric or \ ('precision' or 'prec') in metric or \ ('f1_score' or 'f1') in metric: warnings.warn(f'Log-cosh loss objective only have loss metric. Ignoring metrics {metric}', UserWarning) else: raise TypeError(f'Unknown metric {metric} for objective {self.name}.') if shape is not None: super().reconfig(shape=shape) self.reset() @MType(np.ndarray, np.ndarray, dict) def compute_loss(self, y_t, y_prime_t, *, residue={}): """ Compute the loss. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t ly_t = np.log(np.cosh(ey_t) + 1e-12) return (ly_t, residue) @MType(np.ndarray, np.ndarray, dict) def compute_loss_grad(self, y_t, y_prime_t, *, residue={}): """ Compute the loss gradient tensor for gradient descent update. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t eyg_t = np.tanh(ey_t) return (eyg_t, residue) @MType(np.ndarray, np.ndarray, np.ndarray, dict) def compute_evaluation_metric(self, y_t, y_prime_t, ly_t, evaluation_metric): """ Compute the evaluation metric. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor ly_t: loss tensor Returns: metric """ if 'loss' in evaluation_metric: evaluation_metric['loss'] += ly_t.mean() return evaluation_metric # ------------------------------------------------------------------------ class XTanhLoss(Objective): _label = OBJECTIVE.XTANH_LOSS_LABEL """ Arguments: size: objective size name: objective name metric: loss metric """ @MType(size=int, name=str, metric=(str,)) def __init__(self, *, size=1, name='', metric=('loss',)): self._cache = None super().__init__(size=size, name=name) self.reconfig(metric=metric) # ------------------------------------------------------------------------ @MType(shape=OneOfType((int,), None), metric=OneOfType((str,), None)) def reconfig(self, *, shape=None, metric=None): """ Reconfig objective Arguments: shape: objective layer shape metric: loss metric """ if metric is not None: if 'loss' in metric or ('accuracy' or 'acc') in metric: if 'loss' in metric: self._evaluation['metric']['loss'] = 0 if ('accuracy' or 'acc') in metric or \ ('recall' or 'rc') in metric or \ ('precision' or 'prec') in metric or \ ('f1_score' or 'f1') in metric: warnings.warn(f'XTanh loss objective only have loss metric. Ignoring metrics {metric}', UserWarning) else: raise TypeError(f'Unknown metric {metric} for objective {self.name}.') if shape is not None: super().reconfig(shape=shape) self.reset() @MType(np.ndarray, np.ndarray, dict) def compute_loss(self, y_t, y_prime_t, *, residue={}): """ Compute the loss. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t tanh_of_ey_t = np.tanh(ey_t) ly_t = np.multiply(ey_t, tanh_of_ey_t) self._cache = tanh_of_ey_t return (ly_t, residue) @MType(np.ndarray, np.ndarray, dict) def compute_loss_grad(self, y_t, y_prime_t, *, residue={}): """ Compute the loss gradient tensor for gradient descent update. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t tanh_of_ey_t = self._cache eyg_t = tanh_of_ey_t + ey_t * (1 - np.square(tanh_of_ey_t)) return (eyg_t, residue) @MType(np.ndarray, np.ndarray, np.ndarray, dict) def compute_evaluation_metric(self, y_t, y_prime_t, ly_t, evaluation_metric): """ Compute the evaluation metric. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor ly_t: loss tensor Returns: metric """ if 'loss' in evaluation_metric: evaluation_metric['loss'] += ly_t.mean() return evaluation_metric # ------------------------------------------------------------------------ class XSigmoidLoss(Objective): _label = OBJECTIVE.XSIGMOID_LOSS_LABEL """ Arguments: size: objective size name: objective name metric: loss metric """ @MType(size=int, name=str, metric=(str,)) def __init__(self, *, size=1, name='', metric=('loss',)): self._cache = None super().__init__(size=size, name=name) self.reconfig(metric=metric) # ------------------------------------------------------------------------ @MType(shape=OneOfType((int,), None), metric=OneOfType((str,), None)) def reconfig(self, *, shape=None, metric=None): """ Reconfig objective Arguments: shape: objective layer shape metric: loss metric """ if metric is not None: if 'loss' in metric or ('accuracy' or 'acc') in metric: if 'loss' in metric: self._evaluation['metric']['loss'] = 0 if ('accuracy' or 'acc') in metric or \ ('recall' or 'rc') in metric or \ ('precision' or 'prec') in metric or \ ('f1_score' or 'f1') in metric: warnings.warn(f'XSigmoid loss objective only have loss metric. Ignoring metrics {metric}', UserWarning) else: raise TypeError(f'Unknown metric {metric} for objective {self.name}.') if shape is not None: super().reconfig(shape=shape) self.reset() @MType(np.ndarray, np.ndarray, dict) def compute_loss(self, y_t, y_prime_t, *, residue={}): """ Compute the loss. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t sigmoid_of_ey_t = np.exp(-np.logaddexp(0, -ey_t + 1e-12)) ly_t = np.multiply(2 * ey_t, sigmoid_of_ey_t) - ey_t self._cache = sigmoid_of_ey_t return (ly_t, residue) @MType(np.ndarray, np.ndarray, dict) def compute_loss_grad(self, y_t, y_prime_t, *, residue={}): """ Compute the loss gradient tensor for gradient descent update. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t sigmoid_of_ey_t = self._cache eyg_t = 2 * sigmoid_of_ey_t + np.multiply(np.multiply(2 * ey_t, np.exp(-ey_t)), np.square(sigmoid_of_ey_t)) - 1 return (eyg_t, residue) @MType(np.ndarray, np.ndarray, np.ndarray, dict) def compute_evaluation_metric(self, y_t, y_prime_t, ly_t, evaluation_metric): """ Compute the evaluation metric. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor ly_t: loss tensor Returns: metric """ if 'loss' in evaluation_metric: evaluation_metric['loss'] += ly_t.mean() return evaluation_metric # ------------------------------------------------------------------------ class AlgebraicLoss(Objective): _label = OBJECTIVE.ALGEBRAIC_LOSS_LABEL """ Arguments: size: objective size name: objective name metric: loss metric """ @MType(size=int, name=str, metric=(str,)) def __init__(self, *, size=1, name='', metric=('loss',)): self._cache = None super().__init__(size=size, name=name) self.reconfig(metric=metric) # ------------------------------------------------------------------------ @MType(shape=OneOfType((int,), None), metric=OneOfType((str,), None)) def reconfig(self, *, shape=None, metric=None): """ Reconfig objective Arguments: shape: objective layer shape metric: loss metric """ if metric is not None: if 'loss' in metric or ('accuracy' or 'acc') in metric: if 'loss' in metric: self._evaluation['metric']['loss'] = 0 if ('accuracy' or 'acc') in metric or \ ('recall' or 'rc') in metric or \ ('precision' or 'prec') in metric or \ ('f1_score' or 'f1') in metric: warnings.warn(f'Algebraic loss objective only have loss metric. Ignoring metrics {metric}', UserWarning) else: raise TypeError(f'Unknown metric {metric} for objective {self.name}.') if shape is not None: super().reconfig(shape=shape) self.reset() @MType(np.ndarray, np.ndarray, dict) def compute_loss(self, y_t, y_prime_t, *, residue={}): """ Compute the loss. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t sqr_of_ey_t = np.square(ey_t) inv_of_ey_t = 1 / (1 + sqr_of_ey_t) inv_sqrt_of_ey_t = np.sqrt(inv_of_ey_t) ly_t = np.multiply(sqr_of_ey_t, inv_sqrt_of_ey_t) self._cache = (sqr_of_ey_t, inv_of_ey_t, inv_sqrt_of_ey_t) return (ly_t, residue) @MType(np.ndarray, np.ndarray, dict) def compute_loss_grad(self, y_t, y_prime_t, *, residue={}): """ Compute the loss gradient tensor for gradient descent update. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ ey_t = y_t - y_prime_t (sqr_of_ey_t, inv_of_ey_t, inv_sqrt_of_ey_t) = self._cache eyg_t = np.multiply(2 * ey_t + np.multiply(ey_t, sqr_of_ey_t), np.multiply(inv_of_ey_t, inv_sqrt_of_ey_t)) return (eyg_t, residue) @MType(np.ndarray, np.ndarray, np.ndarray, dict) def compute_evaluation_metric(self, y_t, y_prime_t, ly_t, evaluation_metric): """ Compute the evaluation metric. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor ly_t: loss tensor Returns: metric """ if 'loss' in evaluation_metric: evaluation_metric['loss'] += ly_t.mean() return evaluation_metric # ------------------------------------------------------------------------ class SigmoidCrossentropyLoss(Objective): _label = OBJECTIVE.SIGMOID_CROSSENTROPY_LOSS """ Objective using sigmoid (binary)crossentropyfor loss function. Arguments: size: objective size name: objective name metric: loss and accuracy metrics """ @MType(size=int, name=str, metric=(str,)) def __init__(self, *, size=1, name='', metric=('loss', 'accuracy')): super().__init__(size=size, name=name) self.reconfig(metric=metric) # ------------------------------------------------------------------------ @MType(shape=OneOfType((int,), None), metric=OneOfType((str,), None)) def reconfig(self, *, shape=None, metric=None): """ Reconfig objective Arguments: shape: objective layer shape metric: loss metric """ if metric is not None: if 'loss' in metric or ('accuracy' or 'acc'): if 'loss' in metric: self._evaluation['metric']['loss'] = 0 if ('accuracy' or 'acc') in metric: self._evaluation['metric']['accuracy'] = 0 if ('recall' or 'rc') in metric: self._evaluation['metric']['recall'] = 0 if ('precision' or 'prec') in metric: self._evaluation['metric']['precision'] = 0 if ('f1_score' or 'f1') in metric: self._evaluation['metric']['f1_score'] = 0 else: raise TypeError(f'Unknown metric {metric} for objective {self.name}.') if shape is not None: super().reconfig(shape=shape) self.reset() @MType(dict, np.ndarray, residue=dict) @MShape(axis=1) def forward(self, stage, a_t, *, residue={}): """ Do forward pass method. Arguments: stage: forward stage a_t: post-nonlinearity (a) tensor residue: Returns: layer """ sigmoid_of_a_t = np.exp(-np.logaddexp(0, -a_t + 1e-12)) return super().forward(stage, sigmoid_of_a_t, residue=residue) @MType(np.ndarray, np.ndarray, dict) def compute_loss(self, y_t, y_prime_t, *, residue={}): """ Compute the loss. Arguments: y_t: output (y) tensor y_prime_t: expected output (y) tensor residue: Returns: tuple """ y_prime_t = y_prime_t.astype(np.float32) ly_t = -(y_prime_t * np.log(y_t + 1e-12) + (1 - y_prime_t) * np.log((1 - y_t) + 1e-12)) return (ly_t, residue) @MType(np.ndarray, np.ndarray, dict) def compute_loss_grad(self, y_t, y_prime_t, *, residue={}): """ Compute the loss gradient
#! /usr/bin/env python3 # coding: utf-8 from __future__ import annotations from collections.abc import Iterator import math from operator import itemgetter import typing as t from dropbox import Dropbox import gpxpy import pendulum from psycopg2.extensions import connection import slack from gargbot_3000 import commands, config, database, health from gargbot_3000.journey import achievements, common, location_apis, mapping from gargbot_3000.logger import log queries = common.queries.journey def define_journey(conn, origin, destination) -> int: journey_id = queries.add_journey(conn, origin=origin, destination=destination) return journey_id def parse_gpx(conn, journey_id, xml_data) -> None: gpx = gpxpy.parse(xml_data) plist = gpx.tracks[0].segments[0].points waypoints: list[dict] = [] prev_waypoint = None cumulative_distance = 0 for waypoint in plist: if prev_waypoint is not None: distance = waypoint.distance_2d(prev_waypoint) cumulative_distance += distance data = { "journey_id": journey_id, "lat": waypoint.latitude, "lon": waypoint.longitude, "elevation": waypoint.elevation, "distance": cumulative_distance, } waypoints.append(data) prev_waypoint = waypoint queries.add_waypoints(conn, waypoints) def coordinates_for_distance( conn, journey_id, distance ) -> tuple[float, float, int, bool]: latest_waypoint = queries.get_waypoint_for_distance( conn, journey_id=journey_id, distance=distance ) next_waypoint = queries.get_next_waypoint_for_distance( conn, journey_id=journey_id, distance=distance ) if next_waypoint is None: finished = True current_lat = latest_waypoint["lat"] current_lon = latest_waypoint["lon"] else: finished = False remaining_dist = distance - latest_waypoint["distance"] current_lat, current_lon = common.location_between_waypoints( latest_waypoint, next_waypoint, remaining_dist ) return current_lat, current_lon, latest_waypoint["id"], finished def daily_factoid( date: pendulum.Date, conn: connection, journey_data: dict, distance_today: float, distance_total: float, ) -> str: dist_remaining = journey_data["distance"] - distance_total destination = journey_data["destination"] def remaining_distance() -> str: return ( f"Nå har vi gått {round_meters(distance_total)} totalt på vår journey til {destination}. " f"Vi har {round_meters(dist_remaining)} igjen til vi er framme." ) def eta_average(): n_days = (date - journey_data["started_at"]).days + 1 distance_average = distance_total / n_days days_remaining = math.ceil(dist_remaining / distance_average) eta = date.add(days=days_remaining) return ( f"Average daglig progress er {round_meters(distance_average)}. " f"Holder vi dette tempoet er vi fremme i {destination} {eta.format('DD. MMMM YYYY', locale='nb')}, " f"om {days_remaining} dager." ) def eta_today(): days_remaining = math.ceil(journey_data["distance"] / distance_today) eta = journey_data["started_at"].add(days=days_remaining) return f"Hadde vi gått den distansen hver dag ville journeyen vart til {eta.format('DD. MMMM YYYY', locale='nb')}." def weekly_summary(): data = queries.weekly_summary(conn, journey_id=journey_data["id"], date=date) steps_week = sum(datum["amount"] for datum in data) distance_week = steps_week * common.STRIDE max_week = sorted(data, key=itemgetter("amount"))[-1] max_week_distance = round_meters(max_week["amount"] * common.STRIDE) return ( f"Denne uken har vi gått {round_meters(distance_week)} til sammen. " f"Garglingen som gikk lengst var {max_week['first_name']}, med {max_week_distance}!" ) switch = { pendulum.SUNDAY: remaining_distance, pendulum.MONDAY: eta_average, pendulum.TUESDAY: eta_today, pendulum.WEDNESDAY: remaining_distance, pendulum.THURSDAY: eta_average, pendulum.FRIDAY: eta_today, pendulum.SATURDAY: weekly_summary, } func = switch[date.day_of_week] result = f"Vi gikk *{round_meters(distance_today)}*! " + func() return result def upload_images( journey_id: int, date: pendulum.Date, photo: t.Optional[bytes], traversal_map: t.Optional[bytes], ) -> tuple[t.Optional[str], t.Optional[str]]: # no test coverage dbx = Dropbox(config.dropbox_token) def upload(data: bytes, name: str) -> t.Optional[str]: path = config.dbx_journey_folder / f"{journey_id}_{date}_{name}.jpg" try: uploaded = dbx.files_upload(f=data, path=path.as_posix(), autorename=True) except Exception: log.error(f"Error uploading {name} image", exc_info=True) return None shared = dbx.sharing_create_shared_link(uploaded.path_display) url = shared.url.replace("?dl=0", "?raw=1") return url photo_url = upload(photo, name="photo") if photo else None map_img_url = upload(traversal_map, name="map") if traversal_map else None return photo_url, map_img_url def most_recent_location(conn, journey_id) -> t.Optional[dict]: loc = queries.most_recent_location(conn, journey_id=journey_id) if loc is None: return None loc = dict(loc) loc["date"] = pendulum.Date(loc["date"].year, loc["date"].month, loc["date"].day) return loc def lat_lon_increments( conn: connection, journey_id: int, distance_total: float, last_total_distance: float ) -> Iterator[tuple[float, float]]: incr_length = location_apis.poi_radius * 2 for intermediate_distance in range( int(distance_total), int(last_total_distance + incr_length), -incr_length ): inter_lat, inter_lon, *_ = coordinates_for_distance( conn, journey_id, intermediate_distance ) yield inter_lat, inter_lon def perform_daily_update( conn: connection, journey_id: int, date: pendulum.Date, steps_data: list[dict], gargling_info: dict[int, dict], ) -> t.Optional[ tuple[dict, float, dict, t.Optional[str], str, t.Optional[str], bool, bool] ]: journey_data = dict(queries.get_journey(conn, journey_id=journey_id)) if journey_data["finished_at"] is not None or journey_data["started_at"] is None: return None journey_data["started_at"] = pendulum.Date( year=journey_data["started_at"].year, month=journey_data["started_at"].month, day=journey_data["started_at"].day, ) # TODO: return pendulum instance from db steps_data.sort(key=itemgetter("amount"), reverse=True) steps_today = sum(data["amount"] for data in steps_data) if steps_today == 0: # no test coverage return None last_location = most_recent_location(conn, journey_id) last_total_distance = last_location["distance"] if last_location else 0 distance_today = steps_today * common.STRIDE distance_total = distance_today + last_total_distance lat, lon, latest_waypoint_id, finished = coordinates_for_distance( conn, journey_id, distance_total ) lat_lons = lat_lon_increments(conn, journey_id, distance_total, last_total_distance) address, country, photo, map_url, poi = location_apis.main(lat_lons) new_country = ( country != last_location["country"] if last_location and None not in (country, last_location["country"]) else False ) traversal_map = mapping.main( conn, journey_id, last_location, lat, lon, distance_total, steps_data, gargling_info, ) photo_url, map_img_url = upload_images(journey_id, date, photo, traversal_map,) location = { "journey_id": journey_id, "latest_waypoint": latest_waypoint_id, "lat": lat, "lon": lon, "distance": distance_total, "date": date, "address": address, "country": country, "poi": poi, } return ( location, distance_today, journey_data, photo_url, map_url, map_img_url, new_country, finished, ) def days_to_update(conn, journey_id, date: pendulum.Date) -> t.Iterable[pendulum.Date]: journey = queries.get_journey(conn, journey_id=journey_id) start_loc = most_recent_location(conn, journey_id) if start_loc is None: last_updated_at = journey["started_at"] else: last_updated_at = start_loc["date"].add(days=1) # add one day because (date-date) returns that date period_to_add = date - last_updated_at for day in period_to_add: if day == date: # to not perform update if day is not finished continue yield day def round_meters(n: float) -> str: if n < 1000: unit = "m" else: n /= 1000 unit = "km" n = round(n, 1) if int(n) == n: n = int(n) return f"{n} {unit}" def format_response( n_day: int, date: pendulum.Date, steps_data: list, factoid: str, address: t.Optional[str], country: t.Optional[str], poi: t.Optional[str], photo_url: t.Optional[str], map_url: str, map_img_url: t.Optional[str], body_reports: t.Optional[list[str]], finished: bool, gargling_info: dict[int, dict], achievement: t.Optional[str], ) -> dict: blocks = [] title_txt = ( f"*Ekspedisjonsrapport {date.day}.{date.month}.{date.year} - dag {n_day}*" if not finished else "*Ekspedisjon complete!*" ) blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": title_txt}}) blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": factoid}}) steps_txt = "Steps taken:" most_steps = steps_data[0]["amount"] fewest_steps = steps_data[-1]["amount"] for i, row in enumerate(steps_data): color = gargling_info[row["gargling_id"]]["color_name"] name = gargling_info[row["gargling_id"]]["first_name"] steps = row["amount"] g_distance = round_meters(steps * common.STRIDE) if steps == most_steps: amount = f"*{steps}* ({g_distance}) :first_place_medal:" elif steps == fewest_steps: amount = f"_{steps}_ ({g_distance}) :turtle:" elif i == 1: amount = f"{steps} ({g_distance}) :second_place_medal:" elif i == 2: amount = f"{steps} ({g_distance}) :third_place_medal:" else: amount = f"{steps} ({g_distance})" desc = f"\n\t:dot-{color}: {name}: {amount}" steps_txt += desc blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": steps_txt}}) if achievement: blocks.append( {"type": "section", "text": {"type": "mrkdwn", "text": achievement}} ) if map_img_url is not None: blocks.append( {"type": "image", "image_url": map_img_url, "alt_text": "Breakdown!"} ) location_txt = "" if country is not None: location_txt += f"Velkommen til {country}! :confetti_ball: " if address is not None: location_txt += f"Vi har nå kommet til {address}. " if poi is not None: location_txt += f"Dagens underholdning er {poi}." if location_txt: blocks.append( {"type": "section", "text": {"type": "mrkdwn", "text": location_txt}} ) if photo_url is not None: alt_text = address if address is not None else "Check it!" blocks.append({"type": "image", "image_url": photo_url, "alt_text": alt_text}) blocks.append( { "type": "section", "text": { "type": "mrkdwn", "text": ( f"<{map_url}|Gøggle Maps> | " f"<{config.server_name}/map|Gargbot Kart> | " f"<{config.server_name}/dashboard|Stats>" ), }, } ) if body_reports: blocks.append({"type": "divider"}) body_txt = "Also: " + "".join(body_reports) blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": body_txt}}) distance_summary = factoid.split("!")[0] + "!" response = { "text": f"{title_txt}: {distance_summary}".replace("*", ""), "blocks": blocks, } return response def store_update_data(conn, location_data, finished): queries.add_location(conn, **location_data) if finished: queries.finish_journey( conn, journey_id=location_data["journey_id"], date=location_data["date"] ) def store_steps(conn, steps, journey_id, date) -> None: for step in steps: step["taken_at"] = date step["journey_id"] = journey_id queries.add_steps(conn, steps) def main(conn: connection, current_date: pendulum.Date) -> t.Iterator[dict]: ongoing_journey = queries.get_ongoing_journey(conn) journey_id = ongoing_journey["id"] try: for date in days_to_update(conn, journey_id, current_date): log.info(f"Journey update for {date}") with conn: activity_data = health.activity(conn, date) if not activity_data: # no test coverage continue steps_data, body_reports = activity_data gargling_info = common.get_colors_names( conn, ids=[gargling["gargling_id"] for gargling in steps_data] ) update_data = perform_daily_update( conn=conn, journey_id=journey_id, date=date, steps_data=steps_data, gargling_info=gargling_info, ) if not update_data: # no test coverage continue ( location, distance_today, journey_data, photo_url, map_url, map_img_url, new_country, finished, ) = update_data store_update_data(conn, location, finished) store_steps(conn, steps_data, journey_id, date) achievement = achievements.new(conn, journey_id, date, gargling_info) factoid = daily_factoid( date, conn, journey_data, distance_today, location["distance"], ) n_day = (date - ongoing_journey["started_at"]).days + 1 formatted = format_response( date=date, n_day=n_day, steps_data=steps_data, body_reports=body_reports, factoid=factoid, finished=finished, gargling_info=gargling_info, address=location["address"], country=location["country"] if new_country else None, poi=location["poi"], photo_url=photo_url, map_url=map_url, map_img_url=map_img_url, achievement=achievement, ) yield formatted conn.commit() except Exception: # no test coverage log.error(f"Error in journey.main", exc_info=True) def run_updates() -> None: # no test coverage current_date = pendulum.now() try: # now() function sometimes returns a date, not datetime??
""" A decision is the act of picking an option at a choice, after which one experiences an outcome. Note that the handling of extended/hidden/uncertain outcomes is not yet implemented. Decisions have information on both a player's prospective impressions of the choice in question (as a decision model plus goal saliences) and their retrospective impressions of the option they chose (as a mapping from goal names to Retrospective percepts). When a decision is created, it doesn't yet specify outcomes or retrospective impressions (although the option that it is a decision for includes outcomes that have probabilities). The "roll_outcomes" method can be used to automatically sample a set of outcomes for an option. """ def __init__( self, choice, option=None, outcomes=None, prospective_impressions=None, factored_decision_models=None, goal_relevance=None, retrospective_impressions=None ): """ choice: The choice that this object focuses on. option: The option the choosing of which this Decision represents. May be left blank at first by passing in None. outcomes: A collection of Outcome objects; leave out to create a pre-outcome decision. The special string "generate" can be used to automatically generate outcomes; it just has the effect of calling roll_outcomes. Note that "generate" may not be given when no option is specified (doing so will result in a RuntimeError). prospective_impressions: A mapping from option names to mappings from goal names to prospective impression lists, as returned by ModeOfEngagement.build_decision_model. Can be created automatically along with the factored_decision_models and goal_relevance properties if given as None using the add_prospective_impressions method. factored_decision_models: This is just a list of one or more prospective impressions structures (maps from option names to maps from goal names to impression lists). The models are arranged such that the first model can be used to make decisions, falling back to successive models in the case of a tie at an upper level. Normally, this is given as None and assigned when add_prospective_impressions is called. goal_relevance: A mapping from goal names to Salience values. This expresses the relative importance of various goals at the moment of the decision, and is usually given as None and assigned when add_prospective_impressions is called. retrospective_impressions: A mapping from goal names to lists of Retrospective impression objects. Normally given as None and then assigned using the add_retrospective_impressions method. Note that each goal may have multiple associated impressions based on the various outcomes that occurred. This only makes sense if the option for this Decision has been chosen and outcomes have been rolled (see roll_outcomes). """ self.choice = choice self.option = option if isinstance(self.option, str): self.option = self.choice.options[self.option] # look up within choice self.outcomes = outcomes or {} if self.outcomes == "generate": self.roll_outcomes() elif not isinstance(self.outcomes, dict): utils.check_names( self.outcomes, "Two outcomes named '{{}}' cannot coexist within a Decision." ) self.outcomes = { o.name: o for o in self.outcomes } self.prospective_impressions = prospective_impressions self.factored_decision_models = factored_decision_models self.goal_relevance = goal_relevance self.retrospective_impressions = retrospective_impressions if retrospective_impressions: self.add_simplified_retrospectives() else: self.simplified_retrospectives = None def __str__(self): # TODO: Better here return str(pack(self)) def _diff_(self, other): """ Reports differences (see diffable.py). """ return [ "choices: {}".format(d) for d in diff(self.choice, other.choice) ] + [ "options: {}".format(d) for d in diff(self.option, other.option) ] + [ "outcomes: {}".format(d) for d in diff(self.outcomes, other.outcomes) ] + [ "prospectives: {}".format(d) for d in diff( self.prospective_impressions, other.prospective_impressions ) ] + [ "factored decision models: {}".format(d) for d in diff( self.factored_decision_models, other.factored_decision_models ) ] + [ "goal relevance: {}".format(d) for d in diff(self.goal_relevance, other.goal_relevance) ] + [ "retrospectives: {}".format(d) for d in diff( self.retrospective_impressions, other.retrospective_impressions ) ] + [ "simplified retrospectives: {}".format(d) for d in diff( self.simplified_retrospectives, other.simplified_retrospectives ) ] def __eq__(self, other): if not isinstance(other, Decision): return False if other.choice != self.choice: return False if other.option != self.option: return False if other.outcomes != self.outcomes: return False if other.prospective_impressions != self.prospective_impressions: return False if other.factored_decision_models != self.factored_decision_models: return False if other.goal_relevance != self.goal_relevance: return False if other.retrospective_impressions != self.retrospective_impressions: return False if other.simplified_retrospectives != self.simplified_retrospectives: return False return True def __hash__(self): h = hash(self.choice) h ^= hash(self.option) for on in self.outcomes: h ^= 583948 + hash(self.outcomes[on]) if self.prospective_impressions: for on in self.prospective_impressions: option_impressions = self.prospective_impressions[on] oh = hash(on) for gn in option_impressions: h ^= 874387 + hash(tuple(option_impressions[gn])) + oh if self.factored_decision_models: for dm in self.factored_decision_models: for on in dm: option_impressions = dm[on] oh = hash(on) for gn in option_impressions: h ^= 231893 + hash(tuple(option_impressions[gn])) + oh if self.goal_relevance: for gn in self.goal_relevance: h ^= 3321564 + hash(gn) + hash(self.goal_relevance[gn]) if self.retrospective_impressions: for gn in self.retrospective_impressions: h ^= 67894 + hash(gn) + hash(tuple(self.retrospective_impressions[gn])) if self.simplified_retrospectives: for gn in self.simplified_retrospectives: h ^= 848846 + hash(gn) + hash(self.simplified_retrospectives[gn]) return h def _pack_(self): """ Packs this Decision into a simple object representation which can be converted to JSON. Example: ``` Decision( Choice( "Rescue the baby dragon or not?", [ Option( "rescue_it", [ Outcome( "bites_your_hand", { "health_and_safety": Valence("unsatisfactory"), "befriend_dragon": Valence("unsatisfactory"), }, Salience("implicit"), Certainty("even"), ), Outcome( "appreciates_kindness", { "befriend_dragon": "good" }, "explicit", "likely", ) ] ), Option( "leave_it", [ Outcome( "dislikes_abandonment", { "befriend_dragon": "bad" }, "explicit", 0.97, ), Outcome( "dies", { "befriend_dragon": "awful", "kill_dragon": "great" }, "hinted", "unlikely", actual_likelihood="even" ) ] ) ] ), Option( "rescue_it", [ Outcome( "bites_your_hand", { "health_and_safety": Valence("unsatisfactory"), "befriend_dragon": Valence("unsatisfactory"), }, Salience("implicit"), Certainty("even"), ), Outcome( "appreciates_kindness", { "befriend_dragon": "good" }, "explicit", "likely", ) ] ), [ Outcome( "appreciates_kindness", { "befriend_dragon": "good" }, "explicit", "likely", ) ], prospective_impressions=None, factored_decision_models=None, goal_relevance=None, retrospective_impressions=None ) ``` { "choice": { "name": "Rescue the baby dragon or not?", "options": { "leave_it": { "name": "leave_it", "outcomes": [ { "actual_likelihood": "even", "apparent_likelihood": "unlikely", "effects": { "befriend_dragon": "awful", "kill_dragon": "great" }, "name": "dies", "salience": "hinted" }, { "apparent_likelihood": 0.97, "effects": { "befriend_dragon": "bad" }, "name": "dislikes_abandonment", "salience": "explicit" }, ] }, "rescue_it": { "name": "rescue_it", "outcomes": [ { "apparent_likelihood": "likely", "effects": { "befriend_dragon": "good" }, "name": "appreciates_kindness", "salience": "explicit" }, { "apparent_likelihood": "even", "effects": { "befriend_dragon": "unsatisfactory", "health_and_safety": "unsatisfactory" }, "name": "bites_your_hand", "salience": "implicit" } ] } } }, "option": { "name": "rescue_it", "outcomes": [ { "apparent_likelihood": "likely", "effects": { "befriend_dragon": "good" }, "name": "appreciates_kindness", "salience": "explicit" }, { "apparent_likelihood": "even", "effects": { "befriend_dragon": "unsatisfactory", "health_and_safety": "unsatisfactory" }, "name": "bites_your_hand", "salience": "implicit" } ] }, "outcomes": [ { "apparent_likelihood": "likely", "effects": { "befriend_dragon": "good" }, "name": "appreciates_kindness", "salience": "explicit" } ], "prospective_impressions": None, "factored_decision_models": None, "goal_relevance": None, "retrospective_impressions": None, } ``` TODO: More examples! """ return { "choice": pack(self.choice), "option": pack(self.option), "outcomes": [ pack(o) for o in self.outcomes.values() ], "prospective_impressions": pack(self.prospective_impressions), "factored_decision_models": pack(self.factored_decision_models), "goal_relevance": pack(self.goal_relevance), "retrospective_impressions": pack(self.retrospective_impressions), # Note: no need to pack simplified retrospective impressions, as they'll # be reconstructed from the full retrospectives. } def unpack_decision_model(dm): """ Helper method for _unpack_ that unpacks a decision model (a mapping from option names to mappings from goal names to lists of Prospective impressions). """ return { optname: { goalname: [ unpack(pri, perception.Prospective) for pri in dm[optname][goalname] ] for goalname in dm[optname] } for optname in dm } if dm else None def _unpack_(obj): """ The inverse of `_pack_`; creates a Decision from a simple object. Note that the choice, option, and outcomes of this decision are new, disentangled objects, so this it isn't terribly memory efficient to pack and unpack Decision objects, and true linkage shouldn't be assumed. """ return Decision( unpack(obj["choice"], choice.Choice), unpack(obj["option"], choice.Option), [ unpack(o, choice.Outcome) for o in obj["outcomes"] ], Decision.unpack_decision_model(obj["prospective_impressions"]), [ Decision.unpack_decision_model(dm) for dm in obj["factored_decision_models"] ] if obj["factored_decision_models"] else None, { gn: unpack(obj["goal_relevance"][gn], Salience) for gn in obj["goal_relevance"] } if obj["goal_relevance"] else None, { gn: [ unpack(o, perception.Retrospective) for o in obj["retrospective_impressions"][gn] ] for gn in obj["retrospective_impressions"] } if obj["retrospective_impressions"] else None ) def select_option(self, selection): """ Selects a particular option at this choice, either via a string key or the object itself. """ if isinstance(selection, str): self.option = self.choice.options[selection] elif isinstance(selection, choice.Option): if selection not in self.choice.options.values(): raise ValueError( "Can't select option {} which isn't part of choice {}.".format(
<reponame>beasyx0/blog_api from datetime import timedelta from rest_framework import generics from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from rest_framework.response import Response from rest_framework_simplejwt.tokens import RefreshToken, OutstandingToken from rest_framework_simplejwt.token_blacklist.models import BlacklistedToken from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView from rest_framework_simplejwt.exceptions import TokenError from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() from blog_api.users.api.serializers import TokenObtainPairSerializer, RegisterSerializer, UserSerializer, UserPublicSerializer, UserFollowingSerializer from blog_api.users.models import VerificationCode, PasswordResetCode from blog_api.posts.models import Post, Like, DisLike from blog_api.posts.api.serializers import PostOverviewSerializer from blog_api.posts.api.views import get_paginated_queryset from blog_api.users.signals import new_registration from blog_api.users.utils import get_client_ip @api_view(['POST']) @permission_classes((AllowAny,)) def user_register(request): ''' --New user register view-- ========================================================================================================== :param: str username (required) :param: str email (required) :param: str password (required) :param: str password2 (required) :returns: str message. :returns: Response.HTTP_STATUS_CODE. 1) Checks if the desired email or username is already taken. If so returns 400, an appropriate message on wether existing user is active or not and in case inactive resends verification email. 2) Checks if name in request is blank or none. If so adds email name as name. 3) Attempts to serialize and save new user. Returns 201 for created 400 for errors. 4) Record the users ip address for metrics. ========================================================================================================== ''' user_desired_email = request.data.get('email', None) user_email_exists = User.objects.filter(email=user_desired_email).exists() # 1 user_desired_username = request.data.get('username', None) user_username_exists = User.objects.filter(username=user_desired_username).exists() if any([user_email_exists, user_username_exists]): try: user = User.objects.get(email=user_desired_email) except User.DoesNotExist: user = User.objects.get(username=user_desired_username) # one of them exists if user.email == user_desired_email: verification = user.verification_codes.latest('created_at').send_user_verification_email() if verification['verification_sent']: return Response({ 'registered': False, 'message': 'A user with those credentials already exists and is inactive. ' + verification['message'] }, status=HTTP_400_BAD_REQUEST ) else: return Response({ 'registered': False, 'message': verification['message'] }, status=HTTP_400_BAD_REQUEST ) else: return Response({ 'registered': False, 'message': 'A user with that username already exists. Please try again.' }, status=HTTP_400_BAD_REQUEST ) name = request.data.get('name', None) # 2 if not name or name == '': if user_desired_email: name = user_desired_email.split('@')[0] else: name = 'Awesome User' request.data['name'] = name serializer = RegisterSerializer(data=request.data) # 3 if serializer.is_valid(): serializer.save() user_username = serializer.data['username'] # 4 user_ip_address = get_client_ip(request) new_registration.send( sender='new_registration_done', ip_address=user_ip_address, user_username=user_username, task_id=299 ) return Response({ 'registered': True, 'message': 'User registered successfully, please check your email to verify.' }, status=HTTP_201_CREATED ) return Response({ 'registered': False, 'message': serializer.errors, }, status=HTTP_400_BAD_REQUEST ) @api_view(['POST']) @permission_classes((AllowAny,)) def user_verify(request): ''' --User verification email view-- ========================================================================================================== :param: str verification code (required). :returns: str message. :returns: Response.HTTP_STATUS_CODE. 1) Checks for required verification code in the request. If no code returns 400. 2) Checks that a verification code object exists for code given. If no code then returns 400. 3) Calls verify() on the verification code object. Returns 200 for veried == True else 400. ========================================================================================================== ''' verification_code = request.data.get('verification_code', None) # 1 if not verification_code: return Response({ 'verified': False, 'message': 'Please post a valid verification code to verify.' }, status=HTTP_400_BAD_REQUEST ) try: verification_code_obj = VerificationCode.objects.get(verification_code=verification_code) # 2 verified = verification_code_obj.verify() # 3 if verified['verified']: return Response({ 'verified': True, 'message': verified['message'], }, status=HTTP_200_OK ) else: return Response({ 'verified': False, 'message': verified['message'], }, status=HTTP_400_BAD_REQUEST ) except VerificationCode.DoesNotExist: return Response({ 'verified': False, 'message': 'No verification code found with provided code.' }, status=HTTP_400_BAD_REQUEST ) @api_view(['POST']) @permission_classes((AllowAny,)) def user_verify_resend(request): ''' --Resend verification email view-- ========================================================================================================== :params: str email (required) :returns: str message. :returns: Response.HTTP_STATUS_CODE. 1) Checks for required email is in the request. If no email returns 400. 2) Checks for required password in the request. If no password returns 400. 2) Checks that user object exists with given email. If no user returns 400. 4) Calls send_user_verification_email. Returns the appropriate message and 200 if verifcation resent else 400. ========================================================================================================== ''' email = request.data.get('email', None) # 1 if not email: return Response({ 'verifification_sent': False, 'message': 'Please post a valid email address to resend verification email.' }, status=HTTP_400_BAD_REQUEST ) password = request.data.get('password', None) # 2 if not password: return Response({ 'verifification_sent': False, 'message': 'Please post a valid password to resend verification email.' }, status=HTTP_400_BAD_REQUEST ) try: user = User.objects.get(email=email) # 3 if not user.check_password(password): return Response({ 'verifification_sent': False, 'message': 'Password does not match what we have on file. Please try again.' }, status=HTTP_400_BAD_REQUEST) verification_code = user.verification_codes.latest('created_at') verification_code_sent = verification_code.send_user_verification_email() # 4 if verification_code_sent['verification_sent']: return Response({ 'verifification_sent': verification_code_sent['verification_sent'], 'message': verification_code_sent['message'], }, status=HTTP_200_OK ) else: return Response({ 'verifification_sent': verification_code_sent['verification_sent'], 'message': verification_code_sent['message'], }, status=HTTP_400_BAD_REQUEST ) except User.DoesNotExist: return Response({ 'verifification_sent': False, 'message': 'No user found with provided email.' }, status=HTTP_400_BAD_REQUEST ) user_login_refresh = TokenRefreshView().as_view() class MyObtainTokenPairView(TokenObtainPairView): # 1 ''' --User obtain token view (Login) djangorestframework-simplejwt-- ========================================================================================================== :param: str settings.SIMPLE_JWT_LOGIN_USERNAME_FIELD ('e.g. `email` or `username`') (required) :param: str password (required) :returns: Response.HTTP_STATUS_CODE. :returns: Token, RefreshToken. 1) Attmpts to obtain a token pair with email & password. Returns 200 else 400. ========================================================================================================== ''' permission_classes = (AllowAny,) serializer_class = TokenObtainPairSerializer user_login = MyObtainTokenPairView().as_view() @api_view(['POST']) @permission_classes((AllowAny,)) def user_logout(request): ''' --Logout user view-- ========================================================================================================== :param: str refresh token (required). :returns: str message. :returns: Response.HTTP_STATUS_CODE. 1) Checks that refresh token in request. If no token returns 400. 2) Checks that a refresh object exists. If no returns 400. 3) Attempts to blacklist (logout) the refresh token. Returns 204 else 400. ========================================================================================================== ''' token_str = request.data.get('refresh', None) # 1 if not token_str: return Response({ 'logged_out': False, 'message': 'Please post a valid refresh token to logout.' }, status=HTTP_400_BAD_REQUEST ) try: token = RefreshToken(token_str) # 2 try: token.blacklist() # 3 return Response({ 'logged_out': True, 'message': 'User logged out successfully' }, status=HTTP_204_NO_CONTENT ) except: return Response({ 'logged_out': False, 'message': 'User is already logged out' }, status=HTTP_400_BAD_REQUEST ) except TokenError: return Response({ 'logged_out': False, 'message': 'No token found with given credentials.' }, status=HTTP_400_BAD_REQUEST ) @api_view(['POST']) @permission_classes((AllowAny,)) def user_password_reset_send(request): ''' --Send password reset link view-- ========================================================================================================== :param: str email (required). :returns: str message. :returns: Response.HTTP_STATUS_CODE. 1) Checks for email in request. If no returns 400 and messsage. 2) Checks that user object exists. If no returns 400 and message. 3) Checks if any PasswordResetCode objects exist for user. If so resends it and returns 200 and message. 4) Attempts to create a new PasswordResetCode object for the user. If success returns 200 and message else 400 and messsage. ========================================================================================================== ''' email = request.data.get('email', None) # 1 if not email: return Response({ 'password_reset_link_sent': False, 'message': 'Please post a valid email to get reset password link.' }, status=HTTP_400_BAD_REQUEST ) try: user = User.objects.get(email=email) # 2 codes_exist = PasswordResetCode.objects.filter(user=user).exists() if codes_exist: password_reset_link_sent = PasswordResetCode.objects.filter( user=user).latest('created_at').send_user_password_reset_email() # 3 return Response({ 'password_reset_link_sent': password_reset_link_sent['password_reset_link_sent'], 'message': password_reset_link_sent['message'] }, status=HTTP_200_OK ) code = PasswordResetCode.objects.create(user=user) # 4 password_reset_link_sent = code.send_user_password_reset_email() return Response({ 'password_reset_link_sent': password_reset_link_sent['password_reset_link_sent'], 'message': password_reset_link_sent['message'] }, status=HTTP_200_OK ) except User.DoesNotExist: return Response({ 'message': 'No user found with the provided email.' }, status=HTTP_400_BAD_REQUEST ) @api_view(['POST']) @permission_classes((AllowAny,)) def user_password_reset(request): ''' --Password reset view-- ========================================================================================================== :param: str password_reset_code (required). :param: str password (required), :param: str password2 (required). :returns: str message. :returns: Response.HTTP_STATUS_CODE. 1) Checks that password reset code included in request. If no returns 400 and message. 2) Checks that password and password 2 are included in the request. If no returns 400 and message. 3) Checks that both new passwords match. If no returns 400 and message. 4) Attempts to get the password code object. If no returns 400 and message. 5) Calls verify on the PasswordCode object. Return either True or False and a message. ========================================================================================================== ''' password_reset_code = request.data.get('password_reset_code', None) # 1 if not password_reset_code: return Response({ 'password_reset': False, 'message': 'Please post a valid password reset code to reset password.' }, status=HTTP_400_BAD_REQUEST ) password = request.data.get('password', None) password2 = request.data.get('password2', None) # 2 if password is None or password2 is None: return Response({ 'password_reset': False, 'message': 'Please post two new matching passwords to reset password.' }, status=HTTP_400_BAD_REQUEST ) if password != password2: return Response({ 'password_reset': False, 'message': 'Please post matching passwords to reset password.' # 3 }, status=HTTP_400_BAD_REQUEST ) try: password_reset_code_object = PasswordResetCode.objects.get(password_reset_code=password_reset_code) # 4 password_reset = password_reset_code_object.verify(password) # 5 if password_reset['password_reset']: return Response({ 'password_reset': True, 'message': password_reset['message'] }, status=HTTP_200_OK ) else: return Response({ 'password_reset': False, 'message': password_reset['message'] }, status=HTTP_400_BAD_REQUEST ) except PasswordResetCode.DoesNotExist: return Response({ 'password_reset': False, 'message': 'No password reset code found with provided code.' }, status=HTTP_400_BAD_REQUEST ) @api_view(['PUT']) @permission_classes((IsAuthenticated,)) def user_update(request): """
= self.nsmap), 'text') ''' Foreign Keys ''' existence_test_and_add(self, 'person_historical_index_id', self.person_historical_index_id, 'no_handling') existence_test_and_add(self, 'export_index_id', self.export_index_id, 'no_handling') ''' Shred to database ''' shred(self, self.parse_dict, HUDHomelessEpisodes) ''' Parse sub-tables ''' def parse_person_address(self, element): ''' Element paths ''' xpPersonAddress = 'hmis:PersonAddress' xpPersonAddressDateCollected = 'hmis:PersonAddress/@hmis:dateCollected'#IGNORE:@UnusedVariable xpPersonAddressDateEffective = 'hmis:PersonAddress/@hmis:dateEffective'#IGNORE:@UnusedVariable xpPersonAddressDataCollectionStage = 'hmis:PersonAddress/@hmis:dataCollectionStage'#IGNORE:@UnusedVariable xpAddressPeriodStartDate = 'hmis:AddressPeriod/hmis:StartDate' xpAddressPeriodEndDate = 'hmis:AddressPeriod/hmis:EndDate' xpPreAddressLine = 'hmis:PreAddressLine' xpPreAddressLineDateCollected = 'hmis:PreAddressLine/@hmis:dateCollected' xpPreAddressLineDateEffective = 'hmis:PreAddressLine/@hmis:dateEffective' xpPreAddressLineDataCollectionStage = 'hmis:PreAddressLine/@hmis:dataCollectionStage' xpLine1 = 'hmis:Line1' xpLine1DateCollected = 'hmis:Line1/@hmis:dateCollected' xpLine1DateEffective = 'hmis:Line1/@hmis:dateEffective' xpLine1DataCollectionStage = 'hmis:Line1/@hmis:dataCollectionStage' xpLine2 = 'hmis:Line2' xpLine2DateCollected = 'hmis:Line2/@hmis:dateCollected' xpLine2DateEffective = 'hmis:Line2/@hmis:dateEffective' xpLine2DataCollectionStage = 'hmis:Line2/@hmis:dataCollectionStage' xpCity = 'hmis:City' xpCityDateCollected = 'hmis:City/@hmis:dateCollected' xpCityDateEffective = 'hmis:City/@hmis:dateEffective' xpCityDataCollectionStage = 'hmis:City/@hmis:dataCollectionStage' xpCounty = 'hmis:County' xpCountyDateCollected = 'hmis:County/@hmis:dateCollected' xpCountyDateEffective = 'hmis:County/@hmis:dateEffective' xpCountyDataCollectionStage = 'hmis:County/@hmis:dataCollectionStage' xpState = 'hmis:State' xpStateDateCollected = 'hmis:State/@hmis:dateCollected' xpStateDateEffective = 'hmis:State/@hmis:dateEffective' xpStateDataCollectionStage = 'hmis:State/@hmis:dataCollectionStage' xpZIPCode = 'hmis:ZIPCode' xpZIPCodeDateCollected = 'hmis:ZIPCode/@hmis:dateCollected' xpZIPCodeDateEffective = 'hmis:ZIPCode/@hmis:dateEffective' xpZIPCodeDataCollectionStage = 'hmis:ZIPCode/@hmis:dataCollectionStage' xpCountry = 'hmis:Country' xpCountryDateCollected = 'hmis:Country/@hmis:dateCollected' xpCountryDateEffective = 'hmis:Country/@hmis:dateEffective' xpCountryDataCollectionStage = 'hmis:Country/@hmis:dataCollectionStage' xpIsLastPermanentZip = 'hmis:IsLastPermanentZIP' xpIsLastPermanentZIPDateCollected = 'hmis:IsLastPermanentZIP/@hmis:dateCollected' xpIsLastPermanentZIPDateEffective = 'hmis:IsLastPermanentZIP/@hmis:dateEffective' xpIsLastPermanentZIPDataCollectionStage = 'hmis:IsLastPermanentZIP/@hmis:dataCollectionStage' xpZipQualityCode = 'hmis:ZIPQualityCode' xpZIPQualityCodeDateCollected = 'hmis:ZIPQualityCode/@hmis:dateCollected' xpZIPQualityCodeDateEffective = 'hmis:ZIPQualityCode/@hmis:dateEffective' xpZIPQualityCodeDataCollectionStage = 'hmis:ZIPQualityCode/@hmis:dataCollectionStage' itemElements = element.xpath(xpPersonAddress, namespaces = self.nsmap) if itemElements is not None: for item in itemElements: self.parse_dict = {} ''' Map elements to database columns ''' existence_test_and_add(self, 'address_period_start_date', item.xpath(xpAddressPeriodStartDate, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'address_period_end_date', item.xpath(xpAddressPeriodEndDate, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'pre_address_line', item.xpath(xpPreAddressLine, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'pre_address_line_date_collected', item.xpath(xpPreAddressLineDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'pre_address_line_date_effective', item.xpath(xpPreAddressLineDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'pre_address_line', item.xpath(xpPreAddressLineDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'line1', item.xpath(xpLine1, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'line1_date_collected', item.xpath(xpLine1DateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'line1_date_effective', item.xpath(xpLine1DateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'line1_data_collection_stage', item.xpath(xpLine1DataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'line2', item.xpath(xpLine2, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'line2_date_collected', item.xpath(xpLine2DateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'line2_date_effective', item.xpath(xpLine2DateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'line2_data_collection_stage', item.xpath(xpLine2DataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'city', item.xpath(xpCity, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'city_date_collected', item.xpath(xpCityDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'city_date_effective', item.xpath(xpCityDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'city_data_collection_stage', item.xpath(xpCityDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'county', item.xpath(xpCounty, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'county_date_collected', item.xpath(xpCountyDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'county_date_effective', item.xpath(xpCountyDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'county_data_collection_stage', item.xpath(xpCountyDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'state', item.xpath(xpState, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'state_date_collected', item.xpath(xpStateDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'state_date_effective', item.xpath(xpStateDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'state_data_collection_stage', item.xpath(xpStateDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'zipcode', item.xpath(xpZIPCode, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'zipcode_date_collected', item.xpath(xpZIPCodeDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'zipcod_date_effectivee', item.xpath(xpZIPCodeDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'zipcode_data_collection_stage', item.xpath(xpZIPCodeDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'country', item.xpath(xpCountry, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'country_date_collected', item.xpath(xpCountryDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'country_date_effective', item.xpath(xpCountryDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'country_data_collection_stage', item.xpath(xpCountryDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'is_last_permanent_zip', item.xpath(xpIsLastPermanentZip, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'is_last_permanent_zip_date_collected', item.xpath(xpIsLastPermanentZIPDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'is_last_permanent_zip_date_effective', item.xpath(xpIsLastPermanentZIPDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'is_last_permanent_zip_data_collection_stage', item.xpath(xpIsLastPermanentZIPDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'zip_quality_code', item.xpath(xpZipQualityCode, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'zip_quality_code_date_collected', item.xpath(xpZIPQualityCodeDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'zip_quality_code_date_effective', item.xpath(xpZIPQualityCodeDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'zip_quality_code_data_collection_stage', item.xpath(xpZIPQualityCodeDataCollectionStage, namespaces = self.nsmap), 'attribute_text') ''' Foreign Keys ''' existence_test_and_add(self, 'person_historical_index_id', self.person_historical_index_id, 'no_handling') existence_test_and_add(self, 'export_index_id', self.export_index_id, 'no_handling') ''' Shred to database ''' shred(self, self.parse_dict, PersonAddress) ''' Parse sub-tables ''' def parse_other_names(self, element): ''' Element paths ''' xpOtherNames = 'hmis:OtherNames' xpOtherFirstNameUnhashed = 'hmis:OtherFirstName/hmis:Unhashed' xpOtherFirstNameUnhashedDateCollected = 'hmis:OtherFirstName/hmis:Unhashed/@hmis:dateCollected'#IGNORE:@UnusedVariable xpOtherFirstNameUnhashedDateEffective = 'hmis:OtherFirstName/hmis:Unhashed/@hmis:dateEffective'#IGNORE:@UnusedVariable xpOtherFirstNameUnhashedDataCollectionStage = 'hmis:OtherFirstName/hmis:Unhashed/@hmis:dataCollectionStage'#IGNORE:@UnusedVariable xpOtherFirstNameHashed = 'hmis:OtherFirstName/hmis:Hashed' xpOtherFirstNameHashedDateCollected = 'hmis:OtherFirstName/hmis:Hashed/@hmis:dateCollected' xpOtherFirstNameHashedDateEffective = 'hmis:OtherFirstName/hmis:Hashed/@hmis:dateEffective' xpOtherFirstNameHashedDataCollectionStage = 'hmis:OtherFirstName/hmis:Hashed/@hmis:dataCollectionStage' xpOtherLastNameUnhashed = 'hmis:OtherLastName/hmis:Unhashed' xpOtherLastNameUnhashedDateCollected = 'hmis:OtherLastName/hmis:Unhashed/@hmis:dateCollected'#IGNORE:@UnusedVariable xpOtherLastNameUnhashedDateEffective = 'hmis:OtherLastName/hmis:Unhashed/@hmis:dateEffective'#IGNORE:@UnusedVariable xpOtherLastNameUnhashedDataCollectionStage = 'hmis:OtherLastName/hmis:Unhashed/@hmis:dataCollectionStage'#IGNORE:@UnusedVariable xpOtherLastNameHashed = 'hmis:OtherLastName/hmis:Hashed' xpOtherLastNameHashedDateCollected = 'hmis:OtherLastName/hmis:Hashed/@hmis:dateCollected' xpOtherLastNameHashedDateEffective = 'hmis:OtherLastName/hmis:Hashed/@hmis:dateEffective' xpOtherLastNameHashedDataCollectionStage = 'hmis:OtherLastName/hmis:Hashed/@hmis:dataCollectionStage' xpOtherMiddleNameUnhashed = 'hmis:OtherMiddleName/hmis:Unhashed' xpOtherMiddleNameUnhashedDateCollected = 'hmis:OtherMiddleName/hmis:Unhashed/@hmis:dateCollected'#IGNORE:@UnusedVariable xpOtherMiddleNameUnhashedDateEffective = 'hmis:OtherMiddleName/hmis:Unhashed/@hmis:dateEffective'#IGNORE:@UnusedVariable xpOtherMiddleNameUnhashedDataCollectionStage = 'hmis:OtherMiddleName/hmis:Unhashed/@hmis:dataCollectionStage'#IGNORE:@UnusedVariable xpOtherMiddleNameHashed = 'hmis:OtherMiddleName/hmis:Hashed' xpOtherMiddleNameHashedDateCollected = 'hmis:OtherMiddleName/hmis:Hashed/@hmis:dateCollected' xpOtherMiddleNameHashedDateEffective = 'hmis:OtherMiddleName/hmis:Hashed/@hmis:dateEffective' xpOtherMiddleNameHashedDataCollectionStage = 'hmis:OtherMiddleName/hmis:Hashed/@hmis:dataCollectionStage' xpOtherSuffixUnhashed = 'hmis:OtherSuffix/hmis:Unhashed' xpOtherSuffixUnhashedDateCollected = 'hmis:OtherSuffix/hmis:Unhashed/@hmis:dateCollected'#IGNORE:@UnusedVariable xpOtherSuffixUnhashedDateEffective = 'hmis:OtherSuffix/hmis:Unhashed/@hmis:dateEffective'#IGNORE:@UnusedVariable xpOtherSuffixUnhashedDataCollectionStage = 'hmis:OtherSuffix/hmis:Unhashed/@hmis:dataCollectionStage'#IGNORE:@UnusedVariable xpOtherSuffixHashed = 'hmis:OtherSuffix/hmis:Hashed' xpOtherSuffixHashedDateCollected = 'hmis:OtherSuffix/hmis:Hashed/@hmis:dateCollected' xpOtherSuffixHashedDateEffective = 'hmis:OtherSuffix/hmis:Hashed/@hmis:dateEffective' xpOtherSuffixHashedDataCollectionStage = 'hmis:OtherSuffix/hmis:Hashed/@hmis:dataCollectionStage' itemElements = element.xpath(xpOtherNames, namespaces = self.nsmap) if itemElements is not None: for item in itemElements: self.parse_dict = {} ''' Map elements to database columns ''' existence_test_and_add(self, 'other_first_name_unhashed', item.xpath(xpOtherFirstNameUnhashed, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'other_first_name_hashed', item.xpath(xpOtherFirstNameHashed, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'other_first_name_date_collected', item.xpath(xpOtherFirstNameHashedDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'other_first_name_date_effective', item.xpath(xpOtherFirstNameHashedDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'other_first_name_data_collection_stage', item.xpath(xpOtherFirstNameHashedDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'other_last_name_unhashed', item.xpath(xpOtherLastNameUnhashed, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'other_last_name_hashed', item.xpath(xpOtherLastNameHashed, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'other_last_name_date_collected', item.xpath(xpOtherLastNameHashedDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'other_last_name_date_effective', item.xpath(xpOtherLastNameHashedDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'other_last_name_data_collection_stage', item.xpath(xpOtherLastNameHashedDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'other_middle_name_unhashed', item.xpath(xpOtherMiddleNameUnhashed, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'other_middle_name_hashed', item.xpath(xpOtherMiddleNameHashed, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'other_middle_name_date_collected', item.xpath(xpOtherMiddleNameHashedDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'other_middle_name_date_effective', item.xpath(xpOtherMiddleNameHashedDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'other_middle_name_data_collection_stage', item.xpath(xpOtherMiddleNameHashedDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'other_suffix_unhashed', item.xpath(xpOtherSuffixUnhashed, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'other_suffix_hashed', item.xpath(xpOtherSuffixHashed, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'other_suffix_date_collected', item.xpath(xpOtherSuffixHashedDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'other_suffix_date_effective', item.xpath(xpOtherSuffixHashedDateEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'other_suffix_data_collection_stage', item.xpath(xpOtherSuffixHashedDataCollectionStage, namespaces = self.nsmap), 'attribute_text') ''' Foreign Keys ''' existence_test_and_add(self, 'person_index_id', self.person_index_id, 'no_handling') existence_test_and_add(self, 'export_index_id', self.export_index_id, 'no_handling') ''' Shred to database ''' shred(self, self.parse_dict, OtherNames) ''' Parse sub-tables ''' def parse_races(self, element, pf = 'hmis:'): ''' Element paths ''' xpRaces = pf + 'Race' xpRaceUnhashed = 'hmis:Unhashed' xpRaceUnhashedDateCollected = 'hmis:Unhashed/@hmis:dateCollected' xpRaceUnhashedDataCollectionStage = 'hmis:Unhashed/@hmis:dataCollectionStage' xpRaceHashed = 'hmis:Hashed' itemElements = element.xpath(xpRaces, namespaces = self.nsmap) if itemElements is not None: for item in itemElements: self.parse_dict = {} ''' Map elements to database columns ''' existence_test_and_add(self, 'race_unhashed', item.xpath(xpRaceUnhashed, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'race_date_collected', item.xpath(xpRaceUnhashedDateCollected, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'race_data_collection_stage', item.xpath(xpRaceUnhashedDataCollectionStage, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'race_hashed', item.xpath(xpRaceHashed, namespaces = self.nsmap), 'text') ''' Foreign Keys ''' existence_test_and_add(self, 'person_index_id', self.person_index_id, 'no_handling') existence_test_and_add(self, 'export_index_id', self.export_index_id, 'no_handling') ''' Shred to database ''' shred(self, self.parse_dict, Races) ''' Parse sub-tables ''' def parse_funding_source(self, element): ''' Element paths ''' xpFundingSource = 'hmis:FundingSources/hmis:FundingSource' xpFundingSourceIDIDNum = 'hmis:FundingSourceID/hmis:IDNum' xpFundingSourceIDIDStr = 'hmis:FundingSourceID/hmis:IDStr' xpFundingSourceIDDeleteOccurredDate = 'hmis:FundingSourceID/@hmis:deleteOccurredDate' xpFundingSourceIDDeleteEffective = 'hmis:FundingSourceID/@hmis:deleteEffective' xpFundingSourceIDDelete = 'hmis:FundingSourceID/@hmis:delete' xpFederalCFDA = 'hmis:FederalCFDA' xpReceivesMcKinneyFunding = 'hmis:ReceivesMcKinneyFunding' xpAdvanceOrArrears = 'hmis:AdvanceOrArrears' xpFinancialAssistanceAmount = 'hmis:FinancialAssistanceAmount' itemElements = element.xpath(xpFundingSource, namespaces = self.nsmap) if itemElements is not None: for item in itemElements: self.parse_dict = {} ''' Map elements to database columns ''' existence_test_and_add(self, 'funding_source_id_id_num', item.xpath(xpFundingSourceIDIDNum, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'funding_source_id_id_str', item.xpath(xpFundingSourceIDIDStr, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'funding_source_id_delete_occurred_date', item.xpath(xpFundingSourceIDDeleteOccurredDate, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'funding_source_id_delete_effective_date', item.xpath(xpFundingSourceIDDeleteEffective, namespaces = self.nsmap), 'attribute_date') existence_test_and_add(self, 'funding_source_id_delete', item.xpath(xpFundingSourceIDDelete, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'federal_cfda_number', item.xpath(xpFederalCFDA, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'receives_mckinney_funding', item.xpath(xpReceivesMcKinneyFunding, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'advance_or_arrears', item.xpath(xpAdvanceOrArrears, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'financial_assistance_amount', item.xpath(xpFinancialAssistanceAmount, namespaces = self.nsmap), 'text') ''' Foreign Keys ''' try: existence_test_and_add(self, 'service_index_id', self.service_index_id, 'no_handling') except: pass try: existence_test_and_add(self, 'service_event_index_id', self.service_event_index_id, 'no_handling') except: pass try: existence_test_and_add(self, 'export_index_id', self.export_index_id, 'no_handling') except: pass ''' Shred to database ''' shred(self, self.parse_dict, FundingSource) ''' Parse sub-tables ''' def parse_resource_info(self, element): ''' Element paths ''' xpResourceInfo = 'airs:ResourceInfo' xpResourceSpecialist = 'airs:ResourceSpecialist' xpAvailableForDirectory = "../%s/%s" % (xpResourceInfo, '@AvailableForDirectory') xpAvailableForReferral = "../%s/%s" % (xpResourceInfo, '@AvailableForReferral') xpAvailableForResearch = "../%s/%s" % (xpResourceInfo, '@AvailableForResearch') xpDateAdded = "../%s/%s" % (xpResourceInfo, '@DateAdded') xpDateLastVerified = "../%s/%s" % (xpResourceInfo, '@DateLastVerified') xpDateOfLastAction = "../%s/%s" % (xpResourceInfo, '@DateOfLastAction') xpLastActionType = "../%s/%s" % (xpResourceInfo, '@LastActionType') itemElements = element.xpath(xpResourceInfo, namespaces = self.nsmap) if itemElements is not None: for item in itemElements: self.parse_dict = {} ''' Map elements to database columns ''' existence_test_and_add(self, 'resource_specialist', item.xpath(xpResourceSpecialist, namespaces = self.nsmap), 'text') existence_test_and_add(self, 'available_for_directory', item.xpath(xpAvailableForDirectory, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'available_for_referral', item.xpath(xpAvailableForReferral, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'available_for_research', item.xpath(xpAvailableForResearch, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'date_added', item.xpath(xpDateAdded, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'date_last_verified', item.xpath(xpDateLastVerified, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'date_of_last_action', item.xpath(xpDateOfLastAction, namespaces = self.nsmap), 'attribute_text') existence_test_and_add(self, 'last_action_type', item.xpath(xpLastActionType, namespaces = self.nsmap), 'attribute_text') ''' Foreign Keys ''' try: existence_test_and_add(self, 'agency_index_id', self.agency_index_id, 'no_handling') except: pass try: existence_test_and_add(self, 'site_service_index_id', self.site_service_index_id, 'no_handling') except: pass try: existence_test_and_add(self, 'export_index_id', self.export_index_id, 'no_handling') except: pass ''' Shred to database ''' shred(self, self.parse_dict, ResourceInfo) ''' Parse sub-tables ''' parse_contact(self, item) parse_email(self, item) parse_phone(self, item) def parse_contact(self, element): ''' Element paths ''' xpContact = 'airs:Contact' xpTitle = 'airs:Title' xpName =
gdal.Open('data/6band_wrong_number_extrasamples.tif') assert gdal.GetLastErrorMsg().find('Wrong number of ExtraSamples') >= 0 assert ds.GetRasterBand(6).GetRasterColorInterpretation() == gdal.GCI_AlphaBand ############################################################################### # Test that we can read a one-trip TIFF without StripByteCounts tag def test_tiff_read_one_strip_no_bytecount(): gdal.PushErrorHandler('CPLQuietErrorHandler') ds = gdal.Open('data/one_strip_nobytecount.tif') gdal.PopErrorHandler() assert ds.GetRasterBand(1).Checksum() == 1 ############################################################################### # Test GDAL_GEOREF_SOURCES def test_tiff_read_nogeoref(): tests = [(None, True, True, False, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), (None, True, True, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), (None, False, True, True, 'OSGB_1936', (400000.0, 25.0, 0.0, 1300000.0, 0.0, -25.0)), (None, True, False, False, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), (None, False, True, False, '', (99.5, 1.0, 0.0, 200.5, 0.0, -1.0)), (None, False, False, False, '', (0.0, 1.0, 0.0, 0.0, 0.0, 1.0)), ('INTERNAL', True, True, False, '', (0.0, 1.0, 0.0, 0.0, 0.0, 1.0)), ('INTERNAL,PAM', True, True, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), ('INTERNAL,WORLDFILE', True, True, True, '', (99.5, 1.0, 0.0, 200.5, 0.0, -1.0)), ('INTERNAL,PAM,WORLDFILE', True, True, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), ('INTERNAL,WORLDFILE,PAM', True, True, True, 'LOCAL_CS["PAM"]', (99.5, 1.0, 0.0, 200.5, 0.0, -1.0)), ('WORLDFILE,PAM,INTERNAL', False, False, True, '', (0.0, 1.0, 0.0, 0.0, 0.0, 1.0)), ('PAM,WORLDFILE,INTERNAL', False, False, True, '', (0.0, 1.0, 0.0, 0.0, 0.0, 1.0)), ('TABFILE,WORLDFILE,INTERNAL', True, True, True, 'OSGB_1936', (400000.0, 25.0, 0.0, 1300000.0, 0.0, -25.0)), ('PAM', True, True, False, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), ('PAM,WORLDFILE', True, True, False, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), ('WORLDFILE', True, True, False, '', (99.5, 1.0, 0.0, 200.5, 0.0, -1.0)), ('WORLDFILE,PAM', True, True, False, 'LOCAL_CS["PAM"]', (99.5, 1.0, 0.0, 200.5, 0.0, -1.0)), ('WORLDFILE,INTERNAL', True, True, False, '', (99.5, 1.0, 0.0, 200.5, 0.0, -1.0)), ('WORLDFILE,PAM,INTERNAL', True, True, False, 'LOCAL_CS["PAM"]', (99.5, 1.0, 0.0, 200.5, 0.0, -1.0)), ('WORLDFILE,INTERNAL,PAM', True, True, False, 'LOCAL_CS["PAM"]', (99.5, 1.0, 0.0, 200.5, 0.0, -1.0)), ('NONE', True, True, False, '', (0.0, 1.0, 0.0, 0.0, 0.0, 1.0)), ] for (config_option_value, copy_pam, copy_worldfile, copy_tabfile, expected_srs, expected_gt) in tests: for iteration in range(2): gdal.SetConfigOption('GDAL_GEOREF_SOURCES', config_option_value) gdal.FileFromMemBuffer('/vsimem/byte_nogeoref.tif', open('data/byte_nogeoref.tif', 'rb').read()) if copy_pam: gdal.FileFromMemBuffer('/vsimem/byte_nogeoref.tif.aux.xml', open('data/byte_nogeoref.tif.aux.xml', 'rb').read()) if copy_worldfile: gdal.FileFromMemBuffer('/vsimem/byte_nogeoref.tfw', open('data/byte_nogeoref.tfw', 'rb').read()) if copy_tabfile: gdal.FileFromMemBuffer('/vsimem/byte_nogeoref.tab', open('data/byte_nogeoref.tab', 'rb').read()) ds = gdal.Open('/vsimem/byte_nogeoref.tif') if iteration == 0: gt = ds.GetGeoTransform() srs_wkt = ds.GetProjectionRef() else: srs_wkt = ds.GetProjectionRef() gt = ds.GetGeoTransform() ds = None gdal.SetConfigOption('GDAL_GEOREF_SOURCES', None) gdal.Unlink('/vsimem/byte_nogeoref.tif') gdal.Unlink('/vsimem/byte_nogeoref.tif.aux.xml') gdal.Unlink('/vsimem/byte_nogeoref.tfw') gdal.Unlink('/vsimem/byte_nogeoref.tab') if gt != expected_gt: print('Got ' + str(gt)) print('Expected ' + str(expected_gt)) pytest.fail('Iteration %d, did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile))) if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and expected_srs not in srs_wkt): print('Got ' + srs_wkt) print('Expected ' + expected_srs) pytest.fail('Iteration %d, did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile))) ############################################################################### # Test GDAL_GEOREF_SOURCES def test_tiff_read_inconsistent_georef(): tests = [(None, True, True, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), (None, False, True, True, '26711', (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0)), (None, False, False, True, '26711', (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0)), (None, False, True, False, '26711', (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0)), (None, False, False, False, '26711', (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0)), (None, True, True, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), (None, True, False, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), (None, True, True, False, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), (None, True, False, False, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), ('INTERNAL', True, True, True, '26711', (440720.0, 60.0, 0.0, 3751320.0, 0.0, -60.0)), ('PAM', True, True, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), ('PAM,TABFILE', True, True, True, 'LOCAL_CS["PAM"]', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), ('WORLDFILE', True, True, True, '', (99.5, 1.0, 0.0, 200.5, 0.0, -1.0)), ('TABFILE', True, True, True, 'OSGB_1936', (400000.0, 25.0, 0.0, 1300000.0, 0.0, -25.0)), ('TABFILE,PAM', True, True, True, 'OSGB_1936', (400000.0, 25.0, 0.0, 1300000.0, 0.0, -25.0)), ] for (config_option_value, copy_pam, copy_worldfile, copy_tabfile, expected_srs, expected_gt) in tests: for iteration in range(2): gdal.SetConfigOption('GDAL_GEOREF_SOURCES', config_option_value) gdal.FileFromMemBuffer('/vsimem/byte_inconsistent_georef.tif', open('data/byte_inconsistent_georef.tif', 'rb').read()) if copy_pam: gdal.FileFromMemBuffer('/vsimem/byte_inconsistent_georef.tif.aux.xml', open('data/byte_inconsistent_georef.tif.aux.xml', 'rb').read()) if copy_worldfile: gdal.FileFromMemBuffer('/vsimem/byte_inconsistent_georef.tfw', open('data/byte_inconsistent_georef.tfw', 'rb').read()) if copy_tabfile: gdal.FileFromMemBuffer('/vsimem/byte_inconsistent_georef.tab', open('data/byte_inconsistent_georef.tab', 'rb').read()) ds = gdal.Open('/vsimem/byte_inconsistent_georef.tif') if iteration == 0: gt = ds.GetGeoTransform() srs_wkt = ds.GetProjectionRef() else: srs_wkt = ds.GetProjectionRef() gt = ds.GetGeoTransform() ds = None gdal.SetConfigOption('GDAL_GEOREF_SOURCES', None) gdal.Unlink('/vsimem/byte_inconsistent_georef.tif') gdal.Unlink('/vsimem/byte_inconsistent_georef.tif.aux.xml') gdal.Unlink('/vsimem/byte_inconsistent_georef.tfw') gdal.Unlink('/vsimem/byte_inconsistent_georef.tab') if gt != expected_gt: print('Got ' + str(gt)) print('Expected ' + str(expected_gt)) pytest.fail('Iteration %d, did not get expected gt for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile))) if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and expected_srs not in srs_wkt): print('Got ' + srs_wkt) print('Expected ' + expected_srs) pytest.fail('Iteration %d, did not get expected SRS for %s,copy_pam=%s,copy_worldfile=%s,copy_tabfile=%s' % (iteration, config_option_value, str(copy_pam), str(copy_worldfile), str(copy_tabfile))) ############################################################################### # Test GDAL_GEOREF_SOURCES def test_tiff_read_gcp_internal_and_auxxml(): tests = [(None, True, 'LOCAL_CS["PAM"]', 1), (None, False, '4326', 2), ('INTERNAL', True, '4326', 2), ('INTERNAL', False, '4326', 2), ('INTERNAL,PAM', True, '4326', 2), ('INTERNAL,PAM', False, '4326', 2), ('PAM', True, 'LOCAL_CS["PAM"]', 1), ('PAM', False, '', 0), ('PAM,INTERNAL', True, 'LOCAL_CS["PAM"]', 1), ('PAM,INTERNAL', False, '4326', 2), ] for (config_option_value, copy_pam, expected_srs, expected_gcp_count) in tests: for iteration in range(2): gdal.FileFromMemBuffer('/vsimem/byte_gcp.tif', open('data/byte_gcp.tif', 'rb').read()) if copy_pam: gdal.FileFromMemBuffer('/vsimem/byte_gcp.tif.aux.xml', open('data/byte_gcp.tif.aux.xml', 'rb').read()) open_options = [] if config_option_value is not None: open_options += ['GEOREF_SOURCES=' + config_option_value] ds = gdal.OpenEx('/vsimem/byte_gcp.tif', open_options=open_options) if iteration == 0: gcp_count = ds.GetGCPCount() srs_wkt = ds.GetGCPProjection() else: srs_wkt = ds.GetGCPProjection() gcp_count = ds.GetGCPCount() ds = None gdal.Unlink('/vsimem/byte_gcp.tif') gdal.Unlink('/vsimem/byte_gcp.tif.aux.xml') if gcp_count != expected_gcp_count: print('Got ' + str(gcp_count)) print('Expected ' + str(expected_gcp_count)) pytest.fail('Iteration %d, did not get expected gcp count for %s,copy_pam=%s' % (iteration, config_option_value, str(copy_pam))) if (expected_srs == '' and srs_wkt != '') or (expected_srs != '' and expected_srs not in srs_wkt): print('Got ' + srs_wkt) print('Expected ' + expected_srs) pytest.fail('Iteration %d, did not get expected SRS for %s,copy_pam=%s' % (iteration, config_option_value, str(copy_pam))) ############################################################################### # Test reading .tif + .aux class myHandlerClass(object): def __init__(self): self.msg = None def handler(self, eErrClass, err_no, msg): # pylint: disable=unused-argument if 'File open of' in msg: self.msg = msg def test_tiff_read_aux(): gdal.ErrorReset() ds = gdal.Open('data/f2r23.tif') handler = myHandlerClass() gdal.PushErrorHandler(handler.handler) ds.GetFileList() gdal.PopErrorHandler() assert handler.msg is None, \ ('Got message that indicate recursive calls: %s' % handler.msg) def test_tiff_read_one_band_from_two_bands(): gdal.Translate('/vsimem/tiff_read_one_band_from_two_bands.tif', 'data/byte.tif', options='-b 1 -b 1') gdal.Translate('/vsimem/tiff_read_one_band_from_two_bands_dst.tif', '/vsimem/tiff_read_one_band_from_two_bands.tif', options='-b 1') ds = gdal.Open('/vsimem/tiff_read_one_band_from_two_bands_dst.tif') assert ds.GetRasterBand(1).Checksum() == 4672 ds = None gdal.Unlink('/vsimem/tiff_read_one_band_from_two_bands.tif') gdal.Unlink('/vsimem/tiff_read_one_band_from_two_bands.tif.aux.xml') gdal.Unlink('/vsimem/tiff_read_one_band_from_two_bands_dst.tif') def test_tiff_read_jpeg_cloud_optimized(): for i in range(4): ds = gdal.Open('data/byte_ovr_jpeg_tablesmode%d.tif' % i) cs0 = ds.GetRasterBand(1).Checksum() cs1 = ds.GetRasterBand(1).GetOverview(0).Checksum() assert cs0 == 4743 and cs1 == 1133, i ds = None # This one was generated with a buggy code that emit JpegTables with mode == 1 # when creating the overview directory but failed to properly set this mode while # writing the imagery. libjpeg-6b emits a 'JPEGLib:Huffman table 0x00 was not defined' # error while jpeg-8 works fine def test_tiff_read_corrupted_jpeg_cloud_optimized(): ds = gdal.Open('data/byte_ovr_jpeg_tablesmode_not_correctly_set_on_ovr.tif') cs0 = ds.GetRasterBand(1).Checksum() assert cs0 == 4743 with gdaltest.error_handler(): cs1 = ds.GetRasterBand(1).GetOverview(0).Checksum() if cs1 == 0: print('Expected error while writing overview with libjpeg-6b') elif cs1 != 1133: pytest.fail(cs1) ############################################################################### # Test reading YCbCr images with LZW compression def test_tiff_read_ycbcr_lzw(): tests = [('ycbcr_11_lzw.tif', 13459, 12939, 12414), ('ycbcr_12_lzw.tif', 13565, 13105, 12660), ('ycbcr_14_lzw.tif', 0, 0, 0), # not supported ('ycbcr_21_lzw.tif', 13587, 13297, 12760), ('ycbcr_22_lzw.tif', 13393, 13137, 12656), ('ycbcr_24_lzw.tif', 0, 0, 0), # not supported ('ycbcr_41_lzw.tif', 13218, 12758, 12592), ('ycbcr_42_lzw.tif', 13277, 12779, 12614), ('ycbcr_42_lzw_optimized.tif', 19918, 20120, 19087), ('ycbcr_44_lzw.tif', 12994, 13229, 12149), ('ycbcr_44_lzw_optimized.tif', 19666, 19860, 18836)] for (filename, cs1, cs2, cs3) in tests: ds = gdal.Open('data/' + filename) if cs1 == 0: gdal.PushErrorHandler() got_cs1 = ds.GetRasterBand(1).Checksum() got_cs2 = ds.GetRasterBand(2).Checksum() got_cs3 = ds.GetRasterBand(3).Checksum() if cs1 == 0: gdal.PopErrorHandler() assert got_cs1 == cs1 and got_cs2 == cs2 and got_cs3 == cs3, \ (filename, got_cs1, got_cs2, got_cs3) ############################################################################### # Test reading YCbCr images with nbits > 8 def test_tiff_read_ycbcr_int12(): with gdaltest.error_handler(): ds = gdal.Open('data/int12_ycbcr_contig.tif') assert ds is None assert gdal.GetLastErrorMsg().find('Cannot open TIFF file with') >= 0 ############################################################################### # Test reading band unit from VERT_CS unit (#6675) def test_tiff_read_unit_from_srs(): filename = '/vsimem/tiff_read_unit_from_srs.tif' ds = gdal.GetDriverByName('GTiff').Create(filename, 1, 1) sr = osr.SpatialReference() sr.SetFromUserInput('EPSG:4326+3855') ds.SetProjection(sr.ExportToWkt()) ds = None ds = gdal.Open(filename) unit = ds.GetRasterBand(1).GetUnitType() assert unit == 'metre' ds = None gdal.Unlink(filename) ############################################################################### # Test reading ArcGIS 9.3 .aux.xml def test_tiff_read_arcgis93_geodataxform_gcp(): ds = gdal.Open('data/arcgis93_geodataxform_gcp.tif') assert ds.GetGCPProjection().find('26712') >= 0 assert ds.GetGCPCount() == 16 gcp = ds.GetGCPs()[0] assert (gcp.GCPPixel == pytest.approx(565, abs=1e-5) and \ gcp.GCPLine == pytest.approx(11041, abs=1e-5) and \ gcp.GCPX == pytest.approx(500000, abs=1e-5) and \ gcp.GCPY ==
from __future__ import annotations from dataclasses import dataclass, field from typing import List, Dict, TYPE_CHECKING from reamber.base.Map import Map from reamber.base.lists import TimedList from reamber.sm.SMBpm import SMBpm from reamber.sm.SMConst import SMConst from reamber.sm.SMFake import SMFake from reamber.sm.SMHit import SMHit from reamber.sm.SMHold import SMHold from reamber.sm.SMKeySound import SMKeySound from reamber.sm.SMLift import SMLift from reamber.sm.SMMapMeta import SMMapMeta, SMMapChartTypes from reamber.sm.SMMine import SMMine from reamber.sm.SMRoll import SMRoll from reamber.sm.SMStop import SMStop from reamber.sm.lists.SMBpmList import SMBpmList from reamber.sm.lists.SMNotePkg import SMNotePkg if TYPE_CHECKING: from reamber.sm.SMMapSet import SMMapSet from numpy import gcd import logging log = logging.getLogger(__name__) @dataclass class SMMap(Map, SMMapMeta): """ If you're trying to load using this, use SMMapSet. """ _SNAP_ERROR_BUFFER = 0.001 notes: SMNotePkg = field(default_factory=lambda: SMNotePkg()) bpms: SMBpmList = field(default_factory=lambda: SMBpmList()) def data(self) -> Dict[str, TimedList]: """ Gets the notes and bpms as a dictionary """ return {'notes': self.notes, 'bpms': self.bpms} @staticmethod def readString(noteStr: str, bpms: List[SMBpm], stops: List[SMStop]) -> SMMap: """ Reads the Note part of the SM Map That means including the // Comment, and anything below :param noteStr: The note part :param bpms: BPMs to help sync notes :param stops: Stops to help sync notes :return: """ spl = noteStr.split(":") noteStr = SMMap() noteStr._readNoteMetadata(spl[1:6]) # These contain the metadata # Splits measures by \n and filters out blank + comment entries measures: List[List[str]] =\ [[snap for snap in measure.split("\n") if "//" not in snap and len(snap) > 0] for measure in spl[-1].split(",")] noteStr._readNotes(measures, bpms=bpms, stops=stops) return noteStr def writeString(self) -> List[str]: """ Write an exportable String List to be passed to SMMapset for writing. :return: Exportable String List """ # Tried to use a BPM log.info("StepMania writeString is not stable on MultiBpm cases!") log.info("Start Parsing File") header = [ f"//------{self.chartType}[{self.difficultyVal} {self.difficulty}]------", "#NOTES:", f"\t{self.chartType}:", f"\t{self.description}:", f"\t{self.difficulty}:", f"\t{self.difficultyVal}:", "\t" + ",".join(map(str, self.grooveRadar)) + ":" ] log.info(f"Header {header}") bpmBeats = SMBpm.getBeats(self.bpms, self.bpms) # -------- We will grab all required notes here -------- # List[Tuple[Beat, Column], Char]] notes: List[List[float, int, str]] = [] for snap, ho in zip(SMBpm.getBeats(self.notes.hits(), self.bpms), self.notes.hits()): notes.append([snap, ho.column, SMConst.HIT_STRING]) holdHeads = [] holdTails = [] for head, tail in zip(self.notes.holds().sorted().offsets(),self.notes.holds().sorted().tailOffsets()): holdHeads.append(head) holdTails.append(tail) for snap, ho in zip(SMBpm.getBeats(holdHeads, self.bpms), self.notes.holds()): if isinstance(ho, SMHold): notes.append([snap, ho.column, SMConst.HOLD_STRING_HEAD]) elif isinstance(ho, SMRoll): notes.append([snap, ho.column, SMConst.ROLL_STRING_HEAD]) for snap, ho in zip(SMBpm.getBeats(holdTails, self.bpms), self.notes.holds()): if isinstance(ho, SMHold): notes.append([snap, ho.column, SMConst.HOLD_STRING_TAIL]) elif isinstance(ho, SMRoll): notes.append([snap, ho.column, SMConst.ROLL_STRING_TAIL]) del holdHeads, holdTails notes.sort(key=lambda x: x[0]) # -------- Loop through Bpm -------- # This is where notes are slot into the BPM beats # We loop through the BPMs and find which notes fit # We then remove the fitted notes and repeat # BPM Beat 1 , BPM Beat 2 ... # List[List[Beat, Column, Char]], List[List[Beat, Column, Char]] notesByBpm: List[List[float, int, str]] = [] for bpmBeatIndex in range(len(bpmBeats)): # If we are at the end, we use infinity as the upper bound bpmBeatLower = bpmBeats[bpmBeatIndex] bpmBeatUpper = bpmBeats[bpmBeatIndex + 1] if bpmBeatIndex < len(bpmBeats) - 1 else float("inf") # Filter out placement for this bpm beat noteByBpm: List[List[float, int, str]] = [] noteIndexToRemove = [] for noteIndex, note in enumerate(notes): # We exclude the any notes are that close to the lower BPM Beat else they will repeat if bpmBeatLower - self._SNAP_ERROR_BUFFER <= note[0] < bpmBeatUpper + self._SNAP_ERROR_BUFFER: log.info(f"Write Note: Beat {round(note[0], 2)}, Column {note[1]}, Char {note[2]} set in " f"{round(bpmBeatLower, 1)} - {round(bpmBeatUpper, 1)}") noteByBpm.append(note) noteIndexToRemove.append(noteIndex) # Remove filtered out objects noteIndexToRemove.reverse() # We need to reverse the list to retain correct indexes for index in noteIndexToRemove: del notes[index] # faster than pop # Zeros the measure and converts it into snap units noteByBpm = [[round(m * 48), c, ch] for m, c, ch in noteByBpm] notesByBpm += noteByBpm del noteByBpm, notes, bpmBeatIndex, bpmBeatUpper, bpmBeatLower, note, noteIndexToRemove, index notesByBpm.sort(key=lambda item: item[0]) # -------- Fit into Measures -------- # After finding which notes belong to which BPM # We cut them into measures then slot them in # Note that we want to have the smallest size template before slotting # That's where GCD comes in handy. measures = [[] for _ in range(int(notesByBpm[-1][0] / 192) + 1)] keys = SMMapChartTypes.getKeys(self.chartType) for note in notesByBpm: measures[int(note[0] / 192)].append(note) measuresStr = [] for measureIndex, measure in enumerate(measures): log.info(f"Parse Measure {measureIndex}\t{measure}") measure = [[snap % 192, col, char] for snap, col, char in measure] log.info(f"Zero Measure\t\t{measure}") if len(measure) != 0: # Using GCD, we can determine the smallest template to use gcd_ = gcd.reduce([x[0] for x in measure]) if gcd_ == 0: snapsReq: int = 4 else: snapsReq: int = int(192 / gcd_) log.info(f"Calc Snaps Req.\t{int(snapsReq)}") if snapsReq == 3: snapsReq = 6 # Min 6 snaps to represent if snapsReq < 4: snapsReq = 4 # Min 4 snaps to represent log.info(f"Final Snaps Req.\t{int(snapsReq)}") # This the template created to slot in notes measure = [[int(snap/(192/snapsReq)), col, char] for snap, col, char in measure] measureStr = [['0' for _key in range(keys)] for _snaps in range(int(snapsReq))] log.info(f"Write Measure Input \t\t{measure}") # Note: [Snap, Column, Char] for note in measure: measureStr[note[0]][note[1]] = note[2] else: measureStr = [['0' for _key in range(keys)] for _snaps in range(4)] measuresStr.append("\n".join(["".join(snap) for snap in measureStr])) log.info(f"Finished Parsing Measure") log.info(f"Finished Parsing Notes") return header + ["\n,\n".join(measuresStr)] + [";\n\n"] def _readNotes(self, measures: List[List[str]], bpms: List[SMBpm], stops: List[SMStop]): """ Reads notes from split measures We expect a format of [['0000',...]['0100',...]] :param measures: Measures as 2D List :param bpms: BPMs to help sync :param stops: Stops to help Sync """ globalBeatIndex: float = 0.0 # This will help sync the bpm used currentBpmIndex: int = 0 currentStopIndex: int = -1 offset = bpms[0].offset stopOffsetSum = 0 bpmBeats = SMBpm.getBeats(bpms, bpms) stopBeats = SMBpm.getBeats(stops, bpms) # The buffer is used to find the head and tails # If we find the head, we throw it in here {Col, HeadOffset} # If we find the tail, we extract ^ and clear the Dict then form the Hold/Roll holdBuffer: Dict[int, float] = {} rollBuffer: Dict[int, float] = {} for measure in measures: for beatIndex in range(4): # Grabs the first beat in the measure beat = measure[int(beatIndex * len(measure) / 4): int((beatIndex + 1) * len(measure) / 4)] # Loop through the beat for snapIndex, snap in enumerate(beat): for columnIndex, columnChar in enumerate(snap): # "Switch" statement for character found if columnChar == "0": continue elif columnChar == SMConst.HIT_STRING: self.notes.hits().append(SMHit(offset + stopOffsetSum, column=columnIndex)) log.info(f"Read Hit at \t\t{round(offset + stopOffsetSum)} " f"at Column {columnIndex}") elif columnChar == SMConst.MINE_STRING: self.notes.hits().append(SMMine(offset + stopOffsetSum, column=columnIndex)) log.info(f"Read Mine at \t\t{round(offset + stopOffsetSum, 2)} " f"at Column {columnIndex}") elif columnChar == SMConst.HOLD_STRING_HEAD: holdBuffer[columnIndex] = offset log.info(f"Read HoldHead at \t{round(offset + stopOffsetSum, 2)} " f"at Column {columnIndex}") elif columnChar == SMConst.ROLL_STRING_HEAD: rollBuffer[columnIndex] = offset log.info(f"Read RollHead at \t{round(offset + stopOffsetSum, 2)} " f"at Column {columnIndex}") elif columnChar == SMConst.ROLL_STRING_TAIL: # ROLL and HOLD tail is the same # Flush out hold/roll buffer if columnIndex in holdBuffer.keys(): startOffset = holdBuffer.pop(columnIndex) self.notes.holds().append(SMHold(startOffset + stopOffsetSum, column=columnIndex, _length=offset - startOffset)) log.info(f"Read HoldTail at \t{round(startOffset + stopOffsetSum, 2)} " f"of length {round(offset - startOffset, 2)} " f"at Column {columnIndex}") elif columnIndex in rollBuffer.keys(): startOffset = rollBuffer.pop(columnIndex) self.notes.holds().append(SMRoll(startOffset + stopOffsetSum, column=columnIndex, _length=offset - startOffset)) log.info(f"Read RollTail at \t{round(startOffset + stopOffsetSum, 2)} " f"of length {round(offset - startOffset, 2)} " f"at Column {columnIndex}") elif columnChar == SMConst.LIFT_STRING: self.notes.hits().append(SMLift(offset=offset + stopOffsetSum, column=columnIndex)) log.info(f"Read Lift at \t\t{round(offset + stopOffsetSum, 2)} " f"at Column {columnIndex}") elif columnChar == SMConst.FAKE_STRING: self.notes.hits().append(SMFake(offset=offset + stopOffsetSum, column=columnIndex)) log.info(f"Read Fake at \t\t{round(offset + stopOffsetSum, 2)} " f"at Column {columnIndex}") elif columnChar == SMConst.KEYSOUND_STRING: self.notes.hits().append(SMKeySound(offset=offset + stopOffsetSum, column=columnIndex)) log.info(f"Read KeySound at \t{round(offset + stopOffsetSum, 2)} " f"at Column {columnIndex}") globalBeatIndex += 4.0 / len(measure) offset += bpms[currentBpmIndex].beatLength() / len(beat) # <- Fraction -> <- Length of Beat -> # Length of Snap # Check if next index exists & check if current beat index is outdated while currentBpmIndex + 1 != len(bpms) and \ globalBeatIndex > bpmBeats[currentBpmIndex + 1] - self._SNAP_ERROR_BUFFER: globalBeatIndex = bpmBeats[currentBpmIndex + 1] currentBpmIndex += 1 #
self._append_error( FESyntaxErrors.CONTAINER_END ) return True else: return False #------------------------------------------------------------------------- def _del_statement(self) -> bool: #======================================================================= # <del statement> ::= 'del' <identifiers list> #======================================================================= if self._current.is_DEL(): self._append_syntaxic_node() self._next_token_node() if not self._identifiers_list(): self._append_error( FESyntaxErrors.DEL_IDENT ) return True else: return False #------------------------------------------------------------------------- def _dimensions(self) -> bool: #======================================================================= # <dimensions> ::= '[' <dimensions'> ']' <dimensions> # | EPS #======================================================================= while self._current.is_BRACKETOP(): self._append_syntaxic_node() self._next_token_node() if not self._dimensions1(): if self._float_number(): self._append_error( FESyntaxErrors.DIMENSION_FLOAT ) else: self._append_error( FESyntaxErrors.DIMENSION_CONST ) if self._current.is_BRACKETCL(): self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.DIMENSION_END ) return True #------------------------------------------------------------------------- def _dimensions1(self) -> bool: #======================================================================= # <dimensions'> ::= <integer number> # | <dotted name> #======================================================================= if self._integer_number(): return True elif self._dotted_name(): return True else: return False #------------------------------------------------------------------------- def _dotted_as_name(self) -> bool: #======================================================================= # <dotted as name> ::= <dotted name> <dotted as name'> #======================================================================= if self._dotted_name(): return self.dotted_as_name1() ## (notice: always returns True) else: return False #------------------------------------------------------------------------- def dotted_as_name1(self) -> bool: #======================================================================= # <dotted as name'> ::= 'as' <identifier> # | EPS #======================================================================= if self._current.is_AS(): self._append_syntaxic_node() self._next_token_node() if not self._identifier(): self._append_error( FESyntaxErrors.AS_IDENT ) return True else: return True #------------------------------------------------------------------------- def _dotted_as_names(self) -> bool: #======================================================================= # <dotted as names> ::= <dotted as name> <dotted as names'> #======================================================================= if self._dotted_as_name(): return self._dotted_as_names1() ## (notice: always returns True) else: return False #------------------------------------------------------------------------- def _dotted_as_names1(self) -> bool: #======================================================================= # <dotted as names'> ::= ',' <dotted as name> <dotted as names'> # | EPS #======================================================================= while self._current.is_COMMA(): self._append_syntaxic_node() self._next_token_node() if not self._dotted_as_name(): self._append_error( FESyntaxErrors.DOTTED_AS ) return True #------------------------------------------------------------------------- def _dotted_name(self) -> bool: #======================================================================= # <dotted name> ::= <identifier> <dotted name'> #======================================================================= if self._identifier(): return self._dotted_name1() ## (notice: always returns True) else: return False #------------------------------------------------------------------------- def _dotted_name1(self) -> bool: #======================================================================= # <dotted name'> ::= '.' <identifier> <dotted name'> # | EPS #======================================================================= while self._current.is_DOT(): self._append_syntaxic_node() self._next_token_node() if not self.identifier(): self._append_error( FESyntaxErrors.DOTTED_IDENT ) return True #------------------------------------------------------------------------- def _ellipsis(self) -> bool: #======================================================================= # <ellipsis> ::= '...' #======================================================================= if self._current.is_ELLIPSIS(): self._append_syntaxic_node() self._next_token_node() return True else: return False #------------------------------------------------------------------------- def _embed_statement(self) -> bool: #======================================================================= # <embed statement> ::= 'embed' <language> <embed statement'> #======================================================================= if self._current.is_EMBED(): self._append_syntaxic_node() self._next_token_node() if not self._language(): self._append_error( FESyntaxErrors.EMBEDDED_LANGUAGE ) if not self._embed_statement1(): self._append_error( FESyntaxErrors.EMBEDDED_LANGUAGE_CODE ) return True else: return False #------------------------------------------------------------------------- def _embed_statement1(self) -> bool: #======================================================================= # <embed statement'> ::= <dotted name> <simple statement end> # | <embedded language code> #======================================================================= if self._dotted_name(): if self._simple_statement_end(): self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.STATEMENT_END ) return True elif self._embedded_language_code(): return True else: return False #------------------------------------------------------------------------- def _embedded_language_code(self) -> bool: #=================================================================== # <embedded language code> ::= '{{' <embedded language code'> # <embedded language code'> ::= <any embedded code char> <embeded language code'> # | '}' <embedded language code"> # <embedded language code"> ::= <any embedded code char> <embeded language code'> # | '}' <embedded language exit> #=================================================================== if self._current.is_EMBED_CODE(): ## (notice: previously scanned by the Scanner) self._append_syntaxic_node() self._next_token_node() return self._embedded_language_exit() elif self._current.is_UNEXPECTED(): self._append_syntaxic_node() self._next_token_node() self._append_error( FESyntaxErrors.EMBEDDED_CODE_END ) return True else: return False #------------------------------------------------------------------------- def _embedded_language_exit(self) -> bool: #======================================================================= # <embedded language exit> ::= 'exit' # | EPS #======================================================================= if self._current.is_EXIT(): self._append_syntaxic_node() self._next_token_node() return True #------------------------------------------------------------------------- def _empty_statement(self) -> bool: #======================================================================= # <empty statement> ::= <comment> # | <NEWLINE> #======================================================================= if self._current.is_COMMENT() or self._current.is_COMMENT_ML(): ## (notice: previously scanned by Scanner) self._append_syntaxic_node() self._next_token_node() if not self._new_line(): self._append_error( FESyntaxErrors.COMMENT_NL ) return True elif self._current.is_NL(): self._append_syntaxic_node() self._next_token_node() return True else: return False #------------------------------------------------------------------------- def _enclosure(self) -> bool: #======================================================================= # <enclosure> ::= <bracket form> # | <parenthesis form> #======================================================================= return self._bracket_form() or self._parenthesis_form() #------------------------------------------------------------------------- def _end_line(self) -> bool: #======================================================================= # <end line> ::= <NEWLINE> # | <ENDOFFILE> #======================================================================= if self._current.is_NL() or self._current.is_EOF(): self._append_syntaxic_node() self._next_token_node() return True else: return False #------------------------------------------------------------------------- def _end_of_file(self) -> bool: #======================================================================= # <ENDOFFILE> ::= u0x00 #======================================================================= if self._current.is_EOF(): self._append_syntaxic_node() self._next_token_node() return True else: return False #------------------------------------------------------------------------- def _ensure_statement(self) -> bool: #======================================================================= # <ensure statement> ::= 'ensure' <expression> <ensure statement'> #======================================================================= if self._current.is_ENSURE(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.ENSURE_EXPR ) self._ensure_statement1() ##(notice: always returns True) return True else: return False #------------------------------------------------------------------------- def _ensure_statement1(self) -> bool: #======================================================================= # <ensure statement'> ::= ',' <expression> # | EPS #======================================================================= if self._current.is_COMMA(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.ENSURE_COMMA_EXPR ) return True #------------------------------------------------------------------------- def _enum_definition(self) -> bool: #======================================================================= # <enum definition> ::= <enum type> <identifier> '{' <enum list> '}' #======================================================================= if self._current.is_ENUM(): self._append_syntaxic_node() self._next_token_node() if self._current.is_IDENT(): self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.ENUM_IDENT ) if self._current.is_BRACKETOP: self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.ENUM_BRACKET_OP ) if not self._enum_list(): self._append_error( FESyntaxErrors.ENUM_LIST ) if self._current.is_BRACKETCL(): self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.ENUM_BRACKET_CL ) #------------------------------------------------------------------------- def _enum_item(self) -> bool: #======================================================================= # <enum item> ::= <identifier> <enum item'> #======================================================================= if self._current.is_IDENT(): self._append_syntaxic_node() self._next_token_node() return self._enum_item1() else: return False #------------------------------------------------------------------------- def _enum_item1(self) -> bool: #======================================================================= # <enum item'> ::= '=' <expression> # | EPS #======================================================================= if self._current.is_ASSIGN(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.ENUM_EXPR ) return True else: return False #------------------------------------------------------------------------- def _enum_list(self) -> bool: #======================================================================= # <enum list> ::= <enum item> <enum list'> # <enum list'> ::= ',' <enum item> <enum list'> # | EPS #======================================================================= if self._enum_item(): self._append_syntaxic_node() self._next_token_node() while self._current.is_COMMA(): self._append_syntaxic_node() self._next_token_node() if self._enum_item(): self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.ENUM_LIST_ITEM ) return True else: return False #------------------------------------------------------------------------- def _enum_type(self) -> bool: #======================================================================= # <enum type> ::= 'enum' #======================================================================= if self._current.is_ENUM(): self._append_syntaxic_node() self._next_token_node() return True else: return False #------------------------------------------------------------------------- def _exclude_statement(self) -> bool: #======================================================================= # <exclude statement> ::= 'exclude' <languages> '{{' <statements list> '}}' #======================================================================= if self._current.is_EXCLUDE(): self._append_syntaxic_node() self._next_token_node() if not self._languages(): self._append_error( FESyntaxErrors.EXCLUDE_LANGS ) if self._current.is_EMBED_CODE(): self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.EXCLUDE_EMBED ) return True else: return False #------------------------------------------------------------------------- def _expr_list(self) -> bool: #======================================================================= # <expr list> ::= <expression> <expr list'> #======================================================================= return self._expression() and self._expr_list1() #------------------------------------------------------------------------- def _expr_list1(self) -> bool: #======================================================================= # <expr list'> ::= ',' <expression> <expr list'> # | EPS #======================================================================= while self._current.is_COMMA(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.LIST_COMMA_EXPR ) return True #------------------------------------------------------------------------- def _expression(self) -> bool: #======================================================================= # <expression> ::= <condition> # | <unnamed func> #======================================================================= if self._condition(): return True elif self._unnamed_func(): return True else: return False #------------------------------------------------------------------------- def _factor(self) -> bool: #======================================================================= # <factor> ::= <atom element> <factor'> #======================================================================= if self._atom_element(): self._factor1() return True else: return False #------------------------------------------------------------------------- def _factor1(self) -> bool: #======================================================================= # <factor'> ::= '**' <template args> <unary expr> # | '^^' <template args> <unary expr> # | EPS #======================================================================= if self._current.is_POWER(): self._append_syntaxic_node() self._next_token_node() self._template_args() if not self._unary_expr(): self._append_error( FESyntaxErrors.POWER_EXPR ) return True #------------------------------------------------------------------------- def _false(self) -> bool: #======================================================================= # <FALSE> ::= 'False' # | 'false' #======================================================================= if self._current.is_FALSE(): self._append_syntaxic_node() self._next_token_node() return True else: return False #------------------------------------------------------------------------- def _file_endianness(self) -> bool: #======================================================================= # <file endianness> ::= '<' <expression> <file endianness'> # | '>' <expression> <file endianness'> #======================================================================= if self._current.is_LT() or self._current.is_GT(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.FILE_ENDIAN_EXPR ) self._file_endianness1() return True else: return False #------------------------------------------------------------------------- def _file_endianness1(self) -> bool: #======================================================================= # <file endianness'> ::= '<<' <expression> <file endianness'> # | '>>' <expression> <file endianness'> # | '>>>' <expression> <file endianness'> # | EPS #======================================================================= while self._current.is_SHIFTL() or \ self._current.is_SHIFTR() or \ self._current.is_SHIFT0R(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.FILE_STREAM_EXPR ) return True #------------------------------------------------------------------------- def _file_flushing(self) -> bool: #======================================================================= # <file flushing> ::= '!' <dotted name> <file flushing'> #======================================================================= if self._current.is_EXCL(): self._append_syntaxic_node() self._next_token_node() if not self._dotted_name(): self._append_error( FESyntaxErrors.FILE_FLUSH_IDENT ) self._file_flushing1(); return True else: return False #------------------------------------------------------------------------- def _file_flushing1(self) -> bool: #======================================================================= # <file flushing'> ::= '(' <expression> <file flushing''> ')' # | '[' <expression> ']' '=' <expression> # | '>>' <expression> # | '>>>' <expression> # | EPS #======================================================================= if self._current.is_PAROP(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.FILE_FLUSH_FUNC_CALL ) self._file_flushing2() if self._current.is_PARCL(): self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.FILE_FLUSH_FUNC_END ) elif self._current.is_BRACKETOP(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.FILE_FLUSH_INDEX ) if self._current.is_BRACKETCL(): self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.FILE_FLUSH_INDEX_END ) if self._current.is_ASSIGN(): self._append_syntaxic_node() self._next_token_node() else: self._append_error( FESyntaxErrors.FILE_FLUSH_INDEX_ASSIGN ) if not self._expression(): self._append_error( FESyntaxErrors.FILE_FLUSH_INDEX_EXPR ) elif self._current.is_SHIFTR(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.FILE_FLUSH_STREAM_EXPR ) elif self._current.is_SHIFT0R(): self._append_syntaxic_node() self._next_token_node() if not self._expression(): self._append_error( FESyntaxErrors.FILE_FLUSH_APPEND_EXPR ) return True #------------------------------------------------------------------------- def file_flushing2(self) -> bool: #======================================================================= # <file flushing''> ::= ',' <expression> <file flushing'> # | EPS #======================================================================= if self._current.is_COMMA():
<reponame>ORANGE-XFM/Cloudnet-TOSCA-toolbox<gh_stars>10-100 ###################################################################### # # Software Name : Cloudnet TOSCA toolbox # Version: 1.0 # SPDX-FileCopyrightText: Copyright (c) 2020-21 Orange # SPDX-License-Identifier: Apache-2.0 # # This software is distributed under the Apache License 2.0 # the text of which is available at http://www.apache.org/licenses/LICENSE-2.0 # or see the "LICENSE-2.0.txt" file for more details. # # Author: <NAME> <<EMAIL>> # Software description: TOSCA to Cloudnet Translator ###################################################################### import datetime import logging # for logging purposes. import os import re from copy import deepcopy import cloudnet.tosca.configuration as configuration import cloudnet.tosca.syntax as syntax from cloudnet.tosca.diagnostics import diagnostic from cloudnet.tosca.processors import CEND, CRED, Checker from cloudnet.tosca.utils import merge_dict, normalize_dict profiles_directory = "file:" + os.path.dirname(__file__) + "/profiles" TYPE_SYSTEM = "TypeSystem" TOSCA_NORMATIVE_TYPES = "tosca_normative_types" DEFAULT_TOSCA_NORMATIVE_TYPES = "default_tosca_normative_types" SHORT_NAMES = "short_names" configuration.DEFAULT_CONFIGURATION[TYPE_SYSTEM] = { TOSCA_NORMATIVE_TYPES: { "tosca_simple_yaml_1_0": profiles_directory + "/tosca_simple_yaml_1_0/types.yaml", "tosca_simple_yaml_1_1": profiles_directory + "/tosca_simple_yaml_1_1/types.yaml", "tosca_simple_yaml_1_2": profiles_directory + "/tosca_simple_yaml_1_2/types.yaml", "tosca_simple_yaml_1_3": profiles_directory + "/tosca_simple_yaml_1_3/types.yaml", }, DEFAULT_TOSCA_NORMATIVE_TYPES: "tosca_simple_yaml_1_2", SHORT_NAMES: { # TODO: separate short names for TOSCA 1.0, TOSCA 1.1, TOSCA 1.2 and TOSCA 1.3 "AttachesTo": "tosca.relationships.AttachesTo", "BlockStorage": "tosca.nodes.BlockStorage", # TODO warning not same in 1.0 and 1.2 Storage. removed "ObjectStorage": "tosca.nodes.ObjectStorage", "Compute": "tosca.nodes.Compute", "ConnectsTo": "tosca.relationships.ConnectsTo", "Database": "tosca.nodes.Database", "DBMS": "tosca.nodes.DBMS", "DependsOn": "tosca.relationships.DependsOn", "Deployment.Image.VM": "tosca.artifacts.Deployment.Image.VM", "Endpoint": "tosca.capabilities.Endpoint", "LoadBalancer": "tosca.nodes.LoadBalancer", "HostedOn": "tosca.relationships.HostedOn", "Node": "tosca.capabilities.Node", "PortDef": "tosca.datatypes.network.PortDef", "PortInfo": "tosca.datatypes.network.PortInfo", "PortSpec": "tosca.datatypes.network.PortSpec", "SoftwareComponent": "tosca.nodes.SoftwareComponent", "Root": "tosca.nodes.Root", "WebApplication": "tosca.nodes.WebApplication", "WebServer": "tosca.nodes.WebServer", "tosca:Compute": "tosca.nodes.Compute", "tosca:WebApplication": "tosca.nodes.WebApplication", # TODO: must be completed with all short names "tosca.nodes.ObjectStorage": "tosca.nodes.Storage.ObjectStorage", # TODO remove later "tosca.nodes.BlockStorage": "tosca.nodes.Storage.BlockStorage", # TODO remove later }, # predefined workflows "predefined_workflows": { "deploy": {}, "undeploy": {}, }, } configuration.DEFAULT_CONFIGURATION["logging"]["loggers"][__name__] = { "level": "INFO", } LOGGER = logging.getLogger(__name__) class TypeSystem(object): """ TOSCA Type System. """ def __init__(self, configuration): self.types = {} self.merged_types = {} self.artifact_types = {} self.data_types = { # YAML types "string": {}, "integer": {}, "float": {}, "boolean": {}, "timestamp": {}, "null": {}, # TOSCA types "version": {}, "range": {}, "list": {}, "map": {}, "scalar-unit.size": {}, "scalar-unit.time": {}, "scalar-unit.frequency": {}, "scalar-unit.bitrate": {}, } self.capability_types = {} self.interface_types = {} self.requirement_types = {} self.relationship_types = {} self.node_types = {} self.group_types = {} self.policy_types = {} self.artifact_types_by_file_ext = {} self.short_names = configuration.get(TYPE_SYSTEM, SHORT_NAMES) def is_yaml_type(self, type_name): return type_name in [ "string", "integer", "float", "boolean", "timestamp", "null", "version", ] def get_type_uri(self, short_type_name): result = short_type_name if self.types.get(short_type_name) is None: type_name = self.short_names.get(short_type_name) if type_name is not None: result = self.get_type_uri(type_name) return result def get_type(self, type_name): result = self.types.get(type_name) if result is None: type_name = self.short_names.get(type_name) if type_name is not None: result = self.get_type(type_name) return result def is_derived_from(self, type_name, derived_from_type_name): if type_name is None: return False # normalize short names type_name = self.get_type_uri(type_name) derived_from_type_name = self.get_type_uri(derived_from_type_name) # if type_name == derived_from_type_name: return True type_type = self.get_type(type_name) if type_type is None: return False return self.is_derived_from( type_type.get(syntax.DERIVED_FROM), derived_from_type_name ) def merge_type(self, type_name): if type_name is None: raise ValueError("type_name is None") # Search the result in the cache. result = self.merged_types.get(type_name) if result is not None: return result result = self.get_type(type_name) if result is None: # TBR LOGGER.error(CRED + type_name + ' unknown!' + CEND) # diagnostic(gravity="error", file="", message=type_name + " unknown!", cls="TypeSystem",value=type_name ) # TBR also ? diagnostic(gravity='error', file="", message=type_name + ' unknown!', cls='TypeSystem') return dict() requirements = result.get(syntax.REQUIREMENTS) if requirements: result[syntax.REQUIREMENTS] = normalize_dict(requirements) derived_from = result.get(syntax.DERIVED_FROM) if derived_from is None or self.is_derived_from(derived_from, type_name): result = deepcopy(result) requirements = result.get(syntax.REQUIREMENTS) if requirements: result[syntax.REQUIREMENTS] = normalize_dict(requirements) else: # TBR if not self.is_yaml_type(derived_from): tmp = self.merge_type(derived_from) result = merge_dict(tmp, result) # Store the result in the cache. self.merged_types[type_name] = result return result def merge_node_type(self, node_type_name): result = self.merge_type(node_type_name) result = deepcopy(result) interfaces = result.get(syntax.INTERFACES) if interfaces: for (interface_name, interface_yaml) in interfaces.items(): interface_type = self.get_type(syntax.get_type(interface_yaml)) if interface_type: interfaces[interface_name] = merge_dict( interface_type, interfaces[interface_name] ) for (capability_name, capability_yaml) in syntax.get_capabilities( result ).items(): if isinstance(capability_yaml, dict): value = capability_yaml.get( "value" ) # TODO: rename 'value' to '_old_value_' if value is not None: capability_yaml[syntax.TYPE] = value return result def get_artifact_type_by_file_ext(self, file_ext): return self.artifact_types_by_file_ext.get(file_ext) # TOSCA scalar units. SCALAR_SIZE_UNITS = { "B": 1, # byte "kB": 1000, # kilobyte "KiB": 1024, # kibibyte "MB": 1000000, # megabyte "MiB": 1048576, # mebibyte "GB": 1000000000, # gigabyte "GiB": 1073741824, # gibibyte "TB": 1000000000000, # terabyte "TiB": 1099511627776, # tebibyte } SCALAR_TIME_UNITS = { "d": 86400, # day "h": 3600, # hour "m": 60, # minute "s": 1, # second "ms": 10 ** -3, # millisecond "us": 10 ** -6, # microsecond "ns": 10 ** -9, # nanosecond } SCALAR_FREQUENCY_UNITS = { "Hz": 1, # Hertz "kHz": 10 ** 3, # Kilohertz "MHz": 10 ** 6, # Megahertz "GHz": 10 ** 9, # Gigahertz } SCALAR_BITRATE_UNITS = { "bps": 1, # bit per second "Kbps": 1000, # kilobit (1000 bits) per second "Kibps": 1024, # kibibits (1024 bits) per second "Mbps": 1000000, # megabit (1000000 bits) per second "Mibps": 1048576, # mebibit (1048576 bits) per second "Gbps": 1000000000, # gigabit (1000000000 bits) per second "Gibps": 1073741824, # gibibits (1073741824 bits) per second "Tbps": 1000000000000, # terabit (1000000000000 bits) per second "Tibps": 1099511627776, # tebibits (1099511627776 bits) per second "Bps": 8, # byte per second "KBps": 8 * 1000, # kilobyte (1000 bytes) per second "KiBps": 8 * 1024, # kibibytes (1024 bytes) per second "MBps": 8 * 1000000, # megabyte (1000000 bytes) per second "MiBps": 8 * 1048576, # mebibyte (1048576 bytes) per second "GBps": 8 * 1000000000, # gigabyte (1000000000 bytes) per second "GiBps": 8 * 1073741824, # gibibytes (1073741824 bytes) per second "TBps": 8 * 1000000000000, # terabytes (1000000000000 bytes) per second "TiBps": 8 * 1099511627776, # tebibytes (1099511627776 bytes) per second } def array_to_string_with_or_separator(a_list): return str(a_list).replace("['", "").replace("']", "").replace("', '", " or ") SCALAR_UNIT_RE = re.compile("^([0-9]+(\.[0-9]+)?)( )*([A-Za-z]+)$") def split_scalar_unit(a_string, units): match = SCALAR_UNIT_RE.fullmatch(a_string) if match is None: raise ValueError("<scalar> <unit> expected instead of " + a_string) values = [match.group(1), match.group(4)] try: scalar = float(values[0]) except ValueError: raise ValueError("<scalar> expected instead of " + values[0]) if scalar < 0: raise ValueError("positive <scalar> expected instead of " + str(scalar)) unit = values[1] if units.get(unit) is None: raise ValueError( array_to_string_with_or_separator(list(units.keys())) + " expected instead of " + unit ) return scalar, unit def check_scalar_unit(a_string, units): scalar, unit = split_scalar_unit(a_string, units) return True def normalize_scalar_unit(a_string, units): scalar, unit = split_scalar_unit(a_string, units) return scalar * units.get(unit) VERSION_RE = re.compile("^([0-9]+)\.([0-9]+)(((\.[0-9]+)?)(\.[A-Za-z]+(\-[0-9]+)?)?)?$") def check_version(a_string): return VERSION_RE.fullmatch(a_string) is not None class AbstractTypeChecker(object): def __init__(self, type_name): self.type_name = type_name def check_type(self, value, processor, context_error_message): raise NotImplementedError() class BasicTypeChecker(AbstractTypeChecker): def __init__(self, type_name, lambda_expression): AbstractTypeChecker.__init__(self, type_name) self.lambda_expression = lambda_expression def check_type(self, value, processor, context_error_message): try: if not self.lambda_expression(value): processor.error( context_error_message + ": " + str(value) + " - " + self.type_name + " expected", value, ) return False except ValueError as exc: processor.error( context_error_message + ": " + str(value) + " - " + str(exc), value ) return False return True class ListTypeChecker(AbstractTypeChecker): def __init__(self, type_checker, item_type_checker): AbstractTypeChecker.__init__(self, type_checker.type_name) self.type_checker = type_checker self.item_type_checker = item_type_checker def check_type(self, the_list, processor, context_error_message): if self.type_checker.check_type(the_list, processor, context_error_message): idx = 0 result = True for item in the_list: if not self.item_type_checker.check_type( item, processor, context_error_message + "[" + str(idx) + "]" ): result = False idx += 1 return result return False class MapTypeChecker(AbstractTypeChecker): def __init__(self, type_checker, key_type_checker, value_type_checker): AbstractTypeChecker.__init__(self, type_checker.type_name) self.type_checker = type_checker self.key_type_checker = key_type_checker self.value_type_checker = value_type_checker def check_type(self, the_map, processor, context_error_message): if self.type_checker.check_type(the_map, processor, context_error_message): result = True for key, value in the_map.items(): if not self.key_type_checker.check_type( key, processor, context_error_message ): result = False if not self.value_type_checker.check_type( value, processor, context_error_message + ":" + str(key) ): result = False return result return False class DataTypeChecker(AbstractTypeChecker): def __init__(self, data_type_name, data_type): AbstractTypeChecker.__init__(self, data_type_name) self.data_type = data_type def check_type(self, values, processor, context_error_message): if not isinstance(values, dict): processor.error( context_error_message + ": " + str(values) + " - " + self.type_name + " expected", values, ) else: properties = {syntax.PROPERTIES: values} processor.iterate_over_map_of_assignments( processor.check_value_assignment, syntax.PROPERTIES, properties, self.data_type, self.type_name, context_error_message, ) processor.check_required_properties( properties, self.data_type, context_error_message ) isInt = lambda value: not isinstance(value, bool) and isinstance(value, int) BASIC_TYPE_CHECKERS = { # YAML types "string": BasicTypeChecker("string", lambda value: isinstance(value, str)), "integer": BasicTypeChecker("integer", lambda value: isInt(value)), "float": BasicTypeChecker( "float", lambda value: isinstance(value, float) or isInt(value) ), "boolean": BasicTypeChecker("boolean", lambda value: isinstance(value, bool)), "timestamp": BasicTypeChecker( "timestamp", lambda value: isinstance(value, datetime.datetime) or (isinstance(value, str) and datetime.datetime.fromisoformat(value)), ), "null": BasicTypeChecker("null", lambda value: value is None), # TOSCA
("Gibbs time") print "Events per sec = ", (st['nevents'] / secs) print print "TOT_MC ", for x in tot: print " %.10f" % x, print print "TOT_GIB ", for x in tot_gibbs: print " %.10f" % x, print def test_mm1_response_stationary (self): sampling.set_seed(2334) net = self.mm1 nt = 250 pct = 0.1 nreps = 10 giter = 25 self.test_response_stationarity (net, nt, pct, nreps, giter) def test_mm3_response_stationary (self): sampling.set_seed(2334) net = self.mm3 nt = 250 pct = 0.1 nreps = 1 giter = 25 self.test_response_stationarity (net, nt, pct, nreps, giter) def test_mm3_multiinit_response_stationary (self): sampling.set_seed(2334) net = self.mm3 nt = 50 pct = 0.2 nreps = 10 giter = 100 self.test_response_stationarity (net, nt, pct, nreps, giter, resample_gold=False) def test_ln1b_response_stationary (self): sampling.set_seed(2334) net = self.ln1b nt = 50 pct = 0.2 nreps = 10 giter = 25 self.test_response_stationarity (net, nt, pct, nreps, giter) def test_lnk_response_stationary (self): sampling.set_seed(2334) net = self.lnk nt = 250 pct = 0.2 nreps = 10 giter = 25 # qnet.set_use_rtp(1) self.test_response_stationarity (net, nt, pct, nreps, giter) def test_ln3tier_response_stationary (self): sampling.set_seed(2334) net = self.ln3tier nt = 1 pct = 0.0 nreps = 10000 giter = 10 # qnet.set_use_rtp(1) # BAR # queues.set_proposal(queues.BAR_PROPOSAL) # qnet.set_sampler ("ARS_PWFUN") # END BAR # ZOID queues.set_proposal(queues.ZOID_PROPOSAL) qnet.set_sampler ("ARS_PWFUN") # END ZOID # queues.set_proposal(queues.TWOS_PROPOSAL) self.test_response_stationarity (net, nt, pct, nreps, giter, final_only=True) def test_response_stationarity (self, net, nt, pct, nreps, giter, resample_gold=True, do_init=False, do_report=False, final_only=False): params = net.parameters[:] tot_gold_mrt = numpy.zeros (net.num_queues()) tot_sampled_mrt = numpy.zeros (net.num_queues()) tot_gold_mst = numpy.zeros (net.num_queues()) tot_sampled_mst = numpy.zeros (net.num_queues()) arrv = None for rep in range(nreps): net.parameters = params[:] if not arrv or resample_gold: arrv = net.sample(nt) print "GOLD ARRIVALS" print arrv obs = arrv.subset_by_task (pct, adapt_fn=test_qnet.copy_evt) if final_only: for e in obs: if not obs.is_final(e): e.obs = True if do_report: f = open ("tmh_gold_%d.txt" % rep, "w") qstats.write_arrv (f, obs) f.close() tot_gold_mrt += qstats.mean_response_time (arrv) tot_gold_mst += qstats.mean_service (arrv) if do_init: initial = net.gibbs_initialize (obs.duplicate()) print "INITIALIZATION" print initial initial.validate() else: initial = obs.duplicate() def do_write_arrv_text (net, arrv, iter): if do_report: f = open ("tmh_arrv_%d_%d.txt" % (rep, iter), "w") qstats.write_arrv (f, arrv) f.close () resampled = net.gibbs_resample(initial, burn=0, num_iter=giter, return_arrv=True, report_fn=do_write_arrv_text) arrvl = resampled # resampled = net.gibbs_resample (initial, burn=0, num_iter=giter, return_arrv=True) # mus, arrvl = estimation.sem (net, initial, burn=0, num_iter=giter) # for i in xrange(len(arrvl)): # print "ARRIVALS %d" % i # print arrvl[i] print "FINAL" print arrvl[-1] print "PARAMS: ", net.parameters print "SERVICE:" print "GOLD (OBS) ", qstats.mean_obs_service (obs) print "GOLD ", qstats.mean_service (arrv) print "RESAMPLED ", qstats.mean_service (arrvl[-1]) print "RESPONSE:" print "GOLD (OBS) ", qstats.mean_obs_response (obs) print "GOLD ", qstats.mean_response_time (arrv) print "RESAMPLED ", qstats.mean_response_time (arrvl[-1]) print "MU" for i in xrange(len(arrvl)): print i, qstats.mean_service (arrvl[i]) # resampled = net.gibbs_resample (arrvl[-1], burn=0, num_iter=giter, return_arrv=True) tot_sampled_mrt += qstats.mean_response_time (resampled[-1]) tot_sampled_mst += qstats.mean_service (resampled[-1]) print resampled[-1] print qnet.stats() print "AVG_MRT_GOLD ", tot_gold_mrt / nreps print "AVG_MRT_SAMPLED ", tot_sampled_mrt / nreps print "AVG_MST_GOLD ", tot_gold_mst / nreps print "AVG_MST_SAMPLED ", tot_sampled_mst / nreps def test_ars_vs_slice (self): sampling.set_seed (178) net = self.mm3 nt = 5 nreps = 1000 arrv = net.sample (nt) eid = 6 eid_next = 13 e = arrv.event (eid) e_next = arrv.event (eid_next) e.obs = 0 e_next.obs = 0 print arrv s_ars = [] s_slice = [] qnet.set_sampler ("ARS_PWFUN") for rep in range(nreps): arrvl = net.gibbs_resample (arrv.duplicate(), burn=0, num_iter=1, return_arrv=True) s_ars.append (arrvl[-1].event(eid).d) print "STATS (ARS)" print qnet.stats() qnet.reset_stats() qnet.set_sampler ("SLICE_PWFUN") for rep in range(nreps): arrvl = net.gibbs_resample (arrv.duplicate(), burn=0, num_iter=1, return_arrv=True) s_slice.append (arrvl[-1].event(eid).d) print "STATS (SLICE)" print qnet.stats() # for visualization d_fn = e.queue().departure_proposal (arrv, e) a_fn = e_next.queue().arrival_proposal (arrv, e_next) fn = pwfun.add (a_fn, d_fn) print e print e_next print d_fn.dump_table() print a_fn.dump_table() print fn.dump_table() limits = fn.range() rng = limits[1] - limits[0] if numpy.isinf (rng): rng = 100.0 x = limits[0] for i in xrange(1000): print "FN %.5f %.5f" % (x, fn(x)) x += rng/1000 s_ars.sort() s_slice.sort() for d_ars, d_sl in zip(s_ars, s_slice): print "D", d_ars, d_sl netutils.check_quantiles (self, s_ars, s_slice, nreps) def test_single_departure (self): sampling.set_seed (178) net = self.mm3 nt = 5 nreps = 100 d_ex = [] d_gibbs = [] giter = 1 for rep in xrange(nreps): arrv = net.sample (nt) evts = arrv.events_of_task (2) e = evts[1] e_next = evts[2] d_ex.append (e.d) e.obs = 0 e_next.obs = 0 for i in xrange(giter): arrvl = net.gibbs_resample (arrv, burn=0, num_iter=1) arrv = arrvl[-1] evts = arrv.events_of_task (2) e = evts[1] e_next = evts[2] d_gibbs.append (e.d) netutils.check_quantiles (self, d_ex, d_gibbs, nreps) print qnet.stats() def test_ln3tier_via_slice (self): sampling.set_seed(2334) net = self.ln3tier nt = 250 self.do_test_via_slice(net, nt, lambda arrv: arrv.events_of_qid(1)[0]) def test_ln3tier_zoid_slice (self): sampling.set_seed(2334) net = self.ln3tier nt = 250 queues.set_proposal(queues.ZOID_PROPOSAL) qnet.set_sampler ("ARS_PWFUN") self.do_test_via_slice(net, nt, lambda arrv: arrv.events_of_qid(1)[0]) def test_mm020_slice (self): sampling.set_seed(2334) net = self.mm020 nt = 250 self.do_test_via_slice(net, nt, lambda arrv: arrv.events_of_qid(1)[0]) def do_test_via_slice (self, net, nt, grab_evt): arrv = net.sample (nt) evt5 = grab_evt(arrv) evt5n = evt5.next_by_task() evt5.obs = False evt5n.obs = False print arrv print "Events selected:\n %s\n %s" % (evt5, evt5n) N = 100 alld = [] for i in xrange (N): arrvl = net.gibbs_resample (arrv, burn=0, num_iter=1) evt_rs = arrvl[-1].event (evt5.eid) alld.append (evt_rs.d) d_mean = numpy.mean(alld) prp = queues.pair_proposal (arrv, evt5, evt5n) a,b = prp.range() xs = list(random.uniform (a, b, size=N)) ws = [] for x in xs: dl = evt5.queue().pyDiffListForDeparture (evt5, x) dl.extend (evt5n.queue().pyDiffListForArrival (evt5n, x)) arrv.applyDiffList (dl) evt5.d = x evt5n.a = x ws.append(net.log_prob (arrv) - numpy.log(b-a)) Z = logsumexp(ws) Ws = [ numpy.exp(w - Z) for w in ws ] print "Z = ", Z sum = 0 for w,x in zip(Ws,xs): sum += w*x mc_mean = sum print qnet.stats() print "Sample mean = ", d_mean print "MCINT mean = ", mc_mean f = open("prp-zoid.txt", "w") L,U = prp.range() eps = (U-L)/1000 x = L while x < U: f.write ("%.5f %.5f\n" % (x, prp(x))) x += eps f.close() dfn = evt5.queue().pyDepartureLik (arrv, evt5) afn = evt5n.queue().pyArrivalLik (arrv, evt5n) product = pwfun.add(dfn, afn) f = open ("prp-product.txt", "w") L,U = product.range() eps = (U-L)/1000 x = L while x < U: f.write ("%.5f %.5f\n" % (x, product(x))) x += eps f.close() # ZOID DEBUGGING for x in prp.knots(): print "%.5f %.5f %.5f %.5f" % (x, prp(x), product(x), dfn(x)+afn(x)) self.assertTrue (abs(d_mean - mc_mean) < 0.1, "Not close enough") def test_logprob (self): arrvd = self.delay.sample (50) qnetu.write_multif_to_prefix ("tlp.", arrvd) arrvk = qnetu.read_multif_of_prefix ("tlp.", self.delay) lpd = self.delay.log_prob (arrvd) lpk = self.k100.log_prob (arrvk) self.assertTrue ( abs(lpd-lpk) < 1e-5 ) mm3_text = """ states: - name: INITIAL queues: [INITIAL] successors: [TIER1] initial: TRUE - name: TIER1 queues: [ TIER1_0 , TIER1_1 ] successors: [TIER2] - name: TIER2 queues: [ TIER2_0 , TIER2_1 ] successors: [TIER3] - name: TIER3 queues: [ TIER3_0 ] queues: - { name: INITIAL, service: [M, 1.0 ] } - { name: TIER1_0, processors: 5, service: [M, 6] } - { name: TIER1_1, processors: 5, service: [M, 6] } - { name: TIER2_0, processors: 2, service: [M, 3] } - { name: TIER2_1, processors: 2, service: [M, 3] } - { name: TIER3_0, processors: 3, service: [M, 2] } """ mm020_text = """ states: - name: INITIAL queues: [INITIAL] successors: [TIER1] initial: TRUE - name: TIER1 queues: [ TIER1_0 ] successors: [TIER2] - name: TIER2 queues: [ TIER2_0 ] queues: - { name: INITIAL, service: [M, 0.5 ] } - { name: TIER1_0, processors: 100, service: [M, 1.0] } - { name: TIER2_0, processors: 100, service: [M, 1.0] } """ #- { name: TIER2_0, processors: 5, service: [M, 1.0] } #- { name: INITIAL, service: [M, 2.0 ] } #- { name: TIER1_0, processors: 5, service: [M, 2] } #- { name: TIER2_0, processors: 2, service: [M, 0.8] } mm020b_text = """ states: - name: INITIAL queues: [INITIAL] successors: [TIER1] initial: TRUE - name: TIER1 queues: [ TIER1_0 , TIER1_1 ] successors: [TIER2] - name: TIER2 queues: [ TIER2_0 , TIER2_1 ] successors: [TIER3] - name: TIER3 queues: [ TIER3_0 ] queues: - { name: INITIAL, service: [M, 1.0 ] } - { name: TIER1_0, processors: 5, service: [M, 2] } - {
<filename>CrvDatabase/Fibers/Fibers.py # -*- coding: utf-8 -*- ## ## File = "Fibers_2017Jun29.py" ## Derived from File = "Fibers_2016Jun24.py" ## Derived from File = "Fibers_2016Jun10.py" ## Derived from File = "Fibers_2016Jun10.py" ## Derived from File = "Fibers_2016Jun9.py" ## Derived from File = "Fibers_2016Jun8.py" ## Derived from File = "Fibers_2016May27.py" ## Derived from File = "Fibers_2016May23.py" ## Derived from File = "Fibers_2016May12.py" ## Derived from File = "Extrusions_2016Jan27.py" ## Derived from File = "Extrusions_2016Jan26.py" ## Derived File = "Extrusions_2016Jan21.py" ## Derived from File = "Extrusions_2016Jan14.py" ## Derived from File = "Extrusions_2016Jan7.py" ## Derived from File = "Extrusions_2015Oct12.py" ## ## Test program to read in the lines from a comma separated ## file saved from a spread sheet. Here the delimiter is ## a tab and text is enclosed in " ## ## <NAME> ## Department of Physics ## University of South Alabama ## 2015Sep23 ## #!/bin/env python ## ## To run this script: ## $ python Fibers.py -i 'FiberSpreadSheets/Fibers_2017Jun29.csv' -d 0 -m 1 ## ## Modified by cmj 2016Jan7... Add the databaseConfig class to get the URL for ## the various databases... change the URL in this class to change for all scripts. ## Modified by cmj 2016Jan14 to use different directories for support modules... ## These are located in zip files in the various subdirectories.... ## Modified by cmj2016Jan26.... change the maximum number of columns decoded to use variable. ## change code to accomodate two hole positions ## Modified by cmj2016Jun24... Add one more upward level for subdirectory to get to the utilities directory ## for dataloader... place the CRV utilities directory in the "crvUtilities" directory ## Modified by cmj2017Jun29... Add instructions for use in the call of the script. ## Modified by cmj2017Jun29... Add test mode option; option to turn off send to database. ## Modified by cmj2018Jun14... read in new spectrometer spreadsheet format! ## Modified by cmj2018Oct4.... Change the crvUtilities to contain version of cmjGuiLibGrid2018Oct1 that adds ## yellow highlight to selected scrolled list items ## Modified by cmj2020Jul09... change hdbClient_v2_0 -> hdbClient_v2_2 ## Modified by cmj2020Jul09... change crvUtilities2018->crvUtilities; ## Modified by cmj2020Aug03... cmjGuiLibGrid2019Jan30 -> cmjGuiLibGrid (not used) ## Modified by cmj2020Dec16... replace hdbClient_v2_2 with hdbClient_v3_3 - and (&) on query works ## Modified by cmj2021Mar1.... Convert from python2 to python3: 2to3 -w *.py ## Modified by cmj2021Mar1.... replace dataloader with dataloader3 ## Modified by cmj2021May12... replaced tabs with 6 spaces to convert to python 3 ## ## Modified by cmj2022Jan13... add code to enter the new batch of fibers ## ## sendDataBase = 0 ## zero... don't send to database # import os import sys ## import optparse ## parser module... to parse the command line arguments import math from time import * from collections import defaultdict ## this is needed for two dimensional dictionaries sys.path.append("../../Utilities/hdbClient_v3_3/Dataloader.zip") ## 2020Dec16 sys.path.append("../CrvUtilities/crvUtilities.zip") ## 2020Jul09 from DataLoader import * ## module to read/write to database.... from databaseConfig import * from generalUtilities import generalUtilities ## this is needed for three dimensional dictionaries from collections import defaultdict ## needed for two dimensional dictionaries ProgramName = "Fibers.py" Version = "version2022.01.18" ############################################################################################## ############################################################################################## ## Class to read in an fiber cvs file. class readExtrusionCvsFile(object): def __init__(self): if(self.__cmjDebug != 0): print('inside __init__ \n') self.__cmjDebug = 0 def openFile(self,tempFileName): self.__inFileName = tempFileName self.__inFile=open(self.__inFileName,'r') ## read only file def readFile(self): self.__banner = [] self.__inLine = [] self.__fileLine = [] self.__fileLine = self.__inFile.readlines() for self.__newLine in self.__fileLine: print(('%s') % self.__newLine) print('end of readExtrusion') ## ----------------------------------------------------------------- def openFile(self,tempFileName): ## method to open the file self.__inFileName = tempFileName self.__inFile=open(self.__inFileName,'r') ## read only file ############################################################################################## ############################################################################################## ### Class to store fiber elements class fiber(object): def __init__(self): self.__cmjDebug = 0 ## no debug statements self.__maxColumns = 9 ## maximum columns in the spread sheet self.__sendToDatabase = 0 ## Do not send to database self.__database_config = databaseConfig() self.__url = '' self.__password = '' self.__update = 0 # set to 1 to call dataloader in "update mode" ## 2018Jun15... late in the day... self.__fiberId = {} # Dictionary to store the Fiber ID (reel and position) self.__fiberProductionDate = {} self.__fiberSpoolLength = {} self.__fiberCurrentLength = {} self.__fiberType = {} self.__fiberComments = {} self.__vendorDiameter = {} # Dictionary to store vendor's diameter (key fiberId) self.__vendorAttenuation = {} ## Vendor measurements self.__vendorFiberId = {} # Dictionary... fiber_id (key: fiber_id) self.__vendorSpoolEnd = {} # Dictionary... End where mesurment was made (key: fiber_id) self.__vendorAveDiameter = {} # Dictionary... average vendor diameter (key: fiber_id) self.__vendorSigma = {} # Dictionary... sigma of average diameter (key: fiber_id) self.__vendorNumOfBumpsSpool = {} # Dictionary... number of bumps per spool (key: fiber_id) self.__vendorNumOfBumpsKm = {} # Dictionary... number of bumps per km ## nested dictionaries self.__vendorEccentricity = defaultdict(dict) # Nested dictionary [fiber_id][spool_end] self.__vendorAttenuation = defaultdict(dict) # Nested dictionary [fiber_id][spool_end] self.__vendorVoltAt285cm = defaultdict(dict) # Nested dictionary [fiber_id][spool_end] self.__vendorFiberDistance = {} self.__vendorFiberDistanceNumber = {} self.__myMultiDimDictionary = generalUtilities() self.__vendorAttenuationVsLength = self.__myMultiDimDictionary.nestedDict() # Triply nested dictionary: [fiber_id][spool_end][fiberDistance] ## 2018Jun15... late in the day... ## self.__tempMeasurementDate = '' self.__localMeasurementId = {} # Dictionary to store the local measurment Id self.__localMeasurementDate = {} # Dictionary to store the local measurment date self.__localDiameter = {} # Dictiosevenary to store local diameter measurement (key fiber id) self.__localAttenuation = {} # Dictionary to store local attenuation (key fiberId) self.__localLightYield = {} # Dictionary to store local light yield (key fiberId) self.__localTemperature = {} # Dictionary to store local temp measurement (key fiberId) ## ## Variables for the local attenuation measurement ## The local attenuation measurement is reported in ADC counts self.__localMeasurementWavelengthId = {} self.__localMeasurementWavelengthDate = {} ## Nested directories do not work when there are degenearate key values... ## construct and use nested keys.... self.__wavelengthTestDate = 'Null' self.__wavelengthFiberId = {} ## [fiberId] = FiberId self.__wavelength = {} ## dictionary to hold the fiber wavelengths [wavelength] = wavelength ## Nested dictionary to hold the ADC vs attenuation for each fiber_atteuation_tests ## The keys to this dictionary are [fiberId][wavelength] = ADC self.__wavelengthAdc = defaultdict(dict) ## triply nested dictionary to hold the adc counts ## ## ## Variables for the Vendor attenuation measurement ## The vendor attenuation measurment is reported in mVolts. ## So these are placed in a different table! ## self.__vendorAttenuationId = {} self.__vendorAttenuationDate = {} ## Nested directories do not work when there are degenearate key values... ## construct and use nested keys.... self.__vendorAttenuationTestDate = 'Null' self.__vendorAttenuationFiberId = {} ## [fiberId] = FiberId self.__vendorAttenuationDistance = [] ## a list to hold the attenuation distance = attenDistance self.__vendorAttenuationDistanceNumber = [] ## a list to hold the index for the attenuation distance ## Nested dictionary to hold the ADC vs attenuation for each fiber_atteuation_tests ## The keys to this dictionary are [fiberId][testDate][attenuationDistance] = voltage (milliVolts) self.__vendorAttenuationMilliVolt = self.__myMultiDimDictionary.nestedDict() ## triply nested dictionary to hold the adc counts ## ## Variables for the Local attenuation measurement ## The vendor attenuation measurment is reported in mVolts. ## So these are placed in a different table! ## self.__localAttenuationId = {} self.__localAttenuationDate = {} self.__localAttenuationLength = {} ## Nested directories do not work when there are degenearate key values... ## construct and use nested keys.... self.__localAttenuationTestDate = 'Null' ##########self.__localAttenuationFiberIdDictionary = {} ## [fiberId] = FiberId self.__localAttenuationDistance = [] ## dictionary to hold the attenuation distance = attenDistance ## Nested dictionary to hold the ADC vs attenuation for each fiber_atteuation_tests ## The keys to this dictionary are [fiberId][testDate][attenuationDistance] = voltage (milliVolts) self.__localAttenuationAdcCount = self.__myMultiDimDictionary.nestedDict() ## triply nested dictionary to hold the adc counts ## ## ----------------------------------------------------------------- def turnOnDebug(self): self.__cmjDebug = 1 # turn on debug print("...fiber::turnOnDebug... turn on debug \n") ## ----------------------------------------------------------------- def turnOffDebug(self): self.__cmjDebug = 0 # turn on debug print("...fiber::turnOffDebug... turn off debug \n") ## ----------------------------------------------------------------- def setDebugLevel(self,tempDebug): self.__cmjDebug = tempDebug # turn on debug print(("...fiber::setDebugLevel... set debug level: %d \n") % (self.__cmjDebug)) ## ----------------------------------------------------------------- def turnOnSendToDatabase(self): self.__sendToDatabase = 1 ## send to database print(("...fiber::turnOnSendToDataBase... send to database: self.__sendToDatabase = %s \n") % (self.__sendToDatabase)) ## ----------------------------------------------------------------- def turnOffSendToDatabase(self): self.__sendToDatabase = 0 ## send to database print("...fiber::turnOffSendToDatabase... do not send to database \n") ## ----------------------------------------------------------------- def sendToDevelopmentDatabase(self): self.__sendToDatabase = 1 ## send to database self.__whichDatabase = 'development' print("...fiber::sendToDevelopmentDatabase... send to development database \n") self.__url = self.__database_config.getWriteUrl() self.__password = self.__database_config.getFibersKey() ## ----------------------------------------------------------------- def sendToProductionDatabase(self): self.__sendToDatabase = 1 ## send to database self.__whichDatabase = 'production' print("...fiber::sendToProductionDatabase... send to production database \n") self.__url = self.__database_config.getProductionWriteUrl() self.__password = self.__database_config.getFibersProductionKey() ## --------------------------------------------------------------- def updateMode(self): self.__update = 1 ###############################################1############################################### ############################################################################################## ############################################################################################## ### This
if s.is_positive is None]) eq = eq.subs(reps) return eq, dict([(r, s) for s, r in reps.items()]) def _polarify(eq, lift, pause=False): from sympy import polar_lift, Integral if eq.is_polar: return eq if eq.is_number and not pause: return polar_lift(eq) if isinstance(eq, Symbol) and not pause and lift: return polar_lift(eq) elif eq.is_Atom: return eq elif eq.is_Add: r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args]) if lift: return polar_lift(r) return r elif eq.is_Function: return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args]) elif isinstance(eq, Integral): # Don't lift the integration variable func = _polarify(eq.function, lift, pause=pause) limits = [] for limit in eq.args[1:]: var = _polarify(limit[0], lift=False, pause=pause) rest = _polarify(limit[1:], lift=lift, pause=pause) limits.append((var,) + rest) return Integral(*((func,) + tuple(limits))) else: return eq.func(*[_polarify(arg, lift, pause=pause) if isinstance(arg, Expr) else arg for arg in eq.args]) def polarify(eq, subs=True, lift=False): """ Turn all numbers in eq into their polar equivalents (under the standard choice of argument). Note that no attempt is made to guess a formal convention of adding polar numbers, expressions like 1 + x will generally not be altered. Note also that this function does not promote exp(x) to exp_polar(x). If ``subs`` is True, all symbols which are not already polar will be substituted for polar dummies; in this case the function behaves much like posify. If ``lift`` is True, both addition statements and non-polar symbols are changed to their polar_lift()ed versions. Note that lift=True implies subs=False. >>> from sympy import polarify, sin, I >>> from sympy.abc import x, y >>> expr = (-x)**y >>> expr.expand() (-x)**y >>> polarify(expr) ((_x*exp_polar(I*pi))**_y, {_x: x, _y: y}) >>> polarify(expr)[0].expand() _x**_y*exp_polar(_y*I*pi) >>> polarify(x, lift=True) polar_lift(x) >>> polarify(x*(1+y), lift=True) polar_lift(x)*polar_lift(y + 1) Adds are treated carefully: >>> polarify(1 + sin((1 + I)*x)) (sin(_x*polar_lift(1 + I)) + 1, {_x: x}) """ if lift: subs = False eq = _polarify(sympify(eq), lift) if not subs: return eq reps = dict([(s, Dummy(s.name, polar=True)) for s in eq.free_symbols]) eq = eq.subs(reps) return eq, dict([(r, s) for s, r in reps.items()]) def _unpolarify(eq, exponents_only, pause=False): from sympy import polar_lift, exp, principal_branch, pi if isinstance(eq, bool) or eq.is_Atom: return eq if not pause: if eq.func is exp_polar: return exp(_unpolarify(eq.exp, exponents_only)) if eq.func is principal_branch and eq.args[1] == 2*pi: return _unpolarify(eq.args[0], exponents_only) if ( eq.is_Add or eq.is_Mul or eq.is_Boolean or eq.is_Relational and ( eq.rel_op in ('==', '!=') and 0 in eq.args or eq.rel_op not in ('==', '!=')) ): return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args]) if eq.func is polar_lift: return _unpolarify(eq.args[0], exponents_only) if eq.is_Pow: expo = _unpolarify(eq.exp, exponents_only) base = _unpolarify(eq.base, exponents_only, not (expo.is_integer and not pause)) return base**expo if eq.is_Function and getattr(eq.func, 'unbranched', False): return eq.func(*[_unpolarify(x, exponents_only, exponents_only) for x in eq.args]) return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args]) def unpolarify(eq, subs={}, exponents_only=False): """ If p denotes the projection from the Riemann surface of the logarithm to the complex line, return a simplified version eq' of `eq` such that p(eq') == p(eq). Also apply the substitution subs in the end. (This is a convenience, since ``unpolarify``, in a certain sense, undoes polarify.) >>> from sympy import unpolarify, polar_lift, sin, I >>> unpolarify(polar_lift(I + 2)) 2 + I >>> unpolarify(sin(polar_lift(I + 7))) sin(7 + I) """ from sympy import exp_polar, polar_lift if isinstance(eq, bool): return eq eq = sympify(eq) if subs != {}: return unpolarify(eq.subs(subs)) changed = True pause = False if exponents_only: pause = True while changed: changed = False res = _unpolarify(eq, exponents_only, pause) if res != eq: changed = True eq = res if isinstance(res, bool): return res # Finally, replacing Exp(0) by 1 is always correct. # So is polar_lift(0) -> 0. return res.subs({exp_polar(0): 1, polar_lift(0): 0}) def _denest_pow(eq): """ Denest powers. This is a helper function for powdenest that performs the actual transformation. """ b, e = eq.as_base_exp() # denest exp with log terms in exponent if b is S.Exp1 and e.is_Mul: logs = [] other = [] for ei in e.args: if any(ai.func is C.log for ai in Add.make_args(ei)): logs.append(ei) else: other.append(ei) logs = logcombine(Mul(*logs)) return Pow(exp(logs), Mul(*other)) _, be = b.as_base_exp() if be is S.One and not (b.is_Mul or b.is_Rational and b.q != 1 or b.is_positive): return eq # denest eq which is either pos**e or Pow**e or Mul**e or # Mul(b1**e1, b2**e2) # handle polar numbers specially polars, nonpolars = [], [] for bb in Mul.make_args(b): if bb.is_polar: polars.append(bb.as_base_exp()) else: nonpolars.append(bb) if len(polars) == 1 and not polars[0][0].is_Mul: return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e) elif polars: return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \ *powdenest(Mul(*nonpolars)**e) # see if there is a positive, non-Mul base at the very bottom exponents = [] kernel = eq while kernel.is_Pow: kernel, ex = kernel.as_base_exp() exponents.append(ex) if kernel.is_positive: e = Mul(*exponents) if kernel.is_Mul: b = kernel else: if kernel.is_Integer: # use log to see if there is a power here logkernel = expand_log(log(kernel)) if logkernel.is_Mul: c, logk = logkernel.args e *= c kernel = logk.args[0] return Pow(kernel, e) # if any factor is an atom then there is nothing to be done # but the kernel check may have created a new exponent if any(s.is_Atom for s in Mul.make_args(b)): if exponents: return b**e return eq # let log handle the case of the base of the argument being a mul, e.g. # sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we # will take the log, expand it, and then factor out the common powers that # now appear as coefficient. We do this manually since terms_gcd pulls out # fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2; # gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but # we want 3*x. Neither work with noncommutatives. def nc_gcd(aa, bb): a, b = [i.as_coeff_Mul() for i in [aa, bb]] c = gcd(a[0], b[0]).as_numer_denom()[0] g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0])) return _keep_coeff(c, g) glogb = expand_log(log(b)) if glogb.is_Add: args = glogb.args g = reduce(nc_gcd, args) if g != 1: cg, rg = g.as_coeff_Mul() glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args])) # now put the log back together again if glogb.func is C.log or not glogb.is_Mul: if glogb.args[0].is_Pow or glogb.args[0].func is exp: glogb = _denest_pow(glogb.args[0]) if (abs(glogb.exp) < 1) == True: return Pow(glogb.base, glogb.exp*e) return eq # the log(b) was a Mul so join any adds with logcombine add = [] other = [] for a in glogb.args: if a.is_Add: add.append(a) else: other.append(a) return Pow(exp(logcombine(Mul(*add))), e*Mul(*other)) def powdenest(eq, force=False, polar=False): r""" Collect exponents on powers as assumptions allow. Given ``(bb**be)**e``, this can be simplified as follows: * if ``bb`` is positive, or * ``e`` is an integer, or * ``|be| < 1`` then this simplifies to ``bb**(be*e)`` Given a product of powers raised to a power, ``(bb1**be1 * bb2**be2...)**e``, simplification can be done as follows: - if e is positive, the gcd of all bei can be joined with e; - all non-negative bb can be separated from those that are negative and their gcd can be joined with e; autosimplification already handles this separation. - integer factors from powers that have integers in the denominator of the exponent can be removed from any term and the gcd of such integers can be joined with e Setting ``force`` to True will make symbols that are not explicitly negative behave as though they are positive, resulting in more denesting. Setting ``polar`` to True will do simplifications on the riemann surface of the logarithm, also resulting in more denestings. When there are sums of logs in exp() then a product of powers may be obtained e.g. ``exp(3*(log(a) + 2*log(b)))`` - > ``a**3*b**6``. Examples ======== >>> from sympy.abc import a, b, x, y, z >>> from sympy import Symbol, exp, log, sqrt, symbols, powdenest >>> powdenest((x**(2*a/3))**(3*x)) (x**(2*a/3))**(3*x) >>> powdenest(exp(3*x*log(2))) 2**(3*x) Assumptions may prevent expansion: >>> powdenest(sqrt(x**2)) sqrt(x**2) >>> p = symbols('p', positive=True) >>> powdenest(sqrt(p**2)) p No other expansion is done.
and row['address_desc_short'] is not None: gen_row['address_desc_short'] = self.random_alpha_string(20, True) if 'delivery_instructions' in row and row['delivery_instructions'] is not None: gen_row['delivery_instructions'] = self.random_alpha_string(40, True) if 'unit_no' in row and row['unit_no'] is not None: gen_row['unit_no'] = self.random_numeric_string(3) if 'unit_type' in row and row['unit_type'] is not None: gen_row['unit_type'] = self.random_alpha_string(3) if 'civic_no' in row and row['civic_no'] is not None: gen_row['civic_no'] = self.random_numeric_string(3) if 'civic_no_suffix' in row and row['civic_no_suffix'] is not None: gen_row['civic_no_suffix'] = self.random_alpha_string(3) if 'street_name' in row and row['street_name'] is not None: gen_row['street_name'] = self.random_alpha_string(15) if 'street_type' in row and row['street_type'] is not None: gen_row['street_type'] = 'ST' if 'street_direction' in row and row['street_direction'] is not None: gen_row['street_direction'] = 'N' if 'lock_box_no' in row and row['lock_box_no'] is not None: gen_row['lock_box_no'] = self.random_numeric_string(3) if 'installation_type' in row and row['installation_type'] is not None: gen_row['installation_type'] = self.random_alpha_string(3) if 'installation_name' in row and row['installation_name'] is not None: gen_row['installation_name'] = self.random_alpha_string(10) if 'installation_qualifier' in row and row['installation_qualifier'] is not None: gen_row['installation_qualifier'] = self.random_alpha_string(3) if 'route_service_type' in row and row['route_service_type'] is not None: gen_row['route_service_type'] = self.random_alpha_string(3) if 'route_service_no' in row and row['route_service_no'] is not None: gen_row['route_service_no'] = self.random_numeric_string(3) insert_row_vals = [] insert_values = '' i = 0 for key in col_keys: insert_row_vals.append(row[key]) if generate_individual_sql: insert_values = insert_values + self.get_sql_col_value(gen_row[key], desc[i][1]) i = i + 1 if i < len(col_keys): insert_values = insert_values + ', ' inserts.append(insert_row_vals) if generate_individual_sql: insert_sqls.append('insert into ' + table + ' (' + insert_keys + ') values (' + insert_values + ')') insert_sql = 'insert into ' + table + ' (' + insert_keys + ') values (' + insert_placeholders + ')' if generate_individual_sql: self.generated_sqls.append(create_sql) for insert_sql in insert_sqls: self.generated_sqls.append(insert_sql) else: cache_cursor = None try: cache_cursor = self.cache.cursor() cache_cursor.execute(create_sql) if 0 < len(rows): cache_cursor.executemany(insert_sql, inserts) cache_cursor.close() cache_cursor = None except (Exception) as error: LOGGER.error(error) LOGGER.error(traceback.print_exc()) log_error("BCRegistries exception reading DB: " + str(error)) raise finally: if cache_cursor is not None: cache_cursor.close() cache_cursor = None def get_cache_sql(self, sql): cursor = None try: cursor = self.cache.cursor() cursor.execute(sql) desc = cursor.description column_names = [col[0] for col in desc] rows = [dict(zip(column_names, row)) for row in cursor] cursor.close() cursor = None return rows except (Exception) as error: LOGGER.error(error) LOGGER.error(traceback.print_exc()) log_error("BCRegistries exception reading DB: " + str(error)) raise finally: if cursor is not None: cursor.close() cursor = None # run arbitrary sql's (create and insert) to populate in-mem cache # to be used to populate sample data for unit testing # sqls is an array of sql statements def insert_cache_sqls(self, sqls): for sql in sqls: self.insert_cache_sql(sql) # run arbitrary sql's (create and insert) to populate in-mem cache # to be used to populate sample data for unit testing # sql is an individual sql statement (string) def insert_cache_sql(self, sql): cursor = None try: cursor = self.cache.cursor() cursor.execute(sql) cursor.close() cursor = None except (Exception) as error: LOGGER.error(error) LOGGER.error(traceback.print_exc()) log_error("BCRegistries exception reading DB: " + str(error)) raise finally: if cursor is not None: cursor.close() cursor = None # split up a List of id's into a List of Lists of no more than MAX id's def split_list(self, ids, max): ret = [] sub_ids = [] i = 0 for id in ids: sub_ids.append(id) i = i + 1 if i >= max: ret.append(sub_ids) sub_ids = [] i = 0 if 0 < len(sub_ids): ret.append(sub_ids) return ret # create a "where in" clasuse for a List of id's def id_where_in(self, ids, text=False): if text: delimiter = "'" else: delimiter = '' id_list = '' i = 0 for the_id in ids: id_list = id_list + delimiter + the_id + delimiter i = i + 1 if i < len(ids): id_list = id_list + ', ' return id_list ########################################################################### # load all bc registries data for the specified corps into our in-mem cache ########################################################################### code_tables = ['corp_type', 'corp_op_state', 'party_type', 'office_type', 'event_type', 'filing_type', 'corp_name_type', 'jurisdiction_type', 'xpro_type'] corp_tables = ['corporation', 'corp_state', #'tilma_involved', - not currently used 'jurisdiction', 'corp_name'] other_tables = ['corp_party', 'event', 'filing', 'conv_event', 'office', 'address'] # load all bc registries data for the specified corps into our in-mem cache def cache_bcreg_corps(self, specific_corps, generate_individual_sql=False): if self.use_local_cache(): self.cache_bcreg_corp_tables(specific_corps, generate_individual_sql) self.cache_bcreg_code_tables(generate_individual_sql) # load all bc registries data for the specified corps into our in-mem cache def cache_bcreg_corp_tables(self, specific_corps, generate_individual_sql=False): if self.use_local_cache(): LOGGER.info('Caching data for parties and events ...') self.generated_sqls = [] self.generated_corp_nums = {} # ensure we have a unique list specific_corps = list({s_corp for s_corp in specific_corps}) specific_corps_lists = self.split_list(specific_corps, MAX_WHERE_IN) addr_id_list = [] for corp_nums_list in specific_corps_lists: corp_list = self.id_where_in(corp_nums_list, True) corp_party_where = 'bus_company_num in (' + corp_list + ') or corp_num in (' + corp_list + ')' party_rows = self.get_bcreg_table(self.other_tables[0], corp_party_where, '', True, generate_individual_sql) # include all corp_num from the parties just returned (dba related companies) for party in party_rows: specific_corps.append(party['corp_num']) if 'bus_company_num' in party and party['bus_company_num'] is not None and 0 < len(party['bus_company_num']): specific_corps.append(party['bus_company_num']) # ensure we have a unique list specific_corps = list({s_corp for s_corp in specific_corps}) specific_corps_lists = self.split_list(specific_corps, MAX_WHERE_IN) event_ids = [] for corp_nums_list in specific_corps_lists: corp_nums_list = self.id_where_in(corp_nums_list, True) event_where = 'corp_num in (' + corp_nums_list + ')' event_rows = self.get_bcreg_table(self.other_tables[1], event_where, '', True, generate_individual_sql) for event in event_rows: event_ids.append(str(event['event_id'])) # ensure we have a unique list event_ids = list({event_id for event_id in event_ids}) event_ids_lists = self.split_list(event_ids, MAX_WHERE_IN) for ids_list in event_ids_lists: event_list = self.id_where_in(ids_list) filing_where = 'event_id in (' + event_list + ')' _rows = self.get_bcreg_table(self.other_tables[2], filing_where, '', True, generate_individual_sql) _rows = self.get_bcreg_table(self.other_tables[3], filing_where, '', True, generate_individual_sql) LOGGER.info('Caching data for corporations ...') for corp_nums_list in specific_corps_lists: corp_nums_list = self.id_where_in(corp_nums_list, True) corp_num_where = 'corp_num in (' + corp_nums_list + ')' for corp_table in self.corp_tables: _rows = self.get_bcreg_table(corp_table, corp_num_where, '', True, generate_individual_sql) office_where = 'corp_num in (' + corp_nums_list + ')' office_rows = self.get_bcreg_table(self.other_tables[4], office_where, '', True, generate_individual_sql) for office in office_rows: if office['mailing_addr_id'] is not None: addr_id_list.append(str(office['mailing_addr_id'])) if office['delivery_addr_id'] is not None: addr_id_list.append(str(office['delivery_addr_id'])) # ensure we have a unique list addr_id_list = list({addr_id for addr_id in addr_id_list}) addr_ids_lists = self.split_list(addr_id_list, MAX_WHERE_IN) for ids_list in addr_ids_lists: addr_list = self.id_where_in(ids_list) address_where = 'addr_id in (' + addr_list + ')' _rows = self.get_bcreg_table(self.other_tables[5], address_where, '', True, generate_individual_sql) # load all bc registries data for the specified corps into our in-mem cache def cache_bcreg_code_tables(self, generate_individual_sql=False): if self.use_local_cache(): LOGGER.info('Caching data for code tables ...') self.generated_sqls = [] self.generated_corp_nums = {} for code_table in self.code_tables: _rows = self.get_bcreg_table(code_table, '', '', True, generate_individual_sql) # clear in-mem cache - delete all existing data def cache_cleanup(self): for table in self.corp_tables: self.cache_cleanup_data(table) for table in self.other_tables: self.cache_cleanup_data(table) for table in self.code_tables: self.cache_cleanup_data(table) ########################################################################### # utility methods to query bc registries data ########################################################################### # get all records and return in an array of dicts # returns a zero-length array if none found # optionally takes a WHERE clause and ORDER BY clause (must be valid SQL) def get_bcreg_sql(self, table, sql, cache=False, generate_individual_sql=False): cursor = None try: cursor = self.conn.cursor() cursor.execute(sql) desc = cursor.description column_names = [col[0] for col in desc] rows = [dict(zip(column_names, row)) for row in cursor] cursor.close() cursor = None if self.use_local_cache() and cache: self.cache_bcreg_data(table, desc, rows, generate_individual_sql) return rows except (Exception, psycopg2.DatabaseError) as error: LOGGER.error(error) LOGGER.error(traceback.print_exc()) log_error("BCRegistries exception reading DB: " + str(error)) raise finally: if cursor is not None: cursor.close() cursor = None # get all records and return in an array of dicts # returns a zero-length array if none found # optionally takes a WHERE clause and ORDER BY clause (must be valid SQL) def get_bcreg_table(self, table, where="", orderby="", cache=False, generate_individual_sql=False): sql = "SELECT * FROM " + BC_REGISTRIES_TABLE_PREFIX + table if 0 < len(where): sql = sql + " WHERE " + where if 0 < len(orderby): sql = sql + " ORDER BY " + orderby return self.get_bcreg_sql(table, sql, cache, generate_individual_sql) # get all records and return in an array of dicts # returns a zero-length array
overplot_behind or force_line_plot are set the marker size will be double overplot_markersize so the color is visible. assessment_overplot_category : dict Lookup to categorize assessments into groups. This allows using multiple terms for the same quality control level of failure. Also allows adding more to the defaults. assessment_overplot_category_color : dict Lookup to match overplot category color to assessment grouping. force_line_plot : boolean Option to plot 2D data as 1D line plots. labels : boolean or list Option to overwrite the legend labels. Must have same dimensions as number of lines plotted. cbar_label : str Option to overwrite default colorbar label. secondary_y : boolean Option to plot on secondary y axis. **kwargs : keyword arguments The keyword arguments for :func:`plt.plot` (1D timeseries) or :func:`plt.pcolormesh` (2D timeseries). Returns ------- ax : matplotlib axis handle The matplotlib axis handle of the plot. """ if dsname is None and len(self._obj.keys()) > 1: raise ValueError(("You must choose a datastream when there are 2 " "or more datasets in the TimeSeriesDisplay " "object.")) elif dsname is None: dsname = list(self._obj.keys())[0] # Get data and dimensions data = self._obj[dsname][field] dim = list(self._obj[dsname][field].dims) xdata = self._obj[dsname][dim[0]] if 'units' in data.attrs: ytitle = ''.join(['(', data.attrs['units'], ')']) else: ytitle = field if cbar_label is None: cbar_default = ytitle if len(dim) > 1: if use_var_for_y is None: ydata = self._obj[dsname][dim[1]] else: ydata = self._obj[dsname][use_var_for_y] ydata_dim1 = self._obj[dsname][dim[1]] if np.shape(ydata) != np.shape(ydata_dim1): ydata = ydata_dim1 units = ytitle if 'units' in ydata.attrs.keys(): units = ydata.attrs['units'] ytitle = ''.join(['(', units, ')']) else: units = '' ytitle = dim[1] # Create labels if 2d as 1d if force_line_plot is True: if labels is True: labels = [' '.join([str(d), units]) for d in ydata.values] ytitle = f"({data.attrs['units']})" ydata = None else: ydata = None # Get the current plotting axis, add day/night background and plot data if self.fig is None: self.fig = plt.figure() if self.axes is None: self.axes = np.array([plt.axes()]) self.fig.add_axes(self.axes[0]) # Set up secondary y axis if requested if secondary_y is False: ax = self.axes[subplot_index] else: ax = self.axes[subplot_index].twinx() if ydata is None: if day_night_background is True: self.day_night_background(subplot_index=subplot_index, dsname=dsname) # If limiting data being plotted use masked arrays # Need to do it this way because of autoscale() method if abs_limits[0] is not None and abs_limits[1] is not None: data = np.ma.masked_outside( data, abs_limits[0], abs_limits[1]) elif abs_limits[0] is not None and abs_limits[1] is None: data = np.ma.masked_less_equal( data, abs_limits[0]) elif abs_limits[0] is None and abs_limits[1] is not None: data = np.ma.masked_greater_equal( data, abs_limits[1]) # Plot the data lines = ax.plot(xdata, data, '.', **kwargs) # Check if we need to call legend method after plotting. This is only # called when no assessment overplot is called. add_legend = False if 'label' in kwargs.keys(): add_legend = True # Overplot failing data if requested if assessment_overplot: # If we are doing forced line plot from 2D data need to manage # legend lables. Will make arrays to hold labels of QC failing # because not set when labels not set. if not isinstance(labels, list) and add_legend is False: labels = [] lines = [] # For forced line plot need to plot QC behind point instead of # on top of point. zorder = None if force_line_plot or overplot_behind: zorder = 0 overplot_markersize *= 2. for assessment, categories in assessment_overplot_category.items(): flag_data = self._obj[dsname].qcfilter.get_masked_data( field, rm_assessments=categories, return_inverse=True) if np.invert(flag_data.mask).any() and np.isfinite(flag_data).any(): try: flag_data.mask = np.logical_or(data.mask, flag_data.mask) except AttributeError: pass qc_ax = ax.plot( xdata, flag_data, marker=overplot_marker, linestyle='', markersize=overplot_markersize, color=assessment_overplot_category_color[assessment], label=assessment, zorder=zorder) # If labels keyword is set need to add labels for calling legend if isinstance(labels, list): # If plotting forced_line_plot need to subset the Line2D object # so we don't have more than one added to legend. if len(qc_ax) > 1: lines.extend(qc_ax[:1]) else: lines.extend(qc_ax) labels.append(assessment) add_legend = True # Add legend if labels are available if isinstance(labels, list): ax.legend(lines, labels) elif add_legend: ax.legend() else: # Add in nans to ensure the data are not streaking if add_nan is True: xdata, data = data_utils.add_in_nan(xdata, data) # Sets shading parameter to auto. Matplotlib will check deminsions. # If X,Y and C are same deminsions shading is set to nearest. # If X and Y deminsions are 1 greater than C shading is set to flat. mesh = ax.pcolormesh(np.asarray(xdata), ydata, data.transpose(), shading=set_shading, cmap=cmap, edgecolors='face', **kwargs) # Set Title if set_title is None: set_title = ' '.join([dsname, field, 'on', dt_utils.numpy_to_arm_date( self._obj[dsname].time.values[0])]) if secondary_y is False: ax.set_title(set_title) # Set YTitle ax.set_ylabel(ytitle) # Set X Limit - We want the same time axes for all subplots if not hasattr(self, 'time_rng'): if time_rng is not None: self.time_rng = list(time_rng) else: self.time_rng = [xdata.min().values, xdata.max().values] self.set_xrng(self.time_rng, subplot_index) # Set Y Limit if y_rng is not None: self.set_yrng(y_rng) if hasattr(self, 'yrng'): # Make sure that the yrng is not just the default if ydata is None: if abs_limits[0] is not None or abs_limits[1] is not None: our_data = data else: our_data = data.values else: our_data = ydata finite = np.isfinite(our_data) if finite.any(): our_data = our_data[finite] if invert_y_axis is False: yrng = [np.min(our_data), np.max(our_data)] else: yrng = [np.max(our_data), np.min(our_data)] else: yrng = [0, 1] # Check if current range is outside of new range an only set # values that work for all data plotted. current_yrng = ax.get_ylim() if yrng[0] > current_yrng[0]: yrng[0] = current_yrng[0] if yrng[1] < current_yrng[1]: yrng[1] = current_yrng[1] # Set y range the normal way if not secondary y # If secondary, just use set_ylim if secondary_y is False: self.set_yrng(yrng, subplot_index) else: ax.set_ylim(yrng) # Set X Format if len(subplot_index) == 1: days = (self.xrng[subplot_index, 1] - self.xrng[subplot_index, 0]) else: days = (self.xrng[subplot_index[0], subplot_index[1], 1] - self.xrng[subplot_index[0], subplot_index[1], 0]) myFmt = common.get_date_format(days) ax.xaxis.set_major_formatter(myFmt) # Set X format - We want the same time axes for all subplots if not hasattr(self, 'time_fmt'): self.time_fmt = myFmt # Put on an xlabel, but only if we are making the bottom-most plot if subplot_index[0] == self.axes.shape[0] - 1: ax.set_xlabel('Time [UTC]') if ydata is not None: if cbar_label is None: self.add_colorbar(mesh, title=cbar_default, subplot_index=subplot_index) else: self.add_colorbar(mesh, title=''.join(['(', cbar_label, ')']), subplot_index=subplot_index) return ax def plot_barbs_from_spd_dir(self, dir_field, spd_field, pres_field=None, dsname=None, **kwargs): """ This procedure will make a wind barb plot timeseries. If a pressure field is given and the wind fields are 1D, which, for example, would occur if one wants to plot a timeseries of rawinsonde data, then a time-height cross section of winds will be made. Note: This procedure calls plot_barbs_from_u_v and will take in the same keyword arguments as that procedure. Parameters ---------- dir_field : str The name of the field specifying the wind direction in degrees. 0 degrees is defined to be north and increases clockwise like what is used in standard meteorological notation. spd_field : str The name of the field specifying the wind speed in m/s. pres_field : str The name of the field specifying pressure or height. If using height coordinates, then we recommend setting invert_y_axis to False. dsname : str The name of the datastream to plot. Setting to None will make ACT attempt to autodetect this. kwargs : dict Any additional keyword arguments will be passed into :func:`act.plotting.TimeSeriesDisplay.plot_barbs_from_u_and_v`. Returns ------- the_ax : matplotlib axis handle The handle to the axis where the plot was made on. Examples -------- ..code-block :: python sonde_ds = act.io.armfiles.read_netcdf( act.tests.sample_files.EXAMPLE_TWP_SONDE_WILDCARD) BarbDisplay = act.plotting.TimeSeriesDisplay( {'sonde_darwin': sonde_ds}, figsize=(10,5)) BarbDisplay.plot_barbs_from_spd_dir('deg', 'wspd', 'pres', num_barbs_x=20) """ if dsname is None and len(self._obj.keys()) > 1: raise ValueError(("You must choose a datastream when there are 2 " "or more datasets in the TimeSeriesDisplay " "object.")) elif dsname is None: dsname = list(self._obj.keys())[0] # Make temporary field called tempu, tempv spd = self._obj[dsname][spd_field] dir = self._obj[dsname][dir_field] tempu = -np.sin(np.deg2rad(dir)) * spd tempv = -np.cos(np.deg2rad(dir)) * spd self._obj[dsname]["temp_u"] = deepcopy(self._obj[dsname][spd_field]) self._obj[dsname]["temp_v"] = deepcopy(self._obj[dsname][spd_field]) self._obj[dsname]["temp_u"].values = tempu self._obj[dsname]["temp_v"].values = tempv the_ax = self.plot_barbs_from_u_v("temp_u", "temp_v", pres_field, dsname, **kwargs) del self._obj[dsname]["temp_u"], self._obj[dsname]["temp_v"]
import polars from pyquokka.nodes import * from pyquokka.utils import * import numpy as np import pandas as pd import time import random import pickle from functools import partial import random #ray.init("auto", _system_config={"worker_register_timeout_seconds": 60}, ignore_reinit_error=True, runtime_env={"working_dir":"/home/ubuntu/quokka","excludes":["*.csv","*.tbl","*.parquet"]}) #ray.init("auto", ignore_reinit_error=True, runtime_env={"working_dir":"/home/ziheng/.local/lib/python3.8/site-packages/pyquokka/"}) #ray.init(ignore_reinit_error=True) # do this locally #ray.timeline("profile.json") NONBLOCKING_NODE = 1 BLOCKING_NODE = 2 INPUT_REDIS_DATASET = 3 INPUT_READER_DATASET = 6 class Dataset: def __init__(self, wrapped_dataset) -> None: self.wrapped_dataset = wrapped_dataset def to_list(self): return ray.get(self.wrapped_dataset.to_list.remote()) def to_pandas(self): return ray.get(self.wrapped_dataset.to_pandas.remote()) def to_dict(self): return ray.get(self.wrapped_dataset.to_dict.remote()) @ray.remote class WrappedDataset: def __init__(self, num_channels) -> None: self.num_channels = num_channels self.objects = {i: [] for i in range(self.num_channels)} self.metadata = {} self.remaining_channels = {i for i in range(self.num_channels)} self.done = False def added_object(self, channel, object_handle): if channel not in self.objects or channel not in self.remaining_channels: raise Exception self.objects[channel].append(object_handle) def add_metadata(self, channel, object_handle): if channel in self.metadata or channel not in self.remaining_channels: raise Exception("Cannot add metadata for the same channel twice") self.metadata[channel] = object_handle def done_channel(self, channel): self.remaining_channels.remove(channel) if len(self.remaining_channels) == 0: self.done = True def is_complete(self): return self.done # debugging method def print_all(self): for channel in self.objects: for object in self.objects[channel]: r = redis.Redis(host=object[0], port=6800, db=0) print(pickle.loads(r.get(object[1]))) def get_objects(self): assert self.is_complete() return self.objects def to_pandas(self): assert self.is_complete() dfs = [] for channel in self.objects: for object in self.objects[channel]: r = redis.Redis(host=object[0], port=6800, db=0) dfs.append(pickle.loads(r.get(object[1]))) try: return polars.concat(dfs) except: return pd.concat(dfs) def to_list(self): assert self.is_complete() ret = [] for channel in self.objects: for object in self.objects[channel]: r = redis.Redis(host=object[0], port=6800, db=0) ret.append(pickle.loads(r.get(object[1]))) return ret def to_dict(self): assert self.is_complete() d = {channel:[] for channel in self.objects} for channel in self.objects: for object in self.objects[channel]: r = redis.Redis(host=object[0], port=6800, db=0) thing = pickle.loads(r.get(object[1])) if type(thing) == list: d[channel].extend(thing) else: d[channel].append(thing) return d class TaskGraph: # this keeps the logical dependency DAG between tasks def __init__(self, cluster, checkpoint_bucket = "quokka-checkpoint") -> None: self.cluster = cluster self.current_node = 0 self.nodes = {} self.node_channel_to_ip = {} self.node_ips = {} self.node_type = {} self.node_parents = {} self.node_args = {} self.checkpoint_bucket = checkpoint_bucket s3 = boto3.resource('s3') bucket = s3.Bucket(checkpoint_bucket) bucket.objects.all().delete() r = redis.Redis(host=str(self.cluster.leader_public_ip), port=6800, db=0) state_tags = [i.decode("utf-8") for i in r.keys() if "state-tag" in i.decode("utf-8")] for state_tag in state_tags: r.delete(state_tag) def flip_ip_channels(self, ip_to_num_channel): ips = sorted(list(ip_to_num_channel.keys())) starts = np.cumsum([0] + [ip_to_num_channel[ip] for ip in ips]) start_dict = {ips[k]: starts[k] for k in range(len(ips))} lists_to_merge = [ {i: ip for i in range(start_dict[ip], start_dict[ip] + ip_to_num_channel[ip])} for ip in ips ] channel_to_ip = {k: v for d in lists_to_merge for k, v in d.items()} for key in channel_to_ip: if channel_to_ip[key] == 'localhost': channel_to_ip[key] = ray.worker._global_node.address.split(":")[0] return channel_to_ip def return_dependent_map(self, dependents): dependent_map = {} if len(dependents) > 0: for node in dependents: dependent_map[node] = (self.node_ips[node], len(self.node_channel_to_ip[node])) return dependent_map def epilogue(self,tasknode, channel_to_ip, ips): self.nodes[self.current_node] = tasknode self.node_channel_to_ip[self.current_node] = channel_to_ip self.node_ips[self.current_node] = ips self.current_node += 1 return self.current_node - 1 def new_input_redis(self, dataset, ip_to_num_channel = None, policy = "default", batch_func=None, dependents = []): dependent_map = self.return_dependent_map(dependents) if ip_to_num_channel is None: # automatically come up with some policy ip_to_num_channel = {ip: self.cluster.cpu_count for ip in list(self.cluster.private_ips.values())} channel_to_ip = self.flip_ip_channels(ip_to_num_channel) # this will assert that the dataset is complete. You can only call this API on a completed dataset objects = ray.get(dataset.get_objects.remote()) ip_to_channel_sets = {} for channel in channel_to_ip: ip = channel_to_ip[channel] if ip not in ip_to_channel_sets: ip_to_channel_sets[ip] = {channel} else: ip_to_channel_sets[ip].add(channel) # current heuristics for scheduling objects to reader channels: # if an object can be streamed out locally from someone, always do that # try to balance the amounts of things that people have to stream out locally # if an object cannot be streamed out locally, assign it to anyone # try to balance the amounts of things that people have to fetch over the network. channel_objects = {channel: [] for channel in channel_to_ip} if policy == "default": local_read_sizes = {channel: 0 for channel in channel_to_ip} remote_read_sizes = {channel: 0 for channel in channel_to_ip} for writer_channel in objects: for object in objects[writer_channel]: ip, key, size = object # the object is on a machine that is not part of this task node, will have to remote fetch if ip not in ip_to_channel_sets: # find the channel with the least amount of remote read my_channel = min(remote_read_sizes, key = remote_read_sizes.get) channel_objects[my_channel].append(object) remote_read_sizes[my_channel] += size else: eligible_sizes = {reader_channel : local_read_sizes[reader_channel] for reader_channel in ip_to_channel_sets[ip]} my_channel = min(eligible_sizes, key = eligible_sizes.get) channel_objects[my_channel].append(object) local_read_sizes[my_channel] += size else: raise Exception("other distribution policies not implemented yet.") print("CHANNEL_OBJECTS",channel_objects) tasknode = {} for channel in channel_to_ip: ip = channel_to_ip[channel] if ip != 'localhost': tasknode[channel] = InputRedisDatasetNode.options(max_concurrency = 2, num_cpus=0.001, resources={"node:" + ip : 0.001} ).remote(self.current_node, channel, channel_objects, (self.checkpoint_bucket, str(self.current_node) + "-" + str(channel)), batch_func=batch_func, dependent_map=dependent_map) else: tasknode[channel] = InputRedisDatasetNode.options(max_concurrency = 2, num_cpus=0.001,resources={"node:" + ray.worker._global_node.address.split(":")[0] : 0.001} ).remote(self.current_node, channel, channel_objects, (self.checkpoint_bucket, str(self.current_node) + "-" + str(channel)), batch_func=batch_func, dependent_map=dependent_map) self.node_type[self.current_node] = INPUT_REDIS_DATASET self.node_args[self.current_node] = {"channel_objects":channel_objects, "batch_func": batch_func, "dependent_map":dependent_map} return self.epilogue(tasknode,channel_to_ip, tuple(ip_to_num_channel.keys())) def new_input_reader_node(self, reader, ip_to_num_channel = None, batch_func = None, dependents = [], ckpt_interval = 10): dependent_map = self.return_dependent_map(dependents) if ip_to_num_channel is None: # automatically come up with some policy ip_to_num_channel = {ip: self.cluster.cpu_count for ip in list(self.cluster.private_ips.values())} channel_to_ip = self.flip_ip_channels(ip_to_num_channel) # this is some state that is associated with the number of channels. typically for reading csvs or text files where you have to decide the split points. if hasattr(reader, "get_own_state"): reader.get_own_state(len(channel_to_ip)) # set num channels is still needed later to initialize the self.s3 object, which can't be pickled! tasknode = {} for channel in channel_to_ip: ip = channel_to_ip[channel] if ip != 'localhost': tasknode[channel] = InputReaderNode.options(max_concurrency = 2, num_cpus=0.001, resources={"node:" + ip : 0.001} ).remote(self.current_node, channel, reader, len(channel_to_ip), (self.checkpoint_bucket, str(self.current_node) + "-" + str(channel)), batch_func = batch_func,dependent_map = dependent_map, checkpoint_interval = ckpt_interval) else: tasknode[channel] = InputReaderNode.options(max_concurrency = 2, num_cpus=0.001,resources={"node:" + ray.worker._global_node.address.split(":")[0] : 0.001} ).remote(self.current_node, channel, reader, len(channel_to_ip), (self.checkpoint_bucket, str(self.current_node) + "-" + str(channel)), batch_func = batch_func, dependent_map = dependent_map, checkpoint_interval = ckpt_interval) self.node_type[self.current_node] = INPUT_READER_DATASET self.node_args[self.current_node] = {"reader": reader, "batch_func":batch_func, "dependent_map" : dependent_map, "ckpt_interval": ckpt_interval} return self.epilogue(tasknode,channel_to_ip, tuple(ip_to_num_channel.keys())) def flip_channels_ip(self, channel_to_ip): ips = channel_to_ip.values() result = {ip: 0 for ip in ips} for channel in channel_to_ip: result[channel_to_ip[channel]] += 1 return result def get_default_partition(self, source_ip_to_num_channel, target_ip_to_num_channel): # this can get more sophisticated in the future. For now it's super dumb. def partition_key_0(ratio, data, source_channel, num_target_channels): target_channel = source_channel // ratio return {target_channel: data} def partition_key_1(ratio, data, source_channel, num_target_channels): # return entirety of data to a random channel between source_channel * ratio and source_channel * ratio + ratio target_channel = int(random.random() * ratio) + source_channel * ratio return {target_channel: data} assert(set(source_ip_to_num_channel) == set(target_ip_to_num_channel)) ratio = None direction = None for ip in source_ip_to_num_channel: if ratio is None: if source_ip_to_num_channel[ip] % target_ip_to_num_channel[ip] == 0: ratio = source_ip_to_num_channel[ip] // target_ip_to_num_channel[ip] direction = 0 elif target_ip_to_num_channel[ip] % source_ip_to_num_channel[ip] == 0: ratio = target_ip_to_num_channel[ip] // source_ip_to_num_channel[ip] direction = 1 else: raise Exception("Can't support automated partition function generation since number of channels not a whole multiple of each other between source and target") elif ratio is not None: if direction == 0: assert target_ip_to_num_channel[ip] * ratio == source_ip_to_num_channel[ip], "ratio of number of channels between source and target must be same for every ip right now" elif direction == 1: assert source_ip_to_num_channel[ip] * ratio == target_ip_to_num_channel[ip], "ratio of number of channels between source and target must be same for every ip right now" print("RATIO", ratio) if direction == 0: return partial(partition_key_0, ratio) elif direction == 1: return partial(partition_key_1, ratio) else: return "Something is wrong" def prologue(self, streams, ip_to_num_channel, channel_to_ip, partition_key_supplied): partition_key = {} def partition_key_str(key, data, source_channel, num_target_channels): result = {} for channel in range(num_target_channels): if type(data) == pd.core.frame.DataFrame: if "int" in str(data.dtypes[key]).lower() or "float" in str(data.dtypes[key]).lower(): payload = data[data[key] % num_target_channels == channel] elif data.dtypes[key] == 'object': # str # this is not the fastest. we rehashing this everytime. payload = data[pd.util.hash_array(data[key].to_numpy()) % num_target_channels == channel] else: raise Exception("invalid partition column
<filename>autotest/ogr/ogr_mysql.py #!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test MySQL driver functionality. # Author: <NAME> <even dot rouault at mines dash paris dot ogr> # ############################################################################### # Copyright (c) 2004, <NAME> <<EMAIL>> # Copyright (c) 2008-2013, <NAME> <even dot rouault at mines-paris dot org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library 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 # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. ############################################################################### import sys sys.path.append('../pymod') import gdaltest import ogrtest from osgeo import ogr from osgeo import gdal # E. Rouault : this is almost a copy & paste from ogr_pg.py # # To create the required MySQL instance do something like: # # $ mysql -u root -p # mysql> CREATE DATABASE autotest; # mysql> GRANT ALL ON autotest.* TO 'THE_USER_THAT_RUNS_AUTOTEST'@'localhost'; # ############################################################################### # Open Database. def ogr_mysql_1(): gdaltest.mysql_ds = None try: ogr.GetDriverByName('MySQL') except: return 'skip' gdaltest.mysql_ds = ogr.Open('MYSQL:autotest', update=1) if gdaltest.mysql_ds is not None: return 'success' return 'skip' ############################################################################### # Create table from data/poly.shp def ogr_mysql_2(): if gdaltest.mysql_ds is None: return 'skip' shp_ds = ogr.Open('data/poly.shp') gdaltest.shp_ds = shp_ds shp_lyr = shp_ds.GetLayer(0) ###################################################### # Create Layer gdaltest.mysql_lyr = gdaltest.mysql_ds.CreateLayer('tpoly', srs=shp_lyr.GetSpatialRef(), options=['ENGINE=MyISAM']) ###################################################### # Setup Schema ogrtest.quick_create_layer_def(gdaltest.mysql_lyr, [('AREA', ogr.OFTReal), ('EAS_ID', ogr.OFTInteger), ('PRFEDEA', ogr.OFTString), ('SHORTNAME', ogr.OFTString, 8), ('INT64', ogr.OFTInteger64)]) ###################################################### # Copy in poly.shp dst_feat = ogr.Feature(feature_def=gdaltest.mysql_lyr.GetLayerDefn()) feat = shp_lyr.GetNextFeature() gdaltest.poly_feat = [] while feat is not None: gdaltest.poly_feat.append(feat) dst_feat.SetFrom(feat) dst_feat.SetField('INT64', 1234567890123) gdaltest.mysql_lyr.CreateFeature(dst_feat) feat = shp_lyr.GetNextFeature() dst_feat.Destroy() if gdaltest.mysql_lyr.GetFeatureCount() != shp_lyr.GetFeatureCount(): gdaltest.post_reason('not matching feature count') return 'fail' if not gdaltest.mysql_lyr.GetSpatialRef().IsSame(shp_lyr.GetSpatialRef()): gdaltest.post_reason('not matching spatial ref') return 'fail' return 'success' ############################################################################### # Verify that stuff we just wrote is still OK. def ogr_mysql_3(): if gdaltest.mysql_ds is None: return 'skip' if gdaltest.mysql_lyr.GetGeometryColumn() != 'SHAPE': gdaltest.post_reason('fail') return 'fail' if gdaltest.mysql_lyr.GetFeatureCount() != 10: gdaltest.post_reason('GetFeatureCount() returned %d instead of 10' % gdaltest.mysql_lyr.GetFeatureCount()) return 'fail' expect = [168, 169, 166, 158, 165] gdaltest.mysql_lyr.SetAttributeFilter('eas_id < 170') tr = ogrtest.check_features_against_list(gdaltest.mysql_lyr, 'eas_id', expect) if gdaltest.mysql_lyr.GetFeatureCount() != 5: gdaltest.post_reason('GetFeatureCount() returned %d instead of 5' % gdaltest.mysql_lyr.GetFeatureCount()) return 'fail' gdaltest.mysql_lyr.SetAttributeFilter(None) for i in range(len(gdaltest.poly_feat)): orig_feat = gdaltest.poly_feat[i] read_feat = gdaltest.mysql_lyr.GetNextFeature() if ogrtest.check_feature_geometry(read_feat, orig_feat.GetGeometryRef(), max_error=0.001) != 0: return 'fail' for fld in range(3): if orig_feat.GetField(fld) != read_feat.GetField(fld): gdaltest.post_reason('Attribute %d does not match' % fld) return 'fail' if read_feat.GetField('INT64') != 1234567890123: gdaltest.post_reason('failure') return 'fail' read_feat.Destroy() orig_feat.Destroy() gdaltest.poly_feat = None gdaltest.shp_ds.Destroy() return 'success' if tr else 'fail' ############################################################################### # Write more features with a bunch of different geometries, and verify the # geometries are still OK. def ogr_mysql_4(): if gdaltest.mysql_ds is None: return 'skip' # <NAME> : the mySQL driver doesn't seem to like adding new features and # iterating over a query at the same time. # If trying to do so, we get the 'Commands out of sync' error. wkt_list = ['10', '2', '1', '4', '5', '6'] gdaltest.mysql_lyr.ResetReading() feature_def = gdaltest.mysql_lyr.GetLayerDefn() for item in wkt_list: dst_feat = ogr.Feature(feature_def) wkt = open('data/wkb_wkt/' + item + '.wkt').read() geom = ogr.CreateGeometryFromWkt(wkt) ###################################################################### # Write geometry as a new Oracle feature. dst_feat.SetGeometryDirectly(geom) dst_feat.SetField('PRFEDEA', item) gdaltest.mysql_lyr.CreateFeature(dst_feat) dst_feat.Destroy() # FIXME : The source wkt polygons of '4' and '6' are not closed and # mySQL return them as closed, so the check_feature_geometry returns FALSE # Checking them after closing the rings again returns TRUE. wkt_list = ['10', '2', '1', '5', '4', '6'] for item in wkt_list: wkt = open('data/wkb_wkt/' + item + '.wkt').read() geom = ogr.CreateGeometryFromWkt(wkt) ###################################################################### # Read back the feature and get the geometry. gdaltest.mysql_lyr.SetAttributeFilter("PRFEDEA = '%s'" % item) feat_read = gdaltest.mysql_lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat_read, geom) != 0: print('Geometry changed. Closing rings before trying again for wkt #', item) print('(before):', geom.ExportToWkt()) geom.CloseRings() print('(after) :', geom.ExportToWkt()) if ogrtest.check_feature_geometry(feat_read, geom) != 0: return 'fail' feat_read.Destroy() return 'success' ############################################################################### # Test ExecuteSQL() results layers without geometry. def ogr_mysql_5(): if gdaltest.mysql_ds is None: return 'skip' # <NAME> : unlike PostgreSQL driver : None is sorted in last position expect = [179, 173, 172, 171, 170, 169, 168, 166, 165, 158, None] sql_lyr = gdaltest.mysql_ds.ExecuteSQL('select distinct eas_id from tpoly order by eas_id desc') if sql_lyr.GetFeatureCount() != 11: gdaltest.post_reason('GetFeatureCount() returned %d instead of 11' % sql_lyr.GetFeatureCount()) return 'fail' tr = ogrtest.check_features_against_list(sql_lyr, 'eas_id', expect) gdaltest.mysql_ds.ReleaseResultSet(sql_lyr) return 'success' if tr else 'fail' ############################################################################### # Test ExecuteSQL() results layers with geometry. def ogr_mysql_6(): if gdaltest.mysql_ds is None: return 'skip' sql_lyr = gdaltest.mysql_ds.ExecuteSQL("select * from tpoly where prfedea = '2'") tr = ogrtest.check_features_against_list(sql_lyr, 'prfedea', ['2']) if tr: sql_lyr.ResetReading() feat_read = sql_lyr.GetNextFeature() if ogrtest.check_feature_geometry(feat_read, 'MULTILINESTRING ((5.00121349 2.99853132,5.00121349 1.99853133),(5.00121349 1.99853133,5.00121349 0.99853133),(3.00121351 1.99853127,5.00121349 1.99853133),(5.00121349 1.99853133,6.00121348 1.99853135))') != 0: tr = 0 feat_read.Destroy() sql_lyr.ResetReading() geom = ogr.CreateGeometryFromWkt( 'LINESTRING(-10 -10,0 0)') sql_lyr.SetSpatialFilter(geom) geom.Destroy() if sql_lyr.GetFeatureCount() != 0: gdaltest.post_reason('GetFeatureCount() returned %d instead of 0' % sql_lyr.GetFeatureCount()) return 'fail' if sql_lyr.GetNextFeature() is not None: gdaltest.post_reason('GetNextFeature() did not return None') return 'fail' gdaltest.mysql_ds.ReleaseResultSet(sql_lyr) return 'success' if tr else 'fail' ############################################################################### # Test spatial filtering. def ogr_mysql_7(): if gdaltest.mysql_ds is None: return 'skip' gdaltest.mysql_lyr.SetAttributeFilter(None) geom = ogr.CreateGeometryFromWkt( 'LINESTRING(479505 4763195,480526 4762819)') gdaltest.mysql_lyr.SetSpatialFilter(geom) geom.Destroy() if gdaltest.mysql_lyr.GetFeatureCount() != 1: gdaltest.post_reason('GetFeatureCount() returned %d instead of 1' % gdaltest.mysql_lyr.GetFeatureCount()) return 'fail' tr = ogrtest.check_features_against_list(gdaltest.mysql_lyr, 'eas_id', [158]) gdaltest.mysql_lyr.SetAttributeFilter('eas_id = 158') if gdaltest.mysql_lyr.GetFeatureCount() != 1: gdaltest.post_reason('GetFeatureCount() returned %d instead of 1' % gdaltest.mysql_lyr.GetFeatureCount()) return 'fail' gdaltest.mysql_lyr.SetAttributeFilter(None) gdaltest.mysql_lyr.SetSpatialFilter(None) return 'success' if tr else 'fail' ############################################################################### # Write a feature with too long a text value for a fixed length text field. # The driver should now truncate this (but with a debug message). Also, # put some crazy stuff in the value to verify that quoting and escaping # is working smoothly. # # No geometry in this test. def ogr_mysql_8(): if gdaltest.mysql_ds is None: return 'skip' dst_feat = ogr.Feature(feature_def=gdaltest.mysql_lyr.GetLayerDefn()) dst_feat.SetField('PRFEDEA', 'CrazyKey') dst_feat.SetField('SHORTNAME', 'Crazy"\'Long') # We are obliged to create a fake geometry dst_feat.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT(0 0)')) gdaltest.mysql_lyr.CreateFeature(dst_feat) dst_feat.Destroy() gdaltest.mysql_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat_read = gdaltest.mysql_lyr.GetNextFeature() if feat_read is None: gdaltest.post_reason('creating crazy feature failed!') return 'fail' if feat_read.GetField('shortname') != 'Crazy"\'L': gdaltest.post_reason('Vvalue not properly escaped or truncated:' + feat_read.GetField('shortname')) return 'fail' feat_read.Destroy() return 'success' ############################################################################### # Verify inplace update of a feature with SetFeature(). def ogr_mysql_9(): if gdaltest.mysql_ds is None: return 'skip' gdaltest.mysql_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat = gdaltest.mysql_lyr.GetNextFeature() gdaltest.mysql_lyr.SetAttributeFilter(None) feat.SetField('SHORTNAME', 'Reset') point = ogr.Geometry(ogr.wkbPoint25D) point.SetPoint(0, 5, 6) feat.SetGeometryDirectly(point) if gdaltest.mysql_lyr.SetFeature(feat) != 0: feat.Destroy() gdaltest.post_reason('SetFeature() method failed.') return 'fail' fid = feat.GetFID() feat.Destroy() feat = gdaltest.mysql_lyr.GetFeature(fid) if feat is None: gdaltest.post_reason('GetFeature(%d) failed.' % fid) return 'fail' shortname = feat.GetField('SHORTNAME') if shortname[:5] != 'Reset': gdaltest.post_reason('SetFeature() did not update SHORTNAME, got %s.' % shortname) return 'fail' if ogrtest.check_feature_geometry(feat, 'POINT(5 6)') != 0: print(feat.GetGeometryRef()) gdaltest.post_reason('Geometry update failed') return 'fail' # Test updating non-existing feature feat.SetFID(-10) if gdaltest.mysql_lyr.SetFeature(feat) != ogr.OGRERR_NON_EXISTING_FEATURE: feat.Destroy() gdaltest.post_reason('Expected failure of SetFeature().') return 'fail' # Test deleting non-existing feature if gdaltest.mysql_lyr.DeleteFeature(-10) != ogr.OGRERR_NON_EXISTING_FEATURE: feat.Destroy() gdaltest.post_reason('Expected failure of DeleteFeature().') return 'fail' feat.Destroy() return 'success' ############################################################################### # Verify that DeleteFeature() works properly. def ogr_mysql_10(): if gdaltest.mysql_ds is None: return 'skip' gdaltest.mysql_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat = gdaltest.mysql_lyr.GetNextFeature() gdaltest.mysql_lyr.SetAttributeFilter(None) fid = feat.GetFID() feat.Destroy() if gdaltest.mysql_lyr.DeleteFeature(fid) != 0: gdaltest.post_reason('DeleteFeature() method failed.') return 'fail' gdaltest.mysql_lyr.SetAttributeFilter("PRFEDEA = 'CrazyKey'") feat = gdaltest.mysql_lyr.GetNextFeature() gdaltest.mysql_lyr.SetAttributeFilter(None) if feat is None: return 'success' feat.Destroy() gdaltest.post_reason('DeleteFeature() seems to have had no effect.') return 'fail' ############################################################################### # Test very large query. def ogr_mysql_15(): if gdaltest.mysql_ds is None: return 'skip' expect = [169] query = 'eas_id = 169' for i in range(1000): query = query + (' or eas_id = %d' % (i + 1000)) gdaltest.mysql_lyr.SetAttributeFilter(query) tr = ogrtest.check_features_against_list(gdaltest.mysql_lyr, 'eas_id', expect) gdaltest.mysql_lyr.SetAttributeFilter(None) return 'success' if tr else 'fail' ############################################################################### # Test very large statement. def ogr_mysql_16(): if gdaltest.mysql_ds is None: return 'skip' expect = [169] query = 'eas_id = 169' for ident in range(1000): query = query + (' or eas_id = %d' % (ident + 1000)) statement = 'select eas_id from tpoly where ' + query lyr = gdaltest.mysql_ds.ExecuteSQL(statement) tr = ogrtest.check_features_against_list(lyr, 'eas_id', expect) gdaltest.mysql_ds.ReleaseResultSet(lyr)
field_vals_dict: contains a dictionary indexed by field (sex, age, preference, etc.), and containing the current value # of the field that must be translated into the current language. location = '' return_dict = { 'age': '----', 'sex': '----', 'sub_region': '----', 'region': '----', 'country': '----', 'location': '----', } if settings.BUILD_NAME == "language_build": return_dict.update({# the following entries are only used in language_build 'languages': '----', # list of languages spoken 'languages_to_learn': '----', # list of languages to learn 'language_to_teach': '----', 'language_to_learn': '----', }) #return_dict.update(user_profile_details.UserSpec.activity_categories_unset_dict) else: return_dict.update({# following is only for dating websites 'relationship_status': '----', 'preference': '----', }) try: # we need the options dict for the reverse lookup to get the appropriate value for a given field/value if search_or_profile_fields == "profile": field_dictionary_by_field_name = getattr(user_profile_main_data.UserSpec, "signup_fields_options_dict") elif search_or_profile_fields == "search": field_dictionary_by_field_name = getattr(user_profile_main_data.UserSpec, "search_fields_options_dict") else: assert(0) for (field_name, field_val) in field_vals_dict.iteritems(): lookup_field_name = field_name try: if not isinstance(field_val, list): if field_val and field_val != "----" and field_name != 'username' and field_name != 'bookmark': return_dict[field_name] = field_dictionary_by_field_name[lookup_field_name][lang_idx][field_val] if settings.BUILD_NAME == "discrete_build" or settings.BUILD_NAME == "gay_build" or settings.BUILD_NAME == "swinger_build": if field_name == "relationship_status" and lang_idx == localizations.input_field_lang_idx['es']: if settings.BUILD_NAME == "gay_build": # all profiles in gay_build site are male - give Spanish masculine ending "o" return_dict[field_name] = re.sub('@', 'o', return_dict[field_name]) elif field_vals_dict['sex'] == 'male' or field_vals_dict['sex'] == 'other' or field_vals_dict['sex'] == 'tstvtg': return_dict[field_name] = re.sub('@', 'o', return_dict[field_name]) elif field_vals_dict['sex'] == 'female' or field_vals_dict['sex'] == 'couple': return_dict[field_name] = re.sub('@', 'a', return_dict[field_name]) else: pass # no substitution necessary else: field_vals_list_dict = field_val return_dict[field_name] = generic_html_generator_for_list(lang_idx, lookup_field_name, field_vals_list_dict) except: error_message = "*Error* get_fields_in_current_language - %s value: %s" % (field_name, field_val) return_dict[field_name] = '' error_reporting.log_exception(logging.warning, error_message = error_message) try: if pluralize_sex: if settings.BUILD_NAME != "language_build": # if pluralized, lookup the field name in the "preference" setting (since it is pluralized), # otherwise use the "sex" setting. if field_vals_dict['preference'] != "----": return_dict["preference"] = field_dictionary_by_field_name["preference"][lang_idx][field_vals_dict['preference']] if field_vals_dict['sex'] != "----": return_dict["sex"] = field_dictionary_by_field_name["preference"][lang_idx][field_vals_dict['sex']] else: # preference fields do not exist for language_build, so lookup in the "sex" field if field_vals_dict['sex'] != "----": return_dict["sex"] = field_dictionary_by_field_name["sex"][lang_idx][field_vals_dict['sex']] else: if settings.BUILD_NAME != "language_build": if field_vals_dict['preference'] != "----": return_dict["preference"] = field_dictionary_by_field_name["sex"][lang_idx][field_vals_dict['preference'] ] if field_vals_dict['sex'] != "----": return_dict["sex"] = field_dictionary_by_field_name["sex"][lang_idx][field_vals_dict['sex']] except: # This can be triggered if someone passes in bad parameters on the URL error_reporting.log_exception(logging.warning) try: # in order to get better google keyword coverage, override sex and preference for certian age ranges # depending on the language. if settings.SEO_OVERRIDES_ENABLED: if field_vals_dict['age'] != "----": lang_code = localizations.lang_code_by_idx[lang_idx] return_dict["sex"] = search_engine_overrides.override_sex(lang_code, int(field_vals_dict['age']), return_dict["sex"]) if settings.BUILD_NAME != "language_build": return_dict["preference"] = search_engine_overrides.override_sex(lang_code, int(field_vals_dict['age']), return_dict["preference"]) if field_vals_dict['sub_region'] and field_vals_dict['sub_region'] != "----": return_dict['sub_region'] = field_dictionary_by_field_name['sub_region'][lang_idx][field_vals_dict['sub_region']] if field_vals_dict['region'] and field_vals_dict['region'] != "----": return_dict['region'] = field_dictionary_by_field_name['region'][lang_idx][field_vals_dict['region']] if field_vals_dict['country'] != "----": return_dict['country'] = field_dictionary_by_field_name['country'][lang_idx][field_vals_dict['country']] if return_dict['sub_region'] != "----" : return_dict['location'] = "%s, %s, %s" % (return_dict['sub_region'], return_dict['region'], return_dict['country']) elif return_dict['region'] != "----": return_dict['location'] = "%s, %s" % (return_dict['region'], return_dict['country']) elif return_dict['country'] != "----": return_dict['location'] = return_dict['country'] else: return_dict['location'] = '----' except: # This can be triggered if someone passes in bad parameters on the URL, that result in # the sub_region, region, or country containing invalid values that are not defined. error_reporting.log_exception(logging.warning) except: error_reporting.log_exception(logging.critical) return (return_dict) def add_session_id_to_user_tracker(user_tracker_ref, session_id): # adds the current session identifier to the user_tracker so that if necessary we can clear the sessions from the # database, thereby forcing a logout of a user. try: user_tracker = user_tracker_ref.get() # the following code allocates memory for the list up until the maximum number of sessions is stored, # at which point we start to wrap around the list. list_length = len(user_tracker.list_of_session_ids) if list_length < constants.MAX_STORED_SESSIONS: user_tracker.list_of_session_ids.append(session_id) user_tracker.list_of_session_ids_last_index = list_length else: list_idx = (user_tracker.list_of_session_ids_last_index + 1) % constants.MAX_STORED_SESSIONS user_tracker.list_of_session_ids[list_idx] = session_id user_tracker.list_of_session_ids_last_index = list_idx user_tracker.put() except: error_reporting.log_exception(logging.critical) def get_fake_mail_parent_entity_key(uid1, uid2): # in order to ensure that all messages between two users are in the same entity group, we create a "fake" # entity key, which will be assigned as a parent to all messages between this pair of users. To ensure that # there is only one unique key for each pair of users, we *always* use a key name which contains # the lower key followed by the higher key # Note: Using "uid's" instead of "nid's" is a mistake - if we ever need to restore mail messages to a different # application id, the parent will not be consistent, and the maill messages will not be found. # must ensure that keys are compared using *string* or *integer* representations, *not* key representations - because the # order can change - see (my comment) on StackOverflow # http://stackoverflow.com/questions/7572386/why-are-appengine-database-keys-sorted-differently-than-strings uid1 = str(uid1) uid2 = str(uid2) if uid1 < uid2: parent_key_name = "%s_and_%s" % (uid1, uid2) else: parent_key_name = "%s_and_%s" % (uid2, uid1) mail_parent_key = ndb.Key('FakeMailMessageParent', parent_key_name) return mail_parent_key def get_have_sent_messages_key_name(owner_key, other_key): key_name = "%s_and_%s" % (owner_key.urlsafe(), other_key.urlsafe()) return key_name def get_have_sent_messages_key(owner_key, other_key): key_name = get_have_sent_messages_key_name(owner_key, other_key) have_sent_messages_key = ndb.Key('UsersHaveSentMessages', key_name) return have_sent_messages_key def get_have_sent_messages_object(owner_key, other_key, create_if_does_not_exist = False): try: have_sent_messages_key = get_have_sent_messages_key(owner_key, other_key) have_sent_messages_object = have_sent_messages_key.get() if not have_sent_messages_object and create_if_does_not_exist: have_sent_messages_object = models.UsersHaveSentMessages(id = get_have_sent_messages_key_name(owner_key, other_key)) have_sent_messages_object.datetime_first_message_to_other_today = datetime.datetime.now() have_sent_messages_object.put() return have_sent_messages_object except: error_reporting.log_exception(logging.critical) return None def get_initiate_contact_object(viewer_userobject_key, display_userobject_key, create_if_does_not_exist = False ): # This function returns the object corresponding to previous contact beween the owner and the displayed # profile. This object contains favorites, kisses, etc. # NOTE: There is some twisted logic in the naming scheme here . # Basically, the "displayed_profile" refers to the profile that was/is displayed when a kiss/wink/key was sent. # This means that the sender of the contact (kiss/key), was the viewer at the time that the contact was sent. # The receiver of the contact is the "displayed_profile"... However, when we are checking to see if a person # has the key to see private photos, then we need to query the userobject as if it were the "displayed_profile" # because it was the "displayed_profile" when the key was received. # # In other words user Alex is viewing user Julie. We want to see if Alex has the key of Julie to see her private photos. # We need to query the initiate_contact_object with the displayed_user_object set to Alex, and the viewer_userobject # set to Julie (even though *now* alex is the one viewing the profile of Julie) # check if the client has had previous contact with the profile being viewed try: memcache_key_str = constants.INITIATE_CONTACT_MEMCACHE_PREFIX + viewer_userobject_key.urlsafe() + display_userobject_key.urlsafe() memcache_entity = memcache.get(memcache_key_str) if memcache_entity == 0 and not create_if_does_not_exist: # we stored a zero if we have already checked the database and there is no object for this pair of # users. As long as we are not creating a new entity (if not create_if_does_not_exist), then we can return # a None value for this query. return None elif memcache_entity is not None and memcache_entity != 0: # Entity found in memcache - just return it. initiate_contact_object = deserialize_entity(memcache_entity) return initiate_contact_object else: # Two possibilities to get here: # 1) memcache is None - We need to check the database to see what the current initiate_contact_object is # and store to memcache # 2) memcache_entity == 0 (we have queried the database previously, but it was empty) *and* # create_if_does_not_exist is True (we need to create a new entity) object_key_name = viewer_userobject_key.urlsafe() + display_userobject_key.urlsafe() initiate_contact_key = ndb.Key('InitiateContactModel', object_key_name) initiate_contact_object = initiate_contact_key.get() if initiate_contact_object is None: # database does not contain an object for this pair of users. if create_if_does_not_exist: # only create a
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ **Project Name:** MakeHuman **Product Home Page:** http://www.makehumancommunity.org/ **Github Code Home Page:** https://github.com/makehumancommunity/ **Authors:** <NAME>, <NAME> **Copyright(c):** MakeHuman Team 2001-2019 **Licensing:** AGPL3 This file is part of MakeHuman Community (www.makehumancommunity.org). This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Abstract -------- TODO """ import math import numpy as np import events3d from core import G import glmodule as gl import matrix class Camera(events3d.EventHandler): """ Old camera. Works by moving human mesh instead of changing its own orientation. """ def __init__(self): super(Camera, self).__init__() self.changedPending = False self._fovAngle = 25.0 self._nearPlane = 0.1 self._farPlane = 100.0 self._projection = 1 self._stereoMode = 0 self._eyeX = 0.0 self._eyeY = 0.0 self._eyeZ = 60.0 self._focusX = 0.0 self._focusY = 0.0 self._focusZ = 0.0 self._upX = 0.0 self._upY = 1.0 self._upZ = 0.0 self.eyeSeparation = 1.0 self.updated = False def changed(self): self.callEvent('onChanged', self) self.changedPending = False def getProjection(self): return self._projection def setProjection(self, value): self._projection = value self.changed() projection = property(getProjection, setProjection) def getFovAngle(self): return self._fovAngle def setFovAngle(self, value): self._fovAngle = value self.changed() fovAngle = property(getFovAngle, setFovAngle) def getNearPlane(self): return self._nearPlane def setNearPlane(self, value): self._nearPlane = value self.changed() nearPlane = property(getNearPlane, setNearPlane) def getFarPlane(self): return self._farPlane def setFarPlane(self, value): self._farPlane = value self.changed() farPlane = property(getFarPlane, setFarPlane) def getEyeX(self): return self._eyeX def setEyeX(self, value): self._eyeX = value self.changed() eyeX = property(getEyeX, setEyeX) def getEyeY(self): return self._eyeY def setEyeY(self, value): self._eyeY = value self.changed() eyeY = property(getEyeY, setEyeY) def getEyeZ(self): return self._eyeZ def setEyeZ(self, value): self._eyeZ = value self.changed() eyeZ = property(getEyeZ, setEyeZ) def getEye(self): return (self.eyeX, self.eyeY, self.eyeZ) def setEye(self, xyz): (self._eyeX, self._eyeY, self._eyeZ) = xyz self.changed() eye = property(getEye, setEye) def getFocusX(self): return self._focusX def setFocusX(self, value): self._focusX = value self.changed() focusX = property(getFocusX, setFocusX) def getFocusY(self): return self._focusY def setFocusY(self, value): self._focusY = value self.changed() focusY = property(getFocusY, setFocusY) def getFocusZ(self): return self._focusZ def setFocusZ(self, value): self._focusZ = value self.changed() focusZ = property(getFocusZ, setFocusZ) def getFocus(self): return (self.focusX, self.focusY, self.focusZ) def setFocus(self, xyz): (self._focusX, self._focusY, self._focusZ) = xyz self.changed() focus = property(getFocus, setFocus) def getUpX(self): return self._upX def setUpX(self, value): self._upX = value self.changed() upX = property(getUpX, setUpX) def getUpY(self): return self._upY def setUpY(self, value): self._upY = value self.changed() upY = property(getUpY, setUpY) def getUpZ(self): return self._upZ def setUpZ(self, value): self._upZ = value self.changed() upZ = property(getUpZ, setUpZ) def getUp(self): return (self._upX, self._upY, self._upZ) def setUp(self, xyz): (self._upX, self._upY, self._upZ) = xyz self.changed() up = property(getUp, setUp) def getScale(self): fov = math.tan(self.fovAngle * 0.5 * math.pi / 180.0) delta = np.array(self.eye) - np.array(self.focus) scale = math.sqrt(np.sum(delta ** 2)) * fov return scale scale = property(getScale) def getStereoMode(self): return self._stereoMode def setStereoMode(self, value): self._stereoMode = value self.changed() stereoMode = property(getStereoMode, setStereoMode) def switchToOrtho(self): self._projection = 0 self._nearPlane = -100.0 self.changed() def switchToPerspective(self): self._projection = 1 self._nearPlane = 0.1 self.changed() def getMatrices(self, eye): def lookat(ex, ey, ez, tx, ty, tz, ux, uy, uz): e = np.array([ex, ey, ez]) t = np.array([tx, ty, tz]) u = np.array([ux, uy, uz]) return matrix.lookat(e, t, u) stereoMode = 0 if eye: stereoMode = self.stereoMode aspect = float(max(1, G.windowWidth)) / float(max(1, G.windowHeight)) if stereoMode == 0: # No stereo if self.projection: proj = matrix.perspective(self.fovAngle, aspect, self.nearPlane, self.farPlane) else: height = self.scale width = self.scale * aspect proj = matrix.ortho(-width, width, -height, height, self.nearPlane, self.farPlane) mv = lookat(self.eyeX, self.eyeY, self.eyeZ, # Eye self.focusX, self.focusY, self.focusZ, # Focus self.upX, self.upY, self.upZ) # Up elif stereoMode == 1: # Toe-in method, uses different eye positions, same focus point and projection proj = matrix.perspective(self.fovAngle, aspect, self.nearPlane, self.farPlane) if eye == 1: mv = lookat(self.eyeX - 0.5 * self.eyeSeparation, self.eyeY, self.eyeZ, # Eye self.focusX, self.focusY, self.focusZ, # Focus self.upX, self.upY, self.upZ) # Up elif eye == 2: mv = lookat(self.eyeX + 0.5 * self.eyeSeparation, self.eyeY, self.eyeZ, # Eye self.focusX, self.focusY, self.focusZ, # Focus self.upX, self.upY, self.upZ) # Up elif stereoMode == 2: # Off-axis method, uses different eye positions, focus points and projections widthdiv2 = math.tan(math.radians(self.fovAngle) / 2) * self.nearPlane left = - aspect * widthdiv2 right = aspect * widthdiv2 top = widthdiv2 bottom = -widthdiv2 if eye == 1: # Left eyePosition = -0.5 * self.eyeSeparation elif eye == 2: # Right eyePosition = 0.5 * self.eyeSeparation else: eyePosition = 0.0 left -= eyePosition * self.nearPlane / self.eyeZ right -= eyePosition * self.nearPlane / self.eyeZ # Left frustum is moved right, right frustum moved left proj = matrix.frustum(left, right, bottom, top, self.nearPlane, self.farPlane) # Left camera is moved left, right camera moved right mv = lookat(self.eyeX + eyePosition, self.eyeY, self.eyeZ, # Eye self.focusX + eyePosition, self.focusY, self.focusZ, # Focus self.upX, self.upY, self.upZ) # Up return proj, mv def getTransform(self): _, mv = self.getMatrices(0) return tuple(np.asarray(mv).flat) transform = property(getTransform, None, None, "The transform of the camera.") @staticmethod def getFlipMatrix(): t = matrix.translate((0, G.windowHeight, 0)) s = matrix.scale((1,-1,1)) return t * s def getConvertToScreenMatrix(self, obj = None): viewport = matrix.viewport(0, 0, G.windowWidth, G.windowHeight) projection, modelview = self.getMatrices(0) m = viewport * projection * modelview if obj: m = m * self.getModelMatrix(obj) return self.getFlipMatrix() * m def convertToScreen(self, x, y, z, obj = None): "Convert 3D OpenGL world coordinates to screen coordinates." m = self.getConvertToScreenMatrix(obj) sx, sy, sz = matrix.transform3(m, [x, y, z]) return [sx, sy, sz] def convertToWorld2D(self, sx, sy, obj = None): "Convert 2D (x, y) screen coordinates to OpenGL world coordinates." sz = gl.queryDepth(sx, sy) return self.convertToWorld3D(sx, sy, sz, obj) def convertToWorld3D(self, sx, sy, sz, obj = None): "Convert 3D (x, y, depth) screen coordinates to 3D OpenGL world coordinates." m = self.getConvertToScreenMatrix(obj) x, y, z = matrix.transform3(m.I, [sx, sy, sz]) return [x, y, z] def getModelMatrix(self, obj): return obj.object.transform def updateCamera(self): pass def setRotation(self, rot): human = G.app.selectedHuman human.setRotation(rot) self.changed() def getRotation(self): human = G.app.selectedHuman return human.getRotation() def addRotation(self, axis, amount): human = G.app.selectedHuman rot = human.getRotation() rot[axis] += amount human.setRotation(rot) self.changed() def addTranslation(self, axis, amount): human = G.app.selectedHuman trans = human.getPosition() trans[axis] += amount human.setPosition(trans) self.changed() def addXYTranslation(self, deltaX, deltaY): (amountX, amountY, _) = self.convertToWorld3D(deltaX, deltaY, 0.0) human = G.app.selectedHuman trans = human.getPosition() trans[0] += amountX trans[1] += amountY human.setPosition(trans) self.changed() def addZoom(self, amount): self.eyeZ += amount self.changed() def mousePickHumanCenter(self, mouseX, mouseY): pass def isInParallelView(self): """ Determine whether this camera is in a 'defined view'. This is a parallel view at a fixed rotation: front, back, left, right, top, bottom. """ rot = self.getRotation() for axis in range(3): if (rot[axis] % 360 ) not in [0, 90, 180, 270]: return False return True def isInLeftView(self): return self.getRotation() == [0, 90, 0] def isInRightView(self): return self.getRotation() == [0, 270, 0] def isInSideView(self): return self.isInLeftView() or self.isInRightView() def isInFrontView(self): return self.getRotation() == [0, 0, 0] def isInBackView(self): return self.getRotation() == [0, 180, 0] def isInTopView(self): return self.getRotation() == [90, 0, 0] def isInBottomView(self): return self.getRotation() == [270, 0, 0] class OrbitalCamera(Camera): """ Orbital camera. A camera that rotates on a sphere that completely encapsulates the human mesh (its bounding box) and that has a zoom factor relative to the sphere radius. Camera is rotated, instead of the meshes as is the case in the old model. """ def __init__(self): super(OrbitalCamera, self).__init__() self.center = [0.0, 0.0, 0.0] self.radius = 1.0 self._fovAngle = 90.0 self.fixedRadius = False self.scaleTranslations = True # Enable to make translations depend on zoom factor (only work when zoomed in) # Ortho mode self._projection = 0 # TODO properly test with projection
#!/usr/bin/env python """ run_1yr_benchmark.py: Driver script for creating benchmark plots and testing gcpy 1-year TransportTracers benchmark capability. Run this script to generate benchmark comparisons between: (1) GCC (aka GEOS-Chem "Classic") vs. GCC (2) GCHP vs GCC (not yet tested) (3) GCHP vs GCHP (not yet tested) You can customize this script by editing the following settings in the "Configurables" section below: (1) Edit the path variables so that they point to folders w/ model data (2) Edit the version strings for each benchmark simulation (3) Edit the switches that turn on/off creating of plots and tables (4) If necessary, edit labels for the dev and ref versions Calling sequence: ./run_1yr_tt_benchmark.py To test gcpy, copy this script anywhere you want to run the test and set gcpy_test to True at the top of the script. Benchmark artifacts will be created locally in new folder called Plots. Remarks: By default, matplotlib will try to open an X window for plotting. If you are running this script in an environment where you do not have an active X display (such as in a computational queue), then you will need to use these commands to disable the X-window functionality. import os os.environ["QT_QPA_PLATFORM"]="offscreen" For more information, please see this issue posted at the ipython site: https://github.com/ipython/ipython/issues/10627 This issue might be fixed in matplotlib 3.0. """ # ===================================================================== # Imports and global settings (you should not need to edit these) # ===================================================================== import os from os.path import join import warnings from calendar import monthrange import numpy as np import xarray as xr from gcpy import benchmark as bmk from gcpy.util import get_filepath, get_filepaths import gcpy.budget_tt as ttbdg import gcpy.ste_flux as ste # Tell matplotlib not to look for an X-window os.environ["QT_QPA_PLATFORM"]="offscreen" # Suppress annoying warning messages warnings.filterwarnings("ignore", category=RuntimeWarning) warnings.filterwarnings("ignore", category=UserWarning) warnings.filterwarnings("ignore", category=FutureWarning) # This script has a fixed benchmark type, year, and months bmk_type = "TransportTracersBenchmark" bmk_year_ref = '2019' bmk_year_dev = '2019' bmk_mon_strs = ["Jan", "Apr", "Jul", "Oct"] bmk_mon_inds = [0, 3, 6, 9] bmk_n_months = len(bmk_mon_strs) ######################################################################## ### CONFIGURABLE SETTINGS: ***EDIT AS NEEDED*** ### ######################################################################## # ===================================================================== # Benchmark information # Note: When doing GCHP vs GCC comparisions gchp_dev will be compared # to gcc_dev (not gcc_ref!). # ===================================================================== # High-level directory containing subdirectories with data maindir = "/n/holyscratch01/external_repos/GEOS-CHEM/gcgrid/geos-chem/validation/gcpy_test_data/1yr_transporttracer" # Version strings # NOTE: these will be used in some filenames and so should not have spaces # or other characters not appropriate for a filename. gcc_ref_version = "GCC_ref" gcc_dev_version = "GCC_dev" gchp_ref_version = "GCHP_ref" gchp_dev_version = "GCHP_dev" # Name to be used for directory of output from this script results_dir = "BenchmarkResults" # Path to regridding weights weightsdir = "/n/holyscratch01/external_repos/GEOS-CHEM/gcgrid/gcdata/ExtData/GCHP/RegriddingWeights" # Path to species_databse.yml spcdb_dir = join(maindir, gcc_dev_version) # ===================================================================== # Specify if this is a gcpy test validation run # ===================================================================== gcpy_test = True # ===================================================================== # Comparisons to run # ===================================================================== gcc_vs_gcc = True gchp_vs_gcc = True gchp_vs_gchp = True # GCHP vs GCC diff of diffs not included in transport tracer benchmark # ===================================================================== # Output to generate (plots/tables will be created in this order): # ===================================================================== plot_conc = True plot_wetdep = True rnpbbe_budget = True operations_budget = True ste_table = True # GCC only cons_table = True # ===================================================================== # Data directories # For gchp_vs_gcc_refdir use gcc_dev_version, not ref (mps, 6/27/19) # ===================================================================== # Diagnostic file directory paths gcc_vs_gcc_refdir = join(maindir, gcc_ref_version, "OutputDir") gcc_vs_gcc_devdir = join(maindir, gcc_dev_version, "OutputDir") gchp_vs_gcc_refdir = join(maindir, gcc_dev_version, "OutputDir") gchp_vs_gcc_devdir = join(maindir, gchp_dev_version, "OutputDir") gchp_vs_gchp_refdir = join(maindir, gchp_ref_version, "OutputDir") gchp_vs_gchp_devdir = join(maindir, gchp_dev_version, "OutputDir") # Restart file directory paths gcc_vs_gcc_refrstdir = join(maindir, gcc_ref_version, "restarts") gcc_vs_gcc_devrstdir = join(maindir, gcc_dev_version, "restarts") gchp_vs_gcc_refrstdir = join(maindir, gcc_dev_version, "restarts") gchp_vs_gcc_devrstdir = join(maindir, gchp_dev_version) gchp_vs_gchp_refrstdir = join(maindir, gchp_ref_version) gchp_vs_gchp_devrstdir = join(maindir, gchp_dev_version) # Plots directories if gcpy_test: mainresultsdir = join('.', results_dir) gcc_vs_gcc_resultsdir = join(mainresultsdir,'GCC_version_comparison') gchp_vs_gcc_resultsdir = join(mainresultsdir,'GCHP_GCC_comparison') gchp_vs_gchp_resultsdir = join(mainresultsdir,'GCHP_version_comparison') if not os.path.exists(mainresultsdir): os.mkdir(mainresultsdir) else: gcc_vs_gcc_resultsdir = join(maindir, gcc_dev_version, results_dir) gchp_vs_gchp_resultsdir = join(maindir, gchp_dev_version, results_dir, "GCHP_version_comparison") gchp_vs_gcc_resultsdir = join(maindir, gchp_dev_version, results_dir, "GCHP_GCC_comparison") base_gchp_resultsdir = join(maindir, gchp_dev_version, results_dir) #make results directories that don't exist for resdir, plotting_type in zip([gcc_vs_gcc_resultsdir, base_gchp_resultsdir, gchp_vs_gchp_resultsdir, gchp_vs_gcc_resultsdir], [gcc_vs_gcc, gchp_vs_gcc or gchp_vs_gchp, gchp_vs_gchp, gchp_vs_gcc]): if plotting_type and not os.path.exists(resdir): os.mkdir(resdir) # Tables directories gcc_vs_gcc_tablesdir = join(gcc_vs_gcc_resultsdir,"Tables") gchp_vs_gcc_tablesdir = join(gchp_vs_gcc_resultsdir,"Tables") gchp_vs_gchp_tablesdir = join(gchp_vs_gchp_resultsdir,"Tables") # ===================================================================== # Plot title strings # For gchp_vs_gcc_refstr use gcc_dev_version, not ref (mps, 6/27/19) # ===================================================================== gcc_vs_gcc_refstr = gcc_ref_version gcc_vs_gcc_devstr = gcc_dev_version gchp_vs_gcc_refstr = gcc_dev_version gchp_vs_gcc_devstr = gchp_dev_version gchp_vs_gchp_refstr = gchp_ref_version gchp_vs_gchp_devstr = gchp_dev_version ######################################################################## ### THE REST OF THESE SETTINGS SHOULD NOT NEED TO BE CHANGED ### ######################################################################## # ===================================================================== # Dates and times -- Ref data # ===================================================================== # Month/year strings for use in tabl4e subdirectories (e.g. Jan2016) bmk_mon_yr_strs_ref = [v + bmk_year_ref for v in bmk_mon_strs] # Get all months array of start datetimes for benchmark year bmk_start_ref = np.datetime64(bmk_year_ref + "-01-01") bmk_end_ref = np.datetime64("{}-01-01".format(int(bmk_year_ref)+1)) all_months_ref = np.arange(bmk_start_ref, bmk_end_ref, step=np.timedelta64(1, "M"), dtype="datetime64[M]") # Get all months array of mid-point datetime per month for benchmark year # and # sec in year # NOTE: GCHP time-averaged files have time in the middle of the month sec_per_yr_ref = 0 all_months_mid_ref = np.zeros(12, dtype="datetime64[h]") for t in range(12): days_in_mon = monthrange(int(bmk_year_ref), t + 1)[1] sec_per_yr_ref += days_in_mon * 86400.0 middle_hr = int(days_in_mon * 24 / 2) delta = np.timedelta64(middle_hr, 'h') all_months_mid_ref[t] = all_months_ref[t].astype("datetime64[h]") + delta # Get subset of month datetimes for only benchmark months bmk_mons_ref = all_months_ref[bmk_mon_inds] bmk_mons_mid_ref = all_months_mid_ref[bmk_mon_inds] # ===================================================================== # Dates and times -- Dev data # ===================================================================== # Month/year strings for use in table subdirectories (e.g. Jan2016) bmk_mon_yr_strs_dev = [v + bmk_year_dev for v in bmk_mon_strs] # Get all months array of start datetimes for benchmark year bmk_start_dev = np.datetime64(bmk_year_dev + "-01-01") bmk_end_dev = np.datetime64("{}-01-01".format(int(bmk_year_dev)+1)) all_months_dev = np.arange(bmk_start_dev, bmk_end_dev, step=np.timedelta64(1, "M"), dtype="datetime64[M]") # Get all months array of mid-point datetime per month for benchmark year # and # sec in year # NOTE: GCHP time-averaged files have time in the middle of the month sec_per_yr_dev = 0 all_months_mid_dev = np.zeros(12, dtype="datetime64[h]") for t in range(12): days_in_mon = monthrange(int(bmk_year_dev), t + 1)[1] sec_per_yr_dev += days_in_mon * 86400.0 middle_hr = int(days_in_mon* 24 / 2) delta = np.timedelta64(middle_hr, 'h') all_months_mid_dev[t] = all_months_dev[t].astype("datetime64[h]") + delta # Get subset of month datetimes for only benchmark months bmk_mons_dev = all_months_dev[bmk_mon_inds] bmk_mons_mid_dev = all_months_mid_dev[bmk_mon_inds] # ====================================================================== # Print the list of plots & tables to the screen # ====================================================================== print("The following plots and tables will be created for {}:".format(bmk_type)) if plot_conc: print(" - Concentration plots") if plot_wetdep: print(" - Convective and large-scale wet deposition plots") if rnpbbe_budget: print(" - Radionuclides budget table") if operations_budget: print(" - Operations budget table") if ste_table: print(" - Table of strat-trop exchange") if cons_table: print(" - Table of mass conservation") print("Comparisons will be made for the following combinations:") if gcc_vs_gcc: print(" - GCC vs GCC") if gchp_vs_gcc: print(" - GCHP vs GCC") if gchp_vs_gchp: print(" - GCHP vs GCHP") # ====================================================================== # Create GCC vs GCC benchmark plots and tables # ====================================================================== if gcc_vs_gcc: # -------------------------------------------------------------- # GCC vs GCC Concentration plots # # Separates RnPbBe tracers and passive tracers into separate files. # -------------------------------------------------------------- if plot_conc: print("\n%%% Creating GCC vs. GCC concentration plots %%%") # Only plot concentration categories for TransportTracers restrict_cats = ["RnPbBeTracers", "PassiveTracers"] # Diagnostic collections to read col = "SpeciesConc" colmet = "StateMet" colmet_gchp="StateMet_avg" # Use this for benchmarks prior to 13.0 # Create concentration plots for each benchmark month for t in range(bmk_n_months): # Time & date quantities reftime = bmk_mons_ref[t] devtime = bmk_mons_dev[t] datestr = bmk_mon_yr_strs_dev[t] # Seasonal diagnostic collection files to read ref = get_filepath(gcc_vs_gcc_refdir, col, reftime) dev = get_filepath(gcc_vs_gcc_devdir, col, devtime) refmet = get_filepath(gcc_vs_gcc_refdir, colmet, reftime) devmet = get_filepath(gcc_vs_gcc_devdir, colmet, devtime) bmk.make_benchmark_conc_plots( ref, gcc_vs_gcc_refstr, dev, gcc_vs_gcc_devstr, refmet=refmet, devmet=devmet, dst=gcc_vs_gcc_resultsdir, subdst=datestr, weightsdir=weightsdir, benchmark_type=bmk_type, restrict_cats=restrict_cats, overwrite=True, spcdb_dir=spcdb_dir ) # -------------------------------------------------------------- # GCC vs GCC wet deposition plots # -------------------------------------------------------------- if plot_wetdep: print("\n%%% Creating GCC vs. GCC wet deposition plots %%%") # Diagnostic collection files to read cols = ["WetLossConv", "WetLossLS"] colmet = "StateMet" colmet_gchp="StateMet_avg" # Use this for benchmarks prior to 13.0 # Loop over wet deposition collections and benchmark months for col in cols: for t in range(bmk_n_months): # Time & date quantities reftime = bmk_mons_ref[t] devtime = bmk_mons_dev[t] datestr = bmk_mon_yr_strs_dev[t] # Seasonal diagnostic collection files to read ref = get_filepath(gcc_vs_gcc_refdir, col, reftime) dev = get_filepath(gcc_vs_gcc_devdir, col, devtime) refmet = get_filepath(gcc_vs_gcc_refdir, colmet, reftime) devmet = get_filepath(gcc_vs_gcc_devdir, colmet, devtime) # Make wet deposition plots bmk.make_benchmark_wetdep_plots( ref, gcc_vs_gcc_refstr, dev, gcc_vs_gcc_devstr, refmet=refmet, devmet=devmet, dst=gcc_vs_gcc_resultsdir, datestr=datestr, weightsdir=weightsdir, benchmark_type=bmk_type, collection=col, overwrite=True, spcdb_dir=spcdb_dir ) # -------------------------------------------------------------- # GCC vs GCC radionuclides budget tables # -------------------------------------------------------------- if rnpbbe_budget: print("\n%%% Creating GCC vs. GCC radionuclides budget table %%%") # Make radionuclides budget table ttbdg.transport_tracers_budgets( gcc_dev_version, gcc_vs_gcc_devdir, gcc_vs_gcc_devrstdir, int(bmk_year_dev), dst=gcc_vs_gcc_tablesdir, overwrite=True, spcdb_dir=spcdb_dir ) # -------------------------------------------------------------- # GCC vs GCC operations budgets tables # -------------------------------------------------------------- if operations_budget: print("\n%%% Creating GCC vs. GCC operations budget tables %%%") #
time.time() # In[ ]: print("Training took {:.2f}s".format(t1 - t0)) # Oh no! Training is actually more than twice slower now! How can that be? Well, as we saw in this chapter, dimensionality reduction does not always lead to faster training time: it depends on the dataset, the model and the training algorithm. See figure 8-6 (the `manifold_decision_boundary_plot*` plots above). If you try a softmax classifier instead of a random forest classifier, you will find that training time is reduced by a factor of 3 when using PCA. Actually, we will do this in a second, but first let's check the precision of the new random forest classifier. # *Exercise: Next evaluate the classifier on the test set: how does it compare to the previous classifier?* # In[ ]: X_test_reduced = pca.transform(X_test) y_pred = rnd_clf2.predict(X_test_reduced) accuracy_score(y_test, y_pred) # It is common for performance to drop slightly when reducing dimensionality, because we do lose some useful signal in the process. However, the performance drop is rather severe in this case. So PCA really did not help: it slowed down training and reduced performance. :( # # Let's see if it helps when using softmax regression: # In[ ]: from sklearn.linear_model import LogisticRegression log_clf = LogisticRegression(multi_class="multinomial", solver="lbfgs", random_state=42) t0 = time.time() log_clf.fit(X_train, y_train) t1 = time.time() # In[ ]: print("Training took {:.2f}s".format(t1 - t0)) # In[ ]: y_pred = log_clf.predict(X_test) accuracy_score(y_test, y_pred) # Okay, so softmax regression takes much longer to train on this dataset than the random forest classifier, plus it performs worse on the test set. But that's not what we are interested in right now, we want to see how much PCA can help softmax regression. Let's train the softmax regression model using the reduced dataset: # In[ ]: log_clf2 = LogisticRegression(multi_class="multinomial", solver="lbfgs", random_state=42) t0 = time.time() log_clf2.fit(X_train_reduced, y_train) t1 = time.time() # In[ ]: print("Training took {:.2f}s".format(t1 - t0)) # Nice! Reducing dimensionality led to over 2× speedup. :) Let's check the model's accuracy: # In[ ]: y_pred = log_clf2.predict(X_test_reduced) accuracy_score(y_test, y_pred) # A very slight drop in performance, which might be a reasonable price to pay for a 2× speedup, depending on the application. # So there you have it: PCA can give you a formidable speedup... but not always! # ## 10. # *Exercise: Use t-SNE to reduce the MNIST dataset down to two dimensions and plot the result using Matplotlib. You can use a scatterplot using 10 different colors to represent each image's target class.* # The MNIST dataset was loaded above. # Dimensionality reduction on the full 60,000 images takes a very long time, so let's only do this on a random subset of 10,000 images: # In[ ]: np.random.seed(42) m = 10000 idx = np.random.permutation(60000)[:m] X = mnist['data'][idx] y = mnist['target'][idx] # Now let's use t-SNE to reduce dimensionality down to 2D so we can plot the dataset: # In[ ]: from sklearn.manifold import TSNE tsne = TSNE(n_components=2, random_state=42) X_reduced = tsne.fit_transform(X) # Now let's use Matplotlib's `scatter()` function to plot a scatterplot, using a different color for each digit: # In[ ]: plt.figure(figsize=(13,10)) plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap="jet") plt.axis('off') plt.colorbar() plt.show() # Isn't this just beautiful? :) This plot tells us which numbers are easily distinguishable from the others (e.g., 0s, 6s, and most 8s are rather well separated clusters), and it also tells us which numbers are often hard to distinguish (e.g., 4s and 9s, 5s and 3s, and so on). # Let's focus on digits 2, 3 and 5, which seem to overlap a lot. # In[ ]: plt.figure(figsize=(9,9)) cmap = mpl.cm.get_cmap("jet") for digit in (2, 3, 5): plt.scatter(X_reduced[y == digit, 0], X_reduced[y == digit, 1], c=[cmap(digit / 9)]) plt.axis('off') plt.show() # Let's see if we can produce a nicer image by running t-SNE on these 3 digits: # In[ ]: idx = (y == 2) | (y == 3) | (y == 5) X_subset = X[idx] y_subset = y[idx] tsne_subset = TSNE(n_components=2, random_state=42) X_subset_reduced = tsne_subset.fit_transform(X_subset) # In[ ]: plt.figure(figsize=(9,9)) for digit in (2, 3, 5): plt.scatter(X_subset_reduced[y_subset == digit, 0], X_subset_reduced[y_subset == digit, 1], c=[cmap(digit / 9)]) plt.axis('off') plt.show() # Much better, now the clusters have far less overlap. But some 3s are all over the place. Plus, there are two distinct clusters of 2s, and also two distinct clusters of 5s. It would be nice if we could visualize a few digits from each cluster, to understand why this is the case. Let's do that now. # *Exercise: Alternatively, you can write colored digits at the location of each instance, or even plot scaled-down versions of the digit images themselves (if you plot all digits, the visualization will be too cluttered, so you should either draw a random sample or plot an instance only if no other instance has already been plotted at a close distance). You should get a nice visualization with well-separated clusters of digits.* # Let's create a `plot_digits()` function that will draw a scatterplot (similar to the above scatterplots) plus write colored digits, with a minimum distance guaranteed between these digits. If the digit images are provided, they are plotted instead. This implementation was inspired from one of Scikit-Learn's excellent examples ([plot_lle_digits](http://scikit-learn.org/stable/auto_examples/manifold/plot_lle_digits.html), based on a different digit dataset). # In[ ]: from sklearn.preprocessing import MinMaxScaler from matplotlib.offsetbox import AnnotationBbox, OffsetImage def plot_digits(X, y, min_distance=0.05, images=None, figsize=(13, 10)): # Let's scale the input features so that they range from 0 to 1 X_normalized = MinMaxScaler().fit_transform(X) # Now we create the list of coordinates of the digits plotted so far. # We pretend that one is already plotted far away at the start, to # avoid `if` statements in the loop below neighbors = np.array([[10., 10.]]) # The rest should be self-explanatory plt.figure(figsize=figsize) cmap = mpl.cm.get_cmap("jet") digits = np.unique(y) for digit in digits: plt.scatter(X_normalized[y == digit, 0], X_normalized[y == digit, 1], c=[cmap(digit / 9)]) plt.axis("off") ax = plt.gcf().gca() # get current axes in current figure for index, image_coord in enumerate(X_normalized): closest_distance = np.linalg.norm(neighbors - image_coord, axis=1).min() if closest_distance > min_distance: neighbors = np.r_[neighbors, [image_coord]] if images is None: plt.text(image_coord[0], image_coord[1], str(int(y[index])), color=cmap(y[index] / 9), fontdict={"weight": "bold", "size": 16}) else: image = images[index].reshape(28, 28) imagebox = AnnotationBbox(OffsetImage(image, cmap="binary"), image_coord) ax.add_artist(imagebox) # Let's try it! First let's just write colored digits: # In[ ]: plot_digits(X_reduced, y) # Well that's okay, but not that beautiful. Let's try with the digit images: # In[ ]: plot_digits(X_reduced, y, images=X, figsize=(35, 25)) # In[ ]: plot_digits(X_subset_reduced, y_subset, images=X_subset, figsize=(22, 22)) # *Exercise: Try using other dimensionality reduction algorithms such as PCA, LLE, or MDS and compare the resulting visualizations.* # Let's start with PCA. We will also time how long it takes: # In[ ]: from sklearn.decomposition import PCA import time t0 = time.time() X_pca_reduced = PCA(n_components=2, random_state=42).fit_transform(X) t1 = time.time() print("PCA took {:.1f}s.".format(t1 - t0)) plot_digits(X_pca_reduced, y) plt.show() # Wow, PCA is blazingly fast! But although we do see a few clusters, there's way too much overlap. Let's try LLE: # In[ ]: from sklearn.manifold import LocallyLinearEmbedding t0 = time.time() X_lle_reduced = LocallyLinearEmbedding(n_components=2, random_state=42).fit_transform(X) t1 = time.time() print("LLE took {:.1f}s.".format(t1 - t0)) plot_digits(X_lle_reduced, y) plt.show() # That took a while, and the result does not look too good. Let's see what happens if we apply PCA first, preserving 95% of the variance: # In[ ]: from sklearn.pipeline import Pipeline pca_lle = Pipeline([ ("pca", PCA(n_components=0.95, random_state=42)), ("lle", LocallyLinearEmbedding(n_components=2, random_state=42)), ]) t0 = time.time() X_pca_lle_reduced = pca_lle.fit_transform(X) t1 = time.time() print("PCA+LLE took {:.1f}s.".format(t1 - t0)) plot_digits(X_pca_lle_reduced, y) plt.show() # The result is more or less the same, but this time it was almost 4× faster. # Let's try MDS. It's much too long if we run it on 10,000 instances, so let's just try 2,000 for now: # In[ ]: from sklearn.manifold import MDS m = 2000 t0 = time.time() X_mds_reduced = MDS(n_components=2, random_state=42).fit_transform(X[:m]) t1 = time.time() print("MDS took {:.1f}s (on just 2,000 MNIST images instead of 10,000).".format(t1 - t0)) plot_digits(X_mds_reduced, y[:m]) plt.show() # Meh. This does not look great, all clusters overlap too much. Let's try with PCA first, perhaps it will be faster? # In[ ]: from sklearn.pipeline import Pipeline pca_mds = Pipeline([ ("pca", PCA(n_components=0.95, random_state=42)), ("mds", MDS(n_components=2, random_state=42)), ]) t0 = time.time() X_pca_mds_reduced = pca_mds.fit_transform(X[:2000]) t1 = time.time() print("PCA+MDS took {:.1f}s (on 2,000 MNIST images).".format(t1 - t0)) plot_digits(X_pca_mds_reduced, y[:2000]) plt.show() # Same result, and no speedup: PCA did not help (or hurt). # Let's try LDA: # In[ ]: from sklearn.discriminant_analysis import LinearDiscriminantAnalysis t0 = time.time() X_lda_reduced = LinearDiscriminantAnalysis(n_components=2).fit_transform(X, y) t1 = time.time() print("LDA took {:.1f}s.".format(t1 - t0)) plot_digits(X_lda_reduced, y, figsize=(12,12)) plt.show() # This one is very fast, and it looks nice at first, until you realize that several clusters overlap severely. # Well, it's
support existing_axes that aren't a slice by using transpose, # but that could lead to unpredictable performance consequences because # transposes are not free in TensorFlow. If we did transpose # automatically, the user might never realize that their data is being # produced with the wrong order. (The later will occur with some frequency # because of how broadcasting automatically choose axis order.) # So for now we've taken the strict approach. raise core.AxisOrderError( 'existing_axes %r are not a slice of axis names %r on the input ' 'labeled tensor. Use `transpose` or `impose_axis_order` to reorder ' 'axes on the input explicitly.' % (existing_axes, original_axis_names)) if sum(isinstance(axis, string_types) for axis in new_axes) > 1: raise ValueError( 'at most one axis in new_axes can have unknown size. All other ' 'axes must have an indicated integer size or labels: %r' % new_axes) original_values = list(labeled_tensor.axes.values()) axis_size = lambda axis: -1 if axis.size is None else axis.size shape = [axis_size(axis) for axis in original_values[:start]] for axis_ref in new_axes: if isinstance(axis_ref, string_types): shape.append(-1) else: axis = core.as_axis(axis_ref) shape.append(axis_size(axis)) shape.extend(axis_size(axis) for axis in original_values[stop:]) reshaped_tensor = array_ops.reshape( labeled_tensor.tensor, shape, name=scope) axes = original_values[:start] + list(new_axes) + original_values[stop:] return core.LabeledTensor(reshaped_tensor, axes) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, string_types, string_types, tc.Optional(string_types)) def rename_axis(labeled_tensor, existing_name, new_name, name=None): """Rename an axis of LabeledTensor. Args: labeled_tensor: The input tensor. existing_name: Name for an existing axis on the input. new_name: Desired replacement name. name: Optional op name. Returns: LabeledTensor with renamed axis. Raises: ValueError: If `existing_name` is not an axis on the input. """ with ops.name_scope(name, 'lt_rename_axis', [labeled_tensor]) as scope: if existing_name not in labeled_tensor.axes: raise ValueError('existing_name %r are not contained in the set of axis ' 'names %r on the input labeled tensor' % (existing_name, labeled_tensor.axes.keys())) new_axis = core.Axis(new_name, labeled_tensor.axes[existing_name].value) return reshape(labeled_tensor, [existing_name], [new_axis], name=scope) @tc.returns(tc.List(core.LabeledTensor)) @tc.accepts(string_types, collections.Callable, int, bool, tc.Collection(core.LabeledTensorLike), bool, tc.Optional(string_types)) def _batch_helper(default_name, batch_fn, batch_size, enqueue_many, labeled_tensors, allow_smaller_final_batch, name=None): with ops.name_scope(name, default_name, labeled_tensors) as scope: labeled_tensors = [ core.convert_to_labeled_tensor(lt) for lt in labeled_tensors ] batch_ops = batch_fn([t.tensor for t in labeled_tensors], scope) # TODO(shoyer): Remove this when they sanitize the TF API. if not isinstance(batch_ops, list): assert isinstance(batch_ops, ops.Tensor) batch_ops = [batch_ops] if allow_smaller_final_batch: batch_size = None @tc.returns(core.Axes) @tc.accepts(core.Axes) def output_axes(axes): if enqueue_many: if 'batch' not in axes or list(axes.keys()).index('batch') != 0: raise ValueError( 'When enqueue_many is True, input tensors must have an axis ' 'called "batch" as their first dimension, ' 'but axes were %s' % axes) culled_axes = axes.remove('batch') return core.Axes([('batch', batch_size)] + list(culled_axes.values())) else: return core.Axes([('batch', batch_size)] + list(axes.values())) output_labeled_tensors = [] for i, tensor in enumerate(batch_ops): axes = output_axes(labeled_tensors[i].axes) output_labeled_tensors.append(core.LabeledTensor(tensor, axes)) return output_labeled_tensors @tc.returns(tc.List(core.LabeledTensor)) @tc.accepts( tc.Collection(core.LabeledTensorLike), int, int, int, bool, bool, tc.Optional(string_types)) def batch(labeled_tensors, batch_size, num_threads=1, capacity=32, enqueue_many=False, allow_smaller_final_batch=False, name=None): """Rebatch a tensor. See tf.batch. Args: labeled_tensors: The input tensors. batch_size: The output batch size. num_threads: See tf.batch. capacity: See tf.batch. enqueue_many: If true, the input tensors must contain a 'batch' axis as their first axis. If false, the input tensors must not contain a 'batch' axis. See tf.batch. allow_smaller_final_batch: See tf.batch. name: Optional op name. Returns: The rebatched tensors. If enqueue_many is false, the output tensors will have a new 'batch' axis as their first axis. Raises: ValueError: If enqueue_many is True and the first axis of the tensors isn't "batch". """ def fn(tensors, scope): return input.batch( tensors, batch_size=batch_size, num_threads=num_threads, capacity=capacity, enqueue_many=enqueue_many, allow_smaller_final_batch=allow_smaller_final_batch, name=scope) return _batch_helper('lt_batch', fn, batch_size, enqueue_many, labeled_tensors, allow_smaller_final_batch, name) @tc.returns(tc.List(core.LabeledTensor)) @tc.accepts( tc.Collection(core.LabeledTensorLike), int, int, int, bool, int, tc.Optional(int), bool, tc.Optional(string_types)) def shuffle_batch(labeled_tensors, batch_size, num_threads=1, capacity=32, enqueue_many=False, min_after_dequeue=0, seed=None, allow_smaller_final_batch=False, name=None): """Rebatch a tensor, with shuffling. See tf.batch. Args: labeled_tensors: The input tensors. batch_size: The output batch size. num_threads: See tf.batch. capacity: See tf.batch. enqueue_many: If true, the input tensors must contain a 'batch' axis as their first axis. If false, the input tensors must not contain a 'batch' axis. See tf.batch. min_after_dequeue: Minimum number of elements in the queue after a dequeue, used to ensure mixing. seed: Optional random seed. allow_smaller_final_batch: See tf.batch. name: Optional op name. Returns: The rebatched tensors. If enqueue_many is false, the output tensors will have a new 'batch' axis as their first axis. Raises: ValueError: If enqueue_many is True and the first axis of the tensors isn't "batch". """ def fn(tensors, scope): return input.shuffle_batch( tensors, batch_size=batch_size, num_threads=num_threads, capacity=capacity, enqueue_many=enqueue_many, min_after_dequeue=min_after_dequeue, seed=seed, allow_smaller_final_batch=allow_smaller_final_batch, name=scope) return _batch_helper('lt_shuffle_batch', fn, batch_size, enqueue_many, labeled_tensors, allow_smaller_final_batch, name) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Mapping(string_types, int), tc.Optional(int), tc.Optional(string_types)) def random_crop(labeled_tensor, shape_map, seed=None, name=None): """Randomly crops a tensor to a given size. See tf.random_crop. Args: labeled_tensor: The input tensor. shape_map: A dictionary mapping axis names to the size of the random crop for that dimension. seed: An optional random seed. name: An optional op name. Returns: A tensor of the same rank as `labeled_tensor`, cropped randomly in the selected dimensions. Raises: ValueError: If the shape map contains an axis name not in the input tensor. """ with ops.name_scope(name, 'lt_random_crop', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) for axis_name in shape_map: if axis_name not in labeled_tensor.axes: raise ValueError('Selection axis %s not in axes %s' % (axis_name, labeled_tensor.axes)) shape = [] axes = [] for axis in labeled_tensor.axes.values(): if axis.name in shape_map: size = shape_map[axis.name] shape.append(size) # We lose labels for the axes we crop, leaving just the size. axes.append((axis.name, size)) else: shape.append(len(axis)) axes.append(axis) crop_op = random_ops.random_crop( labeled_tensor.tensor, shape, seed=seed, name=scope) return core.LabeledTensor(crop_op, axes) # TODO(shoyer): Allow the user to select the axis over which to map. @tc.returns(core.LabeledTensor) @tc.accepts(collections.Callable, core.LabeledTensorLike, tc.Optional(string_types)) def map_fn(fn, labeled_tensor, name=None): """Map on the list of tensors unpacked from labeled_tensor. See tf.map_fn. Args: fn: The function to apply to each unpacked LabeledTensor. It should have type LabeledTensor -> LabeledTensor. labeled_tensor: The input tensor. name: Optional op name. Returns: A tensor that packs the results of applying fn to the list of tensors unpacked from labeled_tensor. """ with ops.name_scope(name, 'lt_map_fn', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) unpack_lts = unpack(labeled_tensor) # TODO(ericmc): Fix this upstream. if labeled_tensor.dtype == dtypes.string: # We must construct the full graph here, because functional_ops.map_fn # doesn't work for string-valued tensors. # Constructing the full graph may be slow. map_lts = [fn(t) for t in unpack_lts] return pack(map_lts, list(labeled_tensor.axes.values())[0], name=scope) else: # Figure out what the axis labels should be, but use tf.map_fn to # construct the graph because it's efficient. # It may be slow to construct the full graph, so we infer the labels from # the first element. # TODO(ericmc): This builds a subgraph which then gets thrown away. # Find a more elegant solution. first_map_lt = fn(unpack_lts[0]) final_axes = list(labeled_tensor.axes.values())[:1] + list( first_map_lt.axes.values()) @tc.returns(ops.Tensor) @tc.accepts(ops.Tensor) def tf_fn(tensor): original_axes = list(labeled_tensor.axes.values())[1:] tensor_lt = core.LabeledTensor(tensor, original_axes) return fn(tensor_lt).tensor map_op = functional_ops.map_fn(tf_fn, labeled_tensor.tensor) map_lt = core.LabeledTensor(map_op, final_axes) return core.identity(map_lt, name=scope) @tc.returns(core.LabeledTensor) @tc.accepts(collections.Callable, core.LabeledTensorLike, core.LabeledTensorLike, tc.Optional(string_types)) def foldl(fn, labeled_tensor, initial_value, name=None): """Left fold on the list of tensors unpacked from labeled_tensor. See tf.foldl. Args: fn: The function to apply to each unpacked LabeledTensor. It should have type (LabeledTensor, LabeledTensor) -> LabeledTensor. Its arguments are (accumulated_value, next_value). labeled_tensor: The input tensor. initial_value: The initial value of the accumulator. name: Optional op name. Returns: The accumulated value. """ with ops.name_scope(name, 'lt_foldl', [labeled_tensor, initial_value]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) initial_value = core.convert_to_labeled_tensor(initial_value) @tc.returns(ops.Tensor) @tc.accepts(ops.Tensor, ops.Tensor) def tf_fn(accumulator, next_element): accumulator_lt = core.LabeledTensor(accumulator, initial_value.axes) next_element_lt = core.LabeledTensor( next_element, list(labeled_tensor.axes.values())[1:]) return fn(accumulator_lt, next_element_lt).tensor foldl_op = functional_ops.foldl( tf_fn, labeled_tensor.tensor, initializer=initial_value.tensor) foldl_lt = core.LabeledTensor(foldl_op, initial_value.axes) return core.identity(foldl_lt, name=scope) @tc.returns(core.LabeledTensor) @tc.accepts(core.LabeledTensorLike, tc.Optional(tc.Collection(string_types)), tc.Optional(string_types)) def squeeze(labeled_tensor, axis_names=None, name=None): """Remove size-1 dimensions. See tf.squeeze. Args: labeled_tensor: The input tensor. axis_names: The names of the dimensions to remove, or None to remove all size-1 dimensions. name: Optional op name. Returns: A tensor with the specified dimensions removed. Raises: ValueError: If the named axes are not in the tensor, or if they are not size-1. """ with ops.name_scope(name, 'lt_squeeze', [labeled_tensor]) as scope: labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor) if axis_names is None: axis_names = [a.name for a in labeled_tensor.axes.values() if len(a) == 1] for axis_name in axis_names: if axis_name not in labeled_tensor.axes: raise ValueError('axis %s is not
from __future__ import print_function from __future__ import absolute_import from builtins import zip from builtins import range from . import parobject as php import numpy as nm import re def base_smica(root_grp, hascl, lmin, lmax, nT, nP, wq, rqhat, Acmb, rq0=None, bins=None): if bins == None: nbins = 0 else: bins.shape = (-1, (lmax + 1 - lmin) * nm.sum(hascl)) nbins = bins.shape[0] bins = bins.flat[:] lkl_grp = php.add_lkl_generic( root_grp, "smica", 1, hascl, lmax, lmin, nbins=nbins, bins=bins) lkl_grp.attrs["m_channel_T"] = nT lkl_grp.attrs["m_channel_P"] = nP lkl_grp.create_dataset('wq', data=wq) lkl_grp.create_dataset("Rq_hat", data=rqhat.flat[:]) if rq0 != None: lkl_grp.create_dataset("Rq_0", data=rq0.flat[:]) lkl_grp.attrs["A_cmb"] = Acmb lkl_grp.attrs["n_component"] = 1 return lkl_grp def remove_component(lkl_grp, position): nc = lkl_grp.attrs["n_component"] assert position <= nc for ic in range(position, nc - 1): del lkl_grp["component_%d" % (ic)] lkl_grp.copy("component_%d" % (ic + 1), "component_%d" % ic) del lkl_grp["component_%d" % (nc - 1)] lkl_grp.attrs["n_component"] = nc - 1 def add_component(lkl_grp, typ, position=-1): nc = lkl_grp.attrs["n_component"] if position == -1: position = nc assert position <= nc for ic in range(nc, position, -1): lkl_grp.copy("component_%d" % (ic - 1), "component_%d" % ic) del lkl_grp["component_%d" % (ic - 1)] agrp = lkl_grp.create_group("component_%d" % (position)) agrp.attrs["component_type"] = typ lkl_grp.attrs["n_component"] = nc + 1 return agrp def add_cst_component(lkl_grp, rq0, position=-1): agrp = add_component(lkl_grp, "cst", position) agrp.create_dataset("Rq_0", data=rq0.flat[:]) return agrp def add_cst_component_pars(lkl_grp, pars): rq0 = php.read_somearray(pars.rq0) return add_cst_component(lkl_grp, rq0) def add_gcal_component(lkl_grp, typ, ngcal, gcaltpl, binned=False, names=[], position=-1): if typ.lower() == "log": typ = "gcal_log" else: typ = "gcal_lin" agrp = add_component(lkl_grp, typ, position) agrp.attrs["ngcal"] = nm.array(ngcal, dtype=nm.int) agrp.create_dataset("gcaltpl", data=nm.array( gcaltpl, dtype=nm.double).flat[:]) if binned: agrp.attrs["binned"] = 1 else: agrp.attrs["binned"] = 0 if names: setnames(agrp, names) return agrp def get_dnames(lkl_grp): if "dnames" in lkl_grp.attrs: dnames = [v for v in lkl_grp.attrs["dnames"].split('\0') if v] return dnames else: raise Exception("argl") def add_beamTP_component(lkl_grp, names, neigen, modes, p_track_t, position=-1): typ = "beamTP" im = [] hascl = lkl_grp.attrs["has_cl"] mt = lkl_grp.attrs["m_channel_T"] * hascl[0] mp = lkl_grp.attrs["m_channel_P"] * (hascl[1] or hascl[2]) me = lkl_grp.attrs["m_channel_P"] * hascl[1] mb = lkl_grp.attrs["m_channel_P"] * hascl[2] m = mt + me + mb im = nm.zeros((m, m, neigen), dtype=nm.int) bm_names = [] dnames = get_dnames(lkl_grp) # print p_track_t for i, n in enumerate(names): if "beam" in n: det1, det2, bm = re.findall("beam_(.+)x(.+)_(\d)", n)[0] # print det1,det2,bm idx1 = dnames.index(det1) idx2 = dnames.index(det2) # print idx1,idx2 if idx2 < idx1: idx2, idx1 = idx1, idx2 bm_names += [n] lbm = len(bm_names) # print lbm if idx1 < mt and idx2 < mt: # easy im[idx1, idx2, bm] = lbm im[idx2, idx1, bm] = im[idx1, idx2, bm] if me and p_track_t: im[idx2, idx1 + mt, bm] = lbm im[idx1 + mt, idx2, bm] = im[idx2, idx1 + mt, bm] im[idx1, idx2 + mt, bm] = lbm im[idx2 + mt, idx1, bm] = im[idx1, idx2 + mt, bm] im[idx1 + mt, idx2 + mt, bm] = lbm im[idx2 + mt, idx1 + mt, bm] = im[idx1 + mt, idx2 + mt, bm] if mb and p_track_t: im[idx2, idx1 + mt + me, bm] = lbm im[idx1 + mt + me, idx2, bm] = im[idx2, idx1 + mt + me, bm] im[idx1, idx2 + mt + me, bm] = lbm im[idx2 + mt + me, idx1, bm] = im[idx1, idx2 + mt + me, bm] im[idx1 + mt + me, idx2 + mt + me, bm] = lbm im[idx2 + mt + me, idx1 + mt + me, bm] = im[idx1 + mt + me, idx2 + mt + me, bm] if me and mb and p_track_t: im[idx2 + mt, idx1 + mt + me, bm] = lbm im[idx1 + mt + me, idx2 + mt, bm] = im[idx2 + mt, idx1 + mt + me, bm] im[idx1 + mt, idx2 + mt + me, bm] = lbm im[idx2 + mt + me, idx1 + mt, bm] = im[idx1 + mt, idx2 + mt + me, bm] if idx1 >= mt and idx2 >= mt: # deal with it ! im[idx1, idx2, bm] = lbm im[idx2, idx1, bm] = im[idx1, idx2, bm] if mb: im[idx1 + me, idx2 + me, bm] = lbm im[idx2 + me, idx1 + me, bm] = im[idx1 + me, idx2 + me, bm] im[idx1, idx2 + me, bm] = lbm im[idx2 + me, idx1, bm] = im[idx1, idx2 + me, bm] im[idx2, idx1 + me, bm] = lbm im[idx1 + me, idx2, bm] = im[idx2, idx1 + me, bm] if idx2 >= mt and idx1 < mt: im[idx1, idx2, bm] = lbm im[idx1 + mt, idx2 - mt, bm] = lbm im[idx2, idx1, bm] = lbm im[idx2 - mt, idx1 + mt, bm] = lbm if mb: im[idx1, idx2 + me, bm] = lbm im[idx1 + mt + me, idx2 - mt, bm] = lbm im[idx2 + me, idx1, bm] = lbm im[idx2 - mt, idx1 + mt + me, bm] = lbm #raise NotImplementedError("not done yet. It's late...") if len(bm_names): agrp = add_component(lkl_grp, typ, position) agrp.create_dataset("im", data=nm.array(im.flat[:], dtype=nm.int)) agrp["neigen"] = neigen agrp["npar"] = len(bm_names) agrp.create_dataset("modes", data=nm.array( modes.flat[:], dtype=nm.double)) setnames(agrp, bm_names) def add_totcal_component(lkl_grp, calname, position=-1): typ = "totcal" agrp = add_component(lkl_grp, typ, position) agrp["calname"] = calname return agrp def add_totcalP_component(lkl_grp, calname, position=-1): typ = "totcalP" agrp = add_component(lkl_grp, typ, position) agrp["calnameP"] = calname return agrp def add_calTP_component(lkl_grp, names, calib_order, P_track_T, symetrize, position=-1): typ = "calTP" im = [] dnames = get_dnames(lkl_grp) for i, n in enumerate(names): if "calib" in n: det = re.findall("calib_(.+)", n)[0] idx = dnames.index(det) im += [idx] if len(im): agrp = add_component(lkl_grp, typ, position) agrp.create_dataset("im", data=nm.array(im, dtype=nm.int)) hascl = lkl_grp.attrs["has_cl"] mt = lkl_grp.attrs["m_channel_T"] mp = lkl_grp.attrs["m_channel_P"] me = lkl_grp.attrs["m_channel_P"] * hascl[1] mb = lkl_grp.attrs["m_channel_P"] * hascl[2] m = mt + me + mb t_order = calib_order[:mt] p_order = calib_order[mt:] w = nm.zeros((m, m, 2), dtype=nm.double) other = nm.zeros((m, m, 2), dtype=nm.int) for i1 in range(m): alti1 = i1 if i1 >= mt and i1 < mt + me and p_order[i1 - mt] in t_order: alti1 = t_order.index(p_order[i1 - mt]) elif i1 >= mt + me and p_order[i1 - mt - me] in t_order: alti1 = t_order.index(p_order[i1 - mt - me]) for i2 in range(i1, m): alti2 = i2 if i2 >= mt and i2 < mt + me and p_order[i2 - mt] in t_order: alti2 = t_order.index(p_order[i2 - mt]) elif i2 >= mt + me and p_order[i2 - mt - me] in t_order: alti2 = t_order.index(p_order[i2 - mt - me]) # general case, nothing to do w[i1, i2] = [1, 0] other[i1, i2] = [i1, i2] w[i2, i1] = [1, 0] other[i2, i1] = [i2, i1] if i1 < mt and i2 >= mt and i2 < mt + me: # TE if P_track_T and p_order[i2 - mt] in t_order: w[i1, i2] = [0, 1] other[i1, i2] = [i1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, i1] elif symetrize and p_order[i2 - mt] in t_order and t_order[i1] in p_order: w[i1, i2] = [0.5, 0.5] other[i1, i2] = [p_order.index( t_order[i1]) + mt, alti2] w[i2, i1] = [0.5, 0.5] other[i2, i1] = [ alti2, p_order.index(t_order[i1]) + mt] elif i1 < mt and i2 >= mt + me: # TB if P_track_T and p_order[i2 - mt - me] in t_order: w[i1, i2] = [0, 1] other[i1, i2] = [i1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, i1] elif symetrize and p_order[i2 - mt - me] in t_order and t_order[i1] in p_order: w[i1, i2] = [0.5, 0.5] other[i1, i2] = [p_order.index( t_order[i1]) + mt + me, alti2] w[i2, i1] = [0.5, 0.5] other[i2, i1] = [ alti2, p_order.index(t_order[i1]) + mt + me] elif i1 >= mt and i1 < mt + me and i2 < mt + me: # EE if P_track_T: w[i1, i2] = [0, 1] other[i1, i2] = [alti1, alti2] w[i2, i1] = [0, 1] other[i2, i1] = [alti2, alti1] elif i1 >= mt and i1 < mt + me and i2 >= mt + me: # EB if P_track_T: w[i1, i2] = [0, 1] other[i1,