prompt
stringlengths
15
655k
completion
stringlengths
3
32.4k
api
stringlengths
8
52
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function import os import glob import tqdm import fitsio import numpy as np from functools import partial from sklearn.decomposition import PCA from scipy import interpolate from scipy.signal import medfilt2d as mf from scipy.interpolate import interp1d from multiprocessing import Pool from eleanor import fill_grid # Pre-compute the low pass filter fc = 0.12 b = 0.08 N = int(np.ceil((4 / b))) if not N % 2: N += 1 n = np.arange(N) sinc_func = np.sinc(2 * fc * (n - (N - 1) / 2.)) window = 0.42 - 0.5 * np.cos(2 * np.pi * n / (N - 1)) window += 0.08 * np.cos(4 * np.pi * n / (N - 1)) sinc_func = sinc_func * window sinc_func = sinc_func / np.sum(sinc_func) def lowpass(vec): new_signal = np.convolve(vec, sinc_func) lns = len(new_signal) diff = int(np.abs(lns - len(vec))/2) # low pass filter to remove high order modes return new_signal[diff:-diff] def do_pca(i, j, data, factor, q): xvals = np.dot(factor, data[i,j,:][q]) return xvals def calc_2dbkg(flux, qual, time, fast=True): q = qual == 0 med = np.percentile(flux[:,:,:], 1, axis=(2)) # build a single frame in shape of detector. This was once the median image, not sure why it was changed med = med-mf(med, 21) # subtract off median to remove stable background emission, which is especially apparent in corners g = np.ma.masked_where(med < np.percentile(med, 70.), med) # mask which should separate pixels dominated by starlight from background modes = 21 X = flux[g.mask][:, q] pca = PCA(n_components=modes) pca.fit(X) pv = pca.components_[0:modes] vv = np.column_stack((pv)) for i in range(-15, 16, 3): if i != 0: if i > 0: rolled = np.pad(pv, ((0,0),(i,0)), mode='constant')[:, :-i].T else: rolled = np.pad(pv, ((0,0),(0,-i)), mode='constant')[:, -i:].T # assumption: background is a linear sum of what is seen on pixels on the # detector. Because the earthshine varies with axis, this can be time-shifted # so that individual pixels see the same response at different times vv = np.column_stack((vv, rolled)) vv = np.column_stack((vv, np.ones_like(vv[:,0]))) factor = np.linalg.solve(np.dot(vv.T, vv), vv.T) maskvals = np.ma.masked_array(data=np.zeros((104,148,np.shape(vv)[1])), mask=np.zeros((104,148,np.shape(vv)[1]))) for i in range(len(g)): for j in range(len(g[0])): if g.mask[i][j] == True: maskvals.data[i, j] = do_pca(i, j, flux, factor, q) # build eigenvectors to model the background at each pixel noval = maskvals.data[:,:,:] == 0 maskvals.mask[noval] = True outmeasure =
np.zeros_like(maskvals[:,:,0])
numpy.zeros_like
# -*- coding: utf-8 -*- # Copyright (c) 2015, <NAME>, <NAME> # Licensed under the BSD 3-clause license (see LICENSE.txt) """ Classes in this module enhance several stationary covariance functions with the Stochastic Differential Equation (SDE) functionality. """ from .rbf import RBF from .stationary import Exponential from .stationary import RatQuad import numpy as np import scipy as sp try: from scipy.linalg import solve_continuous_lyapunov as lyap except ImportError: from scipy.linalg import solve_lyapunov as lyap import warnings class sde_RBF(RBF): """ Class provide extra functionality to transfer this covariance function into SDE form. Radial Basis Function kernel: .. math:: k(r) = \sigma^2 \exp \\bigg(- \\frac{1}{2} r^2 \\bigg) \\ \\ \\ \\ \text{ where } r = \sqrt{\sum_{i=1}^{input dim} \frac{(x_i-y_i)^2}{\ell_i^2} } """ def __init__(self, *args, **kwargs): """ Init constructior. Two optinal extra parameters are added in addition to the ones in RBF kernel. :param approx_order: approximation order for the RBF covariance. (Default 10) :type approx_order: int :param balance: Whether to balance this kernel separately. (Defaulf True). Model has a separate parameter for balancing. :type balance: bool """ if 'balance' in kwargs: self.balance = bool( kwargs.get('balance') ) del kwargs['balance'] else: self.balance = True if 'approx_order' in kwargs: self.approx_order = kwargs.get('approx_order') del kwargs['approx_order'] else: self.approx_order = 6 super(sde_RBF, self).__init__(*args, **kwargs) def sde_update_gradient_full(self, gradients): """ Update gradient in the order in which parameters are represented in the kernel """ self.variance.gradient = gradients[0] self.lengthscale.gradient = gradients[1] def sde(self): """ Return the state space representation of the covariance. Note! For Sparse GP inference too small or two high values of lengthscale lead to instabilities. This is because Qc are too high or too low and P_inf are not full rank. This effect depends on approximatio order. For N = 10. lengthscale must be in (0.8,8). For other N tests must be conducted. N=6: (0.06,31) Variance should be within reasonable bounds as well, but its dependence is linear. The above facts do not take into accout regularization. """ #import pdb; pdb.set_trace() if self.approx_order is not None: N = self.approx_order else: N = 10# approximation order ( number of terms in exponent series expansion) roots_rounding_decimals = 6 fn = np.math.factorial(N) p_lengthscale = float( self.lengthscale ) p_variance = float(self.variance) kappa = 1.0/2.0/p_lengthscale**2 Qc = np.array( ((p_variance*np.sqrt(np.pi/kappa)*fn*(4*kappa)**N,),) ) eps = 1e-12 if (float(Qc) > 1.0/eps) or (float(Qc) < eps): warnings.warn("""sde_RBF kernel: the noise variance Qc is either very large or very small. It influece conditioning of P_inf: {0:e}""".format(float(Qc)) ) pp1 = np.zeros((2*N+1,)) # array of polynomial coefficients from higher power to lower for n in range(0, N+1): # (2N+1) - number of polynomial coefficients pp1[2*(N-n)] = fn*(4.0*kappa)**(N-n)/np.math.factorial(n)*(-1)**n pp = sp.poly1d(pp1) roots = sp.roots(pp) neg_real_part_roots = roots[np.round(np.real(roots) ,roots_rounding_decimals) < 0] aa = sp.poly1d(neg_real_part_roots, r=True).coeffs F = np.diag(np.ones((N-1,)),1) F[-1,:] = -aa[-1:0:-1] L= np.zeros((N,1)) L[N-1,0] = 1 H = np.zeros((1,N)) H[0,0] = 1 # Infinite covariance: Pinf = lyap(F, -np.dot(L,np.dot( Qc[0,0],L.T))) Pinf = 0.5*(Pinf + Pinf.T) # Allocating space for derivatives dF = np.empty([F.shape[0],F.shape[1],2]) dQc = np.empty([Qc.shape[0],Qc.shape[1],2]) dPinf = np.empty([Pinf.shape[0],Pinf.shape[1],2]) # Derivatives: dFvariance = np.zeros(F.shape) dFlengthscale = np.zeros(F.shape) dFlengthscale[-1,:] = -aa[-1:0:-1]/p_lengthscale * np.arange(-N,0,1) dQcvariance = Qc/p_variance dQclengthscale = np.array(( (p_variance*np.sqrt(2*np.pi)*fn*2**N*p_lengthscale**(-2*N)*(1-2*N),),)) dPinf_variance = Pinf/p_variance lp = Pinf.shape[0] coeff = np.arange(1,lp+1).reshape(lp,1) + np.arange(1,lp+1).reshape(1,lp) - 2 coeff[np.mod(coeff,2) != 0] = 0 dPinf_lengthscale = -1/p_lengthscale*Pinf*coeff dF[:,:,0] = dFvariance dF[:,:,1] = dFlengthscale dQc[:,:,0] = dQcvariance dQc[:,:,1] = dQclengthscale dPinf[:,:,0] = dPinf_variance dPinf[:,:,1] = dPinf_lengthscale P0 = Pinf.copy() dP0 = dPinf.copy() if self.balance: # Benefits of this are not very sound. Helps only in one case: # SVD Kalman + RBF kernel import GPy.models.state_space_main as ssm (F, L, Qc, H, Pinf, P0, dF, dQc, dPinf,dP0) = ssm.balance_ss_model(F, L, Qc, H, Pinf, P0, dF, dQc, dPinf, dP0 ) return (F, L, Qc, H, Pinf, P0, dF, dQc, dPinf, dP0) class sde_Exponential(Exponential): """ Class provide extra functionality to transfer this covariance function into SDE form. Exponential kernel: .. math:: k(r) = \sigma^2 \exp \\bigg(- \\frac{1}{2} r \\bigg) \\ \\ \\ \\ \text{ where } r = \sqrt{\sum_{i=1}^{input dim} \frac{(x_i-y_i)^2}{\ell_i^2} } """ def sde_update_gradient_full(self, gradients): """ Update gradient in the order in which parameters are represented in the kernel """ self.variance.gradient = gradients[0] self.lengthscale.gradient = gradients[1] def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variance.values) lengthscale = float(self.lengthscale) F = np.array(((-1.0/lengthscale,),)) L = np.array(((1.0,),)) Qc =
np.array( ((2.0*variance/lengthscale,),) )
numpy.array
# coding=utf-8 # Copyright 2022 The Robustness Metrics Authors. # # 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. # Lint as: python3 """Figures for 'Revisiting Calibration of Modern Neural Networks'. This module contains figures showing ECE and accuracy, as well as reliability diagrams, on clean ImageNet. """ from typing import Dict, List, Optional, Tuple import matplotlib as mpl from matplotlib import pyplot as plt import numpy as np import pandas as pd from robustness_metrics.projects.revisiting_calibration import display from robustness_metrics.projects.revisiting_calibration import plotting from robustness_metrics.projects.revisiting_calibration import utils def plot(df_main: pd.DataFrame, df_reliability: pd.DataFrame, gce_prefix: str = plotting.STD_GCE_PREFIX, rescaling_method: str = "temperature_scaling", add_guo: bool = False) -> mpl.figure.Figure: """Plots acc/calib and reliability diagrams on clean ImageNet (Figure 1).""" family_order = display.get_model_families_sorted() if add_guo: family_order.append("guo") if rescaling_method == "both": rescaling_methods = ["none", "temperature_scaling"] else: rescaling_methods = [rescaling_method] # Set up figure: fig = plt.figure(figsize=(display.FULL_WIDTH, 1.6)) if rescaling_method == "both": widths = [1.75, 1.75, 1, 1, 1] else: widths = [1.8, 1, 1, 1, 1, 1] heights = [0.3, 1] spec = fig.add_gridspec( ncols=len(widths), nrows=len(heights), width_ratios=widths, height_ratios=heights) # First panels: acc vs calib ImageNet: for ax_i, rescaling_method in enumerate(rescaling_methods): df_plot, cmap = _get_data(df_main, gce_prefix, family_order, rescaling_methods=[rescaling_method]) ax = fig.add_subplot( spec[0:2, ax_i], box_aspect=1.0) big_ax = ax for i, family in enumerate(family_order): if family == "guo": continue data_sub = df_plot[df_plot.ModelFamily == family] if data_sub.empty: continue ax.scatter( data_sub["downstream_error"], data_sub["MetricValue"], s=plotting.model_to_scatter_size(data_sub.model_size), c=data_sub.family_index, cmap=cmap, vmin=0, vmax=len(family_order), marker=utils.assert_and_get_constant(data_sub.family_marker), alpha=0.7, linewidth=0.0, zorder=100 - i, # Z-order is same as model family order. label=family) # Manually add Guo et al data: # From Table 1 and Table S2 in https://arxiv.org/pdf/1706.04599.pdf. # First model is DenseNet161, second is ResNet152. if add_guo: size = plotting.model_to_scatter_size(1) color = [len(family_order) - 1] * 2 marker = "x" if rescaling_method == "none": ax.scatter([0.2257, 0.2231], [0.0628, 0.0548], s=size, c=color, marker=marker, alpha=0.7, label="guo") if rescaling_method == "temperature_scaling": ax.scatter([0.2257, 0.2231], [0.0199, 0.0186], s=size, c=color, marker=marker, alpha=0.7, label="guo") plotting.show_spines(ax) ax.set_anchor("N") ax.grid(False, which="minor") ax.grid(True, axis="both") ax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(0.1)) ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.01)) ax.set_ylim(bottom=0.01, top=0.09) ax.set_xlim(0.05, 0.55) ax.set_xlabel(display.XLABEL_INET_ERROR) if len(rescaling_methods) == 1: # Showing just one rescaling method. if rescaling_method == "none": ax.set_ylabel(display.YLABEL_ECE_UNSCALED) elif rescaling_method == "temperature_scaling": ax.set_ylabel(display.YLABEL_ECE_TEMP_SCALED) else: # Showing both rescaling methods. if rescaling_method == "none": ax.set_title("Unscaled") elif rescaling_method == "temperature_scaling": ax.set_title("Temperature-scaled") if ax.is_first_col(): ax.set_ylabel("ECE") # Remaining panels: Reliability diagrams: offset = len(rescaling_methods) model_names = [ "mixer/jft-300m/H/14", "vit-h/14", "bit-jft-r152-x4-480", ] if offset == 1: model_names += ["wsl_32x48d", "simclr-4x-fine-tuned-100"] dataset_name = "imagenet(split='validation[20%:]')" for i, model_name in enumerate(model_names): # Get predictions: mask = df_main.ModelName == model_name mask &= df_main.rescaling_method == "none" mask &= df_main.Metric == "accuracy" mask &= df_main.DatasetName == dataset_name raw_model_name = df_main[mask].RawModelName assert len(raw_model_name) <= 1, df_main[mask] if len(raw_model_name) == 0: # pylint: disable=g-explicit-length-test continue binned = _get_binned_reliability_data( df_reliability, utils.assert_and_get_constant(raw_model_name), dataset_name) rel_ax = fig.add_subplot(spec[1, i + offset]) _plot_confidence_and_reliability( conf_ax=fig.add_subplot(spec[0, i + offset]), rel_ax=rel_ax, binned=binned, model_name=model_name, first_col=offset) if rescaling_method == "none": rel_ax.set_xlabel("Confidence\n(unscaled)") elif rescaling_method == "temperature_scaled": rel_ax.set_xlabel("Confidence\n(temp. scaled)") # Model family legend: handles, labels = plotting.get_model_family_legend(big_ax, family_order) legend = big_ax.legend( handles=handles, labels=labels, loc="upper right", frameon=True, labelspacing=0.25, handletextpad=0.1, borderpad=0.3, fontsize=4) legend.get_frame().set_linewidth(mpl.rcParams["axes.linewidth"]) legend.get_frame().set_edgecolor("lightgray") plotting.apply_to_fig_text(fig, display.prettify) offset = 0.05 for ax in fig.axes[1:]: box = ax.get_position() box.x0 += offset box.x1 += offset ax.set_position(box) return fig def plot_reliability_diagrams( df_main: pd.DataFrame, df_reliability: pd.DataFrame, family: str, rescaling_method: str = "temperature_scaling", dataset_name: str = "imagenet(split='validation[20%:]')", gce_prefix=plotting.STD_GCE_PREFIX) -> mpl.figure.Figure: """Plots acc/calib and reliability diagrams on clean ImageNet (Figure 1).""" df_plot, _ = _get_data( df_main, gce_prefix, [family], rescaling_methods=[rescaling_method], dataset_name=dataset_name) df_models = df_plot.drop_duplicates(subset=["ModelName"]) df_models = df_models.sort_values(by="model_size") model_names = df_models.ModelName.to_list() # Set up figure: num_cols = max(5, len(model_names)) width = num_cols * 0.80 fig = plt.figure(figsize=(width, 1.4)) spec = fig.add_gridspec(ncols=num_cols, nrows=2, height_ratios=[0.4, 1]) for i in range(num_cols): if i >= len(model_names): # Add axes as placeholders for formatting but set to invisible: fig.add_subplot(spec[0, i]).set_visible(False) fig.add_subplot(spec[1, i]).set_visible(False) continue model_name = model_names[i] # Get predictions: mask = df_main.ModelName == model_name mask &= df_main.rescaling_method == rescaling_method mask &= df_main.Metric == "accuracy" mask &= df_main.DatasetName == dataset_name raw_model_name = df_main[mask].RawModelName assert len(raw_model_name) == 1 binned = _get_binned_reliability_data( df_reliability, utils.assert_and_get_constant(raw_model_name), dataset_name) rel_ax = fig.add_subplot(spec[1, i]) _plot_confidence_and_reliability( conf_ax=fig.add_subplot(spec[0, i]), rel_ax=rel_ax, binned=binned, model_name=model_name) if rescaling_method == "none": rel_ax.set_xlabel("Confidence\n(unscaled)") elif rescaling_method == "temperature_scaling": rel_ax.set_xlabel("Confidence\n(temp. scaled)") def prettify(s): s = display.prettify(s) s = s.replace("MLP-Mixer-", "MLP-Mixer\n") return s plotting.apply_to_fig_text(fig, prettify) plotting.apply_to_fig_text(fig, lambda x: x.replace("EfficientNet", "EffNet")) fig.subplots_adjust(hspace=-0.05) return fig def _plot_confidence_and_reliability(conf_ax: mpl.axes.Axes, rel_ax: mpl.axes.Axes, binned: Dict[str, np.ndarray], model_name: str, first_col: int = 0) -> None: """Plots a confidence hist and reliability diagram into the provided axes.""" plot_single_reliability_diagram(rel_ax, binned, zorder=100) # Plot and format confidence histogram (top row): ax = conf_ax bin_widths =
np.diff(binned["edges"])
numpy.diff
#!/usr/bin/env python # -*- coding: utf-8 -*- """ acq400.py interface to one acq400 appliance instance - enumerates all site services, available as uut.sX.knob - simple property interface allows natural "script-like" usage - eg:: uut1.s0.set_arm = 1 - equivalent to running this on a logged in shell session on the UUT:: set.site1 set_arm=1 - monitors transient status on uut, provides blocking events - read_channels() - reads all data from channel data service. Created on Sun Jan 8 12:36:38 2017 @author: pgm """ import threading import re import os import errno import signal import sys from . import netclient import numpy as np import socket import timeit import time class AcqPorts: """server port constants""" TSTAT = 2235 STREAM = 4210 SITE0 = 4220 SEGSW = 4250 SEGSR = 4251 DPGSTL = 4521 GPGSTL= 4541 GPGDUMP = 4543 WRPG = 4606 BOLO8_CAL = 45072 DATA0 = 53000 MULTI_EVENT_TMP = 53555 MULTI_EVENT_DISK = 53556 LIVETOP = 53998 ONESHOT = 53999 AWG_ONCE = 54201 AWG_AUTOREARM = 54202 MGTDRAM = 53990 MGTDRAM_PULL_DATA = 53991 class AcqSites: # site service at AcqPorts.SITE0+ AcqSites.SITEi SITE0 = 0 SITE1 = 1 SITE2 = 2 SITE3 = 3 SITE4 = 4 SITE5 = 5 SITE6 = 6 SITE_CA = 13 SITE_CB = 12 SITE_DSP = 14 class SF: """state constants""" STATE = 0 PRE = 1 POST = 2 ELAPSED = 3 DEMUX = 5 class STATE: """transient states""" IDLE = 0 ARM = 1 RUNPRE = 2 RUNPOST = 3 POPROCESS = 4 CLEANUP = 5 @staticmethod def str(st): if st==STATE.IDLE: return "IDLE" if st==STATE.ARM: return "ARM" if st==STATE.RUNPRE: return "RUNPRE" if st==STATE.RUNPOST: return "RUNPOST" if st==STATE.POPROCESS: return "POPROCESS" if st==STATE.CLEANUP: return "CLEANUP" return "UNDEF" class Signals: EXT_TRG_DX = 'd0' INT_TRG_DX = 'd1' MB_CLK_DX = 'd1' class StreamClient(netclient.Netclient): """handles live streaming data""" def __init__(self, addr): print("worktodo") class RawClient(netclient.Netclient): """ handles raw data from any service port """ def __init__(self, addr, port): netclient.Netclient.__init__(self, addr, port) def read(self, nelems, data_size=2, ncols=1, maxbuf=0x400000): """read ndata from channel data server, return as np array. Args: nelems number of data elements, each data_size*ncols nelems <=0 :: read until the end data_size : 2|4 short or int ncols : optional, to create a 2D array """ _dtype = np.dtype('i4' if data_size == 4 else 'i2') # hmm, what if unsigned? if nelems <= 0: nelems = 0x80000000 #2GB approximates infinity. what is infinity in python? bytestogo = nelems * data_size * ncols total_buf = "" while bytestogo > 0: new_buf = self.sock.recv(bytestogo) if not new_buf: break # end of file bytestogo = bytestogo - len(new_buf) total_buf += new_buf # still dubious of append :-) return np.frombuffer(total_buf, _dtype) def get_blocks(self, nelems, data_size=2, ncols=1): block = np.array([1]) while len(block) > 0: block = self.read(nelems, data_size=data_size, ncols=ncols) if len(block) > 0: yield block class MgtDramPullClient(RawClient): def __init__(self, addr): RawClient.__init__(self, addr, AcqPorts.MGTDRAM_PULL_DATA) class ChannelClient(netclient.Netclient): """handles post shot data for one channel. Args: addr (str) : ip address or dns name ch (int) : channel number 1..N """ def __init__(self, addr, ch): netclient.Netclient.__init__(self, addr, AcqPorts.DATA0+ch) # on Linux, recv returns on ~mtu # on Windows, it may buffer up, and it's very slow unless we use a larger buffer def read(self, ndata, data_size=2, maxbuf=0x400000): """read ndata from channel data server, return as np array. Args: ndata (int): number of elements data_size : 2|4 short or int maxbuf=4096 : max bytes to read per packet Returns: np: data array * TODO buffer += this is probably horribly inefficient probably better:: retbuf = np.array(dtype, ndata) retbuf[cursor]. """ _dtype = np.dtype('i4' if data_size == 4 else 'i2') total_buffer = buffer = self.sock.recv(maxbuf) if int(ndata) == 0 or int(ndata) == -1: while True: buffer = self.sock.recv(maxbuf) if not buffer: return
np.frombuffer(total_buffer, dtype=_dtype, count=-1)
numpy.frombuffer
import hashlib import math import numpy as np import pprint import pytest import random import re import subprocess import sys import tempfile import json from catboost import ( CatBoost, CatBoostClassifier, CatBoostRegressor, CatBoostError, EFstrType, FeaturesData, Pool, cv, sum_models, train,) from catboost.eval.catboost_evaluation import CatboostEvaluation, EvalType from catboost.utils import eval_metric, create_cd, get_roc_curve, select_threshold from catboost.utils import DataMetaInfo, TargetStats, compute_training_options import os.path from pandas import read_table, DataFrame, Series, Categorical from six import PY3 from six.moves import xrange from catboost_pytest_lib import ( DelayedTee, binary_path, data_file, local_canonical_file, permute_dataset_columns, remove_time_from_json, test_output_path, generate_random_labeled_set ) if sys.version_info.major == 2: import cPickle as pickle else: import _pickle as pickle pytest_plugins = "list_plugin", fails_on_gpu = pytest.mark.fails_on_gpu EPS = 1e-5 BOOSTING_TYPE = ['Ordered', 'Plain'] OVERFITTING_DETECTOR_TYPE = ['IncToDec', 'Iter'] NONSYMMETRIC = ['Lossguide', 'Depthwise'] TRAIN_FILE = data_file('adult', 'train_small') TEST_FILE = data_file('adult', 'test_small') CD_FILE = data_file('adult', 'train.cd') NAN_TRAIN_FILE = data_file('adult_nan', 'train_small') NAN_TEST_FILE = data_file('adult_nan', 'test_small') NAN_CD_FILE = data_file('adult_nan', 'train.cd') CLOUDNESS_TRAIN_FILE = data_file('cloudness_small', 'train_small') CLOUDNESS_TEST_FILE = data_file('cloudness_small', 'test_small') CLOUDNESS_CD_FILE = data_file('cloudness_small', 'train.cd') QUERYWISE_TRAIN_FILE = data_file('querywise', 'train') QUERYWISE_TEST_FILE = data_file('querywise', 'test') QUERYWISE_CD_FILE = data_file('querywise', 'train.cd') QUERYWISE_CD_FILE_WITH_GROUP_WEIGHT = data_file('querywise', 'train.cd.group_weight') QUERYWISE_CD_FILE_WITH_GROUP_ID = data_file('querywise', 'train.cd.query_id') QUERYWISE_CD_FILE_WITH_SUBGROUP_ID = data_file('querywise', 'train.cd.subgroup_id') QUERYWISE_TRAIN_PAIRS_FILE = data_file('querywise', 'train.pairs') QUERYWISE_TRAIN_PAIRS_FILE_WITH_PAIR_WEIGHT = data_file('querywise', 'train.pairs.weighted') QUERYWISE_TEST_PAIRS_FILE = data_file('querywise', 'test.pairs') AIRLINES_5K_TRAIN_FILE = data_file('airlines_5K', 'train') AIRLINES_5K_TEST_FILE = data_file('airlines_5K', 'test') AIRLINES_5K_CD_FILE = data_file('airlines_5K', 'cd') SMALL_CATEGORIAL_FILE = data_file('small_categorial', 'train') SMALL_CATEGORIAL_CD_FILE = data_file('small_categorial', 'train.cd') BLACK_FRIDAY_TRAIN_FILE = data_file('black_friday', 'train') BLACK_FRIDAY_TEST_FILE = data_file('black_friday', 'test') BLACK_FRIDAY_CD_FILE = data_file('black_friday', 'cd') OUTPUT_MODEL_PATH = 'model.bin' OUTPUT_COREML_MODEL_PATH = 'model.mlmodel' OUTPUT_CPP_MODEL_PATH = 'model.cpp' OUTPUT_PYTHON_MODEL_PATH = 'model.py' OUTPUT_JSON_MODEL_PATH = 'model.json' OUTPUT_ONNX_MODEL_PATH = 'model.onnx' PREDS_PATH = 'predictions.npy' PREDS_TXT_PATH = 'predictions.txt' FIMP_NPY_PATH = 'feature_importance.npy' FIMP_TXT_PATH = 'feature_importance.txt' OIMP_PATH = 'object_importances.txt' JSON_LOG_PATH = 'catboost_info/catboost_training.json' TARGET_IDX = 1 CAT_FEATURES = [0, 1, 2, 4, 6, 8, 9, 10, 11, 12, 16] model_diff_tool = binary_path("catboost/tools/model_comparator/model_comparator") np.set_printoptions(legacy='1.13') class LogStdout: def __init__(self, file): self.log_file = file def __enter__(self): self.saved_stdout = sys.stdout sys.stdout = self.log_file return self.saved_stdout def __exit__(self, exc_type, exc_value, exc_traceback): sys.stdout = self.saved_stdout self.log_file.close() def compare_canonical_models(model, diff_limit=0): return local_canonical_file(model, diff_tool=[model_diff_tool, '--diff-limit', str(diff_limit)]) def map_cat_features(data, cat_features): result = [] for i in range(data.shape[0]): result.append([]) for j in range(data.shape[1]): result[i].append(str(data[i, j]) if j in cat_features else data[i, j]) return result def _check_shape(pool, object_count, features_count): return np.shape(pool.get_features()) == (object_count, features_count) def _check_data(data1, data2): return np.all(np.isclose(data1, data2, rtol=0.001, equal_nan=True)) def _count_lines(afile): with open(afile, 'r') as f: num_lines = sum(1 for line in f) return num_lines def _generate_nontrivial_binary_target(num, seed=20181219, prng=None): ''' Generate binary vector with non zero variance :param num: :return: ''' if prng is None: prng = np.random.RandomState(seed=seed) def gen(): return prng.randint(0, 2, size=num) if num <= 1: return gen() y = gen() # 0/1 labels while y.min() == y.max(): y = gen() return y def _generate_random_target(num, seed=20181219, prng=None): if prng is None: prng = np.random.RandomState(seed=seed) return prng.random_sample((num,)) def set_random_weight(pool, seed=20181219, prng=None): if prng is None: prng = np.random.RandomState(seed=seed) pool.set_weight(prng.random_sample(pool.num_row())) if pool.num_pairs() > 0: pool.set_pairs_weight(prng.random_sample(pool.num_pairs())) def verify_finite(result): inf = float('inf') for r in result: assert(r == r) assert(abs(r) < inf) def append_param(metric_name, param): return metric_name + (':' if ':' not in metric_name else ';') + param # returns (features DataFrame, cat_feature_indices) def load_pool_features_as_df(pool_file, cd_file, target_idx): data = read_table(pool_file, header=None, dtype=str) data.drop([target_idx], axis=1, inplace=True) return (data, Pool(pool_file, column_description=cd_file).get_cat_feature_indices()) # Test cases begin here ######################################################## def test_load_file(): assert _check_shape(Pool(TRAIN_FILE, column_description=CD_FILE), 101, 17) def test_load_list(): pool = Pool(TRAIN_FILE, column_description=CD_FILE) cat_features = pool.get_cat_feature_indices() data = map_cat_features(pool.get_features(), cat_features) label = pool.get_label() assert _check_shape(Pool(data, label, cat_features), 101, 17) def test_load_ndarray(): pool = Pool(TRAIN_FILE, column_description=CD_FILE) cat_features = pool.get_cat_feature_indices() data = np.array(map_cat_features(pool.get_features(), cat_features)) label = np.array(pool.get_label()) assert _check_shape(Pool(data, label, cat_features), 101, 17) @pytest.mark.parametrize('dataset', ['adult', 'adult_nan', 'querywise']) def test_load_df_vs_load_from_file(dataset): train_file, cd_file, target_idx, other_non_feature_columns = { 'adult': (TRAIN_FILE, CD_FILE, TARGET_IDX, []), 'adult_nan': (NAN_TRAIN_FILE, NAN_CD_FILE, TARGET_IDX, []), 'querywise': (QUERYWISE_TRAIN_FILE, QUERYWISE_CD_FILE, 2, [0, 1, 3, 4]) }[dataset] pool1 = Pool(train_file, column_description=cd_file) data = read_table(train_file, header=None) labels = DataFrame(data.iloc[:, target_idx], dtype=np.float32) data.drop([target_idx] + other_non_feature_columns, axis=1, inplace=True) cat_features = pool1.get_cat_feature_indices() pool2 = Pool(data, labels, cat_features) assert _check_data(pool1.get_features(), pool2.get_features()) assert _check_data([float(label) for label in pool1.get_label()], pool2.get_label()) def test_load_series(): pool = Pool(TRAIN_FILE, column_description=CD_FILE) data = read_table(TRAIN_FILE, header=None) labels = Series(data.iloc[:, TARGET_IDX]) data.drop([TARGET_IDX], axis=1, inplace=True) data = Series(list(data.values)) cat_features = pool.get_cat_feature_indices() pool2 = Pool(data, labels, cat_features) assert _check_data(pool.get_features(), pool2.get_features()) assert [int(label) for label in pool.get_label()] == pool2.get_label() def test_pool_cat_features(): pool = Pool(TRAIN_FILE, column_description=CD_FILE) assert np.all(pool.get_cat_feature_indices() == CAT_FEATURES) def test_pool_cat_features_as_strings(): df = DataFrame(data=[[1, 2], [3, 4]], columns=['col1', 'col2']) pool = Pool(df, cat_features=['col2']) assert np.all(pool.get_cat_feature_indices() == [1]) data = [[1, 2, 3], [4, 5, 6]] pool = Pool(data, feature_names=['col1', 'col2', 'col3'], cat_features=['col2', 'col3']) assert np.all(pool.get_cat_feature_indices() == [1, 2]) data = [[1, 2, 3], [4, 5, 6]] with pytest.raises(CatBoostError): Pool(data, cat_features=['col2', 'col3']) def test_load_generated(): pool_size = (100, 10) prng = np.random.RandomState(seed=20181219) data = np.round(prng.normal(size=pool_size), decimals=3) label = _generate_nontrivial_binary_target(pool_size[0], prng=prng) pool = Pool(data, label) assert _check_data(pool.get_features(), data) assert _check_data(pool.get_label(), label) def test_load_dumps(): pool_size = (100, 10) prng = np.random.RandomState(seed=20181219) data = prng.randint(10, size=pool_size) labels = _generate_nontrivial_binary_target(pool_size[0], prng=prng) pool1 = Pool(data, labels) lines = [] for i in range(len(data)): line = [str(labels[i])] + [str(x) for x in data[i]] lines.append('\t'.join(line)) text = '\n'.join(lines) with open('test_data_dumps', 'w') as f: f.write(text) pool2 = Pool('test_data_dumps') assert _check_data(pool1.get_features(), pool2.get_features()) assert pool1.get_label() == [int(label) for label in pool2.get_label()] def test_dataframe_with_pandas_categorical_columns(): df = DataFrame() df['num_feat_0'] = [0, 1, 0, 2, 3, 1, 2] df['num_feat_1'] = [0.12, 0.8, 0.33, 0.11, 0.0, 1.0, 0.0] df['cat_feat_2'] = Series(['A', 'B', 'A', 'C', 'A', 'A', 'A'], dtype='category') df['cat_feat_3'] = Series(['x', 'x', 'y', 'y', 'y', 'x', 'x']) df['cat_feat_4'] = Categorical( ['large', 'small', 'medium', 'large', 'small', 'small', 'medium'], categories=['small', 'medium', 'large'], ordered=True ) df['cat_feat_5'] = [0, 1, 0, 2, 3, 1, 2] labels = [0, 1, 1, 0, 1, 0, 1] model = CatBoostClassifier(iterations=2) model.fit(X=df, y=labels, cat_features=[2, 3, 4, 5]) pred = model.predict(df) preds_path = test_output_path(PREDS_TXT_PATH) np.savetxt(preds_path, np.array(pred), fmt='%.8f') return local_canonical_file(preds_path) # feature_matrix is (doc_count x feature_count) def get_features_data_from_matrix(feature_matrix, cat_feature_indices, order='C'): object_count = len(feature_matrix) feature_count = len(feature_matrix[0]) cat_feature_count = len(cat_feature_indices) num_feature_count = feature_count - cat_feature_count result_num = np.empty((object_count, num_feature_count), dtype=np.float32, order=order) result_cat = np.empty((object_count, cat_feature_count), dtype=object, order=order) for object_idx in xrange(object_count): num_feature_idx = 0 cat_feature_idx = 0 for feature_idx in xrange(len(feature_matrix[object_idx])): if (cat_feature_idx < cat_feature_count) and (cat_feature_indices[cat_feature_idx] == feature_idx): # simplified handling of transformation to bytes for tests result_cat[object_idx, cat_feature_idx] = ( feature_matrix[object_idx, feature_idx] if isinstance(feature_matrix[object_idx, feature_idx], bytes) else str(feature_matrix[object_idx, feature_idx]).encode('utf-8') ) cat_feature_idx += 1 else: result_num[object_idx, num_feature_idx] = float(feature_matrix[object_idx, feature_idx]) num_feature_idx += 1 return FeaturesData(num_feature_data=result_num, cat_feature_data=result_cat) def get_features_data_from_file(data_file, drop_columns, cat_feature_indices, order='C'): data_matrix_from_file = read_table(data_file, header=None, dtype=str) data_matrix_from_file.drop(drop_columns, axis=1, inplace=True) return get_features_data_from_matrix(np.array(data_matrix_from_file), cat_feature_indices, order) def compare_flat_index_and_features_data_pools(flat_index_pool, features_data_pool): assert flat_index_pool.shape == features_data_pool.shape cat_feature_indices = flat_index_pool.get_cat_feature_indices() num_feature_count = flat_index_pool.shape[1] - len(cat_feature_indices) flat_index_pool_features = flat_index_pool.get_features() features_data_pool_features = features_data_pool.get_features() for object_idx in xrange(flat_index_pool.shape[0]): num_feature_idx = 0 cat_feature_idx = 0 for flat_feature_idx in xrange(flat_index_pool.shape[1]): if ( (cat_feature_idx < len(cat_feature_indices)) and (cat_feature_indices[cat_feature_idx] == flat_feature_idx) ): # simplified handling of transformation to bytes for tests assert (flat_index_pool_features[object_idx][flat_feature_idx] == features_data_pool_features[object_idx][num_feature_count + cat_feature_idx]) cat_feature_idx += 1 else: assert np.isclose( flat_index_pool_features[object_idx][flat_feature_idx], features_data_pool_features[object_idx][num_feature_idx], rtol=0.001, equal_nan=True ) num_feature_idx += 1 @pytest.mark.parametrize('order', ['C', 'F'], ids=['order=C', 'order=F']) def test_from_features_data_vs_load_from_files(order): pool_from_files = Pool(TRAIN_FILE, column_description=CD_FILE) features_data = get_features_data_from_file( data_file=TRAIN_FILE, drop_columns=[TARGET_IDX], cat_feature_indices=pool_from_files.get_cat_feature_indices(), order=order ) pool_from_features_data = Pool(data=features_data) compare_flat_index_and_features_data_pools(pool_from_files, pool_from_features_data) def test_features_data_with_empty_objects(): fd = FeaturesData( cat_feature_data=np.empty((0, 4), dtype=object) ) assert fd.get_object_count() == 0 assert fd.get_feature_count() == 4 assert fd.get_num_feature_count() == 0 assert fd.get_cat_feature_count() == 4 assert fd.get_feature_names() == [''] * 4 fd = FeaturesData( num_feature_data=np.empty((0, 2), dtype=np.float32), num_feature_names=['f0', 'f1'] ) assert fd.get_object_count() == 0 assert fd.get_feature_count() == 2 assert fd.get_num_feature_count() == 2 assert fd.get_cat_feature_count() == 0 assert fd.get_feature_names() == ['f0', 'f1'] fd = FeaturesData( cat_feature_data=np.empty((0, 2), dtype=object), num_feature_data=np.empty((0, 3), dtype=np.float32) ) assert fd.get_object_count() == 0 assert fd.get_feature_count() == 5 assert fd.get_num_feature_count() == 3 assert fd.get_cat_feature_count() == 2 assert fd.get_feature_names() == [''] * 5 def test_features_data_names(): # empty specification of names fd = FeaturesData( cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object), num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32), ) assert fd.get_feature_names() == [''] * 5 # full specification of names fd = FeaturesData( cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object), cat_feature_names=['shop', 'search'], num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32), num_feature_names=['weight', 'price', 'volume'] ) assert fd.get_feature_names() == ['weight', 'price', 'volume', 'shop', 'search'] # partial specification of names fd = FeaturesData( cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object), num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32), num_feature_names=['weight', 'price', 'volume'] ) assert fd.get_feature_names() == ['weight', 'price', 'volume', '', ''] # partial specification of names fd = FeaturesData( cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object), cat_feature_names=['shop', 'search'], num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32), ) assert fd.get_feature_names() == ['', '', '', 'shop', 'search'] def compare_pools_from_features_data_and_generic_matrix( features_data, generic_matrix, cat_features_indices, feature_names=None ): pool1 = Pool(data=features_data) pool2 = Pool(data=generic_matrix, cat_features=cat_features_indices, feature_names=feature_names) assert _check_data(pool1.get_features(), pool2.get_features()) assert pool1.get_cat_feature_indices() == pool2.get_cat_feature_indices() assert pool1.get_feature_names() == pool2.get_feature_names() @pytest.mark.parametrize('order', ['C', 'F'], ids=['order=C', 'order=F']) def test_features_data_good(order): # 0 objects compare_pools_from_features_data_and_generic_matrix( FeaturesData(cat_feature_data=np.empty((0, 4), dtype=object, order=order)), np.empty((0, 4), dtype=object), cat_features_indices=[0, 1, 2, 3] ) # 0 objects compare_pools_from_features_data_and_generic_matrix( FeaturesData( cat_feature_data=np.empty((0, 2), dtype=object, order=order), cat_feature_names=['cat0', 'cat1'], num_feature_data=np.empty((0, 3), dtype=np.float32, order=order), ), np.empty((0, 5), dtype=object), cat_features_indices=[3, 4], feature_names=['', '', '', 'cat0', 'cat1'] ) compare_pools_from_features_data_and_generic_matrix( FeaturesData( cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object, order=order) ), [[b'amazon', b'bing'], [b'ebay', b'google']], cat_features_indices=[0, 1] ) compare_pools_from_features_data_and_generic_matrix( FeaturesData( num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32, order=order) ), [[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], cat_features_indices=[] ) compare_pools_from_features_data_and_generic_matrix( FeaturesData( cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object, order=order), num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32, order=order) ), [[1.0, 2.0, 3.0, b'amazon', b'bing'], [22.0, 7.1, 10.2, b'ebay', b'google']], cat_features_indices=[3, 4] ) compare_pools_from_features_data_and_generic_matrix( FeaturesData( cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object, order=order), cat_feature_names=['shop', 'search'] ), [[b'amazon', b'bing'], [b'ebay', b'google']], cat_features_indices=[0, 1], feature_names=['shop', 'search'] ) compare_pools_from_features_data_and_generic_matrix( FeaturesData( num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32, order=order), num_feature_names=['weight', 'price', 'volume'] ), [[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], cat_features_indices=[], feature_names=['weight', 'price', 'volume'] ) compare_pools_from_features_data_and_generic_matrix( FeaturesData( cat_feature_data=np.array([[b'amazon', b'bing'], [b'ebay', b'google']], dtype=object, order=order), cat_feature_names=['shop', 'search'], num_feature_data=np.array([[1.0, 2.0, 3.0], [22.0, 7.1, 10.2]], dtype=np.float32, order=order), num_feature_names=['weight', 'price', 'volume'] ), [[1.0, 2.0, 3.0, b'amazon', b'bing'], [22.0, 7.1, 10.2, b'ebay', b'google']], cat_features_indices=[3, 4], feature_names=['weight', 'price', 'volume', 'shop', 'search'] ) def test_features_data_bad(): # empty with pytest.raises(CatBoostError): FeaturesData() # names w/o data with pytest.raises(CatBoostError): FeaturesData(cat_feature_data=[[b'amazon', b'bing']], num_feature_names=['price']) # bad matrix type with pytest.raises(CatBoostError): FeaturesData( cat_feature_data=[[b'amazon', b'bing']], num_feature_data=np.array([1.0, 2.0, 3.0], dtype=np.float32) ) # bad matrix shape with pytest.raises(CatBoostError): FeaturesData(num_feature_data=np.array([[[1.0], [2.0], [3.0]]], dtype=np.float32)) # bad element type with pytest.raises(CatBoostError): FeaturesData( cat_feature_data=np.array([b'amazon', b'bing'], dtype=object), num_feature_data=np.array([1.0, 2.0, 3.0], dtype=np.float64) ) # bad element type with pytest.raises(CatBoostError): FeaturesData(cat_feature_data=
np.array(['amazon', 'bing'])
numpy.array
# -*- coding: utf-8 -*- """ Created on Tue Aug 3 19:30:34 2021 @author: <NAME> """ # Unidad de recursos de generación # Codigo principal --- Optimización de estabilidad de perfiles de voltaje # Importa librerias necesarias import pandas as pd; import numpy as np; import random; from datetime import date import time # Leectura de la base de datos print("") today = date.today().strftime("%d/%m/%Y") print(date.today() ,' Inicia lectura del sistema a analizar') print(' ',date.today() ,' ',time.strftime("%X")) Data_collection = pd.read_excel("14 bus data.xlsx", sheet_name=None, header=0) print(date.today() ,' Finaliza lectura del sistema a analizar') # Define las 4 matrices de datos LINE = 1*Data_collection['Line']; BUS = 1*Data_collection['Bus']; GEN = 1*Data_collection['Gen']; SHUNT = 1*Data_collection['Shunts']; # # ++++++++++++++++ Evalua la red original y determina el plan de expansión ++++++++++++++++ print("") # Inicia la población del algoritmo de optimización poblacion = 10 if poblacion*(len(GEN)+len(SHUNT)) <= 60: pop = 60 else: pop = 120 # Define la población inicial de los voltajes de los nodos PV print(' Población inicial de los voltajes de los nodos PV') Vmin = 0.93; Vmax = 1.07 x_vgen = np.zeros((pop,len(GEN))) for k in range(0,pop): for j in range(0,len(GEN)): x_vgen[k,j] = Vmin + (Vmax - Vmin)*np.random.rand(1) print(' Propuesta de los niveles de generación') x_gen = np.zeros((pop,len(GEN))) for k in range(0,pop): for j in range(0,len(GEN)): x_gen[k,j] = GEN.iloc[j,3] + (GEN.iloc[j,2] - GEN.iloc[j,3])*np.random.rand(1) print(' Corrigiendo generación') for k in range(0,pop): # si la generación es mayor que la carga if sum(x_gen[k,:]) > 1.01*sum(BUS.iloc[:,5]): alfa = sum(BUS.iloc[:,5])/sum(x_gen[k,:]) x_gen[k,:] = alfa*x_gen[k,:] # si la carga es mayor que la generación elif sum(BUS.iloc[:,5]) > sum(x_gen[k,:]): beta = sum(x_gen[k,:])/sum(BUS.iloc[:,5]) x_gen[k,:] = x_gen[k,:]/beta # Define la población inicial de los Taps de los transformadores # Busca transformadores en el sistema TAP = []; a = LINE.columns.tolist().index('Tipo de línea') for k in range(0,len(LINE)): if LINE.iloc[k,a] > 0: TAP.append(LINE.iloc[k,::]) TAP = pd.DataFrame(TAP) if len(TAP) > 0: print(' Población inicial de las posiciones de los taps') Tmin = 0.9; Tmax = 1.1 x_tap = np.zeros((pop,len(TAP))) for k in range(0,pop): for j in range(0,len(TAP)): x_tap[k,j] = (random.randint(int(Tmin*100),int(Tmax*100))/100) else: print(' No se encontraron transformadores en la red') # # Define la población inicial de los shunts if len(SHUNT) > 0: print(' Población inicial de las suceptancias shunt') Smax = np.zeros(len(SHUNT)) Smin = np.zeros(len(SHUNT)) x_shunt = np.zeros((pop,len(SHUNT))) maxind = SHUNT.columns.tolist().index('Bsvc max pu') minind = SHUNT.columns.tolist().index('Bsvc min pu') for k in range(0,len(SHUNT)): Smax[k] = SHUNT.iloc[k,maxind] Smin[k] = SHUNT.iloc[k,minind] for k in range(0,pop): for j in range(0,len(SHUNT)): x_shunt[k,j] = Smin[j] + (Smax[j] - Smin[j])*np.random.rand(1) else: print(' No se encontraron elementos shunt en la red') # Total de iteraciones n_itera = 10 # Función para determinar elnumero de subconjuntos def Mvalue(m,Obf1,Obf0): if min(Obf0) <= min(Obf1): m = m+1 elif min(Obf0) > min(Obf1) and m >=3: m = m - 1 # Corrige valor de m en caso de ser muy grande if m > 6: m = 6 return m # Numero inicial de subconjuntos M = 2 # Matrices de almacenamiento de información bsof=[] xigen = np.zeros((n_itera,len(GEN))); xivgen = np.zeros((n_itera,len(GEN))) Obfun=np.zeros((n_itera,pop)); Obfunnew=np.zeros((n_itera,pop)) XPG=np.zeros((n_itera,pop,len(GEN))) # guarda datos de cadidatos de generación XVG=np.zeros((n_itera,pop,len(GEN))) # guarda datos de voltajes candidatos if len (TAP) > 0: XTAP = np.zeros((n_itera,pop,len(TAP))) # guarda datos de TAPS candidatos xitap = np.zeros((n_itera,len(TAP))) if len (SHUNT) > 0: XSHUNT = np.zeros((n_itera,pop,len(SHUNT))) # guarda datos de suceptancias candidatos xishunt = np.zeros((n_itera,len(SHUNT))) # Llama a las funciones del proceso iterativo from Power_Flow import PowerFlowAC # Función para calculo de flujos AC from M_YBUS import YBUS_mod # Función para construir Ybus modificada from Invparcial import shipley # Función para construir inversa parcial from Fobjetivo import Lindex # Función para construir inversa parcial from ActualizaX import UpdateDesitionVariablesAA # Función para actualizar 2 variables de desición from ActualizaX import UpdateDesitionVariablesBB # Función para actualizar 3 variables de desición from ActualizaX import UpdateDesitionVariablesCC # Función para actualizar 4 variables de desición print("") print(date.today() ,' Inicia proceso iterativo') print(' ',date.today() ,' ',time.strftime("%X")) # +++++++++++++++++++++++++++ Inicia proceso iterativo +++++++++++++++++++++++ for k in range(0,n_itera): # Crea los conjuntos de pobalciones m=[] for n in range(0,M): if n==0: m.append(round(pop/M)) #elif n == int(M-1): m.append(int(pop)) else: m.append(round((n+1)*pop/M)) for p in range(0,pop): # Matrices auxiliares de datos line = 1*LINE; bus = 1*BUS shunt = 1*SHUNT; Gen = 1*GEN # asigna columna de generacion a cero bus.iloc[:,3] = 1*np.zeros(len(BUS)) # asigna columna de dispositivos de compensación a cero bus.iloc[:,8] = 1*np.zeros(len(BUS)) # Modifica la matriz line de acuerdo a la poblacion de los TAPS if len(TAP) > 0: for i in range(0,len(TAP)): for j in range(0,len(line)): if TAP.iloc[i,0] == line.iloc[j,0] and TAP.iloc[i,1] == line.iloc[j,1]: # Modifica el valor del tap line.iloc[j,a] = x_tap[p,i] # Modifica la matriz bus de acuerdo a los dispositivos shunt if len(SHUNT) > 0: for i in range(0,len(SHUNT)): for j in range(0,len(bus)): if bus.iloc[j,0] == shunt.iloc[i,1]: # Modifica el valor de la suceptancia # solo en esta ocasión se utiliza la solución inicial del voltage bus.iloc[j,8] = x_shunt[p,i] # Modifica la matriz bus de acuerdo a la población de voltajes de generación for i in range(0,len(GEN)): for j in range(0,len(bus)): if bus.iloc[j,0] == GEN.iloc[i,1]: # Modifica el valor del voltaje bus.iloc[j,1] = x_vgen[p,i] # Modifica la matriz bus de acuerdo a la población de generación for i in range(0,len(GEN)): for j in range(0,len(bus)): if bus.iloc[j,0] == GEN.iloc[i,1]: # Modifica el valor del generación bus.iloc[j,3] += x_gen[p,i] busa=1*np.asarray(bus); linea=1*
np.asarray(line)
numpy.asarray
import numpy as np from numpy.ctypeslib import as_array from numpy.testing import assert_array_equal from meshkernel import ( Contacts, GeometryList, Mesh1d, Mesh2d, MeshRefinementParameters, OrthogonalizationParameters, ) from meshkernel.c_structures import ( CContacts, CGeometryList, CMesh1d, CMesh2d, CMeshRefinementParameters, COrthogonalizationParameters, ) def test_cmesh2d_from_mesh2d(): """Tests `from_mesh2d` of the `CMesh2D` class with a simple mesh.""" # 2---3 # | | # 0---1 node_x = np.array([0.0, 1.0, 1.0, 0.0], dtype=np.double) node_y = np.array([0.0, 0.0, 1.0, 1.0], dtype=np.double) edge_nodes = np.array([0, 1, 1, 3, 3, 2, 2, 0], dtype=np.int32) face_nodes = np.array([0, 1, 2, 3], dtype=np.int32) nodes_per_face = np.array([4], dtype=np.int32) edge_x = np.array([0.5, 1.0, 0.5, 0.0], dtype=np.double) edge_y = np.array([0.0, 0.5, 1.0, 0.5], dtype=np.double) face_x = np.array([0.5], dtype=np.double) face_y = np.array([0.5], dtype=np.double) mesh2d = Mesh2d(node_x, node_y, edge_nodes) mesh2d.face_nodes = face_nodes mesh2d.nodes_per_face = nodes_per_face mesh2d.edge_x = edge_x mesh2d.edge_y = edge_y mesh2d.face_x = face_x mesh2d.face_y = face_y c_mesh2d = CMesh2d.from_mesh2d(mesh2d) # Get the numpy arrays from the ctypes object c_mesh2d_node_x = as_array(c_mesh2d.node_x, (4,)) c_mesh2d_node_y = as_array(c_mesh2d.node_y, (4,)) c_mesh2d_edge_nodes =
as_array(c_mesh2d.edge_nodes, (8,))
numpy.ctypeslib.as_array
import collections import numpy as np import time import datetime import os import networkx as nx import pytz import cloudvolume import pandas as pd from multiwrapper import multiprocessing_utils as mu from . import mincut from google.api_core.retry import Retry, if_exception_type from google.api_core.exceptions import Aborted, DeadlineExceeded, \ ServiceUnavailable from google.auth import credentials from google.cloud import bigtable from google.cloud.bigtable.row_filters import TimestampRange, \ TimestampRangeFilter, ColumnRangeFilter, ValueRangeFilter, RowFilterChain, \ ColumnQualifierRegexFilter, RowFilterUnion, ConditionalRowFilter, \ PassAllFilter, BlockAllFilter, RowFilter from google.cloud.bigtable.column_family import MaxVersionsGCRule from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union # global variables HOME = os.path.expanduser("~") N_DIGITS_UINT64 = len(str(np.iinfo(np.uint64).max)) LOCK_EXPIRED_TIME_DELTA = datetime.timedelta(minutes=2, seconds=00) UTC = pytz.UTC # Setting environment wide credential path os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = \ HOME + "/.cloudvolume/secrets/google-secret.json" def compute_indices_pandas(data) -> pd.Series: """ Computes indices of all unique entries Make sure to remap your array to a dense range starting at zero https://stackoverflow.com/questions/33281957/faster-alternative-to-numpy-where :param data: np.ndarray :return: pandas dataframe """ d = data.ravel() f = lambda x: np.unravel_index(x.index, data.shape) return pd.Series(d).groupby(d).apply(f) def log_n(arr, n): """ Computes log to base n :param arr: array or float :param n: int base :return: return log_n(arr) """ if n == 2: return np.log2(arr) elif n == 10: return np.log10(arr) else: return np.log(arr) / np.log(n) def pad_node_id(node_id: np.uint64) -> str: """ Pad node id to 20 digits :param node_id: int :return: str """ return "%.20d" % node_id def serialize_uint64(node_id: np.uint64) -> bytes: """ Serializes an id to be ingested by a bigtable table row :param node_id: int :return: str """ return serialize_key(pad_node_id(node_id)) # type: ignore def deserialize_uint64(node_id: bytes) -> np.uint64: """ De-serializes a node id from a BigTable row :param node_id: bytes :return: np.uint64 """ return np.uint64(node_id.decode()) # type: ignore def serialize_key(key: str) -> bytes: """ Serializes a key to be ingested by a bigtable table row :param key: str :return: bytes """ return key.encode("utf-8") def deserialize_key(key: bytes) -> str: """ Deserializes a row key :param key: bytes :return: str """ return key.decode() def row_to_byte_dict(row: bigtable.row.Row, f_id: str = None, idx: int = None ) -> Dict[int, Dict]: """ Reads row entries to a dictionary :param row: row :param f_id: str :param idx: int :return: dict """ row_dict = {} for fam_id in row.cells.keys(): row_dict[fam_id] = {} for row_k in row.cells[fam_id].keys(): if idx is None: row_dict[fam_id][deserialize_key(row_k)] = \ [c.value for c in row.cells[fam_id][row_k]] else: row_dict[fam_id][deserialize_key(row_k)] = \ row.cells[fam_id][row_k][idx].value if f_id is not None and f_id in row_dict: return row_dict[f_id] elif f_id is None: return row_dict else: raise Exception("Family id not found") def compute_bitmasks(n_layers: int, fan_out: int) -> Dict[int, int]: """ :param n_layers: int :return: dict layer -> bits for layer id """ bitmask_dict = {} for i_layer in range(n_layers, 0, -1): if i_layer == 1: # Lock this layer to an 8 bit layout to maintain compatibility with # the exported segmentation # n_bits_for_layers = np.ceil(log_n(fan_out**(n_layers - 2), fan_out)) n_bits_for_layers = 8 else: n_bits_for_layers = max(1, np.ceil(log_n(fan_out**(n_layers - i_layer), fan_out))) # n_bits_for_layers = fan_out ** int(np.ceil(log_n(n_bits_for_layers, fan_out))) n_bits_for_layers = int(n_bits_for_layers) assert n_bits_for_layers <= 8 bitmask_dict[i_layer] = n_bits_for_layers return bitmask_dict class ChunkedGraph(object): def __init__(self, table_id: str, instance_id: str = "pychunkedgraph", project_id: str = "neuromancer-seung-import", chunk_size: Tuple[int, int, int] = None, fan_out: Optional[int] = None, n_layers: Optional[int] = None, credentials: Optional[credentials.Credentials] = None, client: bigtable.Client = None, cv_path: str = None, is_new: bool = False) -> None: if client is not None: self._client = client else: self._client = bigtable.Client(project=project_id, admin=True, credentials=credentials) self._instance = self.client.instance(instance_id) self._table_id = table_id self._table = self.instance.table(self.table_id) if is_new: self.check_and_create_table() self._n_layers = self.check_and_write_table_parameters("n_layers", n_layers) self._fan_out = self.check_and_write_table_parameters("fan_out", fan_out) self._cv_path = self.check_and_write_table_parameters("cv_path", cv_path) self._chunk_size = self.check_and_write_table_parameters("chunk_size", chunk_size) self._bitmasks = compute_bitmasks(self.n_layers, self.fan_out) self._cv = None # Hardcoded parameters self._n_bits_for_layer_id = 8 self._cv_mip = 3 @property def client(self) -> bigtable.Client: return self._client @property def instance(self) -> bigtable.instance.Instance: return self._instance @property def table(self) -> bigtable.table.Table: return self._table @property def table_id(self) -> str: return self._table_id @property def instance_id(self): return self.instance.instance_id @property def project_id(self): return self.client.project @property def family_id(self) -> str: return "0" @property def incrementer_family_id(self) -> str: return "1" @property def log_family_id(self) -> str: return "2" @property def cross_edge_family_id(self) -> str: return "3" @property def fan_out(self) -> int: return self._fan_out @property def chunk_size(self) -> np.ndarray: return self._chunk_size @property def n_layers(self) -> int: return self._n_layers @property def bitmasks(self) -> Dict[int, int]: return self._bitmasks @property def cv_path(self) -> str: return self._cv_path @property def cv_mip(self) -> int: return self._cv_mip @property def cv(self) -> cloudvolume.CloudVolume: if self._cv is None: self._cv = cloudvolume.CloudVolume(self.cv_path, mip=self._cv_mip) return self._cv @property def root_chunk_id(self): return self.get_chunk_id(layer=int(self.n_layers), x=0, y=0, z=0) def check_and_create_table(self) -> None: """ Checks if table exists and creates new one if necessary """ table_ids = [t.table_id for t in self.instance.list_tables()] if not self.table_id in table_ids: self.table.create() f = self.table.column_family(self.family_id) f.create() f_inc = self.table.column_family(self.incrementer_family_id, gc_rule=MaxVersionsGCRule(1)) f_inc.create() f_log = self.table.column_family(self.log_family_id) f_log.create() f_ce = self.table.column_family(self.cross_edge_family_id, gc_rule=MaxVersionsGCRule(1)) f_ce.create() print("Table created") def check_and_write_table_parameters(self, param_key: str, value: Optional[np.uint64] = None ) -> np.uint64: """ Checks if a parameter already exists in the table. If it already exists it returns the stored value, else it stores the given value. It raises an exception if no value is passed and the parameter does not exist, yet. :param param_key: str :param value: np.uint64 :return: np.uint64 value """ ser_param_key = serialize_key(param_key) row = self.table.read_row(serialize_key("params")) if row is None or ser_param_key not in row.cells[self.family_id]: assert value is not None if param_key in ["fan_out", "n_layers"]: val_dict = {param_key: np.array(value, dtype=np.uint64).tobytes()} elif param_key in ["cv_path"]: val_dict = {param_key: serialize_key(value)} elif param_key in ["chunk_size"]: val_dict = {param_key: np.array(value, dtype=np.uint64).tobytes()} else: raise Exception("Unknown type for parameter") row = self.mutate_row(serialize_key("params"), self.family_id, val_dict) self.bulk_write([row]) else: value = row.cells[self.family_id][ser_param_key][0].value if param_key in ["fan_out", "n_layers"]: value = np.frombuffer(value, dtype=np.uint64)[0] elif param_key in ["cv_path"]: value = deserialize_key(value) elif param_key in ["chunk_size"]: value = np.frombuffer(value, dtype=np.uint64) else: raise Exception("Unknown key") return value def get_serialized_info(self): """ Rerturns dictionary that can be used to load this ChunkedGraph :return: dict """ info = {"table_id": self.table_id, "instance_id": self.instance_id, "project_id": self.project_id} try: info["credentials"] = self.client.credentials except: info["credentials"] = self.client._credentials return info def get_chunk_layer(self, node_or_chunk_id: np.uint64) -> int: """ Extract Layer from Node ID or Chunk ID :param node_or_chunk_id: np.uint64 :return: int """ return int(node_or_chunk_id) >> 64 - self._n_bits_for_layer_id def get_chunk_coordinates(self, node_or_chunk_id: np.uint64 ) -> np.ndarray: """ Extract X, Y and Z coordinate from Node ID or Chunk ID :param node_or_chunk_id: np.uint64 :return: Tuple(int, int, int) """ layer = self.get_chunk_layer(node_or_chunk_id) bits_per_dim = self.bitmasks[layer] x_offset = 64 - self._n_bits_for_layer_id - bits_per_dim y_offset = x_offset - bits_per_dim z_offset = y_offset - bits_per_dim x = int(node_or_chunk_id) >> x_offset & 2 ** bits_per_dim - 1 y = int(node_or_chunk_id) >> y_offset & 2 ** bits_per_dim - 1 z = int(node_or_chunk_id) >> z_offset & 2 ** bits_per_dim - 1 return np.array([x, y, z]) def get_chunk_id(self, node_id: Optional[np.uint64] = None, layer: Optional[int] = None, x: Optional[int] = None, y: Optional[int] = None, z: Optional[int] = None) -> np.uint64: """ (1) Extract Chunk ID from Node ID (2) Build Chunk ID from Layer, X, Y and Z components :param node_id: np.uint64 :param layer: int :param x: int :param y: int :param z: int :return: np.uint64 """ assert node_id is not None or \ all(v is not None for v in [layer, x, y, z]) if node_id is not None: layer = self.get_chunk_layer(node_id) bits_per_dim = self.bitmasks[layer] if node_id is not None: chunk_offset = 64 - self._n_bits_for_layer_id - 3 * bits_per_dim return np.uint64((int(node_id) >> chunk_offset) << chunk_offset) else: if not(x < 2 ** bits_per_dim and y < 2 ** bits_per_dim and z < 2 ** bits_per_dim): raise Exception("Chunk coordinate is out of range for" "this graph on layer %d with %d bits/dim." "[%d, %d, %d]; max = %d." % (layer, bits_per_dim, x, y, z, 2 ** bits_per_dim)) layer_offset = 64 - self._n_bits_for_layer_id x_offset = layer_offset - bits_per_dim y_offset = x_offset - bits_per_dim z_offset = y_offset - bits_per_dim return np.uint64(layer << layer_offset | x << x_offset | y << y_offset | z << z_offset) def get_chunk_ids_from_node_ids(self, node_ids: Iterable[np.uint64] ) -> np.ndarray: """ Extract a list of Chunk IDs from a list of Node IDs :param node_ids: np.ndarray(dtype=np.uint64) :return: np.ndarray(dtype=np.uint64) """ # TODO: measure and improve performance(?) return np.array(list(map(lambda x: self.get_chunk_id(node_id=x), node_ids)), dtype=np.uint64) def get_segment_id_limit(self, node_or_chunk_id: np.uint64) -> np.uint64: """ Get maximum possible Segment ID for given Node ID or Chunk ID :param node_or_chunk_id: np.uint64 :return: np.uint64 """ layer = self.get_chunk_layer(node_or_chunk_id) bits_per_dim = self.bitmasks[layer] chunk_offset = 64 - self._n_bits_for_layer_id - 3 * bits_per_dim return np.uint64(2 ** chunk_offset - 1) def get_segment_id(self, node_id: np.uint64) -> np.uint64: """ Extract Segment ID from Node ID :param node_id: np.uint64 :return: np.uint64 """ return node_id & self.get_segment_id_limit(node_id) def get_node_id(self, segment_id: np.uint64, chunk_id: Optional[np.uint64] = None, layer: Optional[int] = None, x: Optional[int] = None, y: Optional[int] = None, z: Optional[int] = None) -> np.uint64: """ (1) Build Node ID from Segment ID and Chunk ID (2) Build Node ID from Segment ID, Layer, X, Y and Z components :param segment_id: np.uint64 :param chunk_id: np.uint64 :param layer: int :param x: int :param y: int :param z: int :return: np.uint64 """ if chunk_id is not None: return chunk_id | segment_id else: return self.get_chunk_id(layer=layer, x=x, y=y, z=z) | segment_id def get_unique_segment_id_range(self, chunk_id: np.uint64, step: int = 1 ) -> np.ndarray: """ Return unique Segment ID for given Chunk ID atomic counter :param chunk_id: np.uint64 :param step: int :return: np.uint64 """ counter_key = serialize_key('counter') # Incrementer row keys start with an "i" followed by the chunk id row_key = serialize_key("i%s" % pad_node_id(chunk_id)) append_row = self.table.row(row_key, append=True) append_row.increment_cell_value(self.incrementer_family_id, counter_key, step) # This increments the row entry and returns the value AFTER incrementing latest_row = append_row.commit() max_segment_id_b = latest_row[self.incrementer_family_id][counter_key][0][0] max_segment_id = int.from_bytes(max_segment_id_b, byteorder="big") min_segment_id = max_segment_id + 1 - step segment_id_range = np.array(range(min_segment_id, max_segment_id + 1), dtype=np.uint64) return segment_id_range def get_unique_segment_id(self, chunk_id: np.uint64) -> np.uint64: """ Return unique Segment ID for given Chunk ID atomic counter :param chunk_id: np.uint64 :param step: int :return: np.uint64 """ return self.get_unique_segment_id_range(chunk_id=chunk_id, step=1)[0] def get_unique_node_id_range(self, chunk_id: np.uint64, step: int = 1 ) -> np.ndarray: """ Return unique Node ID range for given Chunk ID atomic counter :param chunk_id: np.uint64 :param step: int :return: np.uint64 """ segment_ids = self.get_unique_segment_id_range(chunk_id=chunk_id, step=step) node_ids = np.array([self.get_node_id(segment_id, chunk_id) for segment_id in segment_ids], dtype=np.uint64) return node_ids def get_unique_node_id(self, chunk_id: np.uint64) -> np.uint64: """ Return unique Node ID for given Chunk ID atomic counter :param chunk_id: np.uint64 :return: np.uint64 """ return self.get_unique_node_id_range(chunk_id=chunk_id, step=1)[0] def get_max_node_id(self, chunk_id: np.uint64) -> np.uint64: """ Gets maximal node id in a chunk based on the atomic counter This is an approximation. It is not guaranteed that all ids smaller or equal to this id exists. However, it is guaranteed that no larger id exist at the time this function is executed. :return: uint64 """ counter_key = serialize_key('counter') # Incrementer row keys start with an "i" row_key = serialize_key("i%s" % pad_node_id(chunk_id)) row = self.table.read_row(row_key) # Read incrementer value if row is not None: max_node_id_b = row.cells[self.incrementer_family_id][counter_key][0].value max_node_id = int.from_bytes(max_node_id_b, byteorder="big") else: max_node_id = 0 return np.uint64(max_node_id) def get_unique_operation_id(self) -> np.uint64: """ Finds a unique operation id atomic counter Operations essentially live in layer 0. Even if segmentation ids might live in layer 0 one day, they would not collide with the operation ids because we write information belonging to operations in a separate family id. :return: str """ counter_key = serialize_key('counter') # Incrementer row keys start with an "i" row_key = serialize_key("ioperations") append_row = self.table.row(row_key, append=True) append_row.increment_cell_value(self.incrementer_family_id, counter_key, 1) # This increments the row entry and returns the value AFTER incrementing latest_row = append_row.commit() operation_id_b = latest_row[self.incrementer_family_id][counter_key][0][0] operation_id = int.from_bytes(operation_id_b, byteorder="big") return np.uint64(operation_id) def get_max_operation_id(self) -> np.uint64: """ Gets maximal operation id based on the atomic counter This is an approximation. It is not guaranteed that all ids smaller or equal to this id exists. However, it is guaranteed that no larger id exist at the time this function is executed. :return: uint64 """ counter_key = serialize_key('counter') # Incrementer row keys start with an "i" row_key = serialize_key("ioperations") row = self.table.read_row(row_key) # Read incrementer value if row is not None: max_operation_id_b = row.cells[self.incrementer_family_id][counter_key][0].value max_operation_id = int.from_bytes(max_operation_id_b, byteorder="big") else: max_operation_id = 0 return np.uint64(max_operation_id) def get_cross_chunk_edges_layer(self, cross_edges): if len(cross_edges) == 0: return np.array([], dtype=np.int) cross_chunk_edge_layers = np.ones(len(cross_edges), dtype=np.int) * 2 cross_edge_coordinates = [] for cross_edge in cross_edges: cross_edge_coordinates.append( [self.get_chunk_coordinates(cross_edge[0]), self.get_chunk_coordinates(cross_edge[1])]) cross_edge_coordinates = np.array(cross_edge_coordinates, dtype=np.int) for layer in range(3, self.n_layers): cross_edge_coordinates = cross_edge_coordinates // self.fan_out edge_diff = np.sum(np.abs(cross_edge_coordinates[:, 0] - cross_edge_coordinates[:, 1]), axis=1) cross_chunk_edge_layers[edge_diff > 0] += 1 return cross_chunk_edge_layers def get_cross_chunk_edge_dict(self, cross_edges): cce_layers = self.get_cross_chunk_edges_layer(cross_edges) u_cce_layers = np.unique(cce_layers) cross_edge_dict = {} for l in range(2, self.n_layers): cross_edge_dict[l] = \ np.array([], dtype=np.uint64).reshape(-1, 2) val_dict = {} for cc_layer in u_cce_layers: layer_cross_edges = cross_edges[cce_layers == cc_layer] if len(layer_cross_edges) > 0: val_dict["atomic_cross_edges_%d" % cc_layer] = \ layer_cross_edges.tobytes() cross_edge_dict[cc_layer] = layer_cross_edges return cross_edge_dict def read_row(self, node_id: np.uint64, key: str, idx: int = 0, dtype: type = np.uint64, get_time_stamp: bool = False, fam_id: str = None) -> Any: """ Reads row from BigTable and takes care of serializations :param node_id: uint64 :param key: table column :param idx: column list index :param dtype: np.dtype :param get_time_stamp: bool :param fam_id: str :return: row entry """ key = serialize_key(key) if fam_id is None: fam_id = self.family_id row = self.table.read_row(serialize_uint64(node_id), filter_=ColumnQualifierRegexFilter(key)) if row is None or key not in row.cells[fam_id]: if get_time_stamp: return None, None else: return None cell_entries = row.cells[fam_id][key] if dtype is None: cell_value = cell_entries[idx].value else: cell_value = np.frombuffer(cell_entries[idx].value, dtype=dtype) if get_time_stamp: return cell_value, cell_entries[idx].timestamp else: return cell_value def mutate_row(self, row_key: bytes, column_family_id: str, val_dict: dict, time_stamp: Optional[datetime.datetime] = None ) -> bigtable.row.Row: """ Mutates a single row :param row_key: serialized bigtable row key :param column_family_id: str serialized column family id :param val_dict: dict :param time_stamp: None or datetime :return: list """ row = self.table.row(row_key) for column, value in val_dict.items(): row.set_cell(column_family_id=column_family_id, column=column, value=value, timestamp=time_stamp) return row def bulk_write(self, rows: Iterable[bigtable.row.DirectRow], root_ids: Optional[Union[np.uint64, Iterable[np.uint64]]] = None, operation_id: Optional[np.uint64] = None, slow_retry: bool = True, block_size: int = 2000) -> bool: """ Writes a list of mutated rows in bulk WARNING: If <rows> contains the same row (same row_key) and column key two times only the last one is effectively written to the BigTable (even when the mutations were applied to different columns) --> no versioning! :param rows: list list of mutated rows :param root_ids: list if uint64 :param operation_id: uint64 or None operation_id (or other unique id) that *was* used to lock the root the bulk write is only executed if the root is still locked with the same id. :param slow_retry: bool :param block_size: int """ if slow_retry: initial = 5 else: initial = 1 retry_policy = Retry( predicate=if_exception_type((Aborted, DeadlineExceeded, ServiceUnavailable)), initial=initial, maximum=15.0, multiplier=2.0, deadline=LOCK_EXPIRED_TIME_DELTA.seconds) if root_ids is not None and operation_id is not None: if isinstance(root_ids, int): root_ids = [root_ids] if not self.check_and_renew_root_locks(root_ids, operation_id): return False for i_row in range(0, len(rows), block_size): status = self.table.mutate_rows(rows[i_row: i_row + block_size], retry=retry_policy) if not all(status): raise Exception(status) return True def _range_read_execution(self, start_id, end_id, row_filter: RowFilter = None, n_retries: int = 100): """ Executes predefined range read (read_rows) :param start_id: np.uint64 :param end_id: np.uint64 :param row_filter: BigTable RowFilter :param n_retries: int :return: dict """ # Set up read range_read = self.table.read_rows( start_key=serialize_uint64(start_id), end_key=serialize_uint64(end_id), # allow_row_interleaving=True, end_inclusive=True, filter_=row_filter) range_read.consume_all() # Execute read consume_success = False # Retry reading if any of the writes failed i_tries = 0 while not consume_success and i_tries < n_retries: try: range_read.consume_all() consume_success = True except: time.sleep(i_tries) i_tries += 1 if not consume_success: raise Exception("Unable to consume range read: " "%d - %d -- n_retries = %d" % (start_id, end_id, n_retries)) return range_read.rows def range_read(self, start_id: np.uint64, end_id: np.uint64, n_retries: int = 100, max_block_size: int = 50000, row_keys: Optional[Iterable[str]] = None, row_key_filters: Optional[Iterable[str]] = None, time_stamp: datetime.datetime = datetime.datetime.max ) -> Union[ bigtable.row_data.PartialRowData, Dict[bytes, bigtable.row_data.PartialRowData]]: """ Reads all ids within a given range :param start_id: np.uint64 :param end_id: np.uint64 :param n_retries: int :param max_block_size: int :param row_keys: list of str more efficient read through row filters :param row_key_filters: list of str rows *with* this column will be ignored :param time_stamp: datetime.datetime :return: dict """ # Comply to resolution of BigTables TimeRange time_stamp -= datetime.timedelta( microseconds=time_stamp.microsecond % 1000) # Create filters: time and id range time_filter = TimestampRangeFilter(TimestampRange(end=time_stamp)) if row_keys is not None: filters = [] for k in row_keys: filters.append(ColumnQualifierRegexFilter(serialize_key(k))) if len(filters) > 1: row_filter = RowFilterUnion(filters) else: row_filter = filters[0] else: row_filter = None if row_filter is None: row_filter = time_filter else: row_filter = RowFilterChain([time_filter, row_filter]) if row_key_filters is not None: for row_key in row_key_filters: key_filter = ColumnRangeFilter( column_family_id=self.family_id, start_column=row_key, end_column=row_key, inclusive_start=True, inclusive_end=True) row_filter = ConditionalRowFilter(base_filter=key_filter, false_filter=row_filter, true_filter=BlockAllFilter(True)) max_block_size = np.uint64(max_block_size) block_start_ids = range(start_id, end_id, max_block_size) row_dict = {} for block_start_id in block_start_ids: block_end_id = np.uint64(block_start_id + max_block_size) if block_end_id > end_id: block_end_id = end_id block_row_dict = self._range_read_execution(start_id=block_start_id, end_id=block_end_id, row_filter=row_filter, n_retries=n_retries) row_dict.update(block_row_dict) return row_dict def range_read_chunk(self, layer: int, x: int, y: int, z: int, n_retries: int = 100, max_block_size: int = 1000000, row_keys: Optional[Iterable[str]] = None, row_key_filters: Optional[Iterable[str]] = None, time_stamp: datetime.datetime = datetime.datetime.max, ) -> Union[ bigtable.row_data.PartialRowData, Dict[bytes, bigtable.row_data.PartialRowData]]: """ Reads all ids within a chunk :param layer: int :param x: int :param y: int :param z: int :param n_retries: int :param max_block_size: int :param row_keys: list of str more efficient read through row filters :param row_key_filters: list of str rows *with* this column will be ignored :param time_stamp: datetime.datetime :return: dict """ chunk_id = self.get_chunk_id(layer=layer, x=x, y=y, z=z) if layer == 1: max_segment_id = self.get_segment_id_limit(chunk_id) max_block_size = max_segment_id + 1 else: max_segment_id = self.get_max_node_id(chunk_id=chunk_id) # Define BigTable keys start_id = self.get_node_id(np.uint64(0), chunk_id=chunk_id) end_id = self.get_node_id(max_segment_id, chunk_id=chunk_id) try: rr = self.range_read(start_id, end_id, n_retries=n_retries, max_block_size=max_block_size, row_keys=row_keys, row_key_filters=row_key_filters, time_stamp=time_stamp) except: raise Exception("Unable to consume range read: " "[%d, %d, %d], l = %d, n_retries = %d" % (x, y, z, layer, n_retries)) return rr def range_read_operations(self, time_start: datetime.datetime = datetime.datetime.min, time_end: datetime.datetime = None, start_id: np.uint64 = 0, end_id: np.uint64 = None, n_retries: int = 100, row_keys: Optional[Iterable[str]] = None ) -> Dict[bytes, bigtable.row_data.PartialRowData]: """ Reads all ids within a chunk :param time_start: datetime :param time_end: datetime :param start_id: uint64 :param end_id: uint64 :param n_retries: int :param row_keys: list of str more efficient read through row filters :return: list or yield of rows """ # Set defaults if end_id is None: end_id = self.get_max_operation_id() if time_end is None: time_end = datetime.datetime.utcnow() if end_id < start_id: return {} # Comply to resolution of BigTables TimeRange time_start -= datetime.timedelta( microseconds=time_start.microsecond % 1000) time_end -= datetime.timedelta( microseconds=time_end.microsecond % 1000) # Create filters: time and id range time_filter = TimestampRangeFilter(TimestampRange(start=time_start, end=time_end)) if row_keys is not None: filters = [] for k in row_keys: filters.append(ColumnQualifierRegexFilter(serialize_key(k))) if len(filters) > 1: row_filter = RowFilterUnion(filters) else: row_filter = filters[0] else: row_filter = None if row_filter is None: row_filter = time_filter else: row_filter = RowFilterChain([time_filter, row_filter]) # Set up read range_read = self.table.read_rows( start_key=serialize_uint64(start_id), end_key=serialize_uint64(end_id), end_inclusive=False, filter_=row_filter) range_read.consume_all() # Execute read consume_success = False # Retry reading if any of the writes failed i_tries = 0 while not consume_success and i_tries < n_retries: try: range_read.consume_all() consume_success = True except: time.sleep(i_tries) i_tries += 1 if not consume_success: raise Exception("Unable to consume chunk range read: " "n_retries = %d" % (n_retries)) return range_read.rows def range_read_layer(self, layer_id: int): """ Reads all ids within a layer This can take a while depending on the size of the graph :param layer_id: int :return: list of rows """ raise NotImplementedError() def test_if_nodes_are_in_same_chunk(self, node_ids: Sequence[np.uint64] ) -> bool: """ Test whether two nodes are in the same chunk :param node_ids: list of two ints :return: bool """ assert len(node_ids) == 2 return self.get_chunk_id(node_id=node_ids[0]) == \ self.get_chunk_id(node_id=node_ids[1]) def get_chunk_id_from_coord(self, layer: int, x: int, y: int, z: int) -> np.uint64: """ Return ChunkID for given chunked graph layer and voxel coordinates. :param layer: int -- ChunkedGraph layer :param x: int -- X coordinate in voxel :param y: int -- Y coordinate in voxel :param z: int -- Z coordinate in voxel :return: np.uint64 -- ChunkID """ base_chunk_span = int(self.fan_out) ** max(0, layer - 2) return self.get_chunk_id( layer=layer, x=x // (int(self.chunk_size[0]) * base_chunk_span), y=y // (int(self.chunk_size[1]) * base_chunk_span), z=z // (int(self.chunk_size[2]) * base_chunk_span)) def get_atomic_id_from_coord(self, x: int, y: int, z: int, parent_id: np.uint64, n_tries: int=5 ) -> np.uint64: """ Determines atomic id given a coordinate :param x: int :param y: int :param z: int :param parent_id: np.uint64 :param n_tries: int :return: np.uint64 or None """ if self.get_chunk_layer(parent_id) == 1: return parent_id x /= 2**self.cv_mip y /= 2**self.cv_mip x = int(x) y = int(y) checked = [] atomic_id = None root_id = self.get_root(parent_id) for i_try in range(n_tries): # Define block size -- increase by one each try x_l = x - (i_try - 1)**2 y_l = y - (i_try - 1)**2 z_l = z - (i_try - 1)**2 x_h = x + 1 + (i_try - 1)**2 y_h = y + 1 + (i_try - 1)**2 z_h = z + 1 + (i_try - 1)**2 if x_l < 0: x_l = 0 if y_l < 0: y_l = 0 if z_l < 0: z_l = 0 # Get atomic ids from cloudvolume atomic_id_block = self.cv[x_l: x_h, y_l: y_h, z_l: z_h] atomic_ids, atomic_id_count = np.unique(atomic_id_block, return_counts=True) # sort by frequency and discard those ids that have been checked # previously sorted_atomic_ids = atomic_ids[np.argsort(atomic_id_count)] sorted_atomic_ids = sorted_atomic_ids[~np.in1d(sorted_atomic_ids, checked)] # For each candidate id check whether its root id corresponds to the # given root id for candidate_atomic_id in sorted_atomic_ids: ass_root_id = self.get_root(candidate_atomic_id) if ass_root_id == root_id: # atomic_id is not None will be our indicator that the # search was successful atomic_id = candidate_atomic_id break else: checked.append(candidate_atomic_id) if atomic_id is not None: break # Returns None if unsuccessful return atomic_id def _create_split_log_row(self, operation_id: np.uint64, user_id: str, root_ids: Sequence[np.uint64], selected_atomic_ids: Sequence[np.uint64], removed_edges: Sequence[np.uint64], time_stamp: datetime.datetime ) -> bigtable.row.Row: val_dict = {serialize_key("user"): serialize_key(user_id), serialize_key("roots"): np.array(root_ids, dtype=np.uint64).tobytes(), serialize_key("atomic_ids"): np.array(selected_atomic_ids).tobytes(), serialize_key("removed_edges"): np.array(removed_edges, dtype=np.uint64).tobytes()} row = self.mutate_row(serialize_uint64(operation_id), self.log_family_id, val_dict, time_stamp) return row def _create_merge_log_row(self, operation_id: np.uint64, user_id: str, root_ids: Sequence[np.uint64], selected_atomic_ids: Sequence[np.uint64], time_stamp: datetime.datetime ) -> bigtable.row.Row: val_dict = {serialize_key("user"): serialize_key(user_id), serialize_key("roots"): np.array(root_ids, dtype=np.uint64).tobytes(), serialize_key("atomic_ids"): np.array(selected_atomic_ids).tobytes()} row = self.mutate_row(serialize_uint64(operation_id), self.log_family_id, val_dict, time_stamp) return row def add_atomic_edges_in_chunks(self, edge_id_dict: dict, edge_aff_dict: dict, edge_area_dict: dict, isolated_node_ids: Sequence[np.uint64], verbose: bool = True, time_stamp: Optional[datetime.datetime] = None): """ Creates atomic nodes in first abstraction layer for a SINGLE chunk and all abstract nodes in the second for the same chunk Alle edges (edge_ids) need to be from one chunk and no nodes should exist for this chunk prior to calling this function. All cross edges (cross_edge_ids) have to point out the chunk (first entry is the id within the chunk) :param edge_ids: n x 2 array of uint64s :param cross_edge_ids: m x 2 array of uint64s :param edge_affs: float array of length n :param cross_edge_affs: float array of length m :param isolated_node_ids: list of uint64s ids of nodes that have no edge in the chunked graph :param verbose: bool :param time_stamp: datetime """ if time_stamp is None: time_stamp = datetime.datetime.utcnow() if time_stamp.tzinfo is None: time_stamp = UTC.localize(time_stamp) edge_id_keys = ["in_connected", "in_disconnected", "cross", "between_connected", "between_disconnected"] edge_aff_keys = ["in_connected", "in_disconnected", "between_connected", "between_disconnected"] # Check if keys exist and include an empty array if not n_edge_ids = 0 chunk_id = None for edge_id_key in edge_id_keys: if not edge_id_key in edge_id_dict: empty_edges = np.array([], dtype=np.uint64).reshape(0, 2) edge_id_dict[edge_id_key] = empty_edges else: n_edge_ids += len(edge_id_dict[edge_id_key]) if len(edge_id_dict[edge_id_key]) > 0: node_id = edge_id_dict[edge_id_key][0, 0] chunk_id = self.get_chunk_id(node_id) for edge_aff_key in edge_aff_keys: if not edge_aff_key in edge_aff_dict: edge_aff_dict[edge_aff_key] = np.array([], dtype=np.float32) time_start = time.time() # Catch trivial case if n_edge_ids == 0 and len(isolated_node_ids) == 0: return 0 # Make parent id creation easier if chunk_id is None: chunk_id = self.get_chunk_id(isolated_node_ids[0]) chunk_id_c = self.get_chunk_coordinates(chunk_id) parent_chunk_id = self.get_chunk_id(layer=2, x=chunk_id_c[0], y=chunk_id_c[1], z=chunk_id_c[2]) # Get connected component within the chunk chunk_node_ids = np.concatenate([ isolated_node_ids, np.unique(edge_id_dict["in_connected"]), np.unique(edge_id_dict["in_disconnected"]), np.unique(edge_id_dict["cross"][:, 0]), np.unique(edge_id_dict["between_connected"][:, 0]), np.unique(edge_id_dict["between_disconnected"][:, 0])]) chunk_node_ids = np.unique(chunk_node_ids) node_chunk_ids = np.array([self.get_chunk_id(c) for c in chunk_node_ids], dtype=np.uint64) u_node_chunk_ids, c_node_chunk_ids = np.unique(node_chunk_ids, return_counts=True) if len(u_node_chunk_ids) > 1: raise Exception("%d: %d chunk ids found in node id list. " "Some edges might be in the wrong order. " "Number of occurences:" % (chunk_id, len(u_node_chunk_ids)), c_node_chunk_ids) chunk_g = nx.Graph() chunk_g.add_nodes_from(chunk_node_ids) chunk_g.add_edges_from(edge_id_dict["in_connected"]) ccs = list(nx.connected_components(chunk_g)) # if verbose: # print("CC in chunk: %.3fs" % (time.time() - time_start)) # Add rows for nodes that are in this chunk # a connected component at a time node_c = 0 # Just a counter for the print / speed measurement n_ccs = len(ccs) parent_ids = self.get_unique_node_id_range(parent_chunk_id, step=n_ccs) time_start = time.time() time_dict = collections.defaultdict(list) time_start_1 = time.time() sparse_indices = {} remapping = {} for k in edge_id_dict.keys(): # Circumvent datatype issues u_ids, inv_ids = np.unique(edge_id_dict[k], return_inverse=True) mapped_ids = np.arange(len(u_ids), dtype=np.int32) remapped_arr = mapped_ids[inv_ids].reshape(edge_id_dict[k].shape) sparse_indices[k] = compute_indices_pandas(remapped_arr) remapping[k] = dict(zip(u_ids, mapped_ids)) time_dict["sparse_indices"].append(time.time() - time_start_1) rows = [] for i_cc, cc in enumerate(ccs): # if node_c % 1000 == 1 and verbose: # dt = time.time() - time_start # print("%5d at %5d - %.5fs " % # (i_cc, node_c, dt / node_c), end="\r") node_ids = np.array(list(cc)) u_chunk_ids = np.unique([self.get_chunk_id(n) for n in node_ids]) if len(u_chunk_ids) > 1: print("Found multiple chunk ids:", u_chunk_ids) raise Exception() # Create parent id parent_id = parent_ids[i_cc] parent_id_b = np.array(parent_id, dtype=np.uint64).tobytes() parent_cross_edges = np.array([], dtype=np.uint64).reshape(0, 2) # Add rows for nodes that are in this chunk for i_node_id, node_id in enumerate(node_ids): # Extract edges relevant to this node # in chunk + connected time_start_2 = time.time() if node_id in remapping["in_connected"]: row_ids, column_ids = sparse_indices["in_connected"][remapping["in_connected"][node_id]] inv_column_ids = (column_ids + 1) % 2 connected_ids = edge_id_dict["in_connected"][row_ids, inv_column_ids] connected_affs = edge_aff_dict["in_connected"][row_ids] connected_areas = edge_area_dict["in_connected"][row_ids] time_dict["in_connected"].append(time.time() - time_start_2) time_start_2 = time.time() else: connected_ids = np.array([], dtype=np.uint64) connected_affs = np.array([], dtype=np.float32) connected_areas = np.array([], dtype=np.uint64) # in chunk + disconnected if node_id in remapping["in_disconnected"]: row_ids, column_ids = sparse_indices["in_disconnected"][remapping["in_disconnected"][node_id]] inv_column_ids = (column_ids + 1) % 2 disconnected_ids = edge_id_dict["in_disconnected"][row_ids, inv_column_ids] disconnected_affs = edge_aff_dict["in_disconnected"][row_ids] disconnected_areas = edge_area_dict["in_disconnected"][row_ids] time_dict["in_disconnected"].append(time.time() - time_start_2) time_start_2 = time.time() else: disconnected_ids = np.array([], dtype=np.uint64) disconnected_affs = np.array([], dtype=np.float32) disconnected_areas = np.array([], dtype=np.uint64) # out chunk + connected if node_id in remapping["between_connected"]: row_ids, column_ids = sparse_indices["between_connected"][remapping["between_connected"][node_id]] row_ids = row_ids[column_ids == 0] column_ids = column_ids[column_ids == 0] inv_column_ids = (column_ids + 1) % 2 time_dict["out_connected_mask"].append(time.time() - time_start_2) time_start_2 = time.time() connected_ids = np.concatenate([connected_ids, edge_id_dict["between_connected"][row_ids, inv_column_ids]]) connected_affs = np.concatenate([connected_affs, edge_aff_dict["between_connected"][row_ids]]) connected_areas = np.concatenate([connected_areas, edge_area_dict["between_connected"][row_ids]]) parent_cross_edges = np.concatenate([parent_cross_edges, edge_id_dict["between_connected"][row_ids]]) time_dict["out_connected"].append(time.time() - time_start_2) time_start_2 = time.time() # out chunk + disconnected if node_id in remapping["between_disconnected"]: row_ids, column_ids = sparse_indices["between_disconnected"][remapping["between_disconnected"][node_id]] row_ids = row_ids[column_ids == 0] column_ids = column_ids[column_ids == 0] inv_column_ids = (column_ids + 1) % 2 time_dict["out_disconnected_mask"].append(time.time() - time_start_2) time_start_2 = time.time() connected_ids = np.concatenate([connected_ids, edge_id_dict["between_disconnected"][row_ids, inv_column_ids]]) connected_affs = np.concatenate([connected_affs, edge_aff_dict["between_disconnected"][row_ids]]) connected_areas = np.concatenate([connected_areas, edge_area_dict["between_disconnected"][row_ids]]) time_dict["out_disconnected"].append(time.time() - time_start_2) time_start_2 = time.time() # cross if node_id in remapping["cross"]: row_ids, column_ids = sparse_indices["cross"][remapping["cross"][node_id]] row_ids = row_ids[column_ids == 0] column_ids = column_ids[column_ids == 0] inv_column_ids = (column_ids + 1) % 2 time_dict["cross_mask"].append(time.time() - time_start_2) time_start_2 = time.time() connected_ids = np.concatenate([connected_ids, edge_id_dict["cross"][row_ids, inv_column_ids]]) connected_affs = np.concatenate([connected_affs, np.full((len(row_ids)), np.inf, dtype=np.float32)]) connected_areas = np.concatenate([connected_areas, np.zeros((len(row_ids)), dtype=np.uint64)]) parent_cross_edges = np.concatenate([parent_cross_edges, edge_id_dict["cross"][row_ids]]) time_dict["cross"].append(time.time() - time_start_2) time_start_2 = time.time() # Create node val_dict = \ {"atomic_connected_partners": connected_ids.tobytes(), "atomic_connected_affinities": connected_affs.tobytes(), "atomic_connected_areas": connected_areas.tobytes(), "atomic_disconnected_partners": disconnected_ids.tobytes(), "atomic_disconnected_affinities": disconnected_affs.tobytes(), "atomic_disconnected_areas": disconnected_areas.tobytes(), "parents": parent_id_b} rows.append(self.mutate_row(serialize_uint64(node_id), self.family_id, val_dict, time_stamp=time_stamp)) node_c += 1 time_dict["creating_lv1_row"].append(time.time() - time_start_2) time_start_1 = time.time() # Create parent node rows.append(self.mutate_row(serialize_uint64(parent_id), self.family_id, {"children": node_ids.tobytes()}, time_stamp=time_stamp)) time_dict["creating_lv2_row"].append(time.time() - time_start_1) time_start_1 = time.time() cce_layers = self.get_cross_chunk_edges_layer(parent_cross_edges) u_cce_layers = np.unique(cce_layers) val_dict = {} for cc_layer in u_cce_layers: layer_cross_edges = parent_cross_edges[cce_layers == cc_layer] if len(layer_cross_edges) > 0: val_dict["atomic_cross_edges_%d" % cc_layer] = \ layer_cross_edges.tobytes() if len(val_dict) > 0: rows.append(self.mutate_row(serialize_uint64(parent_id), self.cross_edge_family_id, val_dict, time_stamp=time_stamp)) node_c += 1 time_dict["adding_cross_edges"].append(time.time() - time_start_1) if len(rows) > 100000: time_start_1 = time.time() self.bulk_write(rows) time_dict["writing"].append(time.time() - time_start_1) if len(rows) > 0: time_start_1 = time.time() self.bulk_write(rows) time_dict["writing"].append(time.time() - time_start_1) if verbose: print("Time creating rows: %.3fs for %d ccs with %d nodes" % (time.time() - time_start, len(ccs), node_c)) for k in time_dict.keys(): print("%s -- %.3fms for %d instances -- avg = %.3fms" % (k, np.sum(time_dict[k])*1000, len(time_dict[k]), np.mean(time_dict[k])*1000)) def add_layer(self, layer_id: int, child_chunk_coords: Sequence[Sequence[int]], time_stamp: Optional[datetime.datetime] = None, verbose: bool = True, n_threads: int = 20) -> None: """ Creates the abstract nodes for a given chunk in a given layer :param layer_id: int :param child_chunk_coords: int array of length 3 coords in chunk space :param time_stamp: datetime :param verbose: bool :param n_threads: int """ def _read_subchunks_thread(chunk_coord): # Get start and end key x, y, z = chunk_coord row_keys = ["children"] + \ ["atomic_cross_edges_%d" % l for l in range(layer_id - 1, self.n_layers)] range_read = self.range_read_chunk(layer_id - 1, x, y, z, row_keys=row_keys) # Due to restarted jobs some parents might be duplicated. We can # find these duplicates only by comparing their children because # each node has a unique id. However, we can use that more recently # created nodes have higher segment ids. We are only interested in # the latest version of any duplicated parents. # Deserialize row keys and store child with highest id for # comparison row_cell_dict = {} segment_ids = [] row_ids = [] max_child_ids = [] for row_id_b, row_data in range_read.items(): row_id = deserialize_uint64(row_id_b) segment_id = self.get_segment_id(row_id) cells = row_data.cells cell_family = cells[self.family_id] if self.cross_edge_family_id in cells: row_cell_dict[row_id] = cells[self.cross_edge_family_id] node_child_ids_b = cell_family[children_key][0].value node_child_ids = np.frombuffer(node_child_ids_b, dtype=np.uint64) max_child_ids.append(np.max(node_child_ids)) segment_ids.append(segment_id) row_ids.append(row_id) segment_ids = np.array(segment_ids, dtype=np.uint64) row_ids = np.array(row_ids) max_child_ids = np.array(max_child_ids, dtype=np.uint64) sorting = np.argsort(segment_ids)[::-1] row_ids = row_ids[sorting] max_child_ids = max_child_ids[sorting] counter = collections.defaultdict(int) max_child_ids_occ_so_far = np.zeros(len(max_child_ids), dtype=np.int) for i_row in range(len(max_child_ids)): max_child_ids_occ_so_far[i_row] = counter[max_child_ids[i_row]] counter[max_child_ids[i_row]] += 1 # Filter last occurences (we inverted the list) of each node m = max_child_ids_occ_so_far == 0 row_ids = row_ids[m] ll_node_ids.extend(row_ids) # Loop through nodes from this chunk for row_id in row_ids: if row_id in row_cell_dict: cross_edge_dict[row_id] = {} cell_family = row_cell_dict[row_id] for l in range(layer_id - 1, self.n_layers): row_key = serialize_key("atomic_cross_edges_%d" % l) if row_key in cell_family: cross_edge_dict[row_id][l] = cell_family[row_key][0].value if int(layer_id - 1) in cross_edge_dict[row_id]: atomic_cross_edges_b = cross_edge_dict[row_id][layer_id - 1] atomic_cross_edges = \ np.frombuffer(atomic_cross_edges_b, dtype=np.uint64).reshape(-1, 2) if len(atomic_cross_edges) > 0: atomic_partner_id_dict[row_id] = \ atomic_cross_edges[:, 1] new_pairs = zip(atomic_cross_edges[:, 0], [row_id] * len(atomic_cross_edges)) atomic_child_id_dict_pairs.extend(new_pairs) def _resolve_cross_chunk_edges_thread(args) -> None: start, end = args for i_child_key, child_key in\ enumerate(atomic_partner_id_dict_keys[start: end]): this_atomic_partner_ids = atomic_partner_id_dict[child_key] partners = {atomic_child_id_dict[atomic_cross_id] for atomic_cross_id in this_atomic_partner_ids if atomic_child_id_dict[atomic_cross_id] != 0} if len(partners) > 0: partners = np.array(list(partners), dtype=np.uint64)[:, None] this_ids = np.array([child_key] * len(partners), dtype=np.uint64)[:, None] these_edges = np.concatenate([this_ids, partners], axis=1) edge_ids.extend(these_edges) def _write_out_connected_components(args) -> None: start, end = args n_ccs = int(end - start) parent_ids = self.get_unique_node_id_range(chunk_id, step=n_ccs) rows = [] for i_cc, cc in enumerate(ccs[start: end]): node_ids = np.array(list(cc)) parent_id = parent_ids[i_cc] parent_id_b = np.array(parent_id, dtype=np.uint64).tobytes() parent_cross_edges_b = {} for l in range(layer_id, self.n_layers): parent_cross_edges_b[l] = b"" # Add rows for nodes that are in this chunk for i_node_id, node_id in enumerate(node_ids): if node_id in cross_edge_dict: # Extract edges relevant to this node for l in range(layer_id, self.n_layers): if l in cross_edge_dict[node_id]: parent_cross_edges_b[l] += \ cross_edge_dict[node_id][l] # Create node val_dict = {"parents": parent_id_b} rows.append(self.mutate_row(serialize_uint64(node_id), self.family_id, val_dict, time_stamp=time_stamp)) # Create parent node val_dict = {"children": node_ids.tobytes()} rows.append(self.mutate_row(serialize_uint64(parent_id), self.family_id, val_dict, time_stamp=time_stamp)) val_dict = {} for l in range(layer_id, self.n_layers): if l in parent_cross_edges_b: val_dict["atomic_cross_edges_%d" % l] = \ parent_cross_edges_b[l] if len(val_dict) > 0: rows.append(self.mutate_row(serialize_uint64(parent_id), self.cross_edge_family_id, val_dict, time_stamp=time_stamp)) if len(rows) > 100000: self.bulk_write(rows) rows = [] if len(rows) > 0: self.bulk_write(rows) if time_stamp is None: time_stamp = datetime.datetime.utcnow() if time_stamp.tzinfo is None: time_stamp = UTC.localize(time_stamp) # 1 -------------------------------------------------------------------- # The first part is concerned with reading data from the child nodes # of this layer and pre-processing it for the second part time_start = time.time() children_key = serialize_key("children") atomic_partner_id_dict = {} cross_edge_dict = {} atomic_child_id_dict_pairs = [] ll_node_ids = [] multi_args = child_chunk_coords n_jobs = np.min([n_threads, len(multi_args)]) if n_jobs > 0: mu.multithread_func(_read_subchunks_thread, multi_args, n_threads=n_jobs) d = dict(atomic_child_id_dict_pairs) atomic_child_id_dict = collections.defaultdict(np.uint64, d) ll_node_ids = np.array(ll_node_ids, dtype=np.uint64) if verbose: print("Time iterating through subchunks: %.3fs" % (time.time() - time_start)) time_start = time.time() # Extract edges from remaining cross chunk edges # and maintain unused cross chunk edges edge_ids = [] # u_atomic_child_ids = np.unique(atomic_child_ids) atomic_partner_id_dict_keys = \ np.array(list(atomic_partner_id_dict.keys()), dtype=np.uint64) if n_threads > 1: n_jobs = n_threads * 3 # Heuristic else: n_jobs = 1 n_jobs = np.min([n_jobs, len(atomic_partner_id_dict_keys)]) if n_jobs > 0: spacing = np.linspace(0, len(atomic_partner_id_dict_keys), n_jobs+1).astype(np.int) starts = spacing[:-1] ends = spacing[1:] multi_args = list(zip(starts, ends)) mu.multithread_func(_resolve_cross_chunk_edges_thread, multi_args, n_threads=n_threads) if verbose: print("Time resolving cross chunk edges: %.3fs" % (time.time() - time_start)) time_start = time.time() # 2 -------------------------------------------------------------------- # The second part finds connected components, writes the parents to # BigTable and updates the childs # Make parent id creation easier x, y, z = np.min(child_chunk_coords, axis=0) // self.fan_out chunk_id = self.get_chunk_id(layer=layer_id, x=x, y=y, z=z) # Extract connected components chunk_g = nx.from_edgelist(edge_ids) # Add single node objects that have no edges isolated_node_mask = ~np.in1d(ll_node_ids, np.unique(edge_ids)) add_ccs = list(ll_node_ids[isolated_node_mask][:, None]) ccs = list(nx.connected_components(chunk_g)) + add_ccs if verbose: print("Time connected components: %.3fs" % (time.time() - time_start)) time_start = time.time() # Add rows for nodes that are in this chunk # a connected component at a time if n_threads > 1: n_jobs = n_threads * 3 # Heuristic else: n_jobs = 1 n_jobs = np.min([n_jobs, len(ccs)]) spacing = np.linspace(0, len(ccs), n_jobs+1).astype(np.int) starts = spacing[:-1] ends = spacing[1:] multi_args = list(zip(starts, ends)) mu.multithread_func(_write_out_connected_components, multi_args, n_threads=n_threads) if verbose: print("Time writing %d connected components in layer %d: %.3fs" % (len(ccs), layer_id, time.time() - time_start)) def get_atomic_cross_edge_dict(self, node_id: np.uint64, layer_ids: Sequence[int] = None, deserialize_node_ids: bool = False, reshape: bool = False): """ Extracts all atomic cross edges and serves them as a dictionary :param node_id: np.uitn64 :param layer_ids: list of ints :param deserialize_node_ids: bool :param reshape: bool reshapes the list of node ids to an edge list (n x 2) Only available when deserializing :return: dict """ row = self.table.read_row(serialize_uint64(node_id)) if row is None: return {} atomic_cross_edges = {} if isinstance(layer_ids, int): layer_ids = [layer_ids] if layer_ids is None: layer_ids = range(2, self.n_layers) if self.cross_edge_family_id in row.cells: for l in layer_ids: key = serialize_key("atomic_cross_edges_%d" % l) row_cell = row.cells[self.cross_edge_family_id] atomic_cross_edges[l] = [] if key in row_cell: row_val = row_cell[key][0].value if deserialize_node_ids: atomic_cross_edges[l] = np.frombuffer(row_val, dtype=np.uint64) if reshape: atomic_cross_edges[l] = \ atomic_cross_edges[l].reshape(-1, 2) else: atomic_cross_edges[l] = row_val return atomic_cross_edges def get_parent(self, node_id: np.uint64, get_only_relevant_parent: bool = True, time_stamp: Optional[datetime.datetime] = None) -> Union[ List[Tuple[np.uint64, datetime.datetime]], np.uint64, None]: """ Acquires parent of a node at a specific time stamp :param node_id: uint64 :param get_only_relevant_parent: bool True: return single parent according to time_stamp False: return n x 2 list of all parents ((parent_id, time_stamp), ...) :param time_stamp: datetime or None :return: uint64 or None """ if time_stamp is None: time_stamp = datetime.datetime.utcnow() if time_stamp.tzinfo is None: time_stamp = UTC.localize(time_stamp) parent_key = serialize_key("parents") all_parents = [] p_filter_ = ColumnQualifierRegexFilter(parent_key) row = self.table.read_row(serialize_uint64(node_id), filter_=p_filter_) if row and parent_key in row.cells[self.family_id]: for parent_entry in row.cells[self.family_id][parent_key]: if get_only_relevant_parent: if parent_entry.timestamp > time_stamp: continue else: return np.frombuffer(parent_entry.value, dtype=np.uint64)[0] else: all_parents.append((np.frombuffer(parent_entry.value, dtype=np.uint64)[0], parent_entry.timestamp)) else: return None if len(all_parents) == 0: raise Exception("Did not find a valid parent for %d with" " the given time stamp" % node_id) else: return all_parents def get_children(self, node_id: np.uint64) -> np.ndarray: """ Returns all children of a node :param node_id: np.uint64 :return: np.ndarray[np.uint64] """ children = self.read_row(node_id, "children", dtype=np.uint64) if children is None: return np.empty(0, dtype=np.uint64) else: return children def get_latest_edge_affinity(self, atomic_edge: [np.uint64, np.uint64], check: bool = False) -> np.float32: """ Looks up the LATEST affinity of an edge Future work should add a timestamp option :param atomic_edge: [uint64, uint64] :param check: bool whether to look up affinity from both sides and compare :return: float32 """ edge_affinities = [] if check: iter_max = 2 else: iter_max = 1 for i in range(iter_max): atomic_partners, atomic_affinities = \ self.get_atomic_partners(atomic_edge[i % 2], include_connected_partners=True, include_disconnected_partners=True) edge_mask = atomic_partners == atomic_edge[(i + 1) % 2] if len(edge_mask) == 0: raise Exception("Edge does not exist") edge_affinities.append(atomic_affinities[edge_mask][0]) if len(np.unique(edge_affinities)) == 1: return edge_affinities[0] else: raise Exception("Different edge affinities found... Something went " "horribly wrong.") def get_latest_roots(self, time_stamp: Optional[datetime.datetime] = datetime.datetime.max, n_threads: int = 1): """ :param time_stamp: :return: """ def _read_root_rows(args) -> None: start_seg_id, end_seg_id = args start_id = self.get_node_id(segment_id=start_seg_id, chunk_id=self.root_chunk_id) end_id = self.get_node_id(segment_id=end_seg_id, chunk_id=self.root_chunk_id) range_read = self.table.read_rows( start_key=serialize_uint64(start_id), end_key=serialize_uint64(end_id), # allow_row_interleaving=True, end_inclusive=False, filter_=time_filter) range_read.consume_all() rows = range_read.rows for row_id, row_data in rows.items(): row_keys = row_data.cells[self.family_id] if not serialize_key("new_parents") in row_keys: root_ids.append(deserialize_uint64(row_id)) time_stamp -= datetime.timedelta(microseconds=time_stamp.microsecond % 1000) time_filter = TimestampRangeFilter(TimestampRange(end=time_stamp)) max_seg_id = self.get_max_node_id(self.root_chunk_id) + 1 root_ids = [] n_blocks = np.min([n_threads*3+1, max_seg_id]) seg_id_blocks = np.linspace(1, max_seg_id, n_blocks, dtype=np.uint64) multi_args = [] for i_id_block in range(0, len(seg_id_blocks) - 1): multi_args.append([seg_id_blocks[i_id_block], seg_id_blocks[i_id_block + 1]]) mu.multithread_func( _read_root_rows, multi_args, n_threads=n_threads, debug=False, verbose=True) return root_ids def get_root(self, node_id: np.uint64, time_stamp: Optional[datetime.datetime] = None ) -> Union[List[np.uint64], np.uint64]: """ Takes a node id and returns the associated agglomeration ids :param atomic_id: uint64 :param time_stamp: None or datetime :return: np.uint64 """ if time_stamp is None: time_stamp = datetime.datetime.utcnow() if time_stamp.tzinfo is None: time_stamp = UTC.localize(time_stamp) early_finish = True if self.get_chunk_layer(node_id) == self.n_layers: raise Exception("node is already root") parent_id = node_id while early_finish: parent_id = node_id early_finish = False for i_layer in range(self.get_chunk_layer(node_id)+1, int(self.n_layers + 1)): temp_parent_id = self.get_parent(parent_id, time_stamp=time_stamp) if temp_parent_id is None: early_finish = True break else: parent_id = temp_parent_id return parent_id def get_all_parents(self, node_id: np.uint64, time_stamp: Optional[datetime.datetime] = None ) -> Union[List[np.uint64], np.uint64]: """ Takes a node id and returns all parents and parents' parents up to the top :param atomic_id: uint64 :param time_stamp: None or datetime :return: np.uint64 """ if time_stamp is None: time_stamp = datetime.datetime.utcnow() if time_stamp.tzinfo is None: time_stamp = UTC.localize(time_stamp) early_finish = True parent_ids: List[np.uint64] = [] while early_finish: parent_id = node_id parent_ids = [] early_finish = False for i_layer in range(self.get_chunk_layer(node_id)+1, int(self.n_layers + 1)): temp_parent_id = self.get_parent(parent_id, time_stamp=time_stamp) if temp_parent_id is None: early_finish = True break else: parent_id = temp_parent_id parent_ids.append(parent_id) return parent_ids def lock_root_loop(self, root_ids: Sequence[np.uint64], operation_id: np.uint64, max_tries: int = 1, waittime_s: float = 0.5) -> Tuple[bool, np.ndarray]: """ Attempts to lock multiple roots at the same time :param root_ids: list of uint64 :param operation_id: uint64 :param max_tries: int :param waittime_s: float :return: bool, list of uint64s success, latest root ids """ i_try = 0 while i_try < max_tries: lock_acquired = False # Collect latest root ids new_root_ids: List[np.uint64] = [] for i_root_id in range(len(root_ids)): future_root_ids = self.get_future_root_ids(root_ids[i_root_id]) if len(future_root_ids) == 0: new_root_ids.append(root_ids[i_root_id]) else: new_root_ids.extend(future_root_ids) # Attempt to lock all latest root ids root_ids = np.unique(new_root_ids) for i_root_id in range(len(root_ids)): print("operation id: %d - root id: %d" % (operation_id, root_ids[i_root_id])) lock_acquired = self.lock_single_root(root_ids[i_root_id], operation_id) # Roll back locks if one root cannot be locked if not lock_acquired: for j_root_id in range(len(root_ids)): self.unlock_root(root_ids[j_root_id], operation_id) break if lock_acquired: return True, root_ids time.sleep(waittime_s) i_try += 1 print(i_try) return False, root_ids def lock_single_root(self, root_id: np.uint64, operation_id: np.uint64 ) -> bool: """ Attempts to lock the latest version of a root node :param root_id: uint64 :param operation_id: uint64 an id that is unique to the process asking to lock the root node :return: bool success """ operation_id_b = serialize_uint64(operation_id) lock_key = serialize_key("lock") new_parents_key = serialize_key("new_parents") # Build a column filter which tests if a lock was set (== lock column # exists) and if it is still valid (timestamp younger than # LOCK_EXPIRED_TIME_DELTA) and if there is no new parent (== new_parents # exists) time_cutoff = datetime.datetime.utcnow() - LOCK_EXPIRED_TIME_DELTA # Comply to resolution of BigTables TimeRange time_cutoff -= datetime.timedelta( microseconds=time_cutoff.microsecond % 1000) time_filter = TimestampRangeFilter(TimestampRange(start=time_cutoff)) # lock_key_filter = ColumnQualifierRegexFilter(lock_key) # new_parents_key_filter = ColumnQualifierRegexFilter(new_parents_key) lock_key_filter = ColumnRangeFilter( column_family_id=self.family_id, start_column=lock_key, end_column=lock_key, inclusive_start=True, inclusive_end=True) new_parents_key_filter = ColumnRangeFilter( column_family_id=self.family_id, start_column=new_parents_key, end_column=new_parents_key, inclusive_start=True, inclusive_end=True) # Combine filters together chained_filter = RowFilterChain([time_filter, lock_key_filter]) combined_filter = ConditionalRowFilter( base_filter=chained_filter, true_filter=PassAllFilter(True), false_filter=new_parents_key_filter) # Get conditional row using the chained filter root_row = self.table.row(serialize_uint64(root_id), filter_=combined_filter) # Set row lock if condition returns no results (state == False) time_stamp = datetime.datetime.utcnow() root_row.set_cell(self.family_id, lock_key, operation_id_b, state=False, timestamp=time_stamp) # The lock was acquired when set_cell returns False (state) lock_acquired = not root_row.commit() if not lock_acquired: r = self.table.read_row(serialize_uint64(root_id)) l_operation_ids = [] for cell in r.cells[self.family_id][lock_key]: l_operation_id = deserialize_uint64(cell.value) l_operation_ids.append(l_operation_id) print("Locked operation ids:", l_operation_ids) return lock_acquired def unlock_root(self, root_id: np.uint64, operation_id: np.uint64) -> bool: """ Unlocks a root This is mainly used for cases where multiple roots need to be locked and locking was not sucessful for all of them :param root_id: np.uint64 :param operation_id: uint64 an id that is unique to the process asking to lock the root node :return: bool success """ operation_id_b = serialize_uint64(operation_id) lock_key = serialize_key("lock") # Build a column filter which tests if a lock was set (== lock column # exists) and if it is still valid (timestamp younger than # LOCK_EXPIRED_TIME_DELTA) and if the given operation_id is still # the active lock holder time_cutoff = datetime.datetime.utcnow() - LOCK_EXPIRED_TIME_DELTA # Comply to resolution of BigTables TimeRange time_cutoff -= datetime.timedelta( microseconds=time_cutoff.microsecond % 1000) time_filter = TimestampRangeFilter(TimestampRange(start=time_cutoff)) # column_key_filter = ColumnQualifierRegexFilter(lock_key) # value_filter = ColumnQualifierRegexFilter(operation_id_b) column_key_filter = ColumnRangeFilter( column_family_id=self.family_id, start_column=lock_key, end_column=lock_key, inclusive_start=True, inclusive_end=True) value_filter = ValueRangeFilter( start_value=operation_id_b, end_value=operation_id_b, inclusive_start=True, inclusive_end=True) # Chain these filters together chained_filter = RowFilterChain([time_filter, column_key_filter, value_filter]) # Get conditional row using the chained filter root_row = self.table.row(serialize_uint64(root_id), filter_=chained_filter) # Delete row if conditions are met (state == True) root_row.delete_cell(self.family_id, lock_key, state=True) return root_row.commit() def check_and_renew_root_locks(self, root_ids: Iterable[np.uint64], operation_id: np.uint64) -> bool: """ Tests if the roots are locked with the provided operation_id and renews the lock to reset the time_stam This is mainly used before executing a bulk write :param root_ids: uint64 :param operation_id: uint64 an id that is unique to the process asking to lock the root node :return: bool success """ for root_id in root_ids: if not self.check_and_renew_root_lock_single(root_id, operation_id): print("check_and_renew_root_locks failed - %d" % root_id) return False return True def check_and_renew_root_lock_single(self, root_id: np.uint64, operation_id: np.uint64) -> bool: """ Tests if the root is locked with the provided operation_id and renews the lock to reset the time_stam This is mainly used before executing a bulk write :param root_id: uint64 :param operation_id: uint64 an id that is unique to the process asking to lock the root node :return: bool success """ operation_id_b = serialize_uint64(operation_id) lock_key = serialize_key("lock") new_parents_key = serialize_key("new_parents") # Build a column filter which tests if a lock was set (== lock column # exists) and if the given operation_id is still the active lock holder # and there is no new parent (== new_parents column exists). The latter # is not necessary but we include it as a backup to prevent things # from going really bad. # column_key_filter = ColumnQualifierRegexFilter(lock_key) # value_filter = ColumnQualifierRegexFilter(operation_id_b) column_key_filter = ColumnRangeFilter( column_family_id=self.family_id, start_column=lock_key, end_column=lock_key, inclusive_start=True, inclusive_end=True) value_filter = ValueRangeFilter( start_value=operation_id_b, end_value=operation_id_b, inclusive_start=True, inclusive_end=True) new_parents_key_filter = ColumnRangeFilter( column_family_id=self.family_id, start_column=new_parents_key, end_column=new_parents_key, inclusive_start=True, inclusive_end=True) # Chain these filters together chained_filter = RowFilterChain([column_key_filter, value_filter]) combined_filter = ConditionalRowFilter( base_filter=chained_filter, true_filter=new_parents_key_filter, false_filter=PassAllFilter(True)) # Get conditional row using the chained filter root_row = self.table.row(serialize_uint64(root_id), filter_=combined_filter) # Set row lock if condition returns a result (state == True) root_row.set_cell(self.family_id, lock_key, operation_id_b, state=False) # The lock was acquired when set_cell returns True (state) lock_acquired = not root_row.commit() return lock_acquired def get_latest_root_id(self, root_id: np.uint64) -> np.ndarray: """ Returns the latest root id associated with the provided root id :param root_id: uint64 :return: list of uint64s """ id_working_set = [root_id] new_parent_key = serialize_key("new_parents") latest_root_ids = [] while len(id_working_set) > 0: next_id = id_working_set[0] del(id_working_set[0]) r = self.table.read_row(serialize_uint64(next_id)) # Check if a new root id was attached to this root id if new_parent_key in r.cells[self.family_id]: id_working_set.extend( np.frombuffer( r.cells[self.family_id][new_parent_key][0].value, dtype=np.uint64)) else: latest_root_ids.append(next_id) return np.unique(latest_root_ids) def get_future_root_ids(self, root_id: np.uint64, time_stamp: Optional[datetime.datetime] = datetime.datetime.max)-> np.ndarray: """ Returns all future root ids emerging from this root This search happens in a monotic fashion. At no point are past root ids of future root ids taken into account. :param root_id: np.uint64 :param time_stamp: None or datetime restrict search to ids created before this time_stamp None=search whole future :return: array of uint64 """ if time_stamp.tzinfo is None: time_stamp = UTC.localize(time_stamp) id_history = [] next_ids = [root_id] while len(next_ids): temp_next_ids = [] for next_id in next_ids: ids, row_time_stamp = self.read_row(next_id, key="new_parents", dtype=np.uint64, get_time_stamp=True) if ids is None: r, row_time_stamp = self.read_row(next_id, key="children", dtype=np.uint64, get_time_stamp=True) if row_time_stamp is None: raise Exception("Something went wrong...") if row_time_stamp < time_stamp: if ids is not None: temp_next_ids.extend(ids) if next_id != root_id: id_history.append(next_id) next_ids = temp_next_ids return np.unique(np.array(id_history, dtype=np.uint64)) def get_past_root_ids(self, root_id: np.uint64, time_stamp: Optional[datetime.datetime] = datetime.datetime.min) -> np.ndarray: """ Returns all future root ids emerging from this root This search happens in a monotic fashion. At no point are future root ids of past root ids taken into account. :param root_id: np.uint64 :param time_stamp: None or datetime restrict search to ids created after this time_stamp None=search whole future :return: array of uint64 """ if time_stamp.tzinfo is None: time_stamp = UTC.localize(time_stamp) id_history = [] next_ids = [root_id] while len(next_ids): temp_next_ids = [] for next_id in next_ids: ids, row_time_stamp = self.read_row(next_id, key="former_parents", dtype=np.uint64, get_time_stamp=True) if ids is None: _, row_time_stamp = self.read_row(next_id, key="children", dtype=np.uint64, get_time_stamp=True) if row_time_stamp is None: raise Exception("Something went wrong...") if row_time_stamp > time_stamp: if ids is not None: temp_next_ids.extend(ids) if next_id != root_id: id_history.append(next_id) next_ids = temp_next_ids return np.unique(np.array(id_history, dtype=np.uint64)) def get_root_id_history(self, root_id: np.uint64, time_stamp_past: Optional[datetime.datetime] = datetime.datetime.min, time_stamp_future: Optional[datetime.datetime] = datetime.datetime.max ) -> np.ndarray: """ Returns all future root ids emerging from this root This search happens in a monotic fashion. At no point are future root ids of past root ids or past root ids of future root ids taken into account. :param root_id: np.uint64 :param time_stamp_past: None or datetime restrict search to ids created after this time_stamp None=search whole future :param time_stamp_future: None or datetime restrict search to ids created before this time_stamp None=search whole future :return: array of uint64 """ past_ids = self.get_past_root_ids(root_id=root_id, time_stamp=time_stamp_past) future_ids = self.get_future_root_ids(root_id=root_id, time_stamp=time_stamp_future) history_ids = np.concatenate([past_ids, np.array([root_id], dtype=np.uint64), future_ids]) return history_ids def get_subgraph(self, agglomeration_id: np.uint64, bounding_box: Optional[Sequence[Sequence[int]]] = None, bb_is_coordinate: bool = False, stop_lvl: int = 1, get_edges: bool = False, verbose: bool = True ) -> Union[Tuple[np.ndarray, np.ndarray], np.ndarray]: """ Returns all edges between supervoxels belonging to the specified agglomeration id within the defined bouning box :param agglomeration_id: int :param bounding_box: [[x_l, y_l, z_l], [x_h, y_h, z_h]] :param bb_is_coordinate: bool :param stop_lvl: int :param get_edges: bool :param verbose: bool :return: edge list """ # Helper functions for multithreading def _handle_subgraph_children_layer2_edges_thread( child_ids: Iterable[np.uint64]) -> Tuple[List[np.ndarray], List[np.float32]]: _edges = [] _affinities = [] for child_id in child_ids: this_edges, this_affinities = self.get_subgraph_chunk( child_id, time_stamp=time_stamp) _edges.extend(this_edges) _affinities.extend(this_affinities) return _edges, _affinities def _handle_subgraph_children_layer2_thread( child_ids: Iterable[np.uint64]) -> None: for child_id in child_ids: atomic_ids.extend(self.get_children(child_id)) def _handle_subgraph_children_higher_layers_thread( child_ids: Iterable[np.uint64]) -> None: for child_id in child_ids: _children = self.get_children(child_id) if bounding_box is not None: chunk_ids = self.get_chunk_ids_from_node_ids(_children) chunk_ids = np.array([self.get_chunk_coordinates(c) for c in chunk_ids]) chunk_ids = np.array(chunk_ids) bounding_box_layer = bounding_box / self.fan_out ** np.max([0, (layer - 3)]) bound_check = np.array([ np.all(chunk_ids < bounding_box_layer[1], axis=1), np.all(chunk_ids + 1 > bounding_box_layer[0], axis=1)]).T bound_check_mask = np.all(bound_check, axis=1) _children = _children[bound_check_mask] new_childs.extend(_children) # Make sure that edges are not requested if we should stop on an # intermediate level assert stop_lvl == 1 or not get_edges if get_edges: time_stamp = self.read_row(agglomeration_id, "children", get_time_stamp=True)[1] if bounding_box is not None: if bb_is_coordinate: bounding_box = np.array(bounding_box, dtype=np.float32) / self.chunk_size bounding_box[0] = np.floor(bounding_box[0]) bounding_box[1] = np.ceil(bounding_box[1]) bounding_box = bounding_box.astype(np.int) else: bounding_box = np.array(bounding_box, dtype=np.int) edges = np.array([], dtype=np.uint64).reshape(0, 2) atomic_ids = [] affinities = np.array([], dtype=np.float32) child_ids = [agglomeration_id] time_start = time.time() while len(child_ids) > 0: new_childs = [] layer = self.get_chunk_layer(child_ids[0]) if stop_lvl == layer: atomic_ids = child_ids break # Use heuristic to guess the optimal number of threads n_child_ids = len(child_ids) this_n_threads = np.min([int(n_child_ids // 20) + 1, mu.n_cpus]) if layer == 2: if get_edges: edges_and_affinities = mu.multithread_func( _handle_subgraph_children_layer2_edges_thread, np.array_split(child_ids, this_n_threads), n_threads=this_n_threads, debug=this_n_threads == 1) for edges_and_affinities_pair in edges_and_affinities: _edges, _affinities = edges_and_affinities_pair affinities = np.concatenate([affinities, _affinities]) edges = np.concatenate([edges, _edges]) else: mu.multithread_func( _handle_subgraph_children_layer2_thread, np.array_split(child_ids, this_n_threads), n_threads=this_n_threads, debug=this_n_threads == 1) else: mu.multithread_func( _handle_subgraph_children_higher_layers_thread, np.array_split(child_ids, this_n_threads), n_threads=this_n_threads, debug=this_n_threads == 1) child_ids = new_childs if verbose: print("Layer %d: %.3fms for %d children with %d threads" % (layer, (time.time() - time_start) * 1000, n_child_ids, this_n_threads)) # if len(child_ids) != len(np.unique(child_ids)): # print("N children %d - %d" % (len(child_ids), len(np.unique(child_ids)))) # # print(agglomeration_id, child_ids) # # assert len(child_ids) == len(np.unique(child_ids)) time_start = time.time() atomic_ids =
np.array(atomic_ids, np.uint64)
numpy.array
import os import cv2 import time import json import numpy as np import matplotlib.pyplot as plt from collections import OrderedDict from PIL import Image from Code.utils import extract_video_parameters, release_video, load_video, write_video, fixBorder, convert_to_gray, \ apply_mask, scale_matrix_0_to_255, geodesic_distance_2d from scipy.stats import gaussian_kde def create_scribbles(mask: np.ndarray, type: str, num_of_points: int) -> np.ndarray: if type == 'foreground': indices = np.where(mask == 255) elif type == 'background': indices = np.where(mask == 0) scribbles = np.zeros((num_of_points, 2)) chosen_indices = np.random.choice(len(indices[0]), num_of_points) scribbles[:, 0] = indices[0][chosen_indices] scribbles[:, 1] = indices[1][chosen_indices] return scribbles def kde_scipy(x, x_grid, bandwidth=0.2, **kwargs): """Kernel Density Estimation with Scipy""" kde = gaussian_kde(x, bw_method=bandwidth, **kwargs) return kde.evaluate(x_grid) def video_matting(binary_video: cv2.VideoCapture, input_video: cv2.VideoCapture, config: dict): video_params = extract_video_parameters(input_video) n_frames = video_params['n_frames'] HSV_frames = load_video(input_video, 'hsv') mask_frames = load_video(binary_video, 'gray') num_of_points = 200 foreground_values = np.zeros((num_of_points, 1)) background_values = np.zeros((num_of_points, 1)) trimap = np.zeros((n_frames, video_params['h'], video_params['w'])).astype(np.uint8) for frame_index, frame in enumerate(mask_frames): print(f"[VM] - Frame: {frame_index + 1} / {n_frames}") foreground_scribbles = create_scribbles(frame, 'foreground', num_of_points) background_scribbles = create_scribbles(frame, 'background', num_of_points) frame_v_channel = HSV_frames[frame_index][:, :, 2] frame_v_channel = cv2.equalizeHist(frame_v_channel) foreground_values = frame_v_channel[
np.uint32(foreground_scribbles[:, 0])
numpy.uint32
import pytest import numpy as np from lmdec.decomp import PowerMethod, SuccessiveBatchedPowerMethod from lmdec.array.metrics import subspace_dist from lmdec.array.matrix_ops import svd_to_trunc_svd from lmdec.decomp.utils import make_snp_array import dask.array as da def test_PowerMethod_case1(): n = 100 p = 80 array = np.random.rand(100, 80) mu = array.mean(axis=0) std = np.diag(1/array.std(axis=0)) scaled_centered_array = (array-mu).dot(std) U, S, V = np.linalg.svd(scaled_centered_array, full_matrices=False) # Ground Truth array = make_snp_array(da.array(array), mean=True, std=True, std_method='norm', mask_nan=False, dtype='float64') for k in range(1, 10): U_k, S_k, V_k = U[:, :k], S[:k], V[:k, :] PM = PowerMethod(k=k, tol=1e-9, scoring_method='rmse', max_iter=100, sub_svd_start=False, init_row_sampling_factor=1, factor=None, lmbd=0) U_k_PM, S_k_PM, V_k_PM = PM.svd(array) np.testing.assert_array_almost_equal(S_k, S_k_PM) assert V_k.shape == V_k_PM.shape == (k, p) assert U_k.shape == U_k_PM.shape == (n, k) np.testing.assert_almost_equal(subspace_dist(V_k, V_k_PM, S_k_PM), 0) np.testing.assert_almost_equal(subspace_dist(U_k, U_k_PM, S_k_PM), 0) def test_PowerMethod_case2(): array = np.random.rand(100, 100) mu = array.mean(axis=0) std = np.diag(1/array.std(axis=0)) scaled_centered_array = (array-mu).dot(std) array = make_snp_array(da.array(array), mean=True, std=True, std_method='norm', mask_nan=False, dtype='float64') U, S, V = np.linalg.svd(scaled_centered_array.dot(scaled_centered_array.T), full_matrices=False) # Ground Truth _, _, V = np.linalg.svd(scaled_centered_array.T.dot(scaled_centered_array), full_matrices=False) S = np.sqrt(S) k = 10 U_k, S_k, V_k = U[:, :k], S[:k], V[:k, :] previous_S_error = float('inf') previous_U_error = float('inf') previous_V_error = float('inf') for t in np.logspace(0, -12, 20): PM = PowerMethod(k=k, tol=t, scoring_method='q-vals', max_iter=100, factor=None, lmbd=0) U_k_PM, S_k_PM, V_k_PM = PM.svd(array) assert subspace_dist(U_k, U_k_PM, S_k) <= previous_U_error assert subspace_dist(V_k, V_k_PM, S_k) <= previous_V_error assert np.linalg.norm(S_k-S_k_PM) <= previous_S_error previous_S_error = np.linalg.norm(S_k-S_k_PM) previous_U_error = subspace_dist(U_k, U_k_PM, S_k) previous_V_error = subspace_dist(V_k, V_k_PM, S_k) assert subspace_dist(U_k, U_k_PM, S_k) <= 1e-9 assert subspace_dist(V_k, V_k_PM, S_k) <= 1e-9 assert np.linalg.norm(S_k - S_k_PM) <= 1e-12 def test_PowerMethod_subsvd_finds_eigenvectors(): N = 1000 k = 10 s_orig = np.array([1.01**i for i in range(1, N+1)]) array = da.diag(s_orig) PM = PowerMethod(tol=1e-16, factor=None, lmbd=.1, max_iter=100) U_PM, S_PM, V_PM = PM.svd(array) np.testing.assert_array_almost_equal(s_orig[-k:][::-1], S_PM, decimal=0) # Max Q-Val is 21,000 v = np.zeros_like(V_PM).compute() for j in range(k): v[j, N - k + j] = 1 np.testing.assert_almost_equal(subspace_dist(V_PM, v, S_PM), 0, decimal=5) def test_PowerMethod_subsvd_finds_eigenvectors_failure(): N = 1000 k = 10 s_orig = np.array([1.01**i for i in range(1, N+1)]) array = da.diag(s_orig) PM = PowerMethod(tol=1e-16, lmbd=0, max_iter=100) U_PM, S_PM, V_PM = PM.svd(array) with pytest.raises(AssertionError): np.testing.assert_array_almost_equal(s_orig[-k:][::-1], S_PM, decimal=0) def test_PowerMethod_all_tols_agree(): n = 100 p = 80 k = 10 array = np.random.rand(n, p) PM = PowerMethod(k=k, tol=1e-9, scoring_method='q-vals', max_iter=100, lmbd=0) U_q, S_q, V_q = PM.svd(array) PM = PowerMethod(k=k, tol=1e-4, scoring_method='rmse', max_iter=100, lmbd=0) U_r, S_r, V_r = PM.svd(array) PM = PowerMethod(k=k, tol=1e-9, scoring_method='v-subspace', max_iter=100, lmbd=0) U_v, S_v, V_v = PM.svd(array) np.testing.assert_array_almost_equal(S_q, S_r) np.testing.assert_array_almost_equal(S_q, S_v) np.testing.assert_almost_equal(subspace_dist(U_q, U_r, S_q), 0) np.testing.assert_almost_equal(subspace_dist(U_q, U_v, S_q), 0) np.testing.assert_almost_equal(subspace_dist(V_q, V_r, S_q), 0) np.testing.assert_almost_equal(subspace_dist(V_q, V_v, S_q), 0) def test_PowerMethod_factor(): n = 100 p = 80 array = np.random.rand(n, p) sym_array = array.dot(array.T) for f in ['n', 'p', None]: if f == 'n': factor = n elif f == 'p': factor = p else: factor = 1 U, S, V = np.linalg.svd(sym_array/factor, full_matrices=False) S = np.sqrt(S) k = 10 U_k, S_k, V_k = U[:, :k], S[:k], V[:k, :] array = make_snp_array(da.array(array), mean=False, std=False, std_method='norm', mask_nan=False, dtype='float64') PM = PowerMethod(k=k, tol=1e-9, scoring_method='q-vals', max_iter=100, factor=f, lmbd=0) U_k_PM, S_k_PM, V_k_PM = PM.svd(array) np.testing.assert_array_almost_equal(S_k, S_k_PM) assert U_k.shape == U_k_PM.shape == (n, k) np.testing.assert_almost_equal(subspace_dist(U_k, U_k_PM, S_k_PM), 0) def test_PowerMethod_scale_center(): array = np.random.rand(100, 70) mu = array.mean(axis=0) std = np.diag(1 / array.std(axis=0)) k = 10 for scale in [True, False]: for center in [True, False]: new_array = array if center: new_array = new_array - mu if scale: new_array = new_array.dot(std) U, S, _ = np.linalg.svd(new_array.dot(new_array.T), full_matrices=False) # Ground Truth _, _, V = np.linalg.svd(new_array.T.dot(new_array), full_matrices=False) # Ground Truth S = np.sqrt(S) U_k, S_k, V_k = U[:, :k], S[:k], V[:k, :] snp_array = make_snp_array(da.array(array), std=scale, mean=center, std_method='norm', dtype='float64') np.testing.assert_array_almost_equal(new_array, snp_array) PM = PowerMethod(k=k, tol=1e-12, scoring_method='q-vals', max_iter=100, factor=None, lmbd=0) U_q, S_q, V_q = PM.svd(snp_array) assert subspace_dist(U_k, U_q, S_k) <= 1e-8 assert subspace_dist(V_k, V_q, S_k) <= 1e-8 assert np.linalg.norm(S_k - S_q) <= 1e-9 def test_PowerMethod_multi_tol(): array = np.random.rand(100, 70) k = 10 tol_groups = [[1e-1, 1e-1, 1e-1], [1e-16, 1e-4, 1-16], [1e-6, 1e-16, 1e-16], [1e-16, 1e-16, 1e-6]] for tols in tol_groups: PM = PowerMethod(k=k, tol=tols, scoring_method=['q-vals', 'rmse', 'v-subspace'], factor=None, lmbd=0) _, _, _ = PM.svd(array) assert (min(PM.history.acc['q-vals']) <= tols[0] or min(PM.history.acc['rmse']) <= tols[1] or min(PM.history.acc['v-subspace']) <= tols[2]) fail_test_tols = [1e-6, 1e-16, 1e-16] PM = PowerMethod(k=k, tol=fail_test_tols, scoring_method=['q-vals', 'rmse', 'v-subspace'], factor=None, lmbd=0) _, _, _ = PM.svd(array) assert (min(PM.history.acc['q-vals']) <= fail_test_tols[0] and min(PM.history.acc['rmse']) >= fail_test_tols[1] and min(PM.history.acc['v-subspace']) >= fail_test_tols[2]) def test_PowerMethod_k(): with pytest.raises(ValueError): _ = PowerMethod(k=0) with pytest.raises(ValueError): _ = PowerMethod(k=-1) PM = PowerMethod(k=100) array = np.random.rand(50, 50) with pytest.raises(ValueError): _, _, _ = PM.svd(array) def test_PowerMethod_max_iter(): with pytest.raises(ValueError): _ = PowerMethod(max_iter=0) PM = PowerMethod(max_iter=1) array = np.random.rand(100, 100) _, _, _ = PM.svd(array) assert PM.num_iter == 1 assert len(PM.history.iter['S']) == 1 def test_PowerMethod_time_limit(): with pytest.raises(ValueError): _ = PowerMethod(time_limit=0) PM = PowerMethod(time_limit=10, max_iter=int(1e10), tol=1e-20) array = np.random.rand(100, 100) _, _, _ = PM.svd(array) assert 9 <= PM.time <= 11 @pytest.mark.skip('Have yet to implement stochastic power methods efficiently within dask.') def test_PowerMethod_p(): with pytest.raises(ValueError): _ = PowerMethod(p=-1) with pytest.raises(ValueError): _ = PowerMethod(p=1) def test_PowerMethod_buffer(): with pytest.raises(ValueError): _ = PowerMethod(buffer=-1) array = np.random.rand(1000, 1000) U, S, V = np.linalg.svd(array) S[0:15] = 1e3 + S[0:15] array = U.dot(np.diag(S).dot(V)) for method in ['q-vals', 'rmse', 'v-subspace']: PM1 = PowerMethod(buffer=2, max_iter=3, tol=1e-16, scoring_method=method) PM2 = PowerMethod(buffer=30, max_iter=3, tol=1e-16, scoring_method=method) _, _, _ = PM1.svd(array) _, _, _ = PM2.svd(array) if method == 'v-subspace': # V-Subspace for this convergese quickly due small size of test case assert np.abs(PM1.history.acc[method][-1] - PM2.history.acc[method][-1]) < 1e-4 else: assert PM1.history.acc[method][-1] > PM2.history.acc[method][-1] def test_PowerMethod_sub_svd_start(): array = np.random.rand(100, 100) PM1 = PowerMethod(sub_svd_start=True, tol=1e-12, lmbd=0) _, S1, _ = PM1.svd(array) PM2 = PowerMethod(sub_svd_start=False, tol=1e-12, lmbd=0) _, S2, _ = PM2.svd(array) np.testing.assert_array_almost_equal(S1, S2) def test_PowerMethod_init_row_sampling_factor(): with pytest.raises(ValueError): _ = PowerMethod(init_row_sampling_factor=0) PM1 = PowerMethod(init_row_sampling_factor=4) array = np.random.rand(100, 100) _, _, _ = PM1.svd(array) def test_PowerMethod_bad_arrays(): PM = PowerMethod() with pytest.raises(ValueError): PM.svd(np.random.rand(100)) with pytest.raises(ValueError): PM.svd(np.random.rand(100, 100, 100)) def test_PowerMethod_nan_arrays(): array = np.random.randn(100, 100) for bad_type in [float('nan')]: array[0, 0] = bad_type for start in [True, False]: PM = PowerMethod(sub_svd_start=start, max_iter=2) with pytest.raises(np.linalg.LinAlgError): _, _, _ = PM.svd(da.array(array)) clean_array = make_snp_array(da.array(array), mask_nan=True, std_method='norm', dtype='float64') _, _, _ = PM.svd(clean_array) @pytest.mark.skip def test_PowerMethod_nan_arrays_fills(): array = np.random.randint(0, 3, size=(100, 100)).astype(float) array[0, 0] = 10000 median = round(np.median(array)) mean = round(np.mean(array)) k = 10 for method in ['mean', 'median', 10]: PM = PowerMethod(factor=None, scale=False, center=False, tol=1e-16, lmbd=0) if method == 'mean': filled_value = mean elif method == 'median': filled_value = median else: filled_value = method array[0, 1] = filled_value U, S, V = np.linalg.svd(array, full_matrices=False) U_k, S_k, V_k = svd_to_trunc_svd(U, S, V, k=k) array[0, 1] = float('nan') U, S, V = PM.svd(da.array(array), mask_fill=method, mask_nan=True) assert PM.array.array[0, 1] == filled_value np.testing.assert_array_almost_equal(S, S_k) def test_PowerMethod_reset(): for start in [True, False]: PM = PowerMethod(sub_svd_start=start) _, _, _ = PM.svd(da.array(np.random.randn(100, 50))) _, _, _ = PM.svd(da.array(np.random.randn(110, 60))) @pytest.mark.skip def test_PowerMethod_transpose_array_shape(): N, P, K = 100, 200, 10 array = da.array(np.random.rand(N, P)) PM = PowerMethod(k=K) U_PM, S_PM, V_PM = PM.svd(array) assert U_PM.shape == (N, K) assert S_PM.shape == (K,) assert V_PM.shape == (K, P) U_PM, S_PM, V_PM = PM.svd(array) assert U_PM.shape == (P, K) assert S_PM.shape == (K,) assert V_PM.shape == (K, N) @pytest.mark.skip def test_PowerMethod_transpose_array(): array = da.array(np.random.rand(100, 200)) k = 10 U, S, V = da.linalg.svd(array) U_k, S_k, V_k = svd_to_trunc_svd(U, S, V, k=k) PM = PowerMethod(tol=1e-12, k=k, factor=None, scale=False, center=False, lmbd=0) U_PM, S_PM, V_PM = PM.svd(array) np.testing.assert_array_almost_equal(S_k, S_PM) np.testing.assert_almost_equal(subspace_dist(V_k, V_PM, S_PM), 0) assert U_k.shape == U_PM.shape U_PM, S_PM, V_PM = PM.svd(array, transpose=True) np.testing.assert_almost_equal(subspace_dist(U_PM.T, V_k, S_PM), 0) assert V_PM.shape != U_PM.shape @pytest.mark.skip def test_PowerMethod_persist(): N = 10000 x = da.random.random((N, N)) PM = PowerMethod(max_iter=1) _, _, _ = PM.svd(x, persist=False) _, _, _ = PM.svd(x, persist=True) for dt in ['float64', 'float32', 'int8', 'uint8', 'int64', 'uint64']: _, _, _ = PM.svd(x, persist=True, dtype=dt) def test_PowerMethod_std_method(): N = 1000 P = 100 k = 10 array = da.random.randint(0, 3, size=(N, P)) for method in ['norm', 'binom']: new_array = make_snp_array(array, std_method=method) PM = PowerMethod(k=k, scoring_method='q-vals', tol=1e-13, factor=None) U_PM, S_PM, V_PM = PM.svd(array=new_array) mean = array.mean(axis=0) if method == 'norm': std = array.std(axis=0) else: p = mean/2 std = da.sqrt(2*p*(1-p)) x = (array - mean).dot(np.diag(1/std)) U, S, V = da.linalg.svd(x) U_k, S_k, V_k = svd_to_trunc_svd(U, S, V, k=k) np.testing.assert_almost_equal(subspace_dist(U_PM, U_k, S_k), 0, decimal=3) np.testing.assert_almost_equal(subspace_dist(V_PM, V_k, S_k), 0, decimal=3) np.testing.assert_array_almost_equal(S_k, S_PM, decimal=2) @pytest.mark.xfail def test_PowerMethod_project(): N, P = 1000, 1000 k = 10 svd_array = da.random.random(size=(N, P)).persist() proj_array = da.random.random(size=(10, P)).persist() mu = da.mean(svd_array, axis=0).persist() std = da.diag(1/da.std(svd_array, axis=0)).persist() for scale in [True, False]: for center in [True, False]: svd_array1 = svd_array proj_array1 = proj_array if center: svd_array1 = svd_array1 - mu proj_array1 = proj_array1 - mu if scale: svd_array1 = svd_array1.dot(std) proj_array1 = proj_array1.dot(std) U, S, V = da.linalg.svd(svd_array1) U_k, S_k, V_k = svd_to_trunc_svd(U, S, V, k=k) PM = PowerMethod(k=k, scale=scale, center=center, factor=None, tol=1e-12) U_PM, S_PM, V_PM = PM.svd(array=svd_array) np.testing.assert_array_almost_equal(PM.project(proj_array, onto=V_k.T), proj_array1.dot(V_k.T)) def test_PowerMethod_return_history(): max_iter = 5 array = da.random.random(size=(1000, 1000)) PM = PowerMethod(scoring_method=['rmse', 'q-vals', 'v-subspace'], max_iter=max_iter, tol=[1e-16, 1e-16, 1e-16]) history = PM.svd(array, return_history=True) assert len(history.acc['q-vals']) == max_iter assert len(history.acc['rmse']) == max_iter assert len(history.acc['v-subspace']) == max_iter assert len(history.iter['U']) == 0 assert len(history.iter['S']) == max_iter assert len(history.iter['V']) == max_iter assert len(history.iter['last_value']) == 3 assert history.time['start'] < history.time['stop'] assert len(history.time['step']) == max_iter assert len(history.time['acc']) == max_iter np.testing.assert_array_almost_equal(np.array(history.time['iter']), np.array(history.time['acc']) + np.array(history.time['step']), decimal=3) def test_SSPM_case1(): N, P, k = 100000, 100, 10 array = np.zeros(shape=(N, P)) s_orig = np.linspace(1, 2, P) array[:P, :] = np.diag(np.linspace(1, 2, P)) array[N - 1, :] = 1 U, S, V = np.linalg.svd(array, full_matrices=False) U_k, S_k, V_k = svd_to_trunc_svd(U, S, V, k=k) SSPM = SuccessiveBatchedPowerMethod(k=k, sub_svd_start=True, tol=1e-12, factor=None) U_PM, S_PM, V_PM = SSPM.svd(array) np.testing.assert_almost_equal(subspace_dist(U_PM, U_k, S_k), 0) np.testing.assert_almost_equal(subspace_dist(V_PM, V_k, S_k), 0) np.testing.assert_array_almost_equal(S_k, S_PM) for sub_S in SSPM.history.iter['S'][:-1]:
np.testing.assert_array_almost_equal(s_orig[::-1][:k], sub_S)
numpy.testing.assert_array_almost_equal
# -*- coding: utf-8 -*- """ Created on Sun Feb 28 19:38:58 2016 similarity @author: liudiwei """ import numpy as np #欧几里得距离,使用1/(1+distance)归一化 def eulisSim(matA, matB): return 1.0/(1.0 +
np.linalg.norm(matA - matB)
numpy.linalg.norm
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from six.moves import zip import warnings import scipy.signal import numpy as np import utool as ut from .util_math import TAU def argsubmax(ydata, xdata=None): """ Finds a single submaximum value to subindex accuracy. If xdata is not specified, submax_x is a fractional index. Otherwise, submax_x is sub-xdata (essentially doing the index interpolation for you) Example: >>> # ENABLE_DOCTEST >>> from vtool_ibeis.histogram import * # NOQA >>> import ubelt as ub >>> ydata = [ 0, 1, 2, 1.5, 0] >>> xdata = [00, 10, 20, 30, 40] >>> result1 = argsubmax(ydata, xdata=None) >>> result2 = argsubmax(ydata, xdata=xdata) >>> result = ub.repr2([result1, result2], precision=4, nl=1, nobr=True) >>> print(result) 2.1667, 2.0208, 21.6667, 2.0208, Example: >>> from vtool_ibeis.histogram import * # NOQA >>> hist_ = np.array([0, 1, 2, 3, 4]) >>> centers = None >>> maxima_thresh=None >>> argsubmax(hist_) (4.0, 4.0) """ if len(ydata) == 0: raise IndexError('zero length array') ydata = np.asarray(ydata) xdata = None if xdata is None else np.asarray(xdata) submaxima_x, submaxima_y = argsubmaxima(ydata, centers=xdata) idx = submaxima_y.argmax() submax_y = submaxima_y[idx] submax_x = submaxima_x[idx] return submax_x, submax_y def argsubmaxima(hist, centers=None, maxima_thresh=None, _debug=False): r""" Determines approximate maxima values to subindex accuracy. Args: hist_ (ndarray): ydata, histogram frequencies centers (ndarray): xdata, histogram labels maxima_thresh (float): cutoff point for labeing a value as a maxima Returns: tuple: (submaxima_x, submaxima_y) CommandLine: python -m vtool_ibeis.histogram argsubmaxima python -m vtool_ibeis.histogram argsubmaxima --show Example: >>> # ENABLE_DOCTEST >>> from vtool_ibeis.histogram import * # NOQA >>> maxima_thresh = .8 >>> hist = np.array([6.73, 8.69, 0.00, 0.00, 34.62, 29.16, 0.00, 0.00, 6.73, 8.69]) >>> centers = np.array([-0.39, 0.39, 1.18, 1.96, 2.75, 3.53, 4.32, 5.11, 5.89, 6.68]) >>> (submaxima_x, submaxima_y) = argsubmaxima(hist, centers, maxima_thresh) >>> result = str((submaxima_x, submaxima_y)) >>> print(result) >>> # xdoctest: +REQUIRES(--show) >>> import plottool_ibeis as pt >>> pt.draw_hist_subbin_maxima(hist, centers) >>> pt.show_if_requested() (array([ 3.0318792]), array([ 37.19208239])) """ maxima_x, maxima_y, argmaxima = hist_argmaxima(hist, centers, maxima_thresh=maxima_thresh) argmaxima = np.asarray(argmaxima) if _debug: print('Argmaxima: ') print(' * maxima_x = %r' % (maxima_x)) print(' * maxima_y = %r' % (maxima_y)) print(' * argmaxima = %r' % (argmaxima)) flags = (argmaxima == 0) | (argmaxima == len(hist) - 1) argmaxima_ = argmaxima[~flags] submaxima_x_, submaxima_y_ = interpolate_submaxima(argmaxima_, hist, centers) if np.any(flags): endpts = argmaxima[flags] submaxima_x = (np.hstack([submaxima_x_, centers[endpts]]) if centers is not None else np.hstack([submaxima_x_, endpts])) submaxima_y = np.hstack([submaxima_y_, hist[endpts]]) else: submaxima_y = submaxima_y_ submaxima_x = submaxima_x_ if _debug: print('Submaxima: ') print(' * submaxima_x = %r' % (submaxima_x)) print(' * submaxima_y = %r' % (submaxima_y)) return submaxima_x, submaxima_y def argsubmin2(ydata, xdata=None): if len(ydata) == 0: raise ValueError('zero length array') ydata = np.asarray(ydata) xdata = None if xdata is None else np.asarray(xdata) submax_x, submax_y = argsubmax2(-ydata, xdata) submin_x = submax_x submin_y = -submax_y return submin_x, submin_y def argsubmax2(ydata, xdata=None): """ Finds a single submaximum value to subindex accuracy. If xdata is not specified, submax_x is a fractional index. This version always normalizes x-coordinates. Example: >>> # ENABLE_DOCTEST >>> from vtool_ibeis.histogram import * # NOQA >>> ydata = [ 0, 1, 2, 1.5, 0] >>> xdata = [00, 10, 20, 30, 40] >>> result1 = argsubmax(ydata, xdata=None) >>> result2 = argsubmax(ydata, xdata=xdata) >>> import ubelt as ub >>> result = ub.repr2([result1, result2], precision=4, nl=1, nobr=True) >>> print(result) (2.1667, 2.0208), (21.6667, 2.0208), Example: >>> from vtool_ibeis.histogram import * # NOQA >>> hist_ = np.array([0, 1, 2, 3, 4]) >>> centers = None >>> thresh_factor = None >>> argsubmax(hist_) (4.0, 4.0) """ if len(ydata) == 0: raise ValueError('zero length array') ydata = np.asarray(ydata) xdata = None if xdata is None else np.asarray(xdata) submaxima_x, submaxima_y = argsubmaxima2(ydata, xdata=xdata, normalize_x=True) idx = submaxima_y.argmax() submax_y = submaxima_y[idx] submax_x = submaxima_x[idx] return submax_x, submax_y def argsubmaxima2(ydata, xdata=None, thresh_factor=None, normalize_x=True): return argsubextrema2('max', ydata, xdata=xdata, thresh_factor=thresh_factor, normalize_x=normalize_x) def argsubminima2(ydata, xdata=None, thresh_factor=None, normalize_x=True): """ """ return argsubextrema2('min', ydata, xdata=xdata, thresh_factor=thresh_factor, normalize_x=normalize_x) def argsubextrema2(op, ydata, xdata=None, thresh_factor=None, normalize_x=True, flat=True): r""" Determines approximate maxima values to subindex accuracy. Args: ydata (ndarray): ydata, histogram frequencies xdata (ndarray): xdata, histogram labels thresh_factor (float): cutoff point for labeing a value as a maxima flat (bool): if True allows for flat extrema to be found. Returns: tuple: (submaxima_x, submaxima_y) CommandLine: python -m vtool_ibeis.histogram argsubmaxima python -m vtool_ibeis.histogram argsubmaxima --show Example: >>> # ENABLE_DOCTEST >>> from vtool_ibeis.histogram import * # NOQA >>> thresh_factor = .8 >>> ydata = np.array([6.73, 8.69, 0.00, 0.00, 34.62, 29.16, 0.00, 0.00, 6.73, 8.69]) >>> xdata = np.array([-0.39, 0.39, 1.18, 1.96, 2.75, 3.53, 4.32, 5.11, 5.89, 6.68]) >>> op = 'min' >>> (subextrema_x, subextrema_y) = argsubextrema2(op, ydata, xdata, thresh_factor) >>> result = str((subextrema_x, subextrema_y)) >>> print(result) >>> # xdoctest: +REQUIRES(--show) >>> import plottool_ibeis as pt >>> pt.draw_hist_subbin_maxima(ydata, xdata) >>> pt.show_if_requested() Doctest: >>> from vtool_ibeis.histogram import * # NOQA >>> thresh_factor = .8 >>> ydata = np.array([1, 1, 1, 2, 1, 2, 3, 2, 4, 1.1, 5, 1.2, 1.1, 1.1, 1.2, 1.1]) >>> op = 'max' >>> thresh_factor = .8 >>> (subextrema_x, subextrema_y) = argsubextrema2(op, ydata, thresh_factor=thresh_factor) >>> result = str((subextrema_x, subextrema_y)) >>> print(result) >>> # xdoctest: +REQUIRES(--show) >>> import plottool_ibeis as pt >>> pt.qtensure() >>> xdata = np.arange(len(ydata)) >>> pt.figure(fnum=1, doclf=True) >>> pt.plot(xdata, ydata) >>> pt.plot(subextrema_x, subextrema_y, 'o') >>> ut.show_if_requested() """ if op == 'max': cmp = np.greater cmp_eq = np.greater_equal extreme = np.max factor_op = np.multiply elif op == 'min': cmp = np.less cmp_eq = np.less_equal extreme = np.min factor_op = np.divide else: raise KeyError(op) # absolute extrema abs_extreme_y = extreme(ydata) if thresh_factor is None: thresh_factor = 1.0 # thresh_factor = None if thresh_factor is None: thresh_value = None flags = np.ones(len(ydata), dtype=np.bool) else: # Find relative and flat extrema thresh_value = factor_op(abs_extreme_y, thresh_factor) flags = cmp_eq(ydata, thresh_value) # Only consider non-boundary points flags[[0, -1]] = False mxs = np.where(flags)[0] # ydata[np.vstack([mxs - 1, mxs, mxs + 1])] lvals, mvals, rvals = ydata[mxs - 1], ydata[mxs], ydata[mxs + 1] is_mid_extrema = cmp_eq(mvals, lvals) & cmp_eq(mvals, rvals) is_rel_extrema = cmp(mvals, lvals) & cmp(mvals, rvals) is_flat_extrema = is_mid_extrema & ~is_rel_extrema flat_argextrema = mxs[is_flat_extrema] rel_argextrema = mxs[is_rel_extrema] # Sublocalize relative extrema if len(rel_argextrema) > 0: # rel_subextrema_x, rel_subextrema_y = _sublocalize_extrema( # ydata, xdata, rel_argextrema, cmp, normalize_x) neighbs = np.vstack((rel_argextrema - 1, rel_argextrema, rel_argextrema + 1)) y123 = ydata[neighbs] if normalize_x or xdata is None: x123 = neighbs else: x123 = xdata[neighbs] # Fit parabola around points coeff_list = [] for (x, y) in zip(x123.T, y123.T): coeff = np.polyfit(x, y, deg=2) coeff_list.append(coeff) A, B, C = np.vstack(coeff_list).T # Extreme x point is where the derivative is 0 rel_subextrema_x = -B / (2 * A) rel_subextrema_y = C - B * B / (4 * A) if xdata is not None and normalize_x: # Convert x back to data coordinates if we normalized durring polynimal # fitting. Do linear interpoloation. rel_subextrema_x = linear_interpolation(xdata, rel_subextrema_x) # Check to make sure rel_subextrema is not less extreme than the original # extrema (can be the case only if the extrema is incorrectly given) # In this case just return what the user wanted as the extrema violates = cmp(ydata[rel_argextrema], rel_subextrema_y) if np.any(violates): warnings.warn( 'rel_subextrema was less extreme than the measured extrema', RuntimeWarning) if xdata is not None: rel_subextrema_x[violates] = xdata[rel_argextrema[violates]] else: rel_subextrema_x[violates] = rel_argextrema[violates] rel_subextrema_y[violates] = ydata[rel_argextrema[violates]] else: x123 = None # for plottool_ibeis coeff_list = [] # for plottool_ibeis rel_subextrema_x, rel_subextrema_y = [], [] # Check left boundary boundary_argextrema = [] if len(ydata) > 1: if thresh_value is None or cmp_eq(ydata[0], thresh_value): if cmp_eq(ydata[0], ydata[1]): boundary_argextrema.append(0) # Check right boundary if len(ydata) > 2: if thresh_value is None or cmp_eq(ydata[0], thresh_value): if cmp_eq(ydata[-1], ydata[-2]): boundary_argextrema.append(len(ydata) - 1) # Any non-flat mid extrema can be sublocalized other_argextrema = np.hstack([boundary_argextrema, flat_argextrema]) other_argextrema = other_argextrema.astype(np.int) other_subextrema_y = ydata[other_argextrema] if xdata is None: other_subextrema_x = other_argextrema else: other_subextrema_x = xdata[other_argextrema] # Recombine and order all extremas subextrema_y = np.hstack([rel_subextrema_y, other_subextrema_y]) subextrema_x = np.hstack([rel_subextrema_x, other_subextrema_x]) sortx = subextrema_x.argsort() subextrema_x = subextrema_x[sortx] subextrema_y = subextrema_y[sortx] return subextrema_x, subextrema_y def _sublocalize_extrema(ydata, xdata, argextrema, cmp, normalize_x=True): """ Assumes argextrema are all relative and not on the boundaries """ # extrema_y = ydata[argextrema] # extrema_x = argextrema if xdata is None else xdata[argextrema] neighbs = np.vstack((argextrema - 1, argextrema, argextrema + 1)) y123 = ydata[neighbs] if normalize_x or xdata is None: x123 = neighbs else: x123 = xdata[neighbs] # Fit parabola around points coeff_list = [] for (x, y) in zip(x123.T, y123.T): coeff = np.polyfit(x, y, deg=2) coeff_list.append(coeff) A, B, C = np.vstack(coeff_list).T # Extreme x point is where the derivative is 0 subextrema_x = -B / (2 * A) subextrema_y = C - B * B / (4 * A) if xdata is not None and normalize_x: # Convert x back to data coordinates if we normalized durring polynimal # fitting. Do linear interpoloation. subextrema_x = linear_interpolation(xdata, subextrema_x) # Check to make sure subextrema is not less extreme than the original # extrema (can be the case only if the extrema is incorrectly given) # In this case just return what the user wanted as the extrema violates = cmp(ydata[argextrema], subextrema_y) if np.any(violates): warnings.warn( 'subextrema was less extreme than the measured extrema', RuntimeWarning) if xdata is not None: subextrema_x[violates] = xdata[argextrema[violates]] else: subextrema_x[violates] = argextrema[violates] subextrema_y[violates] = ydata[argextrema[violates]] return subextrema_x, subextrema_y def linear_interpolation(arr, subindices): """ Does linear interpolation to lookup subindex values Example: >>> # ENABLE_DOCTEST >>> from vtool_ibeis.histogram import * # NOQA >>> arr = np.array([0, 1, 2, 3]) >>> subindices = np.array([0, .1, 1, 1.8, 2, 2.5, 3] ) >>> subvalues = linear_interpolation(arr, subindices) >>> assert np.allclose(subindices, subvalues) >>> assert np.allclose(2.3, linear_interpolation(arr, 2.3)) """ idx1 = np.floor(subindices).astype(np.int) idx2 = np.floor(subindices + 1).astype(np.int) idx2 = np.minimum(idx2, len(arr) - 1) alpha = idx2 - subindices subvalues = arr[idx1] * (alpha) + arr[idx2] * (1 - alpha) return subvalues # subindex_take = linear_interpolation def hist_argmaxima(hist, centers=None, maxima_thresh=None): """ must take positive only values CommandLine: python -m vtool_ibeis.histogram hist_argmaxima Example: >>> # ENABLE_DOCTEST >>> from vtool_ibeis.histogram import * # NOQA >>> maxima_thresh = .8 >>> hist = np.array([ 6.73, 8.69, 0.00, 0.00, 34.62, 29.16, 0.00, 0.00, 6.73, 8.69]) >>> centers = np.array([-0.39, 0.39, 1.18, 1.96, 2.75, 3.53, 4.32, 5.11, 5.89, 6.68]) >>> maxima_x, maxima_y, argmaxima = hist_argmaxima(hist, centers) >>> result = str((maxima_x, maxima_y, argmaxima)) >>> print(result) """ # FIXME: Not handling general cases # [0] index because argrelmaxima returns a tuple argmaxima_ = scipy.signal.argrelextrema(hist, np.greater)[0] if len(argmaxima_) == 0: argmaxima_ = hist.argmax() if maxima_thresh is not None: # threshold maxima to be within a factor of the maximum maxima_y = hist[argmaxima_] isvalid = maxima_y > maxima_y.max() * maxima_thresh argmaxima = argmaxima_[isvalid] else: argmaxima = argmaxima_ maxima_y = hist[argmaxima] maxima_x = argmaxima if centers is None else centers[argmaxima] return maxima_x, maxima_y, argmaxima def hist_argmaxima2(hist, maxima_thresh=.8): """ must take positive only values Setup: >>> # ENABLE_DOCTEST >>> from vtool_ibeis.histogram import * # NOQA GridSearch: >>> hist1 = np.array([1, .9, .8, .99, .99, 1.1, .9, 1.0, 1.0]) >>> hist2 = np.array([1, .9, .8, .99, .99, 1.1, 1.0, 1.0]) >>> hist2 = np.array([1, .9, .8, .99, .99, 1.1, 1.0]) >>> hist2 = np.array([1, .9, .8, .99, .99, 1.1, 1.2]) >>> hist2 = np.array([1, 1.2]) >>> hist2 = np.array([1, 1, 1.2]) >>> hist2 = np.array([1]) >>> hist2 = np.array([]) Example: >>> # ENABLE_DOCTEST >>> maxima_thresh = .8 >>> hist = np.array([1, .9, .8, .99, .99, 1.1, .9, 1.0, 1.0]) >>> argmaxima = hist_argmaxima2(hist) >>> print(argmaxima) """ # FIXME: Not handling general cases # [0] index because argrelmaxima returns a tuple if len(hist) == 0: return
np.empty(dtype=np.int)
numpy.empty
from prunedcv import PrunedCV, PrunedGridSearchCV from sklearn.datasets import fetch_california_housing, load_wine from sklearn.linear_model import LogisticRegression from lightgbm import LGBMRegressor import numpy as np import pandas as pd import pytest def test_pruner_prun_yes(): pruner = PrunedCV(4, 0.1) for i in range(6): pruner._add_split_value_and_prun(1.0) pruner._add_split_value_and_prun(10000.0) assert pruner.prune def test_pruner_prun_no(): pruner = PrunedCV(4, 0.1) for i in range(4): pruner._add_split_value_and_prun(1.0) for i in range(3): pruner._add_split_value_and_prun(.6) assert not pruner.prune def test_pruner_prun_back(): pruner = PrunedCV(4, 0.1) for i in range(4): pruner._add_split_value_and_prun(1.0) for i in range(2): pruner._add_split_value_and_prun(10000.0) for i in range(3): pruner._add_split_value_and_prun(1.0) assert not pruner.prune def test_prun_first_run(): pruner = PrunedCV(4, 0.1) for i in range(4): pruner._add_split_value_and_prun(1.0) assert pruner.best_splits_list_ == [1.0, 1.0, 1.0, 1.0] def test_prun_first_run_check(): pruner = PrunedCV(4, 0.1) for i in range(4): pruner._add_split_value_and_prun(1.0) assert not pruner.first_run_ def test_prun_folds_int(): with pytest.raises(TypeError): pruner = PrunedCV(1.1, 0.1) pruner._add_split_value_and_prun(1) def test_prun_folds_num(): with pytest.raises(ValueError): pruner = PrunedCV(1, 0.1) pruner._add_split_value_and_prun(1) def test_prun_vals_type(): with pytest.raises(TypeError): pruner = PrunedCV(4, 0.1) pruner._add_split_value_and_prun(1) def test_prun_score_val_constant(): pruner = PrunedCV(4, 0.1) for i in range(8): pruner._add_split_value_and_prun(1.0) assert pruner.cross_val_score_value == 1.0 def test_prun_score_val_dec(): pruner = PrunedCV(4, 0.1) for i in range(7): pruner._add_split_value_and_prun(1.0) pruner._add_split_value_and_prun(.9) assert pruner.cross_val_score_value < 1.0 def test_prun_score_val_inc(): pruner = PrunedCV(4, 0.1) for i in range(7): pruner._add_split_value_and_prun(1.0) pruner._add_split_value_and_prun(1.1) assert pruner.cross_val_score_value > 1.0 def test_prun_score_val_best(): pruner = PrunedCV(4, 0.1) for i in range(7): pruner._add_split_value_and_prun(1.0) pruner._add_split_value_and_prun(1.1) assert sum(pruner.best_splits_list_) / pruner.cv == 1.0 def test_prun_pruned_cv_score(): pruner = PrunedCV(4, 0.1) for i in range(4): pruner._add_split_value_and_prun(1.0) for i in range(2): pruner._add_split_value_and_prun(2.0) assert pruner.cross_val_score_value == 2.0 def test_prun_3models(): data = fetch_california_housing() x = data['data'] y = data['target'] pruner = PrunedCV(cv=8, tolerance=.1) model1 = LGBMRegressor(max_depth=25) model2 = LGBMRegressor(max_depth=10) model3 = LGBMRegressor(max_depth=2) score1 = pruner.cross_val_score(model1, x, y, shuffle=True, random_state=42) score2 = pruner.cross_val_score(model2, x, y, shuffle=True, random_state=42) score3 = pruner.cross_val_score(model3, x, y, shuffle=True, random_state=42) assert (sum(pruner.best_splits_list_) / pruner.cv == score2) and (score2 < score1) and (score2 < score3) def test_prun_cv_x(): with pytest.raises(TypeError): pruner = PrunedCV(cv=4, tolerance=.1) model = LGBMRegressor() x = [1, 2, 3] y = np.array([1, 2, 3]) pruner.cross_val_score(model, x, y) def test_prun_cv_y(): with pytest.raises(TypeError): pruner = PrunedCV(cv=4, tolerance=.1) model = LGBMRegressor() y = [1, 2, 3] x =
np.array([1, 2, 3])
numpy.array
#!/usr/bin/python # -*- coding: <UTF-8> -*- """ Main functions for visual analytics approach. """ import json import numpy as np import os import toml from flask import Flask, render_template, request from sklearn.metrics import confusion_matrix app = Flask(__name__) @app.route("/") def main(): global userData cwd = os.getcwd() print(cwd) userData = toml.load(r"userData.toml") return render_template("visualizations.html", datasets=userData.keys()) @app.route("/dimRed", methods=["POST"]) def dimRed(): global data, userData parameters = request.get_json() dataset = parameters["dataset"] # read json file with open(userData[dataset]) as f: data = json.load(f) distances_2D, distances_orig = getDistancesToNextSample(data["projection"], data["hiddenStates"]) confusionMatrix = array_to_list(confusion_matrix(data["actualValues"], data["predictions"], labels=range(len(data["classes"])))) return {"projection": data["projection"], "actualValues": data["actualValues"], "predictions": data["predictions"], "hiddenStates": data["hiddenStates"], "modelOutputs": data["modelOutputs"], "texts": data["texts"], "classes": data["classes"], "distances": array_to_list(distances_orig / getMax(distances_orig)), "confusionMatrix": confusionMatrix, "accuracy": data["model_accuracy"]} def getDistancesToNextSample(data2D, dataOrig): allDists2D = [] allDistsOrig = [] for i in range(len(data2D)): dists2D = [] distsOrig = [] for j in range(len(data2D[i]) - 1): dist2D = distance(np.asarray(data2D[i][j]), np.asarray(data2D[i][j + 1])) distOrig = distance(np.asarray(dataOrig[i][j]), np.asarray(dataOrig[i][j + 1])) dists2D.append(dist2D) distsOrig.append(distOrig) allDists2D.append(np.asarray(dists2D)) allDistsOrig.append(np.asarray(distsOrig)) return np.asarray(allDists2D), np.asarray(allDistsOrig) def distance(a, b): return
np.linalg.norm(a - b)
numpy.linalg.norm
# Utility methods for dealing with Dataset objects from __future__ import division import decimal from six import string_types, integer_types from scipy import stats import pandas as pd import numpy as np import warnings import sys import copy import datetime from functools import wraps def parse_result_format(result_format): """This is a simple helper utility that can be used to parse a string result_format into the dict format used internally by great_expectations. It is not necessary but allows shorthand for result_format in cases where there is no need to specify a custom partial_unexpected_count.""" if isinstance(result_format, string_types): result_format = { 'result_format': result_format, 'partial_unexpected_count': 20 } else: if 'partial_unexpected_count' not in result_format: result_format['partial_unexpected_count'] = 20 return result_format class DotDict(dict): """dot.notation access to dictionary attributes""" def __getattr__(self, attr): return self.get(attr) __setattr__= dict.__setitem__ __delattr__= dict.__delitem__ def __dir__(self): return self.keys() #Cargo-cultishly copied from: https://github.com/spindlelabs/pyes/commit/d2076b385c38d6d00cebfe0df7b0d1ba8df934bc def __deepcopy__(self, memo): return DotDict([(copy.deepcopy(k, memo), copy.deepcopy(v, memo)) for k, v in self.items()]) """Docstring inheriting descriptor. Note that this is not a docstring so that this is not added to @DocInherit-\ decorated functions' hybrid docstrings. Usage:: class Foo(object): def foo(self): "Frobber" pass class Bar(Foo): @DocInherit def foo(self): pass Now, Bar.foo.__doc__ == Bar().foo.__doc__ == Foo.foo.__doc__ == "Frobber" Original implementation cribbed from: https://stackoverflow.com/questions/2025562/inherit-docstrings-in-python-class-inheritance, following a discussion on comp.lang.python that resulted in: http://code.activestate.com/recipes/576862/. Unfortunately, the original authors did not anticipate deep inheritance hierarchies, and we ran into a recursion issue when implementing custom subclasses of PandasDataset: https://github.com/great-expectations/great_expectations/issues/177. Our new homegrown implementation directly searches the MRO, instead of relying on super, and concatenates documentation together. """ class DocInherit(object): def __init__(self, mthd): self.mthd = mthd self.name = mthd.__name__ self.mthd_doc = mthd.__doc__ def __get__(self, obj, cls): doc = self.mthd_doc if self.mthd_doc is not None else '' for parent in cls.mro(): if self.name not in parent.__dict__: continue if parent.__dict__[self.name].__doc__ is not None: doc = doc + '\n' + parent.__dict__[self.name].__doc__ @wraps(self.mthd, assigned=('__name__', '__module__')) def f(*args, **kwargs): return self.mthd(obj, *args, **kwargs) f.__doc__ = doc return f def recursively_convert_to_json_serializable(test_obj): """ Helper function to convert a dict object to one that is serializable Args: test_obj: an object to attempt to convert a corresponding json-serializable object Returns: (dict) A converted test_object Warning: test_obj may also be converted in place. """ # Validate that all aruguments are of approved types, coerce if it's easy, else exception # print(type(test_obj), test_obj) #Note: Not 100% sure I've resolved this correctly... try: if not isinstance(test_obj, list) and np.isnan(test_obj): # np.isnan is functionally vectorized, but we only want to apply this to single objects # Hence, why we test for `not isinstance(list))` return None except TypeError: pass except ValueError: pass if isinstance(test_obj, (string_types, integer_types, float, bool)): # No problem to encode json return test_obj elif isinstance(test_obj, dict): new_dict = {} for key in test_obj: new_dict[key] = recursively_convert_to_json_serializable(test_obj[key]) return new_dict elif isinstance(test_obj, (list, tuple, set)): new_list = [] for val in test_obj: new_list.append(recursively_convert_to_json_serializable(val)) return new_list elif isinstance(test_obj, (np.ndarray, pd.Index)): #test_obj[key] = test_obj[key].tolist() ## If we have an array or index, convert it first to a list--causing coercion to float--and then round ## to the number of digits for which the string representation will equal the float representation return [recursively_convert_to_json_serializable(x) for x in test_obj.tolist()] #Note: This clause has to come after checking for np.ndarray or we get: # `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()` elif test_obj == None: # No problem to encode json return test_obj elif isinstance(test_obj, (datetime.datetime, datetime.date)): return str(test_obj) # Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html # https://github.com/numpy/numpy/pull/9505 elif np.issubdtype(type(test_obj), np.bool_): return bool(test_obj) elif np.issubdtype(type(test_obj), np.integer) or np.issubdtype(type(test_obj), np.uint): return int(test_obj) elif np.issubdtype(type(test_obj), np.floating): # Note: Use np.floating to avoid FutureWarning from numpy return float(round(test_obj, sys.float_info.dig)) # elif np.issubdtype(type(test_obj), np.complexfloating): # Note: Use np.complexfloating to avoid Future Warning from numpy # Complex numbers consist of two floating point numbers # return complex( # float(round(test_obj.real, sys.float_info.dig)), # float(round(test_obj.imag, sys.float_info.dig))) elif isinstance(test_obj, decimal.Decimal): return float(test_obj) else: raise TypeError('%s is of type %s which cannot be serialized.' % (str(test_obj), type(test_obj).__name__)) def is_valid_partition_object(partition_object): """Tests whether a given object is a valid continuous or categorical partition object. :param partition_object: The partition_object to evaluate :return: Boolean """ if is_valid_continuous_partition_object(partition_object) or is_valid_categorical_partition_object(partition_object): return True return False def is_valid_categorical_partition_object(partition_object): """Tests whether a given object is a valid categorical partition object. :param partition_object: The partition_object to evaluate :return: Boolean """ if partition_object is None or ("weights" not in partition_object) or ("values" not in partition_object): return False # Expect the same number of values as weights; weights should sum to one if len(partition_object['values']) == len(partition_object['weights']) and \ np.allclose(np.sum(partition_object['weights']), 1): return True return False def is_valid_continuous_partition_object(partition_object): """Tests whether a given object is a valid continuous partition object. :param partition_object: The partition_object to evaluate :return: Boolean """ if (partition_object is None) or ("weights" not in partition_object) or ("bins" not in partition_object): return False if("tail_weights" in partition_object): if (len(partition_object["tail_weights"])!=2): return False comb_weights=partition_object["tail_weights"]+partition_object["weights"] else: comb_weights=partition_object["weights"] # Expect one more bin edge than weight; all bin edges should be monotonically increasing; weights should sum to one if (len(partition_object['bins']) == (len(partition_object['weights']) + 1)) and \ np.all(np.diff(partition_object['bins']) > 0) and \ np.allclose(
np.sum(comb_weights)
numpy.sum
from copy import deepcopy from scripts.fileReadWriteOperations import * from scripts.runCommand import * import multiprocessing import pickle import pprint import sys import numpy as np import pandas as pd def divide_chunks( l, n ): # looping till length l for i in range( 0, len( l ), n ): yield l[i:i + n] def removeSpuriousExonsAndTranscripts( whole_annotation ): remove_these_transcripts = [] for transcript_id in whole_annotation: # Remove transcripts that are less than 50 nucleotides long if whole_annotation[transcript_id]["transcript_end"] - whole_annotation[transcript_id]["transcript_start"] + 1 < 50: remove_these_transcripts.append( transcript_id ) return whole_annotation def createNewTranscripts( combined_list_of_exons_and_breakpoints, transcript_id ): """ """ # Merge consequent cut-points combined_list_of_exons_and_breakpoints_new = [] while True: i = 0 while i < len( combined_list_of_exons_and_breakpoints ): if i + 1 < len( combined_list_of_exons_and_breakpoints ) and combined_list_of_exons_and_breakpoints[i][-1] == 'c' and combined_list_of_exons_and_breakpoints[i + 1][-1] == 'c': combined_list_of_exons_and_breakpoints_new.append( [combined_list_of_exons_and_breakpoints[i][0], combined_list_of_exons_and_breakpoints[i + 1][1], 'c'] ) i += 1 else: combined_list_of_exons_and_breakpoints_new.append( combined_list_of_exons_and_breakpoints[i] ) i += 1 """print(transcript_id,len(combined_list_of_exons_and_breakpoints),len(combined_list_of_exons_and_breakpoints_new)) sys.stdout.flush()""" combined_list_of_exons_and_breakpoints = combined_list_of_exons_and_breakpoints_new i = 0 flag = 0 while i < len( combined_list_of_exons_and_breakpoints ) - 1: if combined_list_of_exons_and_breakpoints[i][-1] == 'c' and combined_list_of_exons_and_breakpoints[i + 1][-1] == 'c': flag = 1 break i += 1 if flag == 0: break combined_list_of_exons_and_breakpoints_new = [] # Remove cut points that span both introns and exons combined_list_of_exons_and_breakpoints_new = [] combined_list_of_exons_and_breakpoints_new.append( combined_list_of_exons_and_breakpoints[0] ) i = 0 while i < len( combined_list_of_exons_and_breakpoints ): if combined_list_of_exons_and_breakpoints[i][-1] == 'c': exon1_start, exon1_end = combined_list_of_exons_and_breakpoints[i - 1][:2] cutpoint_start, cutpoint_end = combined_list_of_exons_and_breakpoints[i][:2] if exon1_start <= cutpoint_start and cutpoint_end <= exon1_end: combined_list_of_exons_and_breakpoints_new.append( combined_list_of_exons_and_breakpoints[i] ) else: pass else: combined_list_of_exons_and_breakpoints_new.append( combined_list_of_exons_and_breakpoints[i] ) i += 1 combined_list_of_exons_and_breakpoints = combined_list_of_exons_and_breakpoints_new # Remove those cases where cut points fall at extreme edges (within 5 nucl) of exon boundaries combined_list_of_exons_and_breakpoints_new = [] i = 0 while i < len( combined_list_of_exons_and_breakpoints ): if combined_list_of_exons_and_breakpoints[i][-1] == 'c': if i - 1 >= 0 and i + 1 < len( combined_list_of_exons_and_breakpoints ) - 1: prev_exon = combined_list_of_exons_and_breakpoints[i - 1][:2] next_exon = combined_list_of_exons_and_breakpoints[i + 1][:2] cut_point_start, cut_point_end = combined_list_of_exons_and_breakpoints[i][:2] if abs( cut_point_start - prev_exon[0] ) <= 5 or abs( cut_point_end - next_exon[1] ) <= 5 or abs( cut_point_start - next_exon[0] ) <= 5 or abs( cut_point_end - prev_exon[1] ) <= 5: pass else: combined_list_of_exons_and_breakpoints_new.append( combined_list_of_exons_and_breakpoints[i] ) elif i == 0: next_exon = combined_list_of_exons_and_breakpoints[i + 1][:2] cut_point_start, cut_point_end = combined_list_of_exons_and_breakpoints[i][:2] if abs( cut_point_end - next_exon[1] ) <= 5 or abs( cut_point_start - next_exon[0] ) <= 5: pass else: combined_list_of_exons_and_breakpoints_new.append( combined_list_of_exons_and_breakpoints[i] ) elif i == len( combined_list_of_exons_and_breakpoints ) - 1: prev_exon = combined_list_of_exons_and_breakpoints[i - 1][:2] cut_point_start, cut_point_end = combined_list_of_exons_and_breakpoints[i][:2] if abs( cut_point_start - prev_exon[0] ) <= 5 or abs( cut_point_end - prev_exon[1] ) <= 5: pass else: combined_list_of_exons_and_breakpoints_new.append( combined_list_of_exons_and_breakpoints[i] ) else: combined_list_of_exons_and_breakpoints_new.append( combined_list_of_exons_and_breakpoints[i] ) i += 1 # combined_list_of_exons_and_breakpoints_new.append( combined_list_of_exons_and_breakpoints[-1]) """print("Prev_length",len(combined_list_of_exons_and_breakpoints)) print("Next_length",len(combined_list_of_exons_and_breakpoints_new))""" combined_list_of_exons_and_breakpoints = combined_list_of_exons_and_breakpoints_new if len( combined_list_of_exons_and_breakpoints ) >= 2: combined_list_of_exons_and_breakpoints_new = [] if combined_list_of_exons_and_breakpoints[-1][2] == 'c' and combined_list_of_exons_and_breakpoints[-2][1] == combined_list_of_exons_and_breakpoints[-1][1]: combined_list_of_exons_and_breakpoints_new = combined_list_of_exons_and_breakpoints[:-1] combined_list_of_exons_and_breakpoints = combined_list_of_exons_and_breakpoints_new subtract_this_value = combined_list_of_exons_and_breakpoints[0][0] combined_list_of_exons_and_breakpoints_new = [] for row in combined_list_of_exons_and_breakpoints: combined_list_of_exons_and_breakpoints_new.append( [row[0] - subtract_this_value, row[1] - subtract_this_value, row[2]] ) combined_list_of_exons_and_breakpoints = combined_list_of_exons_and_breakpoints_new list_of_exon_definitons_of_transcripts = [] current_transcript_exon_definition = [] exon_num = 0 while exon_num < len( combined_list_of_exons_and_breakpoints ): flag = 0 exon = combined_list_of_exons_and_breakpoints[exon_num] if exon[2] == 'e' and exon_num + 1 < len( combined_list_of_exons_and_breakpoints ) and combined_list_of_exons_and_breakpoints[exon_num + 1][2] == 'e': current_transcript_exon_definition.append( [exon[0], exon[1]] ) elif exon[2] == 'e' and exon_num + 1 < len( combined_list_of_exons_and_breakpoints ) and combined_list_of_exons_and_breakpoints[exon_num + 1][2] == 'c': # Check if the cutpoint is overlapping with intron cutpoint = combined_list_of_exons_and_breakpoints[exon_num + 1] exon1 = exon try: exon2 = combined_list_of_exons_and_breakpoints[exon_num + 2] except IndexError: # print(transcript_id) # pprint.pprint(combined_list_of_exons_and_breakpoints) # sys.exit() flag = 1 if flag == 0 and exon1[1] <= cutpoint[0] and cutpoint[1] <= exon2[0]: current_transcript_exon_definition.append( [exon[0], exon[1]] ) current_transcript_exon_definition_cp = deepcopy( current_transcript_exon_definition ) list_of_exon_definitons_of_transcripts.append( current_transcript_exon_definition_cp ) current_transcript_exon_definition = [[exon2[0], exon2[1]]] else: current_transcript_exon_definition.append( [exon[0], combined_list_of_exons_and_breakpoints[exon_num + 1][0] - 1] ) current_transcript_exon_definition_cp = deepcopy( current_transcript_exon_definition ) list_of_exon_definitons_of_transcripts.append( current_transcript_exon_definition_cp ) current_transcript_exon_definition = [[combined_list_of_exons_and_breakpoints[exon_num + 1][1] + 1, exon[1]]] exon_num += 1 elif exon[2] == 'e' and exon_num == len( combined_list_of_exons_and_breakpoints ) - 1: current_transcript_exon_definition.append( [exon[0], exon[1]] ) exon_num += 1 # current_transcript_exon_definition.append(current_transcript_exon_definition) list_of_exon_definitons_of_transcripts.append( current_transcript_exon_definition ) # print(transcript_id) """if transcript_id=="1.7600.0" or transcript_id=="3.41089.0" or transcript_id=="3.41089.1" or transcript_id=="3.46058.0" or transcript_id=="4.47251.1" or transcript_id=="4.47251.2" or transcript_id=="5.71927.0" or transcript_id=="5.71927.1": print(transcript_id) pprint.pprint(combined_list_of_exons_and_breakpoints) for each_transcript_exon_definition in list_of_exon_definitons_of_transcripts: pprint.pprint(each_transcript_exon_definition) print("-"*150) print("="*150)""" list_of_exon_definitons_of_transcripts_new = [] for each_transcript_exon_definition in list_of_exon_definitons_of_transcripts: each_transcript_exon_definition_new = [] for row in each_transcript_exon_definition: each_transcript_exon_definition_new.append( [row[0] + subtract_this_value, row[1] + subtract_this_value] ) list_of_exon_definitons_of_transcripts_new.append( each_transcript_exon_definition_new ) list_of_exon_definitons_of_transcripts = list_of_exon_definitons_of_transcripts_new return list_of_exon_definitons_of_transcripts def removeOverlappingExonsFromEachTranscript( transcript_info ): """ Scans each transcript and removes those exons that are subsets of other exons """ for transcript_id in transcript_info: remove_these_exons = [] i = 0 while i < len( transcript_info[transcript_id]["exons"] ): j = i + 1 exon_i = transcript_info[transcript_id]["exons"][i] while j < len( transcript_info[transcript_id]["exons"] ): exon_j = transcript_info[transcript_id]["exons"][j] if exon_i[0] == exon_j[0] and exon_i[1] == exon_j[1]: remove_these_exons.append( i ) # Check if ith exon is contained in jth exon elif exon_j[0] <= exon_i[0] and exon_i[1] <= exon_j[1]: remove_these_exons.append( i ) # Check if jth exon is contained in ith exon elif exon_i[0] <= exon_j[0] and exon_j[1] <= exon_i[1]: remove_these_exons.append( j ) j += 1 i += 1 remove_these_exons = list( set( remove_these_exons ) )[::-1] """if transcript_id in ["1.15397_0_covsplit.0 ","1.17646_0_covsplit.0","1.19072_0_covsplit.0","4.50055_0_covsplit.0","5.68350_0_covsplit.0","5.68602_0_covsplit.0","5.69132_0_covsplit.0","5.71535_0_covsplit.0"]: print(transcript_id,len(transcript_info[transcript_id]["exons"]),len(transcript_info[transcript_id]["exons"])-len(remove_these_exons)) print(transcript_info[transcript_id]["exons"]) print("="*150)""" for r in remove_these_exons: transcript_info[transcript_id]["exons"].pop( r ) return transcript_info def fixOverlappingAndMergedTranscripts( options, logger_proxy, logging_mutex ): ######################################################################################################### # Read in all the exons that overlap with some intron ######################################################################################################### # Selecting the first Run from the first condition gtffilename = options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/combined_transcripts_connecting_two_transcripts.gtf" output_gtf_filename = options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/combined_cov_opp_split.gtf" if options.skip_cpd == True: os.system( f"mv {gtffilename} {output_gtf_filename}" ) return if os.path.exists( output_gtf_filename ) == True:return exons_overlapping_with_introns_bedfilename = gtffilename[:-4] + "_exons_overlapping_with_introns.bed" overlaps = {} cmd = "bedtools getfasta -s -fi " + options.genome + " -bed <(cat " + gtffilename + "|awk '$3==\"exon\"') > " cmd += options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/sequence_per_exon.fasta" runCommand( ["dummy", cmd] ) donot_split_these_exons = {} sequence_per_exon = readFastaFile( options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/sequence_per_exon.fasta" ) for id in sequence_per_exon: if len( sequence_per_exon[id] ) % 3 == 0: frame_0 = translate( sequence_per_exon[id] ) elif len( sequence_per_exon[id] ) % 3 == 1: frame_0 = translate( sequence_per_exon[id][:-1] ) elif len( sequence_per_exon[id] ) % 3 == 2: frame_0 = translate( sequence_per_exon[id][:-2] ) if len( sequence_per_exon[id][1:] ) % 3 == 0: frame_1 = translate( sequence_per_exon[id][1:] ) elif len( sequence_per_exon[id][1:] ) % 3 == 1: frame_1 = translate( sequence_per_exon[id][1:-1] ) elif len( sequence_per_exon[id][1:] ) % 3 == 2: frame_1 = translate( sequence_per_exon[id][1:-2] ) if len( sequence_per_exon[id][2:] ) % 3 == 0: frame_2 = translate( sequence_per_exon[id][2:] ) elif len( sequence_per_exon[id][2:] ) % 3 == 1: frame_2 = translate( sequence_per_exon[id][2:-1] ) elif len( sequence_per_exon[id][2:] ) % 3 == 2: frame_2 = translate( sequence_per_exon[id][2:-2] ) skip = 0 if abs( len( sequence_per_exon[id] ) / 3 - len( frame_0 ) ) <= 1: skip = 1 if abs( len( sequence_per_exon[id] ) / 3 - len( frame_1 ) ) <= 1: skip = 1 if abs( len( sequence_per_exon[id] ) / 3 - len( frame_2 ) ) <= 1: skip = 1 if skip == 1: chromosome = id.strip()[:-3].split( ":" )[0] start = str( int( id.strip()[:-3].split( ":" )[-1].split( "-" )[0] ) + 1 ) end = id.strip()[:-3].split( ":" )[-1].split( "-" )[-1] if chromosome not in donot_split_these_exons: donot_split_these_exons = [] donot_split_these_exons.append( start + "-" + end ) # if len(frame_0) # print(len(sequence_per_exon[id])/3,len(frame_0),len(frame_1),len(frame_2)) """for chromosome in donot_split_these_exons: print(chromosome,len(donot_split_these_exons)) pprint.pprint(donot_split_these_exons) return""" fhr = open( exons_overlapping_with_introns_bedfilename, "r" ) for line in fhr: chromosome, start, end = line.strip().split()[:3] if chromosome not in overlaps: overlaps = [] overlaps.append( str( int( start ) + 1 ) + "-" + end ) for chromosome in overlaps: overlaps = set( overlaps ) ######################################################################################################### # Read all the transcript info ######################################################################################################### complete_transcript_info = readAllTranscriptsFromGTFFileInParallel( [options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/combined_transcripts_connecting_two_transcripts.gtf", "dummy", "dummy"] )[0] exons_to_transcripts = {} for transcript_id in complete_transcript_info: chromosome = complete_transcript_info[transcript_id]["chromosome"] if chromosome not in exons_to_transcripts: exons_to_transcripts[chromosome] = {} for exon in complete_transcript_info[transcript_id]["exons"]: exon_str = str( exon[0] ) + "-" + str( exon[1] ) if exon_str not in exons_to_transcripts[chromosome]: exons_to_transcripts[chromosome][exon_str] = [] if transcript_id not in exons_to_transcripts[chromosome][exon_str]: exons_to_transcripts[chromosome][exon_str].append( transcript_id ) combined_transcript_info = deepcopy( complete_transcript_info ) ######################################################################################################### # Create file for Change Points Detection computation for each condition and each exon ######################################################################################################### # File content and structure # # Comma separated list # Each entry on newline # Field 1 - "cov" or "opp" Indicating whether the exon should be treated for a coverage split or overlapping case # Field 2 - condition # Field 3 - Chromosome # Field 4 - Exon start # Field 5 - Exon end # Field 6 - Either 2 or 3 Denotes the number of break points # Field 7 onwards - Coverage for each nucleotide for each run inputfile_for_CPD = options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/" + "inputfileforCPD" outputfile_for_CPD = options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/" + "outputfileforCPD" # Create exon_coverage field for transcript_id in complete_transcript_info: complete_transcript_info[transcript_id]["exon_coverage"] = [] # Populate the exon_coverage for each condition exons_processed_for_opp_overlapping_transcripts_all_conditions = {} exons_processed_for_cov_transcripts_all_conditions = {} fhw = open( inputfile_for_CPD, "w" ) for condition in options.mrna_md: combined_transcript_info = deepcopy( complete_transcript_info ) for Run in options.mrna_md[condition]: with logging_mutex: logger_proxy.info( "Processing inside fixOverlappingAndMergedTranscripts " + condition + " " + Run ) coverage_info, skip = pickle.load( open( options.output_star + "/" + Run + "_counts_all_info.pkl", "rb" ) ) for transcript_id in coverage_info: chromosome = transcript_id.split( "." )[0] temp = [] for exon_coverage in coverage_info[transcript_id]["bed_cov"]: temp.append( np.array( exon_coverage ) ) coverage_info[transcript_id]["bed_cov"] = np.array( temp ) # if transcript_id not in complete_transcript_info:continue if len( complete_transcript_info[transcript_id]["exon_coverage"] ) == 0: # print("cov",coverage_info[transcript_id]["bed_cov"]) complete_transcript_info[transcript_id]["exon_coverage"] = np.array( coverage_info[transcript_id]["bed_cov"] ) else: complete_transcript_info[transcript_id]["exon_coverage"] = np.add( complete_transcript_info[transcript_id]["exon_coverage"], np.array( coverage_info[transcript_id]["bed_cov"] ) ) if len( combined_transcript_info[transcript_id]["exon_coverage"] ) == 0: combined_transcript_info[transcript_id]["exon_coverage"] = np.array( coverage_info[transcript_id]["bed_cov"] ) else: combined_transcript_info[transcript_id]["exon_coverage"] = np.add( combined_transcript_info[transcript_id]["exon_coverage"], np.array( coverage_info[transcript_id]["bed_cov"] ) ) # Coverage patterns for each condition ######################################################################################################### # Same exon shared by transcripts in opposite direction ######################################################################################################### exons_processed_for_opp_overlapping_transcripts = {} for chromosome in exons_to_transcripts: exons_processed = [] for exon in exons_to_transcripts[chromosome]: if len( exons_to_transcripts[chromosome][exon] ) == 1:continue list_to_be_written_to_file = [] for i in range( len( exons_to_transcripts[chromosome][exon] ) ): transcript_id_i = exons_to_transcripts[chromosome][exon][i] j = i + 1 while j < len( exons_to_transcripts[chromosome][exon] ): transcript_id_j = exons_to_transcripts[chromosome][exon][j] if "+" in ( complete_transcript_info[transcript_id_i]["direction"], complete_transcript_info[transcript_id_j]["direction"] ) and "-" in ( complete_transcript_info[transcript_id_i]["direction"], complete_transcript_info[transcript_id_j]["direction"] ): exon_num = 0 if str( complete_transcript_info[transcript_id_i]["exons"][0][0] ) + "-" + str( complete_transcript_info[transcript_id_i]["exons"][0][1] ) == exon else -1 # print(exon_num,complete_transcript_info[transcript_id_i]["exon_coverage"]) if len( complete_transcript_info[transcript_id_i]["exon_coverage"] ) == 0: # print(condition,Run,transcript_id_i,'exon_coverage') j += 1 continue exon_coverage = complete_transcript_info[transcript_id_i]["exon_coverage"][exon_num] list_to_be_written_to_file = ["opp", condition, chromosome, exon.split( "-" )[0], exon.split( "-" )[1], "ext"] list_to_be_written_to_file.append( "2" + ";" + ";".join( list( map( str, exon_coverage ) ) ) ) fhw.write( ",".join( list_to_be_written_to_file ) + "\n" ) if chromosome not in exons_processed_for_opp_overlapping_transcripts: exons_processed_for_opp_overlapping_transcripts = [] if chromosome not in exons_processed_for_opp_overlapping_transcripts_all_conditions: exons_processed_for_opp_overlapping_transcripts_all_conditions = [] exons_processed_for_opp_overlapping_transcripts.append( exon ) exons_processed_for_opp_overlapping_transcripts_all_conditions.append( exon ) j += 1 if len( list_to_be_written_to_file ) > 0: break if len( list_to_be_written_to_file ) > 0: break for chromosome in exons_processed_for_opp_overlapping_transcripts: exons_processed_for_opp_overlapping_transcripts = set( exons_processed_for_opp_overlapping_transcripts ) threshold = 5 * len( options.mrna_md[condition] ) max_threshold = 20 * len( options.mrna_md[condition] ) exons_processed = [] for transcript_id in complete_transcript_info: # Skip mono exonic transcripts if len( complete_transcript_info[transcript_id]["exons"] ) == 1:continue for exon_num, exon in enumerate( complete_transcript_info[transcript_id]["exons"] ): # Skip exons that have complete ORFs in them # exon=str(exon[0])+"-"+str(exon[1]) if chromosome in donot_split_these_exons and str( exon[0] ) + "-" + str( exon[1] ) in donot_split_these_exons: # print(chromosome+":"+str(exon[0])+"-"+str(exon[1])) continue if chromosome in exons_processed_for_opp_overlapping_transcripts and str( exon[0] ) + "-" + str( exon[1] ) in exons_processed_for_opp_overlapping_transcripts:continue if str( exon[0] ) + "-" + str( exon[1] ) not in exons_processed: exons_processed.append( str( exon[0] ) + "-" + str( exon[1] ) ) else: continue # Skip exons that overlap with introns since coverage will dip anyways if chromosome in overlaps and str( exon[0] ) + "-" + str( exon[1] ) in overlaps:continue external_exon = ( 1 if ( exon_num == 0 or exon_num == len( complete_transcript_info[transcript_id]["exons"] ) - 1 ) else 0 ) try: exon_coverage = complete_transcript_info[transcript_id]["exon_coverage"][exon_num] except IndexError: print( transcript_id, len( complete_transcript_info[transcript_id]["exons"] ), len( complete_transcript_info[transcript_id]["exon_coverage"] ) ) sys.exit() if external_exon == 0: min_coverage = min( exon_coverage ) max_coverage = max( exon_coverage ) else: # Skip the external exon if its less than 100 if len( exon_coverage ) < 100:continue if exon_num == 0: # First Exon # start_from=100 if len(exon_coverage)>100 else int(0.1*len(exon_coverage)) min_coverage = min( exon_coverage ) max_coverage = max( exon_coverage ) else: # Last Exon # end_at=100 if len(exon_coverage)>100 else int(0.1*len(exon_coverage)) min_coverage = min( exon_coverage ) max_coverage = max( exon_coverage ) std_dev = np.std( exon_coverage ) if min_coverage < threshold and std_dev >= 5 and len( exon_coverage ) >= 50: list_to_be_written_to_file = ["cov", condition, str( chromosome ), str( exon[0] ), str( exon[1] ), ( "ext" if external_exon == 1 else "int" )] # list_to_be_written_to_file.extend(list(map(str,exon_coverage))) list_to_be_written_to_file.append( ( "3" if external_exon == 1 else "2" ) + ";" + ";".join( list( map( str, exon_coverage ) ) ) ) # all_lines_to_be_written["cov"][str(chromosome)+":"+str(exon[0])+"-"+str(exon[1])]=list_to_be_written_to_file fhw.write( ",".join( list_to_be_written_to_file ) + "\n" ) if chromosome not in exons_processed_for_cov_transcripts_all_conditions: exons_processed_for_cov_transcripts_all_conditions = [] exons_processed_for_cov_transcripts_all_conditions.append( str( exon[0] ) + "-" + str( exon[1] ) ) # Clearing out complete_transcript_info for next run for transcript_id in complete_transcript_info: complete_transcript_info[transcript_id]["exon_coverage"] = [] for chromosome in exons_processed_for_opp_overlapping_transcripts_all_conditions: exons_processed_for_opp_overlapping_transcripts_all_conditions = set( exons_processed_for_opp_overlapping_transcripts_all_conditions ) for chromosome in exons_processed_for_cov_transcripts_all_conditions: exons_processed_for_cov_transcripts_all_conditions = set( exons_processed_for_cov_transcripts_all_conditions ) # Coverage patterns for all conditions combined exons_in_opp = [] exons_in_cov = [] with logging_mutex: logger_proxy.info( "Processing inside fixOverlappingAndMergedTranscripts all conditions and runs combined" ) for transcript_id in combined_transcript_info: chromosome = combined_transcript_info[transcript_id]["chromosome"] for exon_num, exon in enumerate( combined_transcript_info[transcript_id]["exons"] ): exon_str = str( exon[0] ) + "-" + str( exon[1] ) if chromosome in exons_processed_for_opp_overlapping_transcripts_all_conditions and exon_str in exons_processed_for_opp_overlapping_transcripts_all_conditions[chromosome]: if exon_str not in exons_in_opp: exons_in_opp.append( exon_str ) else: continue exon_coverage = combined_transcript_info[transcript_id]["exon_coverage"][exon_num] list_to_be_written_to_file = ["opp", "combined", chromosome, exon_str.split( "-" )[0], exon_str.split( "-" )[1], "ext"] list_to_be_written_to_file.append( "2" + ";" + ";".join( list( map( str, exon_coverage ) ) ) ) fhw.write( ",".join( list_to_be_written_to_file ) + "\n" ) if chromosome in exons_processed_for_cov_transcripts_all_conditions and exon_str in exons_processed_for_cov_transcripts_all_conditions: if exon_str not in exons_in_cov: exons_in_cov.append( exon_str ) else: continue if exon_str in exons_in_opp: print( chromosome, exon, "found in opp" ) sys.stdout.flush() continue external_exon = ( 1 if ( exon_num == 0 or exon_num == len( combined_transcript_info[transcript_id]["exons"] ) - 1 ) else 0 ) exon_coverage = combined_transcript_info[transcript_id]["exon_coverage"][exon_num] list_to_be_written_to_file = ["cov", "combined", str( chromosome ), str( exon[0] ), str( exon[1] ), ( "ext" if external_exon == 1 else "int" )] # list_to_be_written_to_file.extend(list(map(str,exon_coverage))) list_to_be_written_to_file.append( ( "3" if external_exon == 1 else "2" ) + ";" + ";".join( list( map( str, exon_coverage ) ) ) ) # all_lines_to_be_written["cov"][str(chromosome)+":"+str(exon[0])+"-"+str(exon[1])]=list_to_be_written_to_file fhw.write( ",".join( list_to_be_written_to_file ) + "\n" ) inputfile_for_CPD = options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/" + "inputfileforCPD" outputfile_for_CPD = options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/" + "outputfileforCPD" pool = multiprocessing.Pool( processes = int( options.cpu ) ) # Split inputfile into chunks if len( open( inputfile_for_CPD, "r" ).read().split( "\n" ) ) > 5000: chunked_file = list( divide_chunks( open( inputfile_for_CPD, "r" ).read().split( "\n" ), 5000 ) ) time.sleep( 5 ) for file_num, chunk in enumerate( chunked_file ): fhw = open( inputfile_for_CPD + "_" + str( file_num ), "w" ) fhw.write( "\n".join( chunk ) ) fhw.close() else: os.system( f"cp {inputfile_for_CPD} {inputfile_for_CPD}_0" ) chunked_file = [] with logging_mutex: logger_proxy.info( "inputfileforCPD generation is complete" ) round_num = 1 present = 0 while present == 0: with logging_mutex: logger_proxy.info( "Starting round " + str( round_num ) ) allinputs = [] for file_num, chunk in enumerate( chunked_file ): outputfilename_portion = outputfile_for_CPD + "_" + str( file_num ) cmd = "Rscript $(which " + options.softwares["find_exonic_troughs"] + ")" cmd += " " + inputfile_for_CPD + "_" + str( file_num ) cmd += " " + outputfilename_portion cmd += " 2 " cmd += " 2> " + outputfilename_portion + ".error" if os.path.exists( outputfilename_portion ) == False: allinputs.append( ["dummy", cmd] ) with logging_mutex: logger_proxy.info( "Performing calculation for " + outputfile_for_CPD + "_" + str( file_num ) ) logger_proxy.info( f"Running cmd - {cmd}" ) pool.map( runCommand, allinputs ) time.sleep( 5 ) file_absent = 0 for file_num, chunk in enumerate( chunked_file ): if os.path.exists( outputfile_for_CPD + "_" + str( file_num ) ) == True: pass else: file_absent = 1 with logging_mutex: logger_proxy.info( "Missing outputfile " + outputfile_for_CPD + "_" + str( file_num ) ) if file_absent == 1: present = 0 elif file_absent == 0: present = 1 if present == 0: round_num += 1 # Combine results in one file cmd = "cat " for f in range( len( list( chunked_file ) ) ): cmd += outputfile_for_CPD + "_" + str( f ) + " " cmd += " > " + outputfile_for_CPD cmd += " 2> " + outputfile_for_CPD + ".error" os.system( cmd ) # return cmd = "rm " + outputfile_for_CPD + "_* " + inputfile_for_CPD + "_* " os.system( cmd ) inputfile_for_CPD = options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/" + "inputfileforCPD" outputfile_for_CPD = options.output_assemblies_psiclass_terminal_exon_length_modified + "/combined/" + "outputfileforCPD" fhr_coverage = open( inputfile_for_CPD, "r" ) fhr_changepoints = open( outputfile_for_CPD, "r" ) exons_with_no_breakpoints_opp = {} exons_to_split_exons_opp = {} exons_to_split_exons_cov = {} complete_info_about_breakpoints = {"cov":{}, "opp":{}} while True: line_coverage = fhr_coverage.readline().strip() line_changepoints = fhr_changepoints.readline().strip() if not line_coverage or not line_changepoints: break type_cov, condition_cov, chromosome_cov, start_cov, end_cov, exon_loc_cov, coverage = line_coverage.strip().split( "," ) type_cpd, condition_cpd, chromosome_cpd, start_cpd, end_cpd, num_breakpoints, exon_loc_cpd, changepoints_cpd = line_changepoints.strip().split( "," ) num_breakpoints = int( num_breakpoints ) if ";" in changepoints_cpd: changepoints_cpd = list( map( int, changepoints_cpd.split( ";" ) ) ) else: changepoints_cpd = [] coverage = list( map( int, coverage.split( ";" ) ) )[2:] exon = start_cpd + "-" + end_cpd if type_cov == "opp": if len( changepoints_cpd ) == 0: pass else: if chromosome_cpd not in exons_to_split_exons_opp: exons_to_split_exons_opp[chromosome_cpd] = {} if len( changepoints_cpd ) == 1: exons_to_split_exons_opp[chromosome_cpd][start_cpd + "-" + end_cpd] = [int( changepoints_cpd[0] )] elif len( changepoints_cpd ) == 2: exons_to_split_exons_opp[chromosome_cpd][start_cpd + "-" + end_cpd] = [int( changepoints_cpd[0] ), int( changepoints_cpd[1] )] if chromosome_cpd not in complete_info_about_breakpoints["opp"]: complete_info_about_breakpoints["opp"][chromosome_cpd] = {} if exon not in complete_info_about_breakpoints["opp"][chromosome_cpd]: complete_info_about_breakpoints["opp"][chromosome_cpd][exon] = {} complete_info_about_breakpoints["opp"][chromosome_cpd][exon][condition_cpd] = {"changepoints":changepoints_cpd, "ratio":[]} elif type_cov == "cov": if chromosome_cpd not in exons_to_split_exons_cov: exons_to_split_exons_cov[chromosome_cpd] = {} if num_breakpoints == 1: pass elif num_breakpoints == 2: if len( changepoints_cpd ) == 2: coverage = list( map( int, coverage ) ) coverage_1st_portion = coverage[:changepoints_cpd[0]] coverage_2nd_portion = coverage[changepoints_cpd[0]:changepoints_cpd[1]] coverage_3rd_portion = coverage[changepoints_cpd[1]:] ratio1 = round( np.average( coverage_2nd_portion ) / np.average( coverage_1st_portion ), 2 ) ratio2 = round( np.average( coverage_2nd_portion ) / np.average( coverage_3rd_portion ), 2 ) """ if np.average(coverage_2nd_portion)/np.average(coverage_1st_portion)<1 and np.average(coverage_2nd_portion)/np.average(coverage_3rd_portion)<1: print(condition,chromosome_cov+":"+start_cov+"-"+end_cov,np.average(coverage_2nd_portion)/np.average(coverage_1st_portion),np.average(coverage_2nd_portion)/np.average(coverage_3rd_portion),changepoints) """ exons_to_split_exons_cov[chromosome_cpd][start_cpd + "-" + end_cpd] = [int( changepoints_cpd[0] ), int( changepoints_cpd[1] )] # print(line_changepoints,ratio1,ratio2) if 0 < min( ratio1, ratio2 ) < 1 and max( ratio1, ratio2 ) < 1: if chromosome_cpd not in complete_info_about_breakpoints["cov"]: complete_info_about_breakpoints["cov"][chromosome_cpd] = {} if exon not in complete_info_about_breakpoints["cov"][chromosome_cpd]: complete_info_about_breakpoints["cov"][chromosome_cpd][exon] = {} complete_info_about_breakpoints["cov"][chromosome_cpd][exon][condition_cpd] = {"changepoints":changepoints_cpd, "ratio":[ratio1, ratio2]} """if chromosome_cpd=="4" and start_cpd=="10439766" and end_cpd=="10440165": print("Ratios",ratio1,ratio2) sys.stdout.flush()""" else: # Do nothing - its a false positive if chromosome_cpd not in complete_info_about_breakpoints["cov"]: complete_info_about_breakpoints["cov"][chromosome_cpd] = {} if exon not in complete_info_about_breakpoints["cov"][chromosome_cpd]: complete_info_about_breakpoints["cov"][chromosome_cpd][exon] = {} complete_info_about_breakpoints["cov"][chromosome_cpd][exon][condition_cpd] = {"changepoints":[], "ratio":[]} elif num_breakpoints == 3: if len( changepoints_cpd ) == 3: coverage = list( map( int, coverage ) ) coverage_1st_portion = coverage[:changepoints_cpd[0]] coverage_2nd_portion = coverage[changepoints_cpd[0]:changepoints_cpd[1]] coverage_3rd_portion = coverage[changepoints_cpd[1]:changepoints_cpd[2]] coverage_4th_portion = coverage[changepoints_cpd[2]:] ratio1 = round( np.average( coverage_2nd_portion ) / np.average( coverage_1st_portion ), 2 ) ratio2 = round( np.average( coverage_2nd_portion ) / np.average( coverage_3rd_portion ), 2 ) ratio3 = round( np.average( coverage_3rd_portion ) / np.average( coverage_2nd_portion ), 2 ) ratio4 = round( np.average( coverage_3rd_portion ) / np.average( coverage_4th_portion ), 2 ) if 0 < min( ratio1, ratio2 ) < 1 and max( ratio1, ratio2 ) < 1: # print(condition,changepoints,chromosome_cov+":"+start_cov+"-"+end_cov,np.average(coverage_2nd_portion)/np.average(coverage_1st_portion),np.average(coverage_2nd_portion)/np.average(coverage_3rd_portion)) # print(line_changepoints,ratio1,ratio2) if chromosome_cpd not in complete_info_about_breakpoints["cov"]: complete_info_about_breakpoints["cov"][chromosome_cpd] = {} if exon not in complete_info_about_breakpoints["cov"][chromosome_cpd]: complete_info_about_breakpoints["cov"][chromosome_cpd][exon] = {} complete_info_about_breakpoints["cov"][chromosome_cpd][exon][condition_cpd] = {"changepoints":changepoints_cpd[:2], "ratio":[ratio1, ratio2]} elif 0 < min( ratio3, ratio4 ) < 1 and max( ratio3, ratio4 ) < 1: # print(condition,changepoints,chromosome_cov+":"+start_cov+"-"+end_cov,np.average(coverage_3rd_portion)/np.average(coverage_2nd_portion),np.average(coverage_3rd_portion)/np.average(coverage_4th_portion)) # print(line_changepoints,ratio3,ratio4) if chromosome_cpd not in complete_info_about_breakpoints["cov"]: complete_info_about_breakpoints["cov"][chromosome_cpd] = {} if exon not in complete_info_about_breakpoints["cov"][chromosome_cpd]: complete_info_about_breakpoints["cov"][chromosome_cpd][exon] = {} complete_info_about_breakpoints["cov"][chromosome_cpd][exon][condition_cpd] = {"changepoints":changepoints_cpd[1:], "ratio":[ratio3, ratio4]} """if chromosome_cpd=="5" and start_cpd=="6688611" and end_cpd=="6690038": print("this",ratio1,ratio2,ratio3,ratio4,np.average(coverage_1st_portion),np.average(coverage_2nd_portion),np.average(coverage_3rd_portion),np.average(coverage_4th_portion))""" else: # Do nothing - its a false positive if chromosome_cpd not in complete_info_about_breakpoints["cov"]: complete_info_about_breakpoints["cov"][chromosome_cpd] = {} if exon not in complete_info_about_breakpoints["cov"][chromosome_cpd]: complete_info_about_breakpoints["cov"][chromosome_cpd][exon] = {} complete_info_about_breakpoints["cov"][chromosome_cpd][exon][condition_cpd] = {"changepoints":[], "ratio":[]} # Modify end exons of transcripts overlapping_transcripts_end_modified = [] for chromosome in complete_info_about_breakpoints["opp"]: for exon in complete_info_about_breakpoints["opp"][chromosome]: # if len(complete_info_about_breakpoints["cov"][chromosome][exon])==total_num_of_conditions+1: median_changepoints = list( map( int, list( np.median(
np.array( [complete_info_about_breakpoints["opp"][chromosome][exon][condition]["changepoints"] for condition in complete_info_about_breakpoints["opp"][chromosome][exon]] )
numpy.array
# -*- coding: utf-8 -*- """ Defines unit tests for :mod:`colour.recovery.jakob2019` module. """ from __future__ import division, unicode_literals import numpy as np import os import shutil import tempfile import unittest from colour.characterisation import COLOURCHECKER_SDS from colour.colorimetry import (ILLUMINANTS, ILLUMINANT_SDS, STANDARD_OBSERVER_CMFS, SpectralDistribution, sd_to_XYZ) from colour.difference import delta_E_CIE1976 from colour.models import RGB_COLOURSPACES, RGB_to_XYZ, XYZ_to_Lab from colour.recovery.jakob2019 import ( XYZ_to_sd_Jakob2019, sd_Jakob2019, error_function, dimensionalise_coefficients, DEFAULT_SPECTRAL_SHAPE_JAKOB_2019, ACCEPTABLE_DELTA_E, Jakob2019Interpolator) from colour.utilities import domain_range_scale, full, ones, zeros __author__ = 'Colour Developers' __copyright__ = 'Copyright (C) 2013-2020 - Colour Developers' __license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause' __maintainer__ = 'Colour Developers' __email__ = '<EMAIL>' __status__ = 'Production' __all__ = [ 'TestErrorFunction', 'TestXYZ_to_sd_Jakob2019', 'TestJakob2019Interpolator' ] CMFS = STANDARD_OBSERVER_CMFS['CIE 1931 2 Degree Standard Observer'] sRGB = RGB_COLOURSPACES['sRGB'] PROPHOTO_RGB = RGB_COLOURSPACES['ProPhoto RGB'] D65 = SpectralDistribution(ILLUMINANT_SDS['D65']) D65_XY = ILLUMINANTS['CIE 1931 2 Degree Standard Observer']["D65"] class TestErrorFunction(unittest.TestCase): """ Defines :func:`colour.recovery.jakob2019.error_function` definition unit tests methods. """ def setUp(self): """ Initialises common tests attributes. """ self._Lab_e = np.array([72, -20, 61]) def test_compare_intermediates(self): """ Compares intermediate results of :func:`colour.recovery.jakob2019.error_function` with :func:`colour.sd_to_XYZ`, :func:`colour.XYZ_to_Lab` and checks if the error is computed correctly by comparing it with :func:`colour.difference.delta_E_CIE1976`. """ # Quoted names refer to colours from ColorChecker N Ohta (using D65). coefficient_list = [ np.array([0, 0, 0]), # 50% gray np.array([0, 0, -1e+9]), # Pure black np.array([0, 0, +1e+9]), # Pure white np.array([1e+9, -1e+9, 2.1e+8]), # A pathological example np.array([2.2667394, -7.6313081, 1.03185]), # 'blue' np.array([-31.377077, 26.810094, -6.1139927]), # 'green' np.array([25.064246, -16.072039, 0.10431365]), # 'red' np.array([-19.325667, 22.242319, -5.8144924]), # 'yellow' np.array([21.909902, -17.227963, 2.142351]), # 'magenta' np.array([-15.864009, 8.6735071, -1.4012552]), # 'cyan' ] # error_function will not align these for us. shape = DEFAULT_SPECTRAL_SHAPE_JAKOB_2019 aligned_cmfs = CMFS.copy().align(shape) illuminant = D65.copy().align(shape) XYZ_n = sd_to_XYZ(D65) XYZ_n /= XYZ_n[1] for coefficients in coefficient_list: error, _derror, R, XYZ, Lab = error_function( coefficients, self._Lab_e, aligned_cmfs, illuminant, additional_data=True) sd = sd_Jakob2019( dimensionalise_coefficients(coefficients, shape), shape) sd_XYZ = sd_to_XYZ(sd, illuminant=illuminant) / 100 sd_Lab = XYZ_to_Lab(XYZ, D65_XY) error_reference = delta_E_CIE1976(self._Lab_e, Lab) np.testing.assert_allclose(sd.values, R, atol=1e-14) np.testing.assert_allclose(XYZ, sd_XYZ, atol=1e-14) self.assertLess(abs(error_reference - error), ACCEPTABLE_DELTA_E) self.assertLess(delta_E_CIE1976(Lab, sd_Lab), ACCEPTABLE_DELTA_E) def test_derivatives(self): """ Compares gradients computed using closed-form expressions of derivatives with finite difference approximations. """ shape = DEFAULT_SPECTRAL_SHAPE_JAKOB_2019 aligned_cmfs = CMFS.copy().align(shape) illuminant = D65.copy().align(shape) XYZ_n = sd_to_XYZ(D65) XYZ_n /= XYZ_n[1] var_range = np.linspace(-10, 10, 1000) h = var_range[1] - var_range[0] # Vary one coefficient at a time, keeping the others fixed to 1. for coefficient_i in range(3): errors = np.empty_like(var_range) derrors = np.empty_like(var_range) for i, var in enumerate(var_range): coefficients = ones(3) coefficients[coefficient_i] = var error, derror = error_function(coefficients, self._Lab_e, aligned_cmfs, illuminant) errors[i] = error derrors[i] = derror[coefficient_i] staggered_derrors = (derrors[:-1] + derrors[1:]) / 2 approximate_derrors = np.diff(errors) / h # The approximated derivatives aren't too accurate, so tolerances # have to be rather loose. np.testing.assert_allclose( staggered_derrors, approximate_derrors, atol=1e-3, rtol=1e-2) class TestXYZ_to_sd_Jakob2019(unittest.TestCase): """ Defines :func:`colour.recovery.jakob2019.XYZ_to_sd_Jakob2019` definition unit tests methods. """ def test_XYZ_to_sd_Jakob2019(self): """ Tests :func:`colour.recovery.jakob2019.XYZ_to_sd_Jakob2019` definition. """ # Tests the round-trip with values of a colour checker. for name, sd in COLOURCHECKER_SDS['ColorChecker N Ohta'].items(): # The colours aren't too saturated and the tests should pass with # or without feedback. for use_feedback in [False, True]: XYZ = sd_to_XYZ(sd, illuminant=D65) / 100 _recovered_sd, error = XYZ_to_sd_Jakob2019( XYZ, illuminant=D65, optimisation_kwargs={'use_feedback': use_feedback}, additional_data=True) if error > ACCEPTABLE_DELTA_E: self.fail('Delta E for \'{0}\' with use_feedback={1}' ' is {2}'.format(name, use_feedback, error)) def test_domain_range_scale_XYZ_to_sd_Jakob2019(self): """ Tests :func:`colour.recovery.jakob2019.XYZ_to_sd_Jakob2019` definition domain and range scale support. """ XYZ_i =
np.array([0.21781186, 0.12541048, 0.04697113])
numpy.array
import autolens as al from skimage import measure import numpy as np import pytest from astropy import cosmology as cosmo from test_autoarray.mock import mock_inversion as mock_inv def critical_curve_via_magnification_from_tracer_and_grid(tracer, grid): magnification = tracer.magnification_from_grid(grid=grid) inverse_magnification = 1 / magnification critical_curves_indices = measure.find_contours(inverse_magnification.in_2d, 0) no_critical_curves = len(critical_curves_indices) contours = [] critical_curves = [] for jj in np.arange(no_critical_curves): contours.append(critical_curves_indices[jj]) contour_x, contour_y = contours[jj].T pixel_coord = np.stack((contour_x, contour_y), axis=-1) critical_curve = grid.geometry.grid_scaled_from_grid_pixels_1d_for_marching_squares( grid_pixels_1d=pixel_coord, shape_2d=magnification.sub_shape_2d ) critical_curve = al.grid_irregular.manual_1d(grid=critical_curve) critical_curves.append(critical_curve) return critical_curves def caustics_via_magnification_from_tracer_and_grid(tracer, grid): caustics = [] critical_curves = critical_curve_via_magnification_from_tracer_and_grid( tracer=tracer, grid=grid ) for i in range(len(critical_curves)): critical_curve = critical_curves[i] deflections_1d = tracer.deflections_from_grid(grid=critical_curve) caustic = critical_curve - deflections_1d caustics.append(caustic) return caustics class TestAbstractTracer: class TestProperties: def test__total_planes(self): tracer = al.Tracer.from_galaxies(galaxies=[al.Galaxy(redshift=0.5)]) assert tracer.total_planes == 1 tracer = al.Tracer.from_galaxies( galaxies=[al.Galaxy(redshift=0.5), al.Galaxy(redshift=1.0)] ) assert tracer.total_planes == 2 tracer = al.Tracer.from_galaxies( galaxies=[ al.Galaxy(redshift=1.0), al.Galaxy(redshift=2.0), al.Galaxy(redshift=3.0), ] ) assert tracer.total_planes == 3 tracer = al.Tracer.from_galaxies( galaxies=[ al.Galaxy(redshift=1.0), al.Galaxy(redshift=2.0), al.Galaxy(redshift=1.0), ] ) assert tracer.total_planes == 2 def test__has_galaxy_with_light_profile(self): gal = al.Galaxy(redshift=0.5) gal_lp = al.Galaxy(redshift=0.5, light_profile=al.lp.LightProfile()) gal_mp = al.Galaxy(redshift=0.5, mass_profile=al.mp.SphericalIsothermal()) tracer = al.Tracer.from_galaxies(galaxies=[gal, gal]) assert tracer.has_light_profile is False tracer = al.Tracer.from_galaxies(galaxies=[gal_mp, gal_mp]) assert tracer.has_light_profile is False tracer = al.Tracer.from_galaxies(galaxies=[gal_lp, gal_lp]) assert tracer.has_light_profile is True tracer = al.Tracer.from_galaxies(galaxies=[gal_lp, gal]) assert tracer.has_light_profile is True tracer = al.Tracer.from_galaxies(galaxies=[gal_lp, gal_mp]) assert tracer.has_light_profile is True def test_plane_with_galaxy(self, sub_grid_7x7): g1 = al.Galaxy(redshift=1) g2 = al.Galaxy(redshift=2) tracer = al.Tracer.from_galaxies(galaxies=[g1, g2]) assert tracer.plane_with_galaxy(g1).galaxies == [g1] assert tracer.plane_with_galaxy(g2).galaxies == [g2] def test__has_galaxy_with_mass_profile(self, sub_grid_7x7): gal = al.Galaxy(redshift=0.5) gal_lp = al.Galaxy(redshift=0.5, light_profile=al.lp.LightProfile()) gal_mp = al.Galaxy(redshift=0.5, mass_profile=al.mp.SphericalIsothermal()) tracer = al.Tracer.from_galaxies(galaxies=[gal, gal]) assert tracer.has_mass_profile is False tracer = al.Tracer.from_galaxies(galaxies=[gal_mp, gal_mp]) assert tracer.has_mass_profile is True tracer = al.Tracer.from_galaxies(galaxies=[gal_lp, gal_lp]) assert tracer.has_mass_profile is False tracer = al.Tracer.from_galaxies(galaxies=[gal_lp, gal]) assert tracer.has_mass_profile is False tracer = al.Tracer.from_galaxies(galaxies=[gal_lp, gal_mp]) assert tracer.has_mass_profile is True def test__planes_indexes_with_inversion(self): gal = al.Galaxy(redshift=0.5) gal_pix = al.Galaxy( redshift=0.5, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), ) tracer = al.Tracer.from_galaxies(galaxies=[gal, gal]) assert tracer.plane_indexes_with_pixelizations == [] tracer = al.Tracer.from_galaxies(galaxies=[gal_pix, gal]) assert tracer.plane_indexes_with_pixelizations == [0] gal_pix = al.Galaxy( redshift=1.0, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), ) tracer = al.Tracer.from_galaxies(galaxies=[gal_pix, gal]) assert tracer.plane_indexes_with_pixelizations == [1] gal_pix_0 = al.Galaxy( redshift=0.6, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), ) gal_pix_1 = al.Galaxy( redshift=2.0, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), ) gal0 = al.Galaxy(redshift=0.25) gal1 = al.Galaxy(redshift=0.5) gal2 = al.Galaxy(redshift=0.75) tracer = al.Tracer.from_galaxies( galaxies=[gal_pix_0, gal_pix_1, gal0, gal1, gal2] ) assert tracer.plane_indexes_with_pixelizations == [2, 4] def test__has_galaxy_with_pixelization(self, sub_grid_7x7): gal = al.Galaxy(redshift=0.5) gal_lp = al.Galaxy(redshift=0.5, light_profile=al.lp.LightProfile()) gal_pix = al.Galaxy( redshift=0.5, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), ) tracer = al.Tracer.from_galaxies(galaxies=[gal, gal]) assert tracer.has_pixelization is False tracer = al.Tracer.from_galaxies(galaxies=[gal_lp, gal_lp]) assert tracer.has_pixelization is False tracer = al.Tracer.from_galaxies(galaxies=[gal_pix, gal_pix]) assert tracer.has_pixelization is True tracer = al.Tracer.from_galaxies(galaxies=[gal_pix, gal]) assert tracer.has_pixelization is True tracer = al.Tracer.from_galaxies(galaxies=[gal_pix, gal_lp]) assert tracer.has_pixelization is True def test__has_galaxy_with_regularization(self, sub_grid_7x7): gal = al.Galaxy(redshift=0.5) gal_lp = al.Galaxy(redshift=0.5, light_profile=al.lp.LightProfile()) gal_reg = al.Galaxy( redshift=0.5, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), ) tracer = al.Tracer.from_galaxies(galaxies=[gal, gal]) assert tracer.has_regularization is False tracer = al.Tracer.from_galaxies(galaxies=[gal_lp, gal_lp]) assert tracer.has_regularization is False tracer = al.Tracer.from_galaxies(galaxies=[gal_reg, gal_reg]) assert tracer.has_regularization is True tracer = al.Tracer.from_galaxies(galaxies=[gal_reg, gal]) assert tracer.has_regularization is True tracer = al.Tracer.from_galaxies(galaxies=[gal_reg, gal_lp]) assert tracer.has_regularization is True def test__has_galaxy_with_hyper_galaxy(self, sub_grid_7x7): gal = al.Galaxy(redshift=0.5) gal_lp = al.Galaxy(redshift=0.5, light_profile=al.lp.LightProfile()) gal_hyper = al.Galaxy(redshift=0.5, hyper_galaxy=al.HyperGalaxy()) tracer = al.Tracer.from_galaxies(galaxies=[gal, gal]) assert tracer.has_hyper_galaxy is False tracer = al.Tracer.from_galaxies(galaxies=[gal_lp, gal_lp]) assert tracer.has_hyper_galaxy is False tracer = al.Tracer.from_galaxies(galaxies=[gal_hyper, gal_hyper]) assert tracer.has_hyper_galaxy is True tracer = al.Tracer.from_galaxies(galaxies=[gal_hyper, gal]) assert tracer.has_hyper_galaxy is True tracer = al.Tracer.from_galaxies(galaxies=[gal_hyper, gal_lp]) assert tracer.has_hyper_galaxy is True def test__upper_plane_index_with_light_profile(self): g0 = al.Galaxy(redshift=0.5) g1 = al.Galaxy(redshift=1.0) g2 = al.Galaxy(redshift=2.0) g3 = al.Galaxy(redshift=3.0) g0_lp = al.Galaxy(redshift=0.5, light_profile=al.lp.LightProfile()) g1_lp = al.Galaxy(redshift=1.0, light_profile=al.lp.LightProfile()) g2_lp = al.Galaxy(redshift=2.0, light_profile=al.lp.LightProfile()) g3_lp = al.Galaxy(redshift=3.0, light_profile=al.lp.LightProfile()) tracer = al.Tracer.from_galaxies(galaxies=[g0_lp]) assert tracer.upper_plane_index_with_light_profile == 0 tracer = al.Tracer.from_galaxies(galaxies=[g0, g0_lp]) assert tracer.upper_plane_index_with_light_profile == 0 tracer = al.Tracer.from_galaxies(galaxies=[g1_lp]) assert tracer.upper_plane_index_with_light_profile == 0 tracer = al.Tracer.from_galaxies(galaxies=[g0, g1_lp]) assert tracer.upper_plane_index_with_light_profile == 1 tracer = al.Tracer.from_galaxies(galaxies=[g0_lp, g1_lp, g2_lp]) assert tracer.upper_plane_index_with_light_profile == 2 tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2_lp]) assert tracer.upper_plane_index_with_light_profile == 2 tracer = al.Tracer.from_galaxies(galaxies=[g0_lp, g1, g2, g3_lp]) assert tracer.upper_plane_index_with_light_profile == 3 tracer = al.Tracer.from_galaxies(galaxies=[g0_lp, g1, g2_lp, g3]) assert tracer.upper_plane_index_with_light_profile == 2 def test__hyper_model_image_of_galaxy_with_pixelization(self, sub_grid_7x7): gal = al.Galaxy(redshift=0.5) gal_pix = al.Galaxy( redshift=0.5, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), ) tracer = al.Tracer.from_galaxies(galaxies=[gal, gal]) assert tracer.hyper_galaxy_image_of_planes_with_pixelizations == [None] tracer = al.Tracer.from_galaxies(galaxies=[gal_pix, gal_pix]) assert tracer.hyper_galaxy_image_of_planes_with_pixelizations == [None] gal_pix = al.Galaxy( redshift=0.5, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), hyper_galaxy_image=1, ) tracer = al.Tracer.from_galaxies(galaxies=[gal_pix, gal]) assert tracer.hyper_galaxy_image_of_planes_with_pixelizations == [1] gal0 = al.Galaxy(redshift=0.25) gal1 = al.Galaxy(redshift=0.75) gal2 = al.Galaxy(redshift=1.5) gal_pix0 = al.Galaxy( redshift=0.5, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), hyper_galaxy_image=1, ) gal_pix1 = al.Galaxy( redshift=2.0, pixelization=al.pix.Pixelization(), regularization=al.reg.Constant(), hyper_galaxy_image=2, ) tracer = al.Tracer.from_galaxies( galaxies=[gal0, gal1, gal2, gal_pix0, gal_pix1] ) assert tracer.hyper_galaxy_image_of_planes_with_pixelizations == [ None, 1, None, None, 2, ] class TestPixelizations: def test__no_galaxy_has_regularization__returns_list_of_ones( self, sub_grid_7x7 ): galaxy_no_pix = al.Galaxy(redshift=0.5) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_no_pix, galaxy_no_pix]) assert tracer.pixelizations_of_planes == [None] def test__source_galaxy_has_regularization__returns_list_with_none_and_regularization( self, sub_grid_7x7 ): galaxy_pix = al.Galaxy( redshift=1.0, pixelization=mock_inv.MockPixelization(value=1), regularization=mock_inv.MockRegularization(matrix_shape=(1, 1)), ) galaxy_no_pix = al.Galaxy(redshift=0.5) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_no_pix, galaxy_pix]) assert tracer.pixelizations_of_planes[0] is None assert tracer.pixelizations_of_planes[1].value == 1 def test__both_galaxies_have_pixelization__returns_both_pixelizations( self, sub_grid_7x7 ): galaxy_pix_0 = al.Galaxy( redshift=0.5, pixelization=mock_inv.MockPixelization(value=1), regularization=mock_inv.MockRegularization(matrix_shape=(3, 3)), ) galaxy_pix_1 = al.Galaxy( redshift=1.0, pixelization=mock_inv.MockPixelization(value=2), regularization=mock_inv.MockRegularization(matrix_shape=(4, 4)), ) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_pix_0, galaxy_pix_1]) assert tracer.pixelizations_of_planes[0].value == 1 assert tracer.pixelizations_of_planes[1].value == 2 class TestRegularizations: def test__no_galaxy_has_regularization__returns_empty_list(self, sub_grid_7x7): galaxy_no_reg = al.Galaxy(redshift=0.5) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_no_reg, galaxy_no_reg]) assert tracer.regularizations_of_planes == [None] def test__source_galaxy_has_regularization__returns_regularizations( self, sub_grid_7x7 ): galaxy_reg = al.Galaxy( redshift=1.0, pixelization=mock_inv.MockPixelization(value=1), regularization=mock_inv.MockRegularization(matrix_shape=(1, 1)), ) galaxy_no_reg = al.Galaxy(redshift=0.5) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_no_reg, galaxy_reg]) assert tracer.regularizations_of_planes[0] is None assert tracer.regularizations_of_planes[1].shape == (1, 1) def test__both_galaxies_have_regularization__returns_both_regularizations( self, sub_grid_7x7 ): galaxy_reg_0 = al.Galaxy( redshift=0.5, pixelization=mock_inv.MockPixelization(value=1), regularization=mock_inv.MockRegularization(matrix_shape=(3, 3)), ) galaxy_reg_1 = al.Galaxy( redshift=1.0, pixelization=mock_inv.MockPixelization(value=2), regularization=mock_inv.MockRegularization(matrix_shape=(4, 4)), ) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_reg_0, galaxy_reg_1]) assert tracer.regularizations_of_planes[0].shape == (3, 3) assert tracer.regularizations_of_planes[1].shape == (4, 4) class TestGalaxyLists: def test__galaxy_list__comes_in_plane_redshift_order(self, sub_grid_7x7): g0 = al.Galaxy(redshift=0.5) g1 = al.Galaxy(redshift=0.5) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) assert tracer.galaxies == [g0, g1] g2 = al.Galaxy(redshift=1.0) g3 = al.Galaxy(redshift=1.0) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2, g3]) assert tracer.galaxies == [g0, g1, g2, g3] g4 = al.Galaxy(redshift=0.75) g5 = al.Galaxy(redshift=1.5) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2, g3, g4, g5]) assert tracer.galaxies == [g0, g1, g4, g2, g3, g5] # def test__galaxy_in_planes_lists__comes_in_lists_of_planes_in_redshift_order(self, sub_grid_7x7): # g0 = al.Galaxy(redshift=0.5) # g1 = al.Galaxy(redshift=0.5) # # tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) # # assert tracer.galaxies_in_planes == [[g0, g1]] # # g2 = al.Galaxy(redshift=1.0) # g3 = al.Galaxy(redshift=1.0) # # tracer = al.Tracer.from_galaxies(galaxies=[g0, g1], galaxies=[g2, g3], # ) # # assert tracer.galaxies_in_planes == [[g0, g1], [g2, g3]] # # g4 = al.Galaxy(redshift=0.75) # g5 = al.Galaxy(redshift=1.5) # # tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2, g3, g4, g5], # ) # # assert tracer.galaxies_in_planes == [[g0, g1], [g4], [g2, g3], [g5]] class TestLightProfileQuantities: def test__extract_centres_of_all_light_profiles_of_all_planes_and_galaxies( self ): g0 = al.Galaxy( redshift=0.5, light=al.lp.SphericalGaussian(centre=(1.0, 1.0)) ) g1 = al.Galaxy( redshift=0.5, light=al.lp.SphericalGaussian(centre=(2.0, 2.0)) ) g2 = al.Galaxy( redshift=1.0, light0=al.lp.SphericalGaussian(centre=(3.0, 3.0)), light1=al.lp.SphericalGaussian(centre=(4.0, 4.0)), ) plane_0 = al.Plane(galaxies=[al.Galaxy(redshift=0.5)], redshift=None) plane_1 = al.Plane(galaxies=[al.Galaxy(redshift=1.0)], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.light_profile_centres_of_planes == [] assert tracer.light_profile_centres == [] plane_0 = al.Plane(galaxies=[g0], redshift=None) plane_1 = al.Plane(galaxies=[g1], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.light_profile_centres_of_planes == [ [(1.0, 1.0)], [(2.0, 2.0)], ] assert tracer.light_profile_centres == [(1.0, 1.0), (2.0, 2.0)] plane_0 = al.Plane(galaxies=[g0, g1], redshift=None) plane_1 = al.Plane(galaxies=[g2], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.light_profile_centres_of_planes == [ [(1.0, 1.0), (2.0, 2.0)], [(3.0, 3.0), (4.0, 4.0)], ] assert tracer.light_profile_centres == [ (1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0), ] class TestMassProfileQuantities: def test__extract_mass_profiles_of_all_planes_and_galaxies(self): g0 = al.Galaxy( redshift=0.5, mass=al.mp.SphericalIsothermal(centre=(1.0, 1.0)) ) g1 = al.Galaxy( redshift=0.5, mass=al.mp.SphericalIsothermal(centre=(2.0, 2.0)) ) g2 = al.Galaxy( redshift=1.0, mass0=al.mp.SphericalIsothermal(centre=(3.0, 3.0)), mass1=al.mp.SphericalIsothermal(centre=(4.0, 4.0)), ) plane_0 = al.Plane(galaxies=[al.Galaxy(redshift=0.5)], redshift=None) plane_1 = al.Plane(galaxies=[al.Galaxy(redshift=1.0)], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.mass_profiles == [] assert tracer.mass_profiles == [] plane_0 = al.Plane(galaxies=[g0], redshift=None) plane_1 = al.Plane(galaxies=[g1], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.mass_profiles_of_planes == [[g0.mass], [g1.mass]] assert tracer.mass_profiles == [g0.mass, g1.mass] plane_0 = al.Plane(galaxies=[g0, g1], redshift=None) plane_1 = al.Plane(galaxies=[g2], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.mass_profiles_of_planes == [ [g0.mass, g1.mass], [g2.mass0, g2.mass1], ] assert tracer.mass_profiles == [g0.mass, g1.mass, g2.mass0, g2.mass1] def test__extract_centres_of_all_mass_profiles_of_all_planes_and_galaxies__ignores_mass_sheets( self ): g0 = al.Galaxy( redshift=0.5, mass=al.mp.SphericalIsothermal(centre=(1.0, 1.0)) ) g1 = al.Galaxy( redshift=0.5, mass=al.mp.SphericalIsothermal(centre=(2.0, 2.0)) ) g2 = al.Galaxy( redshift=1.0, mass0=al.mp.SphericalIsothermal(centre=(3.0, 3.0)), mass1=al.mp.SphericalIsothermal(centre=(4.0, 4.0)), ) plane_0 = al.Plane(galaxies=[al.Galaxy(redshift=0.5)], redshift=None) plane_1 = al.Plane(galaxies=[al.Galaxy(redshift=1.0)], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.mass_profile_centres_of_planes == [] assert tracer.mass_profile_centres == [] plane_0 = al.Plane(galaxies=[g0], redshift=None) plane_1 = al.Plane(galaxies=[g1], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.mass_profile_centres_of_planes == [[(1.0, 1.0)], [(2.0, 2.0)]] assert tracer.mass_profile_centres == [(1.0, 1.0), (2.0, 2.0)] plane_0 = al.Plane(galaxies=[g0, g1], redshift=None) plane_1 = al.Plane(galaxies=[g2], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.mass_profile_centres_of_planes == [ [(1.0, 1.0), (2.0, 2.0)], [(3.0, 3.0), (4.0, 4.0)], ] assert tracer.mass_profile_centres == [ (1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0), ] g1 = al.Galaxy( redshift=0.5, mass=al.mp.SphericalIsothermal(centre=(2.0, 2.0)), sheet=al.mp.MassSheet(centre=(10.0, 10.0)), ) g2 = al.Galaxy( redshift=1.0, mass0=al.mp.SphericalIsothermal(centre=(3.0, 3.0)), mass1=al.mp.SphericalIsothermal(centre=(4.0, 4.0)), sheet=al.mp.MassSheet(centre=(10.0, 10.0)), ) plane_0 = al.Plane(galaxies=[g0, g1], redshift=None) plane_1 = al.Plane(galaxies=[g2], redshift=None) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=None) assert tracer.mass_profile_centres_of_planes == [ [(1.0, 1.0), (2.0, 2.0)], [(3.0, 3.0), (4.0, 4.0)], ] assert tracer.mass_profile_centres == [ (1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0), ] class TestUnits: def test__light_profiles_conversions(self): profile_0 = al.lp.EllipticalGaussian( centre=( al.dim.Length(value=3.0, unit_length="arcsec"), al.dim.Length(value=3.0, unit_length="arcsec"), ), intensity=al.dim.Luminosity(value=2.0, unit_luminosity="eps"), ) galaxy_0 = al.Galaxy(light=profile_0, redshift=1.0) profile_1 = al.lp.EllipticalGaussian( centre=( al.dim.Length(value=4.0, unit_length="arcsec"), al.dim.Length(value=4.0, unit_length="arcsec"), ), intensity=al.dim.Luminosity(value=5.0, unit_luminosity="eps"), ) galaxy_1 = al.Galaxy(light=profile_1, redshift=1.0) plane_0 = al.Plane(galaxies=[galaxy_0]) plane_1 = al.Plane(galaxies=[galaxy_1]) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=cosmo.Planck15) assert tracer.planes[0].galaxies[0].light.centre == (3.0, 3.0) assert tracer.planes[0].galaxies[0].light.unit_length == "arcsec" assert tracer.planes[0].galaxies[0].light.intensity == 2.0 assert tracer.planes[0].galaxies[0].light.intensity.unit_luminosity == "eps" assert tracer.planes[1].galaxies[0].light.centre == (4.0, 4.0) assert tracer.planes[1].galaxies[0].light.unit_length == "arcsec" assert tracer.planes[1].galaxies[0].light.intensity == 5.0 assert tracer.planes[1].galaxies[0].light.intensity.unit_luminosity == "eps" tracer = tracer.new_object_with_units_converted( unit_length="kpc", kpc_per_arcsec=2.0, unit_luminosity="counts", exposure_time=0.5, ) assert tracer.planes[0].galaxies[0].light.centre == (6.0, 6.0) assert tracer.planes[0].galaxies[0].light.unit_length == "kpc" assert tracer.planes[0].galaxies[0].light.intensity == 1.0 assert ( tracer.planes[0].galaxies[0].light.intensity.unit_luminosity == "counts" ) assert tracer.planes[1].galaxies[0].light.centre == (8.0, 8.0) assert tracer.planes[1].galaxies[0].light.unit_length == "kpc" assert tracer.planes[1].galaxies[0].light.intensity == 2.5 assert ( tracer.planes[1].galaxies[0].light.intensity.unit_luminosity == "counts" ) def test__mass_profiles_conversions(self): profile_0 = al.mp.EllipticalSersic( centre=( al.dim.Length(value=3.0, unit_length="arcsec"), al.dim.Length(value=3.0, unit_length="arcsec"), ), intensity=al.dim.Luminosity(value=2.0, unit_luminosity="eps"), mass_to_light_ratio=al.dim.MassOverLuminosity( value=5.0, unit_mass="angular", unit_luminosity="eps" ), ) galaxy_0 = al.Galaxy(mass=profile_0, redshift=1.0) profile_1 = al.mp.EllipticalSersic( centre=( al.dim.Length(value=4.0, unit_length="arcsec"), al.dim.Length(value=4.0, unit_length="arcsec"), ), intensity=al.dim.Luminosity(value=5.0, unit_luminosity="eps"), mass_to_light_ratio=al.dim.MassOverLuminosity( value=10.0, unit_mass="angular", unit_luminosity="eps" ), ) galaxy_1 = al.Galaxy(mass=profile_1, redshift=1.0) plane_0 = al.Plane(galaxies=[galaxy_0]) plane_1 = al.Plane(galaxies=[galaxy_1]) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=cosmo.Planck15) assert tracer.planes[0].galaxies[0].mass.centre == (3.0, 3.0) assert tracer.planes[0].galaxies[0].mass.unit_length == "arcsec" assert tracer.planes[0].galaxies[0].mass.intensity == 2.0 assert tracer.planes[0].galaxies[0].mass.intensity.unit_luminosity == "eps" assert tracer.planes[0].galaxies[0].mass.mass_to_light_ratio == 5.0 assert ( tracer.planes[0].galaxies[0].mass.mass_to_light_ratio.unit_mass == "angular" ) assert tracer.planes[1].galaxies[0].mass.centre == (4.0, 4.0) assert tracer.planes[1].galaxies[0].mass.unit_length == "arcsec" assert tracer.planes[1].galaxies[0].mass.intensity == 5.0 assert tracer.planes[1].galaxies[0].mass.intensity.unit_luminosity == "eps" assert tracer.planes[1].galaxies[0].mass.mass_to_light_ratio == 10.0 assert ( tracer.planes[1].galaxies[0].mass.mass_to_light_ratio.unit_mass == "angular" ) tracer = tracer.new_object_with_units_converted( unit_length="kpc", kpc_per_arcsec=2.0, unit_luminosity="counts", exposure_time=0.5, unit_mass="solMass", critical_surface_density=3.0, ) assert tracer.planes[0].galaxies[0].mass.centre == (6.0, 6.0) assert tracer.planes[0].galaxies[0].mass.unit_length == "kpc" assert tracer.planes[0].galaxies[0].mass.intensity == 1.0 assert ( tracer.planes[0].galaxies[0].mass.intensity.unit_luminosity == "counts" ) assert tracer.planes[0].galaxies[0].mass.mass_to_light_ratio == 30.0 assert ( tracer.planes[0].galaxies[0].mass.mass_to_light_ratio.unit_mass == "solMass" ) assert tracer.planes[1].galaxies[0].mass.centre == (8.0, 8.0) assert tracer.planes[1].galaxies[0].mass.unit_length == "kpc" assert tracer.planes[1].galaxies[0].mass.intensity == 2.5 assert ( tracer.planes[1].galaxies[0].mass.intensity.unit_luminosity == "counts" ) assert tracer.planes[1].galaxies[0].mass.mass_to_light_ratio == 60.0 assert ( tracer.planes[1].galaxies[0].mass.mass_to_light_ratio.unit_mass == "solMass" ) def test__tracer_keeps_attributes(self): profile_0 = al.lp.EllipticalGaussian( centre=( al.dim.Length(value=3.0, unit_length="arcsec"), al.dim.Length(value=3.0, unit_length="arcsec"), ), intensity=al.dim.Luminosity(value=2.0, unit_luminosity="eps"), ) galaxy_0 = al.Galaxy(light=profile_0, redshift=1.0) profile_1 = al.lp.EllipticalGaussian( centre=( al.dim.Length(value=4.0, unit_length="arcsec"), al.dim.Length(value=4.0, unit_length="arcsec"), ), intensity=al.dim.Luminosity(value=5.0, unit_luminosity="eps"), ) galaxy_1 = al.Galaxy(light=profile_1, redshift=1.0) plane_0 = al.Plane(galaxies=[galaxy_0]) plane_1 = al.Plane(galaxies=[galaxy_1]) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=1) assert tracer.cosmology == 1 tracer = tracer.new_object_with_units_converted( unit_length="kpc", kpc_per_arcsec=2.0, unit_luminosity="counts", exposure_time=0.5, ) assert tracer.cosmology == 1 class TestAbstractTracerCosmology: def test__2_planes__z01_and_z1(self): g0 = al.Galaxy(redshift=0.1) g1 = al.Galaxy(redshift=1.0) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) assert tracer.cosmology == cosmo.Planck15 assert tracer.image_plane.arcsec_per_kpc == pytest.approx(0.525060, 1e-5) assert tracer.image_plane.kpc_per_arcsec == pytest.approx(1.904544, 1e-5) assert tracer.image_plane.angular_diameter_distance_to_earth_in_units( unit_length="kpc" ) == pytest.approx(392840, 1e-5) assert tracer.source_plane.arcsec_per_kpc == pytest.approx(0.1214785, 1e-5) assert tracer.source_plane.kpc_per_arcsec == pytest.approx(8.231907, 1e-5) assert tracer.source_plane.angular_diameter_distance_to_earth_in_units( unit_length="kpc" ) == pytest.approx(1697952, 1e-5) assert tracer.angular_diameter_distance_from_image_to_source_plane_in_units( unit_length="kpc" ) == pytest.approx(1481890.4, 1e-5) assert tracer.critical_surface_density_between_planes_in_units( i=0, j=1, unit_length="kpc", unit_mass="solMass" ) == pytest.approx(4.85e9, 1e-2) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) assert tracer.critical_surface_density_between_planes_in_units( i=0, j=1, unit_length="arcsec", unit_mass="solMass" ) == pytest.approx(17593241668, 1e-2) def test__3_planes__z01_z1__and_z2(self): g0 = al.Galaxy(redshift=0.1) g1 = al.Galaxy(redshift=1.0) g2 = al.Galaxy(redshift=2.0) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2], cosmology=cosmo.Planck15 ) assert tracer.arcsec_per_kpc_proper_of_plane(i=0) == pytest.approx( 0.525060, 1e-5 ) assert tracer.kpc_per_arcsec_proper_of_plane(i=0) == pytest.approx( 1.904544, 1e-5 ) assert tracer.angular_diameter_distance_of_plane_to_earth_in_units( i=0, unit_length="kpc" ) == pytest.approx(392840, 1e-5) assert ( tracer.angular_diameter_distance_between_planes_in_units( i=0, j=0, unit_length="kpc" ) == 0.0 ) assert tracer.angular_diameter_distance_between_planes_in_units( i=0, j=1, unit_length="kpc" ) == pytest.approx(1481890.4, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=0, j=2, unit_length="kpc" ) == pytest.approx(1626471, 1e-5) assert tracer.arcsec_per_kpc_proper_of_plane(i=1) == pytest.approx( 0.1214785, 1e-5 ) assert tracer.kpc_per_arcsec_proper_of_plane(i=1) == pytest.approx( 8.231907, 1e-5 ) assert tracer.angular_diameter_distance_of_plane_to_earth_in_units( i=1, unit_length="kpc" ) == pytest.approx(1697952, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=1, j=0, unit_length="kpc" ) == pytest.approx(-2694346, 1e-5) assert ( tracer.angular_diameter_distance_between_planes_in_units( i=1, j=1, unit_length="kpc" ) == 0.0 ) assert tracer.angular_diameter_distance_between_planes_in_units( i=1, j=2, unit_length="kpc" ) == pytest.approx(638544, 1e-5) assert tracer.arcsec_per_kpc_proper_of_plane(i=2) == pytest.approx( 0.116500, 1e-5 ) assert tracer.kpc_per_arcsec_proper_of_plane(i=2) == pytest.approx( 8.58368, 1e-5 ) assert tracer.angular_diameter_distance_of_plane_to_earth_in_units( i=2, unit_length="kpc" ) == pytest.approx(1770512, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=2, j=0, unit_length="kpc" ) == pytest.approx(-4435831, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=2, j=1, unit_length="kpc" ) == pytest.approx(-957816) assert ( tracer.angular_diameter_distance_between_planes_in_units( i=2, j=2, unit_length="kpc" ) == 0.0 ) assert tracer.critical_surface_density_between_planes_in_units( i=0, j=1, unit_length="kpc", unit_mass="solMass" ) == pytest.approx(4.85e9, 1e-2) assert tracer.critical_surface_density_between_planes_in_units( i=0, j=1, unit_length="arcsec", unit_mass="solMass" ) == pytest.approx(17593241668, 1e-2) assert tracer.scaling_factor_between_planes(i=0, j=1) == pytest.approx( 0.9500, 1e-4 ) assert tracer.scaling_factor_between_planes(i=0, j=2) == pytest.approx( 1.0, 1e-4 ) assert tracer.scaling_factor_between_planes(i=1, j=2) == pytest.approx( 1.0, 1e-4 ) def test__4_planes__z01_z1_z2_and_z3(self): g0 = al.Galaxy(redshift=0.1) g1 = al.Galaxy(redshift=1.0) g2 = al.Galaxy(redshift=2.0) g3 = al.Galaxy(redshift=3.0) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2, g3], cosmology=cosmo.Planck15 ) assert tracer.arcsec_per_kpc_proper_of_plane(i=0) == pytest.approx( 0.525060, 1e-5 ) assert tracer.kpc_per_arcsec_proper_of_plane(i=0) == pytest.approx( 1.904544, 1e-5 ) assert tracer.angular_diameter_distance_of_plane_to_earth_in_units( i=0, unit_length="kpc" ) == pytest.approx(392840, 1e-5) assert ( tracer.angular_diameter_distance_between_planes_in_units( i=0, j=0, unit_length="kpc" ) == 0.0 ) assert tracer.angular_diameter_distance_between_planes_in_units( i=0, j=1, unit_length="kpc" ) == pytest.approx(1481890.4, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=0, j=2, unit_length="kpc" ) == pytest.approx(1626471, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=0, j=3, unit_length="kpc" ) == pytest.approx(1519417, 1e-5) assert tracer.arcsec_per_kpc_proper_of_plane(i=1) == pytest.approx( 0.1214785, 1e-5 ) assert tracer.kpc_per_arcsec_proper_of_plane(i=1) == pytest.approx( 8.231907, 1e-5 ) assert tracer.angular_diameter_distance_of_plane_to_earth_in_units( i=1, unit_length="kpc" ) == pytest.approx(1697952, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=1, j=0, unit_length="kpc" ) == pytest.approx(-2694346, 1e-5) assert ( tracer.angular_diameter_distance_between_planes_in_units( i=1, j=1, unit_length="kpc" ) == 0.0 ) assert tracer.angular_diameter_distance_between_planes_in_units( i=1, j=2, unit_length="kpc" ) == pytest.approx(638544, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=1, j=3, unit_length="kpc" ) == pytest.approx(778472, 1e-5) assert tracer.arcsec_per_kpc_proper_of_plane(i=2) == pytest.approx( 0.116500, 1e-5 ) assert tracer.kpc_per_arcsec_proper_of_plane(i=2) == pytest.approx( 8.58368, 1e-5 ) assert tracer.angular_diameter_distance_of_plane_to_earth_in_units( i=2, unit_length="kpc" ) == pytest.approx(1770512, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=2, j=0, unit_length="kpc" ) == pytest.approx(-4435831, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=2, j=1, unit_length="kpc" ) == pytest.approx(-957816) assert ( tracer.angular_diameter_distance_between_planes_in_units( i=2, j=2, unit_length="kpc" ) == 0.0 ) assert tracer.angular_diameter_distance_between_planes_in_units( i=2, j=3, unit_length="kpc" ) == pytest.approx(299564) assert tracer.arcsec_per_kpc_proper_of_plane(i=3) == pytest.approx( 0.12674, 1e-5 ) assert tracer.kpc_per_arcsec_proper_of_plane(i=3) == pytest.approx( 7.89009, 1e-5 ) assert tracer.angular_diameter_distance_of_plane_to_earth_in_units( i=3, unit_length="kpc" ) == pytest.approx(1627448, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=3, j=0, unit_length="kpc" ) == pytest.approx(-5525155, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=3, j=1, unit_length="kpc" ) == pytest.approx(-1556945, 1e-5) assert tracer.angular_diameter_distance_between_planes_in_units( i=3, j=2, unit_length="kpc" ) == pytest.approx(-399419, 1e-5) assert ( tracer.angular_diameter_distance_between_planes_in_units( i=3, j=3, unit_length="kpc" ) == 0.0 ) assert tracer.critical_surface_density_between_planes_in_units( i=0, j=1, unit_length="kpc", unit_mass="solMass" ) == pytest.approx(4.85e9, 1e-2) assert tracer.critical_surface_density_between_planes_in_units( i=0, j=1, unit_length="arcsec", unit_mass="solMass" ) == pytest.approx(17593241668, 1e-2) assert tracer.scaling_factor_between_planes(i=0, j=1) == pytest.approx( 0.9348, 1e-4 ) assert tracer.scaling_factor_between_planes(i=0, j=2) == pytest.approx( 0.984, 1e-4 ) assert tracer.scaling_factor_between_planes(i=0, j=3) == pytest.approx( 1.0, 1e-4 ) assert tracer.scaling_factor_between_planes(i=1, j=2) == pytest.approx( 0.754, 1e-4 ) assert tracer.scaling_factor_between_planes(i=1, j=3) == pytest.approx( 1.0, 1e-4 ) assert tracer.scaling_factor_between_planes(i=2, j=3) == pytest.approx( 1.0, 1e-4 ) def test__6_galaxies__tracer_planes_are_correct(self): g0 = al.Galaxy(redshift=2.0) g1 = al.Galaxy(redshift=2.0) g2 = al.Galaxy(redshift=0.1) g3 = al.Galaxy(redshift=3.0) g4 = al.Galaxy(redshift=1.0) g5 = al.Galaxy(redshift=3.0) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2, g3, g4, g5], cosmology=cosmo.Planck15 ) assert tracer.planes[0].galaxies == [g2] assert tracer.planes[1].galaxies == [g4] assert tracer.planes[2].galaxies == [g0, g1] assert tracer.planes[3].galaxies == [g3, g5] class TestAbstractTracerLensing: class TestTracedGridsFromGrid: def test__x2_planes__no_galaxy__image_and_source_planes_setup__same_coordinates( self, sub_grid_7x7 ): tracer = al.Tracer.from_galaxies( galaxies=[al.Galaxy(redshift=0.5), al.Galaxy(redshift=1.0)] ) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7 ) assert traced_grids_of_planes[0][0] == pytest.approx( np.array([1.25, -1.25]), 1e-3 ) assert traced_grids_of_planes[0][1] == pytest.approx( np.array([1.25, -0.75]), 1e-3 ) assert traced_grids_of_planes[0][2] == pytest.approx( np.array([0.75, -1.25]), 1e-3 ) assert traced_grids_of_planes[0][3] == pytest.approx( np.array([0.75, -0.75]), 1e-3 ) assert traced_grids_of_planes[1][0] == pytest.approx( np.array([1.25, -1.25]), 1e-3 ) assert traced_grids_of_planes[1][1] == pytest.approx( np.array([1.25, -0.75]), 1e-3 ) assert traced_grids_of_planes[1][2] == pytest.approx( np.array([0.75, -1.25]), 1e-3 ) assert traced_grids_of_planes[1][3] == pytest.approx( np.array([0.75, -0.75]), 1e-3 ) def test__x2_planes__sis_lens__traced_grid_includes_deflections__on_planes_setup( self, sub_grid_7x7_simple, gal_x1_mp ): tracer = al.Tracer.from_galaxies( galaxies=[gal_x1_mp, al.Galaxy(redshift=1.0)] ) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7_simple ) assert traced_grids_of_planes[0][0] == pytest.approx( np.array([1.0, 1.0]), 1e-3 ) assert traced_grids_of_planes[0][1] == pytest.approx( np.array([1.0, 0.0]), 1e-3 ) assert traced_grids_of_planes[0][2] == pytest.approx( np.array([1.0, 1.0]), 1e-3 ) assert traced_grids_of_planes[0][3] == pytest.approx( np.array([1.0, 0.0]), 1e-3 ) assert traced_grids_of_planes[1][0] == pytest.approx( np.array([1.0 - 0.707, 1.0 - 0.707]), 1e-3 ) assert traced_grids_of_planes[1][1] == pytest.approx( np.array([0.0, 0.0]), 1e-3 ) assert traced_grids_of_planes[1][2] == pytest.approx( np.array([1.0 - 0.707, 1.0 - 0.707]), 1e-3 ) assert traced_grids_of_planes[1][3] == pytest.approx( np.array([0.0, 0.0]), 1e-3 ) def test__same_as_above_but_2_sis_lenses__deflections_double( self, sub_grid_7x7_simple, gal_x1_mp ): tracer = al.Tracer.from_galaxies( galaxies=[gal_x1_mp, gal_x1_mp, al.Galaxy(redshift=1.0)] ) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7_simple ) assert traced_grids_of_planes[0][0] == pytest.approx( np.array([1.0, 1.0]), 1e-3 ) assert traced_grids_of_planes[0][1] == pytest.approx( np.array([1.0, 0.0]), 1e-3 ) assert traced_grids_of_planes[0][2] == pytest.approx( np.array([1.0, 1.0]), 1e-3 ) assert traced_grids_of_planes[0][3] == pytest.approx( np.array([1.0, 0.0]), 1e-3 ) assert traced_grids_of_planes[1][0] == pytest.approx( np.array([1.0 - 2.0 * 0.707, 1.0 - 2.0 * 0.707]), 1e-3 ) assert traced_grids_of_planes[1][1] == pytest.approx( np.array([-1.0, 0.0]), 1e-3 ) assert traced_grids_of_planes[1][2] == pytest.approx( np.array([1.0 - 2.0 * 0.707, 1.0 - 2.0 * 0.707]), 1e-3 ) assert traced_grids_of_planes[1][3] == pytest.approx( np.array([-1.0, 0.0]), 1e-3 ) def test__4_planes__grids_are_correct__sis_mass_profile( self, sub_grid_7x7_simple ): g0 = al.Galaxy( redshift=2.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=2.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g2 = al.Galaxy( redshift=0.1, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g3 = al.Galaxy( redshift=3.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g4 = al.Galaxy( redshift=1.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g5 = al.Galaxy( redshift=3.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2, g3, g4, g5], cosmology=cosmo.Planck15 ) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7_simple ) # The scaling factors are as follows and were computed independently from the test_autoarray. beta_01 = 0.9348 beta_02 = 0.9839601 # Beta_03 = 1.0 beta_12 = 0.7539734 # Beta_13 = 1.0 # Beta_23 = 1.0 val = np.sqrt(2) / 2.0 assert traced_grids_of_planes[0][0] == pytest.approx( np.array([1.0, 1.0]), 1e-4 ) assert traced_grids_of_planes[0][1] == pytest.approx( np.array([1.0, 0.0]), 1e-4 ) assert traced_grids_of_planes[1][0] == pytest.approx( np.array([(1.0 - beta_01 * val), (1.0 - beta_01 * val)]), 1e-4 ) assert traced_grids_of_planes[1][1] == pytest.approx( np.array([(1.0 - beta_01 * 1.0), 0.0]), 1e-4 ) defl11 = g0.deflections_from_grid( grid=al.grid_irregular.manual_1d( [[(1.0 - beta_01 * val), (1.0 - beta_01 * val)]] ) ) defl12 = g0.deflections_from_grid( grid=al.grid_irregular.manual_1d([[(1.0 - beta_01 * 1.0), 0.0]]) ) assert traced_grids_of_planes[2][0] == pytest.approx( np.array( [ (1.0 - beta_02 * val - beta_12 * defl11[0, 0]), (1.0 - beta_02 * val - beta_12 * defl11[0, 1]), ] ), 1e-4, ) assert traced_grids_of_planes[2][1] == pytest.approx( np.array([(1.0 - beta_02 * 1.0 - beta_12 * defl12[0, 0]), 0.0]), 1e-4 ) assert traced_grids_of_planes[3][1] == pytest.approx( np.array([1.0, 0.0]), 1e-4 ) def test__same_as_above_but_multiple_sets_of_positions(self): import math g0 = al.Galaxy( redshift=2.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=2.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g2 = al.Galaxy( redshift=0.1, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g3 = al.Galaxy( redshift=3.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g4 = al.Galaxy( redshift=1.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g5 = al.Galaxy( redshift=3.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2, g3, g4, g5], cosmology=cosmo.Planck15 ) traced_positions_of_planes = tracer.traced_grids_of_planes_from_grid( grid=al.coordinates([[(1.0, 1.0), (1.0, 1.0)], [(1.0, 1.0)]]) ) # From unit test_autoarray below: # Beta_01 = 0.9348 beta_02 = 0.9839601 # Beta_03 = 1.0 beta_12 = 0.7539734 # Beta_13 = 1.0 # Beta_23 = 1.0 val = math.sqrt(2) / 2.0 assert traced_positions_of_planes[0][0][0] == pytest.approx( (1.0, 1.0), 1e-4 ) assert traced_positions_of_planes[1][0][0] == pytest.approx( ((1.0 - 0.9348 * val), (1.0 - 0.9348 * val)), 1e-4 ) defl11 = g0.deflections_from_grid( grid=al.grid_irregular.manual_1d( [[(1.0 - 0.9348 * val), (1.0 - 0.9348 * val)]] ) ) assert traced_positions_of_planes[2][0][0] == pytest.approx( ( ( 1.0 - beta_02 * val - beta_12 * defl11[0, 0], 1.0 - beta_02 * val - beta_12 * defl11[0, 1], ) ), 1e-4, ) assert traced_positions_of_planes[3][0][0] == pytest.approx( (1.0, 1.0), 1e-4 ) assert traced_positions_of_planes[0][0][1] == pytest.approx( (1.0, 1.0), 1e-4 ) assert traced_positions_of_planes[1][0][1] == pytest.approx( ((1.0 - 0.9348 * val), (1.0 - 0.9348 * val)), 1e-4 ) defl11 = g0.deflections_from_grid( grid=al.grid_irregular.manual_1d( [[(1.0 - 0.9348 * val), (1.0 - 0.9348 * val)]] ) ) assert traced_positions_of_planes[2][0][1] == pytest.approx( ( ( 1.0 - beta_02 * val - beta_12 * defl11[0, 0], 1.0 - beta_02 * val - beta_12 * defl11[0, 1], ) ), 1e-4, ) assert traced_positions_of_planes[3][0][1] == pytest.approx( (1.0, 1.0), 1e-4 ) assert traced_positions_of_planes[0][1][0] == pytest.approx( (1.0, 1.0), 1e-4 ) assert traced_positions_of_planes[1][1][0] == pytest.approx( ((1.0 - 0.9348 * val), (1.0 - 0.9348 * val)), 1e-4 ) defl11 = g0.deflections_from_grid( grid=al.grid_irregular.manual_1d( [[(1.0 - 0.9348 * val), (1.0 - 0.9348 * val)]] ) ) assert traced_positions_of_planes[2][1][0] == pytest.approx( ( ( 1.0 - beta_02 * val - beta_12 * defl11[0, 0], 1.0 - beta_02 * val - beta_12 * defl11[0, 1], ) ), 1e-4, ) assert traced_positions_of_planes[3][1][0] == pytest.approx( (1.0, 1.0), 1e-4 ) def test__positions_are_same_as_grid(self): g0 = al.Galaxy( redshift=2.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=2.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g2 = al.Galaxy( redshift=0.1, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g3 = al.Galaxy( redshift=3.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g4 = al.Galaxy( redshift=1.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g5 = al.Galaxy( redshift=3.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2, g3, g4, g5], cosmology=cosmo.Planck15 ) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=al.grid_irregular.manual_1d([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) ) traced_positions_of_planes = tracer.traced_grids_of_planes_from_grid( grid=al.coordinates([[(1.0, 2.0), (3.0, 4.0)], [(5.0, 6.0)]]) ) assert traced_positions_of_planes[0][0][0] == tuple( traced_grids_of_planes[0][0] ) assert traced_positions_of_planes[1][0][0] == tuple( traced_grids_of_planes[1][0] ) assert traced_positions_of_planes[2][0][0] == tuple( traced_grids_of_planes[2][0] ) assert traced_positions_of_planes[3][0][0] == tuple( traced_grids_of_planes[3][0] ) assert traced_positions_of_planes[0][0][1] == tuple( traced_grids_of_planes[0][1] ) assert traced_positions_of_planes[1][0][1] == tuple( traced_grids_of_planes[1][1] ) assert traced_positions_of_planes[2][0][1] == tuple( traced_grids_of_planes[2][1] ) assert traced_positions_of_planes[3][0][1] == tuple( traced_grids_of_planes[3][1] ) assert traced_positions_of_planes[0][1][0] == tuple( traced_grids_of_planes[0][2] ) assert traced_positions_of_planes[1][1][0] == tuple( traced_grids_of_planes[1][2] ) assert traced_positions_of_planes[2][1][0] == tuple( traced_grids_of_planes[2][2] ) assert traced_positions_of_planes[3][1][0] == tuple( traced_grids_of_planes[3][2] ) def test__x2_planes__sis_lens__upper_plane_limit_removes_final_plane( self, sub_grid_7x7_simple, gal_x1_mp ): tracer = al.Tracer.from_galaxies( galaxies=[gal_x1_mp, al.Galaxy(redshift=1.0)] ) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7_simple, plane_index_limit=0 ) assert traced_grids_of_planes[0][0] == pytest.approx( np.array([1.0, 1.0]), 1e-3 ) assert traced_grids_of_planes[0][1] == pytest.approx( np.array([1.0, 0.0]), 1e-3 ) assert traced_grids_of_planes[0][2] == pytest.approx( np.array([1.0, 1.0]), 1e-3 ) assert traced_grids_of_planes[0][3] == pytest.approx( np.array([1.0, 0.0]), 1e-3 ) assert len(traced_grids_of_planes) == 1 def test__4_planes__grids_are_correct__upper_plane_limit_removes_final_planes( self, sub_grid_7x7_simple ): g0 = al.Galaxy( redshift=2.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=2.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g2 = al.Galaxy( redshift=0.1, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g3 = al.Galaxy( redshift=3.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g4 = al.Galaxy( redshift=1.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g5 = al.Galaxy( redshift=3.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2, g3, g4, g5], cosmology=cosmo.Planck15 ) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7_simple, plane_index_limit=1 ) # The scaling factors are as follows and were computed independently from the test_autoarray. beta_01 = 0.9348 val = np.sqrt(2) / 2.0 assert traced_grids_of_planes[0][0] == pytest.approx( np.array([1.0, 1.0]), 1e-4 ) assert traced_grids_of_planes[0][1] == pytest.approx( np.array([1.0, 0.0]), 1e-4 ) assert traced_grids_of_planes[1][0] == pytest.approx( np.array([(1.0 - beta_01 * val), (1.0 - beta_01 * val)]), 1e-4 ) assert traced_grids_of_planes[1][1] == pytest.approx( np.array([(1.0 - beta_01 * 1.0), 0.0]), 1e-4 ) assert len(traced_grids_of_planes) == 2 class TestProfileImages: def test__x1_plane__single_plane_tracer(self, sub_grid_7x7): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0) ) g1 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) g2 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=3.0) ) image_plane = al.Plane(galaxies=[g0, g1, g2]) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2]) image_plane_profile_image = image_plane.profile_image_from_grid( grid=sub_grid_7x7 ) tracer_profile_image = tracer.profile_image_from_grid(grid=sub_grid_7x7) assert tracer_profile_image.shape_2d == (7, 7) assert (tracer_profile_image == image_plane_profile_image).all() def test__x2_planes__galaxy_light__no_mass__image_sum_of_image_and_source_plane( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0) ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) image_plane = al.Plane(galaxies=[g0]) source_plane = al.Plane(galaxies=[g1]) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) image = image_plane.profile_image_from_grid( grid=sub_grid_7x7 ) + source_plane.profile_image_from_grid(grid=sub_grid_7x7) tracer_profile_image = tracer.profile_image_from_grid(grid=sub_grid_7x7) assert tracer_profile_image.shape_2d == (7, 7) assert image == pytest.approx(tracer_profile_image, 1.0e-4) def test__x2_planes__galaxy_light_mass_sis__source_plane_image_includes_deflections( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0), mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) image_plane = al.Plane(galaxies=[g0]) source_plane_grid = image_plane.traced_grid_from_grid(grid=sub_grid_7x7) source_plane = al.Plane(galaxies=[g1]) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) image = image_plane.profile_image_from_grid( grid=sub_grid_7x7 ) + source_plane.profile_image_from_grid(grid=source_plane_grid) tracer_profile_image = tracer.profile_image_from_grid(grid=sub_grid_7x7) assert image == pytest.approx(tracer_profile_image, 1.0e-4) def test__x2_planes__image__compare_to_galaxy_images(self, sub_grid_7x7): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0) ) g1 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) g2 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=3.0) ) g0_image = g0.profile_image_from_grid(grid=sub_grid_7x7) g1_image = g1.profile_image_from_grid(grid=sub_grid_7x7) g2_image = g2.profile_image_from_grid(grid=sub_grid_7x7) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2]) tracer_profile_image = tracer.profile_image_from_grid(grid=sub_grid_7x7) assert tracer_profile_image == pytest.approx( g0_image + g1_image + g2_image, 1.0e-4 ) def test__x2_planes__returns_image_of_each_plane(self, sub_grid_7x7): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0), mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=1.0), mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) image_plane = al.Plane(galaxies=[g0]) source_plane_grid = image_plane.traced_grid_from_grid(grid=sub_grid_7x7) source_plane = al.Plane(galaxies=[g1]) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) plane_profile_image = image_plane.profile_image_from_grid( grid=sub_grid_7x7 ) + source_plane.profile_image_from_grid(grid=source_plane_grid) tracer_profile_image = tracer.profile_image_from_grid(grid=sub_grid_7x7) assert tracer_profile_image == pytest.approx(plane_profile_image, 1.0e-4) def test__x3_planes___light_no_mass_in_each_plane__image_of_each_plane_is_galaxy_image( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.1, light_profile=al.lp.EllipticalSersic(intensity=0.1) ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=0.2) ) g2 = al.Galaxy( redshift=2.0, light_profile=al.lp.EllipticalSersic(intensity=0.3) ) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2], cosmology=cosmo.Planck15 ) plane_0 = al.Plane(galaxies=[g0]) plane_1 = al.Plane(galaxies=[g1]) plane_2 = al.Plane(galaxies=[g2]) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7 ) image = ( plane_0.profile_image_from_grid(grid=sub_grid_7x7) + plane_1.profile_image_from_grid(grid=traced_grids_of_planes[1]) + plane_2.profile_image_from_grid(grid=traced_grids_of_planes[2]) ) tracer_profile_image = tracer.profile_image_from_grid(grid=sub_grid_7x7) assert image.shape_2d == (7, 7) assert image == pytest.approx(tracer_profile_image, 1.0e-4) def test__x3_planes__galaxy_light_mass_sis__source_plane_image_includes_deflections( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.1, light_profile=al.lp.EllipticalSersic(intensity=0.1) ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=0.2) ) g2 = al.Galaxy( redshift=2.0, light_profile=al.lp.EllipticalSersic(intensity=0.3) ) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2], cosmology=cosmo.Planck15 ) plane_0 = tracer.planes[0] plane_1 = tracer.planes[1] plane_2 = tracer.planes[2] traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7 ) image = ( plane_0.profile_image_from_grid(grid=sub_grid_7x7) + plane_1.profile_image_from_grid(grid=traced_grids_of_planes[1]) + plane_2.profile_image_from_grid(grid=traced_grids_of_planes[2]) ) tracer_profile_image = tracer.profile_image_from_grid(grid=sub_grid_7x7) assert image.shape_2d == (7, 7) assert image == pytest.approx(tracer_profile_image, 1.0e-4) def test__x3_planes__same_as_above_more_galaxies(self, sub_grid_7x7): g0 = al.Galaxy( redshift=0.1, light_profile=al.lp.EllipticalSersic(intensity=0.1) ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=0.2) ) g2 = al.Galaxy( redshift=2.0, light_profile=al.lp.EllipticalSersic(intensity=0.3) ) g3 = al.Galaxy( redshift=0.1, light_profile=al.lp.EllipticalSersic(intensity=0.4) ) g4 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=0.5) ) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2, g3, g4], cosmology=cosmo.Planck15 ) plane_0 = al.Plane(galaxies=[g0, g3]) plane_1 = al.Plane(galaxies=[g1, g4]) plane_2 = al.Plane(galaxies=[g2]) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7 ) image = ( plane_0.profile_image_from_grid(grid=sub_grid_7x7) + plane_1.profile_image_from_grid(grid=traced_grids_of_planes[1]) + plane_2.profile_image_from_grid(grid=traced_grids_of_planes[2]) ) tracer_profile_image = tracer.profile_image_from_grid(grid=sub_grid_7x7) assert image.shape_2d == (7, 7) assert image == pytest.approx(tracer_profile_image, 1.0e-4) def test__profile_images_of_planes__planes_without_light_profiles_are_all_zeros( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.1, light_profile=al.lp.EllipticalSersic(intensity=0.1) ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=0.2) ) g2 = al.Galaxy(redshift=2.0) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2], cosmology=cosmo.Planck15 ) plane_0 = al.Plane(galaxies=[g0]) plane_1 = al.Plane(galaxies=[g1]) plane_0_image = plane_0.profile_image_from_grid(grid=sub_grid_7x7) plane_1_image = plane_1.profile_image_from_grid(grid=sub_grid_7x7) tracer_profile_image_of_planes = tracer.profile_images_of_planes_from_grid( grid=sub_grid_7x7 ) assert len(tracer_profile_image_of_planes) == 3 assert tracer_profile_image_of_planes[0].shape_2d == (7, 7) assert tracer_profile_image_of_planes[0] == pytest.approx( plane_0_image, 1.0e-4 ) assert tracer_profile_image_of_planes[1].shape_2d == (7, 7) assert tracer_profile_image_of_planes[1] == pytest.approx( plane_1_image, 1.0e-4 ) assert tracer_profile_image_of_planes[2].shape_2d == (7, 7) assert ( tracer_profile_image_of_planes[2].in_2d_binned == np.zeros((7, 7)) ).all() def test__x1_plane__padded_image__compare_to_galaxy_images_using_padded_grid_stack( self, sub_grid_7x7 ): padded_grid = sub_grid_7x7.padded_grid_from_kernel_shape( kernel_shape_2d=(3, 3) ) g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0) ) g1 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) g2 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=3.0) ) padded_g0_image = g0.profile_image_from_grid(grid=padded_grid) padded_g1_image = g1.profile_image_from_grid(grid=padded_grid) padded_g2_image = g2.profile_image_from_grid(grid=padded_grid) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2]) padded_tracer_profile_image = tracer.padded_profile_image_from_grid_and_psf_shape( grid=sub_grid_7x7, psf_shape_2d=(3, 3) ) assert padded_tracer_profile_image.shape_2d == (9, 9) assert padded_tracer_profile_image == pytest.approx( padded_g0_image + padded_g1_image + padded_g2_image, 1.0e-4 ) def test__x3_planes__padded_2d_image_from_plane__mapped_correctly( self, sub_grid_7x7 ): padded_grid = sub_grid_7x7.padded_grid_from_kernel_shape( kernel_shape_2d=(3, 3) ) g0 = al.Galaxy( redshift=0.1, light_profile=al.lp.EllipticalSersic(intensity=0.1) ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=0.2) ) g2 = al.Galaxy( redshift=2.0, light_profile=al.lp.EllipticalSersic(intensity=0.3) ) padded_g0_image = g0.profile_image_from_grid(grid=padded_grid) padded_g1_image = g1.profile_image_from_grid(grid=padded_grid) padded_g2_image = g2.profile_image_from_grid(grid=padded_grid) tracer = al.Tracer.from_galaxies( galaxies=[g0, g1, g2], cosmology=cosmo.Planck15 ) padded_tracer_profile_image = tracer.padded_profile_image_from_grid_and_psf_shape( grid=sub_grid_7x7, psf_shape_2d=(3, 3) ) assert padded_tracer_profile_image.shape_2d == (9, 9) assert padded_tracer_profile_image == pytest.approx( padded_g0_image + padded_g1_image + padded_g2_image, 1.0e-4 ) def test__galaxy_image_dict_from_grid(self, sub_grid_7x7): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0) ) g1 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), light_profile=al.lp.EllipticalSersic(intensity=2.0), ) g2 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=3.0) ) g3 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=5.0) ) g0_image = g0.profile_image_from_grid(grid=sub_grid_7x7) g1_image = g1.profile_image_from_grid(grid=sub_grid_7x7) g2_image = g2.profile_image_from_grid(grid=sub_grid_7x7) g1_deflections = g1.deflections_from_grid(grid=sub_grid_7x7) source_grid_7x7 = sub_grid_7x7 - g1_deflections g3_image = g3.profile_image_from_grid(grid=source_grid_7x7) tracer = al.Tracer.from_galaxies( galaxies=[g3, g1, g0, g2], cosmology=cosmo.Planck15 ) image_1d_dict = tracer.galaxy_profile_image_dict_from_grid( grid=sub_grid_7x7 ) assert (image_1d_dict[g0].in_1d == g0_image).all() assert (image_1d_dict[g1].in_1d == g1_image).all() assert (image_1d_dict[g2].in_1d == g2_image).all() assert (image_1d_dict[g3].in_1d == g3_image).all() image_dict = tracer.galaxy_profile_image_dict_from_grid(grid=sub_grid_7x7) assert (image_dict[g0].in_2d == g0_image.in_2d).all() assert (image_dict[g1].in_2d == g1_image.in_2d).all() assert (image_dict[g2].in_2d == g2_image.in_2d).all() assert (image_dict[g3].in_2d == g3_image.in_2d).all() class TestConvergence: def test__galaxy_mass_sis__no_source_plane_convergence(self, sub_grid_7x7): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy(redshift=0.5) image_plane = al.Plane(galaxies=[g0]) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) image_plane_convergence = image_plane.convergence_from_grid( grid=sub_grid_7x7 ) tracer_convergence = tracer.convergence_from_grid(grid=sub_grid_7x7) assert image_plane_convergence.shape_2d == (7, 7) assert (image_plane_convergence == tracer_convergence).all() def test__galaxy_entered_3_times__both_planes__different_convergence_for_each( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=2.0), ) g2 = al.Galaxy( redshift=1.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=3.0), ) g0_convergence = g0.convergence_from_grid(grid=sub_grid_7x7) g1_convergence = g1.convergence_from_grid(grid=sub_grid_7x7) g2_convergence = g2.convergence_from_grid(grid=sub_grid_7x7) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2]) image_plane_convergence = tracer.image_plane.convergence_from_grid( grid=sub_grid_7x7 ) source_plane_convergence = tracer.source_plane.convergence_from_grid( grid=sub_grid_7x7 ) tracer_convergence = tracer.convergence_from_grid(grid=sub_grid_7x7) assert image_plane_convergence == pytest.approx( g0_convergence + g1_convergence, 1.0e-4 ) assert (source_plane_convergence == g2_convergence).all() assert tracer_convergence == pytest.approx( g0_convergence + g1_convergence + g2_convergence, 1.0e-4 ) def test__galaxy_entered_2_times__grid_is_positions(self, positions_7x7): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=2.0), ) g0_convergence = g0.convergence_from_grid(grid=positions_7x7) g1_convergence = g1.convergence_from_grid(grid=positions_7x7) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) image_plane_convergence = tracer.image_plane.convergence_from_grid( grid=positions_7x7 ) source_plane_convergence = tracer.source_plane.convergence_from_grid( grid=positions_7x7 ) tracer_convergence = tracer.convergence_from_grid(grid=positions_7x7) assert image_plane_convergence[0][0] == pytest.approx( g0_convergence[0][0] + g1_convergence[0][0], 1.0e-4 ) assert tracer_convergence[0][0] == pytest.approx( g0_convergence[0][0] + g1_convergence[0][0], 1.0e-4 ) def test__no_galaxy_has_mass_profile__convergence_returned_as_zeros( self, sub_grid_7x7 ): tracer = al.Tracer.from_galaxies( galaxies=[al.Galaxy(redshift=0.5), al.Galaxy(redshift=0.5)] ) assert ( tracer.convergence_from_grid(grid=sub_grid_7x7).in_2d_binned == np.zeros(shape=(7, 7)) ).all() tracer = al.Tracer.from_galaxies( galaxies=[al.Galaxy(redshift=0.1), al.Galaxy(redshift=0.2)] ) assert ( tracer.convergence_from_grid(grid=sub_grid_7x7).in_2d_binned == np.zeros(shape=(7, 7)) ).all() class TestPotential: def test__galaxy_mass_sis__no_source_plane_potential(self, sub_grid_7x7): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy(redshift=0.5) image_plane = al.Plane(galaxies=[g0]) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) image_plane_potential = image_plane.potential_from_grid(grid=sub_grid_7x7) tracer_potential = tracer.potential_from_grid(grid=sub_grid_7x7) assert image_plane_potential.shape_2d == (7, 7) assert (image_plane_potential == tracer_potential).all() def test__galaxy_entered_3_times__both_planes__different_potential_for_each( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=2.0), ) g2 = al.Galaxy( redshift=1.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=3.0), ) g0_potential = g0.potential_from_grid(grid=sub_grid_7x7) g1_potential = g1.potential_from_grid(grid=sub_grid_7x7) g2_potential = g2.potential_from_grid(grid=sub_grid_7x7) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2]) image_plane_potential = tracer.image_plane.potential_from_grid( grid=sub_grid_7x7 ) source_plane_potential = tracer.source_plane.potential_from_grid( grid=sub_grid_7x7 ) tracer_potential = tracer.potential_from_grid(grid=sub_grid_7x7) assert image_plane_potential == pytest.approx( g0_potential + g1_potential, 1.0e-4 ) assert (source_plane_potential == g2_potential).all() assert tracer_potential == pytest.approx( g0_potential + g1_potential + g2_potential, 1.0e-4 ) def test__galaxy_entered_2_times__grid_is_positions(self, positions_7x7): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=2.0), ) g0_potential = g0.potential_from_grid(grid=positions_7x7) g1_potential = g1.potential_from_grid(grid=positions_7x7) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) image_plane_potential = tracer.image_plane.potential_from_grid( grid=positions_7x7 ) source_plane_potential = tracer.source_plane.potential_from_grid( grid=positions_7x7 ) tracer_potential = tracer.potential_from_grid(grid=positions_7x7) assert image_plane_potential[0][0] == pytest.approx( g0_potential[0][0] + g1_potential[0][0], 1.0e-4 ) assert tracer_potential[0][0] == pytest.approx( g0_potential[0][0] + g1_potential[0][0], 1.0e-4 ) def test__no_galaxy_has_mass_profile__potential_returned_as_zeros( self, sub_grid_7x7 ): tracer = al.Tracer.from_galaxies( galaxies=[al.Galaxy(redshift=0.5), al.Galaxy(redshift=0.5)] ) assert ( tracer.potential_from_grid(grid=sub_grid_7x7).in_2d_binned == np.zeros(shape=(7, 7)) ).all() tracer = al.Tracer.from_galaxies( galaxies=[al.Galaxy(redshift=0.1), al.Galaxy(redshift=0.2)] ) assert ( tracer.potential_from_grid(grid=sub_grid_7x7).in_2d_binned == np.zeros(shape=(7, 7)) ).all() class TestDeflectionsOfSummedPlanes: def test__galaxy_mass_sis__source_plane_no_mass__deflections_is_ignored( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy(redshift=0.5) image_plane = al.Plane(galaxies=[g0]) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) image_plane_deflections = image_plane.deflections_from_grid( grid=sub_grid_7x7 ) tracer_deflections = tracer.deflections_of_planes_summed_from_grid( grid=sub_grid_7x7 ) assert tracer_deflections.shape_2d == (7, 7) assert (image_plane_deflections == tracer_deflections).all() def test__galaxy_entered_3_times__different_deflections_for_each( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=2.0), ) g2 = al.Galaxy( redshift=1.0, mass_profile=al.mp.SphericalIsothermal(einstein_radius=3.0), ) g0_deflections = g0.deflections_from_grid(grid=sub_grid_7x7) g1_deflections = g1.deflections_from_grid(grid=sub_grid_7x7) g2_deflections = g2.deflections_from_grid(grid=sub_grid_7x7) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2]) image_plane_deflections = tracer.image_plane.deflections_from_grid( grid=sub_grid_7x7 ) source_plane_deflections = tracer.source_plane.deflections_from_grid( grid=sub_grid_7x7 ) tracer_deflections = tracer.deflections_of_planes_summed_from_grid( grid=sub_grid_7x7 ) assert image_plane_deflections == pytest.approx( g0_deflections + g1_deflections, 1.0e-4 ) assert source_plane_deflections == pytest.approx(g2_deflections, 1.0e-4) assert tracer_deflections == pytest.approx( g0_deflections + g1_deflections + g2_deflections, 1.0e-4 ) def test__galaxy_entered_2_times__grid_is_positions(self, positions_7x7): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=2.0), ) g0_deflections = g0.deflections_from_grid(grid=positions_7x7) g1_deflections = g1.deflections_from_grid(grid=positions_7x7) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) image_plane_deflections = tracer.image_plane.deflections_from_grid( grid=positions_7x7 ) tracer_deflections = tracer.deflections_of_planes_summed_from_grid( grid=positions_7x7 ) assert image_plane_deflections[0][0][0] == pytest.approx( g0_deflections[0][0][0] + g1_deflections[0][0][0], 1.0e-4 ) assert image_plane_deflections[0][0][1] == pytest.approx( g0_deflections[0][0][1] + g1_deflections[0][0][1], 1.0e-4 ) assert tracer_deflections[0][0][0] == pytest.approx( g0_deflections[0][0][0] + g1_deflections[0][0][0], 1.0e-4 ) assert tracer_deflections[0][0][1] == pytest.approx( g0_deflections[0][0][1] + g1_deflections[0][0][1], 1.0e-4 ) def test__no_galaxy_has_mass_profile__deflections_returned_as_zeros( self, sub_grid_7x7 ): tracer = al.Tracer.from_galaxies( galaxies=[al.Galaxy(redshift=0.5), al.Galaxy(redshift=0.5)] ) tracer_deflections = tracer.deflections_of_planes_summed_from_grid( grid=sub_grid_7x7 ) assert ( tracer_deflections.in_2d_binned[:, :, 0] == np.zeros(shape=(7, 7)) ).all() assert ( tracer_deflections.in_2d_binned[:, :, 1] == np.zeros(shape=(7, 7)) ).all() class TestGridAtRedshift: def test__lens_z05_source_z01_redshifts__match_planes_redshifts__gives_same_grids( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=1.0 ), ) g1 = al.Galaxy(redshift=1.0) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) grid_at_redshift = tracer.grid_at_redshift_from_grid_and_redshift( grid=sub_grid_7x7, redshift=0.5 ) assert (grid_at_redshift == sub_grid_7x7).all() grid_at_redshift = tracer.grid_at_redshift_from_grid_and_redshift( grid=sub_grid_7x7, redshift=1.0 ) source_plane_grid = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7 )[1] assert (grid_at_redshift == source_plane_grid).all() def test__same_as_above_but_for_multi_tracing(self, sub_grid_7x7): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=1.0 ), ) g1 = al.Galaxy( redshift=0.75, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=2.0 ), ) g2 = al.Galaxy( redshift=1.5, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=3.0 ), ) g3 = al.Galaxy( redshift=1.0, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=4.0 ), ) g4 = al.Galaxy(redshift=2.0) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2, g3, g4]) traced_grids_of_planes = tracer.traced_grids_of_planes_from_grid( grid=sub_grid_7x7 ) grid_at_redshift = tracer.grid_at_redshift_from_grid_and_redshift( grid=sub_grid_7x7, redshift=0.5 ) assert grid_at_redshift == pytest.approx(traced_grids_of_planes[0], 1.0e-4) grid_at_redshift = tracer.grid_at_redshift_from_grid_and_redshift( grid=sub_grid_7x7, redshift=0.75 ) assert grid_at_redshift == pytest.approx(traced_grids_of_planes[1], 1.0e-4) grid_at_redshift = tracer.grid_at_redshift_from_grid_and_redshift( grid=sub_grid_7x7, redshift=1.0 ) assert grid_at_redshift == pytest.approx(traced_grids_of_planes[2], 1.0e-4) grid_at_redshift = tracer.grid_at_redshift_from_grid_and_redshift( grid=sub_grid_7x7, redshift=1.5 ) assert grid_at_redshift == pytest.approx(traced_grids_of_planes[3], 1.0e-4) grid_at_redshift = tracer.grid_at_redshift_from_grid_and_redshift( grid=sub_grid_7x7, redshift=2.0 ) assert grid_at_redshift == pytest.approx(traced_grids_of_planes[4], 1.0e-4) def test__input_redshift_between_two_planes__two_planes_between_earth_and_input_redshift( self, sub_grid_7x7 ): sub_grid_7x7[0] = np.array([[1.0, -1.0]]) sub_grid_7x7[1] = np.array([[1.0, 0.0]]) g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=1.0 ), ) g1 = al.Galaxy( redshift=0.75, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=2.0 ), ) g2 = al.Galaxy(redshift=2.0) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2]) grid_at_redshift = tracer.grid_at_redshift_from_grid_and_redshift( grid=sub_grid_7x7, redshift=1.9 ) assert grid_at_redshift[0][0] == pytest.approx(-1.06587, 1.0e-1) assert grid_at_redshift[0][1] == pytest.approx(1.06587, 1.0e-1) assert grid_at_redshift[1][0] == pytest.approx(-1.921583, 1.0e-1) assert grid_at_redshift[1][1] == pytest.approx(0.0, 1.0e-1) def test__input_redshift_before_first_plane__returns_image_plane( self, sub_grid_7x7 ): g0 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=1.0 ), ) g1 = al.Galaxy( redshift=0.75, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=2.0 ), ) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) grid_at_redshift = tracer.grid_at_redshift_from_grid_and_redshift( grid=sub_grid_7x7.geometry.unmasked_grid, redshift=0.3 ) assert (grid_at_redshift == sub_grid_7x7.geometry.unmasked_grid).all() class TestMultipleImages: def test__simple_isothermal_case_positions_are_correct(self): grid = al.grid.uniform(shape_2d=(100, 100), pixel_scales=0.05, sub_size=1) g0 = al.Galaxy( redshift=0.5, mass=al.mp.EllipticalIsothermal( centre=(0.001, 0.001), einstein_radius=1.0, axis_ratio=0.8 ), ) g1 = al.Galaxy(redshift=1.0) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) coordinates = tracer.image_plane_multiple_image_positions( grid=grid, source_plane_coordinate=(0.0, 0.0) ) assert coordinates[0][0] == pytest.approx((1.025, -0.025), 1.0e-4) assert coordinates[0][1] == pytest.approx((0.025, -0.975), 1.0e-4) assert coordinates[0][2] == pytest.approx((0.025, 0.975), 1.0e-4) assert coordinates[0][3] == pytest.approx((-1.025, -0.025), 1.0e-4) assert coordinates.scaled[0][0] == pytest.approx((1.025, -0.025), 1.0e-4) assert coordinates.scaled[0][1] == pytest.approx((0.025, -0.975), 1.0e-4) assert coordinates.scaled[0][2] == pytest.approx((0.025, 0.975), 1.0e-4) assert coordinates.scaled[0][3] == pytest.approx((-1.025, -0.025), 1.0e-4) assert coordinates.pixels == [[(29, 49), (49, 30), (49, 69), (70, 49)]] def test__multiple_image_coordinate_of_light_profile_centres_of_source_plane( self ): grid = al.grid.uniform(shape_2d=(50, 50), pixel_scales=0.05, sub_size=4) g0 = al.Galaxy( redshift=0.5, mass=al.mp.EllipticalIsothermal( centre=(0.0, 0.0), einstein_radius=1.0, axis_ratio=0.9 ), ) g1 = al.Galaxy( redshift=1.0, light=al.lp.SphericalGaussian(centre=(0.0, 0.0)) ) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) coordinates_manual = tracer.image_plane_multiple_image_positions( grid=grid, source_plane_coordinate=(0.0, 0.0) ) assert coordinates_manual.pixels == [[(4, 24), (45, 24)]] assert ( coordinates_manual.scaled == tracer.image_plane_multiple_image_positions_of_galaxies(grid=grid)[0] ) class TestContributionMap: def test__contribution_maps_are_same_as_hyper_galaxy_calculation(self): hyper_model_image = al.array.manual_2d([[2.0, 4.0, 10.0]]) hyper_galaxy_image = al.array.manual_2d([[1.0, 5.0, 8.0]]) hyper_galaxy_0 = al.HyperGalaxy(contribution_factor=5.0) hyper_galaxy_1 = al.HyperGalaxy(contribution_factor=10.0) galaxy_0 = al.Galaxy( redshift=0.5, hyper_galaxy=hyper_galaxy_0, hyper_model_image=hyper_model_image, hyper_galaxy_image=hyper_galaxy_image, ) galaxy_1 = al.Galaxy( redshift=1.0, hyper_galaxy=hyper_galaxy_1, hyper_model_image=hyper_model_image, hyper_galaxy_image=hyper_galaxy_image, ) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_0, galaxy_1]) assert ( tracer.contribution_map == tracer.image_plane.contribution_map + tracer.source_plane.contribution_map ).all() assert ( tracer.contribution_maps_of_planes[0].in_1d == tracer.image_plane.contribution_map ).all() assert ( tracer.contribution_maps_of_planes[1].in_1d == tracer.source_plane.contribution_map ).all() galaxy_0 = al.Galaxy(redshift=0.5) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_0, galaxy_1]) assert ( tracer.contribution_map == tracer.source_plane.contribution_map ).all() assert tracer.contribution_maps_of_planes[0] == None assert ( tracer.contribution_maps_of_planes[1].in_1d == tracer.source_plane.contribution_map ).all() galaxy_1 = al.Galaxy(redshift=1.0) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_0, galaxy_1]) assert tracer.contribution_map == None assert tracer.contribution_maps_of_planes[0] == None assert tracer.contribution_maps_of_planes[1] == None class TestLensingObject: def test__correct_einstein_mass_caclulated_for_multiple_mass_profiles__means_all_innherited_methods_work( self ): sis_0 = al.mp.SphericalIsothermal(centre=(0.0, 0.0), einstein_radius=0.2) sis_1 = al.mp.SphericalIsothermal(centre=(0.0, 0.0), einstein_radius=0.4) sis_2 = al.mp.SphericalIsothermal(centre=(0.0, 0.0), einstein_radius=0.6) sis_3 = al.mp.SphericalIsothermal(centre=(0.0, 0.0), einstein_radius=0.8) galaxy_0 = al.Galaxy( mass_profile_0=sis_0, mass_profile_1=sis_1, redshift=0.5 ) galaxy_1 = al.Galaxy( mass_profile_0=sis_2, mass_profile_1=sis_3, redshift=0.5 ) plane = al.Plane(galaxies=[galaxy_0, galaxy_1]) tracer = al.Tracer( planes=[plane, al.Plane(redshift=1.0)], cosmology=cosmo.Planck15 ) assert tracer.einstein_mass_in_units(unit_mass="angular") == pytest.approx( np.pi * 2.0 ** 2.0, 1.0e-1 ) class TestAbstractTracerData: class TestBlurredProfileImages: def test__blurred_image_from_grid_and_psf( self, sub_grid_7x7, blurring_grid_7x7, psf_3x3 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0), mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) plane_0 = al.Plane(redshift=0.5, galaxies=[g0]) plane_1 = al.Plane(redshift=1.0, galaxies=[g1]) blurred_image_0 = plane_0.blurred_profile_image_from_grid_and_psf( grid=sub_grid_7x7, psf=psf_3x3, blurring_grid=blurring_grid_7x7 ) source_grid_7x7 = plane_0.traced_grid_from_grid(grid=sub_grid_7x7) source_blurring_grid_7x7 = plane_0.traced_grid_from_grid( grid=blurring_grid_7x7 ) blurred_image_1 = plane_1.blurred_profile_image_from_grid_and_psf( grid=source_grid_7x7, psf=psf_3x3, blurring_grid=source_blurring_grid_7x7, ) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=cosmo.Planck15) blurred_image = tracer.blurred_profile_image_from_grid_and_psf( grid=sub_grid_7x7, psf=psf_3x3, blurring_grid=blurring_grid_7x7 ) assert blurred_image.in_1d == pytest.approx( blurred_image_0.in_1d + blurred_image_1.in_1d, 1.0e-4 ) assert blurred_image.in_2d == pytest.approx( blurred_image_0.in_2d + blurred_image_1.in_2d, 1.0e-4 ) def test__blurred_images_of_planes_from_grid_and_psf( self, sub_grid_7x7, blurring_grid_7x7, psf_3x3 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0), mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) plane_0 = al.Plane(redshift=0.5, galaxies=[g0]) plane_1 = al.Plane(redshift=1.0, galaxies=[g1]) blurred_image_0 = plane_0.blurred_profile_image_from_grid_and_psf( grid=sub_grid_7x7, psf=psf_3x3, blurring_grid=blurring_grid_7x7 ) source_grid_7x7 = plane_0.traced_grid_from_grid(grid=sub_grid_7x7) source_blurring_grid_7x7 = plane_0.traced_grid_from_grid( grid=blurring_grid_7x7 ) blurred_image_1 = plane_1.blurred_profile_image_from_grid_and_psf( grid=source_grid_7x7, psf=psf_3x3, blurring_grid=source_blurring_grid_7x7, ) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=cosmo.Planck15) blurred_images = tracer.blurred_profile_images_of_planes_from_grid_and_psf( grid=sub_grid_7x7, psf=psf_3x3, blurring_grid=blurring_grid_7x7 ) assert (blurred_images[0].in_1d == blurred_image_0.in_1d).all() assert (blurred_images[1].in_1d == blurred_image_1.in_1d).all() assert (blurred_images[0].in_2d == blurred_image_0.in_2d).all() assert (blurred_images[1].in_2d == blurred_image_1.in_2d).all() def test__blurred_image_from_grid_and_convolver( self, sub_grid_7x7, blurring_grid_7x7, convolver_7x7 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0), mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) plane_0 = al.Plane(redshift=0.5, galaxies=[g0]) plane_1 = al.Plane(redshift=1.0, galaxies=[g1]) blurred_image_0 = plane_0.blurred_profile_image_from_grid_and_convolver( grid=sub_grid_7x7, convolver=convolver_7x7, blurring_grid=blurring_grid_7x7, ) source_grid_7x7 = plane_0.traced_grid_from_grid(grid=sub_grid_7x7) source_blurring_grid_7x7 = plane_0.traced_grid_from_grid( grid=blurring_grid_7x7 ) blurred_image_1 = plane_1.blurred_profile_image_from_grid_and_convolver( grid=source_grid_7x7, convolver=convolver_7x7, blurring_grid=source_blurring_grid_7x7, ) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=cosmo.Planck15) blurred_image = tracer.blurred_profile_image_from_grid_and_convolver( grid=sub_grid_7x7, convolver=convolver_7x7, blurring_grid=blurring_grid_7x7, ) assert blurred_image.in_1d == pytest.approx( blurred_image_0.in_1d + blurred_image_1.in_1d, 1.0e-4 ) assert blurred_image.in_2d == pytest.approx( blurred_image_0.in_2d + blurred_image_1.in_2d, 1.0e-4 ) def test__blurred_images_of_planes_from_grid_and_convolver( self, sub_grid_7x7, blurring_grid_7x7, convolver_7x7 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0), mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) plane_0 = al.Plane(redshift=0.5, galaxies=[g0]) plane_1 = al.Plane(redshift=1.0, galaxies=[g1]) blurred_image_0 = plane_0.blurred_profile_image_from_grid_and_convolver( grid=sub_grid_7x7, convolver=convolver_7x7, blurring_grid=blurring_grid_7x7, ) source_grid_7x7 = plane_0.traced_grid_from_grid(grid=sub_grid_7x7) source_blurring_grid_7x7 = plane_0.traced_grid_from_grid( grid=blurring_grid_7x7 ) blurred_image_1 = plane_1.blurred_profile_image_from_grid_and_convolver( grid=source_grid_7x7, convolver=convolver_7x7, blurring_grid=source_blurring_grid_7x7, ) tracer = al.Tracer(planes=[plane_0, plane_1], cosmology=cosmo.Planck15) blurred_images = tracer.blurred_profile_images_of_planes_from_grid_and_convolver( grid=sub_grid_7x7, convolver=convolver_7x7, blurring_grid=blurring_grid_7x7, ) assert (blurred_images[0].in_1d == blurred_image_0.in_1d).all() assert (blurred_images[1].in_1d == blurred_image_1.in_1d).all() assert (blurred_images[0].in_2d == blurred_image_0.in_2d).all() assert (blurred_images[1].in_2d == blurred_image_1.in_2d).all() def test__galaxy_blurred_image_dict_from_grid_and_convolver( self, sub_grid_7x7, blurring_grid_7x7, convolver_7x7 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0) ) g1 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), light_profile=al.lp.EllipticalSersic(intensity=2.0), ) g2 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=3.0) ) g3 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=5.0) ) g0_blurred_image = g0.blurred_profile_image_from_grid_and_convolver( grid=sub_grid_7x7, convolver=convolver_7x7, blurring_grid=blurring_grid_7x7, ) g1_blurred_image = g1.blurred_profile_image_from_grid_and_convolver( grid=sub_grid_7x7, convolver=convolver_7x7, blurring_grid=blurring_grid_7x7, ) g2_blurred_image = g2.blurred_profile_image_from_grid_and_convolver( grid=sub_grid_7x7, convolver=convolver_7x7, blurring_grid=blurring_grid_7x7, ) g1_deflections = g1.deflections_from_grid(grid=sub_grid_7x7) source_grid_7x7 = sub_grid_7x7 - g1_deflections g1_blurring_deflections = g1.deflections_from_grid(grid=blurring_grid_7x7) source_blurring_grid_7x7 = blurring_grid_7x7 - g1_blurring_deflections g3_blurred_image = g3.blurred_profile_image_from_grid_and_convolver( grid=source_grid_7x7, convolver=convolver_7x7, blurring_grid=source_blurring_grid_7x7, ) tracer = al.Tracer.from_galaxies( galaxies=[g3, g1, g0, g2], cosmology=cosmo.Planck15 ) blurred_image_dict = tracer.galaxy_blurred_profile_image_dict_from_grid_and_convolver( grid=sub_grid_7x7, convolver=convolver_7x7, blurring_grid=blurring_grid_7x7, ) assert (blurred_image_dict[g0].in_1d == g0_blurred_image.in_1d).all() assert (blurred_image_dict[g1].in_1d == g1_blurred_image.in_1d).all() assert (blurred_image_dict[g2].in_1d == g2_blurred_image.in_1d).all() assert (blurred_image_dict[g3].in_1d == g3_blurred_image.in_1d).all() class TestUnmaskedBlurredProfileImages: def test__unmasked_images_of_tracer_planes_and_galaxies(self): psf = al.kernel.manual_2d( array=(np.array([[0.0, 3.0, 0.0], [0.0, 1.0, 2.0], [0.0, 0.0, 0.0]])), pixel_scales=1.0, ) mask = al.mask.manual( mask_2d=np.array( [[True, True, True], [True, False, True], [True, True, True]] ), pixel_scales=1.0, sub_size=1, ) grid = al.masked.grid.from_mask(mask=mask) g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=0.1) ) g1 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=0.2) ) g2 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=0.3) ) g3 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=0.4) ) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1, g2, g3]) padded_grid = grid.padded_grid_from_kernel_shape( kernel_shape_2d=psf.shape_2d ) traced_padded_grids = tracer.traced_grids_of_planes_from_grid( grid=padded_grid ) manual_blurred_image_0 = tracer.image_plane.profile_images_of_galaxies_from_grid( grid=traced_padded_grids[0] )[ 0 ] manual_blurred_image_0 = psf.convolved_array_from_array( array=manual_blurred_image_0 ) manual_blurred_image_1 = tracer.image_plane.profile_images_of_galaxies_from_grid( grid=traced_padded_grids[0] )[ 1 ] manual_blurred_image_1 = psf.convolved_array_from_array( array=manual_blurred_image_1 ) manual_blurred_image_2 = tracer.source_plane.profile_images_of_galaxies_from_grid( grid=traced_padded_grids[1] )[ 0 ] manual_blurred_image_2 = psf.convolved_array_from_array( array=manual_blurred_image_2 ) manual_blurred_image_3 = tracer.source_plane.profile_images_of_galaxies_from_grid( grid=traced_padded_grids[1] )[ 1 ] manual_blurred_image_3 = psf.convolved_array_from_array( array=manual_blurred_image_3 ) unmasked_blurred_image = tracer.unmasked_blurred_profile_image_from_grid_and_psf( grid=grid, psf=psf ) assert unmasked_blurred_image.in_2d == pytest.approx( manual_blurred_image_0.in_2d_binned[1:4, 1:4] + manual_blurred_image_1.in_2d_binned[1:4, 1:4] + manual_blurred_image_2.in_2d_binned[1:4, 1:4] + manual_blurred_image_3.in_2d_binned[1:4, 1:4], 1.0e-4, ) unmasked_blurred_image_of_planes = tracer.unmasked_blurred_profile_image_of_planes_from_grid_and_psf( grid=grid, psf=psf ) assert unmasked_blurred_image_of_planes[0].in_2d == pytest.approx( manual_blurred_image_0.in_2d_binned[1:4, 1:4] + manual_blurred_image_1.in_2d_binned[1:4, 1:4], 1.0e-4, ) assert unmasked_blurred_image_of_planes[1].in_2d == pytest.approx( manual_blurred_image_2.in_2d_binned[1:4, 1:4] + manual_blurred_image_3.in_2d_binned[1:4, 1:4], 1.0e-4, ) unmasked_blurred_image_of_planes_and_galaxies = tracer.unmasked_blurred_profile_image_of_planes_and_galaxies_from_grid_and_psf( grid=grid, psf=psf ) assert ( unmasked_blurred_image_of_planes_and_galaxies[0][0].in_2d == manual_blurred_image_0.in_2d_binned[1:4, 1:4] ).all() assert ( unmasked_blurred_image_of_planes_and_galaxies[0][1].in_2d == manual_blurred_image_1.in_2d_binned[1:4, 1:4] ).all() assert ( unmasked_blurred_image_of_planes_and_galaxies[1][0].in_2d == manual_blurred_image_2.in_2d_binned[1:4, 1:4] ).all() assert ( unmasked_blurred_image_of_planes_and_galaxies[1][1].in_2d == manual_blurred_image_3.in_2d_binned[1:4, 1:4] ).all() class TestVisibilities: def test__visibilities_from_grid_and_transformer( self, sub_grid_7x7, transformer_7x7_7 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0), mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) g0_image_1d = g0.profile_image_from_grid(grid=sub_grid_7x7) deflections = g0.deflections_from_grid(grid=sub_grid_7x7) source_grid_7x7 = sub_grid_7x7 - deflections g1_image_1d = g1.profile_image_from_grid(grid=source_grid_7x7) visibilities = transformer_7x7_7.visibilities_from_image( image=g0_image_1d + g1_image_1d ) tracer = al.Tracer.from_galaxies(galaxies=[g0, g1]) tracer_visibilities = tracer.profile_visibilities_from_grid_and_transformer( grid=sub_grid_7x7, transformer=transformer_7x7_7 ) assert visibilities == pytest.approx(tracer_visibilities, 1.0e-4) def test__visibilities_of_planes_from_grid_and_transformer( self, sub_grid_7x7, transformer_7x7_7 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0) ) g1 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=2.0) ) plane_0 = al.Plane(redshift=0.5, galaxies=[g0]) plane_1 = al.Plane(redshift=0.5, galaxies=[g1]) plane_2 = al.Plane(redshift=1.0, galaxies=[al.Galaxy(redshift=1.0)]) visibilities_0 = plane_0.profile_visibilities_from_grid_and_transformer( grid=sub_grid_7x7, transformer=transformer_7x7_7 ) visibilities_1 = plane_1.profile_visibilities_from_grid_and_transformer( grid=sub_grid_7x7, transformer=transformer_7x7_7 ) tracer = al.Tracer( planes=[plane_0, plane_1, plane_2], cosmology=cosmo.Planck15 ) visibilities = tracer.profile_visibilities_of_planes_from_grid_and_transformer( grid=sub_grid_7x7, transformer=transformer_7x7_7 ) assert (visibilities[0] == visibilities_0).all() assert (visibilities[1] == visibilities_1).all() def test__galaxy_visibilities_dict_from_grid_and_transformer( self, sub_grid_7x7, transformer_7x7_7 ): g0 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=1.0) ) g1 = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal(einstein_radius=1.0), light_profile=al.lp.EllipticalSersic(intensity=2.0), ) g2 = al.Galaxy( redshift=0.5, light_profile=al.lp.EllipticalSersic(intensity=3.0) ) g3 = al.Galaxy( redshift=1.0, light_profile=al.lp.EllipticalSersic(intensity=5.0) ) g0_visibilities = g0.profile_visibilities_from_grid_and_transformer( grid=sub_grid_7x7, transformer=transformer_7x7_7 ) g1_visibilities = g1.profile_visibilities_from_grid_and_transformer( grid=sub_grid_7x7, transformer=transformer_7x7_7 ) g2_visibilities = g2.profile_visibilities_from_grid_and_transformer( grid=sub_grid_7x7, transformer=transformer_7x7_7 ) g1_deflections = g1.deflections_from_grid(grid=sub_grid_7x7) source_grid_7x7 = sub_grid_7x7 - g1_deflections g3_visibilities = g3.profile_visibilities_from_grid_and_transformer( grid=source_grid_7x7, transformer=transformer_7x7_7 ) tracer = al.Tracer.from_galaxies( galaxies=[g3, g1, g0, g2], cosmology=cosmo.Planck15 ) visibilities_dict = tracer.galaxy_profile_visibilities_dict_from_grid_and_transformer( grid=sub_grid_7x7, transformer=transformer_7x7_7 ) assert (visibilities_dict[g0] == g0_visibilities).all() assert (visibilities_dict[g1] == g1_visibilities).all() assert (visibilities_dict[g2] == g2_visibilities).all() assert (visibilities_dict[g3] == g3_visibilities).all() class TestGridIrregularsOfPlanes: def test__x2_planes__traced_grid_setup_correctly(self, sub_grid_7x7): galaxy_pix = al.Galaxy( redshift=1.0, pixelization=mock_inv.MockPixelization( value=1, grid=np.array([[1.0, 1.0]]) ), regularization=mock_inv.MockRegularization(matrix_shape=(1, 1)), ) galaxy_no_pix = al.Galaxy(redshift=0.5) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_no_pix, galaxy_pix]) pixelization_grids = tracer.sparse_image_plane_grids_of_planes_from_grid( grid=sub_grid_7x7 ) assert pixelization_grids[0] == None assert (pixelization_grids[1] == np.array([[1.0, 1.0]])).all() def test__multi_plane__traced_grid_setup_correctly(self, sub_grid_7x7): galaxy_pix0 = al.Galaxy( redshift=1.0, pixelization=mock_inv.MockPixelization( value=1, grid=np.array([[1.0, 1.0]]) ), regularization=mock_inv.MockRegularization(matrix_shape=(1, 1)), ) galaxy_pix1 = al.Galaxy( redshift=2.0, pixelization=mock_inv.MockPixelization( value=1, grid=np.array([[2.0, 2.0]]) ), regularization=mock_inv.MockRegularization(matrix_shape=(1, 1)), ) galaxy_no_pix0 = al.Galaxy(redshift=0.25) galaxy_no_pix1 = al.Galaxy(redshift=0.5) galaxy_no_pix2 = al.Galaxy(redshift=1.5) tracer = al.Tracer.from_galaxies( galaxies=[ galaxy_pix0, galaxy_pix1, galaxy_no_pix0, galaxy_no_pix1, galaxy_no_pix2, ] ) pixelization_grids = tracer.sparse_image_plane_grids_of_planes_from_grid( grid=sub_grid_7x7 ) assert pixelization_grids[0] == None assert pixelization_grids[1] == None assert (pixelization_grids[2] == np.array([[1.0, 1.0]])).all() assert pixelization_grids[3] == None assert (pixelization_grids[4] == np.array([[2.0, 2.0]])).all() class TestTracedGridIrregularsOfPlanes: def test__x2_planes__no_mass_profiles__traced_grid_setup_correctly( self, sub_grid_7x7 ): galaxy_pix = al.Galaxy( redshift=1.0, pixelization=mock_inv.MockPixelization( value=1, grid=al.grid.manual_2d([[[1.0, 0.0]]], pixel_scales=(1.0, 1.0)), ), regularization=mock_inv.MockRegularization(matrix_shape=(1, 1)), ) galaxy_no_pix = al.Galaxy(redshift=0.5) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_no_pix, galaxy_pix]) traced_pixelization_grids = tracer.traced_sparse_grids_of_planes_from_grid( grid=sub_grid_7x7 ) assert traced_pixelization_grids[0] == None assert (traced_pixelization_grids[1] == np.array([[1.0, 0.0]])).all() def test__x2_planes__include_mass_profile__traced_grid_setup_correctly( self, sub_grid_7x7 ): galaxy_no_pix = al.Galaxy( redshift=0.5, mass_profile=al.mp.SphericalIsothermal( centre=(0.0, 0.0), einstein_radius=0.5 ), ) galaxy_pix = al.Galaxy( redshift=1.0, pixelization=mock_inv.MockPixelization( value=1, grid=al.grid.manual_2d([[[1.0, 0.0]]], pixel_scales=(1.0, 1.0)), ), regularization=mock_inv.MockRegularization(matrix_shape=(1, 1)), ) tracer = al.Tracer.from_galaxies(galaxies=[galaxy_no_pix, galaxy_pix]) traced_pixelization_grids = tracer.traced_sparse_grids_of_planes_from_grid( grid=sub_grid_7x7 ) assert traced_pixelization_grids[0] == None assert traced_pixelization_grids[1] == pytest.approx(
np.array([[1.0 - 0.5, 0.0]])
numpy.array
########################################################################################### # Script to load the Sprites video dataset (stored in .npy format) # Adapted from <NAME> (https://github.com/YingzhenLi/Sprites) ########################################################################################### import math import time import numpy as np def sprites_act(path, seed=0, return_labels=False): directions = ['front', 'left', 'right'] actions = ['walk', 'spellcard', 'slash'] start = time.time() path = path + '/npy/' X_train = [] X_test = [] if return_labels: A_train = []; A_test = [] D_train = []; D_test = [] for act in range(len(actions)): for i in range(len(directions)): label = 3 * act + i print(actions[act], directions[i], act, i, label) x = np.load(path + '%s_%s_frames_train.npy' % (actions[act], directions[i])) X_train.append(x) y = np.load(path + '%s_%s_frames_test.npy' % (actions[act], directions[i])) X_test.append(y) if return_labels: a =
np.load(path + '%s_%s_attributes_train.npy' % (actions[act], directions[i]))
numpy.load
# export DISPLAY=:0 import sys sys.path.append("../") import numpy as np import gym from dqn_car.dqn_agent import DQNAgent from dqn_car.networks import NeuralNetwork, TargetNetwork from tensorboard_evaluation import * import itertools as it from utils import EpisodeStats def run_episode(env, agent, deterministic, history_length, skip_frames=2, do_training=True, rendering=True, max_timesteps=1000, test=False): """ This methods runs one episode for a gym environment. deterministic == True => agent executes only greedy actions according the Q function approximator (no random actions). do_training == True => train agent """ stats = EpisodeStats() # Save history image_hist = [] step = 0 total_reward = 0 state = env.reset() # fix bug of corrupted states without rendering in gym environment env.viewer.window.dispatch_events() # append image history to first state state = state_preprocessing(state) image_hist.extend([state] * (history_length + 1)) state = np.array(image_hist).reshape(96, 96, history_length + 1) counter = 7 while True: # TODO: get action_id from agent # Hint: adapt the probabilities of the 5 actions for random sampling so that the agent explores properly. action_id = agent.act(state=state, deterministic=deterministic) if test and counter>0: action_id = 3 counter -= 1 action = action_id_to_action(action_id) # Hint: frame skipping might help you to get better results. reward = 0 for _ in range(skip_frames + 1): next_state, r, terminal, info = env.step(action) reward += r # reward = reward if not terminal else -10 if rendering: env.render() if terminal: break next_state = state_preprocessing(next_state) image_hist.append(next_state) image_hist.pop(0) next_state = np.array(image_hist).reshape(96, 96, history_length + 1) if do_training: agent.train(state, action_id, next_state, reward, terminal) stats.step(reward, action_id) state = next_state if terminal or (step * (skip_frames + 1)) > max_timesteps : break step += 1 return stats def action_id_to_action(action_id): if (action_id==0): a = np.array([0.0, 0.0, 0.0]).astype('float32') if (action_id==1): a = np.array([-1.0, 0.0, 0.0]).astype('float32') if (action_id==2): a = np.array([1.0, 0.0, 0.0]).astype('float32') if (action_id==3): a = np.array([0.0, 1.2, 0.0]).astype('float32') if (action_id==4): a = np.array([0.0, 0.0, 0.2]).astype('float32') return a def train_online(env, agent, num_episodes, history_length, model_dir="./models_carracing", tensorboard_dir="./tensorboard"): if not os.path.exists(model_dir): os.mkdir(model_dir) print("... train agent") tensorboard = Evaluation(os.path.join(tensorboard_dir, "train"), ["episode_reward", "valid_episode_reward", "straight", "left", "right", "accel", "brake"]) for i in range(num_episodes): print("epsiode %d" % i) timesteps = int(np.max([300, i])) stats = run_episode(env, agent, history_length=history_length, max_timesteps=timesteps, deterministic=False, do_training=True) if i % 50 == 0: valid_reward = 0 for j in range(5): valid_stats = run_episode(env, agent, deterministic=True, do_training=False, test=True) valid_reward += valid_stats.episode_reward tensorboard.write_episode_data(i, eval_dict={ "episode_reward" : stats.episode_reward, "valid_episode_reward" : valid_reward/5, "straight" : stats.get_action_usage(0), "left" : stats.get_action_usage(1), "right" : stats.get_action_usage(2), "accel" : stats.get_action_usage(3), "brake" : stats.get_action_usage(4) }) if i % 100 == 0 or (i >= num_episodes - 1): agent.saver.save(agent.sess, os.path.join(model_dir, "dqn_agent.ckpt")) tensorboard.close_session() def state_preprocessing(state): return rgb2gray(state).reshape(96, 96) / 255.0 def rgb2gray(rgb): """ this method converts rgb images to grayscale. """ gray =
np.dot(rgb[...,:3], [0.2125, 0.7154, 0.0721])
numpy.dot
import numpy as np import os import xml.etree.ElementTree as ET import sys import pickle as pkl from astropy import units as u from astropy.time import Time from astropy.timeseries import TimeSeries from astropy.table import vstack from astropy.table import Table from astropy.stats import sigma_clip, mad_std from scipy.signal import savgol_filter
np.random.seed(42)
numpy.random.seed
from __future__ import print_function, division import os import sys root = os.path.join(os.getcwd().split('src')[0], 'src') if root not in sys.path: sys.path.append(root) from utils import * from metrics.abcd import abcd import numpy as np from collections import Counter import pandas from tabulate import tabulate from random import random as rand, choice from sklearn.svm import LinearSVC from sklearn.metrics import roc_auc_score from datasets.handler import get_all_datasets def target_details(test_set): """ Return Max and Min and 'Mass' from the test set """ test_set = test_set[test_set.columns[:-1]] hi, lo = test_set.max().values, test_set.min().values return lo, hi def get_weights(train_set, maxs, mins): s_i = [] for i in xrange(len(train_set)): s_i.append((train_set.ix[i].values, np.sum( [1 if lo <= val < hi else 0 for lo, val, hi in zip(mins, train_set.ix[i].values[:-1], maxs)]) / len( train_set.columns[:-1]))) return s_i def weight_training(train, test, verbose=False): def train_validation_split(): """ Split training data into X_train and X_validation""" sorted_train = sorted(train_w, key=lambda x: x[1], reverse=True) N = len(sorted_train) train0, validation = sorted_train[int(N * 2 / 5):], sorted_train[:int(N * 2 / 5)] return train0, validation def multiply_dframe(dframe, weight): assert len(weight) == len(dframe) N = len(dframe.columns) - 1 wt_array = pd.DataFrame(np.array(N * [weight]).T, columns=dframe.columns[:-1]) new_dframe = dframe.multiply(wt_array) new_dframe[dframe.columns[-1]] = dframe[dframe.columns[-1]] return new_dframe[dframe.columns].dropna(axis=1, inplace=False) def ensemble_measure(lst, classifiers, weigths): def norm_lst(lst): import numpy as np s = np.sum(lst) arr = np.array(lst) / s return np.nan_to_num(arr) tst = pd.DataFrame([t[0] for t in lst], columns=train.columns) X = tst[tst.columns[:-1]] y = tst[tst.columns[-1]] y_hat = [] y_pred = [] for clf in classifiers: y_hat.append(clf.decision_function(X)) if len(y_hat) == 1: y = [1 if p == True else -1 for p in y] auc = roc_auc_score(y, y_hat[0]) else: for pred, wgt in zip(y_hat, norm_lst(weigths)): y_pred.append([wgt * p for p in pred]) y_pred = np.sum(np.array(y_pred).T, axis=1) y = [1 if p == True else -1 for p in y] try: auc = roc_auc_score(y, y_pred) except: set_trace() return auc def resample(train0, weights): """ The name says it all; resample training set""" def oversample(lst): new_lst = [] while len(new_lst) < N: # set_trace() a = choice(lst) b = choice(lst) c = choice(lst) r = rand() new = [x + r * (y - z) for x, y, z in zip(a[0][0][:-1], b[0][0][:-1], c[0][0][:-1])] + [a[0][0][-1]] new_lst.append(((new, (a[0][1] + b[0][1] + c[0][1]) / 3), a[1] + r * (b[1] - c[1]))) return new_lst def undersample(lst): return [choice(lst) for _ in xrange(len(lst))] klass = [t[0][-1] for t in train0] count = Counter(klass) # set_trace() [major, minor] = sorted(count)[::-1] N = int(0.5 * (count[minor] + count[major])) oversamp = [] undersmp = [] therest = [] w_cutoff = np.median(weights) for w, b in zip(weights, train0): if b[1] <= w_cutoff and b[0][-1] is minor: oversamp.append((b, w)) else: therest.append((b, w)) if b[1] >= w_cutoff and b[0][-1] is major: undersmp.append((b, w)) else: therest.append((b, w)) try: therest.extend(undersample(undersmp)) therest.extend(oversample(oversamp)) except: pass weights = [t[1] for t in therest] therest = [t[0] for t in therest] return therest, weights lo, hi = target_details(test) train_w = get_weights(train, hi, lo) train0, validation = train_validation_split() rho_best = 0 h = [] a_m = [] lam = 0.5 # Penalty for each iteration train1 = train0 w = len(train1) * [1] a_best = a_m trn_best = train1 for iter in xrange(5): if verbose: print("Interation number: {}".format(iter)) train1, w = resample(train1, w) sim = [t[1] for t in train1] try: trn = pd.DataFrame([t[0] for t in train1], columns=train.columns) except: trn = pd.DataFrame([t for t in train1], columns=train.columns) w_trn = multiply_dframe(trn, w) # Create an SVM model X = w_trn[w_trn.columns[:-1]] y = w_trn[w_trn.columns[-1]] clf = LinearSVC() clf.fit(X, y) h.append(clf) y_prd = h[-1].predict(X) e_m = np.sum([w0 if not y_hat == y_act else 0 for w0, y_hat, y_act in zip(w, y_prd, y)]) / np.sum( w) a_m.append(lam * np.log((1 - e_m) / (e_m))) w = [w0 * np.exp(a_m[-1]) if not y_hat == y_act else w0 for w0, y_hat, y_act in zip(w, y_prd, y)] p_m = ensemble_measure(validation, h, a_m) if p_m >= rho_best: if verbose: print("Found better Rho. Previously: {0:.2f} | Now: {1:.2f}".format(rho_best, p_m)) rho_best = p_m a_best = a_m trn_best = w_trn if verbose: print("Boosting terminated. Best Rho={}".format(rho_best)) return trn_best, a_best, h def predict_defects(test, weights, classifiers): def norm_lst(lst): import numpy as np s = np.sum(lst) arr = np.array(lst) / s return np.nan_to_num(arr) X = test[test.columns[:-1]] y = test[test.columns[-1]] y_hat = [] y_pred = [] for clf in classifiers: y_hat.append(clf.decision_function(X)) if len(y_hat) == 1: actuals = [1 if p > 0 else 0 for p in y] distribution = y_hat[0] predicted = [1 if p > 0 else 0 for p in distribution] else: for pred, wgt in zip(y_hat, norm_lst(weights)): y_pred.append([wgt * p for p in pred]) distribution = np.sum(np.array(y_pred).T, axis=1) actuals = [1 if p == True else 0 for p in y] predicted = [1 if p > 0 else 0 for p in distribution] return actuals, predicted, distribution def vcb(source, target, verbose=False, n_rep=12): """ TNB: Transfer Naive Bayes :param source: :param target: :param n_rep: number of repeats :return: result """ result = dict() for tgt_name, tgt_path in target.iteritems(): stats = [] if verbose: print("{} \r".format(tgt_name[0].upper() + tgt_name[1:])) val = [] for src_name, src_path in source.iteritems(): if not src_name == tgt_name: src = pandas.read_csv(src_path) tgt = pandas.read_csv(tgt_path) pd, pf, pr, f1, g, auc = [], [], [], [], [], [] for _ in xrange(n_rep): _train, clf_w, classifiers = weight_training(train=src, test=tgt) actual, predicted, distribution = predict_defects(tgt, clf_w, classifiers) p_d, p_f, p_r, rc, f_1, e_d, _g, auroc = abcd(actual, predicted, distribution) pd.append(p_d) pf.append(p_f) pr.append(p_r) f1.append(f_1) g.append(_g) auc.append(int(auroc)) stats.append([src_name, int(np.mean(pd)), int(np.mean(pf)), int(
np.mean(pr)
numpy.mean
# Functions for step algorithms: Newton-Raphson, Rational Function Optimization, # <NAME>. import numpy as np from math import sqrt, fabs # from .OptParams import Params # this will not cause changes in trust to persist import logging from . import v3d from .exceptions import AlgError, OptError from . import optparams as op from . import optimize from .history import oHistory from .displace import displace_molsys from .addIntcos import linear_bend_check from .misc import is_dq_symmetric from .printTools import print_array_string, print_mat_string from .linearAlgebra import abs_max, symm_mat_eig, asymm_mat_eig, symm_mat_inv, norm # TODO I'd like to move the displace call and wrap up here. Make this a proper wrapper # for the stepAlgorithgms def take_step(oMolsys, E, q_forces, H, stepType=None, computer=None): """ Calls one of the optimization algorithms to take a step Parameters ---------- oMolsys : object optking's molecular system E : double energy [aO] q_forces : ndarray forces in internal coordinates [aO] H : ndarray hessian in internal coordinates stepType : string, optional defaults to stepType in options computer : computeWrapper, optional Returns ------- ndarray dispalcement in internals Notes ----- This method computes dq (the step in internal coordinates), calls displace to to take the step (updating the molecular systems geometry) and updates history with the results """ if len(H) == 0 or len(q_forces) == 0: return np.zeros((0)) if not stepType: stepType = op.Params.step_type if stepType == 'NR': return dq_nr(oMolsys, E, q_forces, H) elif stepType == 'RFO': return dq_rfo(oMolsys, E, q_forces, H) elif stepType == 'SD': return dq_sd(oMolsys, E, q_forces) elif stepType == 'BACKSTEP': return dq_backstep(oMolsys) elif stepType == 'P_RFO': return dq_p_rfo(oMolsys, E, q_forces, H) elif stepType == 'LINESEARCH': return dq_linesearch(oMolsys, E, q_forces, H, computer) else: raise OptError('Dq: step type not yet implemented') # TODO this method was described as crude do we need to revisit? def apply_intrafrag_step_scaling(dq): """ Apply maximum step limit by scaling.""" logger = logging.getLogger(__name__) trust = op.Params.intrafrag_trust if sqrt(np.dot(dq, dq)) > trust: scale = trust / sqrt(np.dot(dq, dq)) logger.info("\tStep length exceeds trust radius of %10.5f." % trust) logger.info("\tScaling displacements by %10.5f" % scale) dq *= scale return def de_projected(model, step, grad, hess): """ Compute anticpated energy change along one dimension """ if model == 'NR': return step * grad + 0.5 * step * step * hess elif model == 'RFO': return (step * grad + 0.5 * step * step * hess) / (1 + step * step) else: raise OptError("de_projected does not recognize model.") # TODO why store the attemtped dq? def dq_nr(oMolsys, E, fq, H): """ Takes a step according to Newton Raphson algorithm Parameters ---------- oMolsys : molsys.Molsys optking molecular system E : double energy fq : ndarray forces in internal coordiantes H : ndarray hessian in internal coordinates Notes ----- Presently, the attempted dq is stored in history not the actual dq from the backtransformation """ logger = logging.getLogger(__name__) logger.info("\tTaking NR optimization step.") # Hinv fq = dq Hinv = symm_mat_inv(H, redundant=True) dq = np.dot(Hinv, fq) # applies maximum internal coordinate change apply_intrafrag_step_scaling(dq) # get norm |q| and unit vector in the step direction nr_dqnorm = sqrt(np.dot(dq, dq)) nr_u = dq.copy() / nr_dqnorm logger.info("\tNorm of target step-size %15.10lf" % nr_dqnorm) # get gradient and hessian in step direction nr_g = -1 * np.dot(fq, nr_u) # gradient, not force nr_h = np.dot(nr_u, np.dot(H, nr_u)) if op.Params.print_lvl > 1: logger.info('\tNR target step|: %15.10f' % nr_dqnorm) logger.info('\tNR_gradient: %15.10f' % nr_g) logger.info('\tNR_hessian: %15.10f' % nr_h) DEprojected = de_projected('NR', nr_dqnorm, nr_g, nr_h) logger.info("\tProjected energy change by quadratic approximation: %10.10lf\n" % DEprojected) # Scale fq into aJ for printing fq_aJ = oMolsys.q_show_forces(fq) displace_molsys(oMolsys, dq, fq_aJ) dq_actual = sqrt(np.dot(dq, dq)) logger.info("\tNorm of achieved step-size %15.10f" % dq_actual) # Symmetrize the geometry for next step # symmetrize_geom() # save values in step data oHistory.append_record(DEprojected, dq, nr_u, nr_g, nr_h) # Can check full geometry, but returned indices will correspond then to that. linearList = linear_bend_check(oMolsys, dq) if linearList: raise AlgError("New linear angles", newLinearBends=linearList) return dq # Take Rational Function Optimization step def dq_rfo(oMolsys, E, fq, H): """ Takes a step using Rational Function Optimization Parameters ---------- oMolsys : molsys.Molsys optking molecular system E : double energy fq : ndarray forces in internal coordinates H : ndarray hessian in internal coordinates """ logger = logging.getLogger(__name__) logger.info("\tTaking RFO optimization step.") dim = len(fq) dq = np.zeros((dim)) # To be determined and returned. trust = op.Params.intrafrag_trust # maximum step size max_projected_rfo_iter = 25 # max. # of iterations to try to converge RS-RFO rfo_follow_root = op.Params.rfo_follow_root # whether to follow root rfo_root = op.Params.rfo_root # if following, which root to follow # Determine the eigenvectors/eigenvalues of H. Hevals, Hevects = symm_mat_eig(H) # Build the original, unscaled RFO matrix. RFOmat = np.zeros((dim + 1, dim + 1)) for i in range(dim): for j in range(dim): RFOmat[i, j] = H[i, j] RFOmat[i, dim] = RFOmat[dim, i] = -fq[i] if op.Params.print_lvl >= 4: logger.debug("\tOriginal, unscaled RFO matrix:\n\n" + print_mat_string(RFOmat)) symm_rfo_step = False SRFOmat = np.zeros((dim + 1, dim + 1)) # For scaled RFO matrix. converged = False dqtdq = 10 # square of norm of step alpha = 1.0 # scaling factor for RS-RFO, scaling matrix is sI last_iter_evect = np.zeros((dim)) if rfo_follow_root and len(oHistory.steps) > 1: last_iter_evect[:] = oHistory.steps[ -2].followedUnitVector # RFO vector from previous geometry step # Iterative sequence to find alpha alphaIter = -1 while not converged and alphaIter < max_projected_rfo_iter: alphaIter += 1 # If we exhaust iterations without convergence, then bail on the # restricted-step algorithm. Set alpha=1 and apply crude scaling instead. if alphaIter == max_projected_rfo_iter: logger.warning("\tFailed to converge alpha. Doing simple step-scaling instead.") alpha = 1.0 elif op.Params.simple_step_scaling: # Simple_step_scaling is on, not an iterative method. # Proceed through loop with alpha == 1, and then continue alphaIter = max_projected_rfo_iter # Scale the RFO matrix. for i in range(dim + 1): for j in range(dim): SRFOmat[j, i] = RFOmat[j, i] / alpha SRFOmat[dim, i] = RFOmat[dim, i] if op.Params.print_lvl >= 4: logger.debug("\tScaled RFO matrix.\n\n" + print_mat_string(SRFOmat)) # Find the eigenvectors and eigenvalues of RFO matrix. SRFOevals, SRFOevects = asymm_mat_eig(SRFOmat) if op.Params.print_lvl >= 4: logger.debug("\tEigenvectors of scaled RFO matrix.\n\n" + print_mat_string(SRFOevects)) if op.Params.print_lvl >= 4: logger.debug("\tEigenvalues of scaled RFO matrix.\n\n\t" + print_array_string(SRFOevals)) logger.debug("\tFirst eigenvector (unnormalized) of scaled RFO matrix.\n\n\t" + print_array_string(SRFOevects[0])) # Do intermediate normalization. RFO paper says to scale eigenvector # to make the last element equal to 1. Bogus evect leads can be avoided # using root following. for i in range(dim + 1): # How big is dividing going to make the largest element? # Same check occurs below for acceptability. if fabs(SRFOevects[i][dim]) > 1.0e-10: tval = abs_max(SRFOevects[i] / SRFOevects[i][dim]) if tval < op.Params.rfo_normalization_max: for j in range(dim + 1): SRFOevects[i, j] /= SRFOevects[i, dim] if op.Params.print_lvl >= 4: logger.debug("\tAll scaled RFO eigenvectors (rows).\n\n" + print_mat_string(SRFOevects)) # Use input rfo_root # If root-following is turned off, then take the eigenvector with the # rfo_root'th lowest eigvenvalue. If its the first iteration, then do the same. # In subsequent steps, overlaps will be checked. if not rfo_follow_root or len(oHistory.steps) < 2: # Determine root only once at beginning ? if alphaIter == 0: logger.debug("\tChecking RFO solution %d." % (rfo_root + 1)) for i in range(rfo_root, dim + 1): # Check symmetry of root. dq[:] = SRFOevects[i, 0:dim] if not op.Params.accept_symmetry_breaking: symm_rfo_step = is_dq_symmetric(oMolsys, dq) if not symm_rfo_step: # Root is assymmetric so reject it. logger.warning("\tRejecting RFO root %d because it breaks \ the molecular point group." % (rfo_root+1)) continue # Check normalizability of root. if fabs(SRFOevects[i][dim]) < 1.0e-10: # don't even try to divide logger.warning("\tRejecting RFO root %d because normalization \ gives large value." % (rfo_root + 1)) continue tval = abs_max(SRFOevects[i] / SRFOevects[i][dim]) if tval > op.Params.rfo_normalization_max: # matching test in code above logger.warning("\tRejecting RFO root %d because normalization \ gives large value." % (rfo_root + 1)) continue rfo_root = i # This root is acceptable. break else: rfo_root = op.Params.rfo_root # no good one found, use the default # Save initial root. 'Follow' during the RS-RFO iterations. rfo_follow_root = True else: # Do root following. # Find maximum overlap. Dot only within H block. dots = np.array( [v3d.dot(SRFOevects[i], last_iter_evect, dim) for i in range(dim)], float) bestfit = np.argmax(dots) if bestfit != rfo_root: logger.info("\tRoot-following has changed rfo_root value to %d." % (bestfit + 1)) rfo_root = bestfit if alphaIter == 0: logger.info("\tUsing RFO solution %d." % (rfo_root + 1)) last_iter_evect[:] = SRFOevects[rfo_root][0:dim] # omit last column on right # Print only the lowest eigenvalues/eigenvectors if op.Params.print_lvl >= 2: logger.info("\trfo_root is %d" % (rfo_root + 1)) for i in range(dim + 1): if SRFOevals[i] < -1e-6 or i < rfo_root: eigen_val_vec = ("\n\tScaled RFO eigenvalue %d:\n\t%15.10lf (or 2*%-15.10lf)\n" % (i + 1, SRFOevals[i], SRFOevals[i] / 2)) eigen_val_vec += ("\n\teigenvector:\n\t") eigen_val_vec += print_array_string(SRFOevects[i]) logger.info(eigen_val_vec) dq[:] = SRFOevects[rfo_root][0:dim] # omit last column # Project out redundancies in steps. # Added this projection in 2014; but doesn't seem to help, as f,H are already projected. # project_dq(dq); # zero steps for frozen coordinates? dqtdq = np.dot(dq, dq) # If alpha explodes, give up on iterative scheme if fabs(alpha) > op.Params.rsrfo_alpha_max: converged = False alphaIter = max_projected_rfo_iter - 1 elif sqrt(dqtdq) < (trust + 1e-5): converged = True if alphaIter == 0 and not op.Params.simple_step_scaling: logger.info("\tDetermining step-restricting scale parameter for RS-RFO.") if alphaIter == 0: logger.info("\n\tMaximum step size allowed %10.5lf" % trust) rfo_step_report = ("\n\n\t Iter |step| alpha rfo_root" + "\n\t------------------------------------------------" + "\n\t %5d%12.5lf%14.5lf%12d\n" % (alphaIter + 1, sqrt(dqtdq), alpha, rfo_root + 1)) elif alphaIter > 0 and not op.Params.simple_step_scaling: rfo_step_report = ("\t%5d%12.5lf%14.5lf%12d\n" % (alphaIter + 1, sqrt(dqtdq), alpha, rfo_root + 1)) # Find the analytical derivative, d(norm step squared) / d(alpha) #rfo_step_report += ("\t------------------------------------------------\n") logger.info(rfo_step_report) Lambda = -1 * v3d.dot(fq, dq, dim) if op.Params.print_lvl >= 2: disp_forces = ("\tDisplacement and Forces\n\n") disp_forces += ("\tDq:" + print_array_string(dq, dim)) disp_forces += ("\tFq:" + print_array_string(fq, dim)) logger.info(disp_forces) logger.info("\tLambda calculated by (dq^t).(-f) = %15.10lf\n" % Lambda) # Calculate derivative of step size wrt alpha. tval = 0 for i in range(dim): tval += (pow(v3d.dot(Hevects[i], fq, dim), 2)) / (pow( (Hevals[i] - Lambda * alpha), 3)) analyticDerivative = 2 * Lambda / (1 + alpha * dqtdq) * tval if op.Params.print_lvl >= 2: rfo_step_report = ("\t Analytic derivative d(norm)/d(alpha) = %15.10lf\n" % analyticDerivative) # + "\n\t------------------------------------------------\n") logger.info(rfo_step_report) # Calculate new scaling alpha value. # Equation 20, Besalu and Bofill, Theor. Chem. Acc., 1998, 100:265-274 alpha += 2 * (trust * sqrt(dqtdq) - dqtdq) / analyticDerivative # end alpha RS-RFO iterations # TODO remove if this is indeed old # Crude/old way to limit step size if RS-RFO iterations if not converged or op.Params.simple_step_scaling: apply_intrafrag_step_scaling(dq) if op.Params.print_lvl >= 3: logger.debug("\tFinal scaled step dq:\n\n\t" + print_array_string(dq)) # Get norm |dq|, unit vector, gradient and hessian in step direction # TODO double check Hevects[i] here instead of H ? as for NR rfo_dqnorm = sqrt(np.dot(dq, dq)) logger.info("\tNorm of target step-size: %15.10f\n" % rfo_dqnorm) rfo_u = dq.copy() / rfo_dqnorm rfo_g = -1 * np.dot(fq, rfo_u) rfo_h = np.dot(rfo_u, np.dot(H, rfo_u)) DEprojected = de_projected('RFO', rfo_dqnorm, rfo_g, rfo_h) if op.Params.print_lvl > 1: logger.info('\tRFO target step = %15.10f' % rfo_dqnorm) logger.info('\tRFO gradient = %15.10f' % rfo_g) logger.info('\tRFO hessian = %15.10f' % rfo_h) logger.info("\tProjected energy change by RFO approximation %15.5f\n" % DEprojected) fq_aJ = oMolsys.q_show_forces(fq) displace_molsys(oMolsys, dq, fq_aJ) # For now, saving RFO unit vector and using it in projection to match C++ code, # could use actual Dq instead. dqnorm_actual = sqrt(np.dot(dq, dq)) logger.info("\tNorm of achieved step-size \t %15.10f\n" % dqnorm_actual) # To test step sizes # x_before = original geometry # x_after = new geometry # masses # change = 0.0; # for i in range(natom): # for xyz in range(3): # change += (x_before[3*i+xyz] - x_after[3*i+xyz]) * (x_before[3*i+xyz] - x_after[3*i+xyz]) # * masses[i] # change = sqrt(change); # printxopt("Step-size in mass-weighted cartesian coordinates [bohr (amu)^1/2] : %20.10lf\n" # % change) # printxopt("\tSymmetrizing new geometry\n") # geom = symmetrize_xyz(geom) oHistory.append_record(DEprojected, dq, rfo_u, rfo_g, rfo_h) linearList = linear_bend_check(oMolsys, dq) if linearList: raise AlgError("New linear angles", newLinearBends=linearList) # Before quitting, make sure step is reasonable. It should only be # screwball if we are using the "First Guess" after the back-transformation failed. if sqrt(np.dot(dq, dq)) > 10 * trust: raise AlgError("dq_rfo(): Step is far too large.") return dq def dq_p_rfo(oMolsys, E, fq, H): logger = logging.getLogger(__name__) Hdim = len(fq) # size of Hessian trust = op.Params.intrafrag_trust # maximum step size # rfo_follow_root = op.Params.rfo_follow_root # whether to follow root # rfo follow root is not currently implemented print_lvl = op.Params.print_lvl if print_lvl > 2: logger.info("\tHessian matrix\n" + print_mat_string(H)) # Diagonalize H (technically only have to semi-diagonalize) hEigValues, hEigVectors = symm_mat_eig(H) if print_lvl > 2: logger.info("\tEigenvalues of Hessian\n\n\t" + print_array_string(hEigValues)) logger.info("\tEigenvectors of Hessian (rows)\n" + print_mat_string(hEigVectors)) # Construct diagonalized Hessian with evals on diagonal HDiag = np.zeros((Hdim, Hdim)) for i in range(Hdim): HDiag[i, i] = hEigValues[i] if print_lvl > 2: logger.info("\tH diagonal\n" + print_mat_string(HDiag)) logger.debug( "\tFor P-RFO, assuming rfo_root=1, maximizing along lowest eigenvalue of Hessian.") logger.debug("\tLarger values of rfo_root are not yet supported.") rfo_root = 0 """ TODO: use rfo_root to decide which eigenvectors are moved into the max/mu space. if not rfo_follow_root or len(oHistory.steps) < 2: rfo_root = op.Params.rfo_root printxopt("\tMaximizing along %d lowest eigenvalue of Hessian.\n" % (rfo_root+1) ) else: last_iter_evect = history[-1].Dq dots = np.array([v3d.dot(hEigVectors[i],last_iter_evect,Hdim) for i in range(Hdim)], float) rfo_root = np.argmax(dots) printxopt("\tOverlaps with previous step checked for root-following.\n") printxopt("\tMaximizing along %d lowest eigenvalue of Hessian.\n" % (rfo_root+1) ) """ # number of degrees along which to maximize; assume 1 for now mu = 1 logger.info("\tInternal forces in au:\n\n\t" + print_array_string(fq)) fqTransformed = np.dot(hEigVectors, fq) # gradient transformation logger.info("\tInternal forces in au, in Hevect basis:\n\n\t" + print_array_string(fqTransformed)) # Build RFO max maximizeRFO = np.zeros((mu + 1, mu + 1)) for i in range(mu): maximizeRFO[i, i] = hEigValues[i] maximizeRFO[i, -1] = -fqTransformed[i] maximizeRFO[-1, i] = -fqTransformed[i] if print_lvl > 2: logger.info("\tRFO max\n" + print_mat_string(maximizeRFO)) # Build RFO min minimizeRFO = np.zeros((Hdim - mu + 1, Hdim - mu + 1)) for i in range(0, Hdim - mu): minimizeRFO[i, i] = HDiag[i + mu, i + mu] minimizeRFO[i, -1] = -fqTransformed[i + mu] minimizeRFO[-1, i] = -fqTransformed[i + mu] if print_lvl > 2: logger.info("\tRFO min\n" + print_mat_string(minimizeRFO)) RFOMaxEValues, RFOMaxEVectors = symm_mat_eig(maximizeRFO) RFOMinEValues, RFOMinEVectors = symm_mat_eig(minimizeRFO) logger.info("\tRFO min eigenvalues:\n\n\t" + print_array_string(RFOMinEValues)) logger.info("\tRFO max eigenvalues:\n\n\t" + print_array_string(RFOMaxEValues)) if print_lvl > 2: logger.info("\tRFO min eigenvectors (rows) before normalization:\n" + print_mat_string(RFOMinEVectors)) logger.info("\tRFO max eigenvectors (rows) before normalization:\n" + print_mat_string(RFOMaxEVectors)) # Normalize max and min eigenvectors for i in range(mu + 1): if abs(RFOMaxEVectors[i, mu]) > 1.0e-10: tval = abs(abs_max(RFOMaxEVectors[i, 0:mu]) / RFOMaxEVectors[i, mu]) if fabs(tval) < op.Params.rfo_normalization_max: RFOMaxEVectors[i] /= RFOMaxEVectors[i, mu] if print_lvl > 2: logger.info("\tRFO max eigenvectors (rows):\n" + print_mat_string(RFOMaxEVectors)) for i in range(Hdim - mu + 1): if abs(RFOMinEVectors[i][Hdim - mu]) > 1.0e-10: tval = abs( abs_max(RFOMinEVectors[i, 0:Hdim - mu]) / RFOMinEVectors[i, Hdim - mu]) if fabs(tval) < op.Params.rfo_normalization_max: RFOMinEVectors[i] /= RFOMinEVectors[i, Hdim - mu] if print_lvl > 2: logger.info("\tRFO min eigenvectors (rows):\n" + print_mat_string(RFOMinEVectors)) VectorP = RFOMaxEVectors[mu, 0:mu] VectorN = RFOMinEVectors[rfo_root, 0:Hdim - mu] logger.debug("\tVector P\n\n\t" + print_array_string(VectorP)) logger.debug("\tVector N\n\n\t" + print_array_string(VectorN)) # Combines the eignvectors from RFO max and min PRFOEVector = np.zeros(Hdim) PRFOEVector[0:len(VectorP)] = VectorP PRFOEVector[len(VectorP):] = VectorN PRFOStep = np.dot(hEigVectors.transpose(), PRFOEVector) if print_lvl > 1: logger.info("\tRFO step in Hessian Eigenvector Basis\n\n\t" + print_array_string(PRFOEVector)) logger.info("\tRFO step in original Basis\n\n\t" + print_array_string(PRFOStep)) dq = PRFOStep # if not converged or op.Params.simple_step_scaling: apply_intrafrag_step_scaling(dq) # Get norm |dq|, unit vector, gradient and hessian in step direction # TODO double check Hevects[i] here instead of H ? as for NR rfo_dqnorm = sqrt(np.dot(dq, dq)) logger.info("\tNorm of target step-size %15.10f" % rfo_dqnorm) rfo_u = dq.copy() / rfo_dqnorm rfo_g = -1 * np.dot(fq, rfo_u) rfo_h = np.dot(rfo_u, np.dot(H, rfo_u)) DEprojected = de_projected('RFO', rfo_dqnorm, rfo_g, rfo_h) if op.Params.print_lvl > 1: logger.info('\t|RFO target step| : %15.10f' % rfo_dqnorm) logger.info('\tRFO gradient : %15.10f' % rfo_g) logger.info('\tRFO hessian : %15.10f' % rfo_h) logger.info("\tProjected Delta(E) : %15.10f" % DEprojected) # Scale fq into aJ for printing fq_aJ = oMolsys.q_show_forces(fq) displace_molsys(oMolsys, dq, fq_aJ) # For now, saving RFO unit vector and using it in projection to match C++ code, # could use actual Dq instead. dqnorm_actual = sqrt(np.dot(dq, dq)) logger.info("\tNorm of achieved step-size %15.10f" % dqnorm_actual) oHistory.append_record(DEprojected, dq, rfo_u, rfo_g, rfo_h) linearList = linear_bend_check(oMolsys, dq) if linearList: raise AlgError("New linear angles", newLinearBends=linearList) # Before quitting, make sure step is reasonable. It should only be # screwball if we are using the "First Guess" after the back-transformation failed. if sqrt(np.dot(dq, dq)) > 10 * trust: raise AlgError("opt.py: Step is far too large.") return dq # Take Steepest Descent step def dq_sd(oMolsys, E, fq): """ Take a step using steepest descent method Parameters ---------- oMolsys : object optking molecular system E : double energy fq : ndarray forces in internal coordinates """ logger = logging.getLogger(__name__) logger.info("\tTaking SD optimization step.") dim = len(fq) sd_h = op.Params.sd_hessian # default value if len(oHistory.steps) > 1: previous_forces = oHistory.steps[-2].forces previous_dq = oHistory.steps[-2].Dq # Compute overlap of previous forces with current forces. previous_forces_u = previous_forces.copy() / np.linalg.norm(previous_forces) forces_u = fq.copy() / np.linalg.norm(fq) overlap = np.dot(previous_forces_u, forces_u) logger.debug("\tOverlap of current forces with previous forces %8.4lf" % overlap) previous_dq_norm = np.linalg.norm(previous_dq) if overlap > 0.50: # Magnitude of current force fq_norm = np.linalg.norm(fq) # Magnitude of previous force in step direction previous_forces_norm = v3d.dot(previous_forces, fq, dim) / fq_norm sd_h = (previous_forces_norm - fq_norm) / previous_dq_norm logger.info("\tEstimate of Hessian along step: %10.5e" % sd_h) dq = fq / sd_h apply_intrafrag_step_scaling(dq) sd_dqnorm = np.linalg.norm(dq) logger.info("\tNorm of target step-size %10.5f" % sd_dqnorm) # unit vector in step direction sd_u = dq.copy() / np.linalg.norm(dq) sd_g = -1.0 * sd_dqnorm DEprojected = de_projected('NR', sd_dqnorm, sd_g, sd_h) logger.info( "\tProjected energy change by quadratic approximation: %20.5lf" % DEprojected) fq_aJ = oMolsys.q_show_forces(fq) # for printing displace_molsys(oMolsys, dq, fq_aJ) dqnorm_actual = np.linalg.norm(dq) logger.info("\tNorm of achieved step-size %15.10f" % dqnorm_actual) # Symmetrize the geometry for next step # symmetrize_geom() oHistory.append_record(DEprojected, dq, sd_u, sd_g, sd_h) linearList = linear_bend_check(oMolsys, dq) if linearList: raise AlgError("New linear angles", newLinearBends=linearList) return dq # Take partial backward step. Update current step in history. # Divide the last step size by 1/2 and displace from old geometry. # HISTORY contains: # consecutiveBacksteps : increase by 1 # HISTORY.STEP contains: # No change to these: # forces, geom, E, followedUnitVector, oneDgradient, oneDhessian # Update these: # Dq - cut in half # projectedDE - recompute def dq_backstep(oMolsys): """ takes a partial step backwards Parameters ---------- oMolsys : molsys.Molsys optking molecular system Notes ----- Divides the previous step size by 1/2 and displaces from old geometry Updates dq (cut in half) and recomputes projected DE """ logger = logging.getLogger(__name__) logger.warning("\tRe-doing last optimization step - smaller this time.\n") # Calling function shouldn't let this happen; this is a check for developer if len(oHistory.steps) < 2: raise OptError("Backstep called, but no history is available.") # Erase last, partial step data for current step. del oHistory.steps[-1] # Get data from previous step. fq = oHistory.steps[-1].forces dq = oHistory.steps[-1].Dq oneDgradient = oHistory.steps[-1].oneDgradient oneDhessian = oHistory.steps[-1].oneDhessian # Copy old geometry so displace doesn't change history geom = oHistory.steps[-1].geom.copy() # printxopt('test geom old from history\n') # printMat(oMolsys.geom) # Compute new Dq and energy step projection. dq /= 2 dqNorm = np.linalg.norm(dq) logger.info("\tNorm of target step-size %10.5f" % dqNorm) # Compute new Delta(E) projection. if op.Params.step_type == 'RFO': DEprojected = de_projected('RFO', dqNorm, oneDgradient, oneDhessian) else: DEprojected = de_projected('NR', dqNorm, oneDgradient, oneDhessian) logger.info("\tProjected energy change : %20.5lf" % DEprojected) fq_aJ = oMolsys.q_show_forces(fq) # Displace from previous geometry oMolsys.geom = geom # uses setter; writes into all fragments displace_molsys(oMolsys, dq, fq_aJ) dqNormActual = np.linalg.norm(dq) logger.info("\tNorm of achieved step-size %15.10f" % dqNormActual) # Symmetrize the geometry for next step # symmetrize_geom() # Update the history entries which changed. oHistory.steps[-1].projectedDE = DEprojected oHistory.steps[-1].Dq[:] = dq linearList = linear_bend_check(oMolsys, dq) if linearList: raise AlgError("New linear angles", newLinearBends=linearList) return dq # Take Rational Function Optimization step def dq_linesearch(oMolsys, E, fq, H, computer): """ performs linesearch in direction of gradient Parameters ---------- oMolsys : object optking molecular system E : double energy fq : ndarray forces in internal coordinates H : ndarray hessian in internal coordinates computer : computeWrapper """ logger = logging.getLogger(__name__) s = op.Params.linesearch_step if len(oHistory.steps) > 1: s = norm(oHistory.steps[-2].Dq) / 2 logger.info("\tModifying linesearch s to %10.6f" % s) logger.info("\n\tTaking LINESEARCH optimization step.") fq_unit = fq / sqrt(np.dot(fq, fq)) logger.info("\tUnit vector in gradient direction.\n\n\t" + print_array_string(fq_unit) + "\n") Ea = E geomA = oMolsys.geom # get copy of original geometry Eb = Ec = 0 bounded = False ls_iter = 0 stepScale = 2 # Iterate until we find 3 points bounding minimum. while ls_iter < 10 and not bounded: ls_iter += 1 if Eb == 0: logger.debug("\n\tStepping along forces distance %10.5f" % s) dq = s * fq_unit fq_aJ = oMolsys.q_show_forces(fq) displace_molsys(oMolsys, dq, fq_aJ) xyz = oMolsys.geom logger.debug("\tComputing energy at this point now.") Eb = computer.compute(xyz, driver='energy', return_full=False) oMolsys.geom = geomA # reset geometry to point A if Ec == 0: logger.debug("\n\tStepping along forces distance %10.5f" % (stepScale * s)) dq = (stepScale * s) * fq_unit fq_aJ = oMolsys.q_show_forces(fq) displace_molsys(oMolsys, dq, fq_aJ) xyz = oMolsys.geom logger.debug("\tComputing energy at this point now.") Ec = computer.compute(xyz, driver='energy', return_full=False) oMolsys.geom = geomA # reset geometry to point A logger.info("\n\tCurrent linesearch bounds.\n") logger.info("\t s=%7.5f, Ea=%17.12f" % (0, Ea)) logger.info("\t s=%7.5f, Eb=%17.12f" % (s, Eb)) logger.info("\t s=%7.5f, Ec=%17.12f\n" % (stepScale * s, Ec)) if Eb < Ea and Eb < Ec: # second point is lowest do projection logger.debug("\tMiddle point is lowest energy. Good. Projecting minimum.") Sa = 0.0 Sb = s Sc = stepScale * s A = np.zeros((2, 2)) A[0, 0] = Sc * Sc - Sb * Sb A[0, 1] = Sc - Sb A[1, 0] = Sb * Sb - Sa * Sa A[1, 1] = Sb - Sa B = np.zeros((2)) B[0] = Ec - Eb B[1] = Eb - Ea x = np.linalg.solve(A, B) Xmin = -x[1] / (2 * x[0]) logger.debug("\tParabolic fit ax^2 + bx + c along gradient.") logger.debug("\t *a = %15.10f" % x[0]) logger.debug("\t *b = %15.10f" % x[1]) logger.debug("\t *c = %15.10f" % Ea) Emin_projected = x[0] * Xmin * Xmin + x[1] * Xmin + Ea dq = Xmin * fq_unit logger.info("\tProjected step size to minimum is %12.6f" % Xmin) displace_molsys(oMolsys, dq, fq_aJ) xyz = oMolsys.geom logger.debug("\tComputing energy at projected point.") Emin = computer.compute(xyz, driver='energy', return_full=False) logger.info("\tProjected energy along line: %15.10f" % Emin_projected) logger.info("\t Actual energy along line: %15.10f" % Emin) bounded = True elif Ec < Eb and Ec < Ea: # unbounded. increase step size logger.debug("\tSearching with larger step beyond 3rd point.") s *= stepScale Eb = Ec Ec = 0 else: logger.debug("\tSearching with smaller step between first 2 points.") s *= 0.5 Ec = Eb Eb = 0 # get norm |q| and unit vector in the step direction ls_dqnorm = sqrt(np.dot(dq, dq)) ls_u = dq.copy() / ls_dqnorm # get gradient and hessian in step direction ls_g = -1 * np.dot(fq, ls_u) # should be unchanged ls_h = np.dot(ls_u,
np.dot(H, ls_u)
numpy.dot
from collections import defaultdict import bisect import numpy as np import json import os def new_round(_float, _len): """ Parameters ---------- _float: float _len: int, 指定四舍五入需要保留的小数点后几位数为_len Returns ------- type ==> float, 返回四舍五入后的值 """ if isinstance(_float, float): if str(_float)[::-1].find('.') <= _len: return (_float) if str(_float)[-1] == '5': return (round(float(str(_float)[:-1] + '6'), _len)) else: return (round(_float, _len)) else: return (round(_float, _len)) method_name_to_paper = {"tangent_attack":"Tangent Attack(hemisphere)", "ellipsoid_tangent_attack":"Tangent Attack(semiellipsoid)", "HSJA":"HSJA", "SignOPT":"Sign-OPT", "SVMOPT":"SVM-OPT"} #"RayS": "RayS","GeoDA": "GeoDA"} #"biased_boundary_attack": "Biased Boundary Attack"} def from_method_to_dir_path(dataset, method, norm, targeted): if method == "tangent_attack": path = "{method}_on_defensive_model-{dataset}-{norm}-{target_str}".format(method=method, dataset=dataset, norm=norm, target_str="untargeted" if not targeted else "targeted_increment") if method == "ellipsoid_tangent_attack": path = "{method}_on_defensive_model-{dataset}-{norm}-{target_str}".format(method=method, dataset=dataset, norm=norm, target_str="untargeted" if not targeted else "targeted_increment") elif method == "HSJA": path = "{method}_on_defensive_model-{dataset}-{norm}-{target_str}".format(method=method, dataset=dataset, norm=norm, target_str="untargeted" if not targeted else "targeted_increment") elif method == "GeoDA": path = "{method}_on_defensive_model-{dataset}-{norm}-{target_str}".format(method=method, dataset=dataset, norm=norm, target_str="untargeted" if not targeted else "targeted_increment") elif method == "biased_boundary_attack": path = "{method}_on_defensive_model-{dataset}-{norm}-{target_str}".format(method=method,dataset=dataset,norm=norm, target_str="untargeted" if not targeted else "targeted_increment") elif method == "RayS": path = "{method}_on_defensive_model-{dataset}-{norm}-{target_str}".format(method=method,dataset=dataset,norm=norm, target_str="untargeted" if not targeted else "targeted_increment") elif method == "SignOPT": path = "{method}_on_defensive_model-{dataset}-{norm}-{target_str}".format(method=method,dataset=dataset,norm=norm, target_str="untargeted" if not targeted else "targeted_increment") elif method == "SVMOPT": path = "{method}_on_defensive_model-{dataset}-{norm}-{target_str}".format(method=method,dataset=dataset,norm=norm, target_str="untargeted" if not targeted else "targeted_increment") return path def read_json_and_extract(json_path): with open(json_path, "r") as file_obj: json_content = json.load(file_obj) distortion = json_content["distortion"] return distortion def get_file_name_list(dataset, method_name_to_paper, norm, targeted): folder_path_dict = {} for method, paper_method_name in method_name_to_paper.items(): file_path = "/home1/machen/hard_label_attacks/logs/" + from_method_to_dir_path(dataset, method, norm, targeted) folder_path_dict[paper_method_name] = file_path return folder_path_dict def bin_search(arr, target): if target not in arr: return None arr.sort() return arr[arr.index(target)-1], arr.index(target)-1 def get_mean_and_median_distortion_given_query_budgets(distortion_dict, query_budgets, want_key): mean_and_median_distortions = {} for query_budget in query_budgets: distortion_list = [] for image_index, query_distortion in distortion_dict.items(): query_distortion = {float(query):float(dist) for query,dist in query_distortion.items()} queries = list(query_distortion.keys()) queries = np.sort(queries) find_index = bisect.bisect(queries, query_budget) - 1 # print(len(queries),find_index) # find_index = np.searchsorted(queries, query_budget, side='right') - 1 if query_budget < queries[find_index]: print("query budget is {}, find query is {}, min query is {}, len query_distortion is {}".format(query_budget, queries[find_index], np.min(queries).item(), len(query_distortion))) continue distortion_list.append(query_distortion[queries[find_index]]) distortion_list = np.array(distortion_list) distortion_list = distortion_list[~np.isnan(distortion_list)] # 去掉nan的值 mean_distortion = np.mean(distortion_list) median_distortion =
np.median(distortion_list)
numpy.median
import numpy as np # native endian native int a =
np.array([1, 2, 3, 4])
numpy.array
### from https://github.com/emmanuelle/tomo-tv ### Sea also http://scikit-learn.org/stable/auto_examples/applications/plot_tomography_l1_reconstruction.html import numpy as np from scipy import sparse from scipy import ndimage from scipy import fftpack def build_projection_operator(l_x, n_dir=None, l_det=None, subpix=1, offset=0, pixels_mask=None): """ Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int, default l_x number of angles at which projections are acquired. n_dir projection angles are regularly spaced between 0 and 180. l_det : int, default is l_x number of pixels in the detector. If l_det is not specified, we suppose that l_det = l_x. subpix : int, default 1 number of linear subdivisions used to compute the projection of one image pixel onto a detector pixel. For example, if subpix=2, one image pixel is divided into 2x2 subpixels that are projected onto the detector, and the value of the projections is computed from these 4 projections. offset : int, default 0 width of the strip of image pixels not covered by the detector. offset > 0 means that the image is acquired in local tomography (aka ROI) mode, with the image larger than the detector. If the linear size of the array is l_x, the size of the detector is l_x - 2 offset. pixels_mask : 1-d ndarray of size l_x**2 mask of pixels to keep in the matrix (useful if one wishes to remove pixels inside or outside of a circle, for example) Returns ------- p : sparse matrix of shape (n_dir l_x, l_x**2), in csr format Tomography design matrix. The csr (compressed sparse row) allows for efficient subsequent matrix multiplication. The dtype of the elements is float32, in order to save memory. Notes ----- The returned matrix is sparse, but may nevertheless require a lot of memory for large l_x. For example, with l_x=512 and n_dir=512, the operator takes around 3 Gb of memory. The memory cost is of the order of l_x^2 x n_dir x 8 in bytes. For a given angle, the center of the pixels are rotated by the angle, and projected onto the detector. The value of the data pixel is added to the two pixels of the detector in between which the projection is located, with weights determined by a linear interpolation. Using subpix > 1 slows down the computation of the operator, because a histogram in 2-D has to be computed in order to group the projections of subpixels corresponding to a single image pixel. (this should be accelerated by a Cython function... to be written) Examples -------- >>> # Image with 256 pixels, 128 directions >>> op = build_projection_operator(256, n_dir=128) >>> # Image with 128 pixels (to be reconstructed), 256 detector pixels >>> # subpix = 2 is used for a good precision of the projection of the >>> # coarse image pixels >>> op = build_projection_operator(128, n_dir=256, l_det=256, subpix=2) >>> # Image with 256 pixels, that is twice the size of the detector that >>> # has 128 pixels. >>> op = build_projection_operator(256, n_dir=256, l_det=128, offset=64) >>> # Image with 256 pixels, that is twice the size of the detector that >>> # has 256 pixels. We use subpixels for better precision. >>> op = build_projection_operator(256, n_dir=256, l_det=256, offset=64) >>> # Using a mask: projection operator only for pixels inside a >>> # central circle >>> l_x = 128 >>> X, Y = np.ogrid[:l_x, :l_x] >>> mask = (X - l_x/2)**2 + (Y - l_x/2)**2 < (l_x/2)**2 >>> op = build_projection_operator(l_x, pixels_mask=mask) >>> op.shape (16384, 12849) """ if l_det is None: l_det = l_x X, Y = _generate_center_coordinates(subpix * l_x) X *= 1. / subpix Y *= 1. / subpix Xbig, Ybig = _generate_center_coordinates(l_det) Xbig *= (l_x - 2 * offset) / float(l_det) orig = Xbig.min() labels = None if subpix > 1: # Block-group subpixels Xlab, Ylab = np.mgrid[:subpix * l_x, :subpix * l_x] labels = (l_x * (Xlab / subpix) + Ylab / subpix).ravel() if n_dir is None: n_dir = l_x angles = np.linspace(0, np.pi, n_dir, endpoint=False) weights, data_inds, detector_inds = [], [], [] # Indices for data pixels. For each data, one data pixel # will contribute to the value of two detector pixels. for i, angle in enumerate(angles): # rotate data pixels centers Xrot = np.cos(angle) * X - np.sin(angle) * Y # compute linear interpolation weights inds, dat_inds, w = _weights_fast(Xrot, dx=(l_x - 2 * offset) / float(l_det), orig=orig, labels=labels) # crop projections outside the detector mask = np.logical_and(inds >= 0, inds < l_det) weights.append(w[mask]) detector_inds.append((inds[mask] + i * l_det).astype(np.int32)) data_inds.append(dat_inds[mask]) weights = np.concatenate(weights) weights /= subpix**2 detector_inds = np.concatenate(detector_inds) data_inds = np.concatenate(data_inds) if pixels_mask is not None: if pixels_mask.ndim > 1: pixels_mask = pixels_mask.ravel() mask = pixels_mask[data_inds] data_inds = data_inds[mask] data_inds = rank_order(data_inds)[0] detector_inds = detector_inds[mask] weights = weights[mask] proj_operator = sparse.coo_matrix((weights, (detector_inds, data_inds))) return sparse.csr_matrix(proj_operator) def _weights_fast(x, dx=1, orig=0, ravel=True, labels=None): """ Compute linear interpolation weights for projection array `x` and regularly spaced detector pixels separated by `dx` and starting at `orig`. """ if ravel: x = np.ravel(x) floor_x = np.floor((x - orig) / dx).astype(np.int32) alpha = ((x - orig - floor_x * dx) / dx).astype(np.float32) inds = np.hstack((floor_x, floor_x + 1)) weights = np.hstack((1 - alpha, alpha)) data_inds =
np.arange(x.size, dtype=np.int32)
numpy.arange
import numpy as np import random def hash(tile, dir=None): # manually specify test area x = y = w = h = 0 if(dir != None): x1 = [1, 0, 0, 0][dir] * (tile.shape[0] - 1) y1 = [0, 0, 0, 1][dir] * (tile.shape[1] - 1) x2 = x1 + [0, 1, 0, 1][dir] * (tile.shape[0] - 1) + 1 y2 = y1 + [1, 0, 1, 0][dir] * (tile.shape[1] - 1) + 1 else: x1 = y1 = 0 x2 = tile.shape[0] y2 = tile.shape[1] area = tile[y1:y2, x1:x2] return str(area.flatten()) def createPropagator(tiles): n = len(tiles) propagator = np.zeros((n, 4, n), dtype=int) for i in range(n): for dir in range(4): hash1 = hash(tiles[i], dir) for j in range(n): propagator[i][dir][j] = hash1 == hash(tiles[j], (dir+2) % 4) return propagator xr = [[1,0],[0,-1],[-1,0],[0,1]] yr = [[0,1],[1,0],[0,-1],[-1,0]] t = [[0,0],[0,1],[1,1],[1,0]] def expandRotations(tiles): if tiles.shape[1] != tiles.shape[2]: return tiles # not square! TODO could still do 180 rots newTiles = [] for tile in tiles: hashes = [] for d in range(4): tile = np.rot90(tile) hashRotated = hash(tile) if(not hashRotated in hashes): newTiles.append(tile) hashes.append(hashRotated) return np.array(newTiles) deltas = [[1,0], [0,-1], [-1,0], [0,1]] cacheTileHashes = None cachedPropagator = None def runWFC(tiles, w, h, initialTile=0): generator = wfcGenerator(tiles, w, h, initialTile) image = next(generator) try: while True: next(generator) except StopIteration: pass return image def wfcGenerator(tiles, w, h, initialTile=0): global cacheTileHashes, cachedPropagator, deltas n = len(tiles) propagator = None if(not cachedPropagator is None and not cacheTileHashes is None and len(cacheTileHashes) == len(tiles)): same = True for i in range(n): if(hash(tiles[i]) != cacheTileHashes[i]): same = False break if(same): propagator = cachedPropagator if(propagator is None): propagator = cachedPropagator = createPropagator(tiles) cacheTileHashes = [hash(tile) for tile in tiles] inBounds = lambda p : p[0]>=0 and p[1]>=0 and p[0]<w and p[1]<h possibilitySpace = np.ones((w, h, n), dtype=np.int) # buffer that contains number of possible tiles at the positions (inverse of constraint) # positions where the possibility space is collapsed to 0 or a tile is already placed have value n+1 possibilityBuffer = np.ones((w, h), dtype=np.int) * n # edge precondition edgeTile = 0 for x in range(w): possibilitySpace[x][0] *= propagator[edgeTile][3] possibilitySpace[x][h-1] *= propagator[edgeTile][1] for y in range(h): possibilitySpace[0][y] *= propagator[edgeTile][0] possibilitySpace[w-1][y] *= propagator[edgeTile][2] tileW = tiles.shape[1] tileH = tiles.shape[2] image = np.ones((h * tileH, w * tileW), np.int) * initialTile yield image while(True): yield image # always the same image! but we still yield it just in case # find random maximum constrained position minVal = int(np.amin(possibilityBuffer)) if minVal == n+1: break tupleList = np.where(possibilityBuffer == minVal) listOfCordinates = list(zip(tupleList[0], tupleList[1])) p = np.array(listOfCordinates[random.randint(0, len(listOfCordinates) - 1)]) # replace superposition = possibilitySpace[tuple(p)] possibleIndeces = np.where(superposition == 1)[0] tileIndex = possibleIndeces[random.randrange(len(possibleIndeces))] # tileIndex = possibleIndeces[0] possibilitySpace[tuple(p)] =
np.zeros(n)
numpy.zeros
import numpy as np from scipy.stats import rankdata, norm, gaussian_kde from scipy.sparse import issparse def rank(data,axis=None): # this is only approximate for speed return rankdata(data, axis=axis, method='ordinal') def _unit_norm(data,axis=None): # l1-normalization if issparse(data): sum_data = np.sum(data,axis=axis) return data.multiply(1/sum_data) if axis is not None: sum_data = np.sum(data,axis=axis) sum_data = np.expand_dims(sum_data, axis=axis) else: sum_data = np.sum(data) return data/sum_data def confusion(samps1, samps2, res=200): xmin = min(samps1.min(), samps2.min()) xmax = max(samps1.max(), samps2.max()) xgrid = np.linspace(xmin,xmax,res) try: kde_1 = gaussian_kde(samps1) kde_2 = gaussian_kde(samps2) f = kde_1.evaluate(xgrid) g = kde_2.evaluate(xgrid) integrand = f*g/(f+g) c = np.trapz(integrand,xgrid) except np.linalg.LinAlgError as error: if 'singular matrix' in str(error): c = 0.5000001 else: raise if np.isnan(c): d = 1 else: d = 1-c return d - 0.5 def confusion_filters(data, n_each=1000,offset=0.5): feat_means = np.mean(data,axis=0) # Feature means n_feat = data.shape[1] # Length of features order = np.argsort(feat_means) # Features sorted by mean value if issparse(data): order = order.A1 if n_each == 'all': # Take all available samples samp_inds = np.arange(np.size(data,0)) elif type(n_each) == int: # Randomly select a smaller sample of data if n_each >= data.shape[0]: samp_inds = np.arange(np.size(data,0)) else: samp_inds = np.random.choice(np.size(data,0), n_each, replace=False) else: raise ValueError('Unrecognised n_each value %s with type %s', n_each, type(n_each)) if issparse(data): inc = data[samp_inds,:].toarray() else: inc = data[samp_inds,:] dist_map = np.zeros([n_feat,3]) for ward in range(1,n_feat): c_top = confusion(inc[:,order[-ward-1]],inc[:,order[-1]]) c_neighbour = confusion(inc[:,order[-ward-1]],inc[:,order[-ward]]) c_bottom = confusion(inc[:,order[-ward-1]],inc[:,order[0]]) dist_map[ward,:] = [c_top,c_neighbour,c_bottom] p_map=np.zeros(n_feat) running_p=offset+dist_map[-1,1] p_map[0]=offset p_map[1]=running_p for ward in range(2,n_feat): p_neigh=dist_map[-ward,1] n_sum=1 if dist_map[-ward,0]<1 and dist_map[-ward+1,0]<1: p_top=(dist_map[-ward,0]-dist_map[-ward+1,0]) n_sum+=1 else: p_top=0 if dist_map[-ward,2]<1 and dist_map[-ward+1,2]<1: p_bottom=(dist_map[-ward+1,2]-dist_map[ward,2]) n_sum+=1 else: p_bottom=0 t_p=(p_top+p_neigh+p_bottom)/n_sum running_p+=max(t_p,0) p_map[ward] = running_p return p_map class FilterFactory(): """Factory class to build filters for rank similarity estimators. Parameters ---------- filter_function : {'auto'} or callable, default='auto' Function which determines the weights from subsections of the input data. 'auto' performs a mean and rank, optionally drawn from a distribution. create_distribution : {'confusion'}, callable or None, default=None Creates a distribution to draw ranks from. - 'confusion' is a distribution based on the confusibility of features in the input data. Note: the 'confusion' option is extremely slow. per_label : bool, default=False Creates a separate distribution per class label. Only used when ``create_distribution != None``. """ def __init__(self, filter_function='auto', create_distribution=None, per_label=False): self.filter_function = filter_function self.create_distribution = create_distribution self.per_label = per_label if self.filter_function == 'auto': if self.create_distribution == None: self.filter_function = self.rank_mean_filter elif self.create_distribution == 'confusion': self.filter_function = self.distribution_mean_filter else: self.filter_function = self.distribution_mean_filter else: #test function nsamp = 5 nfet = 10 X = np.random.rand(nsamp, nfet) distribution = np.random.rand(1,nfet) try: tmp = self.filter_function(X, distribution, 0) except: print("Testing filter_function failed\n", "It should accept 3 inputs- X, distribution, index") raise # checks that output looks as expected if not tmp.shape[0] == 1: raise ValueError("Output of filter_function is not a single filter, it has shape %i" % tmp.shape[0]) if not tmp.shape[1] == nfet: raise ValueError("N features output of filter_function %i is different than input %i" % (tmp.shape[1], nfet)) self.dist_index = 0 self.distribution = None def transform(self, X): """Transforms data X into a filter. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input data. Returns ------- filter : ndarray of shape (n_features, ) """ return self.filter_function(X, self.distribution, self.dist_index) def fit_distribution(self,X,y=None): """Fits a distribution to data X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input data. y : ndarray, shape (n_samples,) or None, default=None Target values when distribution is created per label. """ if self.create_distribution == 'confusion': self.create_distribution = confusion_filters if self.per_label == True: all_labels =
np.unique(y)
numpy.unique
from __future__ import division, absolute_import, print_function import numpy as np import scipy.sparse as ss import scipy.sparse.csgraph as ssc from scipy.linalg import solve from collections import deque from ..mini_six import range class TransformMixin(object): def kernelize(self, kernel): '''Re-weight according to a specified kernel function. kernel : str, {none, binary, rbf} none -> no reweighting binary -> all edges are given weight 1 rbf -> applies a gaussian function to edge weights ''' if kernel == 'none': return self if kernel == 'binary': if self.is_weighted(): return self._update_edges(1, copy=True) return self if kernel == 'rbf': w = self.edge_weights() r = np.exp(-w / w.std()) return self._update_edges(r, copy=True) raise ValueError('Invalid kernel type: %r' % kernel) def barycenter_edge_weights(self, X, copy=True, reg=1e-3): '''Re-weight such that the sum of each vertex's edge weights is 1. The resulting weighted graph is suitable for locally linear embedding. reg : amount of regularization to keep the problem well-posed ''' new_weights = [] for i, adj in enumerate(self.adj_list()): C = X[adj] - X[i] G = C.dot(C.T) trace = np.trace(G) r = reg * trace if trace > 0 else reg G.flat[::G.shape[1] + 1] += r w = solve(G, np.ones(G.shape[0]), sym_pos=True, overwrite_a=True, overwrite_b=True) w /= w.sum() new_weights.extend(w.tolist()) return self.reweight(new_weights, copy=copy) def connected_subgraphs(self, directed=True, ordered=False): '''Generates connected components as subgraphs. When ordered=True, subgraphs are ordered by number of vertices. ''' num_ccs, labels = self.connected_components(directed=directed) # check the trivial case first if num_ccs == 1: yield self raise StopIteration if ordered: # sort by descending size (num vertices) order = np.argsort(np.bincount(labels))[::-1] else: order = range(num_ccs) # don't use self.subgraph() here, because we can reuse adj adj = self.matrix('dense', 'csr', 'csc') for c in order: mask = labels == c sub_adj = adj[mask][:,mask] yield self.__class__.from_adj_matrix(sub_adj) def shortest_path_subtree(self, start_idx, directed=True): '''Returns a subgraph containing only the shortest paths from start_idx to every other vertex. ''' adj = self.matrix() _, pred = ssc.dijkstra(adj, directed=directed, indices=start_idx, return_predecessors=True) adj = ssc.reconstruct_path(adj, pred, directed=directed) if not directed: adj = adj + adj.T return self.__class__.from_adj_matrix(adj) def minimum_spanning_subtree(self): '''Returns the (undirected) minimum spanning tree subgraph.''' dist = self.matrix('dense', copy=True) dist[dist==0] = np.inf np.fill_diagonal(dist, 0) mst = ssc.minimum_spanning_tree(dist) return self.__class__.from_adj_matrix(mst + mst.T) def neighborhood_subgraph(self, start_idx, radius=1, weighted=True, directed=True, return_mask=False): '''Returns a subgraph containing only vertices within a given geodesic radius of start_idx.''' adj = self.matrix('dense', 'csr', 'csc') dist = ssc.dijkstra(adj, directed=directed, indices=start_idx, unweighted=(not weighted), limit=radius) mask = np.isfinite(dist) sub_adj = adj[mask][:,mask] g = self.__class__.from_adj_matrix(sub_adj) if return_mask: return g, mask return g def isograph(self, min_weight=None): '''Remove short-circuit edges using the Isograph algorithm. min_weight : float, optional Minimum weight of edges to consider removing. Defaults to max(MST). From "Isograph: Neighbourhood Graph Construction Based On Geodesic Distance For Semi-Supervised Learning" by <NAME> al., 2011. Note: This uses the non-iterative algorithm which removes edges rather than reweighting them. ''' W = self.matrix('dense') # get candidate edges: all edges - MST edges tree = self.minimum_spanning_subtree() candidates = np.argwhere((W - tree.matrix('dense')) > 0) cand_weights = W[candidates[:,0], candidates[:,1]] # order by increasing edge weight order = np.argsort(cand_weights) cand_weights = cand_weights[order] # disregard edges shorter than a threshold if min_weight is None: min_weight = tree.edge_weights().max() idx = np.searchsorted(cand_weights, min_weight) cand_weights = cand_weights[idx:] candidates = candidates[order[idx:]] # check each candidate edge to_remove = np.zeros_like(cand_weights, dtype=bool) for i, (u,v) in enumerate(candidates): W_uv =
np.where(W < cand_weights[i], W, 0)
numpy.where
# Tests the matrices.py file, which is responsible for the creation and manipulation of scattering matrices import unittest from rcwa.testing import * from rcwa.shorthand import * from rcwa import Source, Layer, LayerStack import numpy as np from rcwa.matrices import * class Test1x1Harmonic(unittest.TestCase): def testCalculateKz(self): KzCalculated = calculateKzForward(self.Kx, self.Ky, self.layerStack.reflectionLayer) KzActual =
np.float64(self.KzReflectionRegion)
numpy.float64
#!/usr/bin/env Python3 """ ProtienNetMap LabeledFunctions for working with the Sequence UNET model """ from dataclasses import dataclass import numpy as np import pandas as pd from Bio import SeqIO from graph_cnn import contact_graph from proteinnetpy.data import LabeledFunction AMINO_ACIDS = np.array(['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']) AA_HASH = {aa: index for index, aa in enumerate(AMINO_ACIDS)} # TODO Move these to ProteinNetPy? class SequenceUNETMapFunction(LabeledFunction): """ ProteinNetMapFunction returning the required data for the sequence UNET model """ def __init__(self, num_layers=4, threshold=None, contact_graph=False, weights=False, pssm=False): self.num_layers = num_layers self.threshold = threshold self.contact_graph = contact_graph self.weights = weights self.pssm = pssm output_shapes = ([None, 20], [None, None]) if self.contact_graph else ([None, 20],) output_types = ('float32', 'float32') if self.contact_graph else ('float32',) output_shapes = [output_shapes, [None, 20]] output_types = [output_types, 'int32' if self.threshold is not None else 'float32'] if self.weights: output_shapes.append([None]) output_types.append('float32') self.output_shapes = tuple(output_shapes) self.output_types = tuple(output_types) def __call__(self, record): data = record.evolutionary.T if self.pssm else record.get_one_hot_sequence().T labels = record.evolutionary.T weights = np.ones(data.shape[0]) if self.threshold is not None: labels = labels < self.threshold labels = labels.astype(int) + 1 # Need to make sure output can be halved a sufficient number of time pad_rows = 2 ** (self.num_layers - 1) - data.shape[0] % 2 ** (self.num_layers - 1) if pad_rows: data = np.pad(data, ((0, pad_rows), (0, 0)), mode='constant') labels = np.pad(labels, ((0, pad_rows), (0, 0)), mode='constant') weights = np.pad(weights, (0, pad_rows), mode='constant') if self.contact_graph: contacts = contact_graph(record) if pad_rows: contacts = np.pad(contacts, ((0, pad_rows), (0, pad_rows)), mode='constant') out = (data, contacts) if self.contact_graph else (data,) if self.weights: return out, labels, weights else: return out, labels class MaskedSequenceMapFunction(LabeledFunction): """ ProteinNetMapFunction returning sequences with masked positions and the true AAs in those positions. This is used to train a generalisable base for the sequence UNET model num_layers: number of layers in the SequenceUNET model, used to 0 pad output so it can be halved an appropriate number of times. contact_graph: Include contact graph input mask: Number of positions to mask. Treated as an absolute if an integer or a proportion if a float. """ def __init__(self, num_layers=4, contact_graph=False, mask=5): self.num_layers = num_layers self.contact_graph = contact_graph self.mask = mask if isinstance(self.mask, int): self.int_mask = True elif isinstance(self.mask, float): self.int_mask = False else: raise TypeError(f"mask must be an int or float, recieved {mask}") output_shapes = ([None, 20], [None, None]) if self.contact_graph else ([None, 20],) output_types = ('float32', 'float32') if self.contact_graph else ('float32',) output_shapes = [output_shapes, [None, 20], [None]] output_types = [output_types, 'float32', 'float32'] self.output_shapes = tuple(output_shapes) self.output_types = tuple(output_types) def __call__(self, record): seq = record.get_one_hot_sequence().T labels = np.copy(seq) length = seq.shape[0] weights = np.zeros(length) # Mask sequences n_masked = self.mask if self.int_mask else int(self.mask * length) masked_positions = np.random.choice(length, n_masked, replace=False) seq[masked_positions, :] = 0 weights[masked_positions] = 1 # Need to make sure output can be halved a sufficient number of time pad_rows = 2 ** (self.num_layers - 1) - length % 2 ** (self.num_layers - 1) if pad_rows: seq = np.pad(seq, ((0, pad_rows), (0, 0)), mode='constant') labels = np.pad(labels, ((0, pad_rows), (0, 0)), mode='constant') weights = np.pad(weights, (0, pad_rows), mode='constant') # Generate contact graph # TODO Should this be masked? if self.contact_graph: contacts = contact_graph(record) if pad_rows: contacts = np.pad(contacts, ((0, pad_rows), (0, pad_rows)), mode='constant') out = (seq, contacts) else: out = (seq,) return out, labels, weights class ClinVarMapFunction(LabeledFunction): """ ProteinNetMapFunction returning the required data for the Mutation PSSM Top model clinvar: Annotated clinvar variants pandas data frame num_layers: Number of layers of UNET model contact_graph: Include contact graph in output pssm: Return the true PSSM instead of the sequence """ def __init__(self, clinvar, num_layers=None, contact_graph=True, pssm=False): self.clinvar = clinvar self.clinvar['pdb_id'] = self.clinvar['pdb_id'].str.upper() self.num_layers = num_layers self.contact_graph = contact_graph self.pssm = pssm out_shape = ([None, 20], [None, None]) if self.contact_graph else ([None, 20],) out_type = ('float32', 'float32') if self.contact_graph else ('float32',) # (Seq, struct graph), labels self.output_shapes = (out_shape, [None, 20]) self.output_types = (out_type, 'int32') def __call__(self, record): out_main = record.evolutionary.T if self.pssm else record.get_one_hot_sequence().T contacts = contact_graph(record, contact_distance=800) if self.contact_graph else None labels = self._calc_clinvar(record, shape=out_main.shape) if self.num_layers is not None: # Need to make sure output can be halved a sufficient number of time pad_rows = 2 ** (self.num_layers - 1) - out_main.shape[0] % 2 ** (self.num_layers - 1) if pad_rows: out_main = np.pad(out_main, ((0, pad_rows), (0, 0)), mode='constant') labels = np.pad(labels, ((0, pad_rows), (0, 0)), mode='constant') if self.contact_graph: contacts = np.pad(contacts, ((0, pad_rows), (0, pad_rows)), mode='constant') if self.contact_graph: return (out_main, contacts), labels else: return (out_main,), labels def _calc_clinvar(self, record, shape): """ Generate clinvar label matrix for a given record """ try: muts = self.clinvar[((self.clinvar.pdb_id == record.pdb_id) & (self.clinvar.chain == record.pdb_chain))] # Offset pos by first unmasked index, since that is what first_pdb_pos corresponds to pos = (np.nonzero(record.mask)[0][0] + muts.pdb_pos - muts.first_pdb_pos).values aa =
np.vectorize(AA_HASH.__getitem__)
numpy.vectorize
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * import sys # from pyquaternion import Quaternion ## would be useful for 3D simulation import numpy as np import math as math window = 0 # number of the glut window theta = 0.0 simTime = 0 dT = 0.01 simRun = True RAD_TO_DEG = 180.0 / 3.1416 multi = 0 boardY = 0 ##################################################### #### Link class, i.e., for a rigid body ##################################################### class Link: color = [0, 0, 0] ## draw color size = [1, 1, 1] ## dimensions mass = 1.0 ## mass in kg izz = 1.0 ## moment of inertia about z-axis theta = 0 ## 2D orientation (will need to change for 3D) omega = 0 ## 2D angular velocity posn = np.array([0.0, 0.0, 0.0]) ## 3D position (keep z=0 for 2D) vel = np.array([0.0, 0.0, 0.0]) ## initial velocity def draw(self): ### steps to draw a link glPushMatrix() ## save copy of coord frame glTranslatef(self.posn[0], self.posn[1], self.posn[2]) ## move glRotatef(self.theta * RAD_TO_DEG, 0, 0, 1) ## rotate glScale(self.size[0], self.size[1], self.size[2]) ## set size glColor3f(self.color[0], self.color[1], self.color[2]) ## set colour DrawCube() ## draw a scaled cube glPopMatrix() ## restore old coord frame ##################################################### # #### Bar class, i.e., for dynamic illustration ##################################################### class Bar: color = [0, 0, 0] size = [1, 1, 1] posn = np.array([5.0, 0.0, 0.0]) def draw(self): glPushMatrix() ## save copy of coord frame glTranslatef(self.posn[0], self.posn[1], self.posn[2]) ## move glScale(self.size[0], self.size[1], self.size[2]) ## set size glColor3f(self.color[0], self.color[1], self.color[2]) ## set colour DrawCube() ## draw a scaled cube glPopMatrix() ## restore old coord frame ##################################################### # #### Bar class, i.e., for dynamic illustration ##################################################### class Ground: color = [0.1, 0.1, 0.7] size = [7, 0.02, 7] posn = np.array([0.0, -3.5, 0.0]) def draw(self): glPushMatrix() ## save copy of coord frame glTranslatef(self.posn[0], self.posn[1], self.posn[2]) ## move glScale(self.size[0], self.size[1], self.size[2]) ## set size glColor3f(self.color[0], self.color[1], self.color[2]) ## set colour DrawCube() ## draw a scaled cube glPopMatrix() ## restore old coord frame ##################################################### #### main(): launches app ##################################################### def main(): global window global link1, link2, link3, link4, alone global kBar, pBar global ground global multi multi = 0 glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) # display mode glutInitWindowSize(640, 480) # window size glutInitWindowPosition(0, 0) # window coords for mouse start at top-left window = glutCreateWindow("Lotus' Pendulum") glutDisplayFunc(DrawWorld) # register the function to draw the world # glutFullScreen() # full screen glutIdleFunc(SimWorld) # when doing nothing, redraw the scene glutReshapeFunc(ReSizeGLScene) # register the function to call when window is resized glutKeyboardFunc(keyPressed) # register the function to call when keyboard is pressed InitGL(640, 480) # initialize window link1 = Link(); link2 = Link(); link3 = Link(); link4 = Link(); alone = Link(); kBar = Bar() pBar = Bar() ground = Ground(); resetSim() glutMainLoop() # start event processing loop ##################################################### #### keyPressed(): called whenever a key is pressed ##################################################### def resetSim(): global link1, link2, link3, link4 global kBar, pBar global simTime, simRun global ground global boardY printf("Simulation reset\n") simRun = True simTime = 0 alone.size = [0.04, 1.0, 0.12] alone.color = [0.5, 0.9, 0.9] alone.vel = np.array([0.0, 0.0, 0.0]) alone.theta = math.pi * 3/4 alone.posn = np.array([-0.5 * math.sin(alone.theta), 0.5 * math.cos(alone.theta), 0.0]) alone.omega = 0.0 ## radians per second link1.size = [0.04, 1.0, 0.12] link1.color = [0.85, 0.9, 1.0] link1.vel = np.array([0.0, 0.0, 0.0]) link1.theta = math.pi * 3/4 link1.posn = [0,0,0] + np.array([-0.5 * math.sin(link1.theta), 0.5 * math.cos(link1.theta), 0.0]) link1.omega = 0.0 ## radians per second link2.size = [0.04, 1.0, 0.12] link2.color = [0.65, 0.79, 0.99] link2.theta = math.pi * 3/4 link2.vel = np.array([0.0, 0.0, 0.0]) link2.posn = link1.posn + np.array([-math.sin(link1.theta), math.cos(link1.theta), 0.0]) link2.omega = 0.0 ## radians per second link3.size = [0.04, 1.0, 0.12] link3.color = [0.45, 0.66, 0.98] link3.theta = math.pi * 3/4 link3.posn = link2.posn + np.array([-math.sin(link2.theta), math.cos(link2.theta), 0.0]) link3.vel = np.array([0.0, 0.0, 0.0]) link3.omega = 0.0 ## radians per second link4.size = [0.04, 1.0, 0.12] link4.color = [0.3, 0.55, 0.95] link4.theta = math.pi * 3 / 4 link4.posn = link3.posn + np.array([-math.sin(link3.theta), math.cos(link3.theta), 0.0]) link4.vel = np.array([0.0, 0.0, 0.0]) link4.omega = 0.0 ## radians per second kBar.color = [0.6, 0.7, 0.8] kBar.size = [0.2, 0.4, 0.2] kBar.posn = np.array([1.0, -3.5, 6.5]) pBar.color = [0.6, 0.9, 0.65] pBar.size = [0.2, 0.4, 0.2] pBar.posn = np.array([kBar.posn[0], kBar.size[1], kBar.posn[2]]) ground.color = [0.3, 0.3, 0.7] boardY = ground.posn[1] ##################################################### #### keyPressed(): called whenever a key is pressed ##################################################### def keyPressed(key, x, y): global simRun global multi global boardY ch = key.decode("utf-8") if ch == ' ': #### toggle the simulation if (simRun == True): simRun = False else: simRun = True elif ch == chr(27): #### ESC key sys.exit() elif ch == 'q': #### quit sys.exit() elif ch == 'r': #### reset simulation resetSim() elif ch == 'n': #### reset simulation multi = 0 resetSim() elif ch == 'm': #### reset simulation multi = 1 resetSim() elif ch == 'w': #### reset simulation boardY += 1 elif ch == 's': #### reset simulation boardY -= 1 ##################################################### #### SimWorld(): simulates a time step ##################################################### def SimWorld(): global simTime, dT, simRun global link1, link2, link3, link4, alone global boardY I = 1.0/12.0 deltaTheta = 2.4 if (simRun == False): ## is simulation stopped? return ############################### #### For 4-link ############################### r1 = [0.5 * math.sin(link1.theta),-0.5 * math.cos(link1.theta),0] r1x = r1[0] r1y = r1[1] r2 = [0.5 * math.sin(link2.theta),-0.5 * math.cos(link2.theta),0] r2x = r2[0] r2y = r2[1] r3 = [0.5 * math.sin(link3.theta),-0.5 * math.cos(link3.theta),0] r3x = r3[0] r3y = r3[1] r4 = [0.5 * math.sin(link4.theta),-0.5 * math.cos(link4.theta),0] r4x = r4[0] r4y = r4[1] constraint1 =1*(link1.posn + r1 - [0,0,0])+ 0.01*(np.cross([0,0,link1.omega], r1) - link1.vel) constraint2 =1*(link2.posn + r2 - (link1.posn - r1))+ 0.01*(np.cross([0,0,link2.omega], r2) - link2.vel) constraint3 =1*(link3.posn + r3 - (link2.posn - r2))+ 0.01*(np.cross([0,0,link3.omega], r3) - link3.vel) constraint4 =1*(link4.posn + r4 - (link3.posn - r3))+ 0.01*(np.cross([0,0,link4.omega], r4) - link4.vel) t1x = -r1x * link1.omega * link1.omega + constraint1[0] t1y = -r1y * link1.omega * link1.omega + constraint1[1] t2x = r1x * link1.omega * link1.omega + r2x * link2.omega * link2.omega - constraint2[0] t2y = r1y * link1.omega * link1.omega + r2y * link2.omega * link2.omega - constraint2[1] t3x = r2x * link2.omega * link2.omega + r3x * link3.omega * link3.omega - constraint3[0] t3y = r2y * link2.omega * link2.omega + r3y * link3.omega * link3.omega - constraint3[1] t4x = r3x * link3.omega * link3.omega + r4x * link4.omega * link4.omega - constraint4[0] t4y = r3y * link3.omega * link3.omega + r4y * link4.omega * link4.omega - constraint4[1] damp1 = link1.omega * 0.5 damp2 = link2.omega * 0.5 damp3 = link3.omega * 0.5 damp4 = link4.omega * 0.5 ground.posn[1] = boardY bottom4 = link4.posn - r4 - 0.2 bottom3 = link3.posn - r3 - 0.2 bottom2 = link2.posn - r2 - 0.2 bottom1 = link1.posn - r1 - 0.2 penalty4 = 80.0 * (ground.posn[1] - bottom4[1]) - 20.0* link4.vel[1] penalty3 = 80.0 * (ground.posn[1] - bottom3[1]) - 20.0 * link3.vel[1] penalty2 = 80.0 * (ground.posn[1] - bottom2[1]) - 20.0 * link2.vel[1] penalty1 = 80.0 * (ground.posn[1] - bottom1[1]) - 20.0 * link1.vel[1] if ground.posn[1] > bottom4[1]: ground.color = [0.9,0.9,0.9] else: ground.color = [0.85, 0.85, 0.85] penalty4 = 0 if ground.posn[1] > bottom3[1]: ground.color = [0.9,0.9,0.9] else: ground.color = [0.85, 0.85, 0.85] penalty3 = 0 if ground.posn[1] > bottom2[1]: ground.color = [0.9,0.9,0.9] else: ground.color = [0.85, 0.85, 0.85] penalty2 = 0 if ground.posn[1] > bottom1[1]: ground.color = [0.9,0.9,0.9] else: ground.color = [0.85, 0.85, 0.85] penalty1= 0 # print(penalty) # 1 2 3 4 A B C D a = np.array([[1,0,0, 0,0,0, 0,0,0, 0,0,0, -1,0, 1,0, 0,0, 0,0], #1 [0,1,0, 0,0,0, 0,0,0, 0,0,0, 0,-1, 0,1, 0,0, 0,0], [0,0,I, 0,0,0, 0,0,0, 0,0,0, r1y,-r1x,r1y,-r1x,0,0, 0,0], [0,0,0, 1,0,0, 0,0,0, 0,0,0, 0,0, -1,0, 1,0, 0,0], #2 [0,0,0, 0,1,0, 0,0,0, 0,0,0, 0,0, 0,-1, 0,1, 0,0], [0,0,0, 0,0,I, 0,0,0, 0,0,0, 0,0,r2y,-r2x,r2y,-r2x, 0,0], [0,0,0, 0,0,0, 1,0,0, 0,0,0, 0,0, 0,0, -1,0, 1,0], #3 [0,0,0, 0,0,0, 0,1,0, 0,0,0, 0,0, 0,0, 0,-1, 0,1], [0,0,0, 0,0,0, 0,0,I, 0,0,0, 0,0, 0,0,r3y,-r3x,r3y,-r3x], [0,0,0, 0,0,0, 0,0,0, 1,0,0, 0,0, 0,0, 0,0, -1,0], #4 [0,0,0, 0,0,0, 0,0,0, 0,1,0, 0,0, 0,0, 0,0, 0,-1], [0,0,0, 0,0,0, 0,0,0, 0,0,I, 0,0, 0,0, 0,0,r4y,-r4x], [-1,0,r1y, 0,0,0, 0,0,0, 0,0,0, 0,0, 0,0, 0,0, 0,0], #A [0,-1,-r1x, 0,0,0, 0,0,0, 0,0,0, 0,0, 0,0, 0,0, 0,0], [-1,0,-r1y, 1,0,-r2y,0,0,0, 0,0,0, 0,0, 0,0, 0,0, 0,0], #B [0,-1,r1x, 0,1,r2x, 0,0,0, 0,0,0, 0,0, 0,0, 0,0, 0,0], [0,0,0, -1,0,-r2y,1,0,-r3y,0,0,0, 0,0, 0,0, 0,0, 0,0], #C [0,0,0, 0,-1,r2x,0,1,r3x, 0,0,0, 0,0, 0,0, 0,0, 0,0], [0,0,0, 0,0,0, -1,0,-r3y,1,0,-r4y, 0,0, 0,0, 0,0, 0,0], #D [0,0,0, 0,0,0, 0,-1,r3x, 0,1,r4x, 0,0, 0,0, 0,0, 0,0]]) b = np.array([0,-10+penalty1,-damp1- r1x * penalty1, 0,-10+penalty2,-damp2- r2x * penalty2, 0,-10+penalty3,-damp3- r3x * penalty3, 0,-10+penalty4, -damp4 - r4x * penalty4, t1x,t1y, t2x,t2y, t3x,t3y, t4x,t4y]) x = np.linalg.solve(a, b) #### solve for the equations of motion (simple in this case!) acc1 = np.array([x[0], x[1], 0]) ### linear acceleration = [0, -G, 0] acc2 = np.array([x[3], x[4], 0]) ### linear acceleration = [0, -G, 0] acc3 = np.array([x[6], x[7], 0]) ### linear acceleration = [0, -G, 0] acc4 = np.array([x[9], x[10], 0]) ### linear acceleration = [0, -G, 0] omega_dot1 = x[2] ### assume no angular acceleration omega_dot2 = x[5] ### assume no angular acceleration omega_dot3 = x[8] ### assume no angular acceleration omega_dot4 = x[11] ### assume no angular acceleration #### explicit Euler integration to update the state link1.posn += link1.vel * dT link1.vel += acc1 * dT link1.theta += link1.omega * dT link1.omega += omega_dot1 * dT link2.posn += link2.vel * dT link2.vel += acc2 * dT link2.theta += link2.omega * dT link2.omega += omega_dot2 * dT link3.posn += link3.vel * dT link3.vel += acc3 * dT link3.theta += link3.omega * dT link3.omega += omega_dot3 * dT link4.posn += link4.vel * dT link4.vel += acc4 * dT link4.theta += link4.omega * dT link4.omega += omega_dot4 * dT ################################# ####### For Alone: ################################# ra = [0.5 * math.sin(alone.theta), -0.5 * math.cos(alone.theta), 0] rax = ra[0] ray = ra[1] dampA = alone.omega * 0.04 constraintA = 2 * (alone.posn + ra - [0, 0, 0]) + 0.002 * (np.cross([0, 0, alone.omega], ra) - alone.vel) tax = -rax * alone.omega * alone.omega + constraintA[0] tay = -ray * alone.omega * alone.omega + constraintA[1] aa = np.array([[1, 0, 0, -1, 0], [0, 1, 0, 0, -1], [0, 0, I, ray,-rax], [-1, 0, ray, 0, 0], [0, -1, -rax, 0, 0]]) ab =
np.array([0, -10, -dampA, tax, tay])
numpy.array
# # Jupyter Notebook for Counting Building Occupancy from Polaris Traffic Simulation Data # # This notebook will load a Polaris SQLlite data file into a Pandas data frame using sqlite3 libraries and count the average number of people in each building in each hour of the simulation. # # For help with Jupyter notebooks # # For help on using sql with Pandas see # http://www.pererikstrandberg.se/blog/index.cgi?page=PythonDataAnalysisWithSqliteAndPandas # # For help on data analysis with Pandas see # http://nbviewer.jupyter.org/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/Index.ipynb # import sqlite3 import numpy as np import pandas as pd import matplotlib.pyplot as plt fname = ".\data\detroit-Demand.sqlite" outfolder = ".\\output\\" print(f'Connecting to database {fname}') # Create your connection. Assumes data is in a parallel subdirectory to this one cnx = sqlite3.connect('.\data\detroit2-Demand.sqlite') print("getting location data from SQLite File") # exract all the beginning locations of the building simulation beginning_location = pd.read_sql_query("SELECT * FROM Beginning_Location_All", cnx) print("getting trip data from SQLite File") trips = pd.read_sql_query("SELECT start, end, origin, destination, person FROM Trip", cnx) trips["start_hr"] = trips.start // 3600 trips["end_hr"] = trips.end // 3600 print("analyzing data from SQL file") # create the data frames that have the counts of things grouped by start hr & origin and end hr & destination departs = trips.groupby(['start_hr', 'origin']).size().reset_index(name='countleave') arrives = trips.groupby(['end_hr', 'destination']).size().reset_index(name='countarrive') departm = {} arrivem = {} # create an array of hours for general use hr = list(range(24)) print("extracting departures and arrivals") # create a dataframe for departurses and arrivals per hour by location # columns are hours, rows are locations. Fill in missing data with zeros for i in hr: departm[i] = pd.merge( beginning_location, departs[departs.start_hr == i], left_on='location', right_on='origin', how='left' ).fillna(0) arrivem[i] = pd.merge( beginning_location, arrives[arrives.end_hr == i], left_on='location', right_on='destination', how='left' ).fillna(0) # now create an occupancy for each building at each our by adding arrivals and # subtracting departures from each building at each hour occm = {} occm[0] = departm[0].occupants + arrivem[0].countarrive - departm[0].countleave for i in range(1, 24): occm[i] = occm[i-1] + arrivem[i].countarrive - departm[i].countleave # convert occupancy dictionary to a dataframe occupancy = pd.DataFrame(occm) print("counting up occupancy") # add columns with the locations and their land use / categorization # to the occupancy dataframe occupancy["location"]=beginning_location.location occupancy['land_use']=beginning_location.land_use cols=['location', 'land_use']+list(range(23)) # reorder the columns putting location and land use at the beginning cols=['location', 'land_use'] + hr occupancy = occupancy[cols] print("removing zero occupancy locations dataframe") # Remove locations with no occupancy over 24 hours occupancy_clean = occupancy[occupancy.iloc[:, 2:].abs().sum(axis=1) != 0] print("grouping locations by land use type") # Group locations by land use type land_uses = occupancy_clean.land_use.unique() occu_profiles = {} for land in land_uses: profiles = occupancy_clean[occupancy_clean.land_use == land].drop('land_use', axis=1) occu_profiles[land] = profiles.set_index('location') print("plotting occupancy by land use") # plot Occupancy schedules by land use type fig, axs = plt.subplots(5, 2, figsize=(16, 20)) axs_flat = [x for y in axs for x in y] for i, ax in enumerate(axs_flat[:-1]): land_type = list(occu_profiles.keys())[i] df = occu_profiles[land_type] ax.step(hr, df.mean(axis=0), color=[0, 0.45, 0.7], label='average') ax.fill_between( hr, df.min(axis=0), df.max(axis=0), step='pre', color=[0, 0.45, 0.7], alpha=0.5, label='range' ) ax.set_xticks(range(0, 24, 2)) ax.tick_params(labelsize=14) ax.set_xlabel('hour', fontsize=14) ax.set_ylabel('occupancy', fontsize=14) ax.legend(fontsize=14) ax.set_xlim([0,23]) ax.set_ylim([df.min().min() - 1,df.max().max() + 1]) ax.set_title(land_type, fontsize=18) fig.tight_layout() fig.savefig(outfolder + 'occupancy_by_land_use_type.png', bbox_inches='tight', dpi=600) plt.close() print("plotting occupancy histograms") # plot histogram of maximum occupancy by land use type fig, axs = plt.subplots(5, 2, figsize=(12, 20)) axs_flat = [x for y in axs for x in y] for i, ax in enumerate(axs_flat[:-1]): land_type = list(occu_profiles.keys())[i] df = occu_profiles[land_type] ax.hist( x=df.max(axis=1).values, color=[0, 0.45, 0.7], alpha=0.5, label='all buildings' ) ax.axvline( x=df.max(axis=1).mean(), color=[0, 0.45, 0.7], linewidth=2, label='average' ) # ax.set_xticks(range(0, 24, 1)) ax.tick_params(labelsize=14) ax.set_xlabel('Maximum occpuancy', fontsize=14) ax.set_ylabel('Counts', fontsize=14) ax.legend(fontsize=14) ax.set_title(land_type, fontsize=18) fig.tight_layout() fig.savefig( outfolder+'maximum_occupancy_by_land_use_type.png', bbox_inches='tight', dpi=600) plt.close() print("developing schedules") # Export occupancy profile data for key, value in occu_profiles.items(): csv_out = outfolder + f'Detroit_occupancy_{key.lower()}.csv' value.to_csv(csv_out) # Extract schedules with 4+ maximum occupancy and 0+ minimum occupancy occu_profiles_clean = {} for key, value in occu_profiles.items(): occu_profiles_clean[key] = value[(value.max(axis=1) >= 4) & (value.min(axis=1) >= 0)] # Normalize by maximum occupancy occu_profiles_clean_norm = {} for key, value in occu_profiles_clean.items(): occu_profiles_clean_norm[key] = value.div(value.max(axis=1), axis=0) land_types = ['BUSINESS', 'RESIDENTIAL-MULTI'] print("plotting schedules by land use type ") # Cleaned occupancy schedules by land use type for land_type in land_types: fig = plt.figure(figsize=(12, 5)) ax = fig.add_subplot(111) df = occu_profiles_clean[land_type] ax.step(hr, df.mean(axis=0), color=[0, 0.45, 0.7], label='average') ax.fill_between( hr, df.min(axis=0), df.max(axis=0), step='pre', color=[0, 0.45, 0.7], alpha=0.5, label='range' ) ax.set_xticks(range(0, 24, 2)) ax.tick_params(labelsize=14) ax.set_xlabel('hour', fontsize=14) ax.set_ylabel('occupancy', fontsize=14) ax.legend(fontsize=14) ax.set_xlim([0,23]) ax.set_ylim([df.min().min() - 1,df.max().max() + 1]) ax.set_title(land_type, fontsize=18) fig.savefig(outfolder + 'occupancy_clean_{}.png'.format(land_type.lower()), bbox_inches='tight', dpi=600) plt.close() print("plotting average occupancy with 905% CI") # Plot average occupancy profiles with 95% range for land_type in land_types: fig = plt.figure(figsize=(12, 5)) ax = fig.add_subplot(111) df = occu_profiles_clean_norm[land_type] ax.step(hr, df.mean(axis=0), color=[0, 0.45, 0.7], label='average') ax.fill_between( hr, df.quantile(0.025, axis=0), df.quantile(0.975, axis=0), step='pre', color=[0, 0.45, 0.7], alpha=0.5, label='95% range' ) ax.set_xticks(range(0, 24, 2)) ax.tick_params(labelsize=14) ax.set_xlabel('hour', fontsize=14) ax.set_ylabel('occupancy percentage', fontsize=14) ax.legend(fontsize=14) ax.set_xlim([0,23]) ax.set_title(land_type, fontsize=18) fig.savefig(outfolder + f'occupancy_clean_norm_{land_type.lower()}.png', bbox_inches='tight', dpi=600) plt.close() print("exporting data to CSVs") # Export cleaned and normalized data for land_type in land_types: csv_out_clean = outfolder + f'Detroit_occupancy_clean_{land_type.lower()}.csv' csv_out_clean_norm = outfolder + f'Detroit_occupancy_clean_norm_{land_type.lower()}.csv' occu_profiles_clean[land_type].to_csv(csv_out_clean) occu_profiles_clean_norm[land_type].to_csv(csv_out_clean_norm) occu_profiles_clean['BUSINESS'].max(axis=1).value_counts() # Reference schedules from prototype building models ref_sches = { 'occupancy': { 'BUSINESS': [ 0, 0, 0, 0, 0, 0, 0.11, 0.21, 1, 1, 1, 1, 0.53, 1, 1, 1, 1, 0.32, 0.11, 0.11, 0.11, 0.11, 0.05, 0 ], 'RESIDENTIAL-MULTI': [ 1, 1, 1, 1, 1, 1, 1, 0.85, 0.39, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.30, 0.52, 0.87, 0.87, 0.87, 1, 1, 1 ] }, 'light': { 'BUSINESS': [ 0.18, 0.18, 0.18, 0.18, 0.18, 0.23, 0.23, 0.42, 0.9, 0.9, 0.9, 0.9, 0.8, 0.9, 0.9, 0.9, 0.9, 0.61, 0.42, 0.42, 0.32, 0.32, 0.23, 0.18 ], 'RESIDENTIAL-MULTI': [ 0.011, 0.011, 0.011, 0.011, 0.034, 0.074, 0.079, 0.074, 0.034, 0.023, 0.023, 0.023, 0.023, 0.023, 0.023, 0.040, 0.079, 0.113, 0.153, 0.181, 0.181, 0.124, 0.068, 0.028 ] }, 'plug': { 'BUSINESS': [ 0.5, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 1, 1, 1, 0.94, 1, 1, 1, 1, 0.5, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2 ], 'RESIDENTIAL-MULTI': [ 0.45, 0.41, 0.39, 0.38, 0.38, 0.43, 0.54, 0.65, 0.66, 0.67, 0.69, 0.70, 0.69, 0.66, 0.65, 0.68, 0.80, 1.00, 1.00, 0.93, 0.89, 0.85, 0.71, 0.58 ] }, } # Adjust lighting and plug load schedules using KNN regression def adjust_sche(elec_ref, occu_ref, occu, n=3): hours_adjusted = np.asarray(range(1, 25)) / 24 * np.pi occu_ref_array = np.asarray(occu_ref) elec_ref_array = np.asarray(elec_ref) elec = [] for i in range(24): dist = np.sqrt( np.sin(abs(hours_adjusted - (i+1) / 24 * np.pi)) ** 2 + (occu_ref_array - occu[i]) ** 2 ) try: elec.append(elec_ref_array[dist == 0][0]) except IndexError: idxs = np.argsort(dist)[:n] elec.append(
np.average(elec_ref_array[idxs], weights=1/dist[idxs])
numpy.average
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import random class MCLoss(nn.Module): def __init__(self, num_classes=200, cnums=[10, 11], cgroups=[152, 48], p=0.4, lambda_=10): super().__init__() if isinstance(cnums, int): cnums = [cnums] elif isinstance(cnums, tuple): cnums = list(cnums) assert isinstance(cnums, list), print("Error: cnums should be int or a list of int, not {}".format(type(cnums))) assert sum(cgroups) == num_classes, print("Error: num_classes != cgroups.") self.cnums = cnums self.cgroups = cgroups self.p = p self.lambda_ = lambda_ self.celoss = nn.CrossEntropyLoss() self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) def forward(self, feat, targets): n, c, h, w = feat.size() sp = [0] tmp =
np.array(self.cgroups)
numpy.array
# -*- coding: utf-8 -*- """ Created on Thu Dec 10 00:03:08 2015 @author: <NAME> """ import numpy as np import matplotlib.pyplot as pl import path from matplotlib import gridspec def load_txt(filepath): # skip header l = np.loadtxt(filepath,skiprows = 1,unpack = True) return l def summarize(a,b): summary = a,b return summary def save_txt(summary): filename = 'summary.txt' np.savetxt(filename,
np.transpose([summary])
numpy.transpose
import numpy as np import matplotlib.pyplot as plt import aux as a ### DEFINITIONS ### nx = 801 # Pixels in image plane ny = 801 # Pixels in source plane xl = 5.0 # Size of image plane covered (theta_E) yl = 5.0 # Size of source plane covered (theta_E) ### LENS PARAMETERS ### xlens = 0.0 # Lens x-position ylens = 0.0 # Lens y-position mlens = 20.0 # Lens mass (affects Einstein radius) xs = 2.0 * xl / (nx - 1) # Pixel size on image map ys = 2.0 * yl / (ny - 1) # Pixel size on source map # x and y positions of source (circle of radius 0.4) rad = 0.1 x_lst =
np.arange(-1,1,0.1)
numpy.arange
import numpy as np def LMS(input, desired, mu, L): """ Performs LMS adpative filtering on input signal Parameters: input : array-like Input signa; desired : array-like Desired signal mu : float Learning rate L : int Length of adaptive filter Return: y : array-like Filtered signal e : array-like Error signal w : array-like Final filter coefficients (of length L) """ assert len(input) == len( desired), 'Desired and input signals must have equal length' N = len(input) w = np.zeros(L) y = np.zeros(N) x_win = np.zeros(L) e = np.zeros(N) for n in range(N): x_win = np.concatenate((x_win[1:L], [input[n]])) y[n] = np.dot(w, x_win) e[n] = desired[n] - y[n] w = w + mu * e[n] * x_win return y, e, w def NLMS(input, desired, mu=0.1, L=7): """ Performs Norm LMS adpative filtering on input signal Parameters: input : array-like Input signa; desired : array-like Desired signal mu : float Learning rate L : int Length of adaptive filter Return: y : array-like Filtered signal e : array-like Error signal w : array-like Final filter coefficients (of length L) """ assert len(input) == len( desired), 'Desired and input signals must have equal length' N = len(input) w = np.zeros(L) y = np.zeros(N) x_win = np.zeros(L) e = np.zeros(N) for n in range(N): x_win = np.concatenate((x_win[1:L], [input[n]])) y[n] = np.dot(w, x_win) e[n] = desired[n] - y[n] w = w + mu * e[n] * x_win / np.sqrt(np.sum(x_win**2)) return y, e, w def NL_LMS(input, desired, mu, L, g, g_prime): """ Performs Nonlinear LMS adaptive filtering on input signal Parameters: input : array-like Input signa; desired : array-like Desired signal mu : float Learning rate L : int Length of adaptive filter g : lambda (float) : float Nonlinear function, ex: tanh(x) g_prime : lambda (float) : float Derivative of nonlinear function, ex 1/cosh(x)^2 Return: y : array-like Filtered signal e : array-like Error signal w : array-like Final filter coefficients (of length L) """ assert len(input) == len( desired), 'Desired and input signals must have equal length' N = len(input) w = np.zeros(L) y =
np.zeros(N)
numpy.zeros
import unittest import numpy as np import spectral_estimators as se class TestComplexSinusoid(unittest.TestCase): def test_zero(self): for n in range(1, 100): t = np.random.randn(n) y = se.utils.complex_sinusoid(0, t) np.testing.assert_allclose(np.ones(n),
np.real(y)
numpy.real
import sys import os import shutil import collections import warnings from contextlib import contextmanager from typing import Union, Iterable, Sized, Generator, Sequence import wget import requests import tqdm import numpy as np import scipy.special as spec from scipy.interpolate import interp1d from astropy.constants import c # the speed of light from astropy import cosmology from astropy import units import halotools.utils as ht_utils from . import mocksurvey as ms @contextmanager def temp_seed(seed): if seed is None: # Do NOT alter random state do_alter = False elif is_int(seed): # New state with specified seed do_alter = True else: # New state with random seed assert isinstance(seed, str) and seed.lower() == "none", \ f"seed={seed} not understood. Must be int, None, or 'none'" do_alter = True seed = None state = np.random.get_state() if do_alter: np.random.seed(seed) try: yield finally: if do_alter: # noinspection PyTypeChecker np.random.set_state(state) @contextmanager def suppress_stdout(): with open(os.devnull, "w") as devnull: old_stdout = sys.stdout sys.stdout = devnull try: yield finally: sys.stdout = old_stdout def explicit_path(path: str, assert_dir=False, assert_file=False) -> bool: ans = path.startswith((os.path.sep, os.path.curdir, os.path.pardir)) if ans and assert_dir and not os.path.isdir(path): raise NotADirectoryError(f"Explicit path {path} must " f"already exist as a directory.") if ans and assert_file and not os.path.isfile(path): raise FileNotFoundError(f"Explicit path {path} must " f"already exist as a file.") return ans def selector_from_meta(meta: dict): x, y = np.array([meta["x_arcmin"], meta["y_arcmin"]]) / 60 * np.pi / 180 omega = 2 * x * np.sin(y / 2.) selector = ms.LightConeSelector( meta["z_low"], meta["z_high"], omega * (180 / np.pi) ** 2, fieldshape="square", realspace=True) for key in meta.keys(): if key.startswith("selector_"): selector &= eval( meta[key] .replace(" km / (Mpc s),", ",") .replace(" K,", ",") .replace("LightConeSelector", "ms.LightConeSelector") .replace("FlatLambdaCDM", "cosmology.FlatLambdaCDM")) return selector def make_struc_array(names, values, dtypes: Union[Iterable[str], str] = "<f4", subshapes: Union[Sized, None] = None): if subshapes is None: subshapes = [() for _ in names] subshapes = [() if x is None else (tuple(x) if is_arraylike(x) else (x,)) for x in subshapes] if isinstance(dtypes, str): dtypes = [dtypes for _ in names] if len(values): lengths = [len(val) for val in values] length = lengths[0] assert np.all([x == length for x in lengths]), \ f"Arrays must be same length: names={names}, lengths={lengths}" else: length = 0 dtype = [(n, d, s) for n, d, s in zip(names, dtypes, subshapes)] ans = np.zeros(length, dtype=dtype) for n, v in zip(names, values): ans[n] = v return ans def lightcone_array(id=None, upid=None, x=None, y=None, z=None, obs_sm=None, obs_sfr=None, redshift=None, ra=None, dec=None, **kwargs): dtypes = [] array = dict(id=id, upid=upid, x=x, y=y, z=z, obs_sm=obs_sm, obs_sfr=obs_sfr, redshift=redshift, ra=ra, dec=dec, **kwargs) for name in list(array.keys()): if array[name] is None: del array[name] elif name in ("id", "upid"): dtypes.append("<i8") else: dtypes.append("<f4") return make_struc_array(array.keys(), array.values(), dtypes) def apply_over_window(func, a, window, axis=-1, edge_case=None, **kwargs): """ `func` must be a numpy-friendly function which accepts an array as a positional argument and utilizes an `axis` keyword argument This function is just a wrapper for rolling_window, and is essentially implemented by the following code: >>> return func(rolling_window(a, window, axis=axis), axis=-1) See rolling_window docstring for more info """ return func(rolling_window(a, window, axis=axis, edge_case=edge_case), axis=-1, **kwargs) def rolling_window(a, window, axis=-1, edge_case=None): """ Append a new axis of length `window` on `a` over which to roll over the specified `axis` of `a`. The new window axis is always the LAST axis in the returned array. WARNING: Memory usage for this function is O(a.size * window) Parameters ---------- a : array-like Input array over which to add a new axis containing windows window : int Number of elements in each window axis : int (default = -1) The specified axis with which windows are drawn from edge_case : str (default = "replace") We need to choose a scheme of how to deal with the ``window - 1`` windows which contain entries beyond the edge of our specified axis. The following options are supported: edge_case = None | "replace" Windows containing entries beyond the edges will still exist, but those entries will be replaced with the edge entry. The nth axis element will be positioned in the ``window//2``th element of the nth window edge_case = "wrap" Windows containing entries beyond the edges will still exist, and those entries will wrap around the axis. The nth axis element will be positioned in the ``window//2``th element of the nth window edge_case = "contract" Windows containing entries beyond the edges will be removed entirely (e.g., if ``a.shape = (10, 10, 10)``, ``window = 4``, and ``axis = 1`` then the output array will have shape ``(10, 7, 10, 4)`` because the specified axis will be reduced by a length of ``window-1``). The nth axis element will be positioned in the 0th element of the nth window. """ # Input sanitization a = np.asarray(a) window = int(window) axis = int(axis) ndim = len(a.shape) axis = axis + ndim if axis < 0 else axis assert -1 < axis < ndim, "Invalid value for `axis`" assert 1 < window < a.shape[axis], "Invalid value for `window`" assert edge_case in [None, "replace", "contract", "wrap"], \ "Invalid value for `edge_case`" # Convenience function 'onaxes' maps smaller-dimensional arrays # along the desired axes of dimension of the output array def onaxes(*axes): return tuple(slice(None) if i in axes else None for i in range(ndim + 1)) # Repeat the input array `window` times, adding a new axis at the end rep = np.repeat(a[..., None], window, axis=-1) # Create `window`-lengthed index arrays that increase by one # for each window (i.e., rolling indices) ind = np.repeat(np.arange(a.shape[axis])[:, None], window, axis=-1 )[onaxes(axis, ndim)] ind += np.arange(window)[onaxes(ndim)] # Handle the edge cases if (edge_case is None) or (edge_case == "replace"): ind -= window // 2 ind[ind < 0] = 0 ind[ind >= a.shape[axis]] = a.shape[axis] - 1 elif edge_case == "wrap": ind -= window // 2 ind %= a.shape[axis] elif edge_case == "contract": ind = ind[tuple(slice(1 - window) if i == axis else slice(None) for i in range(ndim + 1))] # Select the output array using our array of rolling indices `ind` selection = tuple(ind if i == axis else np.arange(rep.shape[i])[onaxes(i)] for i in range(ndim + 1)) return rep[selection] def generate_sublists(full_list: Sized, sublength: int) -> Generator: """Break up a list into sub-lists of a given length""" def generator(): i = 0 imax = len(full_list) while i < imax: yield full_list[i: (i := i + sublength)] return generator() def rejoin_sublists(sub_lists: Iterable) -> Generator: """Iterate over items in sub-lists created by generate_sublists()""" if hasattr(sub_lists, "tolist") and callable(sub_lists.tolist): sub_lists = sub_lists.tolist() def generator(): for sub_list in sub_lists: for item in sub_list: yield item return generator() def unbiased_std_factor(n): """ Returns 1/c4(n) """ if is_arraylike(n): wh = n < 343 ans = np.ones(np.shape(n)) * (4. * n - 3.) / (4. * n - 4.) n = n[wh] ans[wh] = spec.gamma((n - 1) / 2) / np.sqrt(2 / (n - 1)) / spec.gamma(n / 2) return ans else: ans = spec.gamma((n - 1) / 2) / np.sqrt(2 / (n - 1)) / spec.gamma(n / 2) return ans if n < 343 else (4. * n - 3.) / (4. * n - 4.) def auto_bootstrap(func, args, nbootstrap=50): results = [func(*args) for _ in range(nbootstrap)] results = np.array(results) mean = np.nanmean(results, axis=0) std = np.nanstd(results, axis=0, ddof=1) return mean, std # noinspection PyPep8Naming def get_N_subsamples_len_M(sample, N, M, norepeats=False, suppress_warning=False, seed=None): """ Returns (N,M,*) array containing N subsamples, each of length M. We require M < L, where (L,*) is the shape of `sample`. If norepeats=True, then we require N*M < L.""" with temp_seed(seed): assert (is_arraylike(sample)) maxM = len(sample) assert (M <= maxM) maxN = np.math.factorial(maxM) // (np.math.factorial(M) * np.math.factorial(maxM - M)) if N is None: N = int(maxM // M) assert (N <= maxN) if norepeats: if N * M > maxM: msg = "Warning: Cannot make %d subsamples without repeats\n" % N N = int(maxM / float(M)) msg += "Making %d subsamples instead" % N if not suppress_warning: print(msg) sample = np.asarray(sample) newshape = (N, M, *sample.shape[1:]) newsize = N * M np.random.shuffle(sample) return sample[:newsize].reshape(newshape) if isinstance(sample, np.ndarray): return get_N_subsamples_len_M_numpy(sample, N, M, maxM, seed) else: return get_N_subsamples_len_M_list(sample, N, M, maxM, seed) # noinspection PyPep8Naming def get_N_subsamples_len_M_list(sample, N, M, maxM, seed=None): with temp_seed(seed): i = 0 subsamples = [] while i < N: subsample = set(np.random.choice(maxM, M, replace=False)) if subsample not in subsamples: subset = [] for index in subsample: subset.append(sample[index]) subsamples.append(subset) i += 1 return subsamples # noinspection PyPep8Naming def get_N_subsamples_len_M_numpy(sample, N, M, maxM, seed=None): with temp_seed(seed): i = 0 subsamples = np.zeros((N, maxM), dtype=bool) while i < N: subsample = np.random.choice(maxM, M, replace=False) subsample = np.bincount(subsample, minlength=maxM).astype(bool) if np.any(np.all(subsample[None, :] == subsamples[:i, :], axis=1)): continue else: subsamples[i, :] = subsample i += 1 subset = np.tile(sample, (N, *[1] * len(sample.shape)))[subsamples].reshape((N, M, *sample.shape[1:])) return subset def is_arraylike(a): # return isinstance(a, (tuple, list, np.ndarray)) return isinstance(a, collections.abc.Container ) and not isinstance(a, str) def is_int(a): return np.asarray(a).dtype.kind == "i" def angular_separation(ra1, dec1, ra2=0, dec2=0): """All angles (ra1, dec1, ra2=0, dec2=0) must be given in radians""" cos_theta = np.sin(dec1) * np.sin(dec2) + np.cos(dec1) * np.cos(dec2) * np.cos(ra1 - ra2) return np.arccos(cos_theta) def angle_to_dist(angle, redshift, cosmo, deg=False): if deg: angle *= np.pi / 180. angle = min([angle, np.pi / 2.]) z = comoving_disth(redshift, cosmo) dist = z * 2 * np.tan(angle / 2.) return dist def redshift_lim_to_dist(delta_redshift, mean_redshift, cosmo): redshifts = np.asarray([mean_redshift - delta_redshift / 2., mean_redshift + delta_redshift / 2.]) distances = comoving_disth(redshifts, cosmo) dist = distances[1] - distances[0] return dist # noinspection PyPep8Naming def get_random_center(Lbox, fieldshape, numcenters=None, seed=None, pad=30): with temp_seed(seed): # origin_shift = np.asarray(origin_shift) Lbox = np.asarray(Lbox) fieldshape = np.asarray(fieldshape) if numcenters is None: shape = 3 else: shape = (numcenters, 3) if pad is None: pad = np.array([0., 0., 0.]) else: pad = np.asarray(pad) assert (np.all(2. * pad + fieldshape <= Lbox)) xyz_min = np.random.random(shape) * (Lbox - fieldshape - 2. * pad) # - origin_shift center = xyz_min + fieldshape / 2. + pad return center # noinspection PyPep8Naming def get_random_gridded_center(Lbox, fieldshape, numcenters=None, pad=None, replace=False, seed=None): with temp_seed(seed): Lbox = np.asarray(Lbox) fieldshape = np.asarray(fieldshape) if numcenters is None: numcenters = 1 one_dim = True else: one_dim = False centers = grid_centers(Lbox, fieldshape, pad) if not replace and numcenters > len(centers): raise ValueError("numcenters=%d, but there are only %d possible grid centers" % (numcenters, len(centers))) if isinstance(numcenters, str) and numcenters.lower().startswith("all"): numcenters = len(centers) which = np.random.choice(np.arange(len(centers)), numcenters, replace=replace) centers = centers[which] if one_dim: return centers[0] else: return centers # noinspection PyPep8Naming def grid_centers(Lbox, fieldshape, pad=None): if pad is None: pad = np.array([0., 0., 0.]) nbd = (Lbox / (np.asarray(fieldshape) + 2 * pad)).astype(int) xcen, ycen, zcen = [np.linspace(0, Lbox[i], nbd[i] + 1)[1:] for i in range(3)] centers = np.asarray(np.meshgrid(xcen, ycen, zcen)).reshape((3, xcen.size * ycen.size * zcen.size)).T centers -= np.asarray([xcen[0], ycen[0], zcen[0]])[np.newaxis, :] / 2. return centers def sample_fraction(sample, fraction, seed=None): with temp_seed(seed): assert (0 <= fraction <= 1) if hasattr(sample, "__len__"): n = len(sample) return_indices = False else: n = sample return_indices = True nfrac = int(n * fraction) indices = np.random.choice(n, nfrac, replace=False) if return_indices: return indices else: return sample[indices] def kwargs2attributes(obj, kwargs): class_name = str(obj.__class__).split("'")[1].split(".")[1] if not set(kwargs).issubset(obj.__dict__): valid_keys = obj.__dict__.keys() bad_keys = set(kwargs) - valid_keys raise KeyError("Invalid keys %s in %s creation. Valid keys are: %s" % (str(bad_keys), class_name, str(valid_keys))) for key in set(kwargs.keys()): if kwargs[key] is None: del kwargs[key] obj.__dict__.update(kwargs) def rdz2xyz(rdz, cosmo, use_um_convention=False, deg=False): """If cosmo=None then z is assumed to already be distance, not redshift.""" if cosmo is None: dist = rdz[:, 2] else: dist = comoving_disth(rdz[:, 2], cosmo) if deg: rdz = rdz.copy() rdz[:, :2] *= np.pi / 180.0 z = (dist * np.cos(rdz[:, 1]) * np.cos(rdz[:, 0])).astype(np.float32) x = (dist * np.cos(rdz[:, 1]) * np.sin(rdz[:, 0])).astype(np.float32) y = (dist * np.sin(rdz[:, 1])).astype(np.float32) xyz = np.vstack([x, y, z]).T if use_um_convention: xyz = xyz_convention_ms2um(xyz) return xyz # in Mpc/h def xyz_convention_ms2um(xyz): # Convert an xyz array from mocksurvey convention (left-handed; z=los) # to UniverseMachine convention (right-handed; x=los) xyz = xyz[:, [2, 0, 1]] xyz[:, 1] *= -1 return xyz def redshift_rest_flux_correction(from_z, to_z, cosmo): shift = (1 + from_z) / (1 + to_z) dist = (cosmo.luminosity_distance(from_z).value / cosmo.luminosity_distance(to_z).value) return shift * dist ** 2 def comoving_disth(redshifts, cosmo): z = np.asarray(redshifts) dist = cosmo.comoving_distance(z).value * cosmo.h return (dist.astype(z.dtype) if is_arraylike(dist) else dist) def distance2redshift(dist, cosmo, vr=None, zprec=1e-3, h_scaled=True): c_km_s = c.to('km/s').value dist_units = units.Mpc / cosmo.h if h_scaled else units.Mpc def d2z(d): return cosmology.z_at_value( cosmo.comoving_distance, d * dist_units, -0.99) if not is_arraylike(dist): return d2z(dist) if len(dist) == 0: return np.array([]) zmin, zmax = [d2z(f(dist)) for f in [min, max]] zmin = (zmin + 1) * .99 - 1 zmax = (zmax + 1) * 1.01 - 1 # compute cosmological redshift + doppler shift num_points = int((zmax - zmin) / zprec) + 2 yy = np.linspace(zmin, zmax, num_points, dtype=np.float32) xx = cosmo.comoving_distance(yy).value.astype(np.float32) if h_scaled: xx *= cosmo.h f = interp1d(xx, yy, kind='cubic') z_cos = f(dist).astype(np.float32) # Add velocity distortion if vr is None: redshift = z_cos else: redshift = z_cos + (vr / c_km_s) * (1.0 + z_cos) return redshift def ra_dec_z(xyz, vel=None, cosmo=None, zprec=1e-3, deg=False): """ Convert position array `xyz` and velocity array `vel` (optional), each of shape (N,3), into ra/dec/redshift array, using the (ra,dec) convention of :math:`\\hat{z} \\rightarrow ({\\rm ra}=0,{\\rm dec}=0)`, :math:`\\hat{x} \\rightarrow ({\\rm ra}=\\frac{\\pi}{2},{\\rm dec}=0)`, :math:`\\hat{y} \\rightarrow ({\\rm ra}=0,{\\rm dec}=\\frac{\\pi}{2})` If cosmo is None, redshift is replaced with comoving distance (same units as xyz) """ if cosmo is not None: # remove h scaling from position so we can use the cosmo object xyz = xyz / cosmo.h # comoving distance from observer (at origin) r = np.sqrt(xyz[:, 0] ** 2 + xyz[:, 1] ** 2 + xyz[:, 2] ** 2) r_cyl_eq = np.sqrt(xyz[:, 2] ** 2 + xyz[:, 0] ** 2) # radial velocity from observer (at origin) if vel is None: vr = None else: r_safe = r.copy() r_safe[r_safe == 0] = 1. vr = np.sum(xyz * vel, axis=1) / r_safe if cosmo is None: redshift = r else: redshift = distance2redshift(r, cosmo, vr, zprec, h_scaled=False) # calculate spherical coordinates # theta = np.arccos(xyz[:, 2]/r) # <--- causes large round off error near (x,y) = (0,0) # theta = np.arctan2(r_cyl, xyz[:, 2]) # phi = np.arctan2(xyz[:, 1], xyz[:, 0]) # Put ra,dec = 0,0 on the z-axis dec = np.arctan2(xyz[:, 1], r_cyl_eq) ra = np.arctan2(xyz[:, 0], xyz[:, 2]) if deg: ra *= 180 / np.pi dec *= 180 / np.pi return np.vstack([ra, dec, redshift]).T.astype(np.float32) def update_table(table, coldict): for key in coldict: table[key] = coldict[key] def xyz_array(struc_array, keys=None, attributes=False): if keys is None: keys = ['x', 'y', 'z'] if attributes: struc_array = struc_array.__dict__ return np.vstack([struc_array[key] for key in keys]).T # noinspection PyPep8Naming,PyUnusedLocal def logN(data, rands, njackknife=None, volume_factor=1): del rands if njackknife is None: jackknife_factor = 1 else: n = np.product(njackknife) jackknife_factor = n / float(n - 1) return np.log(volume_factor * jackknife_factor * len(data)) # noinspection PyUnusedLocal,PyShadowingNames def logn(data, rands, volume, njackknife=None): del rands if njackknife is None: jackknife_factor = 1 else: n = np.product(njackknife) jackknife_factor = n / float(n - 1) return np.log(jackknife_factor * len(data) / float(volume)) # noinspection PyPep8Naming def rand_rdz(N, ralim, declim, zlim, cosmo=None, seed=None): """ Returns an array of shape (N,3) with columns ra,dec,z (z is treated as distance, unless cosmo is specified) within the specified limits such that the selected points are chosen randomly over a uniform distribution Caution: Limits beyond dec = +/-pi/2 will be trimmed silently """ declim = [max(min(declim), -np.pi/2), min(max(declim), np.pi/2)] with temp_seed(seed): N = int(N) ans = np.random.random((N, 3)) ans[:, 0] = (ralim[1] - ralim[0]) * ans[:, 0] + ralim[0] ans[:, 1] = np.arcsin((np.sin(declim[1]) - np.sin(declim[0])) * ans[:, 1] + np.sin(declim[0])) ans[:, 2] = ((zlim[1] ** 3 - zlim[0] ** 3) * ans[:, 2] + zlim[0] ** 3) ** (1. / 3.) if cosmo is not None: ans[:, 2] = distance2redshift(ans[:, 2], cosmo=cosmo, vr=None) return ans def volume(sqdeg, zlim, cosmo=None): """ Returns the comoving volume of a chunk of a sphere in units of [Mpc/h]^3. z is interpreted as distance [Mpc/h] unless cosmo is given """ if cosmo is not None: zlim = comoving_disth(zlim, cosmo) omega = sqdeg * (np.pi/180.) ** 2 return omega/3. * (zlim[1] ** 3 - zlim[0] ** 3) def volume_rdz(ralim, declim, zlim, cosmo=None): """ Returns the comoving volume of a chunk of a sphere of given limits in ra, dec, and z. z is interpreted as distance unless cosmo is given """ if cosmo is not None: zlim = comoving_disth(zlim, cosmo) omega = 2. * (ralim[1] - ralim[0]) * np.sin((declim[1] - declim[0]) / 2.) return omega/3. * (zlim[1] ** 3 - zlim[0] ** 3) def rdz_distance(rdz, rdz_prime, cosmo=None): """ rdz is an array of coordinates of shape (N,3) while rdz_prime is a single point of comparison of shape (3,) z is interpreted as radial distance unless cosmo is given Returns the distance of each rdz coordinate from rdz_prime """ if cosmo is not None: rdz[:, 2] = comoving_disth(rdz[:, 2], cosmo) r, d, z = rdz.T rp, dp, zp = rdz_prime return np.sqrt(r ** 2 + rp ** 2 - 2. * r * rp * (np.cos(d) * np.cos(dp) * np.cos(r - rp) + np.sin(d) * np.sin(dp))) def xyz_distance(xyz, xyz_prime): x, y, z = xyz.T xp, yp, zp = xyz_prime return np.sqrt((x - xp) ** 2 + (y - yp) ** 2 + (z - zp) ** 2) def unit_vector(theta, phi): x = np.sin(theta) * np.cos(phi) y = np.sin(theta) * np.sin(phi) z = np.cos(theta) return x, y, z def make_npoly(radius, n): import spherical_geometry.polygon as spoly phi1 = 2. * np.pi / float(n) points = [unit_vector(radius, phi1 * i) for i in
np.arange(n)
numpy.arange
import tensorflow as tf import numpy as np from model import Unet import sys import skimage.io as io import cv2 from cv2 import resize sys.path.append("../tools") from pycocotools.coco import COCO from pycocotools import mask from utils import img_generator, probaToBinaryMask import argparse from tqdm import tqdm def arg_parser(): parser = argparse.ArgumentParser() parser.add_argument("--nb_classes", default = "10", type = int, help = "number of categories") parser.add_argument("--epochs", default = "10", type = int, help = "number of epochs") parser.add_argument("--batch_size", default = "2", type = int, help = "size of miniibatch") parser.add_argument("--learning_rate", default = "0.001", type = float, help = "learning_rate") parser.add_argument("--loss", default = "crossentropy", help = "type of loss function : crossentropy or dice") args = parser.parse_args() return args class Trainer: def __init__(self, args): #save args self.args = args #init coco utils self.coco_train = COCO("../annotations/instances_train2014.json") self.coco_val = COCO("../annotations/instances_val2014.json") #init tensorflow session tf.reset_default_graph() config = tf.ConfigProto(allow_soft_placement=True) config.gpu_options.allow_growth = True self.sess = tf.Session(config = config) #init model self.input_img = tf.placeholder(tf.float32, shape = (None,None,None,3)) self.label = tf.placeholder(tf.float32, shape = (None,None,None,args.nb_classes)) self.model = Unet(input_img = self.input_img, nb_classes = args.nb_classes) #define loss : Cross Entropy and Dice with tf.variable_scope('optimization'): with tf.variable_scope('loss'): if args.loss == 'crossentropy': """logits = tf.reshape(self.model.output_log, [-1, args.nb_classes]) labels = tf.reshape(self.label, [-1, args.nb_classes])""" self.loss = -tf.reduce_mean(tf.multiply(self.label,tf.log(self.model.output_proba))) elif args.loss == "dice": labels = self.label proba = self.model.output_proba intersection = tf.reduce_sum(proba*labels) union = tf.reduce_sum(proba + labels) self.loss = -intersection/union #Optimizer self.optimizer = tf.train.MomentumOptimizer(learning_rate=args.learning_rate, momentum=0.99) self.train_op = self.optimizer.minimize(self.loss) #summary file for tensorboard self.tf_train_loss = tf.Variable(0.0, trainable = False, name = 'Train_Loss') self.tf_train_loss_summary = tf.summary.scalar("Loss", self.tf_train_loss) self.tf_train_accuracy = tf.Variable(0.0, trainable = False, name = 'Train_Accuracy') self.tf_train_accuracy_summary = tf.summary.scalar("Train Accuracy", self.tf_train_accuracy) self.tf_train_dice = tf.Variable(0.0, trainable=False, name="Train_Dice_Coef") self.tf_train_dice_summary = tf.summary.scalar("Train Dice Coef", self.tf_train_dice) self.tf_eval_accuracy = tf.Variable(0.0, trainable = False, name = 'Eval_accuracy') self.tf_eval_accuracy_summary = tf.summary.scalar('Evaluation Accuracy', self.tf_eval_accuracy) self.tf_eval_dice = tf.Variable(0.0, trainable = False, name = "Eval_Dice_Coef") self.tf_eval_dice_summary = tf.summary.scalar("Evaluation Dice Coef", self.tf_eval_dice) self.writer = tf.summary.FileWriter('./graphs', self.sess.graph) #saver self.saver = tf.train.Saver() self.sess.run(tf.initialize_all_variables()) def save_model(self, filename): with tf.Graph().as_default(): self.saver.save(self.sess, filename) def train(self): with tf.Graph().as_default(): for i_epoch in range(1, self.args.epochs+1): #init paramters for summary loss_train = [] accuracy_train = [] accuracy_val = [] dice_train = [] dice_val = [] #streaming image #images_train = img_generator('images_train.json') #images_val = img_generator('images_val.json') #checkpoint self.save_model(filename = './checkpoints/checkpoint_epoch-{}.ckpt'.format(i_epoch)) #train catIDs = list(range(1,self.args.nb_classes+1)) print("Epoch {} \n".format(i_epoch)) print("Train \n") #minibatch minibatch_image = [] minibatch_label = [] count = 0 #Find images with categories imgIds = self.coco_train.getImgIds(catIds = catIDs) catIDs = [x-1 for x in catIDs] for imgId in tqdm(imgIds): count += 1 #get image image = self.coco_train.loadImgs([imgId]) #create grouth truth map y = np.zeros((512, 512, self.args.nb_classes)) for cat in catIDs: annIds = self.coco_train.getAnnIds(imgIds = image[0]['id'], catIds = [cat+1]) anns = self.coco_train.loadAnns(annIds) if len(anns) > 0: for ann in anns: mask = self.coco_train.annToMask(ann) mask = resize(mask, (512,512), interpolation = cv2.INTER_NEAREST) y[:,:,cat] = np.logical_or(y[:,:,cat], mask).astype(np.float32) #import image img = io.imread("../train2014/{}".format(image[0]["file_name"])) img = resize(img, (512, 512)) if img.shape == (512,512): img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) minibatch_image.append(img) minibatch_label.append(y) if len(minibatch_image) == self.args.batch_size or count == len(imgIds): # get loss training loss_train.append(self.sess.run(self.loss, feed_dict={ self.input_img:
np.asarray(minibatch_image)
numpy.asarray
from Synthetic_Dataset import Synthetic_Dataset import random import numpy as np import math import torch import torch.nn as nn import matplotlib.pyplot as plt import torchvision.utils as vutils from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision import transforms from torchvision.datasets import CIFAR10, MNIST from torchvision.models.inception import inception_v3 import argparse from Run_GAN_Training import * from ComputationalTools import * from models import MLP, ResNet18 aux_model_folder = "Aux_Models" if not os.path.exists(aux_model_folder): os.makedirs(aux_model_folder) def Get_classification_logit_prob_class(net, input, device=torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')): with torch.no_grad(): pred_logits = net(torch.from_numpy(input).to(device).float()) # print(pred_logits) pred_probs = F.softmax(pred_logits, dim=1).data.cpu().numpy() # print(pred_probs) mean_pred_probs = np.mean(pred_probs, axis=0) # print(mean_pred_probs) pred_classes = np.argmax(pred_probs, axis=1) # print(pred_classes) pred_classes_one_hot = np.zeros_like(pred_probs) pred_classes_one_hot[np.arange(len(pred_probs)), pred_classes] = 1 # print(pred_classes_one_hot) pred_classes_count = np.sum(pred_classes_one_hot, axis=0) # print(pred_classes_count) mode_num = np.sum(pred_classes_count[:-1] > 0) # print(mode_num) return mean_pred_probs, mode_num, pred_classes_count def Load_aux_classifier(dataset_config): print("dataset_config", dataset_config) aux_model_checkpoint_folder_list = glob.glob(os.path.join(aux_model_folder, f"{dataset_config}*")) print("aux_model_folder", aux_model_folder) print("dataset_config", dataset_config) print("aux_model_checkpoint_folder_list", aux_model_checkpoint_folder_list) aux_model_checkpoint_folder = aux_model_checkpoint_folder_list[0] aux_model_checkpoint_path_list = glob.glob(os.path.join(aux_model_checkpoint_folder, f"*.pth")) aux_model_checkpoint_path = aux_model_checkpoint_path_list[0] """ load_models """ checkpoint = torch.load(aux_model_checkpoint_path) args = checkpoint["args"] rng =
np.random.RandomState(seed=args.seed)
numpy.random.RandomState
import numpy as np import math def house(v): v = v.copy() sigma = np.dot(v[1:], v[1:]) print('v = {}'.format(v)) x0 = v[0] print('x0 = {}'.format(x0)) if sigma > 0: mu = math.sqrt(x0*x0 + sigma) print('mu = {}'.format(mu)) if x0 <= 0: v0 = x0 - mu else: v0 = -sigma/(x0 + mu) v02 = v0*v0 print('v02 = {}'.format(v02)) beta = 2*v02/(sigma + v02) print('beta = {}'.format(beta)) v = v / v0 v[0] = 1 print('v = {}'.format(v)) elif x0 < 0: beta = 2 v[0] = 1 else: beta = 0 v[0] = 1 return beta, v A = np.array([[1, -1],[1, 1]]) n = 2 A0 = A beta, v0 = house(A0[:,0]) print("v0 = {}".format(v0)) v0 = v0.reshape((n,1)) print("v0 = {}".format(v0)) rho = np.dot(v0.transpose(),A[:,1:]) print("rho = {}".format(rho)) Q0 = np.eye(n) - beta * np.dot(v0, v0.transpose()) print("Q0 = {}".format(Q0)) A1 = np.dot(Q0, A0) print("A1 = {}".format(A1)) beta, v1 = house(A1[1:,1]) print("v1 = {}".format(v1)) v1 =
np.vstack((0, v1))
numpy.vstack
#!/usr/bin/env python from __future__ import print_function, division import argparse from multiprocessing import Pool, cpu_count import numpy as np # linear algebra import dicom import os import scipy.ndimage from skimage import measure, morphology from skimage.segmentation import clear_border import time from common import save, load DESCRIPTION = """ Explain the script here Following the tutorial given here: https://www.kaggle.com/gzuidhof/data-science-bowl-2017/full-preprocessing-tutorial Date accessed: 3/7/17 """ def make_arg_parser(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument('-i', '--input', help='<PATH> The input folder', type=str, required=True) parser.add_argument('--min_bound', type=int, default=-1000) parser.add_argument('--max_bound', type=int, default=400) parser.add_argument('--pixel_mean', type=float, default=.25) parser.add_argument('-d', '--debug', type=bool, default=False) parser.add_argument('-o', '--output', help='<PATH> The output folder', type=str, required=True) return parser # Load the scans in given folder path def load_scan(path): slices = [dicom.read_file(os.path.join(path, s)) for s in os.listdir(path)] slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) slice_thickness = 0 index = 0 while slice_thickness == 0: try: slice_thickness = slices[index].SliceLocation - slices[index+1].SliceLocation except AttributeError: slice_thickness = slices[index].ImagePositionPatient[2] - slices[index+1].ImagePositionPatient[2] index += 1 slice_thickness = np.abs(slice_thickness) for s in slices: s.SliceThickness = slice_thickness return slices def get_pixels_hu(slices): image = np.stack([s.pixel_array for s in slices]) # Convert to int16 (from sometimes int16), # should be possible as values should always be low enough (<32k) image = image.astype(np.int16) # Set outside-of-scan pixels to 0 # The intercept is usually -1024, so air is approximately 0 image[image == -2000] = 0 # Convert to Hounsfield units (HU) for slice_number in range(len(slices)): intercept = slices[slice_number].RescaleIntercept slope = slices[slice_number].RescaleSlope if slope != 1: image[slice_number] = slope * image[slice_number].astype(np.float64) image[slice_number] = image[slice_number].astype(np.int16) image[slice_number] += np.int16(intercept) return np.array(image, dtype=np.int16) def largest_label_volume(im, bg=-1): vals, counts = np.unique(im, return_counts=True) counts = counts[vals != bg] vals = vals[vals != bg] if len(counts) > 0: return vals[np.argmax(counts)] else: return None def segment_lung_mask(image, fill_lung_structures=True): # not actually binary, but 1 and 2. # 0 is treated as background, which we do not want binary_image = np.array(image > -400, dtype=np.int8) + 1 binary_image = np.array([clear_border(binary_image[i]) for i in range(binary_image.shape[0])]) labels = measure.label(binary_image) # Pick the pixel in the very corner to determine which label is air. # Improvement: Pick multiple background labels from around the patient # More resistant to "trays" on which the patient lays cutting the air # around the person in half background_label = labels[0, 0, 0] # Fill the air around the person binary_image[background_label == labels] = 2 # Method of filling the lung structures (that is superior to something like # morphological closing) if fill_lung_structures: # For every slice we determine the largest solid structure for i, axial_slice in enumerate(binary_image): axial_slice = axial_slice - 1 labeling = measure.label(axial_slice) l_max = largest_label_volume(labeling, bg=0) if l_max is not None: # This slice contains some lung binary_image[i][labeling != l_max] = 1 binary_image -= 1 # Make the image actual binary binary_image = 1 - binary_image # Invert it, lungs are now 1 # Remove other air pockets insided body labels = measure.label(binary_image, background=0) l_max = largest_label_volume(labels, bg=0) if l_max is not None: # There are air pockets binary_image[labels != l_max] = 0 return binary_image # DO THIS ONLINE # MIN_BOUND = -1000.0 # MAX_BOUND = 400.0 # PIXEL_MEAN = 0.25 def normalize(image, min_bound=-1000, max_bound=400): image = (image - min_bound) / (max_bound - min_bound) image[image > 1] = 1. image[image < 0] = 0. return image # DO THIS OFFLINE # pixel_corr = 350 def zero_center(image, pixel_mean=350): image = image - pixel_mean return image def resize(img, shape=(50, 50, 20)): img = img.transpose(2, 1, 0) zoom_factors = [i/float(j) for i, j in zip(shape, img.shape)] img = scipy.ndimage.interpolation.zoom(img, zoom=zoom_factors, order=1, mode='nearest') return img def add_zero_padding(ndarray): max_dim = np.max(ndarray.shape) zeros = np.zeros(shape=[max_dim]*3) offsets = np.array((max_dim - ndarray.shape) / 2, dtype=np.int8) zeros[offsets[0]:ndarray.shape[0]+offsets[0], offsets[1]:ndarray.shape[1]+offsets[1], offsets[2]:ndarray.shape[2]+offsets[2]] = ndarray return zeros def process_patient(fargs): input_folder, outfile, args = fargs t0 = time.clock() patient = load_scan(input_folder) curr_patient_pixels = get_pixels_hu(patient) # DEBUG # print(curr_patient_pixels.shape) # if (np.array(curr_patient_pixels.shape) == 0).any(): # print(input_folder) pix_resampled, spacing = resample(curr_patient_pixels, patient, [1, 1, 1]) del patient del curr_patient_pixels # Not sure exactly what that means segmented_lungs_fill_masked = segment_lung_mask(pix_resampled, True) print(np.sum(segmented_lungs_fill_masked) / float(np.prod(segmented_lungs_fill_masked.shape))) # Take care of some edge cases if np.sum(segmented_lungs_fill_masked) / float(
np.prod(segmented_lungs_fill_masked.shape)
numpy.prod
#!/usr/bin/env python # coding: utf-8 # # MFRpred # # This is the MFRpred code runnning as a jupyter notebook, about the prediction of flux rope magnetic fields # # Authors: <NAME>, <NAME>, M. Reiss Space Research Institute IWF Graz, Austria # Last update: July 2020 # # How to predict the rest of the MFR if first 10, 20, 30, 40, 50% are seen? # Everything should be automatically with a deep learning method or ML fit methods # # --- # MIT LICENSE # # Copyright 2020, <NAME>, <NAME>, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # In[2]: import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib import cm from scipy import stats import scipy.io import sunpy.time import numpy as np import time import pickle import seaborn as sns import pandas as pd import os import sys from sunpy.time import parse_time from sklearn.model_selection import cross_val_score from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolute_error, mean_squared_error, median_absolute_error, r2_score from sklearn.feature_selection import SelectKBest, SelectPercentile, f_classif from sklearn.linear_model import LinearRegression from sklearn.linear_model import Lasso from sklearn.linear_model import Ridge from sklearn.linear_model import ElasticNet from sklearn.linear_model import HuberRegressor from sklearn.linear_model import Lars from sklearn.linear_model import LassoLars from sklearn.linear_model import PassiveAggressiveRegressor from sklearn.linear_model import RANSACRegressor from sklearn.linear_model import SGDRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from pandas.plotting import scatter_matrix import warnings warnings.filterwarnings('ignore') #get all variables from the input.py file: from input import feature_hours #make new directory if it not exists mfrdir='mfr_predict' if os.path.isdir(mfrdir) == False: os.mkdir(mfrdir) plotdir='plots' if os.path.isdir(plotdir) == False: os.mkdir(plotdir) os.system('jupyter nbconvert --to script mfrpred.ipynb') # # 1 feature selection # # # In[5]: # sns.set_context("talk") # sns.set_style("darkgrid") sns.set_context("notebook", font_scale=0.4, rc={"lines.linewidth": 2.5}) #usage of script: python mfr_featureSelection.py wind_features.p sta_features.p stb_features.p --features # if --features is set, then code will produce pickle-file with features and labels # if --features is not set, then code will read from already existing pickle-file # you only have to set features at the first run of the code, or if you changed something in the corresponding parts of the code # then --features if features need to be determined again # and --mfr if there are shall be no sheath features determined features = True if features: print("get features") mfr = False if mfr: print("only mfr") # first three arguments need to be file names to save features into - argv0='wind_features.p' argv1='sta_features.p' argv2='stb_features.p' # ####################### functions ############################################### def get_feature(sc_time, start_time, end_time, sc_ind, sc_feature, feature_hours, *VarArgs): feature_mean = np.zeros(np.size(sc_ind)) feature_max = np.zeros(np.size(sc_ind)) feature_std = np.zeros(np.size(sc_ind)) for Arg in VarArgs: if Arg == 'mean': for p in np.arange(0, np.size(sc_ind)): # extract values from MFR data feature_temp = sc_feature[np.where(np.logical_and(sc_time > start_time[sc_ind[p]], sc_time < end_time[sc_ind[p]] + feature_hours / 24.0))] # print(feature_temp) feature_mean[p] = np.nanmean(feature_temp) # print('mean') elif Arg == 'std': for p in np.arange(0, np.size(sc_ind)): # extract values from MFR data feature_temp = sc_feature[np.where(np.logical_and(sc_time > start_time[sc_ind[p]], sc_time < end_time[sc_ind[p]] + feature_hours / 24.0))] # print(feature_temp) feature_std[p] = np.nanstd(feature_temp) elif Arg == 'max': for p in np.arange(0, np.size(sc_ind)): # extract values from MFR data feature_temp = sc_feature[np.where(np.logical_and(sc_time > start_time[sc_ind[p]], sc_time < end_time[sc_ind[p]] + feature_hours / 24.0))] # print(feature_temp) feature_temp = feature_temp[np.isfinite(feature_temp)] try: feature_max[p] = np.max(feature_temp) except ValueError: # raised if `y` is empty. pass # print('max') if np.any(feature_mean) and np.any(feature_max) and np.any(feature_std): # print('mean and std and max') return feature_mean, feature_max, feature_std elif np.any(feature_mean) and np.any(feature_max) and (not np.any(feature_std)): # print('mean and max') return feature_mean, feature_max elif np.any(feature_mean) and (not np.any(feature_max)) and (not np.any(feature_std)): # print('only mean') return feature_mean elif (not np.any(feature_mean)) and np.any(feature_max) and np.any(feature_std): # print('max and std') return feature_max, feature_std elif (not
np.any(feature_mean)
numpy.any
#!/usr/bin/env python """This is the grow_tree.py module. This module contains code required to generate morphologically accurate tree structures from data. Some of this code is specific to growing to fill well defined shapes. The code is not optimised, and there are other tools developed by our group that can generate tree structures into more complex shapes more rapidly, using precompiled code-bases. Please contact us for advice on using these tools. """ import numpy as np from . import pg_utilities from . import analyse_tree def grow_large_tree(angle_max, angle_min, fraction, min_length, point_limit, volume, thickness, ellipticity, datapoints, initial_geom, random_seed): ''' :Function name: **grow_tree_large** This function uses the volume filling branching algorithm to grow a tree structure toward an arbitrary set of data points. At this stage the algorithm does not check whether the tree is within the volume at each growth point. However, this functionality is available in other group softwares, please ask a group member to advise if you wish to use these other softwares. :inputs: :inputs: - angle_max: The maximum angle between two branches - angle_min: The miniumum angle between two branches - fraction: The fraction of distance between stem and datapoint centre of mass to grow - min_length: Minimum length of a branch - point_limit: Smallest number of datapoints assigned to a branch - volume: Volume of ellipsoid - thickness: Thickness of placenta - ellipticity: The ratio of y to x dimensions of the placenta - datapoints: A set of data points distributed within the placenta - initial_geom: Branching geometry to grow from :return: - A geometric structure consisting of 'nodes', 'elems', 'elem_up', and 'elem_down' - nodes: x,y,z coordinates of node location - elems: Elements connecting the nodes - elem_up and elem_down: The connectivity matrices for elements listing up and downstream elements for each - A list of data point locations associated with terminal branches (useful for post-processing and defining centre of terminal tissue units. - tb_list: A list of elements in the tree that are associated with each data point - tb_loc: The location of that datapoint ''' np.random.seed(seed=random_seed) #so if you randomly perturb in growing you get repeatable results if (volume==0) or (thickness==0) or (ellipticity==0): check_in_ellipsoid = 0 else: check_in_ellipsoid = 1 # Calulate axis dimensions of ellipsoid with given volume, thickness and ellipticity if(check_in_ellipsoid): radii = pg_utilities.calculate_ellipse_radii(volume, thickness, ellipticity) z_radius = radii['z_radius'] x_radius = radii['x_radius'] y_radius = radii['y_radius'] print('z radius ' + str(z_radius)) print('x_radius ' + str(x_radius)) print('y_radius ' + str(y_radius)) # We can estimate the number of elements in the generated model based on the number of data (seed points) to # pre-allocate data arrays. est_generation = int(np.ceil(np.log(len(datapoints)) / np.log(2))) total_estimated = 0 for i in range(0, est_generation + 1): total_estimated = total_estimated + 2 ** i print('total_estimated', total_estimated) # Define the total number of nodes and elements prior to growing, plus the new number expected num_elems_old = len(initial_geom["elems"]) num_nodes_old = len(initial_geom["nodes"]) num_elems_new = num_elems_old + total_estimated num_nodes_new = num_nodes_old + total_estimated print('Number of existing elements ' + str(num_elems_old)) print('Number of existing nodes ' + str(num_nodes_old)) print('Expected number of elements after growing ', str(num_elems_new)) print('Expected number of nodes after growing ', str(num_nodes_new)) original_data_length = len(datapoints) # Pre-allocation of data arrays # elem_directions = np.zeros((num_elems_new, 3)) # elem_order = np.zeros((num_elems_new, 3)) node_loc = np.zeros((num_nodes_new, 4)) node_loc[0:num_nodes_old][:] = initial_geom["nodes"] elems = np.zeros((num_elems_new, 3), dtype=int) elems[0:num_elems_old][:] = initial_geom["elems"] elem_upstream = np.zeros((num_elems_new, 3), dtype=int) elem_upstream[0:num_elems_old][:] = initial_geom['elem_up'] elem_downstream = np.zeros((num_elems_new, 3), dtype=int) elem_downstream[0:num_elems_old][:] = initial_geom['elem_down'] # local arrays nstem = np.zeros((num_elems_new, 2), dtype=int) # number of seeds per parent map_seed_to_elem = np.zeros(len(datapoints), dtype=int) # seed to elem - initial array for groupings tb_loc = np.zeros((2 * len(datapoints),4)) # Set initial values for local and global nodes and elements ne = num_elems_old - 1 # current maximum element number nnod = num_nodes_old - 1 # current maximum node number numtb = 0 # count of terminals parentlist = group_elem_parent_term(0, initial_geom['elem_down']) # master parent list # Initialise LD array to map each seed point to a parent branch. # For a single parent, all seed points will initially be mapped to # it; for multiple parents data_to_mesh is called to calculate # the closest parent end-point to each seed point. map_seed_to_elem = map_seed_to_elem + parentlist[0] map_seed_to_elem = data_to_mesh(map_seed_to_elem, datapoints, parentlist, node_loc, elems) for npar in range(0,len(parentlist)): print('Generating children for parent ' + str(npar) + '(elem #' + str(parentlist[npar]) + ') of a total of ' + str(len(parentlist))) current_parent = parentlist[npar] num_next_parents = 1 data_current_parent = np.zeros((len(datapoints), 3)) nd_for_parent = 0 for nd in range(0, len(datapoints)): if map_seed_to_elem[nd] == current_parent: data_current_parent[nd_for_parent] = datapoints[nd][:] map_seed_to_elem[nd] = 0 datapoints[nd][:] = 0 nd_for_parent = nd_for_parent + 1 datapoints = datapoints[np.nonzero(map_seed_to_elem)] #remove the datapoints you are currently analysing from master list map_seed_to_elem = map_seed_to_elem[np.nonzero(map_seed_to_elem)] #remove parent you are currently analysing from master list data_current_parent.resize(nd_for_parent, 3,refcheck=False) local_parent_temp = np.zeros(num_elems_new, dtype=int) # rezero local parent arrays local_parent = np.zeros(num_elems_new, dtype=int) local_parent[0] = current_parent map_seed_to_elem_new = np.zeros(len(data_current_parent), dtype=int) map_seed_to_elem_new = map_seed_to_elem_new + current_parent remaining_data = len(data_current_parent) original_data = len(data_current_parent) # START OF BIFURCATING DISTRIBUTATIVE ALGORITHM # could make this an optional output at a later date #print(' newgens #brn total# #term #data') ngen = 0 # for output, look to have each generation of elements recordded while num_next_parents != 0: # for ok in range(0,2): ngen = ngen + 1 # increment generation from parent for output num_parents = num_next_parents # update the number of current parents num_next_parents = 0 # reset the number of local parents for next iteration noelem_gen = 0 for m in range(0, num_parents): ne_parent = local_parent[m] com = mesh_com(ne_parent, map_seed_to_elem_new, data_current_parent) np_start = int(elems[ne_parent][2]) np_prt_start = int(elems[ne_parent][1]) point1 = node_loc[np_start][1:4] point2 = node_loc[np_prt_start][1:4] length_parent = np.linalg.norm(point1 - point2) # Split the seed points by the plane defined by the parent branch and the com of the # seedpoints attached to it colinear = pg_utilities.check_colinear(point1,point2, com) if colinear: #peturb COM slightly (exclude one data point) com = mesh_com(ne_parent, map_seed_to_elem_new, data_current_parent[1:len(data_current_parent)]) split_data = data_splitby_plane(map_seed_to_elem_new, data_current_parent, com, node_loc[np_prt_start][1:4], node_loc[np_start][1:4], ne_parent, ne, point_limit) too_short =0 too_long =0 not_in =0 # Check that there ar enough seedpoints in both groups to proceed # Note long term one could allow one group to continue and the other not to if split_data['enough_points'][0] and split_data['enough_points'][1]: for n in range(0, 2): branch = True # Calculate centre of mass to grow toward com = mesh_com(ne + 1, map_seed_to_elem_new, data_current_parent) # location of start of new element start_node_loc = node_loc[np_start][1:4] # length of new branch length_new = np.linalg.norm(fraction * (com - start_node_loc)) # check that the new branch is long enough and if not need to adjust length and remove associated data point if length_new < min_length: length_new = min_length branch = False too_short = 1 if(length_new > 2.0*length_parent and ngen > 4): length_new = length_parent branch = False too_long = 1 # calculate location of end node end_node_loc = start_node_loc + length_new * (com - start_node_loc) / np.linalg.norm( (com - start_node_loc)) # Checks that branch angles are appropriate end_node_loc = mesh_check_angle(angle_min, angle_max, node_loc[elems[ne_parent][1]][1:4], start_node_loc, end_node_loc, ne_parent, ne + 1) if(check_in_ellipsoid): #Check end node is in the ellipsoid in_ellipsoid = pg_utilities.check_in_ellipsoid(end_node_loc[0], end_node_loc[1], end_node_loc[2], x_radius, y_radius, z_radius) if(not in_ellipsoid): branch = False #This should be the last branch here. not_in = 1 count = 0 while(not in_ellipsoid and count <=50): length_new = 0.95*length_new # calculate location of end node end_node_loc = start_node_loc + length_new * (com - start_node_loc) / np.linalg.norm( (com - start_node_loc)) # Check end node is in the ellipsoid in_ellipsoid = pg_utilities.check_in_ellipsoid(end_node_loc[0], end_node_loc[1], end_node_loc[2], x_radius, y_radius, z_radius) count = count + 1 # Create new elements and nodes elems[ne + 1][0] = ne + 1 # creating new element elems[ne + 1][1] = np_start # starts at this node elems[ne + 1][2] = nnod + 1 # ends at this node elem_upstream[ne + 1][0] = 1 # The new element has one parent elem_upstream[ne + 1][1] = ne_parent elem_downstream[ne + 1][0] = 0 # the new element currently has no children elem_downstream[ne_parent][0] = elem_downstream[ne_parent][ 0] + 1 # the parent element gets this as a child elem_downstream[ne_parent][elem_downstream[ne_parent][0]] = ne + 1 node_loc[nnod + 1][0] = nnod + 1 node_loc[nnod + 1][1:4] = end_node_loc ne = ne + 1 nnod = nnod + 1 noelem_gen = noelem_gen + 1 # Only used for runtime output, number of new elements created in current generation nstem[ne][0] = nstem[ne_parent][0] if branch: # We are making a new branch so this one becomes a parent for next time local_parent_temp[num_next_parents] = ne num_next_parents = num_next_parents + 1 else: # Should not branch in the next generation but this is not implemented yet tb_loc[numtb][0] = ne count_data = 0 min_dist = 1.0e10 for nd in range(0, len(data_current_parent)): dist = dist_two_vectors(data_current_parent[nd][:],node_loc[int(elems[ne][2])][1:4]) if dist < min_dist: if map_seed_to_elem_new[nd] == ne: count_data = count_data + 1 nd_min = nd min_dist = dist if count_data != 0: # If there were any data points associated map_seed_to_elem_new[nd_min] = 0 remaining_data = remaining_data - 1 tb_loc[numtb][1:4] = data_current_parent[nd_min][:] numtb = numtb + 1 else: # Not ss so no splitting # Not enough seed points in the set during the split parent branch becomes a terminal tb_loc[numtb][0] = ne_parent min_dist = 1.0e10 count_data = 0 for nd in range(0, len(data_current_parent)): if map_seed_to_elem_new[nd] != 0: if map_seed_to_elem_new[nd] == ne + 1: map_seed_to_elem_new[nd] = ne_parent # give back to parent if map_seed_to_elem_new[nd] == ne + 2: map_seed_to_elem_new[nd] = ne_parent dist = dist_two_vectors(data_current_parent[nd][:], node_loc[int(elems[ne_parent][2])][1:4]) if dist < min_dist: if map_seed_to_elem_new[nd] == ne_parent: count_data = count_data + 1 nd_min = nd min_dist = dist if count_data != 0: # If there were any data points associated map_seed_to_elem_new[nd_min] = 0 remaining_data = remaining_data - 1 tb_loc[numtb][1:4] = data_current_parent[nd_min][:] else: print('Warning: No datapoint assigned to element: ' + str(ne)) numtb = numtb + 1 # .......Copy the temporary list of branches to NE_OLD. These become the # .......parent elements for the next branching for n in range(0, num_next_parents): local_parent[n] = local_parent_temp[n] nstem[int(local_parent[n])][1] = 0 # initial count of data points if remaining_data < original_data: # only need to reallocate data if we have lost some data points original_data = remaining_data # reallocate datapoints map_seed_to_elem_new = reassign_data_to_mesh(map_seed_to_elem_new, data_current_parent, local_parent[0:num_next_parents], node_loc, elems) # # Could make this an optional output at a later date # print(' ' + str(ngen) + ' ' + str(noelem_gen) + ' ' + str(ne) + # ' ' + str(numtb) + ' ' + str(remaining_data)) elems.resize(ne + 1, 3, refcheck=False) elem_upstream.resize(ne + 1, 3, refcheck=False) elem_downstream.resize(ne + 1, 3, refcheck=False) node_loc.resize(nnod + 1, 4, refcheck=False) tb_loc.resize(numtb, 4, refcheck=False) print('Growing algorithm completed, number of terminal branches: ' + str(numtb)) return {'nodes': node_loc, 'elems': elems, 'elem_up': elem_upstream, 'elem_down': elem_downstream, 'term_loc': tb_loc} def data_with_parent(current_parent, map_seed_to_elem, datapoints): new_datapoints = np.zeros((len(datapoints), 3)) nd_for_parent = 0 for nd in range(0, len(datapoints)): if map_seed_to_elem[nd] == current_parent: new_datapoints[nd_for_parent] = datapoints[nd][:] map_seed_to_elem[nd] = 0 datapoints[nd][:] = 0 nd_for_parent = nd_for_parent + 1 datapoints = datapoints[np.nonzero(map_seed_to_elem)] map_seed_to_elem = map_seed_to_elem[np.nonzero(map_seed_to_elem)] new_datapoints.resize(nd_for_parent, 3) return new_datapoints def grow_chorionic_surface(angle_max, angle_min, fraction, min_length, point_limit, volume, thickness, ellipticity, datapoints, initial_geom, sorv): """ :Function name: **grow_chorionic_surface** Grows a tree constrained to the surface of an semi-ellipsoid and based on data points defined on that surface. Employs the space filling branching algorithm :inputs: - angle_max: The maximum angle between two branches - angle_min: The miniumum angle between two branches - fraction: The fraction of distance between stem and datapoint centre of mass to grow - min_length: Minimum length of a branch - point_limit: Smallest number of datapoints assigned to a branch - volume: Volume of ellipsoid - thickness: Thickness of placenta - ellipticity: The ratio of y to x dimensions of the placenta - datapoints: A set of data points distributed over the chorionic surface - initial_geom: Branching geometry to grow from - sorv: Surface or volume :return: A geometric structure consisting of 'nodes', 'elems', 'elem_up', and 'elem_down' - nodes: x,y,z coordinates of node location - elems: Elements connecting the nodes - elem_up and elem_down: The connectivity matrices for elements listing up and downstream elements for each """ # Calulate axis dimensions of ellipsoid with given volume, thickness and ellipticity radii = pg_utilities.calculate_ellipse_radii(volume, thickness, ellipticity) z_radius = radii['z_radius'] x_radius = radii['x_radius'] y_radius = radii['y_radius'] # We can estimate the number of elements in the generated model based on the number of data (seed points) to # pre-allocate data arrays. est_generation = int(np.ceil(np.log(len(datapoints)) / np.log(2))) total_estimated = 0 for i in range(0, est_generation + 1): total_estimated = total_estimated + 2 ** i # Define the total number of nodes and elements prior to growing, plus the new number expected num_elems_old = len(initial_geom["elems"]) num_nodes_old = len(initial_geom["nodes"]) num_elems_new = num_elems_old + total_estimated num_nodes_new = num_nodes_old + total_estimated original_data = len(datapoints) # Pre-allocation of data arrays # elem_directions = np.zeros((num_elems_new, 3)) # elem_order = np.zeros((num_elems_new, 3)) node_loc = np.zeros((num_nodes_new, 4)) node_loc[0:num_nodes_old][:] = initial_geom["nodes"] elems = np.zeros((num_elems_new, 3), dtype=int) elems[0:num_elems_old][:] = initial_geom["elems"] elem_upstream = np.zeros((num_elems_new, 3), dtype=int) elem_upstream[0:num_elems_old][:] = initial_geom['elem_up'] elem_downstream = np.zeros((num_elems_new, 3), dtype=int) elem_downstream[0:num_elems_old][:] = initial_geom['elem_down'] # local arrays nstem = np.zeros((num_elems_new, 2), dtype=int) local_parent_temp = np.zeros(num_elems_new, dtype=int) local_parent = np.zeros(num_elems_new, dtype=int) map_seed_to_elem = np.zeros(len(datapoints), dtype=int) tb_list = np.zeros(2 * len(datapoints), dtype=int) # number of terminal bronchioles # initialise local_parent (list of old terminals) to list of terminals in current geometry parentlist = group_elem_parent_term(0, initial_geom['elem_down']) local_parent[0:len(parentlist)] = parentlist num_parents = len(parentlist) # Curerent number of terminals num_next_parents = num_parents for n in range(0, len(parentlist)): nstem[n][0] = local_parent[n] # Initialise LD array to map each seed point to a parent branch. # For a single parent, all seed points will initially be mapped to # it; for multiple parents data_to_mesh is called to calculate # the closest parent end-point to each seed point. map_seed_to_elem = map_seed_to_elem + local_parent[0] map_seed_to_elem = data_to_mesh(map_seed_to_elem, datapoints, parentlist, node_loc, elems) # Assign temporary arrays for nd in range(0, len(datapoints)): if map_seed_to_elem[nd] != 0: ne_min = map_seed_to_elem[nd] # element associated with this seed nstem[ne_min][1] = nstem[ne_min][1] + 1 # This element has x data pints # Dealing with cases when there are no datapoints assigned with an element num_parents = 0 # intialise number of parents for n in range(0, len(parentlist)): if nstem[parentlist[n]][1] != 0: # if parent has a data point allocated then its in local parent list local_parent[num_parents] = parentlist[n] num_parents = num_parents + 1 num_next_parents = num_parents n_elm_temp = num_next_parents # remove terminal elements with only one data point associated and corresponding data pomt # from the group numtb = 0 for n in range(0, num_next_parents): ne_min = local_parent[n] # this is the parent in the local list (has at least one datapoint) if nstem[ne_min][1] < 2: # If only one datapint for nd in range(0, len(datapoints)): if (map_seed_to_elem[nd] == ne_min): map_seed_to_elem[nd] = 0 # remove datapoint from the list local_parent[n] = 0 # Not a parent, wont branch n_elm_temp = n_elm_temp - 1 # tb_list[numtb] = ne_min numtb = numtb + 1 for n in range(0, num_next_parents): if local_parent[n] == 0: i = 0 while (n + i < num_next_parents) and (local_parent[n + i] == 0): i = i + 1 for m in range(n, num_next_parents - 1): local_parent[m] = local_parent[m + i] num_next_parents = n_elm_temp remaining_data = 0 for nd in range(0, len(datapoints)): if map_seed_to_elem[nd] > 0: remaining_data = remaining_data + 1 # START OF BIFURCATING DISTRIBUTATIVE ALGORITHM # Could potentially make this an optional output at a later date # print(' newgens #brn total# #term #data') # Set initial values for local and global nodes and elements ne = num_elems_old - 1 # current maximum element number nnod = num_nodes_old - 1 # current maximum node number ngen = 0 # for output, look to have each generation of elements recordded while num_next_parents != 0: # for ok in range(0,2): ngen = ngen + 1 # increment generation from parent for output num_parents = num_next_parents # update the number of current parents num_next_parents = 0 # reset the number of local parents for next iteration noelem_gen = 0 for m in range(0, num_parents): ne_parent = local_parent[m] com = mesh_com(ne_parent, map_seed_to_elem, datapoints) np_start = int(elems[ne_parent][2]) np_prt_start = int(elems[ne_parent][1]) # Split the seed points by the plane defined by the parent branch and the com of the # seedpoints attached to it if sorv == 'surface': split_data = data_splitby_xy(map_seed_to_elem, datapoints, com, node_loc[np_start][1:3], ne_parent, ne, point_limit) else: split_data = data_splitby_plane(map_seed_to_elem, datapoints, com, node_loc[np_prt_start][1:4], node_loc[np_start][1:4], ne_parent, ne, point_limit) # Check that there ar enough seedpoints in both groups to proceed # Note long term one could allow one group to continue and the other not to if split_data['enough_points'][0] and split_data['enough_points'][1]: for n in range(0, 2): branch = True # Calculate centre of mass to grow toward com = mesh_com(ne + 1, map_seed_to_elem, datapoints) # location of start of new element start_node_loc = node_loc[np_start][1:4] # length of new branch length_new = np.linalg.norm(fraction * (com - start_node_loc)) # check that the new branch is long enough and if not need to adjust length and remove associated data point if length_new < min_length: length_new = min_length branch = False # calculate location of end node end_node_loc = start_node_loc + length_new * (com - start_node_loc) / np.linalg.norm( (com - start_node_loc)) # Checks that branch angles are appropriate if sorv == 'surface': # first node is 1st parent node node1 = np.array( [node_loc[elems[ne_parent][1]][0], node_loc[elems[ne_parent][1]][1], 0]) # second parent node (start of new branch node2 = np.array([start_node_loc[0], start_node_loc[1], 0]) # end of new branch node3 = np.array([end_node_loc[0], end_node_loc[1], 0]) end_node = mesh_check_angle(angle_min, angle_max, node1, node2, node3, ne_parent, ne + 1) end_node_loc[0:2] = end_node[0:2] end_node_loc[2] = pg_utilities.z_from_xy(end_node[0], end_node[1], x_radius, y_radius, z_radius) elif sorv == 'volume': end_node_loc = mesh_check_angle(angle_min, angle_max, node_loc[elems[ne_parent][1]][1:4], start_node_loc, end_node_loc, ne_parent, ne + 1) # Create new elements and nodes elems[ne + 1][0] = ne + 1 # creating new element elems[ne + 1][1] = np_start # starts at this node elems[ne + 1][2] = nnod + 1 # ends at this node elem_upstream[ne + 1][0] = 1 # The new element has one parent elem_upstream[ne + 1][1] = ne_parent elem_downstream[ne + 1][0] = 0 # the new element currently has no children elem_downstream[ne_parent][0] = elem_downstream[ne_parent][ 0] + 1 # the parent element gets this as a child elem_downstream[ne_parent][elem_downstream[ne_parent][0]] = ne + 1 node_loc[nnod + 1][0] = nnod + 1 node_loc[nnod + 1][1:4] = end_node_loc ne = ne + 1 nnod = nnod + 1 noelem_gen = noelem_gen + 1 # Only used for runtime output, number of new elements created in current generation nstem[ne][0] = nstem[ne_parent][0] if branch: # We are making a new branch so this one becomes a parent for next time local_parent_temp[num_next_parents] = ne num_next_parents = num_next_parents + 1 else: # Note that this needs to be updated so that the branch and its datapoints get deleted from the list and dont grow nest time # but for python speed reasons we should leave here for now local_parent_temp[num_next_parents] = ne num_next_parents = num_next_parents + 1 # numtb = numtb + 1 else: # Not ss so no splitting # Not enough seed points in the set during the split parent branch becomes a terminal tb_list[numtb] = ne_parent numtb = numtb + 1 min_dist = 1.0e10 count_data = 0 for nd in range(0, len(datapoints)): if map_seed_to_elem[nd] != 0: if map_seed_to_elem[nd] == ne + 1: map_seed_to_elem[nd] = ne_parent # give back to parent if map_seed_to_elem[nd] == ne + 2: map_seed_to_elem[nd] = ne_parent dist = dist_two_vectors(datapoints[nd][:], node_loc[int(elems[ne_parent][2])][1:4]) if dist < min_dist: if map_seed_to_elem[nd] == ne_parent: count_data = count_data + 1 nd_min = nd min_dist = dist if count_data != 0: # If there were any data points associated map_seed_to_elem[nd_min] = 0 remaining_data = remaining_data - 1 # .......Copy the temporary list of branches to NE_OLD. These become the # .......parent elements for the next branching for n in range(0, num_next_parents): local_parent[n] = local_parent_temp[n] nstem[int(local_parent[n])][1] = 0 # initialaw count of data points if remaining_data < original_data: # only need to reallocate data if we have lost some data points original_data = remaining_data # reallocate datapoints map_seed_to_elem = data_to_mesh(map_seed_to_elem, datapoints, local_parent[0:num_next_parents], node_loc, elems) # Could potentially make this an optional output at a later date # print(' ' + str(ngen) + ' ' + str(noelem_gen) + ' ' + str(ne) + # ' ' + str(numtb) + ' ' + str(remaining_data)) elems.resize(ne + 1, 3, refcheck=False) elem_upstream.resize(ne + 1, 3, refcheck=False) elem_downstream.resize(ne + 1, 3, refcheck=False) node_loc.resize(nnod + 1, 4, refcheck=False) return {'nodes': node_loc, 'elems': elems, 'elem_up': elem_upstream, 'elem_down': elem_downstream} def refine_1D(initial_geom, from_elem,project): ''' :Function name: **refine_1d** Refines a 1D branching tree once along its major axis. Has the option to project to the surface of an ellipsoid. :inputs: - initial_geom: The branching structure to be refined - from_elem: The element from which to start refining - project: A data structure defining whether to project to the surface of an ellipsoid and ellipsoid properties :return: A geometric structure consisting of 'nodes', 'elems', 'elem_up', and 'elem_down' - nodes: x,y,z coordinates of node location - elems: Elements connecting the nodes - elem_up and elem_down: The connectivity matrices for elements listing up and downstream elements for each ''' # Estimate new number of nodes and elements num_elems_old = len(initial_geom['elems']) num_nodes_old = len(initial_geom['nodes']) num_elems_new = 2 * num_elems_old - from_elem + 1 num_nodes_new = num_nodes_old + num_elems_old - from_elem + 1 elems_old = initial_geom['elems'] node_loc_old = initial_geom['nodes'] elem_upstream_old = initial_geom['elem_up'] elem_downstream_old = initial_geom['elem_down'] # allocate temporary arrays elems = np.zeros((num_elems_new, 3), dtype=int) node_loc = np.zeros((num_nodes_new, 4)) elem_upstream = np.zeros((num_elems_new, 3), dtype=int) elem_downstream = np.zeros((num_elems_new, 3), dtype=int) old_2_new = np.zeros((num_elems_old, 2), dtype=int) for nnod in range(0, num_nodes_new): node_loc[nnod][0] = nnod # will be a numeric list of nodes # copy non-split elements and nodes into the arrays if from_elem != 0: # nothing needs to be done if from elem is zero node_loc[0][:] = initial_geom['nodes'][0][:] elems[0:from_elem][:] = initial_geom['elems'][0:from_elem][:] elem_upstream[0:from_elem][:] = initial_geom['elem_up'][0:from_elem][:] elem_downstream[0:from_elem][:] = initial_geom['elem_down'][0:from_elem][:] for ne in range(0, from_elem): # grab second node from each non-split element node_loc[elems_old[ne][2]][:] = node_loc_old[elems_old[ne][2]][:] old_2_new[ne][0] = ne old_2_new[ne][1] = ne new_elems = from_elem - 1 nnod = from_elem for ne in range(from_elem, num_elems_old): # split element in two at half way point old_2_new[ne][0] = new_elems + 1 old_2_new[ne][1] = new_elems + 2 in_node = elems[old_2_new[elem_upstream_old[ne][1]][1]][2] in_point = node_loc_old[elems_old[ne][1]][1:4] out_point = node_loc_old[elems_old[ne][2]][1:4] mid_point = np.zeros(3) for i in range(0, 3): mid_point[i] = (in_point[i] + out_point[i]) / 2.0 if project['status']: mid_point[2] = pg_utilities.z_from_xy(mid_point[0], mid_point[1], project['x_radius'], project['y_radius'], project['z_radius']) # Create a new node at midpoint nnod = nnod + 1 node_loc[nnod][1:4] = mid_point # Next node is outpoint nnod1 = nnod + 1 node_loc[nnod1][1:4] = out_point # create first new element new_elems = new_elems + 1 elems[new_elems][0] = new_elems elems[new_elems][1] = in_node elems[new_elems][2] = nnod new_elems = new_elems + 1 elems[new_elems][0] = new_elems elems[new_elems][1] = nnod elems[new_elems][2] = nnod1 nnod = nnod1 node_loc.resize(nnod + 1, 4, refcheck=False) elems.resize(new_elems + 1, 3, refcheck=False) elem_connectivity = pg_utilities.element_connectivity_1D(node_loc, elems) return {'nodes': node_loc, 'elems': elems, 'elem_up': elem_connectivity['elem_up'], 'elem_down': elem_connectivity['elem_down']} def add_stem_villi(initial_geom, from_elem, sv_length, export_stem, stem_xy_file): ''' :Function name: **add_stem_villi** This function takes an initial, refined, branching geometry and adds stem villi, that point up into the placental volume at close to 90 degrees from their stem branches. The function also exports the location of stem villi so that these can later be used to generate boundary conditions for uteroplacental flow models. :inputs: - initial_geom: An initial branching geometry with node points where stem villi are to be added - from_elem: Definition of the element from which stem villi are to be generated - sv_length: Length of stem villi, in units consistent with your geometry - export_stem: A logical defining whether or not to export the geometry - stem_xy_file: Filename for export :return: A geometric structure consisting of 'nodes', 'elems', 'elem_up', and 'elem_down' - nodes: x,y,z coordinates of node location - elems: Elements connecting the nodes - elem_up and elem_down: The connectivity matrices for elements listing up and downstream elements for each ''' # Estimate new number of nodes and elements num_elems_old = len(initial_geom['elems']) num_nodes_old = len(initial_geom['nodes']) elems_old = initial_geom['elems'] node_loc_old = initial_geom['nodes'] elem_upstream_old = initial_geom['elem_up'] elem_downstream_old = initial_geom['elem_down'] # calculate number pf new elements to add num_2_add = 0 for ne in range(from_elem, num_elems_old): if elem_downstream_old[ne][0] == 1: num_2_add = num_2_add + 1 # Allocate arrays num_elems_new = num_elems_old + num_2_add num_nodes_new = num_nodes_old + num_2_add elems = np.zeros((num_elems_new, 3), dtype=int) node_loc = np.zeros((num_nodes_new, 4)) node_loc[0:num_nodes_old][:] = initial_geom['nodes'] elems[0:num_elems_old][:] = initial_geom['elems'] # Create new elements nnod = num_nodes_old - 1 ne0 = num_elems_old - 1 for ne in range(from_elem, num_elems_old): if elem_downstream_old[ne][0] == 1: nnod = nnod + 1 ne0 = ne0 + 1 node_loc[nnod][0] = nnod elems[ne0][0] = ne0 elems[ne0][1] = elems[ne][2] elems[ne0][2] = nnod node_loc[nnod][1:3] = node_loc[elems[ne][2]][1:3] node_loc[nnod][3] = node_loc[elems[ne][2]][3] - sv_length elem_connectivity = pg_utilities.element_connectivity_1D(node_loc, elems) if(export_stem): f = open(stem_xy_file, 'w') strahler = analyse_tree.evaluate_orders(node_loc,elems)['strahler'] for ne in range(0,len(elems)): if(strahler[ne] == 1): nnod = elems[ne][2] f.write("%s %s %s\n" % (node_loc[nnod][1], node_loc[nnod][2],ne+1)) f.close() return {'nodes': node_loc, 'elems': elems, 'elem_up': elem_connectivity['elem_up'], 'elem_down': elem_connectivity['elem_down']} def mesh_check_angle(angle_min, angle_max, node1, node2, node3, ne_parent, myno): normal_to_plane = np.zeros(3) vector_cross_n = np.zeros(3) vector1 = (node2 - node1) vector1_u = vector1 / np.linalg.norm(vector1) vector2 = (node3 - node2) vector2_u = vector2 / np.linalg.norm(vector2) angle = pg_utilities.angle_two_vectors(vector1, vector2) if angle <= 1.e-15: length = np.linalg.norm(vector2) node3[0] = node3[0] + np.random.uniform(-0.01 * length, 0.01 * length) node3[1] = node3[1] + np.random.uniform(-0.01 * length, 0.01 * length) node3[2] = node3[2] + np.random.uniform(-0.01 * length, 0.01 * length) vector2 = node3 - node2 # want to rotate vector 2 wrt vector 1 angle = pg_utilities.angle_two_vectors(vector1, vector2) normal_to_plane[0] = (vector2[1] * vector1[2] - vector2[2] * vector1[1]) normal_to_plane[1] = (vector2[0] * vector1[2] - vector2[2] * vector1[0]) normal_to_plane[2] = (vector2[0] * vector1[1] - vector2[1] * vector1[0]) normal_to_plane_u = normal_to_plane / np.linalg.norm(normal_to_plane) vector_cross_n[0] = (vector1[1] * normal_to_plane[2] - vector1[2] * normal_to_plane[1]) vector_cross_n[1] = (vector1[0] * normal_to_plane[2] - vector1[2] * normal_to_plane[0]) vector_cross_n[2] = (vector1[0] * normal_to_plane[1] - vector1[1] * normal_to_plane[0]) dotprod = np.dot(vector2, vector_cross_n) if dotprod < 0.: angle = -1. * angle if abs(angle) < angle_min: # Need to adjust node3 to get a angle equal to angle_min angle0 = abs(angle) angle_rot = (angle0 - angle_min) # amount of angle to add # need to rotate around axis normal to the plane that the original and the vector make # unit vector normal to plane: R = np.zeros((3, 3)) R[0][0] = np.cos(angle_rot) + normal_to_plane_u[0] ** 2 * (1 - np.cos(angle_rot)) R[0][1] = normal_to_plane_u[0] * normal_to_plane_u[1] * (1 - np.cos(angle_rot)) - normal_to_plane_u[2] * np.sin( angle_rot) R[0][2] = normal_to_plane_u[0] * normal_to_plane[2] * (1 - np.cos(angle_rot)) + normal_to_plane_u[1] * np.sin( angle_rot) R[1][0] = normal_to_plane_u[0] * normal_to_plane_u[1] * (1 - np.cos(angle_rot)) + normal_to_plane_u[2] * np.sin( angle_rot) R[1][1] = np.cos(angle_rot) + normal_to_plane_u[1] ** 2 * (1 - np.cos(angle_rot)) R[1][2] = normal_to_plane_u[1] * normal_to_plane_u[2] * (1 - np.cos(angle_rot)) - normal_to_plane_u[0] * np.sin( angle_rot) R[2][0] = normal_to_plane_u[0] * normal_to_plane[2] * (1 - np.cos(angle_rot)) - normal_to_plane_u[1] * np.sin( angle_rot) R[2][1] = normal_to_plane_u[1] * normal_to_plane_u[2] * (1 - np.cos(angle_rot)) + normal_to_plane_u[0] * np.sin( angle_rot) R[2][2] = np.cos(angle_rot) + normal_to_plane_u[2] ** 2 * (1 - np.cos(angle_rot)) nu_vec = np.zeros(3) nu_vec[0] = R[0][0] * vector2[0] + R[0][1] * vector2[1] + R[0][2] * vector2[2] nu_vec[1] = R[1][0] * vector2[0] + R[1][1] * vector2[1] + R[1][2] * vector2[2] nu_vec[2] = R[2][0] * vector2[0] + R[2][1] * vector2[1] + R[2][2] * vector2[2] node3 = node2 + nu_vec elif abs(angle) > angle_max: # Need to adjust node3 to get a angle equal to angle_max angle0 = abs(angle) angle_rot = (angle0 - angle_max) # amount of angle to add # need to rotate around axis normal to the plane that the original and the vector make # unit vector normal to plane: R = np.zeros((3, 3)) R[0][0] = np.cos(angle_rot) + normal_to_plane_u[0] ** 2 * (1 - np.cos(angle_rot)) R[0][1] = normal_to_plane_u[0] * normal_to_plane_u[1] * (1 - np.cos(angle_rot)) - normal_to_plane_u[2] * np.sin( angle_rot) R[0][2] = normal_to_plane_u[0] * normal_to_plane[2] * (1 - np.cos(angle_rot)) + normal_to_plane_u[1] * np.sin( angle_rot) R[1][0] = normal_to_plane_u[0] * normal_to_plane_u[1] * (1 -
np.cos(angle_rot)
numpy.cos
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2016-2020 German Aerospace Center (DLR) and others. # SUMOPy module # Copyright (C) 2012-2017 University of Bologna - DICAM # This program and the accompanying materials are made available under the # terms of the Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the Eclipse # Public License 2.0 are satisfied: GNU General Public License, version 2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file results_mpl-01-preimportlib.py # @author <NAME> # @date import os import numpy as np from collections import OrderedDict #import matplotlib as mpl #from matplotlib.patches import Arrow,Circle, Wedge, Polygon,FancyArrow #from matplotlib.collections import PatchCollection #import matplotlib.colors as colors #import matplotlib.cm as cmx #import matplotlib.pyplot as plt #import matplotlib.image as image from coremodules.misc.matplottools import * import agilepy.lib_base.classman as cm import agilepy.lib_base.arrayman as am from agilepy.lib_base.geometry import * from agilepy.lib_base.processes import Process def init_plot(): plt.close("all") fig = plt.figure() ax = fig.add_subplot(111) fig.tight_layout() return ax def plot_net(ax, net, color_edge="gray", width_edge=2, color_node=None, alpha=0.5): for shape in net.edges.shapes.get_value(): x_vec = np.array(shape)[:, 0] y_vec = np.array(shape)[:, 1] ax.plot(x_vec, y_vec, color=color_edge, lw=width_edge, alpha=alpha, zorder=-100) # do nodes if color_node is None: is_nodefill = False color_node = 'none' else: is_nodefill = True #ax.scatter(x_vec[0], y_vec[0], s=np.pi * (10.0)**2, c=colors, alpha=0.5) coords = net.nodes.coords.get_value() radii = net.nodes.radii.get_value() #ax.scatter(coords[:,0], coords[:,1], s=np.pi * (radii)**2, alpha=0.5) #patches = [] for coord, radius in zip(coords, radii): ax.add_patch(Circle(coord, radius=radius, linewidth=width_edge, edgecolor=color_edge, facecolor=color_node, fill=is_nodefill, alpha=alpha, zorder=-50)) def plot_maps(ax, maps, alpha=0.5): # print 'plot_maps' net = maps.parent.get_net() rootdir = os.path.dirname(net.parent.get_rootfilepath()) for filename, bbox in zip(maps.filenames.get_value(), maps.bboxes.get_value()): # print ' ',filename, if filename == os.path.basename(filename): # filename does not contain path info filepath = os.path.join(rootdir, filename) else: # filename contains path info (can happen if interactively inserted) filepath = filename # print ' filepath',filepath im = image.imread(filepath) myaximage = ax.imshow(im, aspect='auto', extent=( bbox[0, 0], bbox[1, 0], bbox[0, 1], bbox[1, 1]), alpha=alpha, zorder=-1000) def plot_facilities(ax, facilities, color_building="gray", color_outline='white', width_line=2, alpha=0.5): if color_building is None: is_fill = False color_building = 'none' else: is_fill = True for shape in facilities.shapes.get_value(): #x_vec = np.array(shape)[:,0] #y_vec = np.array(shape)[:,1] # ax.plot(x_vec, y_vec, color = color_building, lw = width_line, # alpha=alpha ) ax.add_patch(Polygon(np.array(shape)[:, :2], linewidth=width_line, edgecolor=color_outline, facecolor=color_building, fill=is_fill, alpha=alpha, zorder=-200)) def plot_edgevalues_lines(ax, ids_result, config_ids_edge, values, width_max=10.0, alpha=0.8, printformat='%.2f', color_outline=None, color_fill=None, color_label='black', is_antialiased=True, is_fill=True, is_widthvalue=True, arrowshape='left', length_arrowhead=10.0, headwidthstretch=1.3, fontsize=32, valuelabel=''): head_width = headwidthstretch*width_max fontsize_ticks = int(0.8*fontsize) edges = config_ids_edge.get_linktab() ids_edges = config_ids_edge[ids_result] #values = config_values[ids_result] values_norm = np.array(values, dtype=np.float32)/np.max(values) patches = [] displacement = float(width_max)/2.0 if is_widthvalue: linewidths = width_max*values_norm else: linewidths = width_max * np.ones(len(values_norm), np.float32) deltaangle_text = -np.pi/2.0 displacement_text = displacement+width_max jet = cm_jet = plt.get_cmap('jet') c_norm = colors.Normalize(vmin=0, vmax=np.max(values)) # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots/11558629#11558629 sm = cmx.ScalarMappable(norm=c_norm, cmap=jet) sm.set_array(values_norm) for id_edge, value, value_norm, linewidth in zip(ids_edges, values, values_norm, linewidths): shape, angles_perb = get_resultshape(edges, id_edge, displacement) x_vec = np.array(shape)[:, 0] y_vec = np.array(shape)[:, 1] deltax = x_vec[-1]-x_vec[0] deltay = y_vec[-1]-y_vec[0] # http://matplotlib.org/users/pyplot_tutorial.html line = mpl.lines.Line2D(x_vec, y_vec, color=sm.to_rgba(value), linewidth=linewidth, antialiased=is_antialiased, alpha=alpha, solid_capstyle='round', zorder=0, ) ax.add_line(line) if printformat is not '': angles_text = np.arctan2(deltay, deltax)+deltaangle_text # print ' angles_text',printformat%value,angles_text/(np.pi)*180,(angles_text>np.pi/2),(angles_text<3*np.pi/2) if (angles_text > np.pi/2) | (angles_text < -np.pi/2): angles_text += np.pi x_label = x_vec[0]+0.66*deltax+displacement_text*np.cos(angles_text) y_label = y_vec[0]+0.66*deltay+displacement_text*np.sin(angles_text) ax.text(x_label, y_label, printformat % value, rotation=angles_text/(np.pi)*180, color=color_label, fontsize=fontsize_ticks, zorder=10, ) if is_fill: cbar = plt.colorbar(sm) # mpl.setp(cbar.ax.yaxis.get_ticklabels(), fontsize=fontsize)#weight='bold', # cb.ax.tick_params(labelsize=font_size) if valuelabel != '': cbar.ax.set_ylabel(valuelabel, fontsize=fontsize) # , weight="bold") for l in cbar.ax.yaxis.get_ticklabels(): # l.set_weight("bold") l.set_fontsize(fontsize_ticks) def plot_edgevalues_arrows(ax, ids_result, config_ids_edge, values, width_max=10.0, alpha=0.8, printformat='%.2f', color_outline=None, color_fill=None, color_label='black', is_antialiased=True, is_fill=True, is_widthvalue=True, arrowshape='left', length_arrowhead=10.0, headwidthstretch=1.3, fontsize=32, valuelabel=''): head_width = headwidthstretch*width_max fontsize_ticks = int(0.8*fontsize) edges = config_ids_edge.get_linktab() ids_edges = config_ids_edge[ids_result] #values = config_values[ids_result] values_norm = np.array(values, dtype=np.float32)/np.max(values) patches = [] displacement = float(width_max)/4.0 if is_widthvalue: linewidths = width_max*values_norm else: linewidths = width_max * np.ones(len(values_norm), np.float32) deltaangle_text = -np.pi/2.0 displacement_text = displacement+width_max for id_edge, value, value_norm, linewidth in zip(ids_edges, values, values_norm, linewidths): shape, angles_perb = get_resultshape(edges, id_edge, displacement) x_vec = np.array(shape)[:, 0] y_vec = np.array(shape)[:, 1] deltax = x_vec[-1]-x_vec[0] deltay = y_vec[-1]-y_vec[0] if printformat is not '': angles_text = np.arctan2(deltay, deltax)+deltaangle_text if (angles_text > np.pi/2) | (angles_text < -np.pi/2): angles_text += np.pi x_label = x_vec[0]+0.66*deltax+displacement_text*np.cos(angles_text) y_label = y_vec[0]+0.66*deltay+displacement_text*
np.sin(angles_text)
numpy.sin
# 本文用到的库 import numpy as np import pandas as pd from sklearn.tree import DecisionTreeClassifier import base64 import streamlit as st from sklearn import preprocessing from dtreeviz.trees import * from data import getDataSetOrigin,dataPreprocessing import joblib from DecisionTree import dt_param_selector import numpy as np import matplotlib.pyplot as plt from data import dataPreprocessing from sklearn.tree import DecisionTreeClassifier import streamlit as st def decisionTreeViz(clf): df = dataPreprocessing() X, y = df[df.columns[:-1]], df["label"] viz = dtreeviz( clf, X, y, orientation="LR", target_name="label", feature_names=df.columns[:-1], class_names=["good", "bad"], # need class_names for classifier ) return viz def svg_write(svg, center=True): """ Disable center to left-margin align like other objects. """ # Encode as base 64 b64 = base64.b64encode(svg.encode("utf-8")).decode("utf-8") # Add some CSS on top css_justify = "center" if center else "left" css = ( f'<p style="text-align:center; display: flex; justify-content: {css_justify};">' ) html = f'{css}<img src="data:image/svg+xml;base64,{b64}"/>' # Write the HTML st.write(html, unsafe_allow_html=True, width=800, caption="决策树") def plotSurface(): st.set_option('deprecation.showPyplotGlobalUse', False) # Parameters n_classes = 2 plot_colors = "ryb" plot_step = 0.02 # Load data df = dataPreprocessing() plt.figure(figsize=(8,4)) for pairidx, pair in enumerate([[1, 0], [1, 3], [1, 4], [1, 5], [3, 0], [3, 2], [3, 4], [3, 5]]): # We only take the two corresponding features X, y = df[df.columns[:-1]].values[:, pair], df["label"] # Train clf = DecisionTreeClassifier().fit(X, y) # Plot the decision boundary fig=plt.subplot(2, 4, pairidx + 1) x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid( np.arange(x_min, x_max, plot_step),
np.arange(y_min, y_max, plot_step)
numpy.arange
import uuid import re import operator import sys, getopt import os import pandas as p import numpy as np import numpy.ma as ma import random import scipy.stats as ss import scipy as sp import scipy.misc as spm import scipy.special as sps from scipy.special import psi as digamma from scipy.stats import truncnorm from scipy.special import erfc from scipy.special import erf from pygam import LinearGAM, s, f from sklearn.linear_model import LinearRegression import statsmodels.api as sm from sklearn.preprocessing import PolynomialFeatures from copy import deepcopy from copy import copy import math from math import floor import subprocess from subprocess import Popen, PIPE, STDOUT from operator import mul, truediv, eq, ne, add, ge, le, itemgetter import networkx as nx import argparse import collections from collections import deque from collections import defaultdict from collections import Counter from numpy.random import RandomState from BayesPaths.graph import Graph from BayesPaths.UtilsFunctions import convertNodeToName from BayesPaths.UtilsFunctions import elop from BayesPaths.UtilsFunctions import expNormLogProb from BayesPaths.UtilsFunctions import TN_vector_expectation from BayesPaths.UtilsFunctions import TN_vector_variance from BayesPaths.UtilsFunctions import readRefAssign from BayesPaths.UnitigGraph import UnitigGraph from BayesPaths.NMFM import NMF from BayesPaths.NMF_VB import NMF_VB from BayesPaths.bnmf_vb import bnmf_vb from BayesPaths.ResidualBiGraph3 import ResidualBiGraph from BayesPaths.ResidualBiGraph3 import FlowGraphML from BayesPaths.ResidualBiGraph3 import FlowFitTheta from BayesPaths.AugmentedBiGraph import AugmentedBiGraph from BayesPaths.AugmentedBiGraph import gaussianNLL_F from BayesPaths.AugmentedBiGraph import gaussianNLL_D import subprocess import shlex import multiprocessing as mp from multiprocessing.pool import ThreadPool from multiprocessing import Pool from pathos.multiprocessing import ProcessingPool import logging from subprocess import DEVNULL def reject_outliers(data, m = 2.): d = np.abs(data - np.median(data)) mdev = np.median(d) s = d/mdev if mdev else 0. return s<m def call_proc(cmd): """ This runs in a separate thread. """ #subprocess.call(shlex.split(cmd)) # This will block until cmd finishes p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return (out, err) def findSuperBubble(directedGraph, source, descendents, parents): queue = deque([source]) seen = set() visited = set() sink = None while queue: node = queue.popleft() visited.add(node) if node in seen: seen.remove(node) nList = list(descendents(node)) if len(nList) > 0: for child in nList: if child == source: break seen.add(child) childVisited = set(parents(child)) if childVisited.issubset(visited): queue.append(child) if len(queue) == 1 and len(seen) < 2: if len(seen) == 0 or queue[0] in seen: if not directedGraph.has_edge(queue[0],source): sink = queue[0] break return (visited, sink) """ This module implements the Lowess function for nonparametric regression. Functions: lowess Fit a smooth nonparametric regression curve to a scatterplot. For more information, see <NAME>: "Robust locally weighted regression and smoothing scatterplots", Journal of the American Statistical Association, December 1979, volume 74, number 368, pp. 829-836. <NAME> and <NAME>: "Locally weighted regression: An approach to regression analysis by local fitting", Journal of the American Statistical Association, September 1988, volume 83, number 403, pp. 596-610. """ # Authors: <NAME> <<EMAIL>> # # License: BSD (3-clause) from math import ceil import numpy as np from scipy import linalg def lowess(x, y, f=2. / 3., iter=3): """lowess(x, y, f=2./3., iter=3) -> yest Lowess smoother: Robust locally weighted regression. The lowess function fits a nonparametric regression curve to a scatterplot. The arrays x and y contain an equal number of elements; each pair (x[i], y[i]) defines a data point in the scatterplot. The function returns the estimated (smooth) values of y. The smoothing span is given by f. A larger value for f will result in a smoother curve. The number of robustifying iterations is given by iter. The function will run faster with a smaller number of iterations. """ n = len(x) r = int(ceil(f * n)) h = [np.sort(np.abs(x - x[i]))[r] for i in range(n)] w = np.clip(np.abs((x[:, None] - x[None, :]) / h), 0.0, 1.0) w = (1 - w ** 3) ** 3 yest = np.zeros(n) delta = np.ones(n) for iteration in range(iter): for i in range(n): weights = delta * w[:, i] b = np.array([np.sum(weights * y), np.sum(weights * y * x)]) A = np.array([[np.sum(weights), np.sum(weights * x)], [np.sum(weights * x), np.sum(weights * x * x)]]) beta = linalg.solve(A, b) yest[i] = beta[0] + beta[1] * x[i] residuals = y - yest s = np.median(np.abs(residuals)) delta = np.clip(residuals / (6.0 * s), -1, 1) delta = (1 - delta ** 2) ** 2 return yest formatter = logging.Formatter('%(asctime)s %(message)s') def setup_logger(name, log_file, level=logging.INFO): """To setup as many loggers as you want""" handler = logging.FileHandler(log_file) handler.setFormatter(formatter) logger = logging.getLogger(name) logger.setLevel(level) logger.addHandler(handler) return logger class AssemblyPathSVA(): """ Class for structured variational approximation on Assembly Graph""" minW = 1.0e-3 minLogQGamma = 1.0e-100 minNoiseCov = 100. minBeta = 1.0e-100 minVar = 1.0e-3 xRangeFixed = 100. minStrainCoverage = 2. def __init__(self, prng, logger, assemblyGraphs, source_maps, sink_maps, G = 2, logFile = None, maxFlux=2, readLength = 100, epsilon = 1.0e5, epsilonNoise = 1.0e-3, alpha=1.0e-9,beta=1.0e-9,alpha0=1.0e-9,beta0=1.0e-9, no_folds = 10, ARD = False, BIAS = True, NOISE = True, muTheta0 = 1.0, tauTheta0 = 100.0, minIntensity = None, fgExePath="./runfg_source/", tauThresh = 0.1, nNmfIters=10, bLoess = True, bGam = True, tauType='auto', biasType = 'unitig', working_dir="/tmp", minSumCov = None, fracCov = None, bARD2 = True): self.prng = prng #random state to store self.logger = logger self.readLength = readLength #sequencing read length self.assemblyGraphs = dict(assemblyGraphs) self.source_maps = dict(source_maps) self.sink_maps = dict(sink_maps) self.fgExePath = fgExePath self.factorGraphs = {} # dict of factorGraphs as pyfac Graphs self.factorDiGraphs = {} # dict of factorGraphs as networkx diGraphs self.unitigFactorNodes = {} self.unitigFluxNodes = {} self.maxFlux = 2 self.maxTotal = 16 self.working_dir = working_dir #define dummy source and sink node names self.sinkNode = 'sink+' self.sourceNode = 'source+' self.no_folds = no_folds if minIntensity == None: self.minIntensity = AssemblyPathSVA.minStrainCoverage/self.readLength else: self.minIntensity = minIntensity #prior parameters for Gamma tau self.alpha = alpha self.beta = beta self.ARD = ARD self.bARD2 = bARD2 if self.ARD: self.alpha0, self.beta0 = alpha0, beta0 self.BIAS = BIAS if self.BIAS: self.muTheta0 = muTheta0 self.tauTheta0 = tauTheta0 self.tauType = tauType self.nNmfIters = nNmfIters self.V = 0 self.mapIdx = {} self.mapUnitigs = {} self.adjLengths = {} self.covMapAdj = {} self.unitigs = [] self.genes = [] self.mapGeneIdx = collections.defaultdict(dict) bFirst = True self.nBubbles = 0 self.mapBubbles = {} self.augmentedBiGraphs = {} self.residualBiGraphs = {} geneList = sorted(assemblyGraphs) genesRemove = [] for gene in geneList: self.logger.info('Construct factor graph for: %s', gene) assemblyGraph = self.assemblyGraphs[gene] source_names = [convertNodeToName(source) for source in source_maps[gene]] sink_names = [convertNodeToName(sink) for sink in sink_maps[gene]] assemblyGraph.setDirectedBiGraphSource(source_names,sink_names) self.kFactor = self.readLength/(self.readLength - assemblyGraph.overlapLength + 1.) try: (factorGraph, unitigFactorNode, unitigFluxNode, factorDiGraph, bubble_map) = self.createFactorGraph(assemblyGraph, source_maps[gene], sink_maps[gene]) except ValueError as e: print('COG ' + gene + ' too large not processing') genesRemove.append(gene) continue self.augmentedBiGraphs[gene] = AugmentedBiGraph.createFromUnitigGraph(assemblyGraph) self.residualBiGraphs[gene] = ResidualBiGraph.createFromUnitigGraph(assemblyGraph) self.genes.append(gene) unitigsDash = list(unitigFactorNode.keys()) unitigsDash.sort(key=int) self.factorGraphs[gene] = factorGraph self.factorDiGraphs[gene] = factorDiGraph self.unitigFactorNodes[gene] = unitigFactorNode self.unitigFluxNodes[gene] = unitigFluxNode self.mapUnitigs[gene] = unitigsDash unitigAdj = [gene + "_" + s for s in unitigsDash] self.unitigs.extend(unitigAdj) for (unitigNew, unitig) in zip(unitigAdj,unitigsDash): if unitig.startswith('connect'): self.adjLengths[unitigNew] = 0.0 else: #self.adjLengths[unitigNew] = assemblyGraph.lengths[unitig] - 2.0*assemblyGraph.overlapLength + 2.0*self.readLength self.adjLengths[unitigNew] = assemblyGraph.lengths[unitig] - 2.0*assemblyGraph.overlapLength + self.readLength assert self.adjLengths[unitigNew] > 0 self.mapIdx[unitigNew] = self.V self.mapGeneIdx[gene][unitig] = self.V self.covMapAdj[unitigNew] = assemblyGraph.covMap[unitig] * float(self.adjLengths[unitigNew])*(self.kFactor/self.readLength) if bFirst: self.S = assemblyGraph.covMap[unitig].shape[0] bFirst = False self.mapBubbles[self.V] = bubble_map[unitig] self.V += 1 for gene in genesRemove: del self.assemblyGraphs[gene] del self.sink_maps[gene] del self.source_maps[gene] self.cGraph = AugmentedBiGraph.combineGraphs(self.augmentedBiGraphs, self.genes) self.biasMap = {} self.nBias = 0 if biasType == 'bubble': self.biasMap = self.mapBubbles self.nBias = self.nBubbles elif biasType == 'unitig': self.nBias = self.V self.biasMap = {v:v for v in range(self.V)} elif biasType == 'gene': self.nBias = len(self.genes) gene_idx = 0 for gene, unitigs in self.mapUnitigs.items(): for unitig in unitigs: v = self.mapGeneIdx[gene][unitig] self.biasMap[v] = gene_idx gene_idx += 1 else: self.logger.error('Invalid bias type') self.biasType = biasType self.logger.info('Using bias type: %s', self.biasType) #find degenerate unitig sequences (self.degenSeq, self.MaskDegen) = self.flag_degenerate_sequences() self.VDash = self.V - len(self.degenSeq.keys()) self.logger.info('Using %d of %d non-degenerate unitigs',self.VDash,self.V) self.X = np.zeros((self.V,self.S)) self.XN = np.zeros((self.V,self.S)) self.lengths = np.zeros(self.V) #note really need to remove unreachable nodes from calculations self.logPhiPrior = np.zeros(self.V) for gene, unitigFactorNode in self.unitigFactorNodes.items(): self.setPhiConstant(self.mapUnitigs[gene], self.mapGeneIdx[gene], unitigFactorNode) idx = 0 for v in self.unitigs: covName = None if v in self.covMapAdj: covName = self.covMapAdj[v] else: self.logger.error('Cannot get coverage for unitig: %s',v) self.lengths[idx] = self.adjLengths[v] self.X[idx,:] = covName if self.lengths[idx] > 0.: self.XN[idx,:] = covName/self.lengths[idx] idx=idx+1 self.XD = np.floor(self.X).astype(int) sumSourceCovs = Counter() sumSinkCovs = Counter() sumSourceCovsS = defaultdict(lambda:np.zeros(self.S)) sumSinkCovsS = defaultdict(lambda:np.zeros(self.S)) self.geneCovs = {} self.geneDegenerate = {} self.gene_maps = defaultdict(set) for gene, sources in self.source_maps.items(): for source in sources: sunitig = source[0] sumSourceCovs[gene] += np.sum(self.assemblyGraphs[gene].covMap[sunitig]) sumSourceCovsS[gene] += self.assemblyGraphs[gene].covMap[sunitig] vunitig = self.mapGeneIdx[gene][sunitig] if vunitig in self.degenSeq: mapv = self.degenSeq[vunitig] mapGene = self.unitigs[mapv].split('_')[0] self.gene_maps[mapGene].add(gene) self.geneDegenerate[gene] = mapGene for gene, sinks in self.sink_maps.items(): #print(gene) for sink in sinks: sunitig = sink[0] if sunitig in self.mapGeneIdx[gene]: sumSinkCovs[gene] += np.sum(self.assemblyGraphs[gene].covMap[sunitig]) sumSinkCovsS[gene] += self.assemblyGraphs[gene].covMap[sunitig] #print(str(sunitig)) vunitig = self.mapGeneIdx[gene][sunitig] if vunitig in self.degenSeq: mapv = self.degenSeq[vunitig] mapGene = self.unitigs[mapv].split('_')[0] self.gene_maps[mapGene].add(gene) self.geneDegenerate[gene] = mapGene for gene, sinkCovs in sumSinkCovs.items(): tempMatrix = np.zeros((2,self.S)) tempMatrix[0,:] = sumSinkCovsS[gene] tempMatrix[1,:] = sumSourceCovsS[gene] self.geneCovs[gene] = np.mean(tempMatrix,axis=0) self.maxSampleCov = 0. if minSumCov is not None: self.minSumCov = minSumCov self.fracCov = 0.0 elif fracCov is not None: self.fracCov = fracCov self.estCov = np.mean(np.asarray(list(sumSourceCovs.values()) + list(sumSinkCovs.values()))) self.minSumCov = self.fracCov*self.estCov self.meanSampleCov = np.mean(np.array(list(sumSourceCovsS.values()) + list(sumSinkCovsS.values())),axis=0) self.maxSampleCov = self.fracCov*np.max(self.meanSampleCov) else: self.minSumCov = 0.0 self.fracCov = 0.0 # print("Minimum coverage: " + str(self.minSumCov)) if self.minSumCov > 0.0: self.adjUncertain = np.max(self.meanSampleCov)/self.readLength for gene, unitigFluxNode in self.unitigFluxNodes.items(): self.removeNoise(unitigFluxNode, self.mapUnitigs[gene], gene, self.minSumCov) sumCov=np.sum(self.meanSampleCov) self.sumCov = sumCov #self.maxFlow = (5.0*sumCov)/self.readLength self.maxFlow = 1. (self.cRGraph, cIdx) = ResidualBiGraph.combineGraphs(self.residualBiGraphs, self.genes,self.mapGeneIdx,self.maxFlow) self.cGeneIdx = {} self.cGeneIdx['gene'] = cIdx self.logger.info('Read length used %d', self.readLength) self.logger.info('Kmer coverage conversion factor %.3f', self.kFactor) self.totalCov = sumCov*self.kFactor self.logger.info('Total sum of sample coverages: %.3f', self.totalCov) self.minIntensity = max(1.5,self.fracCov*self.totalCov)/self.readLength self.logger.info('Set minimum intensity/cov for strain: %.3f,%.3f', self.minIntensity, self.minIntensity*self.readLength) self.NOISE = NOISE if self.totalCov < self.minNoiseCov: self.NOISE = False self.logger.info('Coverage < %.3f no noise', self.minNoiseCov) self.logger.info('Applying noise: %s', str(self.NOISE)) if self.tauType == 'auto': xRange = np.max(self.X) - np.min(self.X[self.X > 0]) self.logger.info('Automatically set precision') if xRange < AssemblyPathSVA.xRangeFixed: self.logger.info('Xrange %.3f < %.3f used fixed precision',xRange, AssemblyPathSVA.xRangeFixed) self.tauType = 'fixed' else: self.logger.info('Xrange %.3f > %.3f used log-scaled precision',xRange, AssemblyPathSVA.xRangeFixed) self.tauType = 'log' if self.tauType == 'fixed': self.bLogTau = False self.bFixedTau = True self.bPoissonTau = False elif self.tauType == 'log': self.bLogTau = True self.bFixedTau = False self.bPoissonTau = False elif self.tauType == 'empirical': self.bLogTau = False self.bFixedTau = False self.bPoissonTau = False elif self.tauType == 'poisson': self.bLogTau = False self.bFixedTau = False self.bPoissonTau = True self.expTau = 1.0/(self.X + 0.5) self.expLogTau = np.log(self.expTau) else: self.logger.error("Hmm... impossible tau strategy disturbing") self.logger.info('Precision type: %s', self.tauType) #create mask matrices self.Identity = np.ones((self.V,self.S)) #Now initialise SVA parameters self.G = G if self.NOISE: self.GDash = self.G + 1 self.epsilonNoise = epsilonNoise if self.maxSampleCov > 0.: self.epsilonNoise = self.maxSampleCov/self.readLength else: self.GDash = self.G self.Omega = self.V*self.S #list of mean assignments of strains to graph self.expPhi = np.zeros((self.V,self.GDash)) self.expPhi2 = np.zeros((self.V,self.GDash)) self.HPhi = np.zeros((self.V,self.GDash)) if self.NOISE: self.expPhi[:,self.G] = 1. self.expPhi2[:,self.G] = 1. self.epsilon = epsilon #parameter for gamma exponential prior self.expGamma = np.zeros((self.GDash,self.S)) #expectation of gamma self.expGamma2 = np.zeros((self.GDash,self.S)) self.muGamma = np.zeros((self.GDash,self.S)) self.tauGamma = np.zeros((self.GDash,self.S)) self.varGamma = np.zeros((self.GDash,self.S)) #current excitations on the graph self.eLambda = np.zeros((self.V,self.S)) self.margG = dict() for gene in self.genes: self.margG[gene] = [dict() for x in range(self.G)] if self.ARD: self.alphak_s, self.betak_s = np.zeros(self.G), np.zeros(self.G) self.exp_lambdak, self.exp_loglambdak = np.zeros(self.G), np.zeros(self.G) for g in range(self.G): self.alphak_s[g] = self.alpha0 self.betak_s[g] = self.beta0 self.update_exp_lambdak(g) if self.BIAS: self.expThetaCat = np.ones(self.nBias) self.expThetaCat.fill(self.muTheta0) self.expTheta2Cat = np.ones(self.nBias) self.expTheta2Cat.fill(self.muTheta0*self.muTheta0) self.muThetaCat = np.ones(self.nBias) self.muThetaCat.fill(self.muTheta0) self.tauThetaCat = np.ones(self.nBias) self.tauThetaCat.fill(self.tauTheta0) self.expTheta = np.ones(self.V) self.expTheta.fill(self.muTheta0) self.expTheta2 = np.ones(self.V) self.expTheta2.fill(self.muTheta0*self.muTheta0) self.muTheta = np.ones(self.V) self.muTheta.fill(self.muTheta0) self.tauTheta = np.ones(self.V) self.tauTheta.fill(self.tauTheta0) self.varTheta = 1.0/self.tauTheta self.elbo = 0. self.bLoess = bLoess self.bGam = bGam self.tauThresh = tauThresh self.logX = np.log(self.X + 0.5) self.expTau = np.full((self.V,self.S),self.alpha/self.beta) self.expLogTau = np.full((self.V,self.S), digamma(self.alpha)- math.log(self.beta)) self.betaTau = np.full((self.V,self.S),self.beta) self.alphaTau = np.full((self.V,self.S),self.alpha) def flag_degenerate_sequences(self): #First test for unitig overlaps uniqSeqs = defaultdict(list) for gene in sorted(self.assemblyGraphs): assemblyGraph = self.assemblyGraphs[gene] unitigs = self.mapUnitigs[gene] for unitig in unitigs: uniqSeqs[assemblyGraph.sequences[unitig]].append((gene,unitig)) maskMatrix = np.ones((self.V,self.S)) degenSeq = {} for uniqSeq, hits in uniqSeqs.items(): if len(hits) > 1: for hit in hits[1:]: vmask = self.mapGeneIdx[hit[0]][hit[1]] maskMatrix[vmask,:] = 0. degenSeq[vmask] = self.mapGeneIdx[hits[0][0]][hits[0][1]] return (degenSeq, maskMatrix) def update_lambdak(self,k): ''' Parameter updates lambdak. ''' if self.bARD2: self.alphak_s[k] = self.alpha0 + 0.5*self.S self.betak_s[k] = self.beta0 + 0.5*self.expGamma2[k,:].sum() else: self.alphak_s[k] = self.alpha0 + self.S self.betak_s[k] = self.beta0 + self.expGamma[k,:].sum() def update_exp_lambdak(self,g): ''' Update expectation lambdak. ''' self.exp_lambdak[g] = self.alphak_s[g]/self.betak_s[g] self.exp_loglambdak[g] = digamma(self.alphak_s[g]) - math.log(self.betak_s[g]) def writeNetworkGraph(self,networkGraph, fileName): copyGraph = networkGraph.copy() for (n,d) in copyGraph.nodes(data=True): del d["code"] nx.write_graphml(copyGraph,fileName) def createFactorGraph(self, assemblyGraph, sources, sinks): tempGraph = self.createTempGraph(assemblyGraph, assemblyGraph.unitigs) self.addSourceSink(tempGraph, sources, sinks) #use largest connected factor graph tempUFactor = tempGraph.to_undirected() compFactor = sorted(nx.connected_components(tempUFactor),key = len, reverse=True) for c in compFactor: if 'source+' in c and 'sink+' in c: largestFactor = c break fNodes = list(tempGraph.nodes()) for node in fNodes: if node not in largestFactor: tempGraph.remove_node(node) #self.writeNetworkGraph(tempGraph,"temp.graphml") bubble_list = [] bidx = self.nBubbles node = 'source+' while node != 'sink+': (visited,sink) = findSuperBubble(tempGraph,node,tempGraph.neighbors,tempGraph.predecessors) if sink is not None: bubble_list.append((node,sink,visited)) node = sink else: break try: (factorGraph, unitigFactorNodes, unitigFluxNodes) = self.generateFactorGraph(tempGraph, assemblyGraph.unitigs) except ValueError as e: print('Not using COG as factor graph too large') raise unitigsDash = list(unitigFactorNodes.keys()) bubble_map = {} map_bubble = defaultdict(list) for (node,sink,visited) in bubble_list: unode = node[:-1] if unode in unitigsDash: bubble_map[unode] = bidx map_bubble[bidx].append(unode) bidx += 1 for visit in visited: if visit != node: uvisit = visit[:-1] if uvisit in unitigsDash: bubble_map[uvisit] = bidx map_bubble[bidx].append(uvisit) if len(map_bubble[bidx]) > 0: bidx += 1 for unitig in unitigsDash: if unitig not in bubble_map: bubble_map[unitig] = bidx map_bubble[bidx].append(unitig) if len(map_bubble[bidx]) > 0: bidx += 1 self.nBubbles = bidx return (factorGraph, unitigFactorNodes, unitigFluxNodes, tempGraph,bubble_map) def generateFactorGraph(self, factorGraph, unitigs): probGraph = Graph() for node in factorGraph: if 'factor' not in factorGraph.nodes[node]: print(str(node)) else: if not factorGraph.nodes[node]['factor']: #just add edge as variable probGraph.addVarNode(node,self.maxFlux) for node in factorGraph: if factorGraph.nodes[node]['factor']: inNodes = list(factorGraph.predecessors(node)) outNodes = list(factorGraph.successors(node)) nIn = len(inNodes) nOut = len(outNodes) Ntotal = nIn + nOut if Ntotal < self.maxTotal: factorMatrix = np.zeros([self.maxFlux]*Ntotal) for indices, value in np.ndenumerate(factorMatrix): fIn = sum(indices[0:nIn]) fOut = sum(indices[nIn:]) if node == self.sourceNode: if fIn == fOut: if fIn == 0: factorMatrix[indices] = 1.0 else: factorMatrix[indices] = 1.0 else: if fIn == fOut: factorMatrix[indices] = 1.0 mapNodeList = [probGraph.mapNodes[x] for x in inNodes + outNodes] #mapNodes[node] = probGraph.addFacNode(factorMatrix, *mapNodeList) probGraph.addFacNode(factorMatrix, *mapNodeList) else: raise ValueError('Too many inputs links to node') unitigFacNodes = {} unitigFluxNodes = {} for unitig in unitigs: plusNode = unitig + "+" inNodesPlus = [] if plusNode in factorGraph: inNodesPlus = list(factorGraph.predecessors(plusNode)) minusNode = unitig + "-" inNodesMinus = [] if minusNode in factorGraph: inNodesMinus = list(factorGraph.predecessors(minusNode)) nInPlus = len(inNodesPlus) nInMinus = len(inNodesMinus) Ntotal = nInPlus + nInMinus if Ntotal > 0: mapNodesF = [probGraph.mapNodes[x] for x in inNodesPlus + inNodesMinus] nMax = Ntotal*(self.maxFlux - 1) + 1 probGraph.addVarNode(unitig,nMax) dimF = [nMax] + [self.maxFlux]*Ntotal fluxMatrix = np.zeros(dimF) dummyMatrix = np.zeros([self.maxFlux]*Ntotal) for indices, value in np.ndenumerate(dummyMatrix): tIn = sum(indices) fluxMatrix[tuple([tIn]+ list(indices))] = 1.0 unitigFluxNodes[unitig] = probGraph.addFacNode(fluxMatrix, *([probGraph.mapNodes[unitig]] + mapNodesF)) discreteMatrix = np.zeros((nMax,1)) unitigFacNodes[unitig] = probGraph.addFacNode(discreteMatrix, probGraph.mapNodes[unitig]) return (probGraph,unitigFacNodes, unitigFluxNodes) def removeNoise(self, unitigFluxNodes, unitigs, gene, minSumCov): for unitig in unitigs: v_idx = self.mapGeneIdx[gene][unitig] sumCov = np.sum(self.X[v_idx,:]) if sumCov < minSumCov: unitigFluxNodes[unitig].P = np.zeros_like(unitigFluxNodes[unitig].P) zeroth = next(np.ndindex(unitigFluxNodes[unitig].P.shape)) unitigFluxNodes[unitig].P[zeroth] = 1. def createTempGraph(self, assemblyGraph, unitigs): factorGraph = nx.DiGraph() for node in unitigs: #add positive and negative version of untig to factor graph nodePlus = (node, True) nodeMinus = (node, False) nodePlusName = convertNodeToName(nodePlus) nodeMinusName = convertNodeToName(nodeMinus) if nodePlusName not in factorGraph: factorGraph.add_node(nodePlusName, factor=True, code=nodePlus) if nodeMinusName not in factorGraph: factorGraph.add_node(nodeMinusName, factor=True, code=nodeMinus) #get all links outgoing given +ve direction on node for outnode, dirns in assemblyGraph.overlaps[node].items(): for dirn in dirns: (start,end) = dirn #add outgoing positive edge if start: addEdge = (nodePlus, (outnode, end)) else: #reverse as incoming edge addEdge = ((outnode,not end), (node, True)) edgeName = convertNodeToName(addEdge) if edgeName not in factorGraph: factorGraph.add_node(edgeName, factor=False, code=addEdge) if start: factorGraph.add_edge(nodePlusName, edgeName) else: factorGraph.add_edge(edgeName, nodePlusName) #add negative edges if start: #reverse as incoming edge addEdge = ((outnode, not end),(nodeMinus)) else: addEdge = (nodeMinus, (outnode, end)) edgeName = convertNodeToName(addEdge) if edgeName not in factorGraph: factorGraph.add_node(edgeName, factor=False, code=addEdge) if start: factorGraph.add_edge(edgeName, nodeMinusName) else: factorGraph.add_edge(nodeMinusName, edgeName) return factorGraph def addSourceSink(self, tempGraph, sources, sinks): #add sink factor and dummy flow out if self.sinkNode not in tempGraph: tempGraph.add_node(self.sinkNode, factor=True, code=('sink',True)) node_code = (('sink',True),('infty',True)) sinkEdge = convertNodeToName(node_code) tempGraph.add_node(sinkEdge, factor=False, code=node_code) tempGraph.add_edge(self.sinkNode, sinkEdge) if self.sourceNode not in tempGraph: tempGraph.add_node(self.sourceNode, factor=True, code=('source',True)) node_code = (('zero',True),('source',True)) sourceEdge = convertNodeToName(node_code) tempGraph.add_node(sourceEdge, factor=False, code=node_code) tempGraph.add_edge(sourceEdge, self.sourceNode) for (sinkid,dirn) in sinks: node_code = ((sinkid,dirn),('sink',True)) edgeName = convertNodeToName(node_code) sinkName = convertNodeToName((sinkid,dirn)) tempGraph.add_node(edgeName, factor=False, code=node_code) tempGraph.add_edge(sinkName,edgeName) tempGraph.add_edge(edgeName,self.sinkNode) for (sourceid,dirn) in sources: node_code = (('source',True),(sourceid,dirn)) edgeName = convertNodeToName(node_code) sourceName = convertNodeToName((sourceid,dirn)) tempGraph.add_node(edgeName, factor=False, code=node_code) tempGraph.add_edge(edgeName,sourceName) tempGraph.add_edge(self.sourceNode,edgeName) def parseMargString(self, factorGraph, lines): mapMarg = {} lines = [x.strip() for x in lines] for line in lines: matchP = re.search(r'\((.*)\)',line) if matchP is not None: matchedP = matchP.group(1) matchVar = re.search(r'\{x(.*?)\}',matchedP) if matchVar is not None: var = matchVar.group(1) matchVals = re.search(r'\((.*?)\)',matchedP) if matchVals is not None: vals = matchVals.group(1).split(',') floatVals = [float(i) for i in vals] if int(var) >= len(factorGraph.varNames): varName = "Debug" else: varName = factorGraph.varNames[int(var)] if varName is not None: mapMarg[varName] = np.asarray(floatVals) return mapMarg def parseFGString(self, factorGraph, lines): mapVar = {} lines = [x.strip() for x in lines] #lines = outputString.split('\\n') bFirst = True for line in lines: if not bFirst: toks = line.split(',') if len(toks) == 2: varIdx = int(toks[0][1:]) varName = factorGraph.varNames[int(varIdx)] varValue = int(toks[1]) mapVar[varName] = varValue bFirst = False return mapVar def updateUnitigFactors(self, unitigs, unitigMap, unitigFacNodes, gidx, mask=None): if mask is None: mask = np.ones((self.V, self.S)) mapGammaG = self.expGamma[gidx,:] mapGammaG2 = self.expGamma2[gidx,:] #dSum2 = np.sum(mapGammaG2) tPhi = np.delete(self.expPhi,gidx,1) tGamma = np.delete(self.expGamma,gidx,0) #import ipdb; ipdb.set_trace() currNELambda = np.dot(tPhi,tGamma) for unitig in unitigs: if unitig in unitigFacNodes: unitigFacNode = unitigFacNodes[unitig] v_idx = unitigMap[unitig] v_mask = mask[v_idx,] P = unitigFacNode.P tempMatrix = np.zeros_like(P) currELambda = currNELambda[v_idx,:]*v_mask lengthNode = self.lengths[v_idx] nMax = unitigFacNode.P.shape[0] dFac = -0.5*self.expTau[v_idx,:]*lengthNode #now S dim if not self.BIAS: T1 = mapGammaG*(lengthNode*currELambda - self.X[v_idx,:]) else: T1 = mapGammaG*(lengthNode*currELambda*self.expTheta2[v_idx] - self.X[v_idx,:]*self.expTheta[v_idx]) dVal1 = 2.0*T1*v_mask dVal2 = lengthNode*mapGammaG2*v_mask if self.BIAS: dVal2 *= self.expTheta2[v_idx] for d in range(nMax): tempMatrix[d] = np.sum(dFac*(dVal1*float(d) + dVal2*float(d*d))) unitigFacNode.P = expNormLogProb(tempMatrix) def updateUnitigFactorsN(self, unitigs, unitigMap, unitigFacNodes): for unitig in unitigs: if unitig in unitigFacNodes: unitigFacNode = unitigFacNodes[unitig] v_idx = unitigMap[unitig] P = unitigFacNode.P tempMatrix = np.zeros_like(P) nMax = unitigFacNode.P.shape[0] unitigFacNode.P = expNormLogProb(tempMatrix) def updateUnitigFactorsW(self,unitigs, unitigMap, unitigFacNodes, W,gidx): for unitig in unitigs: if unitig in unitigFacNodes: unitigFacNode = unitigFacNodes[unitig] v_idx = unitigMap[unitig] P = unitigFacNode.P tempMatrix = np.zeros_like(P) w = W[v_idx,gidx] wmax = P.shape[0] - 1 tempMatrix.fill(self.minW) if w > wmax: w = wmax iw = int(w) difw = w - iw tempMatrix[iw] = 1.0 - difw if iw < wmax: tempMatrix[iw + 1] = difw unitigFacNode.P = tempMatrix def updateUnitigFactorsMarg(self,unitigs, unitigMap, unitigFacNodes, marg): for unitig in unitigs: if unitig in unitigFacNodes: unitigFacNode = unitigFacNodes[unitig] v_idx = unitigMap[unitig] P = unitigFacNode.P if unitig in marg: unitigFacNode.P = np.copy(marg[unitig]) def setPhiConstant(self,unitigs, unitigMap, unitigFacNodes): dLogNPhi = 0. for unitig in unitigs: if unitig in unitigFacNodes: unitigFacNode = unitigFacNodes[unitig] v_idx = unitigMap[unitig] P = unitigFacNode.P wmax = P.shape[0] self.logPhiPrior[v_idx] = math.log(1.0/wmax) def updateUnitigFactorsRef(self, unitigs, unitigMap, unitigFacNodes, mapRef,ref): for unitig in unitigs: if unitig in unitigFacNodes: unitigFacNode = unitigFacNodes[unitig] v_idx = unitigMap[unitig] P = unitigFacNode.P tempMatrix = np.zeros_like(P) if ref in mapRef[unitig]: delta = mapRef[unitig][ref] else: delta = 10.0 tempMatrix[1] = 0.99*np.exp(-0.25*delta) tempMatrix[0] = 1.0 - tempMatrix[1] unitigFacNode.P = tempMatrix def removeGamma(self,g_idx): meanAss = self.expPhi[:,g_idx] gammaG = self.expGamma[g_idx,:] self.eLambda -= meanAss[:,np.newaxis]*gammaG[np.newaxis,:] def addGamma(self,g_idx): meanAss = self.expPhi[:,g_idx] gammaG = self.expGamma[g_idx,:] self.eLambda += meanAss[:,np.newaxis]*gammaG[np.newaxis,:] def updateTheta(self, mask = None): if mask is None: mask = np.ones((self.V, self.S)) self.eLambda = np.dot(self.expPhi, self.expGamma) denom = np.sum(self.expTau*self.exp_square_lambda_matrix()*mask,axis=1)*self.lengths*self.lengths numer = self.lengths*np.sum(self.X*self.eLambda*self.expTau*mask,axis=1) self.muThetaCat.fill(self.muTheta0*self.tauTheta0) self.tauThetaCat.fill(self.tauTheta0) for v in range(self.V): b = self.biasMap[v] self.muThetaCat[b] += numer[v] self.tauThetaCat[b] += denom[v] self.muThetaCat = self.muThetaCat/self.tauThetaCat self.expThetaCat = np.asarray(TN_vector_expectation(self.muThetaCat,self.tauThetaCat)) self.varThetaCat = np.asarray(TN_vector_variance(self.muThetaCat,self.tauThetaCat)) self.expTheta2Cat = self.varThetaCat + self.expThetaCat*self.expThetaCat for v in range(self.V): b = self.biasMap[v] self.muTheta[v] = self.muThetaCat[b] self.expTheta[v] = self.expThetaCat[b] self.varTheta[v] = self.varThetaCat[b] self.expTheta2[v] = self.expTheta2Cat[b] def updateGamma(self, g_idx, mask = None, bMaskDegen = False): if mask is None: mask = np.ones((self.V, self.S)) if bMaskDegen: mask = mask*self.MaskDegen temp = np.delete(self.expGamma,g_idx,0) temp2 = np.delete(self.expPhi,g_idx,1) if not self.BIAS: numer = (self.X - np.dot(temp2,temp)*self.lengths[:,np.newaxis]) else: numer = (self.X*self.expTheta[:,np.newaxis] - np.dot(temp2,temp)*self.lengths[:,np.newaxis]*self.expTheta2[:,np.newaxis]) gphi = self.expPhi[:,g_idx]*self.lengths numer = gphi[:,np.newaxis]*numer denom = self.lengths*self.lengths*self.expPhi2[:,g_idx]#dimensions of V if self.BIAS: denom *= self.expTheta2 dSum = np.dot((self.expTau*mask).transpose(),denom) numer=numer*self.expTau*mask nSum = np.sum(numer,0) if self.NOISE and g_idx == self.G: lamb = 1.0/self.epsilonNoise else: lamb = 1.0/self.epsilon if self.ARD: if self.bARD2: lamb = 0. else: lamb = self.exp_lambdak[g_idx] nSum -= lamb if self.ARD and self.bARD2: if g_idx != self.G: dSum += self.exp_lambdak[g_idx] muGammaG = nSum/dSum tauGammaG = dSum expGammaG = np.asarray(TN_vector_expectation(muGammaG,tauGammaG)) varGammaG = np.asarray(TN_vector_variance(muGammaG,tauGammaG)) expGamma2G = varGammaG + expGammaG*expGammaG self.expGamma[g_idx,:] = expGammaG self.expGamma2[g_idx,:] = expGamma2G self.tauGamma[g_idx,:] = tauGammaG self.muGamma[g_idx,:] = muGammaG self.varGamma[g_idx,:] = varGammaG def updateTau(self,bFit=True, mask = None, bMaskDegen = True): if self.bPoissonTau: self.expTau = 1.0/(self.X + 0.5) self.expLogTau = np.log(self.expTau) return if mask is None: mask = np.ones((self.V, self.S)) if self.bFixedTau: self.updateFixedTau(mask, bMaskDegen) else: if self.bLogTau: self.updateLogTauX(bFit, mask, bMaskDegen) else: self.updateEmpTauX(bFit, mask, bMaskDegen) def updateFixedTau(self, mask = None, bMaskDegen = True): if mask is None: mask = np.ones((self.V, self.S)) if bMaskDegen: maskFit = self.MaskDegen*mask else: maskFit = mask Omega = float(np.sum(maskFit)) square_diff_matrix = self.exp_square_diff_matrix() betaTemp = self.beta + 0.5*np.sum(square_diff_matrix*maskFit) alphaTemp = self.alpha + 0.5*Omega tempTau = alphaTemp/betaTemp tempLogTau = digamma(alphaTemp) - np.log(betaTemp) self.betaTau.fill(betaTemp/Omega) self.betaTau = mask*self.betaTau self.alphaTau.fill(alphaTemp/Omega) self.alphaTau = mask*self.alphaTau self.expTau.fill(tempTau) self.expTau = self.expTau*mask self.expLogTau.fill(tempLogTau) self.expLogTau = self.expLogTau*mask def updateLogTauX(self,bFit = True, mask = None, bMaskDegen = True): if mask is None: mask = np.ones((self.V, self.S)) square_diff_matrix = self.exp_square_diff_matrix() mX = np.ma.masked_where(mask==0, self.X) X1D = np.ma.compressed(mX) mSDM = np.ma.masked_where(mask==0, square_diff_matrix) mBetaTau = self.beta*X1D + 0.5*np.ma.compressed(mSDM) mBetaTau[mBetaTau < AssemblyPathSVA.minBeta] = AssemblyPathSVA.minBeta mLogExpTau = digamma(self.alpha + 0.5) - np.log(mBetaTau) if bMaskDegen: maskFit = self.MaskDegen*mask else: maskFit = mask mXFit = np.ma.masked_where(maskFit==0, self.X) X1DFit = np.ma.compressed(mXFit) mSDMFit = np.ma.masked_where(maskFit==0, square_diff_matrix) mBetaTauFit = self.beta*X1DFit + 0.5*np.ma.compressed(mSDMFit) mBetaTauFit[mBetaTauFit < AssemblyPathSVA.minBeta] = AssemblyPathSVA.minBeta mLogExpTauFit = digamma(self.alpha + 0.5) - np.log(mBetaTauFit) try: if self.bLoess: assert(bMaskDegen == False) self.logger.info("Attemptimg Loess smooth") yest_sm = lowess(X1D,mLogExpTau, f=0.75, iter=3) elif self.bGam: if bFit: self.gam = LinearGAM(s(0,n_splines=5,constraints='monotonic_dec')).fit(X1DFit, mLogExpTauFit) yest_sm = self.gam.predict(X1D) else: self.logger.info("Attemptimg linear regression") model = LinearRegression() poly_reg = PolynomialFeatures(degree=2) X_poly = poly_reg.fit_transform(X1DFit.reshape(-1,1)) model.fit(X_poly, mLogExpTauFit) X_poly_est = poly_reg.fit_transform(X1D.reshape(-1,1)) yest_sm = model.predict(X_poly_est) except ValueError: self.logger.info("Performing fixed tau") self.updateFixedTau(mask,bMaskDegen) return np.place(self.expLogTau, mask == 1, yest_sm) np.place(self.expTau, mask == 1, np.exp(yest_sm)) np.place(self.betaTau, mask == 1, mBetaTau) def updateEmpTauX(self,bFit = True, mask = None, bMaskDegen = False): if mask is None: mask = np.ones((self.V, self.S)) square_diff_matrix = self.exp_square_diff_matrix() if bMaskDegen: maskFit = self.MaskDegen*mask else: maskFit = mask mXFit = np.ma.masked_where(maskFit==0, self.X) X1DFit = np.ma.compressed(mXFit) logX1DFit = np.log(0.5 + X1DFit) mSDMFit = np.ma.masked_where(maskFit==0, square_diff_matrix) mFitFit = np.ma.compressed(mSDMFit) logMFitFit = np.log(mFitFit + AssemblyPathSVA.minVar) if bFit: try: self.gam = LinearGAM(s(0,n_splines=5,constraints='monotonic_inc')).fit(logX1DFit,logMFitFit) except ValueError: self.logger.info("Performing fixed tau") self.updateFixedTau(mask) return mX = np.ma.masked_where(mask==0, self.X) X1D = np.ma.compressed(mX) logX1D = np.log(0.5 + X1D) yest_sm = self.gam.predict(logX1D) mBetaTau = self.beta*(X1D + 0.5) + 0.5*np.exp(yest_sm) np.place(self.betaTau, mask == 1, mBetaTau) mExpTau = (self.alpha + 0.5)/mBetaTau np.place(self.expTau, mask == 1, mExpTau) mLogTau = digamma(self.alpha + 0.5) - np.log(mBetaTau) np.place(self.expLogTau, mask == 1, mLogTau) def updateExpPhi(self,unitigs,mapUnitig,marg,g_idx): for unitig in unitigs: if unitig in marg: v_idx = mapUnitig[unitig] ND = marg[unitig].shape[0] self.expPhi[v_idx,g_idx] = np.sum(marg[unitig]*np.arange(ND)) d2 = np.square(np.arange(ND)) self.expPhi2[v_idx,g_idx] = np.sum(marg[unitig]*d2) self.HPhi[v_idx,g_idx] = ss.entropy(marg[unitig]) def writeFactorGraphs(self, g, drop_strain, relax_path, mask = None): if mask is None: mask = np.ones((self.V, self.S)) fgFileStubs = {} for gene, factorGraph in self.factorGraphs.items(): if not drop_strain[gene][g]: unitigs = self.assemblyGraphs[gene].unitigs self.updateUnitigFactors(unitigs, self.mapGeneIdx[gene], self.unitigFactorNodes[gene], g, mask) factorGraph.reset() if relax_path: factorGraph.var['zero+source+'].clear_condition() factorGraph.var['sink+infty+'].clear_condition() else: factorGraph.var['zero+source+'].condition(1) factorGraph.var['sink+infty+'].condition(1) graphString = str(factorGraph) graphFileStub = str(uuid.uuid4()) + 'graph_'+ str(g) graphFileName = self.working_dir + "/" + graphFileStub + '.fg' with open(graphFileName, "w") as text_file: print(graphString, file=text_file) fgFileStubs[gene] = graphFileStub return fgFileStubs def readMarginals(self, fgFileStubs, g, drop_strain): for gene, factorGraph in self.factorGraphs.items(): if not drop_strain[gene][g]: outFile = self.working_dir + "/" + fgFileStubs[gene] + '.out' try: inHandle = open(outFile, 'r') outLines = inHandle.readlines() inHandle.close() margP = self.parseMargString(factorGraph, outLines) if len(margP) > 0: self.margG[gene][g] = margP self.updateExpPhi(self.assemblyGraphs[gene].unitigs,self.mapGeneIdx[gene],self.margG[gene][g],g) if os.path.exists(outFile): os.remove(outFile) fgFile = self.working_dir + "/" + fgFileStubs[gene] + '.fg' if os.path.exists(fgFile): os.remove(fgFile) #raise FileNotFoundError('Debug') except FileNotFoundError: tempMap = {} vt = 0 nU = len(self.unitigFactorNodes[gene]) tempEta = np.zeros(nU) print('Attempting flow optimisation') for unitig, factorNode in self.unitigFactorNodes[gene].items(): if factorNode.P.ndim > 1: dVal = factorNode.P[1][0] elif factorNode.P.ndim == 1: dVal = factorNode.P[1] else: dVal = 0.5 tempMap[unitig] = vt tempEta[vt] = dVal vt += 1 flowFitTheta = FlowFitTheta(self.residualBiGraphs[gene], self.prng,tempEta, tempMap, True) flowFitTheta.optimiseFlows(20, 1.0) for unitig in self.assemblyGraphs[gene].unitigs: if unitig in self.mapGeneIdx[gene]: v_idx = self.mapGeneIdx[gene][unitig] m_idx = tempMap[unitig] self.expPhi[v_idx,g] = flowFitTheta.Eta[m_idx] self.expPhi2[v_idx,g] = flowFitTheta.Eta[m_idx]*flowFitTheta.Eta[m_idx] # if nx.is_directed_acyclic_graph(self.factorDiGraphs[gene]): # self.logger.info("Attempt greedy path: " + str(g) + " " + gene + ":" + fgFileStubs[gene]) #greedyPath = self.sampleGreedyPath(gene, g) # greedyPath = self.sampleMaxWeightPath(gene, g) # for unitig in self.assemblyGraphs[gene].unitigs: # if unitig in self.mapGeneIdx[gene]: # v_idx = self.mapGeneIdx[gene][unitig] # self.expPhi[v_idx,g] = 0. # self.expPhi2[v_idx,g] = 0. #for unitigd in greedyPath: # unitig = unitigd[:-1] # if unitig in self.mapGeneIdx[gene]: # v_idx = self.mapGeneIdx[gene][unitig] # self.expPhi[v_idx,g] = 1. # self.expPhi2[v_idx,g] = 1. #else: # self.logger.warning("Cannot attempt greedy path") fgFile = self.working_dir + "/" + fgFileStubs[gene] + '.fg' if os.path.exists(fgFile): os.remove(fgFile) def update(self, maxIter, removeRedundant,mask=None, bMaskDegen = False, drop_strain=None,relax_path=False, uncertainFactor=None,minDiff=1.0e-3,bMulti=True): if mask is None: mask = np.ones((self.V, self.S)) if drop_strain is None: drop_strain = {gene:[False]*self.G for gene in self.genes} iter = 0 self.eLambda = np.dot(self.expPhi, self.expGamma) self.updateTau(True, mask, bMaskDegen) diffElbo = 1.0 currElbo=self.calc_elbo(mask, bMaskDegen) self.logger.info("Iter, G, Div, DivF, total_elbo, diffElbo") bChangeG = False while iter <= 50 or (iter < maxIter and (diffElbo > minDiff or bChangeG)): #update phi marginals if removeRedundant: if iter >= 50 and iter % 10 == 0: if self.G > 1: bChangeG = self.removeRedundant(self.minIntensity, 10,relax_path,uncertainFactor,mask,bMaskDegen) for g in range(self.G): #self.removeGamma(g) fgFileStubs = {} threads = [] fgFileStubs = self.writeFactorGraphs(g, drop_strain, relax_path, mask) if bMulti: pool = Pool(len(self.genes)) results = [] for gene, graphFileStub in fgFileStubs.items(): graphFileName = self.working_dir + '/' + graphFileStub + '.fg' outFileName = self.working_dir + '/' + graphFileStub + '.out' cmd = self.fgExePath + 'runfg_flex ' + graphFileName + ' ' + outFileName + ' 0 -1' results.append(pool.apply_async(call_proc, (cmd,))) pool.close() pool.join() for result in results: out, err = result.get() # print("out: {} err: {}".format(out, err)) else: results = [] for gene, graphFileStub in fgFileStubs.items(): graphFileName = self.working_dir + '/' + graphFileStub + '.fg' outFileName = self.working_dir + '/' + graphFileStub + '.out' cmd = self.fgExePath + 'runfg_flex ' + graphFileName + ' ' + outFileName + ' 0 -1' results.append(call_proc(cmd)) self.readMarginals(fgFileStubs, g, drop_strain) #self.addGamma(g) if self.ARD: for g in range(self.G): self.update_lambdak(g) self.update_exp_lambdak(g) for g in range(self.GDash): self.updateGamma(g, mask, bMaskDegen) self.eLambda = np.zeros((self.V,self.S)) for g in range(self.GDash): self.addGamma(g) #if iter % 10 == 0: self.updateTau(True, mask, bMaskDegen) if self.BIAS: self.updateTheta(mask) total_elbo = self.calc_elbo(mask, bMaskDegen) diffElbo = abs(total_elbo - currElbo) if np.isnan(diffElbo) or math.isinf(diffElbo): diffElbo = 1. currElbo = total_elbo DivF = self.divF(mask) Div = self.div(mask) if iter % 10 == 0: self.logger.info("%d, %d, %f, %f, %f, %f", iter, self.G, Div, DivF, total_elbo, diffElbo) iter += 1 def get_outlier_cogs_sample(self, mCogFilter = 2.0, cogSampleFrac=0.95): uniquegenes = list(set(self.geneCovs.keys()) ^ set(self.geneDegenerate.keys())) nGenes = len(uniquegenes) g = 0 geneSampleCovArray = np.zeros((nGenes,self.S)) for gene in uniquegenes: geneSampleCovArray[g,:] = self.geneCovs[gene] g = g + 1 outlierGeneSample = np.zeros((nGenes,self.S),dtype=bool) for s in range(self.S): outlierGeneSample[:,s] = reject_outliers(geneSampleCovArray[:,s], m = mCogFilter) filterGenes = outlierGeneSample.sum(axis=1) < (self.S*cogSampleFrac) filteredGenes = [i for (i, v) in zip(uniquegenes, filterGenes) if v] for gene in filteredGenes: filteredGenes.extend(self.gene_maps[gene]) return filteredGenes def updateGammaFixed(self, maxIter, drop_strain=None, relax_path=False): if drop_strain is None: drop_strain = {gene:[False]*self.G for gene in self.genes} iter = 0 self.eLambda = np.dot(self.expPhi, self.expGamma) self.updateTau() while iter < maxIter: #update phi marginals for g in range(self.G): self.removeGamma(g) fgFileStubs = {} threads = [] fgFileStubs = self.writeFactorGraphs(g, drop_strain, relax_path) pool = ThreadPool(len(self.genes)) results = [] for gene, graphFileStub in fgFileStubs.items(): graphFileName = self.working_dir + '/' + graphFileStub + '.fg' outFileName = self.working_dir + '/' + graphFileStub + '.out' cmd = self.fgExePath + 'runfg_flex ' + graphFileName + ' ' + outFileName + ' 0 -1' results.append(pool.apply_async(call_proc, (cmd,))) pool.close() pool.join() for result in results: out, err = result.get() # print("out: {} err: {}".format(out, err)) self.readMarginals(fgFileStubs, g, drop_strain) self.addGamma(g) if self.ARD: for g in range(self.G): self.update_lambdak(g) self.update_exp_lambdak(g) self.updateTau() if self.BIAS: self.updateTheta() total_elbo = self.calc_elbo() DivF = self.divF() Div = self.div() #print(str(iter)+ "," + str(Div) + "," + str(DivF)+ "," + str(total_elbo)) iter += 1 def updatePhiFixed(self, maxIter): iter = 0 while iter < maxIter: for g in range(self.G): self.updateGamma(g) self.eLambda = np.zeros((self.V,self.S)) for g in range(self.GDash): self.addGamma(g) #print(str(iter)+","+ str(self.divF())) iter += 1 def div(self,M=None,bMaskDegen = False): if M is None: M = np.ones((self.V,self.S)) if bMaskDegen: M = M*self.MaskDegen """Compute divergence of target matrix from its NMF estimate.""" Va = self.eLambda if self.BIAS: Va = self.expTheta[:,np.newaxis]*Va return (M*(np.multiply(self.XN, np.log(elop(self.XN, Va, truediv))) + (Va - self.XN))).sum() def divF(self,M=None, bMaskDegen = False): if M is None: M = np.ones((self.V,self.S)) if bMaskDegen: M = M*self.MaskDegen """Compute squared Frobenius norm of a target matrix and its NMF estimate.""" if self.BIAS: R = self.expTheta[:,np.newaxis]*self.eLambda - self.XN else: R = self.eLambda - self.XN return (M*np.multiply(R, R)).sum()/np.sum(M) def divF_matrix(self): """Compute squared Frobenius norm of a target matrix and its NMF estimate.""" if self.BIAS: R = self.expTheta[:,np.newaxis]*self.eLambda - self.XN else: R = self.eLambda - self.XN return np.multiply(R, R) def divergenceN(self, XN, Va): return (np.multiply(XN, np.log(elop(XN, Va, truediv))) - XN + Va).sum() def sampleGreedyPath(self, gene, g): path = [] current = self.sourceNode biGraph = self.factorDiGraphs[gene] assert nx.is_directed_acyclic_graph(biGraph) while current != self.sinkNode: outPaths = list(biGraph.successors(current)) destinations = [list(biGraph.successors(x))[0] for x in outPaths] path.append(current) NDest = len(destinations) if NDest > 0: n = 0 divN = np.zeros(NDest) for dest in destinations: unitig = dest[:-1] if unitig in self.unitigFactorNodes[gene]: unitigFacNode = self.unitigFactorNodes[gene][unitig] divN[n] = unitigFacNode.P[1] n = n+1 outPath = outPaths[np.argmax(divN)] else: break current = list(biGraph.successors(outPath))[0] #print(str(current)) return path def sampleMaxWeightPath(self, gene, g): unitigGraphGene = self.assemblyGraphs[gene] # import ipdb; ipdb.set_trace() if unitigGraphGene.directedUnitigBiGraphS is None: sources_gene = self.source_maps[gene] sinks_gene = self.sink_maps[gene] source_names = [convertNodeToName(source) for source in sources_gene] sink_names = [convertNodeToName(sink) for sink in sinks_gene] unitigGraphGene.setDirectedBiGraphSource(source_names,sink_names) unitigValueDir = defaultdict(lambda: float(-1000)) for unitig, factorNode in self.unitigFactorNodes[gene].items(): if factorNode.P.ndim > 1: dVal = factorNode.P[1][0] elif factorNode.P.ndim == 1: dVal = factorNode.P[1] else: dVal = -1000.0 if np.log(dVal) > -1000.0: unitigValueDir[unitig] = np.log(dVal) unitigValueDir['source+'] = 0. unitigValueDir['sink+'] = 0. (maxPath, maxSeq) = unitigGraphGene.getHeaviestBiGraphPathUnitigNode(unitigValueDir, None, None) return maxPath def sampleMargPath(self,margP,biGraph): path = [] visited = set() current = self.sinkNode while current != self.sourceNode: inPaths = list(biGraph.predecessors(current)) NC = len(inPaths) if NC > 0: tempProb = np.zeros(NC) for idx, inPath in enumerate(inPaths): if inPath not in visited: if inPath in margP: tempProb[idx] = np.sum(margP[inPath][1:]) else: tempProb[idx] = 0. if np.sum(tempProb) > 0.: tempProb = tempProb/np.sum(tempProb) selectIn = self.prng.choice(np.arange(NC), 1, p=tempProb) else: selectIn = self.prng.choice(np.arange(NC),1) path.append(current) current = list(biGraph.predecessors(inPaths[selectIn[0]]))[0] visited.add(inPaths[selectIn[0]]) else: path.append(current) self.logger.warning("Warning: Ended up in errorenous terminal node sampleMargPath") break path.reverse() return path def runFGMarginal(self, factorGraph, g): graphString = str(factorGraph) outFileStub = str(uuid.uuid4()) + 'graph_'+ str(g) graphFileName = self.working_dir + '/' + outFileStub + '.fg' outFileName = self.working_dir + '/' + outFileStub + ".out" with open(graphFileName, "w") as text_file: print(graphString, file=text_file) cmd = self.fgExePath + 'runfg_flex ' + graphFileName + ' ' + outFileName + ' 0 -1' p = Popen(cmd, stdout=PIPE,shell=True) p.wait() with open (outFileName, "r") as myfile: outString=myfile.readlines() os.remove(graphFileName) os.remove(outFileName) return self.parseMargString(factorGraph, outString) def getPathDivergence(self, nSamples,drop_strain=None,relax_path=False): divergence_mean = np.zeros(self.G) (paths,haplotypes) = self.sampleNHaplotypes(nSamples, drop_strain, relax_path) for g in range(self.G): divergences = np.zeros(nSamples) map_length = 0. for s in range(nSamples): div_s = 0 for gene, factorGraph in self.factorGraphs.items(): gMap = self.paths[gene][g] if s == 0: map_length += len(gMap) div_s += len(set(gMap) ^ set(paths[s][gene][g])) divergences[s] = div_s divergence_mean[g] = np.mean(divergences)/map_length return divergence_mean def sampleNHaplotypes(self,nSamples,drop_strain=None,relax_path=False): if drop_strain is None: drop_strain = {gene:[False]*self.G for gene in self.genes} self.eLambda = np.dot(self.expPhi,self.expGamma) all_paths = [] all_haplotypes = [] for s in range(nSamples): paths = defaultdict(list) haplotypes = defaultdict(list) for g in range(self.G): for gene, factorGraph in self.factorGraphs.items(): if not drop_strain[gene][g]: unitigs = self.assemblyGraphs[gene].unitigs marginals = self.margG[gene][g] #self.runFGMarginal(factorGraph, g) biGraph = self.factorDiGraphs[gene] pathG = self.sampleMargPath(marginals,biGraph) pathG.pop() paths[gene].append(pathG) if len(pathG) > 0: unitig = self.assemblyGraphs[gene].getUnitigWalk(pathG) haplotypes[gene].append(unitig) else: haplotypes[gene].append("") paths[gene].append(None) all_haplotypes.append(haplotypes) all_paths.append(paths) return (all_paths, all_haplotypes) def convertMAPToPath(self,mapPath,factorGraph): path = [] visited = set() current = self.sourceNode while current != self.sinkNode: outPaths = list(factorGraph.successors(current)) for outPath in outPaths: if mapPath[outPath] == 1 and outPath not in visited: visited.add(outPath) break path.append(current) if mapPath[outPath] == 1: current = list(factorGraph.successors(outPath))[0] else: break return path def convertMAPMarg(self,MAP,mapNodes): marg = {} for unitig,assign in MAP.items(): if unitig in mapNodes: unitigNode = mapNodes[unitig] nN = unitigNode.dim tempMatrix = np.zeros(nN) tempMatrix[int(assign)] = 1.0 marg[unitig] = tempMatrix return marg def calcTreeWidths(self): treeWidths = {} for gene, factorGraph in self.factorGraphs.items(): unitigs = self.assemblyGraphs[gene].unitigs self.updateUnitigFactorsN(unitigs, self.mapGeneIdx[gene], self.unitigFactorNodes[gene]) factorGraph.var['zero+source+'].condition(1) factorGraph.var['sink+infty+'].condition(1) graphString = str(factorGraph) stubName = str(uuid.uuid4()) + 'graph_w' graphFileName = self.working_dir + '/' + stubName + '.fg' outFileName = self.working_dir + '/' + stubName + '.out' with open(graphFileName, "w") as text_file: print(graphString, file=text_file) cmd = self.fgExePath + 'runfg_width ' + graphFileName + ' ' + outFileName subprocess.run(cmd, shell=True,check=False) treeWidths[gene] = -1 try: inHandle = open(outFileName, 'r') outLines = inHandle.readlines() inHandle.close() header = outLines[0] matchW = re.search(r'treewidth: (.*) states:.*',header) if matchW is not None: treeWidths[gene] = int(matchW.group(1)) os.remove(graphFileName) os.remove(outFileName) except FileNotFoundError: os.remove(graphFileName) return treeWidths def graphNormMatrix(self, uMap, BNMF, selectV): gGamma = np.zeros((self.G,self.S)) gPhi = np.zeros((self.V,self.G)) for g in range(self.G): xVals = {} Lengths = {} maxFlow = 0. mapSedge = {} for edge in self.cGraph.sEdges: unitigd = edge[1][:-1] v = self.mapIdx[unitigd] if selectV[v]: u = uMap[v] xVals[edge] = BNMF.exp_U[u,g] Lengths[edge] = 1.0 mapSedge[v] = edge else: u = uMap[self.degenSeq[v]] xVals[edge] = BNMF.exp_U[u,g] Lengths[edge] = 1.0 mapSedge[v] = edge self.cGraph.X = xVals self.cGraph.L = Lengths self.cGraph.optimseFlows(self.logger, gaussianNLL_F, gaussianNLL_D, 200) (maxFlow,maxFlows) = nx.maximum_flow(self.cGraph.diGraph, 'source+','sink+', capacity='flow') #maxFlow = max(maxFlow,0.01) #self.logger('%d %f',g,maxFlow) if maxFlow > 1.0e-6: gGamma[g,:] = BNMF.exp_V.T[g,:]*maxFlow for v in range(self.V): if v in mapSedge: vedge = mapSedge[v] fFlow = self.cGraph.diGraph[vedge[0]][vedge[1]]['flow'] gPhi[v,g] = fFlow/maxFlow else: gPhi[v,g] = 0. #else: # gPhi[:,g] = 0. # gGamma[g,:] = 0. return (gGamma, gPhi) def graphNormMatrix2(self, uMap, NMF_VB, selectV): gGamma = np.zeros((self.G,self.S)) gPhi = np.zeros((self.V,self.G)) allPaths = defaultdict(lambda: np.zeros(self.S)) for g in range(self.G): xVals = {} Lengths = {} maxFlow = 0. mapSedge = {} for edge in self.cGraph.sEdges: unitigd = edge[1][:-1] v = self.mapIdx[unitigd] if selectV[v]: u = uMap[v] xVals[edge] = NMF_VB.expPhi[u,g] Lengths[edge] = 1.0 mapSedge[v] = edge else: u = uMap[self.degenSeq[v]] xVals[edge] = NMF_VB.expPhi[u,g] Lengths[edge] = 1.0 mapSedge[v] = edge self.cGraph.X = xVals self.cGraph.L = Lengths self.logger.info("Graph norm for haplo: %d",g) self.cGraph.optimseFlows(self.logger,gaussianNLL_F, gaussianNLL_D, 200) copyGraph = self.cGraph.diGraph.copy() (maxFlow,maxFlows) = nx.maximum_flow(copyGraph, 'source+','sink+', capacity='flow') paths = self.cGraph.decomposeFlows() for path, flow in paths.items(): if flow > 1.0e-9: allPaths[path] += flow*NMF_VB.expGamma[g,:] gGamma[g,:] = NMF_VB.expGamma[g,:]*maxFlow for v in range(self.V): if v in mapSedge: vedge = mapSedge[v] fFlow = copyGraph[vedge[0]][vedge[1]]['flow'] gPhi[v,g] = fFlow/maxFlow else: gPhi[v,g] = 0. return (gGamma, gPhi, allPaths) def graphNormMatrix3(self, uMap, NMF_VB, selectV): gGamma = np.zeros((self.G,self.S)) gPhi = np.zeros((self.V,self.G)) for g in range(self.G): xVals = {} Lengths = {} maxFlow = 0. mapSedge = {} for edge in self.cGraph.sEdges: unitigd = edge[1][:-1] v = self.mapIdx[unitigd] if selectV[v]: u = uMap[v] xVals[edge] = NMF_VB.expPhi[u,g] Lengths[edge] = 1.0 mapSedge[v] = edge else: u = uMap[self.degenSeq[v]] xVals[edge] = NMF_VB.expPhi[u,g] Lengths[edge] = 1.0 mapSedge[v] = edge self.cGraph.X = xVals self.cGraph.L = Lengths self.logger.info("Graph norm for haplo: %d",g) self.cGraph.optimseFlows(self.logger,gaussianNLL_F, gaussianNLL_D, 200) copyGraph = self.cGraph.diGraph.copy() (maxFlow,maxFlows) = nx.maximum_flow(copyGraph, 'source+','sink+', capacity='flow') gGamma[g,:] = NMF_VB.expGamma[g,:]*maxFlow for v in range(self.V): if v in mapSedge: vedge = mapSedge[v] fFlow = copyGraph[vedge[0]][vedge[1]]['flow'] gPhi[v,g] = fFlow/maxFlow else: gPhi[v,g] = 0. return (gGamma, gPhi) # def __init__(self, X, lengths, G = 2, epsilon = 1.0e5, epsilonNoise = 1.0e-3, # alpha=1.0e-9,beta=1.0e-9,alpha0=1.0e-9,beta0=1.0e-9, tauThresh = 0.1, # maxSampleCov = 0., tauType='poisson', ARD = True, BIAS = False, NOISE = False): def initNMFVB(self, mask = None, bMaskDegen = True, bScale = False, bARD = True): if mask is None: mask = np.ones((self.V, self.S)) if bMaskDegen: mask = mask*self.MaskDegen selectV = np.sum(mask,axis=1) > 0 XC = self.X[selectV,:] XCN = self.XN[selectV,:] MC = mask[selectV,:] LC = self.lengths[selectV] no_runs = self.nNmfIters bestGamma = None bestErr = 1.0e10 bestPhi = None uMap = {} u = 0 for v in range(self.V): if selectV[v]: uMap[v] = u u = u+1 n = 0 while n < no_runs: hyperp = { 'alphatau':0.1, 'betatau':0.1, 'alpha0':1.0e-6, 'beta0':1.0e-6, 'lambdaU':1.0e-3, 'lambdaV':1.0e-3} XSum = np.sum(XCN,axis=0) if bScale: XCNDash = (100*XCN)/XSum[np.newaxis,:] BNMF = bnmf_vb(self.prng,self.logger,XCN,MC,self.G, ARD = bARD, hyperparameters=hyperp) self.logger.info("Round: %d of NMF",n) BNMF.initialise(init_UV='random') BNMF.run(1000) self.logger.info("Graph normalise NMF") (gGamma, gPhi) = self.graphNormMatrix(uMap, BNMF, selectV) if bScale: gGamma = (gGamma*XSum[np.newaxis,:])/100. XN_pred = np.dot(gPhi,gGamma) err = (mask * (self.XN - XN_pred)**2).sum() / float(mask.sum()) self.logger.info("Error round %d of NMF: %f",n, err) self.logger.info(str(n) + "," + str(err)) if err < bestErr: bestGamma = gGamma bestPhi = gPhi bestErr = err n += 1 self.logger.info("Best error: %f",bestErr) self.expGamma[0:self.G,:] = bestGamma self.expPhi[:,0:self.G] = bestPhi self.expGamma2 = self.expGamma*self.expGamma self.expPhi2 = self.expPhi*self.expPhi def initFlowGraph(self, mask=None, bMaskDegen = False): if mask is None: maskF = np.ones((self.V)) else: maskF = np.sum(mask,axis=1) maskF[maskF >= 1.] = 1. if bMaskDegen: maskF = maskF*np.any(self.MaskDegen,axis=1) XT = np.sum(self.X,axis=1) #self.maxFlow XN = XT/self.lengths maxN = np.max(XN) XT = XT/maxN self.tgenes = ['gene'] self.tCGraph = {} self.tCGraph['gene'] = self.cRGraph flowGraph = FlowGraphML(self.tCGraph, self.tgenes, self.prng, XT, self.lengths,self.cGeneIdx, maskF,False, 0.) flowGraph.bLasso = False flowGraph.fLambda = 0. flowGraph.optimiseFlows(200,bKLDivergence = False) eLambda = (flowGraph.phi + flowGraph.DELTA) * flowGraph.lengths for v in range(flowGraph.V): print(str(v) + ',' + str(flowGraph.X[v]) + ',' + str(flowGraph.phi[v]) + ',' + str(eLambda[v])) paths = flowGraph.decomposeFlows() minI = 3.0/(maxN*self.readLength) fpaths = {k:v for (k,v) in paths['gene'].items() if v > minI} sF = sorted(fpaths.items(), key=lambda x: -x[1]) nP = min(len(sF),self.G) for g in range(nP): pathU = sF[g][0] for unitigp in pathU: ud = unitigp[:-1] if ud in flowGraph.mapGeneIdx['gene']: vp = flowGraph.mapGeneIdx['gene'][ud] self.expPhi[vp,g] = 1. self.expPhi2[vp,g] = 1. retained = np.ones(self.GDash,dtype=bool) retained[nP:self.G] = False self.filterHaplotypes(retained,20,mask,bMaskDegen) if mask is None: mask = np.ones((self.V, self.S)) if bMaskDegen: mask = mask*self.MaskDegen covNMF = NMF(self.XN,mask,self.G,n_run = 20, prng = self.prng) covNMF.random_initialize() covNMF.W = self.expPhi[:,0:self.G] covNMF.factorizeH() #covNMF.train(1000,no_runs = 1) #covNMF.factorizeG() #covNMF.factorizeP() self.expGamma[0:self.G,:] = np.copy(covNMF.H) self.expGamma2 = self.expGamma*self.expGamma #self.expGamma[0:self.G,:] = np.copy(covNMF.Ga def initNMF(self, mask = None, bMaskDegen = True): #import ipdb; ipdb.set_trace() if mask is None: mask = np.ones((self.V, self.S)) if bMaskDegen: mask = mask*self.MaskDegen selectV = np.sum(mask,axis=1) > 0 XC = self.XN[selectV,:] MC = mask[selectV,:] LC = self.lengths[selectV] covNMF = NMF(XC,MC,self.G,n_run = 20, prng = self.prng) #covNMF = NMF_NNLS(XC,MC,self.G,LC) #covNMF = NMF_NNLS(XC,MC,self.G) covNMF.factorize() covNMF.factorizeH() #covNMF.train(1000,no_runs = 1) #covNMF.factorizeG() #covNMF.factorizeP() self.expGamma[0:self.G,:] = np.copy(covNMF.H) #self.expGamma[0:self.G,:] = np.copy(covNMF.Ga) self.expGamma2 = self.expGamma*self.expGamma covNMF.factorizeW() initEta = np.zeros((self.V,self.G)) u = 0 for v in range(self.V): if selectV[v]: initEta[v,:] = covNMF.W[u,:] u += 1 for v, vmap in self.degenSeq.items(): initEta[v,:] = initEta[vmap,:] for g in range(self.G): treeWidths = {} for gene, factorGraph in self.factorGraphs.items(): unitigs = self.assemblyGraphs[gene].unitigs self.updateUnitigFactorsW(unitigs, self.mapGeneIdx[gene], self.unitigFactorNodes[gene], initEta, g) factorGraph.reset() self.logger.info(gene) factorGraph.var['zero+source+'].condition(1) factorGraph.var['sink+infty+'].condition(1) graphString = str(factorGraph) stubName = str(uuid.uuid4()) + 'graph_'+ str(g) graphFileName = self.working_dir + '/' + stubName + '.fg' outFileName = self.working_dir + '/' + stubName + '.out' with open(graphFileName, "w") as text_file: print(graphString, file=text_file) cmd = self.fgExePath + 'runfg_flex ' + graphFileName + ' ' + outFileName + ' 0 -1' #subprocess.run('./runfg_marg_old ' + graphFileName + ' 0 > ' + outFileName, shell=True,check=True) subprocess.run(cmd, shell=True,check=False) #p = Popen(cmd, stdout=PIPE,shell=True) treeWidths[gene] = -1 try: inHandle = open(outFileName, 'r') outLines = inHandle.readlines() inHandle.close() header = outLines[0] matchW = re.search(r'.*twidth:(.*)',header) if matchW is not None: treeWidths[gene] = int(matchW.group(1)) self.margG[gene][g] = self.parseMargString(factorGraph,outLines) self.updateExpPhi(unitigs,self.mapGeneIdx[gene],self.margG[gene][g],g) os.remove(graphFileName) os.remove(outFileName) except FileNotFoundError: os.remove(graphFileName) if nx.is_directed_acyclic_graph(self.factorDiGraphs[gene]): self.logger.info("Attempt greedy path: " + str(g) + " " + gene) #greedyPath = self.sampleGreedyPath(gene, g) greedyPath = self.sampleMaxWeightPath(gene, g) for unitig in self.assemblyGraphs[gene].unitigs: if unitig in self.mapGeneIdx[gene]: v_idx = self.mapGeneIdx[gene][unitig] self.expPhi[v_idx,g] = 0. self.expPhi2[v_idx,g] = 0. for unitigd in greedyPath: unitig = unitigd[:-1] if unitig in self.mapGeneIdx[gene]: v_idx = self.mapGeneIdx[gene][unitig] self.expPhi[v_idx,g] = 1. self.expPhi2[v_idx,g] = 1. else: self.logger.warning("Cannot attempt greedy path") self.addGamma(g) self.logger.info("-1,"+ str(self.div())) return treeWidths def initNMFGamma(self,assCopyGamma): gamma = np.copy(assCopyGamma.expGamma) covNMF = NMF(self.XN,self.Identity,self.G,n_run = 10, prng = self.prng) covNMF.random_initialize() covNMF.H = np.copy(gamma[0:self.G,:]) covNMF.factorizeW() self.eLambda = np.zeros((self.V,self.S)) initEta = covNMF.W self.epsilon = assCopyGamma.epsilon #parameter for gamma exponential prior self.expGamma = gamma #expectation of gamma self.expGamma2 = np.copy(assCopyGamma.expGamma2) self.muGamma = np.copy(assCopyGamma.muGamma) self.tauGamma = np.copy(assCopyGamma.tauGamma) self.varGamma = np.copy(assCopyGamma.varGamma) for g in range(self.G): for gene, factorGraph in self.factorGraphs.items(): unitigs = self.assemblyGraphs[gene].unitigs self.updateUnitigFactorsW(unitigs, self.mapGeneIdx[gene], self.unitigFactorNodes[gene], initEta, g) factorGraph.reset() factorGraph.var['zero+source+'].condition(1) factorGraph.var['sink+infty+'].condition(1) graphString = str(factorGraph) outFileStub = str(uuid.uuid4()) + 'graph_'+ str(g) graphFileName = self.working_dir + '/' + outFileStub + '.fg' outFileName = self.working_dir + '/' + outFileStub + '.out' with open(graphFileName, "w") as text_file: print(graphString, file=text_file) cmd = self.fgExePath + 'runfg_flex ' + graphFileName + ' ' + outFileName + ' 0 -1' #subprocess.run('./runfg_marg_old ' + graphFileName + ' 0 > ' + outFileName, shell=True,check=True) subprocess.run(cmd, shell=True,check=True) #p = Popen(cmd, stdout=PIPE,shell=True) with open (outFileName, "r") as myfile: outLines=myfile.readlines() self.margG[gene][g] = self.parseMargString(factorGraph,outLines) self.updateExpPhi(unitigs,self.mapGeneIdx[gene],self.margG[gene][g],g) os.remove(graphFileName) os.remove(outFileName) self.addGamma(g) self.logger.info("-1,"+ str(self.div())) def exp_square_lambda(self): ''' Compute: sum_s E_q(phi,gamma) [ sum ( Phi_v Gamma_s )^2 ]. ''' eLambda2Sum = self.eLambda*self.eLambda diagonal = np.dot(self.expPhi*self.expPhi,self.expGamma*self.expGamma) return np.sum(eLambda2Sum - diagonal + np.dot(self.expPhi2,self.expGamma2), axis = 1) def exp_square_lambda_matrix(self): ''' Compute: sum_s E_q(phi,gamma) [ sum ( Phi_v Gamma_s )^2 ]. ''' eLambda2Sum = self.eLambda*self.eLambda diagonal = np.dot(self.expPhi*self.expPhi,self.expGamma*self.expGamma) return eLambda2Sum - diagonal + np.dot(self.expPhi2,self.expGamma2) def gene_mean_diff(self): diff_matrix = self.divF_matrix() gene_vals = defaultdict(list) for gene in self.genes: unitigs = self.mapUnitigs[gene] for unitig in unitigs: v_idx = self.mapGeneIdx[gene][unitig] gene_vals[gene].append(np.mean(diff_matrix[v_idx,:])) gene_means = {} for gene in self.genes: gene_means[gene] = np.mean(np.array(gene_vals[gene])) return gene_means def gene_MSE(self): ''' Predict missing values in R. ''' R_pred = self.lengths[:,np.newaxis]*np.dot(self.expPhi, self.expGamma) if self.BIAS: R_pred = R_pred*self.expTheta[:,np.newaxis] diff_matrix = (self.X - R_pred)**2 gene_vals = defaultdict(list) for gene in self.genes: unitigs = self.mapUnitigs[gene] for unitig in unitigs: v_idx = self.mapGeneIdx[gene][unitig] gene_vals[gene].extend(diff_matrix[v_idx,:].tolist()) gene_means = {} for gene in self.genes: gene_means[gene] = np.mean(np.array(gene_vals[gene])) return gene_means def mean_diff(self): diff_matrix = self.divF_matrix() return np.sum(diff_matrix)/self.V*self.S def gene_mean_elbo(self): gene_means = {} for gene in self.genes: unitigs = self.mapUnitigs[gene] gene_elbo = self.calc_unitig_elbo(gene, unitigs) gene_mean_elbo = gene_elbo/len(unitigs) gene_means[gene] = gene_mean_elbo return gene_means def gene_mean_deviance(self): deviance_matrix = self.calc_expdeviance_matrix() gene_means = {} for gene in self.genes: unitigs = self.mapUnitigs[gene] mean_dev = 0. for unitig in unitigs: v_idx = self.mapGeneIdx[gene][unitig] mean_dev += np.mean(deviance_matrix[v_idx,:]) gene_means[gene] = mean_dev/len(unitigs) return gene_means def gene_mean_poisson(self, mask = None, bMaskDegen = False, bNoise = True): if mask is None: mask = np.ones((self.V,self.S)) if bMaskDegen: mask = mask*self.MaskDegen # import ipdb; ipdb.set_trace() poissonWeight = 1.0/(self.X + 0.5) sd_matrix = self.exp_square_diff_matrix(bNoise = bNoise) gene_means = {} for gene in self.genes: unitigs = self.mapUnitigs[gene] mean_dev = 0. v_ids = [] for unitig in unitigs: v_idx = self.mapGeneIdx[gene][unitig] v_ids.append(v_idx) maskU = mask[v_ids,] weightU = poissonWeight[v_ids,] Omega = np.sum(maskU) total_elbo = 0.5*(np.sum(weightU*maskU) - Omega*math.log(2*math.pi)) total_elbo -= 0.5*np.sum(maskU*weightU*sd_matrix[v_ids,]) gene_means[gene] = -total_elbo/Omega return gene_means def exp_square_diff_matrix_unitigs(self,unitig_idxs): ''' Compute: sum_Omega E_q(phi,gamma) [ ( Xvs - L_v Phi_v Gamma_s )^2 ]. ''' #return (self.M *( ( self.R - numpy.dot(self.exp_U,self.exp_V.T) )**2 + \ # ( numpy.dot(self.var_U+self.exp_U**2, (self.var_V+self.exp_V**2).T) - numpy.dot(self.exp_U**2,(self.exp_V**2).T) ) ) ).sum() if self.BIAS: R = self.X[unitig_idxs,:] - self.lengths[unitig_idxs,np.newaxis]*self.expTheta[unitig_idxs,np.newaxis]*self.eLambda[unitig_idxs,:] else: R = self.X[unitig_idxs,:] - self.lengths[unitig_idxs,np.newaxis]*self.eLambda[unitig_idxs,:] t1 = np.dot(self.expPhi[unitig_idxs,:]*self.expPhi[unitig_idxs,:], self.expGamma*self.expGamma) if self.BIAS: eT2 = self.expTheta[unitig_idxs]*self.expTheta[unitig_idxs] t1 = eT2[:,np.newaxis]*t1 diff = np.dot(self.expPhi2[unitig_idxs,:],self.expGamma2) - t1 L2 = self.lengths[unitig_idxs]*self.lengths[unitig_idxs] if self.BIAS: diff = np.dot(self.expPhi2[unitig_idxs,:],self.expGamma2)*self.expTheta2[unitig_idxs,np.newaxis] - t1 else: diff = np.dot(self.expPhi2[unitig_idxs,:],self.expGamma2) - t1 diff2 = L2[:,np.newaxis]*diff return R*R + diff2 def exp_square_diff_matrix(self, bNoise = True): ''' Compute: sum_Omega E_q(phi,gamma) [ ( Xvs - L_v Phi_v Gamma_s )^2 ]. ''' #return (self.M *( ( self.R - numpy.dot(self.exp_U,self.exp_V.T) )**2 + \ # ( numpy.dot(self.var_U+self.exp_U**2, (self.var_V+self.exp_V**2).T) - numpy.dot(self.exp_U**2,(self.exp_V**2).T) ) ) ).sum() if bNoise: tPhi = self.expPhi tGamma = self.expGamma tPhi2 = self.expPhi2 tGamma2 = self.expGamma2 else: tPhi = self.expPhi[:,0:self.G] tPhi2 = self.expPhi2[:,0:self.G] tGamma = self.expGamma[0:self.G,:] tGamma2 = self.expGamma2[0:self.G,:] tLambda = np.dot(tPhi, tGamma) if self.BIAS: R = self.X - self.lengths[:,np.newaxis]*self.expTheta[:,np.newaxis]*tLambda else: R = self.X - self.lengths[:,np.newaxis]*tLambda t1 = np.dot(tPhi*tPhi, tGamma*tGamma) if self.BIAS: eT2 = self.expTheta*self.expTheta t1 = eT2[:,np.newaxis]*t1 diff = np.dot(tPhi2,tGamma2) - t1 L2 = self.lengths*self.lengths if self.BIAS: diff = np.dot(tPhi2,tGamma2)*self.expTheta2[:,np.newaxis] - t1 else: diff = np.dot(tPhi2,tGamma2) - t1 diff2 = L2[:,np.newaxis]*diff return R*R + diff2 def exp_square_diff(self): ''' Compute: sum_Omega E_q(phi,gamma) [ ( Xvs - L_v Phi_v Gamma_s )^2 ]. ''' #return (self.M *( ( self.R - numpy.dot(self.exp_U,self.exp_V.T) )**2 + \ # ( numpy.dot(self.var_U+self.exp_U**2, (self.var_V+self.exp_V**2).T) - numpy.dot(self.exp_U**2,(self.exp_V**2).T) ) ) ).sum() if self.BIAS: R = self.X - self.lengths[:,np.newaxis]*self.expTheta[:,np.newaxis]*self.eLambda else: R = self.X - self.lengths[:,np.newaxis]*self.eLambda t1 = np.dot(self.expPhi*self.expPhi, self.expGamma*self.expGamma) if self.BIAS: eT2 = self.expTheta*self.expTheta t1 = eT2[:,np.newaxis]*t1 if self.BIAS: diff = np.dot(self.expPhi2,self.expGamma2)*self.expTheta2[:,np.newaxis] - t1 else: diff = np.dot(self.expPhi2,self.expGamma2) - t1 L2 = self.lengths*self.lengths diff2 = L2[:,np.newaxis]*diff return np.sum(R*R + diff2) def calc_strain_drop_elbo(self): self.eLambda = np.dot(self.expPhi, self.expGamma) current_gene_elbos = {} for gene in self.genes: current_gene_elbo = self.calc_unitig_elbo(gene, self.mapUnitigs[gene]) current_gene_elbos[gene] = current_gene_elbo self.logger.info(gene + "," + str(current_gene_elbo) + "," + str(current_gene_elbo/float(len(self.mapUnitigs[gene])))) diff_elbo = defaultdict(list) for g in range(self.G): self.removeGamma(g) for gene in self.genes: new_gene_elbo = self.calc_unitig_elbo(gene, self.mapUnitigs[gene]) diff_elbof = (new_gene_elbo - current_gene_elbos[gene])/float(len(self.mapUnitigs[gene])) if diff_elbof < 0: diff_elbo[gene].append(False) else: diff_elbo[gene].append(True) self.logger.info(gene + "," + str(g) + "," + str(diff_elbof)) self.addGamma(g) return diff_elbo def drop_gene_strains(self, gene, g): unitig_drops = [self.mapGeneIdx[gene][x] for x in self.mapUnitigs[gene]] self.expPhi[unitig_drops,g] = 0. self.expPhi2[unitig_drops,g] = 0. def calc_unitig_elbo(self, gene, unitigs): ''' Compute the ELBO of a subset of unitigs. ''' unitig_idxs = [self.mapGeneIdx[gene][x] for x in unitigs] nU = len(unitig_idxs) total_elbo = 0.0 # Log likelihood total_elbo += 0.5*(np.sum(self.expLogTau[unitig_idxs,:]) - nU*self.S*math.log(2*math.pi)) #first part likelihood total_elbo -= 0.5*np.sum(self.expTau[unitig_idxs,:]*self.exp_square_diff_matrix_unitigs(unitig_idxs)) #second part likelihood #Prior theta if using bias if self.BIAS: dS = np.sqrt(self.tauTheta0/2.0)*self.muTheta0 thetaConst = 0.5*np.log(self.tauTheta0/(2.0*np.pi)) -0.5*self.tauTheta0*self.muTheta0*self.muTheta0 - np.log(0.5*(1 + erf(dS))) lnThetaPrior = nU*thetaConst lnThetaPrior += np.sum(-0.5*self.tauTheta0*(self.expTheta2[unitig_idxs] - 2.0*self.expTheta[unitig_idxs]*self.muTheta0)) total_elbo += lnThetaPrior #add phio prior assuming uniform total_elbo += self.G*np.sum(self.logPhiPrior[unitig_idxs]) #add tau prior total_elbo += nU*self.S*(self.alpha * math.log(self.beta) - sps.gammaln(self.alpha)) total_elbo += np.sum((self.alpha - 1.)*self.expLogTau[unitig_idxs,:] - self.beta*self.expTau[unitig_idxs,:]) if self.BIAS: qTheta = -0.5*np.log(self.tauTheta[unitig_idxs]).sum() + 0.5*nU*math.log(2.*math.pi) qTheta += np.log(0.5*sps.erfc(-self.muTheta[unitig_idxs]*np.sqrt(self.tauTheta[unitig_idxs])/math.sqrt(2.))).sum() qTheta += (0.5*self.tauTheta[unitig_idxs] * (self.varTheta[unitig_idxs] + (self.expTheta[unitig_idxs] - self.muTheta[unitig_idxs])**2 ) ).sum() total_elbo += qTheta # q for tau dTemp1 = np.sum((self.alpha + 0.5)*np.log(self.betaTau[unitig_idxs,:]) + sps.gammaln(self.alpha + 0.5)) dTemp2 = np.sum((self.alpha - 0.5)*self.expLogTau[unitig_idxs,:] + self.betaTau[unitig_idxs,:]*self.expTau[unitig_idxs,:]) total_elbo += - dTemp1 total_elbo += - dTemp2 # q for phi total_elbo += np.sum(self.HPhi[unitig_idxs]) return total_elbo def calc_expdeviance_matrix(self): # Log likelihood deviance_matrix = 0.5*self.expTau*self.exp_square_diff_matrix() deviance_matrix -= 0.5*self.expLogTau return deviance_matrix def calc_expll(self, mask = None, bMaskDegen = False): if mask is None: mask = np.ones((self.V,self.S)) if bMaskDegen: mask = mask*self.MaskDegen total_elbo = 0. # Log likelihood nTOmega = np.sum(mask) total_elbo += 0.5*(np.sum(self.expLogTau*mask) - nTOmega*math.log(2*math.pi)) #first part likelihood total_elbo -= 0.5*np.sum(mask*self.expTau*self.exp_square_diff_matrix()) #second part likelihood return total_elbo def calc_expll_poisson(self, mask = None, bMaskDegen = False, bNoise = True): if mask is None: mask = np.ones((self.V,self.S)) if bMaskDegen: mask = mask*self.MaskDegen total_elbo = 0. # Log likelihood nTOmega = np.sum(mask) poissonWeight = 1.0/(self.X + 0.5) total_elbo += 0.5*(np.sum(poissonWeight*mask) - nTOmega*math.log(2*math.pi)) #first part likelihood total_elbo -= 0.5*np.sum(mask*poissonWeight*self.exp_square_diff_matrix(bNoise = bNoise)) #second part likelihood return total_elbo def calc_expll_poisson_maximal(self, mask = None, bMaskDegen = False): if mask is None: mask = np.ones((self.V,self.S)) if bMaskDegen: mask = mask*self.MaskDegen total_elbo = 0. # Log likelihood nTOmega = np.sum(mask) poissonWeight = 1.0/(self.X + 0.5) self.getMaximalUnitigs('Dummy', drop_strain=None,relax_path=False,writeSeq=False) pPhi = np.zeros((self.V,self.G)) for gene, mapGene in self.mapGeneIdx.items(): for g in range(self.G): for node in self.paths[gene][g]: v_idx = mapGene[node[:-1]] pPhi[v_idx,g] = 1. R_pred = self.lengths[:,np.newaxis]*np.dot(pPhi, self.expGamma[0:self.G,:]) if self.BIAS: R_pred = R_pred*self.expTheta[:,np.newaxis] total_elbo += 0.5*(np.sum(poissonWeight*mask) - nTOmega*math.log(2*math.pi)) #first part likelihood diff_matrix = (self.X - R_pred)**2 total_elbo -= 0.5*np.sum(mask*poissonWeight*diff_matrix) #second part likelihood return total_elbo def calc_expll_poisson2(self, mask = None, bMaskDegen = False): if mask is None: mask = np.ones((self.V,self.S)) if bMaskDegen: mask = mask*self.MaskDegen R_pred = self.lengths[:,np.newaxis]*np.dot(self.expPhi[:,0:self.G], self.expGamma[0:self.G,:]) if self.BIAS: R_pred = R_pred*self.expTheta[:,np.newaxis] R2 = (self.X - R_pred)**2 total_elbo = 0. # Log likelihood nTOmega = np.sum(mask) poissonWeight = 1.0/(self.X + 0.5) total_elbo += 0.5*(np.sum(poissonWeight*mask) - nTOmega*math.log(2*math.pi)) #first part likelihood total_elbo -= 0.5*np.sum(mask*poissonWeight*R2) #second part likelihood return total_elbo def calc_elbo(self, mask = None, bMaskDegen = False): if mask is None: mask = np.ones((self.V,self.S)) if bMaskDegen: mask = mask*self.MaskDegen ''' Compute the ELBO. ''' total_elbo = 0. # Log likelihood nTOmega = np.sum(mask) total_elbo += 0.5*(np.sum(self.expLogTau*mask) - nTOmega*math.log(2*math.pi)) #first part likelihood total_elbo -= 0.5*np.sum(mask*self.expTau*self.exp_square_diff_matrix()) #second part likelihood if self.NOISE: if self.ARD: total_elbo += self.alpha0 * math.log(self.beta0) - sp.special.gammaln(self.alpha0) \ + (self.alpha0 - 1.)*self.exp_loglambdak.sum() - self.beta0 * self.exp_lambdak.sum() total_elbo += self.S * np.log(self.exp_lambdak).sum() - (self.exp_lambdak[:,np.newaxis] * self.expGamma[0:self.G]).sum() else: total_elbo += np.sum(-math.log(self.epsilon) - self.expGamma[0:self.G]/self.epsilon) total_elbo += np.sum(-math.log(self.epsilonNoise) - self.expGamma[self.G]/self.epsilonNoise) else: # Prior lambdak, if using ARD, and prior U, V if self.ARD: total_elbo += self.alpha0 * math.log(self.beta0) - sp.special.gammaln(self.alpha0) \ + (self.alpha0 - 1.)*self.exp_loglambdak.sum() - self.beta0 * self.exp_lambdak.sum() total_elbo += self.S * np.log(self.exp_lambdak).sum() - (self.exp_lambdak[:,np.newaxis] * self.expGamma).sum() else: total_elbo += np.sum(-math.log(self.epsilon) - self.expGamma/self.epsilon) #Prior theta if using bias if self.BIAS: dS = np.sqrt(self.tauTheta0/2.0)*self.muTheta0 thetaConst = 0.5*np.log(self.tauTheta0/(2.0*np.pi)) -0.5*self.tauTheta0*self.muTheta0*self.muTheta0 - np.log(0.5*(1 + erf(dS))) lnThetaPrior = self.V*thetaConst #thetaMoment1 = np.array(TN_vector_expectation(self.expTheta,self.tauTheta)) #thetaVar = np.array(TN_vector_variance(self.expTheta,self.tauTheta)) #thetaMoment2 = thetaVar + 2.0*self.expTheta*thetaMoment1 - self.expTheta*self.expTheta lnThetaPrior += np.sum(-0.5*self.tauTheta0*(self.expTheta2 - 2.0*self.expTheta*self.muTheta0)) total_elbo += lnThetaPrior #add phio prior assuming uniform total_elbo += self.G*np.sum(self.logPhiPrior) #add tau prior if self.bFixedTau: total_elbo += nTOmega*(self.alpha * math.log(self.beta) - sps.gammaln(self.alpha)) total_elbo += np.sum((self.alpha - 1.)*self.expLogTau*mask - self.beta*self.expTau*mask) # q for lambdak, if using ARD if self.ARD: total_elbo += - sum([v1*math.log(v2) for v1,v2 in zip(self.alphak_s,self.betak_s)]) + sum([sp.special.gammaln(v) for v in self.alphak_s]) \ - ((self.alphak_s - 1.)*self.exp_loglambdak).sum() + (self.betak_s * self.exp_lambdak).sum() #add q for gamma qGamma = -0.5*np.log(self.tauGamma).sum() + 0.5*self.GDash*self.S*math.log(2.*math.pi) temp = sps.erfc(-self.muGamma*np.sqrt(self.tauGamma)/math.sqrt(2.)) temp[temp < AssemblyPathSVA.minLogQGamma] = AssemblyPathSVA.minLogQGamma qGamma += np.log(0.5*temp).sum() qGamma += (0.5*self.tauGamma * ( self.varGamma + (self.expGamma - self.muGamma)**2 ) ).sum() total_elbo += qGamma if self.BIAS: qTheta = -0.5*np.log(self.tauTheta).sum() + 0.5*self.V*math.log(2.*math.pi) qTheta += np.log(0.5*sps.erfc(-self.muTheta*np.sqrt(self.tauTheta)/math.sqrt(2.))).sum() qTheta += (0.5*self.tauTheta * ( self.varTheta + (self.expTheta - self.muTheta)**2 ) ).sum() total_elbo += qTheta # q for tau if self.bFixedTau: dTemp1 = (self.alpha + 0.5)*np.sum(np.log(self.betaTau)*mask) - nTOmega*sps.gammaln(self.alpha + 0.5) dTemp2 = np.sum((self.alpha - 0.5)*self.expLogTau*mask) + np.sum(self.betaTau*self.expTau*mask) total_elbo += - dTemp1 total_elbo += - dTemp2 # q for phi total_elbo += np.sum(self.HPhi) return total_elbo def predict(self, M_pred, bMaskDegen = False): ''' Predict missing values in R. ''' R_pred = self.lengths[:,np.newaxis]*np.dot(self.expPhi, self.expGamma) if self.BIAS: R_pred = R_pred*self.expTheta[:,np.newaxis] if bMaskDegen: M_pred = M_pred*self.MaskDegen MSE = self.compute_MSE(M_pred, self.X, R_pred) #R2 = self.compute_R2(M_pred, self.R, R_pred) #Rp = self.compute_Rp(M_pred, self.R, R_pred) return MSE def predict_sqrt(self, M_pred, bMaskDegen = False): ''' Predict missing values in R. ''' R_pred = self.lengths[:,np.newaxis]*np.dot(self.expPhi, self.expGamma) if self.BIAS: R_pred = R_pred*self.expTheta[:,np.newaxis] if bMaskDegen: M_pred = M_pred*self.MaskDegen MSE = self.compute_MSE(M_pred, np.sqrt(self.X), np.sqrt(R_pred)) #R2 = self.compute_R2(M_pred, self.R, R_pred) #Rp = self.compute_Rp(M_pred, self.R, R_pred) return MSE def predictMaximal(self, M_pred, bMaskDegen = False): ''' Predict missing values in R. ''' self.getMaximalUnitigs('Dummy', drop_strain=None,relax_path=False,writeSeq=False) pPhi = np.zeros((self.V,self.GDash)) for gene, mapGene in self.mapGeneIdx.items(): for g in range(self.G): for node in self.paths[gene][g]: v_idx = mapGene[node[:-1]] pPhi[v_idx,g] = 1. if self.NOISE: pPhi[:,self.G] = 1.0 R_pred = self.lengths[:,np.newaxis]*np.dot(pPhi, self.expGamma) if self.BIAS: R_pred = R_pred*self.expTheta[:,np.newaxis] if bMaskDegen: M_pred = M_pred*self.MaskDegen MSE = self.compute_MSE(M_pred, self.X, R_pred) #R2 = self.compute_R2(M_pred, self.R, R_pred) #Rp = self.compute_Rp(M_pred, self.R, R_pred) return MSE def meanMargMaximal(self): ''' Predict missing values in R. ''' self.getMaximalUnitigs('Dummy', drop_strain=None,relax_path=False,writeSeq=False) meanMargMaximal = np.zeros(self.G) countMargMaximal = np.zeros(self.G) for gene, mapGene in self.mapGeneIdx.items(): for g in range(self.G): for node in self.paths[gene][g]: v_idx = mapGene[node[:-1]] meanMargMaximal[g] += (1.0 - self.expPhi[v_idx,g]) countMargMaximal[g] += 1 return meanMargMaximal/countMargMaximal ''' Functions for computing MSE, R^2 (coefficient of determination), Rp (Pearson correlation) ''' def compute_MSE(self,M,R,R_pred): ''' Return the MSE of predictions in R_pred, expected values in R, for the entries in M. ''' return (M * (R-R_pred)**2).sum() / float(M.sum()) def calcPathDist(self, relax_path): dist = np.zeros((self.G,self.G)) self.MAPs = defaultdict(list) pathsg = defaultdict(dict) for g in range(self.G): for gene, factorGraph in self.factorGraphs.items(): unitigs = self.assemblyGraphs[gene].unitigs self.updateUnitigFactorsMarg(unitigs, self.mapGeneIdx[gene], self.unitigFactorNodes[gene], self.margG[gene][g]) factorGraph.reset() if not relax_path: factorGraph.var['zero+source+'].condition(1) factorGraph.var['sink+infty+'].condition(1) else: factorGraph.var['zero+source+'].clear_condition() factorGraph.var['sink+infty+'].clear_condition() maximals = self.runFGMaximal(factorGraph, g) self.MAPs[gene].append(maximals) biGraph = self.factorDiGraphs[gene] if maximals is not None: pathG = self.convertMAPToPath(self.MAPs[gene][g],biGraph) pathG.pop(0) pathsg[g][gene] = pathG else: pathsg[g][gene] = None for g in range(self.G): for h in range(g+1,self.G): diff = 0 comp = 0 for gene in self.genes: if pathsg[g][gene] is not None and pathsg[h][gene] is not None: if len(set(pathsg[g][gene])) > 0 and len(set(pathsg[h][gene])) > 0: comp += 1 diff += len(set(pathsg[g][gene]) ^ set(pathsg[h][gene])) dist[g,h] = diff dist[h,g] = diff return dist def filterHaplotypes(self,retained,gammaIter,mask=None,bMaskDegen=False): nNewG = np.sum(retained[0:self.G]) if nNewG < self.G: self.logger.info("New strain number " + str(nNewG)) oldG = self.G if self.NOISE: self.G = nNewG self.GDash = self.G + 1 else: self.G = nNewG self.GDash = self.G newPhi = self.expPhi[:,retained] newPhi2 = self.expPhi2[:,retained] newPhiH = self.HPhi[:,retained] newExpGamma = self.expGamma[retained,:] newExpGamma2 = self.expGamma2[retained,:] newMuGamma = self.muGamma[retained,:] newTauGamma = self.tauGamma[retained,:] newVarGamma = self.varGamma[retained,:] self.expPhi = newPhi self.expPhi2 = newPhi2 self.HPhi = newPhiH self.expGamma = newExpGamma self.expGamma2 = newExpGamma2 self.muGamma = newMuGamma self.tauGamma = newTauGamma self.varGamma = newVarGamma if self.ARD: self.alphak_s = self.alphak_s[retained[0:oldG]] self.betak_s = self.betak_s[retained[0:oldG]] self.exp_lambdak = self.exp_lambdak[retained[0:oldG]] self.exp_loglambdak = self.exp_loglambdak[retained[0:oldG]] iter = 0 while iter < gammaIter: if self.ARD: for g in range(self.G): self.update_lambdak(g) self.update_exp_lambdak(g) for g in range(self.GDash): self.updateGamma(g, mask, bMaskDegen) self.eLambda = np.zeros((self.V,self.S)) for g in range(self.GDash): self.addGamma(g) self.updateTau() iter += 1 self.margG = dict() for gene in self.genes: self.margG[gene] = [dict() for x in range(self.G)] ''' Filters on uncertainty''' def filterUncertain(self, maxUncertainty,relax_path,gammaIter=10): self.getMaximalUnitigs("Temp",drop_strain=None, relax_path=relax_path, writeSeq = False) mean_div = self.getPathDivergence(100,drop_strain=None,relax_path=relax_path) removed = np.zeros(self.GDash,dtype=bool) removed[0:self.G] = mean_div > maxUncertainty retained = np.logical_not(removed) if self.NOISE: retained[self.G] = True self.filterHaplotypes(retained,gammaIter) ''' Removes strain below a given total intensity and degenerate''' def removeRedundant(self, minIntensity, gammaIter, relax_path, uncertainFactor=None, mask = None, bMaskDegen = False): if uncertainFactor is not None: self.getMaximalUnitigs("Temp",drop_strain=None, relax_path=relax_path,writeSeq=False) #mean_div = self.getPathDivergence(100,drop_strain=None,relax_path=relax_path) mean_div = self.meanMargMaximal() #calculate number of good strains nNewG = 0 nOldG = self.G sumIntensity = np.sum(self.expGamma,axis=1) if uncertainFactor is not None: dTemp = min(1.0,np.exp(-uncertainFactor*np.max(mean_div))) sumIntensity[np.argmax(mean_div)] *= dTemp dist = self.calcPathDist(relax_path) #first collapse degenerate clusters clusters = defaultdict(list) gSorted = np.argsort(-sumIntensity[0:self.G]) for g in gSorted.tolist(): found = False hclust = -1 for clust, members in clusters.items(): if dist[g][clust] == 0: found=True hclust = clust break if not found: clusters[g].append(g) else: clusters[hclust].append(g) nClusts = len(list(clusters.keys())) removed = np.zeros(self.GDash,dtype=bool) removedClust = defaultdict(lambda: False) if nClusts < self.G: newGamma =
np.copy(self.expGamma)
numpy.copy
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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. # python3 """NeuTra implementation.""" # pylint: disable=invalid-name,missing-docstring import time from typing import Any, Text, Tuple, NamedTuple from absl import logging import gin import numpy as np import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from hmc_swindles import targets from hmc_swindles import utils from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import # pylint: disable=g-import-not-at-top USE_LOCAL_FUN_MC = True if USE_LOCAL_FUN_MC: from fun_mc import using_tensorflow as fun_mc # pylint: disable=reimported tfd = tfp.distributions tfb = tfp.bijectors tfkl = tf.keras.layers @gin.configurable("head_tail_bijector") def MakeHeadTailBijectorFn(num_dims, head_layers=(), activation=tf.nn.elu, train=False, head_dims=3): """A RealNVP for stochastic volatility model.""" # pylint: disable=no-value-for-parameter del train tail_dims = num_dims - head_dims @utils.MakeTFTemplate def head_bijector_fn(x): x.set_shape(list(x.shape)[:-1] + [head_dims]) input_shape = x.shape for i, units in enumerate(head_layers): x = utils.MaskedDense( inputs=x, units=units, num_blocks=head_dims, exclusive=True if i == 0 else False, kernel_initializer=utils.L2HMCInitializer(factor=0.01), activation=activation, ) x = utils.MaskedDense( inputs=x, units=2 * head_dims, num_blocks=head_dims, activation=None, kernel_initializer=utils.L2HMCInitializer(factor=0.01), ) x = tf.reshape(x, shape=tf.concat([input_shape, [2]], axis=0)) shift, log_scale = tf.unstack(x, num=2, axis=-1) return tfb.Chain([tfb.Shift(shift=shift), tfb.Scale(log_scale=log_scale)]) @utils.MakeTFTemplate def head_to_tail_bijector_fn(x, _): for units in head_layers: x = tfkl.Dense( units=units, activation=activation, kernel_initializer=utils.L2HMCInitializer(factor=0.01), )(x,) shift = tfkl.Dense( units=1, activation=None, kernel_initializer=utils.L2HMCInitializer(factor=0.01), )(x,) return tfb.Chain( [tfb.Shift(shift=shift), tfb.Scale(log_scale=tf.Variable(0.))]) @utils.MakeTFTemplate def tail_to_head_bijector_fn(x, _): x = tf.reduce_mean(x, axis=-1, keepdims=True) for units in head_layers: x = tfkl.Dense(units=units, activation=activation)(x) shift = tfkl.Dense(units=head_dims, activation=None)(x) return tfb.Chain( [tfb.Shift(shift=shift), tfb.Scale(log_scale=tf.Variable(tf.zeros(head_dims)))]) b = tfb.Identity() b = tfb.Blockwise( [ tfb.Invert( tfb.MaskedAutoregressiveFlow( bijector_fn=head_bijector_fn("head"))), tfb.Identity(), ], [head_dims, tail_dims], )(b,) b = tfb.RealNVP( num_masked=head_dims, bijector_fn=head_to_tail_bijector_fn("head_to_tail"))( b) b = tfb.Permute(list(reversed(range(num_dims))))(b) b = tfb.RealNVP( num_masked=tail_dims, bijector_fn=tail_to_head_bijector_fn("tail_to_head"))( b) b = tfb.Permute(list(reversed(range(num_dims))))(b) b = tfb.Blockwise( [ tfb.Identity(), tfb.Shift(shift=tf.Variable(tf.zeros([tail_dims]))) ], [head_dims, tail_dims], )(b,) # Construct the variables _ = b.forward(tf.zeros([1, num_dims])) return b @gin.configurable("affine_bijector") def MakeAffineBijectorFn(num_dims, train=False, use_tril=False): mu = tf.Variable(tf.zeros([num_dims]), name="mean", trainable=train) if use_tril: tril_flat = tf.Variable( tf.zeros([num_dims * (num_dims + 1) // 2]), name="tril_flat", trainable=train) tril_raw = tfp.math.fill_triangular(tril_flat) sigma = tf.nn.softplus(tf.linalg.diag_part(tril_raw)) tril = tf.linalg.set_diag(tril_raw, sigma) return tfb.Shift(shift=mu)(tfb.ScaleMatvecTriL(scale_tril=tril)) else: sigma = tf.nn.softplus( tf.Variable(tf.zeros([num_dims]), name="invpsigma", trainable=train)) return tfb.Shift(shift=mu)(tfb.ScaleMatvecDiag(scale_diag=sigma)) @gin.configurable("rnvp_bijector") def MakeRNVPBijectorFn(num_dims, num_stages, hidden_layers, scale=1.0, activation=tf.nn.elu, train=False, learn_scale=False, dropout_rate=0.0): swap = tfb.Permute(permutation=
np.arange(num_dims - 1, -1, -1)
numpy.arange
import csv import importlib import sys sys.path.append('..') import os import json import argparse import copy from enum import IntEnum from datetime import datetime import numpy as np import scipy.integrate as solve import scipy.optimize as opt import matplotlib.pylab as plt from scripts.tsv import parse as parse_tsv from scripts.R0_estimator import get_Re_guess # ------------------------------------------------------------------------ # Indexing enums compartments = ['S', 'E1', 'E2', 'E3', 'I', 'H', 'C', 'D', 'R', 'T', 'NUM'] Sub = IntEnum('Sub', compartments, start=0) groups = ['_0', '_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', 'NUM'] Age = IntEnum('Age', groups , start=0) # ------------------------------------------------------------------------ # Default parameters DefaultRates = {"latency":1/3.0, "logR0":1.0, "infection":1/3.0, "hospital":1/7.0, "critical":1/14, "imports":.1, "efficacy":0.5} RateFields = list(DefaultRates.keys()) # ------------------------------------------------------------------------ # Organizational classes class Data(object): def __str__(self): return str({k : str(v) for k, v in self.__dict__.items()}) class TimeRange(Data): def __init__(self, day0, start, end, delta=1): self.day0 = day0 self.start = start self.end = end self.delta = delta class Params(Data): """ Parameters needed to run the model. Initialized to default values. No default value for logR0 as if it is not set the self.infectivity function doesn't give proper values. """ def __init__(self, logR0, ages=None, size=None, containment_start=None, times=None, logInitial=None, seroprevalence=0): self.ages = ages self.size = size self.time = times self.containment_start = containment_start self.seroprevalence = seroprevalence # Rates self.latency = DefaultRates["latency"] self.logR0 = logR0 self.infection = DefaultRates["infection"] self.beta = np.exp(self.logR0) * self.infection self.hospital = DefaultRates["hospital"] self.critical = DefaultRates["critical"] self.imports = DefaultRates["imports"] self.efficacy = DefaultRates["efficacy"] # Fracs self.confirmed = np.array([5, 5, 10, 15, 20, 20, 25, 30, 40]) / 100 self.severe = np.array([1, 3, 3, 3, 6, 10, 25, 35, 50]) / 100 self.severe *= self.confirmed self.palliative = np.array([0, 0, 0, 0, 0, 0, 5, 10, 20]) / 100 self.icu = np.array([5, 10, 10, 15, 20, 25, 30, 25, 15]) / 100 self.fatality = np.array([10, 10, 10, 10, 10, 20, 30, 40, 50]) / 100 self.recovery = 1 - self.severe self.discharge = 1 - self.icu self.stabilize = 1 - self.fatality self.reported = 1/30 self.logInitial = logInitial or 1 # Make infection function self.infectivity = lambda t,containment_start,eff,beta : beta if t<containment_start else beta*(1-eff) # ------------------------------------------------------------------------ # Functions def get_IFR(age_distribution): params = Params(0) ifr_by_age = params.severe*(params.palliative + params.icu*params.fatality) return np.sum(age_distribution*ifr_by_age) def get_reporting_fraction(cases, deaths, IFR, right_censoring=30, n_days=60): left_index = max(0,len(cases) - right_censoring - n_days) right_index = max(0,len(cases) - right_censoring) n_cases = cases[right_index] - cases[left_index] n_deaths = deaths[right_index] - deaths[left_index] if n_deaths: reported = IFR*n_cases/n_deaths if np.isfinite(reported): return reported return 0.3 # ------------------------------------------ # Modeling def make_evolve(params): # Equations for coupled ODEs def evolve(t, pop): pop2d = np.reshape(pop, (Sub.NUM, Age.NUM)) fracI = pop2d[Sub.I, :].sum() / params.size dpop =
np.zeros_like(pop2d)
numpy.zeros_like
import numpy as np from screws.freeze.main import FrozenOnly from screws.quadrature import Quadrature from objects.CSCG._3d.mesh.domain.regions.region.interpolations.allocator import InterpolationAllocator from objects.CSCG._3d.mesh.domain.regions.region.side_geometries.allocator import SideGeometryAllocator from objects.CSCG._3d.mesh.domain.regions.region.types_wrt_metric.allocator import TypeWr2MetricAllocator from objects.CSCG._3d.mesh.domain.regions.region.sides.main import Sides from objects.CSCG._3d.mesh.domain.regions.region.sub_geometry.main import RegionSubGeometry from objects.CSCG._3d.mesh.domain.regions.region.inheriting.topology import RegionTopology from objects.CSCG._3d.mesh.domain.regions.region.IS import _3dCSCG_Region_IS class Region(RegionTopology, FrozenOnly): def __init__(self, ndim, name, cc, st, interpolator, domain_input): """ Parameters ---------- ndim : int Must be 3. name : cc : corner coordinates st : side type interpolator : domain_input : The DomainInput, but its classname is not 'DomainInput'. It inherits the class `DomainInput` but has personal name. """ assert ndim == 3, " < Region> " self._ndim_ = ndim self._name_ = name self._volume_ = None self._domain_input_ = domain_input # can not remove this line self.___PRIVATE_set_corner_coordinates___(cc) self.___PRIVATE_set_side_types___(st) self.___PRIVATE_parse_side_types___() self._type_wrt_metric_ = self.___PRIVATE_PARSE_type_wrt_metric___() self._interpolation_ = InterpolationAllocator(interpolator)(self) self.___is_orthogonal___ = None self._sides_ = Sides(self) self._sub_geometry_ = RegionSubGeometry(self) self._IS_ = None self._MAP_ = None self._freeze_self_() @property def map(self): return self._MAP_ @property def type_wrt_metric(self): return self._type_wrt_metric_ @property def sides(self): return self._sides_ @property def name(self): return self._name_ @property def ndim(self): return self._ndim_ @property def interpolation(self): return self._interpolation_ @property def volume(self): """ Return the volume of this region.""" if self._volume_ is None: p = 20 # we use this many high order numerical quadrature. qx, qy, qz, quad_weights = Quadrature([p, p, p], category='Gauss').quad_ndim_ravel detJ = self.interpolation.Jacobian(qx, qy, qz) self._volume_ =
np.sum(detJ * quad_weights)
numpy.sum
from lenstronomy.Analysis.image_reconstruction import MultiBandImageReconstruction from lenstronomy.Data.pixel_grid import PixelGrid from lenstronomy.Data.imaging_data import ImageData from lenstronomy.Util import util import numpy as np import numpy.testing as npt import copy class MultiPatchReconstruction(MultiBandImageReconstruction): """ this class illustrates the model of disconnected multi-patch modeling with 'joint-linear' option in one single array. """ def __init__(self, multi_band_list, kwargs_model, kwargs_params, multi_band_type='joint-linear', kwargs_likelihood=None, kwargs_pixel_grid=None, verbose=True): """ :param multi_band_list: list of imaging data configuration [[kwargs_data, kwargs_psf, kwargs_numerics], [...]] :param kwargs_model: model keyword argument list :param kwargs_params: keyword arguments of the model parameters, same as output of FittingSequence() 'kwargs_result' :param multi_band_type: string, option when having multiple imaging data sets modelled simultaneously. Options are: - 'multi-linear': linear amplitudes are inferred on single data set - 'linear-joint': linear amplitudes ae jointly inferred - 'single-band': single band :param kwargs_likelihood: likelihood keyword arguments as supported by the Likelihood() class :param kwargs_pixel_grid: keyword argument of PixelGrid() class. This is optional and overwrites a minimal grid Attention for consistent pixel grid definitions! :param verbose: if True (default), computes and prints the total log-likelihood. This can deactivated for speedup purposes (does not run linear inversion again), and reduces the number of prints. """ self._multi_band_list = multi_band_list if not multi_band_type == 'joint-linear': raise ValueError('MultiPatchPlot only works with multi_band_type="joint_linear". ' 'Setting choice was %s. ' % multi_band_type) MultiBandImageReconstruction.__init__(self, multi_band_list, kwargs_model, kwargs_params, multi_band_type=multi_band_type, kwargs_likelihood=kwargs_likelihood, verbose=verbose) if kwargs_pixel_grid is not None: self._pixel_grid_joint = PixelGrid(**kwargs_pixel_grid) else: self._pixel_grid_joint = self._joint_pixel_grid(multi_band_list) @property def pixel_grid_joint(self): """ :return: PixelGrid() class instance covering the entire window of the sky including all individual patches """ return self._pixel_grid_joint @staticmethod def _joint_pixel_grid(multi_band_list): """ Joint PixelGrid() class instance. This routine only works when the individual patches have the same coordinate system orientation and pixel scale. :param multi_band_list: list of imaging data configuration [[kwargs_data, kwargs_psf, kwargs_numerics], [...]] :return: PixelGrid() class instance covering the entire window of the sky including all individual patches """ nx, ny = 0, 0 kwargs_data = copy.deepcopy(multi_band_list[0][0]) kwargs_pixel_grid = {'nx': 0, 'ny': 0, 'transform_pix2angle': kwargs_data['transform_pix2angle'], 'ra_at_xy_0': kwargs_data['ra_at_xy_0'], 'dec_at_xy_0': kwargs_data['dec_at_xy_0']} pixel_grid = PixelGrid(**kwargs_pixel_grid) Mpix2a = pixel_grid.transform_pix2angle # set up joint coordinate system and pixel size to include all frames for i in range(len(multi_band_list)): kwargs_data = multi_band_list[i][0] data_class_i = ImageData(**kwargs_data) Mpix2a_i = data_class_i.transform_pix2angle # check we are operating in the same coordinate system/rotation and pixel scale npt.assert_almost_equal(Mpix2a, Mpix2a_i, decimal=5) # evaluate pixel of zero point with the base coordinate system ra0, dec0 = data_class_i.radec_at_xy_0 x_min, y_min = pixel_grid.map_coord2pix(ra0, dec0) nx_i, ny_i = data_class_i.num_pixel_axes nx, ny = _update_frame_size(nx, ny, x_min, y_min, nx_i, ny_i) # select minimum in x- and y-axis # transform back in RA/DEC and make this the new zero point of the base coordinate system ra_at_xy_0_new, dec_at_xy_0_new = pixel_grid.map_pix2coord(np.minimum(x_min, 0), np.minimum(y_min, 0)) kwargs_pixel_grid['ra_at_xy_0'] = ra_at_xy_0_new kwargs_pixel_grid['dec_at_xy_0'] = dec_at_xy_0_new kwargs_pixel_grid['nx'] = nx kwargs_pixel_grid['ny'] = ny pixel_grid = PixelGrid(**kwargs_pixel_grid) return pixel_grid def image_joint(self): """ patch together the individual patches of data and models :return: image_joint, model_joint, norm_residuals_joint """ nx, ny = self._pixel_grid_joint.num_pixel_axes image_joint = np.zeros((ny, nx)) model_joint =
np.zeros((ny, nx))
numpy.zeros
# -*- coding: utf-8 -*- """ Created on Thu Jan 30 10:40:46 2020 @author: lealp """ import pandas as pd pd.set_option('display.width', 50000) pd.set_option('display.max_rows', 50000) pd.set_option('display.max_columns', 5000) import numpy as np from dask.diagnostics import ProgressBar import pymannkendall as mk import xarray as xr def apply_mk(x, alpha=0.05): ''' The mannkendall test is described in: 1) http://www.scielo.br/pdf/eagri/v33n2/05.pdf 2) https://vsp.pnnl.gov/help/Vsample/Design_Trend_Mann_Kendall.htm The algorithm is described in: https://pypi.org/project/pymannkendall/ Returns: 2d-tuple containing the condition value (True/False) of the pvalue<alpha and the temporal trend coefficient ''' result = mk.original_test(x, alpha=alpha) if result[1] == True: return
np.array([result[1], result[-1]])
numpy.array
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is the "snake" Python module. It is the lower level module used to analyze non-magnetic bright points. It is assume that small UIO 3D boxes containing single nMBPs are given. The goal of this module is to locate the 3D region in which nMBP forms. The set of minima of density (layer by layer, at constant z) correponding to the nMBP are first located. This set has the shape of a "snake", and hence the name of the module. This "snake" defines the "eye" of the nMBP, looking like the "eye" of a tornado. At each layer, one has the "eye" of the nMBP. For a specific layer and from the corresponding eye one then computes the region that contains the nMBP. First step ---------- First step is to obtain candidates for the local minimum (of density), that corresponds to the eye of the nMBP in a specific layer. For this purpose, a minimum filter is used. This introduces a free parameter, 'radius', or 'r'. Experimentally 3 is a good value. Unfortunately this gives many candidates and only one has to be selected. Second step ----------- The second step is to reduce the number of selected candidates. The eye of the nMBP has a quite low density, but only around tau=1. For a layer around tau=1, one can plot a histogram of density at local minima. Experimentally one obtains that the steepest slope of the histogram separates fairly well a small set of local minima (among which the nMBP) from a set containing the biggest amount of irrelevant local minima. This procedure works extremely well at tau=1, usually leading directly to the single nMBP. Away from tau=1 it generally leaves a few other candidates. The candidates left are sorted by increasing density, and at most the first three are kept. Third step ---------- Third step is identifying THE nMBP among all remaining local minima. This cannot be done generally from one single layer. The idea is to first apply step two to a layer near tau=1 and for each candidate move up and down to the nearest local minimum, thus identifying all possible "snakes". At this point, one has as many snakes as initial candidates. One chooses the longest, and if two snakes have identical length, one chooses the one that is less twisted. Getting the neighbourhood ------------------------- One needs now to identify the neighbourhood of the nMBP. We proceed again layer by layer. We look for a star domain whose centre is the already computed eye. The idea is to move radially in each direction away from the eye. Density generally increases, and one always keep track of the maximum density. When the density increases above a fraction (1.-threshold) of rho_max - rho_eye, one decides it is the boundary of the star domain. The threshold is experimentally taken to be 0.8. It is the other free parameter of the algorithms used here. Note that the results are not very sensitive to these free parameters. Of course, the number of directions to explore radially increases with the size of the domain, and for points near the eye there is a huge redundancy. The idea is to build a (discrete) spiral around the eye, parametrized so that all points are more or less equidistant from the neighbours and that the maximum distance does not exceed a fraction of the inter-cell distance. This fraction is chosen so that the spiral covers all the mesh. This spiral is an invertible mathematical function, and one can therefore get for each point the neighbours that are in a radial direction, allowing hence to move radially. Because the mesh is discrete, the algorithm does not work perfectly and the star domain found is in fact not even connected, but it seems to be a very good choice of neighbourhood. Getting the region containing the nMBP, its border, and the background ---------------------------------------------------------------------- Now one looks for a domain inside the neighbourhood, containing the nMBP, and satisfying condition C defined by |(rho_eye-<rho>)/<rho>| < 0. This domain must be as big as possible satisfying these conditions. The background is defined as the complementary part of this region with respect to the neighbourhood. This domain D is choosen consistently so that <rho> is the mean taken over the background and such that the domain is connected. One proceeds iterarively. A first approximation to D is given by the neighbourhood itself. A new approximation is computed applying D followed by a flood fill algorithm (flood fill produces the biggest connected domain to the eye and satisfying some condition). Applying this condition over and over reduces the size of D. When the size remains constant the algorithm is stopped. """ import numpy as np import scipy import scipy.ndimage as ndimage import scipy.ndimage.filters as filters try: import matplotlib.pyplot as plt except ImportError: print('Warning: matplotlib is missing.') from flood_fill import flood_fill def find_min(data, ng_sz=3, threshold=np.Inf, time=-1): data_max = filters.maximum_filter(data, ng_sz) maxima = (data == data_max) data_min = filters.minimum_filter(data, ng_sz) minima = (data == data_min) diff = ((data_max - data_min)/np.abs(data_max) < threshold) minima[diff == False] = False labeled, num_objects = ndimage.label(minima) slices = ndimage.find_objects(labeled) #x, y = [], [] p = [] for dy, dx in slices: x_center = .5*(dx.start+dx.stop-1) #x.append(x_center) y_center = .5*(dy.start+dy.stop-1) #y.append(y_center) if time >= 0: p.append((y_center,x_center,time)) else: p.append((y_center,x_center)) return p def x_coords(p): return [p0[0] for p0 in p] def y_coords(p): return [p0[1] for p0 in p] def d2(p1,p2,periodX=0,periodY=0): if periodX == 0: deltaX = p2[0]-p1[0] else : deltaX = min(
np.abs(p2[0]-p1[0])
numpy.abs
import numpy as np def generate_cosmic_rays( shape, mean_cosmic_rays=1, min_length=10, max_length=30, rng=None): """Generate a binary mask w/ cosmic rays. This routine generates cosmic rays by choosing a random position in the image, a random angle, and a random length of the cosmic ray track. Then pixels along the line determined by the length of the track, the position, and the angle are marked. The width of the track is broadened a bit when the row or column changes. The total number of cosmic rays is Poisson distributed according to `mean_cosmic_rays`. The length of the track is chosen uniformly between `min_length` and `max_length`. Parameters ---------- shape : int or tuple of ints The shape of the mask to generate. mean_cosmic_rays : int, optional The mean number of cosmic rays. min_length : int, optional The minimum length of the track. max_length : int, optional The maximum length of the track. rng : np.random.RandomState or None, optional An RNG to use. If none is provided, a new `np.random.RandomState` state instance will be created. Returns ------- msk : np.ndarray, shape `shape` A boolean mask marking the locations of the cosmic rays. """ msk = np.zeros(shape) rng = rng or np.random.RandomState() n_cosmic_rays = rng.poisson(mean_cosmic_rays) for _ in range(n_cosmic_rays): y = rng.randint(0, msk.shape[0]-1) x = rng.randint(0, msk.shape[1]-1) angle = rng.uniform() * 2.0 * np.pi n_pix = rng.randint(min_length, max_length+1) cosa = np.cos(angle) sina = np.sin(angle) _x_prev = None _y_prev = None for _ in range(n_pix): _x = int(x + 0.5) _y = int(y + 0.5) if _y >= 0 and _y < msk.shape[0] and _x >= 0 and _x < msk.shape[1]: if _x_prev is not None and _y_prev is not None: if _x_prev != _x: msk[_y, _x_prev] = 1 if _y_prev != _y: msk[_y_prev, _x] = 1 msk[_y, _x] = 1 _x_prev = _x _y_prev = _y x += cosa y += sina return msk.astype(bool) def generate_bad_columns( shape, mean_bad_cols=1, widths=(1, 2, 5, 10), p=(0.8, 0.1, 0.075, 0.025), min_length_frac=(1, 1, 0.25, 0.25), max_length_frac=(1, 1, 0.75, 0.75), gap_prob=(0.30, 0.30, 0, 0), min_gap_frac=(0.1, 0.1, 0, 0), max_gap_frac=(0.3, 0.3, 0, 0), rng=None): """Generate a binary mask w/ bad columns. Parameters ---------- shape : int or tuple of ints The shape of the mask to generate. mean_bad_cols : float, optional The mean of the Poisson distribution for the total number of bad columns to generate. widths : n-tuple of ints, optional The possible widths of the bad columns. p : n-tuple of floats, optional The frequency of each of the bad column widths. min_length_frac : n-tuple of floats, optional The minimum fraction of the image the bad column spans. There should be one entry per bad column width in `widths`. max_length_frac : n-tuple of floats, optional The maximum fraction of the image the bad column spans. There should be one entry per bad column width in `widths`. gap_prob : n-tuple of floats, optional The probability that the bad column has a gap in it. There should be one entry per bad column width in `widths`. min_gap_frac : n-tuple of floats, optional The minimum fraction of the image that the gap spans. There should be one entry per bad column width in `widths`. max_gap_frac : n-tuple of floats, optional The maximum fraction of the image that the gap spans. There should be one entry per bad column width in `widths`. rng : np.random.RandomState or None, optional An RNG to use. If none is provided, a new `np.random.RandomState` state instance will be created. Returns ------- msk : np.ndarray, shape `shape` A boolean mask marking the locations of the bad columns. """ p = np.array(p) / np.sum(p) msk =
np.zeros(shape)
numpy.zeros
#!/usr/bin/env python # cube2gesp, N atoms, M grid points from ase.io.cube import read_cube_data from ase.units import Bohr from scipy.interpolate import RegularGridInterpolator from scipy.interpolate import LinearNDInterpolator import numpy as np import io import argparse def main(): parser = argparse.ArgumentParser(description='Convert .cube format to' ' Fortran-RESP-readible .gesp format.') parser.add_argument('infile_cube', metavar='infile.cube', help="Input in .cube format (Bohr and Hartree)") parser.add_argument('outfile_gesp', nargs='?', metavar='outfile.gesp', default='outfile.gesp', help="Output in .gesp format") parser.add_argument('-n', nargs='?', metavar='N', default=-1, const=99999, type=int, help="Maximum number of grid points") args = parser.parse_args() cube2gesp(args.infile_cube, args.outfile_gesp, args.n) def cube2gesp(infile_cube, outfile_gesp, N = -1): # cube file measures in Bohr, but ASE converts input to Angstrom # however, field is not converted while distances are cube_data, cube_atoms = read_cube_data(infile_cube) # nX = cube_data.shape # X = cube_atoms.cell.diagonal() # measures of cell in spatial dimensions # x_grid = np.linspace(0,X[0],nX[0]) # y_grid = np.linspace(0,X[1],nX[1]) # z_grid = np.linspace(0,X[2],nX[2]) # x_grid3,y_grid3,z_grid3=np.meshgrid(x_grid,y_grid,z_grid) # general approach for creating a grid of coordinates # in 3 dimensions and N points in each spatial dimension, # X.shape == (3, N, N, N) dim = cube_data.ndim # usually 3 print("Read .cube file of shape {} in box {}.".format(cube_data.shape,cube_atoms.cell.diagonal())) X_lin = [] X = np.empty((dim,) + cube_data.shape) for i in range(0,dim): X_lin.append( np.linspace(0, cube_atoms.cell[i,i], cube_data.shape[i]) ) X_list=np.meshgrid(*X_lin,indexing='ij') X = np.asarray(X_list) Unit_Cell = X[:,1,1,1].prod() # for uniform grid Integral = cube_data.flatten().sum()*Unit_Cell print("Reconstructed uniform grid of shape {}.".format(X.shape)) if N > 0: print("Interpolate .cube data of shape {} and {} points in total onto grid" " of less than {} points.".format(cube_data.shape, np.prod(cube_data.shape), N) ) gridInterpolator = RegularGridInterpolator( tuple(X_lin), cube_data, method="linear", bounds_error=True ) NX = np.asarray(cube_data.shape) r = (N / np.prod(cube_data.shape))**(1/dim) Nx = np.floor(r * NX) x_lin = [] for i in range(0,dim): x_lin.append( np.linspace(0, cube_atoms.cell[i,i], Nx[i]) ) x_list=
np.meshgrid(*x_lin,indexing='ij')
numpy.meshgrid
"""Collection of subsampling method on the neurons.""" import numpy as np from McNeuron import Neuron from McNeuron import Node from numpy import linalg as LA def find_sharpest_fork(nodes): """ Looks at the all branching point in the Nodes list, selects those which both its children are end points and finds the closest pair of childern (the distance between children). Parameters ---------- Nodes: list the list of Node Returns ------- sharpest_pair: array the index of the pair of closest pair of childern distance: float Distance of the pair of children """ pair_list = [] Dis = np.array([]) for n in nodes: if n.parent is not None: if n.parent.parent is not None: a = n.parent.children if(isinstance(a, list)): if(len(a)==2): n1 = a[0] n2 = a[1] if(len(n1.children) == 0 and len(n2.children) == 0): pair_list.append([n1 , n2]) dis = LA.norm(a[0].xyz - a[1].xyz,2) Dis = np.append(Dis,dis) if(len(Dis)!= 0): (b,) = np.where(Dis == Dis.min()) sharpest_pair = pair_list[b[0]] distance = Dis.min() else: sharpest_pair = [0,0] distance = 0. return sharpest_pair, distance def random_subsample(neuron, num): """ randomly selects a few nodes from neuron and builds a new neuron with them. The location of these node in the new neuron is the same as the original neuron and the morphology of them is such that if node A is parent (or grand parent) of node B in the original neuron, it is the same for the new neuron. Parameters ---------- num: int number of nodes to be selected randomly. Returns ------- Neuron: the subsampled neuron """ I = np.arange(neuron.n_soma, neuron.n_node) np.random.shuffle(I) selected_index = I[0:num - 1] selected_index = np.union1d([0], selected_index) selected_index = selected_index.astype(int) selected_index = np.unique(np.sort(selected_index)) return neuron_with_selected_nodes(neuron, selected_index) def regular_subsample(neuron): """ Returning subsampled neuron with main nodes. i.e endpoints and branching nodes. Parameters ---------- neuron: Neuron input neuron Returns ------- Neuron: the subsampled neuron """ # select all the main points selected_index = get_index_of_main_nodes(neuron) # Computing the parent id of the selected nodes neuron = neuron_with_selected_nodes(neuron, selected_index) return neuron def prune_subsample(neuron, number): main_point = subsample_main_nodes(neuron) Nodes = main_point.nodes_list rm = (main_point.n_node - number)/2. for remove in range(int(rm)): b, m = find_sharpest_fork(Nodes) remove_pair_adjust_parent(Nodes, b) return Neuron(input_format = 'only list of nodes', input_file = Nodes) def get_index_of_main_nodes(neuron): """ Returning the index of branching points and end points. Parameters ---------- neuron: Neuron input neuron Returns ------- selected_index: array the list of main point; branching points and end points """ branch_order = neuron.branch_order(neuron.parent_index) (branch_index,) = np.where(branch_order[neuron.n_soma:] == 2) (endpoint_index,) = np.where(branch_order[neuron.n_soma:] == 0) selected_index = np.union1d(branch_index + neuron.n_soma, endpoint_index + neuron.n_soma) selected_index = np.append(range(neuron.n_soma), selected_index) return selected_index def neuron_with_axon(neuron): """ Parameters: ----------- neuron Return: ------- neuron with axon (whitout dendrite) """ (basal,) = np.where(neuron.nodes_type != 3) (apical,) = np.where(neuron.nodes_type != 4) selected = np.intersect1d(basal, apical) return neuron_with_selected_nodes(neuron, selected) def neuron_with_dendrite(neuron): (axon,) = np.where(neuron.nodes_type != 2) return neuron_with_selected_nodes(neuron, axon) def neuron_with_selected_nodes(neuron, selected_index): """ Giving back a new neuron made up with the selected_index nodes of self. if node A is parent (or grand parent) of node B in the original neuron, it is the same for the new neuron. Parameters ---------- selected_index: numpy array the index of nodes from original neuron for making new neuron. Returns ------- Neuron: the subsampled neuron. """ parent = parent_id(neuron, selected_index) # making the list of nodes n_list = [] for i in range(selected_index.shape[0]): n = Node() n.xyz = neuron.nodes_list[selected_index[i]].xyz n.r = neuron.nodes_list[selected_index[i]].r n.node_type = neuron.nodes_list[selected_index[i]].node_type n_list.append(n) # adjusting the childern and parents for the nodes. for i in np.arange(1, selected_index.shape[0]): j = parent[i] n_list[i].parent = n_list[j] n_list[j].add_child(n_list[i]) return Neuron(input_format='Matrix of swc without Node class', input_file=n_list) def straigh_subsample(neuron, distance): """ Subsampling a neuron from original neuron. It has all the main points of the original neuron, i.e endpoints or branching nodes, and meanwhile the distance of two consecutive nodes of subsample neuron is around the 'distance'. for each segment between two consecuative main points, a few nodes from the segment will be added to the selected node; it starts from the far main point, and goes on the segment toward the near main point. Then the first node which is going to add has the property that it is the farest node from begining on the segment such that its distance from begining is less than 'distance'. The next nodes will be selected similarly. this procesure repeat for all the segments. Parameters ---------- distance: float the mean distance between pairs of consecuative nodes. Returns ------- Neuron: the subsampled neuron """ # Selecting the main points: branching nodes and end nodes selected_index = get_index_of_main_nodes(neuron) # for each segment between two consecuative main points, a few nodes from the segment will be added to the selected node. # These new nodes will be selected base on the fact that neural distance of two consecuative nodes is around 'distance'. # Specifically, it starts from the far main point, and goes on the segment toward the near main point. Then the first node which is # going to add has the property that it is the farest node from begining on the segment such that its distance from begining is # less than 'distance'. The next nodes will be selected similarly. for i in selected_index: upList = np.array([i], dtype=int) index = neuron.parent_index[i] dist = neuron.distance_from_parent[i] while(~np.any(selected_index == index)): upList = np.append(upList, index) index = neuron.parent_index[index] dist = np.append(dist, sum(neuron.distance_from_parent[upList])) dist = np.append(0, dist) (I,) = np.where(np.diff(np.floor(dist/distance)) > 0) I = upList[I] selected_index = np.append(selected_index, I) selected_index = np.unique(selected_index) neuron = neuron_with_selected_nodes(neuron, selected_index) return neuron def straight_subsample_with_fixed_number(neuron, num): """ Returning a straightened subsample neuron with fixed number of nodes. Parameters ---------- num: int number of nodes on the subsampled neuron Returns ------- distance: float the subsampling distance neuron: Neuron the subsampled neuron """ l = sum(neuron.distance_from_parent) branch_number = len(np.where(neuron.branch_order[neuron.n_soma:] == 2)) distance = l/(num - branch_number) neuron = straigh_subsample(neuron, distance) return neuron, distance def parent_id2(neuron, selected_index): """ Return the parent id of all the selected_index of the neurons. Parameters ---------- selected_index: numpy array the index of nodes Returns ------- parent_id: the index of parent of each element in selected_index in this array. """ parent_id = np.array([], dtype=int) for i in selected_index: p = neuron.parent_index[i] while(~np.any(selected_index == p)): p = neuron.parent_index[p] (ind,) = np.where(selected_index == p) parent_id = np.append(parent_id, ind) return parent_id def parent_id(neuron, selected_index): """ Return the parent id of all the selected_index of the neurons. Parameters ---------- selected_index: numpy array the index of nodes Returns ------- parent_id: the index of parent of each element in selected_index in this array. """ length = len(neuron.nodes_list) selected_length = len(selected_index) adjacency = np.zeros([length,length]) adjacency[neuron.parent_index[1:], range(1,length)] = 1 full_adjacency = np.linalg.inv(np.eye(length) - adjacency) selected_full_adjacency = full_adjacency[np.ix_(selected_index,selected_index)] selected_adjacency = np.eye(selected_length) - np.linalg.inv(selected_full_adjacency) selected_parent_id = np.argmax(selected_adjacency, axis=0) return selected_parent_id def prune(neuron, number_of_nodes, threshold): """ Pruning the neuron. It removes all the segments that thier length is less than threshold unless the number of nodes becomes lower than lowest_number. In the former case, it removes the segments until the number of nodes is exactly the lowest_number. Parameters ---------- neuron: Neuron input neuron. number_of_nodes: int the number of nodes for output neuron. Returns ------- pruned_neuron: Neuron The pruned neuron. """ n = len(neuron.nodes_list) for i in range(n - number_of_nodes): length, index = shortest_tips(neuron) if(length < threshold): neuron = remove_node(neuron, index) else: break neuron.set_distance_from_parent() return neuron def remove_node(neuron, index): neuron.n_node -= 1 node = neuron.nodes_list[index] parent_index = neuron.get_index_for_no_soma_node(node.parent) p = node.parent node.parent.remove_child(node) neuron.location = np.delete(neuron.location,index, axis = 1) neuron.nodes_list.remove(node) neuron.branch_order = np.delete(neuron.branch_order,index) new_parent_index = neuron.get_index_for_no_soma_node(p) neuron.branch_order[new_parent_index] -= 1 neuron.parent_index = np.delete(neuron.parent_index,index) I = np.where(neuron.parent_index > index) neuron.parent_index[I] -= 1 neuron.set_distance_from_parent() return neuron def shortest_tips(neuron): """ Returing the initial node of segment with the given end point. The idea is to go up from the tip. """ (endpoint_index,) = np.where(neuron.branch_order[neuron.n_soma:] == 0) (branch_index,) = np.where(neuron.branch_order[neuron.n_soma:] == 2) selected_index = np.union1d(neuron.n_soma + endpoint_index, neuron.n_soma + branch_index) selected_index = np.append(0, selected_index) par = parent_id(neuron, range(1,len(endpoint_index) + 1)) dist = neuron.location[:, endpoint_index] - neuron.location[:, par] lenght = sum(dist**2,2) index = np.argmin(lenght) return np.sqrt(min(lenght)), endpoint_index[index] + neuron.n_soma def straight_prune_subsample(neuron, number_of_nodes): """ Subsampling a neuron with straightening and pruning. At the first step, it strighten the neuron with 200 nodes (if the number of nodes for the neuron is less than 200, it doesn't change it). Then the neuron is pruned with a twice the distance used for straightening. If the number of nodes is less than 'number_of_nodes' the algorithm stops otherwise it increases the previous distance by one number and does the same on the neuron. Parameters ---------- neuron: Neuron input neuron number_of_nodes: int the number of nodes for the output neuron Returns ------- sp_neuron: Neuron the subsample neuron after straightening and pruning. """ if(neuron.n_node > 200): neuron, distance = straight_subsample_with_fixed_number(neuron, 200) sp_neuron = prune(neuron=neuron, number_of_nodes=number_of_nodes, threshold=2*distance) while(len(sp_neuron.nodes_list)>number_of_nodes): distance += 1 sp_neuron = straigh_subsample(sp_neuron, distance) sp_neuron = prune(neuron=sp_neuron, number_of_nodes=number_of_nodes, threshold=2*distance) return sp_neuron def mesoscale_subsample(neuron, number): main_point = subsample_main_nodes(neuron) Nodes = main_point.nodes_list rm = (main_point.n_node - number)/2. for remove in range(int(rm)): b, m = find_sharpest_fork(neuron, Nodes) remove_pair_adjust_parent(neuron, Nodes, b) neuron = Neuron(input_format = 'only list of nodes', input_file = Nodes) if(neuron.n_node > number): (I,) = np.where(neuron.branch_order == 0) neuron = remove_node(neuron, I[0]) return neuron def subsample_main_nodes(neuron): """ subsamples a neuron with its main node only; i.e endpoints and branching nodes. Returns ------- Neuron: the subsampled neuron """ # select all the main points selected_index = get_index_of_main_nodes(neuron) # Computing the parent id of the selected nodes n = neuron_with_selected_nodes(neuron, selected_index) return n def find_sharpest_fork(neuron, Nodes): """ Looks at the all branching point in the Nodes list, selects those which both its children are end points and finds the closest pair of childern (the distance between children). Parameters ---------- Nodes: list the list of Node Returns ------- sharpest_pair: array the index of the pair of closest pair of childern distance: float Distance of the pair of children """ pair_list = [] Dis = np.array([]) for n in Nodes: if n.parent is not None: if n.parent.parent is not None: a = n.parent.children if(isinstance(a, list)): if(len(a)==2): n1 = a[0] n2 = a[1] if(len(n1.children) == 0 and len(n2.children) == 0): pair_list.append([n1 , n2]) dis = LA.norm(a[0].xyz - a[1].xyz,2) Dis = np.append(Dis,dis) if(len(Dis)!= 0): (b,) = np.where(Dis == Dis.min()) sharpest_pair = pair_list[b[0]] distance = Dis.min() else: sharpest_pair = [0,0] distance = 0. return sharpest_pair, distance def find_sharpest_fork_general(neuron, Nodes): """ Looks at the all branching point in the Nodes list, selects those which both its children are end points and finds the closest pair of childern (the distance between children). Parameters ---------- Nodes: list the list of Node Returns ------- sharpest_pair: array the index of the pair of closest pair of childern distance: float Distance of the pair of children """ pair_list = [] Dis = np.array([]) for n in Nodes: if n.parent is not None: if n.parent.parent is not None: a = n.parent.children if(isinstance(a, list)): if(len(a)==2): n1 = a[0] n2 = a[1] pair_list.append([n1 , n2]) dis = LA.norm(a[0].xyz - a[1].xyz,2) Dis = np.append(Dis,dis) if(len(Dis)!= 0): (b,) = np.where(Dis == Dis.min()) sharpest_pair = pair_list[b[0]] distance = Dis.min() else: sharpest_pair = [0,0] distance = 0. return sharpest_pair, distance def remove_pair_replace_node(neuron, Nodes, pair): """ Removes the pair of nodes and replace it with a new node. the parent of new node is the parent of the pair of node, and its location and its radius are the mean of removed nodes. Parameters ---------- Nodes: list the list of Nodes pair: array The index of pair of nodes. the nodes should be end points and have the same parent. Returns ------- The new list of Nodes which the pair are removed and a mean node is replaced. """ par = pair[0].parent loc = pair[0].xyz + pair[1].xyz loc = loc/2 r = pair[0].r + pair[1].r r = r/2 Nodes.remove(pair[1]) Nodes.remove(pair[0]) n = McNeuron.Node() n.xyz = loc n.r = r par.children = [] par.add_child(n) n.parent = par Nodes.append(n) def remove_pair_adjust_parent(neuron, Nodes, pair): """ Removes the pair of nodes and adjust its parent. the location of the parent is the mean of the locaton of two nodes. Parameters ---------- Nodes: list the list of Nodes pair: array The index of pair of nodes. the nodes should be end points and have the same parent. Returns ------- The new list of Nodes which the pair are removed their parent is adjusted. """ par = pair[0].parent loc = pair[0].xyz + pair[1].xyz loc = loc/2 Nodes.remove(pair[1]) Nodes.remove(pair[0]) par.xyz = loc par.children = [] def parent_id_for_extract(original_parent_id, selected_index): """ Return the parent id of all the selected_index of the neurons. Parameters ---------- selected_index: numpy array the index of nodes Returns ------- parent_id: the index of parent of each element in selected_index in this array. """ length = len(original_parent_id) selected_length = len(selected_index) adjacency = np.zeros([length, length]) adjacency[original_parent_id[1:]-1, range(1, length)] = 1 full_adjacency = np.linalg.inv(np.eye(length) - adjacency) selected_full_adjacency = full_adjacency[np.ix_(selected_index, selected_index)] selected_adjacency = np.eye(selected_length) - np.linalg.inv(selected_full_adjacency) selected_parent_id = np.argmax(selected_adjacency, axis=0) return selected_parent_id def parent_id_for_extract2(original_parent_id, selected_index): parent_id = np.array([], dtype=int) for i in selected_index[1:]: p = original_parent_id[i] while(~np.any(selected_index == p-1)): p = original_parent_id[p-1] (ind,) = np.where(selected_index == p-1) parent_id = np.append(parent_id, ind) parent_id = np.append(-1, parent_id) return parent_id def extract_main_neuron_from_swc(matrix, num = 300): a, b = np.unique(matrix[:,6],return_counts=True) (I,) = np.where(b==2) branch_point = a[I] end_point = np.setxor1d(np.arange(0,matrix.shape[0]), matrix[4:,6]) I = np.union1d(branch_point, end_point) leng = matrix.shape[0] lengi = len(I) I = np.union1d(I, np.arange(0,n, int(n/(leng - lengi - 1)))) random_point = np.setxor1d(
np.arange(3,matrix.shape[0])
numpy.arange
from datetime import datetime import json import pytest import traitlets as tl import numpy as np import xarray as xr from numpy.testing import assert_equal import podpac from podpac.core.coordinates.utils import make_coord_array from podpac.core.coordinates.array_coordinates1d import ArrayCoordinates1d from podpac.core.coordinates.uniform_coordinates1d import UniformCoordinates1d from podpac.core.coordinates.stacked_coordinates import StackedCoordinates from podpac.core.coordinates.coordinates import Coordinates class TestArrayCoordinatesInit(object): def test_empty(self): c = ArrayCoordinates1d([]) a = np.array([], dtype=float) assert_equal(c.coordinates, a) assert_equal(c.bounds, [np.nan, np.nan]) with pytest.raises(RuntimeError): c.argbounds assert c.size == 0 assert c.shape == (0,) assert c.dtype is None assert c.deltatype is None assert c.is_monotonic is None assert c.is_descending is None assert c.is_uniform is None assert c.start is None assert c.stop is None assert c.step is None repr(c) def test_numerical_singleton(self): a = np.array([10], dtype=float) c = ArrayCoordinates1d(10) assert_equal(c.coordinates, a) assert_equal(c.bounds, [10.0, 10.0]) assert c.coordinates[c.argbounds[0]] == c.bounds[0] assert c.coordinates[c.argbounds[1]] == c.bounds[1] assert c.size == 1 assert c.shape == (1,) assert c.dtype == float assert c.deltatype == float assert c.is_monotonic == True assert c.is_descending is None assert c.is_uniform is None assert c.start is None assert c.stop is None assert c.step is None repr(c) def test_numerical_array(self): # unsorted values = [1, 6, 0, 4.0] a = np.array(values, dtype=float) c = ArrayCoordinates1d(a) assert_equal(c.coordinates, a) assert_equal(c.bounds, [0.0, 6.0]) assert c.coordinates[c.argbounds[0]] == c.bounds[0] assert c.coordinates[c.argbounds[1]] == c.bounds[1] assert c.size == 4 assert c.shape == (4,) assert c.dtype == float assert c.deltatype == float assert c.is_monotonic == False assert c.is_descending is False assert c.is_uniform == False assert c.start is None assert c.stop is None assert c.step is None repr(c) # sorted ascending values = [0, 1, 4, 6] a = np.array(values, dtype=float) c = ArrayCoordinates1d(values) assert_equal(c.coordinates, a)
assert_equal(c.bounds, [0.0, 6.0])
numpy.testing.assert_equal
# -*- coding: utf-8 -*- import numpy as np from pytest import raises from vispy import scene from vispy.testing import (TestingCanvas, requires_application, run_tests_if_main, requires_pyopengl) from vispy.testing.image_tester import assert_image_approved @requires_pyopengl() def test_volume(): vol = np.zeros((20, 20, 20), 'float32') vol[8:16, 8:16, :] = 1.0 # Create V = scene.visuals.Volume(vol) assert V.clim == (0, 1) assert V.method == 'mip' # Set wrong data with raises(ValueError): V.set_data(
np.zeros((20, 20), 'float32')
numpy.zeros
from __future__ import print_function ################################################################################################### # Libraries ################################################################################################### import os import numpy as np from pysam import Samfile, Fastafile from Bio import motifs import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from scipy.signal import savgol_filter from scipy.stats import scoreatpercentile from argparse import SUPPRESS import pyx # Internal from rgt.Util import GenomeData, AuxiliaryFunctions from rgt.HINT.signalProcessing import GenomicSignal from rgt.GenomicRegionSet import GenomicRegionSet from rgt.HINT.biasTable import BiasTable def plotting_args(parser): # Parameters Options parser.add_argument("--organism", type=str, metavar="STRING", default="hg19", help=("Organism considered on the analysis. Check our full documentation for all available " "options. All default files such as genomes will be based on the chosen organism " "and the data.config file.")) parser.add_argument("--reads-file", type=str, metavar="FILE", default=None) parser.add_argument("--region-file", type=str, metavar="FILE", default=None) parser.add_argument("--reads-file1", type=str, metavar="FILE", default=None) parser.add_argument("--reads-file2", type=str, metavar="FILE", default=None) parser.add_argument("--motif-file", type=str, metavar="FILE", default=None) parser.add_argument("--bias-table", type=str, metavar="FILE1_F,FILE1_R", default=None) parser.add_argument("--bias-table1", type=str, metavar="FILE1_F,FILE1_R", default=None) parser.add_argument("--bias-table2", type=str, metavar="FILE1_F,FILE1_R", default=None) parser.add_argument("--window-size", type=int, metavar="INT", default=400) # Hidden Options parser.add_argument("--initial-clip", type=int, metavar="INT", default=50, help=SUPPRESS) parser.add_argument("--downstream-ext", type=int, metavar="INT", default=1, help=SUPPRESS) parser.add_argument("--upstream-ext", type=int, metavar="INT", default=0, help=SUPPRESS) parser.add_argument("--forward-shift", type=int, metavar="INT", default=5, help=SUPPRESS) parser.add_argument("--reverse-shift", type=int, metavar="INT", default=-5, help=SUPPRESS) parser.add_argument("--k-nb", type=int, metavar="INT", default=6, help=SUPPRESS) parser.add_argument("--y-lim", type=float, metavar="FLOAT", default=0.3, help=SUPPRESS) # Output Options parser.add_argument("--output-location", type=str, metavar="PATH", default=os.getcwd(), help="Path where the output bias table files will be written.") parser.add_argument("--output-prefix", type=str, metavar="STRING", default=None, help="The prefix for results files.") # plot type parser.add_argument("--seq-logo", default=False, action='store_true') parser.add_argument("--bias-raw-bc-line", default=False, action='store_true') parser.add_argument("--raw-bc-line", default=False, action='store_true') parser.add_argument("--strand-line", default=False, action='store_true') parser.add_argument("--unstrand-line", default=False, action='store_true') parser.add_argument("--bias-line", default=False, action='store_true') parser.add_argument("--atac-dnase-line", default=False, action='store_true') parser.add_argument("--bias-raw-bc-strand-line2", default=False, action='store_true') parser.add_argument("--fragment-raw-size-line", default=False, action='store_true') parser.add_argument("--fragment-bc-size-line", default=False, action='store_true') def plotting_run(args): if args.seq_logo: seq_logo(args) if args.bias_raw_bc_line: bias_raw_bc_strand_line(args) if args.strand_line: strand_line(args) if args.unstrand_line: unstrand_line(args) if args.raw_bc_line: raw_bc_line(args) if args.bias_raw_bc_strand_line2: bias_raw_bc_strand_line2(args) if args.fragment_raw_size_line: fragment_size_raw_line(args) if args.fragment_bc_size_line: fragment_size_bc_line(args) def seq_logo(args): logo_fname = os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix)) pwm_file = os.path.join(args.output_location, "{}.pwm".format(args.output_prefix)) pwm_dict = dict( [("A", [0.0] * args.window_size), ("C", [0.0] * args.window_size), ("G", [0.0] * args.window_size), ("T", [0.0] * args.window_size), ("N", [0.0] * args.window_size)]) genome_data = GenomeData(args.organism) fasta_file = Fastafile(genome_data.get_genome()) bam = Samfile(args.reads_file, "rb") regions = GenomicRegionSet("Peaks") regions.read(args.region_file) for region in regions: for r in bam.fetch(region.chrom, region.initial, region.final): if not r.is_reverse: cut_site = r.pos - 1 p1 = cut_site - int(args.window_size / 2) else: cut_site = r.aend + 1 p1 = cut_site - int(args.window_size / 2) p2 = p1 + args.window_size # Fetching k-mer currStr = str(fasta_file.fetch(region.chrom, p1, p2)).upper() if r.is_reverse: continue for i in range(0, len(currStr)): pwm_dict[currStr[i]][i] += 1 with open(pwm_file, "w") as f: for e in ["A", "C", "G", "T"]: f.write(" ".join([str(int(c)) for c in pwm_dict[e]]) + "\n") pwm = motifs.read(open(pwm_file), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(args.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False, yaxis_scale=args.y_lim) start = -(args.window_size / 2) end = (args.window_size / 2) - 1 x = np.linspace(start, end, num=args.window_size).tolist() fig = plt.figure(figsize=(8, 2)) ax = fig.add_subplot(111) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_position(('outward', 15)) ax.tick_params(direction='out') ax.xaxis.set_ticks(map(int, x)) x1 = map(int, x) ax.set_xticklabels(map(str, x1), rotation=90) ax.set_xlabel("Coordinates from Read Start", fontweight='bold') ax.set_ylim([0, args.y_lim]) ax.yaxis.set_ticks([0, args.y_lim]) ax.set_yticklabels([str(0), str(args.y_lim)], rotation=90) ax.set_ylabel("bits", rotation=90) figure_name = os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix)) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(args.output_location, "{}.eps".format(args.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.5, 1.5, logo_fname, width=18.8, height=3.5)) c.writeEPSfile(output_fname) os.system("epstopdf " + output_fname) os.remove(os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.eps".format(args.output_prefix))) def bias_raw_bc_line(args): signal = GenomicSignal(args.reads_file) signal.load_sg_coefs(slope_window_size=9) bias_table = BiasTable() bias_table_list = args.bias_table.split(",") table = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) genome_data = GenomeData(args.organism) fasta = Fastafile(genome_data.get_genome()) pwm_dict = dict([("A", [0.0] * args.window_size), ("C", [0.0] * args.window_size), ("G", [0.0] * args.window_size), ("T", [0.0] * args.window_size), ("N", [0.0] * args.window_size)]) num_sites = 0 mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(args.motif_file) bam = Samfile(args.reads_file, "rb") mean_signal_bias_f = np.zeros(args.window_size) mean_signal_bias_r = np.zeros(args.window_size) mean_signal_raw = np.zeros(args.window_size) mean_signal_raw_f = np.zeros(args.window_size) mean_signal_raw_r = np.zeros(args.window_size) mean_signal_bc = np.zeros(args.window_size) mean_signal_bc_f = np.zeros(args.window_size) mean_signal_bc_r = np.zeros(args.window_size) motif_len = 0 for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": # Extend by window_size mid = (region.initial + region.final) / 2 p1 = mid - (args.window_size / 2) p2 = mid + (args.window_size / 2) motif_len = region.final - region.initial signal_bias_f, signal_bias_r, raw, raw_f, raw_r, bc, bc_f, bc_r = \ signal.get_bias_raw_bc_signal(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift, strand=True) num_sites += 1 mean_signal_bias_f = np.add(mean_signal_bias_f, np.array(signal_bias_f)) mean_signal_bias_r = np.add(mean_signal_bias_r, np.array(signal_bias_r)) mean_signal_raw = np.add(mean_signal_raw, np.array(raw)) mean_signal_raw_f = np.add(mean_signal_raw_f, np.array(raw_f)) mean_signal_raw_r = np.add(mean_signal_raw_r, np.array(raw_r)) mean_signal_bc = np.add(mean_signal_bc, np.array(bc)) mean_signal_bc_f = np.add(mean_signal_bc_f, np.array(bc_f)) mean_signal_bc_r = np.add(mean_signal_bc_r, np.array(bc_r)) # Update pwm aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 if region.orientation == "+": for i in range(len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 mean_signal_bias_f = mean_signal_bias_f / num_sites mean_signal_bias_r = mean_signal_bias_r / num_sites mean_signal_raw = mean_signal_raw / num_sites mean_signal_bc = mean_signal_bc / num_sites mean_signal_bc_f = mean_signal_bc_f / num_sites mean_signal_bc_r = mean_signal_bc_r / num_sites # Output the norm and slope signal output_fname = os.path.join(args.output_location, "{}.txt".format(args.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, mean_signal_bias_f))) + "\n") f.write("\t".join((map(str, mean_signal_bias_r))) + "\n") f.write("\t".join((map(str, mean_signal_raw))) + "\n") f.write("\t".join((map(str, mean_signal_bc))) + "\n") f.close() # Output PWM and create logo pwm_fname = os.path.join(args.output_location, "{}.pwm".format(args.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(args.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(8, 6)) start = -(args.window_size / 2) end = (args.window_size / 2) - 1 x = np.linspace(start, end, num=args.window_size) if motif_len % 2 == 0: x1 = int(- (motif_len / 2)) x2 = int(motif_len / 2) else: x1 = int(-(motif_len / 2) - 1) x2 = int((motif_len / 2) + 1) ############################################################ # bias signal per strand fp_score = sum(mean_signal_raw[args.window_size / 2 + x1: args.window_size / 2 + x2]) shoulder_l = sum(mean_signal_raw[args.window_size / 2 + x1 - motif_len:args.window_size / 2 + x1]) shoulder_r = sum(mean_signal_raw[args.window_size / 2 + x2:args.window_size / 2 + x2 + motif_len]) sfr = (shoulder_l + shoulder_r) / (2 * fp_score) min_ax1 = min(mean_signal_raw) max_ax1 = max(mean_signal_raw) ax1.plot(x, mean_signal_raw, color='blue', label='Uncorrected') ax1.text(0.15, 0.9, 'n = {}'.format(num_sites), verticalalignment='bottom', horizontalalignment='right', transform=ax1.transAxes, fontweight='bold') ax1.text(0.35, 0.15, 'SFR = {}'.format(round(sfr, 2)), verticalalignment='bottom', horizontalalignment='right', transform=ax1.transAxes, fontweight='bold') ax1.xaxis.set_ticks_position('bottom') ax1.yaxis.set_ticks_position('left') ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['left'].set_position(('outward', 15)) ax1.spines['bottom'].set_position(('outward', 5)) ax1.tick_params(direction='out') ax1.set_xticks([start, 0, end]) ax1.set_xticklabels([str(start), 0, str(end)]) ax1.set_yticks([min_ax1, max_ax1]) ax1.set_yticklabels([str(round(min_ax1, 2)), str(round(max_ax1, 2))], rotation=90) ax1.set_title(args.output_prefix, fontweight='bold') ax1.set_xlim(start, end) ax1.set_ylim([min_ax1, max_ax1]) ax1.legend(loc="lower right", frameon=False) #################################################################### ##################################################################### # Bias corrected, non-bias corrected (not strand specific) fp_score = sum(mean_signal_bc[args.window_size / 2 + x1: args.window_size / 2 + x2]) shoulder_l = sum(mean_signal_bc[args.window_size / 2 + x1 - motif_len:args.window_size / 2 + x1]) shoulder_r = sum(mean_signal_bc[args.window_size / 2 + x2:args.window_size / 2 + x2 + motif_len]) sfr = (shoulder_l + shoulder_r) / (2 * fp_score) min_ax2 = min(mean_signal_bc) max_ax2 = max(mean_signal_bc) ax2.plot(x, mean_signal_bc, color='red', label='Corrected') ax2.text(0.35, 0.15, 'SFR = {}'.format(round(sfr, 2)), verticalalignment='bottom', horizontalalignment='right', transform=ax2.transAxes, fontweight='bold') ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('left') ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.spines['left'].set_position(('outward', 15)) ax2.tick_params(direction='out') ax2.set_xticks([start, 0, end]) ax2.set_xticklabels([str(start), 0, str(end)]) ax2.set_yticks([min_ax2, max_ax2]) ax2.set_yticklabels([str(round(min_ax2, 2)), str(round(max_ax2, 2))], rotation=90) ax2.set_xlim(start, end) ax2.set_ylim([min_ax2, max_ax2]) ax2.legend(loc="lower right", frameon=False) fp_score_f = sum(mean_signal_bc_f[args.window_size / 2 + x1: args.window_size / 2 + x2]) shoulder_l_f = sum(mean_signal_bc_f[args.window_size / 2 + x1 - motif_len:args.window_size / 2 + x1]) shoulder_r_f = sum(mean_signal_bc_f[args.window_size / 2 + x2:args.window_size / 2 + x2 + motif_len]) sfr_f = (shoulder_l_f + shoulder_r_f) / (2 * fp_score_f) fp_score_r = sum(mean_signal_bc_r[args.window_size / 2 + x1: args.window_size / 2 + x2]) shoulder_l_r = sum(mean_signal_bc_r[args.window_size / 2 + x1 - motif_len:args.window_size / 2 + x1]) shoulder_r_r = sum(mean_signal_bc_r[args.window_size / 2 + x2:args.window_size / 2 + x2 + motif_len]) sfr_r = (shoulder_l_r + shoulder_r_r) / (2 * fp_score_r) min_ax3 = min(min(mean_signal_bc_f), min(mean_signal_bc_r)) max_ax3 = max(max(mean_signal_bc_f), max(mean_signal_bc_r)) ax3.plot(x, mean_signal_bc_f, color='purple', label='Forward') ax3.plot(x, mean_signal_bc_r, color='green', label='Reverse') ax3.text(0.35, 0.15, 'SFR_f = {}'.format(round(sfr_f, 2)), verticalalignment='bottom', horizontalalignment='right', transform=ax3.transAxes, fontweight='bold') ax3.text(0.35, 0.05, 'SFR_r = {}'.format(round(sfr_r, 2)), verticalalignment='bottom', horizontalalignment='right', transform=ax3.transAxes, fontweight='bold') ax3.xaxis.set_ticks_position('bottom') ax3.yaxis.set_ticks_position('left') ax3.spines['top'].set_visible(False) ax3.spines['right'].set_visible(False) ax3.spines['left'].set_position(('outward', 15)) ax3.tick_params(direction='out') ax3.set_xticks([start, 0, end]) ax3.set_xticklabels([str(start), 0, str(end)]) ax3.set_yticks([min_ax3, max_ax3]) ax3.set_yticklabels([str(round(min_ax3, 2)), str(round(max_ax3, 2))], rotation=90) ax3.set_xlim(start, end) ax3.set_ylim([min_ax3, max_ax3]) ax3.legend(loc="lower right", frameon=False) ax3.spines['bottom'].set_position(('outward', 40)) ax1.axvline(x=x1, ymin=-0.3, ymax=1, c="black", lw=0.5, ls='dashed', zorder=0, clip_on=False) ax1.axvline(x=x2, ymin=-0.3, ymax=1, c="black", lw=0.5, ls='dashed', zorder=0, clip_on=False) ax2.axvline(x=x1, ymin=-0.5, ymax=1.2, c="black", lw=0.5, ls='dashed', zorder=0, clip_on=False) ax2.axvline(x=x2, ymin=-0.5, ymax=1.2, c="black", lw=0.5, ls='dashed', zorder=0, clip_on=False) ############################################################################### # merge the above figures figure_name = os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(args.output_location, "{}.eps".format(args.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.45, 0.89, logo_fname, width=18.3, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) os.remove(pwm_fname) os.remove(os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.line.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.eps".format(args.output_prefix))) def raw_bc_line(args): signal = GenomicSignal(args.reads_file) signal.load_sg_coefs(slope_window_size=9) bias_table = BiasTable() bias_table_list = args.bias_table.split(",") table = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) genome_data = GenomeData(args.organism) fasta = Fastafile(genome_data.get_genome()) pwm_dict = dict([("A", [0.0] * args.window_size), ("C", [0.0] * args.window_size), ("G", [0.0] * args.window_size), ("T", [0.0] * args.window_size), ("N", [0.0] * args.window_size)]) num_sites = 0 mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(args.motif_file) bam = Samfile(args.reads_file, "rb") mean_signal_raw = np.zeros(args.window_size) mean_signal_bc = np.zeros(args.window_size) for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": # Extend by window_size mid = (region.initial + region.final) / 2 p1 = mid - (args.window_size / 2) p2 = mid + (args.window_size / 2) signal_bias_f, signal_bias_r, raw, raw_f, raw_r, bc, bc_f, bc_r = \ signal.get_bias_raw_bc_signal(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift, strand=True) num_sites += 1 mean_signal_raw = np.add(mean_signal_raw, np.array(raw)) mean_signal_bc = np.add(mean_signal_bc, np.array(bc)) # Update pwm aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 if region.orientation == "+": for i in range(len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 mean_signal_raw = mean_signal_raw / num_sites mean_signal_bc = mean_signal_bc / num_sites # Output the norm and slope signal output_fname = os.path.join(args.output_location, "{}.txt".format(args.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, mean_signal_raw))) + "\n") f.write("\t".join((map(str, mean_signal_bc))) + "\n") f.close() # Output PWM and create logo pwm_fname = os.path.join(args.output_location, "{}.pwm".format(args.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(args.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) fig = plt.figure(figsize=(8, 4)) ax = fig.add_subplot(111) start = -(args.window_size / 2) end = (args.window_size / 2) - 1 x = np.linspace(start, end, num=args.window_size) ############################################################ min_ = min(min(mean_signal_raw), min(mean_signal_bc)) max_ = max(max(mean_signal_raw), max(mean_signal_bc)) ax.plot(x, mean_signal_raw, color='red', label='Uncorrected') ax.plot(x, mean_signal_bc, color='blue', label='Corrected') ax.text(0.15, 0.9, 'n = {}'.format(num_sites), verticalalignment='bottom', horizontalalignment='right', transform=ax.transAxes, fontweight='bold') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_position(('outward', 15)) ax.spines['bottom'].set_position(('outward', 5)) ax.tick_params(direction='out') ax.set_xticks([start, 0, end]) ax.set_xticklabels([str(start), 0, str(end)]) ax.set_yticks([min_, max_]) ax.set_yticklabels([str(round(min_, 2)), str(round(max_, 2))], rotation=90) ax.set_title(args.output_prefix, fontweight='bold') ax.set_xlim(start, end) ax.set_ylim(min_, max_) ax.legend(loc="lower right", frameon=False) ax.spines['bottom'].set_position(('outward', 40)) ############################################################################### # merge the above figures figure_name = os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(args.output_location, "{}.eps".format(args.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.45, 0.89, logo_fname, width=18.3, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) os.remove(pwm_fname) os.remove(os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.line.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.eps".format(args.output_prefix))) def bias_raw_bc_strand_line(args): signal = GenomicSignal(args.reads_file) signal.load_sg_coefs(slope_window_size=9) bias_table = BiasTable() bias_table_list = args.bias_table.split(",") table = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) genome_data = GenomeData(args.organism) fasta = Fastafile(genome_data.get_genome()) pwm_dict = dict([("A", [0.0] * args.window_size), ("C", [0.0] * args.window_size), ("G", [0.0] * args.window_size), ("T", [0.0] * args.window_size), ("N", [0.0] * args.window_size)]) num_sites = 0 mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(args.motif_file) bam = Samfile(args.reads_file, "rb") mean_signal_bias_f = np.zeros(args.window_size) mean_signal_bias_r = np.zeros(args.window_size) mean_signal_raw = np.zeros(args.window_size) mean_signal_bc = np.zeros(args.window_size) for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": mid = (region.initial + region.final) / 2 p1 = mid - (args.window_size / 2) p2 = mid + (args.window_size / 2) signal_bias_f, signal_bias_r, signal_raw, signal_bc = \ signal.get_bias_raw_bc_signal(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift) num_sites += 1 mean_signal_bias_f = np.add(mean_signal_bias_f, np.array(signal_bias_f)) mean_signal_bias_r = np.add(mean_signal_bias_r, np.array(signal_bias_r)) mean_signal_raw = np.add(mean_signal_raw, np.array(signal_raw)) mean_signal_bc = np.add(mean_signal_bc, np.array(signal_bc)) # Update pwm aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 dna_seq_rev = AuxiliaryFunctions.revcomp(str(fasta.fetch(region.chrom, p1 + aux_plus, p2 + aux_plus)).upper()) if region.orientation == "+": for i in range(0, len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 mean_signal_bias_f = mean_signal_bias_f / num_sites mean_signal_bias_r = mean_signal_bias_r / num_sites mean_signal_raw = mean_signal_raw / num_sites mean_signal_bc = mean_signal_bc / num_sites # Output the norm and slope signal output_fname = os.path.join(args.output_location, "{}.txt".format(args.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, mean_signal_bias_f))) + "\n") f.write("\t".join((map(str, mean_signal_bias_r))) + "\n") f.write("\t".join((map(str, mean_signal_raw))) + "\n") f.write("\t".join((map(str, mean_signal_bc))) + "\n") f.close() # Output PWM and create logo pwm_fname = os.path.join(args.output_location, "{}.pwm".format(args.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(args.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 4)) start = -(args.window_size / 2) end = (args.window_size / 2) - 1 x = np.linspace(start, end, num=args.window_size) ############################################################ # bias signal per strand min_ = min(min(mean_signal_bias_f), min(mean_signal_bias_r)) max_ = max(max(mean_signal_bias_f), max(mean_signal_bias_r)) ax1.plot(x, mean_signal_bias_f, color='purple', label='Forward') ax1.plot(x, mean_signal_bias_r, color='green', label='Reverse') ax1.text(0.15, 0.9, 'n = {}'.format(num_sites), verticalalignment='bottom', horizontalalignment='right', transform=ax1.transAxes, fontweight='bold') ax1.xaxis.set_ticks_position('bottom') ax1.yaxis.set_ticks_position('left') ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['left'].set_position(('outward', 15)) ax1.spines['bottom'].set_position(('outward', 5)) ax1.tick_params(direction='out') ax1.set_xticks([start, 0, end]) ax1.set_xticklabels([str(start), 0, str(end)]) ax1.set_yticks([min_, max_]) ax1.set_yticklabels([str(round(min_, 2)), str(round(max_, 2))], rotation=90) ax1.set_title(args.output_prefix, fontweight='bold') ax1.set_xlim(start, end) ax1.set_ylim([min_, max_]) ax1.legend(loc="upper right", frameon=False) #################################################################### ##################################################################### # Bias corrected, non-bias corrected (not strand specific) min_ = min(min(mean_signal_raw), min(mean_signal_bc)) max_ = max(max(mean_signal_raw), max(mean_signal_bc)) ax2.plot(x, mean_signal_raw, color='blue', label='Uncorrected') ax2.plot(x, mean_signal_bc, color='red', label='Corrected') ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('left') ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.spines['left'].set_position(('outward', 15)) ax2.tick_params(direction='out') ax2.set_xticks([start, 0, end]) ax2.set_xticklabels([str(start), 0, str(end)]) ax2.set_yticks([min_, max_]) ax2.set_yticklabels([str(round(min_, 2)), str(round(max_, 2))], rotation=90) ax2.set_xlim(start, end) ax2.set_ylim([min_, max_]) ax2.legend(loc="upper right", frameon=False) ax2.spines['bottom'].set_position(('outward', 40)) ############################################################################### # merge the above figures figure_name = os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(args.output_location, "{}.eps".format(args.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.51, 0.89, logo_fname, width=18.3, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) os.remove(pwm_fname) os.remove(os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.line.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.eps".format(args.output_prefix))) def bias_raw_bc_strand_line2(args): signal = GenomicSignal(args.reads_file) signal.load_sg_coefs(slope_window_size=9) bias_table = BiasTable() bias_table_list = args.bias_table.split(",") table = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) genome_data = GenomeData(args.organism) fasta = Fastafile(genome_data.get_genome()) pwm_dict = dict([("A", [0.0] * args.window_size), ("C", [0.0] * args.window_size), ("G", [0.0] * args.window_size), ("T", [0.0] * args.window_size), ("N", [0.0] * args.window_size)]) num_sites = 0 mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(args.motif_file) bam = Samfile(args.reads_file, "rb") mean_signal_bias_f = np.zeros(args.window_size) mean_signal_bias_r = np.zeros(args.window_size) mean_signal_raw = np.zeros(args.window_size) mean_signal_raw_f = np.zeros(args.window_size) mean_signal_raw_r = np.zeros(args.window_size) mean_signal_bc = np.zeros(args.window_size) mean_signal_bc_f = np.zeros(args.window_size) mean_signal_bc_r = np.zeros(args.window_size) for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": mid = (region.initial + region.final) / 2 p1 = mid - (args.window_size / 2) p2 = mid + (args.window_size / 2) signal_bias_f, signal_bias_r, signal_raw, signal_raw_f, signal_raw_r, signal_bc, signal_bc_f, signal_bc_r = \ signal.get_bias_raw_bc_signal(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift, strand=True) num_sites += 1 mean_signal_bias_f = np.add(mean_signal_bias_f, np.array(signal_bias_f)) mean_signal_bias_r = np.add(mean_signal_bias_r, np.array(signal_bias_r)) mean_signal_raw = np.add(mean_signal_raw, np.array(signal_raw)) mean_signal_raw_f = np.add(mean_signal_raw_f, np.array(signal_raw_f)) mean_signal_raw_r = np.add(mean_signal_raw_r, np.array(signal_raw_r)) mean_signal_bc = np.add(mean_signal_bc, np.array(signal_bc)) mean_signal_bc_f = np.add(mean_signal_bc_f, np.array(signal_bc_f)) mean_signal_bc_r = np.add(mean_signal_bc_r, np.array(signal_bc_r)) # Update pwm aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 dna_seq_rev = AuxiliaryFunctions.revcomp(str(fasta.fetch(region.chrom, p1 + aux_plus, p2 + aux_plus)).upper()) if region.orientation == "+": for i in range(0, len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 mean_signal_bias_f = mean_signal_bias_f / num_sites mean_signal_bias_r = mean_signal_bias_r / num_sites mean_signal_raw = mean_signal_raw / num_sites mean_signal_raw_f = mean_signal_raw_f / num_sites mean_signal_raw_r = mean_signal_raw_r / num_sites mean_signal_bc = mean_signal_bc / num_sites mean_signal_bc_f = mean_signal_bc_f / num_sites mean_signal_bc_r = mean_signal_bc_r / num_sites # mean_signal_raw = rescaling(mean_signal_raw) # mean_signal_bc = rescaling(mean_signal_bc) # Output the norm and slope signal output_fname = os.path.join(args.output_location, "{}.txt".format(args.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, mean_signal_bias_f))) + "\n") f.write("\t".join((map(str, mean_signal_bias_r))) + "\n") f.write("\t".join((map(str, mean_signal_raw))) + "\n") f.write("\t".join((map(str, mean_signal_raw_f))) + "\n") f.write("\t".join((map(str, mean_signal_raw_r))) + "\n") f.write("\t".join((map(str, mean_signal_bc))) + "\n") f.write("\t".join((map(str, mean_signal_bc_f))) + "\n") f.write("\t".join((map(str, mean_signal_bc_r))) + "\n") f.close() # Output PWM and create logo pwm_fname = os.path.join(args.output_location, "{}.pwm".format(args.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(args.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) # fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, figsize=(8, 8)) fig, (ax1, ax4) = plt.subplots(2, figsize=(8, 4)) start = -(args.window_size / 2) end = (args.window_size / 2) - 1 x = np.linspace(start, end, num=args.window_size) ############################################################ # bias signal per strand min_ = min(min(mean_signal_bias_f), min(mean_signal_bias_r)) max_ = max(max(mean_signal_bias_f), max(mean_signal_bias_r)) ax1.plot(x, mean_signal_bias_f, color='purple', label='Forward') ax1.plot(x, mean_signal_bias_r, color='green', label='Reverse') ax1.text(0.15, 0.9, 'n = {}'.format(num_sites), verticalalignment='bottom', horizontalalignment='right', transform=ax1.transAxes, fontweight='bold') ax1.xaxis.set_ticks_position('bottom') ax1.yaxis.set_ticks_position('left') ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['left'].set_position(('outward', 15)) ax1.spines['bottom'].set_position(('outward', 5)) ax1.tick_params(direction='out') ax1.set_xticks([start, 0, end]) ax1.set_xticklabels([str(start), 0, str(end)]) ax1.set_yticks([min_, max_]) ax1.set_yticklabels([str(round(min_, 2)), str(round(max_, 2))], rotation=90) ax1.set_title(args.output_prefix, fontweight='bold') ax1.set_xlim(start, end) ax1.set_ylim([min_, max_]) ax1.legend(loc="upper right", frameon=False) #################################################################### ##################################################################### # Bias corrected, non-bias corrected (not strand specific) # min_ = min(min(mean_signal_raw_f), min(mean_signal_raw_r)) # max_ = max(max(mean_signal_raw_f), max(mean_signal_raw_r)) # ax2.plot(x, mean_signal_raw_f, color='red', label='Forward') # ax2.plot(x, mean_signal_raw_r, color='green', label='Reverse') # ax2.xaxis.set_ticks_position('bottom') # ax2.yaxis.set_ticks_position('left') # ax2.spines['top'].set_visible(False) # ax2.spines['right'].set_visible(False) # ax2.spines['left'].set_position(('outward', 15)) # ax2.tick_params(direction='out') # ax2.set_xticks([start, -1, 0, 1, end]) # ax2.set_xticklabels([str(start), -1, 0,1, str(end)]) # ax2.set_yticks([min_, max_]) # ax2.set_yticklabels([str(round(min_, 2)), str(round(max_, 2))], rotation=90) # ax2.set_xlim(start, end) # ax2.set_ylim([min_, max_]) # ax2.legend(loc="upper right", frameon=False) ##################################################################### # Bias corrected and strand specific # min_ = min(min(mean_signal_bc_f), min(mean_signal_bc_r)) # max_ = max(max(mean_signal_bc_f), max(mean_signal_bc_r)) # ax3.plot(x, mean_signal_bc_f, color='red', label='Forward') # ax3.plot(x, mean_signal_bc_r, color='green', label='Reverse') # ax3.xaxis.set_ticks_position('bottom') # ax3.yaxis.set_ticks_position('left') # ax3.spines['top'].set_visible(False) # ax3.spines['right'].set_visible(False) # ax3.spines['left'].set_position(('outward', 15)) # ax3.tick_params(direction='out') # ax3.set_xticks([start, 0, end]) # ax3.set_xticklabels([str(start), 0, str(end)]) # ax3.set_yticks([min_, max_]) # ax3.set_yticklabels([str(round(min_, 2)), str(round(max_, 2))], rotation=90) # ax3.set_xlim(start, end) # ax3.set_ylim([min_, max_]) # ax3.legend(loc="upper right", frameon=False) ##################################################################### # Bias corrected, non-bias corrected (not strand specific) min_ = min(min(mean_signal_raw), min(mean_signal_bc)) max_ = max(max(mean_signal_raw), max(mean_signal_bc)) ax4.plot(x, mean_signal_raw, color='blue', label='Uncorrected') ax4.plot(x, mean_signal_bc, color='red', label='Corrected') ax4.xaxis.set_ticks_position('bottom') ax4.yaxis.set_ticks_position('left') ax4.spines['top'].set_visible(False) ax4.spines['right'].set_visible(False) ax4.spines['left'].set_position(('outward', 15)) ax4.tick_params(direction='out') ax4.set_xticks([start, 0, end]) ax4.set_xticklabels([str(start), 0, str(end)]) ax4.set_yticks([min_, max_]) ax4.set_yticklabels([str(round(min_, 2)), str(round(max_, 2))], rotation=90) ax4.set_xlim(start, end) ax4.set_ylim([min_, max_]) ax4.legend(loc="upper right", frameon=False) ax4.spines['bottom'].set_position(('outward', 40)) ############################################################################### # merge the above figures figure_name = os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(args.output_location, "{}.eps".format(args.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.45, 0.89, logo_fname, width=18.3, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) os.remove(pwm_fname) os.remove(os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.line.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.eps".format(args.output_prefix))) def strand_line(args): genomic_signal = GenomicSignal(args.reads_file) genomic_signal.load_sg_coefs(slope_window_size=9) table = None if args.bias_table is not None: bias_table = BiasTable() bias_table_list = args.bias_table.split(",") table = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) genome_data = GenomeData(args.organism) fasta = Fastafile(genome_data.get_genome()) num_sites = 0 mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(args.motif_file) bam = Samfile(args.reads_file, "rb") mean_signal_f = np.zeros(args.window_size) mean_signal_r = np.zeros(args.window_size) pwm_dict = None for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": # Extend by 50 bp mid = (region.initial + region.final) / 2 p1 = mid - (args.window_size / 2) p2 = mid + (args.window_size / 2) if args.bias_table is not None: signal_f, signal_r = genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift) else: signal_f, signal_r = genomic_signal.get_raw_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift) num_sites += 1 mean_signal_f = np.add(mean_signal_f, signal_f) mean_signal_r = np.add(mean_signal_r, signal_r) # Update pwm if pwm_dict is None: pwm_dict = dict([("A", [0.0] * (p2 - p1)), ("C", [0.0] * (p2 - p1)), ("G", [0.0] * (p2 - p1)), ("T", [0.0] * (p2 - p1)), ("N", [0.0] * (p2 - p1))]) aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 dna_seq_rev = AuxiliaryFunctions.revcomp(str(fasta.fetch(region.chrom, p1 + aux_plus, p2 + aux_plus)).upper()) if region.orientation == "+": for i in range(0, len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 elif region.orientation == "-": for i in range(0, len(dna_seq_rev)): pwm_dict[dna_seq_rev[i]][i] += 1 mean_norm_signal_f = genomic_signal.boyle_norm(mean_signal_f) perc = scoreatpercentile(mean_norm_signal_f, 98) std = np.std(mean_norm_signal_f) mean_norm_signal_f = genomic_signal.hon_norm_atac(mean_norm_signal_f, perc, std) mean_norm_signal_r = genomic_signal.boyle_norm(mean_signal_r) perc = scoreatpercentile(mean_norm_signal_r, 98) std = np.std(mean_norm_signal_r) mean_norm_signal_r = genomic_signal.hon_norm_atac(mean_norm_signal_r, perc, std) mean_slope_signal_f = genomic_signal.slope(mean_norm_signal_f, genomic_signal.sg_coefs) mean_slope_signal_r = genomic_signal.slope(mean_norm_signal_r, genomic_signal.sg_coefs) # Output the norm and slope signal output_fname = os.path.join(args.output_location, "{}.txt".format(args.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, mean_norm_signal_f))) + "\n") f.write("\t".join((map(str, mean_slope_signal_f))) + "\n") f.write("\t".join((map(str, mean_norm_signal_r))) + "\n") f.write("\t".join((map(str, mean_slope_signal_r))) + "\n") f.close() # Output PWM and create logo pwm_fname = os.path.join(args.output_location, "{}.pwm".format(args.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(args.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) start = -(args.window_size / 2) end = (args.window_size / 2) - 1 x = np.linspace(start, end, num=args.window_size) fig = plt.figure(figsize=(8, 4)) ax = fig.add_subplot(111) min_signal = min(min(mean_signal_f), min(mean_signal_r)) max_signal = max(max(mean_signal_f), max(mean_signal_r)) ax.plot(x, mean_signal_f, color='red', label='Forward') ax.plot(x, mean_signal_r, color='green', label='Reverse') ax.set_title(args.output_prefix, fontweight='bold') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_position(('outward', 15)) ax.tick_params(direction='out') ax.set_xticks([start, 0, end]) ax.set_xticklabels([str(start), 0, str(end)]) ax.set_yticks([min_signal, max_signal]) ax.set_yticklabels([str(round(min_signal, 2)), str(round(max_signal, 2))], rotation=90) ax.set_xlim(start, end) ax.set_ylim([min_signal, max_signal]) ax.legend(loc="upper right", frameon=False) ax.spines['bottom'].set_position(('outward', 40)) figure_name = os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(args.output_location, "{}.eps".format(args.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.37, 0.89, logo_fname, width=18.5, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) # os.remove(pwm_fname) os.remove(os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.line.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.eps".format(args.output_prefix))) def unstrand_line(args): genomic_signal = GenomicSignal(args.reads_file) genomic_signal.load_sg_coefs(slope_window_size=9) table = None if args.bias_table is not None: bias_table = BiasTable() bias_table_list = args.bias_table.split(",") table = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) genome_data = GenomeData(args.organism) fasta = Fastafile(genome_data.get_genome()) num_sites = 0 mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(args.motif_file) bam = Samfile(args.reads_file, "rb") mean_signal = np.zeros(args.window_size) pwm_dict = None output_fname = os.path.join(args.output_location, "{}.txt".format(args.output_prefix)) with open(output_fname, "w") as output_f: for region in mpbs_regions: mid = (region.initial + region.final) / 2 p1 = mid - (args.window_size / 2) p2 = mid + (args.window_size / 2) if args.bias_table is not None: signal = genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift, strand=False) else: signal = genomic_signal.get_raw_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift, strand=False) if region.orientation == "-": signal = np.flip(signal) name = "{}_{}_{}".format(region.chrom, str(region.initial), str(region.final)) output_f.write(name + "\t" + "\t".join(map(str, map(int, signal))) + "\n") num_sites += 1 mean_signal = np.add(mean_signal, signal) # Update pwm if pwm_dict is None: pwm_dict = dict([("A", [0.0] * (p2 - p1)), ("C", [0.0] * (p2 - p1)), ("G", [0.0] * (p2 - p1)), ("T", [0.0] * (p2 - p1)), ("N", [0.0] * (p2 - p1))]) aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 dna_seq_rev = AuxiliaryFunctions.revcomp( str(fasta.fetch(region.chrom, p1 + aux_plus, p2 + aux_plus)).upper()) if region.orientation == "+": for i in range(0, len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 elif region.orientation == "-": for i in range(0, len(dna_seq_rev)): pwm_dict[dna_seq_rev[i]][i] += 1 mean_signal = mean_signal / num_sites # Output PWM and create logo pwm_fname = os.path.join(args.output_location, "{}.pwm".format(args.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(args.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) start = -(args.window_size / 2) end = (args.window_size / 2) - 1 x = np.linspace(start, end, num=args.window_size) fig = plt.figure(figsize=(8, 4)) ax = fig.add_subplot(111) min_signal = min(mean_signal) max_signal = max(mean_signal) ax.plot(x, mean_signal, color='red') ax.set_title(args.output_prefix, fontweight='bold') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_position(('outward', 15)) ax.tick_params(direction='out') ax.set_xticks([start, 0, end]) ax.set_xticklabels([str(start), 0, str(end)]) ax.set_yticks([min_signal, max_signal]) ax.set_yticklabels([str(round(min_signal, 2)), str(round(max_signal, 2))], rotation=90) ax.set_xlim(start, end) ax.set_ylim([min_signal, max_signal]) ax.legend(loc="upper right", frameon=False) ax.spines['bottom'].set_position(('outward', 40)) figure_name = os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(args.output_location, "{}.eps".format(args.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.31, 0.89, logo_fname, width=18.5, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) os.remove(pwm_fname) os.remove(os.path.join(args.output_location, "{}.line.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.logo.eps".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.line.pdf".format(args.output_prefix))) # os.remove(os.path.join(args.output_location, "{}.logo.pdf".format(args.output_prefix))) os.remove(os.path.join(args.output_location, "{}.eps".format(args.output_prefix))) def fragment_size_raw_line(args): mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(args.motif_file) bam = Samfile(args.reads_file, "rb") signal_f_max_145 = np.zeros(args.window_size) signal_r_max_145 = np.zeros(args.window_size) signal_f_146_307 = np.zeros(args.window_size) signal_r_146_307 = np.zeros(args.window_size) signal_f_min_307 = np.zeros(args.window_size) signal_r_min_307 = np.zeros(args.window_size) signal_f = np.zeros(args.window_size) signal_r = np.zeros(args.window_size) for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": # Extend by 50 bp mid = (region.initial + region.final) / 2 p1 = mid - (args.window_size / 2) p2 = mid + (args.window_size / 2) # Fetch raw signal for read in bam.fetch(region.chrom, p1, p2): # All reads if not read.is_reverse: cut_site = read.pos + args.forward_shift if p1 <= cut_site < p2: signal_f[cut_site - p1] += 1.0 else: cut_site = read.aend + args.reverse_shift - 1 if p1 <= cut_site < p2: signal_r[cut_site - p1] += 1.0 # length <= 145 if abs(read.template_length) <= 145: if not read.is_reverse: cut_site = read.pos + args.forward_shift if p1 <= cut_site < p2: signal_f_max_145[cut_site - p1] += 1.0 else: cut_site = read.aend + args.reverse_shift - 1 if p1 <= cut_site < p2: signal_r_max_145[cut_site - p1] += 1.0 # length > 145 and <= 307 if 145 < abs(read.template_length) <= 307: if not read.is_reverse: cut_site = read.pos + args.forward_shift if p1 <= cut_site < p2: signal_f_146_307[cut_site - p1] += 1.0 else: cut_site = read.aend + args.reverse_shift - 1 if p1 <= cut_site < p2: signal_r_146_307[cut_site - p1] += 1.0 # length > 307 if abs(read.template_length) > 307: if not read.is_reverse: cut_site = read.pos + args.forward_shift if p1 <= cut_site < p2: signal_f_min_307[cut_site - p1] += 1.0 else: cut_site = read.aend + args.reverse_shift - 1 if p1 <= cut_site < p2: signal_r_min_307[cut_site - p1] += 1.0 # Output the norm and slope signal output_fname = os.path.join(args.output_location, "{}.txt".format(args.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, signal_f))) + "\n") f.write("\t".join((map(str, signal_r))) + "\n") f.write("\t".join((map(str, signal_f_max_145))) + "\n") f.write("\t".join((map(str, signal_r_max_145))) + "\n") f.write("\t".join((map(str, signal_f_146_307))) + "\n") f.write("\t".join((map(str, signal_r_146_307))) + "\n") f.write("\t".join((map(str, signal_f_min_307))) + "\n") f.write("\t".join((map(str, signal_r_min_307))) + "\n") f.close() # find out the linker position pos_f_1, pos_r_1, pos_f_2, pos_r_2 = get_linkers_position(signal_f_146_307, signal_r_146_307, signal_f_min_307, signal_r_min_307) p1 = (pos_f_1 - pos_f_2) / 2 + pos_f_2 p2 = p1 + 180 p3 = args.window_size - p2 p4 = args.window_size - p1 fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, figsize=(8, 8)) start = -(args.window_size / 2) end = (args.window_size / 2) - 1 x = np.linspace(start, end, num=args.window_size) x_ticks = [start, p1 - 500, p2 - 500, 0, p3 - 500, p4 - 500, end] update_axes_for_fragment_size_line(ax1, x, x_ticks, start, end, signal_f, signal_r, p1, p2, p3, p4) update_axes_for_fragment_size_line(ax2, x, x_ticks, start, end, signal_f_max_145, signal_r_max_145, p1, p2, p3, p4) update_axes_for_fragment_size_line(ax3, x, x_ticks, start, end, signal_f_146_307, signal_r_146_307, p1, p2, p3, p4) update_axes_for_fragment_size_line(ax4, x, x_ticks, start, end, signal_f_min_307, signal_r_min_307, p1, p2, p3, p4) figure_name = os.path.join(args.output_location, "{}.pdf".format(args.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="pdf", dpi=300) def fragment_size_bc_line(args): mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(args.motif_file) genomic_signal = GenomicSignal(args.reads_file) genomic_signal.load_sg_coefs(11) bam = Samfile(args.reads_file, "rb") genome_data = GenomeData(args.organism) fasta = Fastafile(genome_data.get_genome()) bias_table = BiasTable() bias_table_list = args.bias_table.split(",") table = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) signal_f_max_145 = np.zeros(args.window_size) signal_r_max_145 = np.zeros(args.window_size) signal_f_146_307 = np.zeros(args.window_size) signal_r_146_307 = np.zeros(args.window_size) signal_f_min_307 = np.zeros(args.window_size) signal_r_min_307 = np.zeros(args.window_size) signal_f = np.zeros(args.window_size) signal_r = np.zeros(args.window_size) for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": mid = (region.initial + region.final) / 2 p1 = mid - (args.window_size / 2) p2 = mid + (args.window_size / 2) # All reads signal_bc_f, signal_bc_r = \ genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift, min_length=None, max_length=None, strand=True) # length <= 145 signal_bc_max_145_f, signal_bc_max_145_r = \ genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift, min_length=None, max_length=145, strand=True) # length > 145 and <= 307 signal_bc_146_307_f, signal_bc_146_307_r = \ genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift, min_length=145, max_length=307, strand=True) # length > 307 signal_bc_min_307_f, signal_bc_min_307_r = \ genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=args.forward_shift, reverse_shift=args.reverse_shift, min_length=307, max_length=None, strand=True) signal_f = np.add(signal_f, np.array(signal_bc_f)) signal_r = np.add(signal_r, np.array(signal_bc_r)) signal_f_max_145 = np.add(signal_f_max_145, np.array(signal_bc_max_145_f)) signal_r_max_145 = np.add(signal_r_max_145, np.array(signal_bc_max_145_r)) signal_f_146_307 = np.add(signal_f_146_307, np.array(signal_bc_146_307_f)) signal_r_146_307 = np.add(signal_r_146_307, np.array(signal_bc_146_307_r)) signal_f_min_307 = np.add(signal_f_min_307, np.array(signal_bc_min_307_f)) signal_r_min_307 = np.add(signal_r_min_307, np.array(signal_bc_min_307_r)) # Output the norm and slope signal output_fname = os.path.join(args.output_location, "{}.txt".format(args.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, signal_f))) + "\n") f.write("\t".join((map(str, signal_r))) + "\n") f.write("\t".join((map(str, signal_f_max_145))) + "\n") f.write("\t".join((map(str, signal_r_max_145))) + "\n") f.write("\t".join((map(str, signal_f_146_307))) + "\n") f.write("\t".join((map(str, signal_r_146_307))) + "\n") f.write("\t".join((map(str, signal_f_min_307))) + "\n") f.write("\t".join((map(str, signal_r_min_307))) + "\n") f.close() # find out the linker position pos_f_1, pos_r_1, pos_f_2, pos_r_2 = get_linkers_position(signal_f_146_307, signal_r_146_307, signal_f_min_307, signal_r_min_307) p1 = (pos_f_1 - pos_f_2) / 2 + pos_f_2 p2 = p1 + 180 p3 = args.window_size - p2 p4 = args.window_size - p1 fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, figsize=(8, 8)) start = -(args.window_size / 2) end = (args.window_size / 2) - 1 x = np.linspace(start, end, num=args.window_size) x_ticks = [start, p1 - 500, p2 - 500, 0, p3 - 500, p4 - 500, end] update_axes_for_fragment_size_line(ax1, x, x_ticks, start, end, signal_f, signal_r, p1, p2, p3, p4) update_axes_for_fragment_size_line(ax2, x, x_ticks, start, end, signal_f_max_145, signal_r_max_145, p1, p2, p3, p4) update_axes_for_fragment_size_line(ax3, x, x_ticks, start, end, signal_f_146_307, signal_r_146_307, p1, p2, p3, p4) update_axes_for_fragment_size_line(ax4, x, x_ticks, start, end, signal_f_min_307, signal_r_min_307, p1, p2, p3, p4) figure_name = os.path.join(args.output_location, "{}.pdf".format(args.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="pdf", dpi=300) def update_axes_for_fragment_size_line(ax, x, x_ticks, start, end, signal_f, signal_r, p1, p2, p3, p4): max_signal = max(max(signal_f), max(signal_r)) min_signal = min(min(signal_f), min(signal_r)) ax.plot(x, signal_f, color='red', label='Forward') ax.plot(x, signal_r, color='green', label='Reverse') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_position(('outward', 15)) ax.tick_params(direction='out') ax.set_xticks(x_ticks) ax.set_xticklabels(map(str, x_ticks)) ax.set_xlim(start, end) ax.set_yticks([min_signal, max_signal]) ax.set_yticklabels([str(int(min_signal)), str(int(max_signal))], rotation=90) ax.set_ylim([min_signal, max_signal]) ax.legend().set_visible(False) f_1, r_1 = sum(signal_f[:p1]) / sum(signal_r), sum(signal_r[:p1]) / sum(signal_r) f_2, r_2 = sum(signal_f[p1:p2]) / sum(signal_r), sum(signal_r[p1:p2]) / sum(signal_r) f_3, r_3 = sum(signal_f[p2:500]) / sum(signal_r), sum(signal_r[p2:500]) / sum(signal_r) f_4, r_4 = sum(signal_f[500:p3]) / sum(signal_r), sum(signal_r[500:p3]) / sum(signal_r) f_5, r_5 = sum(signal_f[p3:p4]) / sum(signal_r), sum(signal_r[p3:p4]) / sum(signal_r) f_6, r_6 = sum(signal_f[p4:]) / sum(signal_r), sum(signal_r[p4:]) / sum(signal_r) text_x_1 = ((p1 - 0) / 2.0 + 0) / 1000 text_x_2 = ((p2 - p1) / 2.0 + p1) / 1000 text_x_3 = ((500 - p2) / 2.0 + p2) / 1000 text_x_4 = ((p3 - 500) / 2.0 + 500) / 1000 text_x_5 = ((p4 - p3) / 2.0 + p3) / 1000 text_x_6 = ((1000 - p4) / 2.0 + p4) / 1000 ax.text(text_x_1, 1.0, str(round(f_1, 2)), verticalalignment='center', color='red', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_1, 0.9, str(round(r_1, 2)), verticalalignment='center', color='green', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_2, 1.0, str(round(f_2, 2)), verticalalignment='center', color='red', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_2, 0.9, str(round(r_2, 2)), verticalalignment='center', color='green', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_3, 1.0, str(round(f_3, 2)), verticalalignment='center', color='red', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_3, 0.9, str(round(r_3, 2)), verticalalignment='center', color='green', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_4, 1.0, str(round(f_4, 2)), verticalalignment='center', color='red', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_4, 0.9, str(round(r_4, 2)), verticalalignment='center', color='green', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_5, 1.0, str(round(f_5, 2)), verticalalignment='center', color='red', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_5, 0.9, str(round(r_5, 2)), verticalalignment='center', color='green', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_6, 1.0, str(round(f_6, 2)), verticalalignment='center', color='red', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.text(text_x_6, 0.9, str(round(r_6, 2)), verticalalignment='center', color='green', horizontalalignment='center', transform=ax.transAxes, fontsize=12) def get_linkers_position(signal_f_146_307, signal_r_146_307, signal_f_min_307, signal_r_min_307): smooth_signal_f_146_307 = savgol_filter(signal_f_146_307, window_length=51, polyorder=2) smooth_signal_r_146_307 = savgol_filter(signal_r_146_307, window_length=51, polyorder=2) smooth_signal_f_min_307 = savgol_filter(signal_f_min_307, window_length=51, polyorder=2) smooth_signal_r_min_307 = savgol_filter(signal_r_min_307, window_length=51, polyorder=2) position_f_1 = np.argmax(smooth_signal_f_146_307[:400]) position_f_2 = np.argmax(smooth_signal_f_min_307[:position_f_1]) position_r_1 = np.argmax(smooth_signal_r_146_307[600:]) + 600 position_r_2 = np.argmax(smooth_signal_r_min_307[position_r_1:]) + position_r_1 return position_f_1, position_r_1, position_f_2, position_r_2 def rescaling(vector): maxN = max(vector) minN = min(vector) return [(e - minN) / (maxN - minN) for e in vector] class Plot: def __init__(self, organism, reads_file, motif_file, window_size, downstream_ext, upstream_ext, forward_shift, reverse_shift, initial_clip, bias_table, k_nb, output_loc, output_prefix): self.organism = organism self.reads_file = reads_file self.motif_file = motif_file self.window_size = window_size self.downstream_ext = downstream_ext self.upstream_ext = upstream_ext self.forward_shift = forward_shift self.reverse_shift = reverse_shift self.initial_clip = initial_clip self.bias_table = bias_table self.k_nb = k_nb self.output_loc = output_loc self.output_prefix = output_prefix def line3(self, bias_table1, bias_table2): signal = GenomicSignal(self.reads_file) signal.load_sg_coefs(slope_window_size=9) bias_table = BiasTable() bias_table_list = bias_table1.split(",") table1 = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) bias_table = BiasTable() bias_table_list = bias_table2.split(",") table2 = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) genome_data = GenomeData(self.organism) fasta = Fastafile(genome_data.get_genome()) pwm_dict = dict([("A", [0.0] * self.window_size), ("C", [0.0] * self.window_size), ("G", [0.0] * self.window_size), ("T", [0.0] * self.window_size), ("N", [0.0] * self.window_size)]) num_sites = 0 mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(self.motif_file) bam = Samfile(self.reads_file, "rb") mean_signal_raw = np.zeros(self.window_size) mean_signal_bc1 = np.zeros(self.window_size) mean_signal_bc2 = np.zeros(self.window_size) for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": # Extend by window_size mid = (region.initial + region.final) / 2 p1 = mid - (self.window_size / 2) p2 = mid + (self.window_size / 2) signal_raw, signal_bc1 = \ self.get_signal3(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table1) signal_raw, signal_bc2 = \ self.get_signal3(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table2) num_sites += 1 mean_signal_raw = np.add(mean_signal_raw, np.array(signal_raw)) mean_signal_bc1 = np.add(mean_signal_bc1, np.array(signal_bc1)) mean_signal_bc2 = np.add(mean_signal_bc2, np.array(signal_bc2)) # Update pwm aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 dna_seq_rev = AuxiliaryFunctions.revcomp( str(fasta.fetch(region.chrom, p1 + aux_plus, p2 + aux_plus)).upper()) if region.orientation == "+": for i in range(0, len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 elif region.orientation == "-": for i in range(0, len(dna_seq_rev)): pwm_dict[dna_seq_rev[i]][i] += 1 mean_signal_raw = mean_signal_raw / num_sites mean_signal_bc1 = mean_signal_bc1 / num_sites mean_signal_bc2 = mean_signal_bc2 / num_sites mean_signal_raw = self.rescaling(mean_signal_raw) mean_signal_bc1 = self.rescaling(mean_signal_bc1) mean_signal_bc2 = self.rescaling(mean_signal_bc2) # Output the norm and slope signal output_fname = os.path.join(self.output_loc, "{}.txt".format(self.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, mean_signal_raw))) + "\n") f.write("\t".join((map(str, mean_signal_bc1))) + "\n") f.write("\t".join((map(str, mean_signal_bc2))) + "\n") f.close() # Output PWM and create logo pwm_fname = os.path.join(self.output_loc, "{}.pwm".format(self.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(self.output_loc, "{}.logo.eps".format(self.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(self.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) fig, (ax1, ax2) = plt.subplots(2) start = -(self.window_size / 2) end = (self.window_size / 2) - 1 x = np.linspace(start, end, num=self.window_size) ############################################################ # bias signal per strand min_ = min(mean_signal_raw) max_ = max(mean_signal_raw) ax1.plot(x, mean_signal_raw, color='red') ax1.xaxis.set_ticks_position('bottom') ax1.yaxis.set_ticks_position('left') ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['left'].set_position(('outward', 15)) ax1.spines['bottom'].set_position(('outward', 5)) ax1.tick_params(direction='out') ax1.set_xticks([start, 0, end]) ax1.set_xticklabels([str(start), 0, str(end)]) ax1.set_yticks([min_, max_]) ax1.set_yticklabels([str(round(min_, 2)), str(round(max_, 2))], rotation=90) ax1.set_title(self.output_prefix, fontweight='bold') ax1.set_xlim(start, end) ax1.set_ylim([min_, max_]) ax1.legend(loc="upper right", frameon=False) ax1.set_ylabel("Raw Signal", rotation=90, fontweight='bold') #################################################################### ##################################################################### # Bias corrected, non-bias corrected (not strand specific) min_ = min(min(mean_signal_bc1), min(mean_signal_bc2)) max_ = max(max(mean_signal_bc1), max(mean_signal_bc2)) ax2.plot(x, mean_signal_bc1, color='red', label='VOM_8_NonNaked') ax2.plot(x, mean_signal_bc2, color='green', label='KMER_6_NonNaked') ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('left') ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.spines['left'].set_position(('outward', 15)) ax2.tick_params(direction='out') ax2.set_xticks([start, 0, end]) ax2.set_xticklabels([str(start), 0, str(end)]) ax2.set_yticks([min_, max_]) ax2.set_yticklabels([str(round(min_, 2)), str(round(max_, 2))], rotation=90) ax2.set_xlim(start, end) ax2.set_ylim([min_, max_]) ax2.legend(loc="lower right", frameon=False) ax2.spines['bottom'].set_position(('outward', 40)) ax2.set_xlabel("Coordinates from Motif Center", fontweight='bold') ax2.set_ylabel("Bias Corrected Signal", rotation=90, fontweight='bold') ################################################################################### ############################################################################### # merge the above figures figure_name = os.path.join(self.output_loc, "{}.line.eps".format(self.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(self.output_loc, "{}.eps".format(self.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(2.0, 1.39, logo_fname, width=13.8, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) os.remove(pwm_fname) os.remove(os.path.join(self.output_loc, "{}.line.eps".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.logo.eps".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.line.pdf".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.logo.pdf".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.eps".format(self.output_prefix))) def line4(self): genome_data = GenomeData(self.organism) fasta = Fastafile(genome_data.get_genome()) mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(self.motif_file) bam = Samfile(self.reads_file, "rb") pwm_dict = None signal_raw_f = None signal_raw_r = None num_sites = 0 for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": # Extend by 50 bp mid = (region.initial + region.final) / 2 p1 = mid - (self.window_size / 2) p2 = mid + (self.window_size / 2) # p1 = region.initial - (self.window_size / 2) # p2 = region.final + (self.window_size / 2) size = p2 - p1 if pwm_dict is None: pwm_dict = dict([("A", [0.0] * size), ("C", [0.0] * size), ("G", [0.0] * size), ("T", [0.0] * size), ("N", [0.0] * size)]) if signal_raw_f is None: signal_raw_f = np.zeros(size) if signal_raw_r is None: signal_raw_r = np.zeros(size) # Fetch raw signal for read in bam.fetch(region.chrom, p1, p2): if not read.is_reverse: cut_site = read.pos + self.forward_shift if p1 <= cut_site < p2: signal_raw_f[cut_site - p1] += 1.0 else: cut_site = read.aend + self.reverse_shift - 1 if p1 <= cut_site < p2: signal_raw_r[cut_site - p1] += 1.0 num_sites += 1 # Update pwm aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 dna_seq_rev = AuxiliaryFunctions.revcomp(str(fasta.fetch(region.chrom, p1 + aux_plus, p2 + aux_plus)).upper()) if region.orientation == "+": for i in range(0, len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 elif region.orientation == "-": for i in range(0, len(dna_seq_rev)): pwm_dict[dna_seq_rev[i]][i] += 1 # mean_signal_raw_f = self.rescaling(signal_raw_f) # mean_signal_raw_r = self.rescaling(signal_raw_r) mean_signal_raw_f = signal_raw_f mean_signal_raw_r = signal_raw_r # Output the norm and slope signal output_fname = os.path.join(self.output_loc, "{}.txt".format(self.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, mean_signal_raw_f))) + "\n") f.write("\t".join((map(str, mean_signal_raw_r))) + "\n") f.close() # Output PWM and create logo pwm_fname = os.path.join(self.output_loc, "{}.pwm".format(self.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(self.output_loc, "{}.logo.eps".format(self.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) start = -(size / 2) end = (size / 2) - 1 x = np.linspace(start, end, num=size) fig = plt.figure(figsize=(8, 4)) ax2 = fig.add_subplot(111) min_signal = min(min(mean_signal_raw_f), min(mean_signal_raw_r)) max_signal = max(max(mean_signal_raw_f), max(mean_signal_raw_r)) ax2.plot(x, mean_signal_raw_f, color='red', label='Forward') ax2.plot(x, mean_signal_raw_r, color='green', label='Reverse') ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('left') ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.spines['left'].set_position(('outward', 15)) ax2.tick_params(direction='out') ax2.set_title(self.output_prefix, fontweight='bold') ax2.set_xticks([start, 0, end]) ax2.set_xticklabels([str(start), 0, str(end)]) ax2.set_yticks([min_signal, max_signal]) ax2.set_yticklabels([str(round(min_signal, 2)), str(round(max_signal, 2))], rotation=90) ax2.set_xlim(start, end) ax2.set_ylim([min_signal, max_signal]) ax2.legend(loc="upper right", frameon=False) ax2.spines['bottom'].set_position(('outward', 40)) # ax2.set_xlabel("Coordinates from Motif Center", fontweight='bold') # ax2.set_ylabel("Average Signal", rotation=90, fontweight='bold') figure_name = os.path.join(self.output_loc, "{}.line.eps".format(self.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(self.output_loc, "{}.eps".format(self.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.48, 0.92, logo_fname, width=18.5, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) os.remove(pwm_fname) os.remove(os.path.join(self.output_loc, "{}.line.eps".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.logo.eps".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.line.pdf".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.logo.pdf".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.eps".format(self.output_prefix))) def atac_dnase_bc_line(self, reads_file1, reads_file2, bias_table1, bias_table2): genome_data = GenomeData(self.organism) fasta = Fastafile(genome_data.get_genome()) pwm_dict = dict([("A", [0.0] * self.window_size), ("C", [0.0] * self.window_size), ("G", [0.0] * self.window_size), ("T", [0.0] * self.window_size), ("N", [0.0] * self.window_size)]) bias_table = BiasTable() bias_table_list = bias_table1.split(",") table1 = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) bias_table_list = bias_table2.split(",") table2 = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(self.motif_file) bam_atac = Samfile(reads_file1, "rb") bam_dnase = Samfile(reads_file2, "rb") mean_signal_atac = np.zeros(self.window_size) mean_signal_dnase = np.zeros(self.window_size) num_sites = 0 for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": # Extend by 50 bp mid = (region.initial + region.final) / 2 p1 = mid - (self.window_size / 2) p2 = mid + (self.window_size / 2) # Fetch raw signal signal_atac = self.get_bc_signal(ref=region.chrom, start=p1, end=p2, bam=bam_atac, fasta=fasta, bias_table=table1, forward_shift=5, reverse_shift=-4) signal_dnase = self.get_bc_signal(ref=region.chrom, start=p1, end=p2, bam=bam_dnase, fasta=fasta, bias_table=table2, forward_shift=0, reverse_shift=0) num_sites += 1 mean_signal_atac = np.add(mean_signal_atac, np.array(signal_atac)) mean_signal_dnase = np.add(mean_signal_dnase, np.array(signal_dnase)) # Update pwm aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 dna_seq_rev = AuxiliaryFunctions.revcomp(str(fasta.fetch(region.chrom, p1 + aux_plus, p2 + aux_plus)).upper()) if region.orientation == "+": for i in range(0, len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 elif region.orientation == "-": for i in range(0, len(dna_seq_rev)): pwm_dict[dna_seq_rev[i]][i] += 1 mean_signal_atac = self.rescaling(mean_signal_atac) mean_signal_dnase = self.rescaling(mean_signal_dnase) # Output the norm and slope signal output_fname = os.path.join(self.output_loc, "{}.txt".format(self.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, mean_signal_atac))) + "\n") f.write("\t".join((map(str, mean_signal_dnase))) + "\n") f.close() # Output PWM and create logo pwm_fname = os.path.join(self.output_loc, "{}.pwm".format(self.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(self.output_loc, "{}.logo.eps".format(self.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(self.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) start = -(self.window_size / 2) end = (self.window_size / 2) - 1 x = np.linspace(start, end, num=self.window_size) fig = plt.figure(figsize=(8, 4)) ax2 = fig.add_subplot(111) min_signal = min(min(mean_signal_atac), min(mean_signal_dnase)) max_signal = max(max(mean_signal_atac), max(mean_signal_dnase)) ax2.plot(x, mean_signal_atac, color='red', label='ATAC-seq') ax2.plot(x, mean_signal_dnase, color='green', label='DNase-seq') ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('left') ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.spines['left'].set_position(('outward', 15)) ax2.tick_params(direction='out') ax2.set_title(self.output_prefix, fontweight='bold') ax2.set_xticks([start, 0, end]) ax2.set_xticklabels([str(start), 0, str(end)]) ax2.set_yticks([min_signal, max_signal]) ax2.set_yticklabels([str(round(min_signal, 2)), str(round(max_signal, 2))], rotation=90) ax2.set_xlim(start, end) ax2.set_ylim([min_signal, max_signal]) ax2.legend(loc="upper right", frameon=False) # ax2.legend(loc="lower right", frameon=False) ax2.spines['bottom'].set_position(('outward', 40)) figure_name = os.path.join(self.output_loc, "{}.line.eps".format(self.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(self.output_loc, "{}.eps".format(self.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.51, 0.89, logo_fname, width=18.3, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) os.remove(pwm_fname) os.remove(os.path.join(self.output_loc, "{}.line.eps".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.logo.eps".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.line.pdf".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.logo.pdf".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.eps".format(self.output_prefix))) def get_bc_signal(self, ref, start, end, bam, fasta, bias_table, forward_shift, reverse_shift): # Parameters window = 50 defaultKmerValue = 1.0 # Initialization fBiasDict = bias_table[0] rBiasDict = bias_table[1] k_nb = len(fBiasDict.keys()[0]) p1 = start p2 = end p1_w = p1 - (window / 2) p2_w = p2 + (window / 2) p1_wk = p1_w - int(k_nb / 2.) p2_wk = p2_w + int(k_nb / 2.) currStr = str(fasta.fetch(ref, p1_wk, p2_wk - 1)).upper() currRevComp = AuxiliaryFunctions.revcomp(str(fasta.fetch(ref, p1_wk + 1, p2_wk)).upper()) # Iterating on sequence to create the bias signal signal_bias_f = [] signal_bias_r = [] for i in range(int(k_nb / 2.), len(currStr) - int(k_nb / 2) + 1): fseq = currStr[i - int(k_nb / 2.):i + int(k_nb / 2.)] rseq = currRevComp[len(currStr) - int(k_nb / 2.) - i:len(currStr) + int(k_nb / 2.) - i] try: signal_bias_f.append(fBiasDict[fseq]) except Exception: signal_bias_f.append(defaultKmerValue) try: signal_bias_r.append(rBiasDict[rseq]) except Exception: signal_bias_r.append(defaultKmerValue) # Raw counts signal_raw_f = [0.0] * (p2_w - p1_w) signal_raw_r = [0.0] * (p2_w - p1_w) for read in bam.fetch(ref, p1_w, p2_w): if not read.is_reverse: cut_site = read.pos + self.forward_shift if p1_w <= cut_site < p2_w: signal_raw_f[cut_site - p1_w] += 1.0 else: cut_site = read.aend + self.reverse_shift - 1 if p1_w <= cut_site < p2_w: signal_raw_r[cut_site - p1_w] += 1.0 # Smoothed counts Nf = [] Nr = [] fSum = sum(signal_raw_f[:window]) rSum = sum(signal_raw_r[:window]) fLast = signal_raw_f[0] rLast = signal_raw_r[0] for i in range((window / 2), len(signal_raw_f) - (window / 2)): Nf.append(fSum) Nr.append(rSum) fSum -= fLast fSum += signal_raw_f[i + (window / 2)] fLast = signal_raw_f[i - (window / 2) + 1] rSum -= rLast rSum += signal_raw_r[i + (window / 2)] rLast = signal_raw_r[i - (window / 2) + 1] # Calculating bias and writing to wig file fSum = sum(signal_bias_f[:window]) rSum = sum(signal_bias_r[:window]) fLast = signal_bias_f[0] rLast = signal_bias_r[0] signal_bc = [] for i in range((window / 2), len(signal_bias_f) - (window / 2)): nhatf = Nf[i - (window / 2)] * (signal_bias_f[i] / fSum) nhatr = Nr[i - (window / 2)] * (signal_bias_r[i] / rSum) signal_bc.append(nhatf + nhatr) fSum -= fLast fSum += signal_bias_f[i + (window / 2)] fLast = signal_bias_f[i - (window / 2) + 1] rSum -= rLast rSum += signal_bias_r[i + (window / 2)] rLast = signal_bias_r[i - (window / 2) + 1] return signal_bc def atac_dnase_raw_line(self, reads_file1, reads_file2): genome_data = GenomeData(self.organism) fasta = Fastafile(genome_data.get_genome()) pwm_dict = dict([("A", [0.0] * self.window_size), ("C", [0.0] * self.window_size), ("G", [0.0] * self.window_size), ("T", [0.0] * self.window_size), ("N", [0.0] * self.window_size)]) mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(self.motif_file) bam_atac = Samfile(reads_file1, "rb") bam_dnase = Samfile(reads_file2, "rb") mean_signal_atac = np.zeros(self.window_size) mean_signal_dnase = np.zeros(self.window_size) num_sites = 0 for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": # Extend by 50 bp mid = (region.initial + region.final) / 2 p1 = mid - (self.window_size / 2) p2 = mid + (self.window_size / 2) # Fetch raw signal for read in bam_atac.fetch(region.chrom, p1, p2): if not read.is_reverse: cut_site = read.pos + self.forward_shift if p1 <= cut_site < p2: mean_signal_atac[cut_site - p1] += 1.0 else: cut_site = read.aend + self.reverse_shift - 1 if p1 <= cut_site < p2: mean_signal_atac[cut_site - p1] += 1.0 # Fetch raw signal for read in bam_dnase.fetch(region.chrom, p1, p2): if not read.is_reverse: cut_site = read.pos if p1 <= cut_site < p2: mean_signal_dnase[cut_site - p1] += 1.0 else: cut_site = read.aend - 1 if p1 <= cut_site < p2: mean_signal_dnase[cut_site - p1] += 1.0 num_sites += 1 # Update pwm aux_plus = 1 dna_seq = str(fasta.fetch(region.chrom, p1, p2)).upper() if (region.final - region.initial) % 2 == 0: aux_plus = 0 dna_seq_rev = AuxiliaryFunctions.revcomp(str(fasta.fetch(region.chrom, p1 + aux_plus, p2 + aux_plus)).upper()) if region.orientation == "+": for i in range(0, len(dna_seq)): pwm_dict[dna_seq[i]][i] += 1 elif region.orientation == "-": for i in range(0, len(dna_seq_rev)): pwm_dict[dna_seq_rev[i]][i] += 1 mean_signal_atac = self.rescaling(mean_signal_atac) mean_signal_dnase = self.rescaling(mean_signal_dnase) # Output the norm and slope signal output_fname = os.path.join(self.output_loc, "{}.txt".format(self.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, mean_signal_atac))) + "\n") f.write("\t".join((map(str, mean_signal_dnase))) + "\n") f.close() # Output PWM and create logo pwm_fname = os.path.join(self.output_loc, "{}.pwm".format(self.output_prefix)) pwm_file = open(pwm_fname, "w") for e in ["A", "C", "G", "T"]: pwm_file.write(" ".join([str(int(f)) for f in pwm_dict[e]]) + "\n") pwm_file.close() logo_fname = os.path.join(self.output_loc, "{}.logo.eps".format(self.output_prefix)) pwm = motifs.read(open(pwm_fname), "pfm") pwm.weblogo(logo_fname, format="eps", stack_width="large", stacks_per_line=str(self.window_size), color_scheme="color_classic", unit_name="", show_errorbars=False, logo_title="", show_xaxis=False, xaxis_label="", show_yaxis=False, yaxis_label="", show_fineprint=False, show_ends=False) start = -(self.window_size / 2) end = (self.window_size / 2) - 1 x = np.linspace(start, end, num=self.window_size) fig = plt.figure(figsize=(8, 4)) ax2 = fig.add_subplot(111) min_signal = min(min(mean_signal_atac), min(mean_signal_dnase)) max_signal = max(max(mean_signal_atac), max(mean_signal_dnase)) ax2.plot(x, mean_signal_atac, color='red', label='ATAC-seq') ax2.plot(x, mean_signal_dnase, color='green', label='DNase-seq') ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('left') ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.spines['left'].set_position(('outward', 15)) ax2.tick_params(direction='out') ax2.set_title(self.output_prefix, fontweight='bold') ax2.set_xticks([start, 0, end]) ax2.set_xticklabels([str(start), 0, str(end)]) ax2.set_yticks([min_signal, max_signal]) ax2.set_yticklabels([str(round(min_signal, 2)), str(round(max_signal, 2))], rotation=90) ax2.set_xlim(start, end) ax2.set_ylim([min_signal, max_signal]) ax2.legend(loc="upper right", frameon=False) ax2.spines['bottom'].set_position(('outward', 40)) figure_name = os.path.join(self.output_loc, "{}.line.eps".format(self.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="eps", dpi=300) # Creating canvas and printing eps / pdf with merged results output_fname = os.path.join(self.output_loc, "{}.eps".format(self.output_prefix)) c = pyx.canvas.canvas() c.insert(pyx.epsfile.epsfile(0, 0, figure_name, scale=1.0)) c.insert(pyx.epsfile.epsfile(1.51, 0.89, logo_fname, width=18.3, height=1.75)) c.writeEPSfile(output_fname) os.system("epstopdf " + figure_name) os.system("epstopdf " + logo_fname) os.system("epstopdf " + output_fname) os.remove(pwm_fname) os.remove(os.path.join(self.output_loc, "{}.line.eps".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.logo.eps".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.line.pdf".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.logo.pdf".format(self.output_prefix))) os.remove(os.path.join(self.output_loc, "{}.eps".format(self.output_prefix))) def fragment_size_raw_line(self): mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(self.motif_file) bam = Samfile(self.reads_file, "rb") signal_f_max_145 = np.zeros(self.window_size) signal_r_max_145 = np.zeros(self.window_size) signal_f_146_307 = np.zeros(self.window_size) signal_r_146_307 = np.zeros(self.window_size) signal_f_min_307 = np.zeros(self.window_size) signal_r_min_307 = np.zeros(self.window_size) signal_f = np.zeros(self.window_size) signal_r = np.zeros(self.window_size) for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": # Extend by 50 bp mid = (region.initial + region.final) / 2 p1 = mid - (self.window_size / 2) p2 = mid + (self.window_size / 2) # Fetch raw signal for read in bam.fetch(region.chrom, p1, p2): # All reads if not read.is_reverse: cut_site = read.pos + self.forward_shift if p1 <= cut_site < p2: signal_f[cut_site - p1] += 1.0 else: cut_site = read.aend + self.reverse_shift - 1 if p1 <= cut_site < p2: signal_r[cut_site - p1] += 1.0 # length <= 145 if abs(read.template_length) <= 145: if not read.is_reverse: cut_site = read.pos + self.forward_shift if p1 <= cut_site < p2: signal_f_max_145[cut_site - p1] += 1.0 else: cut_site = read.aend + self.reverse_shift - 1 if p1 <= cut_site < p2: signal_r_max_145[cut_site - p1] += 1.0 # length > 145 and <= 307 if 145 < abs(read.template_length) <= 307: if not read.is_reverse: cut_site = read.pos + self.forward_shift if p1 <= cut_site < p2: signal_f_146_307[cut_site - p1] += 1.0 else: cut_site = read.aend + self.reverse_shift - 1 if p1 <= cut_site < p2: signal_r_146_307[cut_site - p1] += 1.0 # length > 307 if abs(read.template_length) > 307: if not read.is_reverse: cut_site = read.pos + self.forward_shift if p1 <= cut_site < p2: signal_f_min_307[cut_site - p1] += 1.0 else: cut_site = read.aend + self.reverse_shift - 1 if p1 <= cut_site < p2: signal_r_min_307[cut_site - p1] += 1.0 # Output the norm and slope signal output_fname = os.path.join(self.output_loc, "{}.txt".format(self.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, signal_f))) + "\n") f.write("\t".join((map(str, signal_r))) + "\n") f.write("\t".join((map(str, signal_f_max_145))) + "\n") f.write("\t".join((map(str, signal_r_max_145))) + "\n") f.write("\t".join((map(str, signal_f_146_307))) + "\n") f.write("\t".join((map(str, signal_r_146_307))) + "\n") f.write("\t".join((map(str, signal_f_min_307))) + "\n") f.write("\t".join((map(str, signal_r_min_307))) + "\n") f.close() # find out the linker position pos_f_1, pos_r_1, pos_f_2, pos_r_2 = self.get_linkers_position(signal_f_146_307, signal_r_146_307, signal_f_min_307, signal_r_min_307) p1 = (pos_f_1 - pos_f_2) / 2 + pos_f_2 p2 = p1 + 180 p3 = self.window_size - p2 p4 = self.window_size - p1 fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, figsize=(8, 8)) start = -(self.window_size / 2) end = (self.window_size / 2) - 1 x = np.linspace(start, end, num=self.window_size) x_ticks = [start, p1 - 500, p2 - 500, 0, p3 - 500, p4 - 500, end] self.update_axes_for_fragment_size_line(ax1, x, x_ticks, start, end, signal_f, signal_r, p1, p2, p3, p4) self.update_axes_for_fragment_size_line(ax2, x, x_ticks, start, end, signal_f_max_145, signal_r_max_145, p1, p2, p3, p4) self.update_axes_for_fragment_size_line(ax3, x, x_ticks, start, end, signal_f_146_307, signal_r_146_307, p1, p2, p3, p4) self.update_axes_for_fragment_size_line(ax4, x, x_ticks, start, end, signal_f_min_307, signal_r_min_307, p1, p2, p3, p4) figure_name = os.path.join(self.output_loc, "{}.pdf".format(self.output_prefix)) fig.subplots_adjust(bottom=.2, hspace=.5) fig.tight_layout() fig.savefig(figure_name, format="pdf", dpi=300) def fragment_size_bc_line(self, bias_table_files): mpbs_regions = GenomicRegionSet("Motif Predicted Binding Sites") mpbs_regions.read(self.motif_file) genomic_signal = GenomicSignal(self.reads_file) genomic_signal.load_sg_coefs(11) bam = Samfile(self.reads_file, "rb") genome_data = GenomeData(self.organism) fasta = Fastafile(genome_data.get_genome()) bias_table = BiasTable() bias_table_list = bias_table_files.split(",") table = bias_table.load_table(table_file_name_F=bias_table_list[0], table_file_name_R=bias_table_list[1]) signal_f_max_145 = np.zeros(self.window_size) signal_r_max_145 = np.zeros(self.window_size) signal_f_146_307 = np.zeros(self.window_size) signal_r_146_307 = np.zeros(self.window_size) signal_f_min_307 = np.zeros(self.window_size) signal_r_min_307 = np.zeros(self.window_size) signal_f = np.zeros(self.window_size) signal_r = np.zeros(self.window_size) for region in mpbs_regions: if str(region.name).split(":")[-1] == "Y": mid = (region.initial + region.final) / 2 p1 = mid - (self.window_size / 2) p2 = mid + (self.window_size / 2) # All reads signal_bc_f, signal_bc_r = \ genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=self.forward_shift, reverse_shift=self.reverse_shift, min_length=None, max_length=None, strand=True) # length <= 145 signal_bc_max_145_f, signal_bc_max_145_r = \ genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=self.forward_shift, reverse_shift=self.reverse_shift, min_length=None, max_length=145, strand=True) # length > 145 and <= 307 signal_bc_146_307_f, signal_bc_146_307_r = \ genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=self.forward_shift, reverse_shift=self.reverse_shift, min_length=145, max_length=307, strand=True) # length > 307 signal_bc_min_307_f, signal_bc_min_307_r = \ genomic_signal.get_bc_signal_by_fragment_length(ref=region.chrom, start=p1, end=p2, bam=bam, fasta=fasta, bias_table=table, forward_shift=self.forward_shift, reverse_shift=self.reverse_shift, min_length=307, max_length=None, strand=True) signal_f = np.add(signal_f, np.array(signal_bc_f)) signal_r = np.add(signal_r, np.array(signal_bc_r)) signal_f_max_145 = np.add(signal_f_max_145, np.array(signal_bc_max_145_f)) signal_r_max_145 = np.add(signal_r_max_145, np.array(signal_bc_max_145_r)) signal_f_146_307 = np.add(signal_f_146_307, np.array(signal_bc_146_307_f)) signal_r_146_307 = np.add(signal_r_146_307, np.array(signal_bc_146_307_r)) signal_f_min_307 = np.add(signal_f_min_307, np.array(signal_bc_min_307_f)) signal_r_min_307 = np.add(signal_r_min_307, np.array(signal_bc_min_307_r)) # Output the norm and slope signal output_fname = os.path.join(self.output_loc, "{}.txt".format(self.output_prefix)) f = open(output_fname, "w") f.write("\t".join((map(str, signal_f))) + "\n") f.write("\t".join((map(str, signal_r))) + "\n") f.write("\t".join((map(str, signal_f_max_145))) + "\n") f.write("\t".join((map(str, signal_r_max_145))) + "\n") f.write("\t".join((map(str, signal_f_146_307))) + "\n") f.write("\t".join((map(str, signal_r_146_307))) + "\n") f.write("\t".join((map(str, signal_f_min_307))) + "\n") f.write("\t".join((map(str, signal_r_min_307))) + "\n") f.close() # find out the linker position pos_f_1, pos_r_1, pos_f_2, pos_r_2 = self.get_linkers_position(signal_f_146_307, signal_r_146_307, signal_f_min_307, signal_r_min_307) p1 = (pos_f_1 - pos_f_2) / 2 + pos_f_2 p2 = p1 + 180 p3 = self.window_size - p2 p4 = self.window_size - p1 fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, figsize=(8, 8)) start = -(self.window_size / 2) end = (self.window_size / 2) - 1 x =
np.linspace(start, end, num=self.window_size)
numpy.linspace
import math import os import numpy as np import pygame from gym import spaces from gym.utils import seeding from scipy.spatial import distance as ssd from .._utils import Agent FPS = 15 class Archea(Agent): def __init__(self, idx, radius, n_sensors, sensor_range, max_accel, speed_features=True): self._idx = idx self._radius = radius self._n_sensors = n_sensors self._sensor_range = sensor_range self._max_accel = max_accel # Number of observation coordinates from each sensor self._sensor_obscoord = 5 if speed_features: self._sensor_obscoord += 3 self._sensor_obs_coord = self._n_sensors * self._sensor_obscoord self._obs_dim = self._sensor_obs_coord + 2 # +1 for is_colliding_evader, +1 for is_colliding_poison self._position = None self._velocity = None # Generate self._n_sensors angles, evenly spaced from 0 to 2pi # We generate 1 extra angle and remove it because linspace[0] = 0 = 2pi = linspace[-1] angles = np.linspace(0., 2. * np.pi, self._n_sensors + 1)[:-1] # Convert angles to x-y coordinates sensor_vectors = np.c_[np.cos(angles), np.sin(angles)] self._sensors = sensor_vectors @property def observation_space(self): return spaces.Box(low=np.float32(-np.sqrt(2)), high=np.float32(2 * np.sqrt(2)), shape=(self._obs_dim,), dtype=np.float32) @property def action_space(self): return spaces.Box(low=np.float32(-self._max_accel), high=np.float32(self._max_accel), shape=(2,), dtype=np.float32) @property def position(self): assert self._position is not None return self._position @property def velocity(self): assert self._velocity is not None return self._velocity def set_position(self, pos): assert pos.shape == (2,) self._position = pos def set_velocity(self, velocity): assert velocity.shape == (2,) self._velocity = velocity @property def sensors(self): assert self._sensors is not None return self._sensors def sensed(self, object_coord, object_radius, same=False): """Whether object would be sensed by the pursuers""" relative_coord = object_coord - np.expand_dims(self.position, 0) # Projection of object coordinate in direction of sensor sensorvals = self.sensors.dot(relative_coord.T) # Set sensorvals to np.inf when object should not be seen by sensor distance_squared = (relative_coord ** 2).sum(axis=1)[None, :] sensorvals[ (sensorvals < 0) # Wrong direction (by more than 90 degrees in both directions) | (sensorvals - object_radius > self._sensor_range) # Outside sensor range | (distance_squared - sensorvals ** 2 > object_radius ** 2) # Sensor does not intersect object ] = np.inf if same: # Set sensors values for sensing the current object to np.inf sensorvals[:, self._idx - 1] = np.inf return sensorvals def sense_barriers(self, min_pos=0, max_pos=1): sensor_vectors = self.sensors * self._sensor_range # Let's try a different method---polar! # The key insight is that there is a triangle formed when the particle moves outside of the circle # Namely, the triangle with vertices---center, particle, and intersection # So the sides are---position vector, velocity vector, and radius # TODO: get rid of magic number 0.5 position = self.position - 0.5 # We first need the angle formed by center, particle, and particle movement direction # For vectorized calculation, I will use reshape so that all sensors could be calculated together unit_vector_1 = (position / np.linalg.norm(position)).reshape(-1, 1) unit_vector_2 = sensor_vectors / np.linalg.norm(sensor_vectors) dot_product = unit_vector_2 @ unit_vector_1 theta_two = np.arccos(dot_product) # Now we apply the sine law once and find the other angle that we can know theta_one = np.arcsin(np.linalg.norm(position) * np.sin(theta_two) / 0.5) # Finally, we find the last angle # As well as the corresponding triangle side because that tells us where the particle will end up theta_three = np.pi - theta_one - theta_two max_length = np.linalg.norm(position) * np.sin(theta_three) / np.sin(theta_one) clipped_vectors = max_length / np.linalg.norm(sensor_vectors, axis=1).reshape(self._n_sensors, 1) * sensor_vectors # Find the ratio of the clipped sensor vector to the original sensor vector # Scaling the vector by this ratio will limit the end of the vector to the barriers ratios = np.divide(clipped_vectors, sensor_vectors, out=np.ones_like(clipped_vectors), where=np.abs(sensor_vectors) > 0.00000001) # Find the minimum ratio (x or y) of clipped endpoints to original endpoints minimum_ratios = np.amin(ratios, axis=1) # Convert to 2d array of size (n_sensors, 1) sensor_values = np.expand_dims(minimum_ratios, 0) # Set values beyond sensor range to infinity does_sense = minimum_ratios < (1.0 - 1e-4) does_sense = np.expand_dims(does_sense, 0) sensor_values[np.logical_not(does_sense)] = np.inf # Convert -0 to 0 sensor_values[sensor_values == -0] = 0 return sensor_values.T class MAWaterWorld(): def __init__(self, n_pursuers=5, n_evaders=5, n_poison=10, n_coop=2, n_sensors=30, sensor_range=0.2, radius=0.015, obstacle_radius=0.2, obstacle_coord=(0.5, 0.5), pursuer_max_accel=0.01, evader_speed=0.01, poison_speed=0.01, poison_reward=-1.0, food_reward=10.0, encounter_reward=0.01, thrust_penalty=-0.5, local_ratio=1.0, speed_features=True, max_cycles=500): """ n_pursuers: number of pursuing archea (agents) n_evaders: number of evader archea n_poison: number of poison archea n_coop: number of pursuing archea (agents) that must be touching food at the same time to consume it n_sensors: number of sensors on all pursuing archea (agents) sensor_range: length of sensor dendrite on all pursuing archea (agents) radius: archea base radius. Pursuer: radius, evader: 2 x radius, poison: 3/4 x radius obstacle_radius: radius of obstacle object obstacle_coord: coordinate of obstacle object. Can be set to `None` to use a random location pursuer_max_accel: pursuer archea maximum acceleration (maximum action size) evader_speed: evading archea speed poison_speed: poison archea speed poison_reward: reward for pursuer consuming a poison object (typically negative) food_reward:reward for pursuers consuming an evading archea encounter_reward: reward for a pursuer colliding with an evading archea thrust_penalty: scaling factor for the negative reward used to penalize large actions local_ratio: Proportion of reward allocated locally vs distributed globally among all agents speed_features: toggles whether pursuing archea (agent) sensors detect speed of other archea max_cycles: After max_cycles steps all agents will return done """ self.seed() self.n_pursuers = n_pursuers self.n_evaders = n_evaders self.n_coop = n_coop self.n_poison = n_poison self.obstacle_radius = obstacle_radius obstacle_coord = np.array(obstacle_coord) self.initial_obstacle_coord = self.np_random.uniform(0, 1, 2) if obstacle_coord is None else obstacle_coord self.pursuer_max_accel = pursuer_max_accel self.evader_speed = evader_speed self.poison_speed = poison_speed self.radius = radius self.n_sensors = n_sensors self.sensor_range = np.ones(self.n_pursuers) * min(sensor_range, (math.ceil(math.sqrt(2) * 100) / 100.0)) self.poison_reward = poison_reward self.food_reward = food_reward self.thrust_penalty = thrust_penalty self.encounter_reward = encounter_reward self.last_rewards = [np.float64(0) for _ in range(self.n_pursuers)] self.control_rewards = [0 for _ in range(self.n_pursuers)] self.last_dones = [False for _ in range(self.n_pursuers)] self.last_obs = [None for _ in range(self.n_pursuers)] self.n_obstacles = 1 self.local_ratio = local_ratio self._speed_features = speed_features self.max_cycles = max_cycles # TODO: Look into changing hardcoded radius ratios self._pursuers = [ Archea(pursuer_idx + 1, self.radius, self.n_sensors, sensor_range, self.pursuer_max_accel, speed_features=self._speed_features) for pursuer_idx in range(self.n_pursuers) ] self._evaders = [ Archea(evader_idx + 1, self.radius * 2, self.n_pursuers, 0, self.evader_speed) for evader_idx in range(self.n_evaders) ] self._poisons = [ Archea(poison_idx + 1, self.radius * 3 / 4, self.n_poison, 0, self.poison_speed) for poison_idx in range(self.n_poison) ] self.num_agents = self.n_pursuers self.action_space = [agent.action_space for agent in self._pursuers] self.observation_space = [ agent.observation_space for agent in self._pursuers] self.renderOn = False self.pixel_scale = 30 * 25 self.cycle_time = 1.0 * 15. / FPS self.frames = 0 self.reset() def close(self): if self.renderOn: # pygame.event.pump() pygame.display.quit() pygame.quit() @property def agents(self): return self._pursuers def get_param_values(self): return self.__dict__ def seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return [seed] def _generate_coord(self, radius): # sample points in the circle # I use the length-angle method of sampling # There needs to be both a lower bound and upper bound on the length # because we don't want the object to go outside or start where the obstacle is # TODO: get rid of magic numbers here: 0.5 is radius of circle length = self.np_random.uniform(10 * self.radius * (2 ** (1 / 2)), 0.5 - radius * 2) angle = np.pi * self.np_random.uniform(0, 2) x = length * np.cos(angle) y = length * np.sin(angle) coord = np.array([self.initial_obstacle_coord[0] + x, self.initial_obstacle_coord[1] + y]) # Create random coordinate that avoids obstacles while ssd.cdist(coord[None, :], self.obstacle_coords) <= radius * 2 + self.obstacle_radius: length = self.np_random.uniform(10 * self.radius * (2 ** (1 / 2)), 0.5 - radius * 2) angle = np.pi * self.np_random.uniform(0, 2) x = length * np.cos(angle) y = length * np.sin(angle) coord = np.array([self.initial_obstacle_coord[0] + x, self.initial_obstacle_coord[1] + y]) return coord def reset(self): self.frames = 0 # Initialize obstacles if self.initial_obstacle_coord is None: # Generate obstacle positions in range [0, 1) self.obstacle_coords = self.np_random.rand(self.n_obstacles, 2) else: self.obstacle_coords = self.initial_obstacle_coord[None, :] # Set each obstacle's velocity to 0 # TODO: remove if obstacles should never move self.obstacle_speeds = np.zeros((self.n_obstacles, 2)) # Initialize pursuers for pursuer in self._pursuers: pursuer.set_position(self._generate_coord(pursuer._radius)) pursuer.set_velocity(np.zeros(2)) # Initialize evaders for evader in self._evaders: evader.set_position(self._generate_coord(evader._radius)) # Generate velocity such that speed <= self.evader_speed velocity = self.np_random.rand(2) - 0.5 speed = np.linalg.norm(velocity) if speed > self.evader_speed: # Limit speed to self.evader_speed velocity = velocity / speed * self.evader_speed evader.set_velocity(velocity) # Initialize poisons for poison in self._poisons: poison.set_position(self._generate_coord(poison._radius)) # Generate both velocity components from range [-self.poison_speed, self.poison_speed) # Generate velocity such that speed <= self.poison_speed velocity = self.np_random.rand(2) - 0.5 speed = np.linalg.norm(velocity) if speed > self.poison_speed: # Limit speed to self.poison_speed velocity = velocity / speed * self.poison_speed poison.set_velocity(velocity) rewards = np.zeros(self.n_pursuers) sensor_features, collided_pursuer_evader, collided_pursuer_poison, rewards \ = self.collision_handling_subroutine(rewards, True) obs_list = self.observe_list( sensor_features, collided_pursuer_evader, collided_pursuer_poison) self.last_rewards = [np.float64(0) for _ in range(self.n_pursuers)] self.control_rewards = [0 for _ in range(self.n_pursuers)] self.last_dones = [False for _ in range(self.n_pursuers)] self.last_obs = obs_list return obs_list[0] def _caught(self, is_colliding_x_y, n_coop): """ Check whether collision results in catching the object This is because you need `n_coop` agents to collide with the object to actually catch it """ # Number of collisions for each y n_collisions = is_colliding_x_y.sum(axis=0) # List of y that have been caught caught_y = np.where(n_collisions >= n_coop)[0] # Boolean array indicating which x caught any y in caught_y did_x_catch_y = is_colliding_x_y[:, caught_y] # List of x that caught corresponding y in caught_y x_caught_y = np.where(did_x_catch_y >= 1)[0] return caught_y, x_caught_y def _closest_dist(self, closest_object_idx, input_sensorvals): """Closest distances according to `idx`""" sensorvals = [] for pursuer_idx in range(self.n_pursuers): sensors = np.arange(self.n_sensors) # sensor indices objects = closest_object_idx[pursuer_idx, ...] # object indices sensorvals.append(input_sensorvals[pursuer_idx, ..., sensors, objects]) return np.c_[sensorvals] def _extract_speed_features(self, object_velocities, object_sensorvals, sensed_mask): # sensed_mask is a boolean mask of which sensor values detected an object sensorvals = [] for pursuer in self._pursuers: relative_speed = object_velocities - np.expand_dims(pursuer.velocity, 0) sensorvals.append(pursuer.sensors.dot(relative_speed.T)) sensed_speed = np.c_[sensorvals] # Speeds in direction of each sensor speed_features = np.zeros((self.n_pursuers, self.n_sensors)) sensorvals = [] for pursuer_idx in range(self.n_pursuers): sensorvals.append( sensed_speed[pursuer_idx, :, :][np.arange(self.n_sensors), object_sensorvals[pursuer_idx, :]] ) # Set sensed values, all others remain 0 speed_features[sensed_mask] = np.c_[sensorvals][sensed_mask] return speed_features def collision_handling_subroutine(self, rewards, is_last): # Stop pursuers upon hitting a wall for pursuer in self._pursuers: # Here we are trying to clip based on a circle, not a square # Given the current position of the pursuer (outside of the circle) and its velocity, # we want to "pull it back" along the direction of the velocity vector into the circle again # TODO: get rid of the 0.5 magic number # The code below will make a lot more sense if you reference this website # https://codereview.stackexchange.com/questions/86421/line-segment-to-circle-collision-algorithm # The code is optimized so that we find the intersection between the velocity vector and the circle # using vector calculus, and that intersection will be where the pursuer tangents the circle distance = abs(pursuer.position - 0.5) + pursuer._radius # if we are outside the circle if (distance[0] ** 2 + distance[1] ** 2 > 0.5 ** 2): # again, you should reference the link above to make sure this velocity vector makes sense # We are treating the pursuer position as the starting point of the velocity vector if (pursuer.velocity[0] == 0 and pursuer.velocity[1] == 0) or ( pursuer.velocity[0] == -0 and pursuer.velocity[1] == -0): # If this happens then we have no velocity to rely on. # In that case, we just bring the particle back directly towards the center v = 0.5 - pursuer.position else: v = -1 * pursuer.velocity # The determinant of this quadratic equation must always be non-negative because # there will always be an intersection between the velocity and the circle # In fact, there will always be two intersections # We are looking for the closest one, hence the t with the smaller absolute value q = self.initial_obstacle_coord p = pursuer.position a = v.dot(v) b = 2 * v.dot(p - q) c = p.dot(p) + q.dot(q) - 2 * p.dot(q) - 0.5 ** 2 disc = b ** 2 - 4 * a * c assert disc >= 0 sqrt_disc = math.sqrt(disc) sol = [(-b + sqrt_disc) / (2 * a), (-b - sqrt_disc) / (2 * a)] abs_sol = [abs(number) for number in sol] min_abs = min(abs_sol) idx = abs_sol.index(min_abs) t = sol[idx] # The last term is because the pursuer has a radius that we need to account for pursuer.set_position( pursuer.position + t * v + 2 * pursuer._radius / np.linalg.norm(0.5 - pursuer.position) * ( 0.5 - pursuer.position)) pursuer.set_velocity(v) def rebound_particles(particles, n): collisions_particle_obstacle = np.zeros(n) # Particles rebound on hitting an obstacle for idx, particle in enumerate(particles): # We find whether the particle is colliding with any of the four sides our hourglass obstacle # In graphics the four corners are actually 10 * self.radius # However, the collision needs to account for an extra radius length center = self.obstacle_coords[0] topleft = np.array([center[0] - 11 * self.radius, center[1] - 11 * self.radius]) topright = np.array([center[0] + 11 * self.radius, center[1] - 11 * self.radius]) bottomleft =
np.array([center[0] - 11 * self.radius, center[1] + 11 * self.radius])
numpy.array
import torchtext, random, torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from tqdm import tqdm global use_cuda use_cuda = torch.cuda.is_available() device = 0 if use_cuda else -1 TEXT = torchtext.data.Field() train, val, test = torchtext.datasets.LanguageModelingDataset.splits(path=".", train="train.txt", validation="valid.txt", test="valid.txt", text_field=TEXT) TEXT.build_vocab(train, max_size=1000) if False else TEXT.build_vocab(train) TEXT.vocab.load_vectors('glove.840B.300d') train_iter, val_iter, test_iter = torchtext.data.BPTTIterator.splits((train, val, test), batch_size=10, device=device, bptt_len=32, repeat=False) class LSTMLanguageModel(nn.Module): """ lstm with uniform parameter initialization and dropout as per Zaremba et al. 2014 """ def __init__(self, hidden_dim = 100, TEXT = TEXT, batch_size = 10): super(LSTMLanguageModel, self).__init__() self.hidden_dim = hidden_dim self.batch_size = batch_size vocab_size, embedding_dim = TEXT.vocab.vectors.shape self.embeddings = nn.Embedding(vocab_size, embedding_dim) self.embeddings.weight.data.copy_(TEXT.vocab.vectors) self.lstm = nn.LSTM(input_size = embedding_dim, hidden_size = self.hidden_dim, dropout = 0.50) self.linear = nn.Linear(in_features = self.hidden_dim, out_features = vocab_size) self.drop = nn.Dropout(p = 0.50) self.init_lstm_params_uniformly(bound = 0.04) def init_lstm_params_uniformly(self, bound): for layer_params in self.lstm._all_weights: for param in layer_params: if 'weight' in param: init.uniform(self.lstm.__getattr__(param), -bound, bound) def init_hidden(self): direction = 2 if self.lstm.bidirectional else 1 if use_cuda: return (Variable(torch.zeros(direction*self.lstm.num_layers, self.batch_size, self.hidden_dim)).cuda(), Variable(torch.zeros(direction*self.lstm.num_layers, self.batch_size, self.hidden_dim)).cuda()) else: return (Variable(torch.zeros(direction*self.lstm.num_layers, self.batch_size, self.hidden_dim)), Variable(torch.zeros(direction*self.lstm.num_layers, self.batch_size, self.hidden_dim))) def detach_hidden(self, hidden): """ util function to keep down number of graphs """ return tuple([h.detach() for h in hidden]) def forward(self, x, hidden, train = True): """ predict, return hidden state so it can be used to intialize the next hidden state """ embedded = self.embeddings(x) embedded = self.drop(embedded) if train else embedded lstm_output, hdn = self.lstm(embedded, hidden) reshaped = lstm_output.view(-1, lstm_output.size(2)) dropped = self.drop(reshaped) if train else reshaped decoded = self.linear(dropped) logits = F.log_softmax(decoded, dim = 1) return logits, self.detach_hidden(hdn) class Trainer: def __init__(self, train_iter, val_iter): self.train_iter = train_iter self.val_iter = val_iter def string_to_batch(self, string): relevant_split = string.split() # last two words, ignore ___ ids = [self.word_to_id(word) for word in relevant_split] if use_cuda: return Variable(torch.LongTensor(ids)).cuda() else: return Variable(torch.LongTensor(ids)) def word_to_id(self, word, TEXT = TEXT): return TEXT.vocab.stoi[word] def batch_to_input(self, batch): ngrams = self.collect_batch_ngrams(batch) x = Variable(torch.LongTensor([ngram[:-1] for ngram in ngrams])) y = Variable(torch.LongTensor([ngram[-1] for ngram in ngrams])) if use_cuda: return x.cuda(), y.cuda() else: return x, y def collect_batch_ngrams(self, batch, n = 3): data = batch.text.view(-1).data.tolist() return [tuple(data[idx:idx + n]) for idx in range(0, len(data) - n + 1)] def train_model(self, model, num_epochs): parameters = filter(lambda p: p.requires_grad, model.parameters()) optimizer = torch.optim.Adam(params = parameters, lr=1e-3) criterion = nn.NLLLoss() for epoch in tqdm_notebook(range(num_epochs)): epoch_loss = [] hidden = model.init_hidden() model.train() for batch in tqdm_notebook(train_iter): x, y = batch.text, batch.target.view(-1) if use_cuda: x, y = x.cuda(), y.cuda() optimizer.zero_grad() y_pred, hidden = model.forward(x, hidden, train = True) loss = criterion(y_pred, y) loss.backward() torch.nn.utils.clip_grad_norm(model.lstm.parameters(), 1) optimizer.step() epoch_loss.append(loss.data[0]) model.eval() train_ppl = np.exp(np.mean(epoch_loss)) val_ppl = self.validate(model) print('Epoch {0} | Loss: {1} | Train PPL: {2} | Val PPL: {3}'.format(epoch+1, np.mean(epoch_loss), train_ppl, val_ppl)) print('Model trained.') self.write_kaggle(model) print('Output saved.') def validate(self, model): criterion = nn.NLLLoss() hidden = model.init_hidden() aggregate_loss = [] for batch in val_iter: y_p, _ = model.forward(batch.text, hidden, train = False) y_t = batch.target.view(-1) loss = criterion(y_p, y_t) aggregate_loss.append(loss.data[0]) val_ppl = np.exp(
np.mean(aggregate_loss)
numpy.mean
import unittest import numpy as np from girth.factoranalysis import sparsify_loadings from girth.common import procrustes_rotation class TestRotation(unittest.TestCase): """Test fixture for testing Rotation.""" def test_rotation_orthogonal(self): """Testing recovery of orthogonal rotation.""" rotation_angle = np.radians(37.4) cos_theta, sin_theta = np.cos(rotation_angle), np.sin(rotation_angle) rotation = np.array([[cos_theta, -sin_theta], [sin_theta, cos_theta]]) # Uncorrelated Loadings real_loadings = np.array([1, 0] * 5 + [0, 1]* 5).reshape(10, 2) rotated_loadings = real_loadings @ rotation loadings, bases = sparsify_loadings(rotated_loadings, seed=51743549, orthogonal=True) procrust_adjustment = procrustes_rotation(real_loadings, loadings) rotation_determinate = np.linalg.det(procrust_adjustment) self.assertAlmostEqual(rotation_determinate, 1.0, 5)
np.testing.assert_allclose(bases, rotation @ procrust_adjustment, rtol=1e-4, atol=1e-4)
numpy.testing.assert_allclose
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class ReduceMean(Base): @staticmethod def export_do_not_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 0 node = onnx.helper.make_node( 'ReduceMean', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[12.5, 1.5] # [35., 1.5] # [57.5, 1.5]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_do_not_keepdims_random') @staticmethod def export_keepdims(): # type: () -> None shape = [3, 2, 2] axes = [1] keepdims = 1 node = onnx.helper.make_node( 'ReduceMean', inputs=['data'], outputs=['reduced'], axes=axes, keepdims=keepdims) data = np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) #print(reduced) #[[[12.5, 1.5]] # [[35., 1.5]] # [[57.5, 1.5]]] expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_example') np.random.seed(0) data = np.random.uniform(-10, 10, shape).astype(np.float32) reduced = np.mean(data, axis=tuple(axes), keepdims=keepdims == 1) expect(node, inputs=[data], outputs=[reduced], name='test_reduce_mean_keepdims_random') @staticmethod def export_default_axes_keepdims(): # type: () -> None shape = [3, 2, 2] axes = None keepdims = 1 node = onnx.helper.make_node( 'ReduceMean', inputs=['data'], outputs=['reduced'], keepdims=keepdims) data =
np.array([[[5, 1], [20, 2]], [[30, 1], [40, 2]], [[55, 1], [60, 2]]], dtype=np.float32)
numpy.array
# Copyright 2013 <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 numpy as np from SparseArray import SparseArray import json import os import gzip def line_iterator(filename): if filename.endswith(".gz"): f = gzip.GzipFile(filename) else: try: f = open(filename, encoding='utf8') except TypeError: f = open(filename) while True: line = f.readline() # Test the type of the line and encode it if neccesary... if type(line) is bytes: try: line = str(line, encoding='utf8') except TypeError: line = str(line) # If the line is empty, we are done... if len(line) == 0: break line = line.strip() # If line is empty, jump to next... if len(line) == 0: continue yield line # Close the file... f.close() def json_iterator(filename): for line in line_iterator(filename): yield json.loads(line) def tonparray(a): return np.array(a.full_array()) def BER(y, yh): u = np.unique(y) b = 0 for cl in u: m = y == cl b += (~(y[m] == yh[m])).sum() / float(m.sum()) return (b / float(u.shape[0])) * 100. def RSE(x, y): return ((x - y)**2).sum() / ((x - x.mean())**2).sum() params_fname = os.path.join(os.path.dirname(__file__), 'conf', 'parameter_values.json') with open(params_fname, 'r') as fpt: PARAMS = json.loads(fpt.read()) class Inputs(object): def __init__(self): self._word2id = {} self._label2id = {} @property def word2id(self): return self._word2id @property def label2id(self): return self._label2id @word2id.setter def word2id(self, s): self._word2id = s @label2id.setter def label2id(self, s): self._label2id = s @staticmethod def _num_terms(a): if 'num_terms' in a: num_terms = a['num_terms'] else: num_terms = len(a) if 'klass' in a: num_terms -= 1 return num_terms def convert(self, x): try: return float(x) except ValueError: if x not in self.word2id: self.word2id[x] = len(self.word2id) return self.word2id[x] def convert_label(self, x): try: x = float(x) if
np.isfinite(x)
numpy.isfinite
# Copyright 2018 The Exoplanet ML Authors. # # 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. """Beam DoFns for running Box Least Squares and processing the output.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import apache_beam as beam from apache_beam.metrics import Metrics import numpy as np from box_least_squares import box_least_squares_pb2 as bls_pb2 from box_least_squares.python import box_least_squares from experimental.beam.transit_search import bls_scorer from light_curve import light_curve_pb2 def _max_duration(period, density_star): return (period * 365.25**2 / (np.pi**3 * density_star * 215**3))**(1 / 3) class GeneratePeriodogramDoFn(beam.DoFn): """Generates the BLS periodogram for a light curve.""" def __init__(self, all_periods, all_nbins, weight_min_factor, duration_density_min, duration_min_days, duration_density_max, duration_min_fraction): """Initializes the DoFn.""" self.all_periods = all_periods self.all_nbins = all_nbins self.max_nbins = max(self.all_nbins) self.weight_min_factor = weight_min_factor self.duration_density_min = duration_density_min self.duration_min_days = duration_min_days self.duration_density_max = duration_density_max self.duration_min_fraction = duration_min_fraction def process(self, inputs): """Generates the BLS periodogram for a light curve. Args: inputs: A tuple (key, light_curve_pb2.LightCurve) Yields: A tuple (key, box_least_squares_pb2.Periodogram) """ Metrics.counter(self.__class__.__name__, "inputs-seen").inc() # Unpack the light curve. lc = inputs["light_curve"] time =
np.array(lc.light_curve.time, dtype=np.float)
numpy.array
import json from pprint import pprint import jsonlines import numpy as np def classify_entail_cnfd(logits_a, logits_b): return np.sign(logits_a[:, 0] - logits_b[:, 0]) def classify_contra_cnfd(logits_a, logits_b): return
np.sign(logits_b[:, 2] - logits_a[:, 2])
numpy.sign
# coding=utf-8 """ This module contains methods for accessing a static simulator mocked through a data file. """ from typing import Dict, Any, List, Tuple, Optional from warnings import warn import numpy as np from acnportal.acnsim.interface import ( Interface, SessionInfo, InfrastructureInfo, Constraint, ) from acnportal.algorithms import infrastructure_constraints_feasible class TestingInterface(Interface): """ Static interface based on an attributes dict for testing algorithms without a full environment. """ data: Dict[str, Any] def __init__(self, data: Dict[str, Any]) -> None: super().__init__(None) self.data = data def _get_or_error(self, field: str) -> Any: if field in self.data: return self.data[field] else: raise NotImplementedError(f"No data provided for {field}.") @property def last_applied_pilot_signals(self) -> Dict[str, float]: """ Return the pilot signals that were applied in the last _iteration of the simulation for all active EVs. Does not include EVs that arrived in the current _iteration. Returns: Dict[str, number]: A dictionary with the session ID as key and the pilot signal as value. """ return self._get_or_error("last_applied_pilot_signals") @property def last_actual_charging_rate(self) -> Dict[str, float]: """ Return the actual charging rates in the last period for all active EVs. Returns: Dict[str, number]: A dictionary with the session ID as key and actual charging rate as value. """ return self._get_or_error("last_actual_charging_rate") @property def current_time(self) -> int: """ Get the current time (the current _iteration) of the simulator. Returns: int: The current _iteration of the simulator. """ return self._get_or_error("current_time") @property def period(self) -> float: """ Return the length of each timestep in the simulation. Returns: int: Length of each time interval in the simulation. [minutes] """ return self._get_or_error("period") def active_sessions(self) -> List[SessionInfo]: """ Return a list of SessionInfo objects describing the currently charging EVs. Returns: List[SessionInfo]: List of currently active charging sessions. """ active_sessions = self._get_or_error("active_sessions") return [ SessionInfo(current_time=self.current_time, **session) for session in active_sessions ] def infrastructure_info(self) -> InfrastructureInfo: """ Returns an InfrastructureInfo object generated from interface. Returns: InfrastructureInfo: A description of the charging infrastructure. """ infrastructure = self._get_or_error("infrastructure_info") return InfrastructureInfo( np.array(infrastructure["constraint_matrix"]), np.array(infrastructure["constraint_limits"]), np.array(infrastructure["phases"]), np.array(infrastructure["voltages"]), infrastructure["constraint_ids"], infrastructure["station_ids"], np.array(infrastructure["max_pilot"]), np.array(infrastructure["min_pilot"]), [np.array(allowable) for allowable in infrastructure["allowable_pilots"]], np.array(infrastructure["is_continuous"]), ) def allowable_pilot_signals(self, station_id: str) -> Tuple[bool, List[float]]: """ Returns the allowable pilot signal levels for the specified EVSE. One may assume an EVSE pilot signal of 0 is allowed regardless of this function's return values. Args: station_id (str): The ID of the station for which the allowable rates should be returned. Returns: bool: If the range is continuous or not list[float]: The sorted set of acceptable pilot signals. If continuous this range will have 2 values the min and the max acceptable values. [A] """ infrastructure = self._get_or_error("infrastructure_info") i = infrastructure["station_ids"].index(station_id) return ( infrastructure["is_continuous"][i], infrastructure["allowable_pilots"][i], ) def max_pilot_signal(self, station_id: str) -> float: """ Returns the maximum allowable pilot signal level for the specified EVSE. Args: station_id (str): The ID of the station for which the allowable rates should be returned. Returns: float: the maximum pilot signal supported by this EVSE. [A] """ infrastructure = self._get_or_error("infrastructure_info") i = infrastructure["station_ids"].index(station_id) return infrastructure["max_pilot"][i] def min_pilot_signal(self, station_id: str) -> float: """ Returns the minimum allowable pilot signal level for the specified EVSE. Args: station_id (str): The ID of the station for which the allowable rates should be returned. Returns: float: the minimum pilot signal supported by this EVSE. [A] """ infrastructure = self._get_or_error("infrastructure_info") i = infrastructure["station_ids"].index(station_id) return infrastructure["min_pilot"][i] def evse_voltage(self, station_id: str) -> float: """ Returns the voltage of the EVSE. Args: station_id (str): The ID of the station for which the allowable rates should be returned. Returns: float: voltage of the EVSE. [V] """ infrastructure = self._get_or_error("infrastructure_info") i = infrastructure["station_ids"].index(station_id) return infrastructure["voltages"][i] def evse_phase(self, station_id: str) -> float: """ Returns the phase angle of the EVSE. Args: station_id (str): The ID of the station for which the allowable rates should be returned. Returns: float: phase angle of the EVSE. [degrees] """ infrastructure = self._get_or_error("infrastructure_info") i = infrastructure["station_ids"].index(station_id) return infrastructure["phases"][i] def get_constraints(self) -> Constraint: """ Get the constraint matrix and corresponding EVSE ids for the network. Returns: np.ndarray: Matrix representing the constraints of the network. Each row is a constraint and each """ infrastructure = self._get_or_error("infrastructure_info") return Constraint(
np.array(infrastructure["constraint_matrix"])
numpy.array
""" Classes and functions for generalized q-sampling """ import numpy as np import dipy.reconst.recspeed as rp from dipy.data import get_sphere import os from os.path import join as opj class GeneralizedQSampling(): """ Implements Generalized Q-Sampling Generates a model-free description for every voxel that can be used from simple to very complicated configurations like quintuple crossings if your datasets support them. You can use this class for every kind of DWI image but it will perform much better when you have a balanced sampling scheme. Implements equation [9] from Generalized Q-Sampling as described in <NAME>, <NAME>, <NAME>. Generalized Q-Sampling Imaging. IEEE TMI, 2010. Parameters ----------- data : array, shape(X,Y,Z,D) bvals : array, shape (N,) gradients : array, shape (N,3) also known as bvecs Lambda : float, smoothing parameter - diffusion sampling length Key Properties --------------- QA : array, shape(X,Y,Z,5), quantitative anisotropy IN : array, shape(X,Y,Z,5), indices of QA, qa unit directions fwd : float, normalization parameter Notes ------- In order to reconstruct the spin distribution function a nice symmetric evenly distributed sphere is provided using 362 or 642 points. This is usually sufficient for most of the datasets. See also ---------- dipy.tracking.propagation.EuDX, dipy.reconst.dti.Tensor, dipy.data.get_sphere """ def __init__(self,data,bvals,gradients,Lambda=1.2,odfsphere=None,mask=None): """ Generates a model-free description for every voxel that can be used from simple to very complicated configurations like quintuple crossings if your datasets support them. You can use this class for every kind of DWI image but it will perform much better when you have a balanced sampling scheme. Implements equation [9] from Generalized Q-Sampling as described in <NAME>, <NAME>, <NAME>. Generalized Q-Sampling Imaging. IEEE TMI, 2010. Parameters ----------- data: array, shape(X,Y,Z,D) bvals: array, shape (N,) gradients: array, shape (N,3) also known as bvecs Lambda: float, smoothing parameter - diffusion sampling length Key Properties --------------- QA : array, shape(X,Y,Z,5), quantitative anisotropy IN : array, shape(X,Y,Z,5), indices of QA, qa unit directions fwd : float, normalization parameter Notes ------- In order to reconstruct the spin distribution function a nice symmetric evenly distributed sphere is provided using 362 points. This is usually sufficient for most of the datasets. See also ---------- dipy.tracking.propagation.EuDX, dipy.reconst.dti.Tensor, dipy.data.__init__.get_sphere """ if odfsphere == None: eds = eds=np.load(get_sphere('symmetric362')) odf_vertices=eds['vertices'] odf_faces=eds['faces'] self.odf_vertices=odf_vertices # 0.01506 = 6*D where D is the free water diffusion coefficient # l_values sqrt(6 D tau) D free water diffusion coefficient and # tau included in the b-value scaling = np.sqrt(bvals*0.01506) tmp=
np.tile(scaling, (3,1))
numpy.tile
''' @author: <NAME> ''' import numpy as np import random import pandas as pd import gensim import nltk from gensim.utils import simple_preprocess from gensim.parsing.preprocessing import STOPWORDS from nltk.stem import WordNetLemmatizer, SnowballStemmer from nltk.stem.porter import * import ssl from scipy.stats import * from scipy.special import gamma, gammaln, psi import sys from sys import argv from pathlib import Path import time import json from resource import getrusage as resource_usage, RUSAGE_SELF from functools import reduce import matplotlib.pyplot as plt from statistics import mode from itertools import chain import csv def getopts(argv): opts = {} while argv: if argv[0] == '-docpath': opts[argv[0][1:]] = argv[1] elif argv[0] == '-idpath': opts[argv[0][1:]] = argv[1] elif argv[0] == '-K': opts[argv[0][1:]] = int(argv[1]) elif argv[0] == '-alpha': opts[argv[0][1:]] = float(argv[1]) elif argv[0] == '-beta': opts[argv[0][1:]] = float(argv[1]) elif argv[0] == '-num_samples': opts[argv[0][1:]] = int(argv[1]) elif argv[0] == '-ident': opts[argv[0][1:]] = argv[1] elif argv[0] == '-num_warmup': opts[argv[0][1:]] = argv[1] argv = argv[1:] return opts class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() return json.JSONEncoder.default(self, obj) def gibbs_sampling(num_iter, num_warmup, num_topic, num_vocab, documents, alpha, eta): num_doc = len(documents) topicAssignments = {} # initialize counter c_tw = np.zeros([num_topic, num_vocab]) # count topic to words c_dt = np.zeros([num_doc, num_topic]) # count docs to topics c_t = np.zeros(num_topic) # accumulative c_tw (helper count: can be calculated from c_tw np.sum(c_dt[t,:])) c_d = np.zeros(num_doc) # accumulative c_dt (helper count: can be calculated from c_dt np.sum(c_dt[d,:])) # initialize the parameters of distributions theta = [] sample_theta = np.zeros([num_doc, num_topic]) beta = [] sample_beta = np.zeros([num_topic, num_vocab]) topic_assignments = [] # Calculate counts and sample topic assignment (cat) randomly for i, d in enumerate(documents): doc_size = len(documents[d]) cat = np.random.randint(0,num_topic, size = doc_size) topicAssignments[i] = cat for j, w in enumerate(documents[d]): c_t[cat[j]] += 1 c_d[i] += 1 c_tw[cat[j],w] += 1 c_dt[i, cat[j]] += 1 likelihood = 0 for i, _ in enumerate(documents): likelihood += ((gammaln(num_topic*alpha) + np.sum(gammaln(c_dt[i] + alpha))) - (num_topic * gammaln(alpha) + gammaln(np.sum(c_dt[i] + alpha)))) for t in range(num_topic): likelihood += ((gammaln(num_vocab*eta) + np.sum(gammaln(c_tw[t] + eta)))- (num_vocab * gammaln(eta) + gammaln(
np.sum(c_tw[t] + eta)
numpy.sum
#generic import import numpy as np import sys #mne import from mne import Epochs, pick_types from mne.io import concatenate_raws from mne.io.edf import read_raw_edf from mne.datasets import eegbci from mne.event import find_events from mne.decoding import CSP #pyriemann import from pyriemann.classification import MDM,FgMDM from pyriemann.tangentspace import TangentSpace from pyriemann.estimation import covariances #sklearn imports from sklearn.cross_validation import cross_val_score, KFold from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.lda import LDA ############################################################################### ## Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = 1., 2. event_id = dict(hands=2, feet=3) subject = 7 runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [read_raw_edf(f, preload=True) for f in eegbci.load_data(subject, runs)] raw = concatenate_raws(raw_files) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') #subsample elecs picks = picks[::2] # Apply band-pass filter raw.filter(7., 35., method='iir',picks=picks) events = find_events(raw, shortest_event=0, stim_channel='STI 014') # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier epochs = Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=None, preload=True, add_eeg_ref=False,verbose = False) labels = epochs.events[:, -1] - 2 # cross validation cv = KFold(len(labels),10, shuffle=True, random_state=42) # get epochs epochs_data_train = epochs.get_data() # compute covariance matrices cov_data_train = covariances(epochs_data_train) ############################################################################### # Classification with Minimum distance to mean mdm = MDM() # Use scikit-learn Pipeline with cross_val_score function scores = cross_val_score(mdm, cov_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance = np.mean(labels == labels[0]) class_balance = max(class_balance, 1. - class_balance) print("MDM Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)) ############################################################################### # Classification with Tangent Space Logistic Regression ts = TangentSpace(metric='riemann') lr = LogisticRegression(penalty='l2') clf = Pipeline([('TS', ts), ('LR', lr)]) # Use scikit-learn Pipeline with cross_val_score function scores = cross_val_score(clf, cov_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance = np.mean(labels == labels[0]) class_balance = max(class_balance, 1. - class_balance) print("TS + LR Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)) ############################################################################### # Classification with CSP + linear discrimant analysis # Assemble a classifier lda = LDA() csp = CSP(n_components=4, reg='lws', log=True) clf = Pipeline([('CSP', csp), ('LDA', lda)]) scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance =
np.mean(labels == labels[0])
numpy.mean
import numpy as np import numpy.linalg as la import pdb class Map(): """map object Attributes: getGlobalPosition: convert position from (s, ey) to (X,Y) """ def __init__(self, halfWidth): """Initialization halfWidth: track halfWidth Modify the vector spec to change the geometry of the track """ # Goggle-shaped track # self.slack = 0.15 # self.halfWidth = halfWidth # spec = np.array([[60 * 0.03, 0], # [80 * 0.03, -80 * 0.03 * 2 / np.pi], # # Note s = 1 * np.pi / 2 and r = -1 ---> Angle spanned = np.pi / 2 # [20 * 0.03, 0], # [80 * 0.03, -80 * 0.03 * 2 / np.pi], # [40 * 0.03, +40 * 0.03 * 10 / np.pi], # [60 * 0.03, -60 * 0.03 * 5 / np.pi], # [40 * 0.03, +40 * 0.03 * 10 / np.pi], # [80 * 0.03, -80 * 0.03 * 2 / np.pi], # [20 * 0.03, 0], # [80 * 0.03, -80 * 0.03 * 2 / np.pi]]) # L-shaped track self.halfWidth = 0.45 self.slack = 0.45 lengthCurve = 4.5 spec = np.array([[1.0, 0], [lengthCurve, lengthCurve / np.pi], # Note s = 1 * np.pi / 2 and r = -1 ---> Angle spanned = np.pi / 2 [lengthCurve / 2, -lengthCurve / np.pi], [lengthCurve, lengthCurve / np.pi], [lengthCurve / np.pi * 2, 0], [lengthCurve / 2, lengthCurve / np.pi]]) # spec = np.array([[1.0, 0], # [lengthCurve, lengthCurve / np.pi], # # Note s = 1 * np.pi / 2 and r = -1 ---> Angle spanned = np.pi / 2 # [lengthCurve / 4, lengthCurve / (2 * np.pi)], # [lengthCurve / 4, - lengthCurve / (2 * np.pi)], # [lengthCurve / np.pi * 2, 0], # [lengthCurve / 2, lengthCurve / np.pi]]) # Oval track # spec = np.array([[2.0, 0], # [4.5, -4.5 / np.pi], # # Note s = 1 * np.pi / 2 and r = -1 ---> Angle spanned = np.pi / 2 # [4.0, 0], # [4.5, -4.5 / np.pi], # [2.0, 0]]) # Now given the above segments we compute the (x, y) points of the track and the angle of the tangent vector (psi) at # these points. For each segment we compute the (x, y, psi) coordinate at the last point of the segment. Furthermore, # we compute also the cumulative s at the starting point of the segment at signed curvature # PointAndTangent = [x, y, psi, cumulative s, segment length, signed curvature] ######################################################## #SS: Need to do something to mark the coordinate points of the lane boundaries. #SS: Use OpenCV to measure attitude of the car w.r.t. the lane boundary angle. ######################################################### PointAndTangent = np.zeros((spec.shape[0] + 1, 6)) for i in range(0, spec.shape[0]): if spec[i, 1] == 0.0: # If the current segment is a straight line l = spec[i, 0] # Length of the segments if i == 0: ang = 0 # Angle of the tangent vector at the starting point of the segment x = 0 + l * np.cos(ang) # x coordinate of the last point of the segment y = 0 + l * np.sin(ang) # y coordinate of the last point of the segment else: ang = PointAndTangent[i - 1, 2] # Angle of the tangent vector at the starting point of the segment x = PointAndTangent[i-1, 0] + l * np.cos(ang) # x coordinate of the last point of the segment y = PointAndTangent[i-1, 1] + l * np.sin(ang) # y coordinate of the last point of the segment psi = ang # Angle of the tangent vector at the last point of the segment if i == 0: NewLine = np.array([x, y, psi, PointAndTangent[i, 3], l, 0]) else: NewLine = np.array([x, y, psi, PointAndTangent[i-1, 3] + PointAndTangent[i-1, 4], l, 0]) PointAndTangent[i, :] = NewLine # Write the new info else: l = spec[i, 0] # Length of the segment r = spec[i, 1] # Radius of curvature if r >= 0: direction = 1 else: direction = -1 if i == 0: ang = 0 # Angle of the tangent vector at the # starting point of the segment CenterX = 0 \ + np.abs(r) * np.cos(ang + direction * np.pi / 2) # x coordinate center of circle CenterY = 0 \ + np.abs(r) * np.sin(ang + direction * np.pi / 2) # y coordinate center of circle else: ang = PointAndTangent[i - 1, 2] # Angle of the tangent vector at the # starting point of the segment CenterX = PointAndTangent[i-1, 0] \ + np.abs(r) * np.cos(ang + direction * np.pi / 2) # x coordinate center of circle CenterY = PointAndTangent[i-1, 1] \ + np.abs(r) * np.sin(ang + direction * np.pi / 2) # y coordinate center of circle spanAng = l / np.abs(r) # Angle spanned by the circle psi = wrap(ang + spanAng * np.sign(r)) # Angle of the tangent vector at the last point of the segment angleNormal = wrap((direction * np.pi / 2 + ang)) angle = -(np.pi - np.abs(angleNormal)) * (sign(angleNormal)) x = CenterX + np.abs(r) * np.cos( angle + direction * spanAng) # x coordinate of the last point of the segment y = CenterY + np.abs(r) * np.sin( angle + direction * spanAng) # y coordinate of the last point of the segment if i == 0: NewLine = np.array([x, y, psi, PointAndTangent[i, 3], l, 1 / r]) else: NewLine = np.array([x, y, psi, PointAndTangent[i-1, 3] + PointAndTangent[i-1, 4], l, 1 / r]) PointAndTangent[i, :] = NewLine # Write the new info # plt.plot(x, y, 'or') xs = PointAndTangent[-2, 0] ys = PointAndTangent[-2, 1] xf = 0 yf = 0 psif = 0 # plt.plot(xf, yf, 'or') # plt.show() l = np.sqrt((xf - xs) ** 2 + (yf - ys) ** 2) NewLine = np.array([xf, yf, psif, PointAndTangent[-2, 3] + PointAndTangent[-2, 4], l, 0]) PointAndTangent[-1, :] = NewLine self.PointAndTangent = PointAndTangent self.TrackLength = PointAndTangent[-1, 3] + PointAndTangent[-1, 4] ####################### #SS: Dont need this section. Save actual coordinate position of the car. #SS: Save ey, s, ####################### def getGlobalPosition(self, s, ey): """coordinate transformation from curvilinear reference frame (s, ey) to inertial reference frame (X, Y) (s, ey): position in the curvilinear reference frame """ # wrap s along the track while (s > self.TrackLength): s = s - self.TrackLength # Compute the segment in which system is evolving PointAndTangent = self.PointAndTangent index = np.all([[s >= PointAndTangent[:, 3]], [s < PointAndTangent[:, 3] + PointAndTangent[:, 4]]], axis=0) i = int(np.where(np.squeeze(index))[0]) if PointAndTangent[i, 5] == 0.0: # If segment is a straight line # Extract the first final and initial point of the segment xf = PointAndTangent[i, 0] yf = PointAndTangent[i, 1] xs = PointAndTangent[i - 1, 0] ys = PointAndTangent[i - 1, 1] psi = PointAndTangent[i, 2] # Compute the segment length deltaL = PointAndTangent[i, 4] reltaL = s - PointAndTangent[i, 3] # Do the linear combination x = (1 - reltaL / deltaL) * xs + reltaL / deltaL * xf + ey * np.cos(psi + np.pi / 2) y = (1 - reltaL / deltaL) * ys + reltaL / deltaL * yf + ey * np.sin(psi + np.pi / 2) else: r = 1 / PointAndTangent[i, 5] # Extract curvature ang = PointAndTangent[i - 1, 2] # Extract angle of the tangent at the initial point (i-1) # Compute the center of the arc if r >= 0: direction = 1 else: direction = -1 CenterX = PointAndTangent[i - 1, 0] \ + np.abs(r) * np.cos(ang + direction * np.pi / 2) # x coordinate center of circle CenterY = PointAndTangent[i - 1, 1] \ + np.abs(r) * np.sin(ang + direction * np.pi / 2) # y coordinate center of circle spanAng = (s - PointAndTangent[i, 3]) / (np.pi * np.abs(r)) * np.pi angleNormal = wrap((direction * np.pi / 2 + ang)) angle = -(np.pi - np.abs(angleNormal)) * (sign(angleNormal)) x = CenterX + (np.abs(r) - direction * ey) * np.cos( angle + direction * spanAng) # x coordinate of the last point of the segment y = CenterY + (np.abs(r) - direction * ey) * np.sin( angle + direction * spanAng) # y coordinate of the last point of the segment return x, y def getLocalPosition(self, x, y, psi): """coordinate transformation from inertial reference frame (X, Y) to curvilinear reference frame (s, ey) (X, Y): position in the inertial reference frame """ PointAndTangent = self.PointAndTangent CompletedFlag = 0 for i in range(0, PointAndTangent.shape[0]): if CompletedFlag == 1: break if PointAndTangent[i, 5] == 0.0: # If segment is a straight line # Extract the first final and initial point of the segment xf = PointAndTangent[i, 0] yf = PointAndTangent[i, 1] xs = PointAndTangent[i - 1, 0] ys = PointAndTangent[i - 1, 1] psi_unwrap = np.unwrap([PointAndTangent[i - 1, 2], psi])[1] epsi = psi_unwrap - PointAndTangent[i - 1, 2] # Check if on the segment using angles if (la.norm(np.array([xs, ys]) -
np.array([x, y])
numpy.array
import pyglet from pyglet import gl import numpy as np from luminate import utility from luminate import datasource as ds class AbstractWidget: _numPoints = 500 def __init__(self, window, x, y, width, height): self._window = window self.x = x self.y = y self.width = width self.height = height def draw(self): gl.glTranslatef(self.x, self.y, 0) gl.glPushMatrix() self._draw_impl() gl.glPopMatrix() def _draw_impl(self): pass def update(self, dt): pass num_textures = 0 class TextureWidget(AbstractWidget): def __init__(self, window, x, y, width, height, alpha=1.0, data_source=None): super().__init__(window, x, y, width, height) self._alpha = alpha if data_source is None: tex_data_2d = np.zeros((width, height, 3)) mid_grey =
np.array((0.5, 0.5, 0.5))
numpy.array
import math import colorsys import cv2 as cv import numpy as np import progressbar import pyvista as pv import tensorflow as tf def progbar(n): bar = progressbar.ProgressBar( maxval=n, widgets=[ progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage(), ' | ', progressbar.SimpleProgress(), ' | ', progressbar.AdaptiveETA() ] ) return bar def crop_bbox(in_pc, bbox): out_pc = in_pc[ (in_pc[:, 0] >= bbox[0]) & (in_pc[:, 0] <= bbox[3]) & (in_pc[:, 1] >= bbox[1]) & (in_pc[:, 1] <= bbox[4]) & (in_pc[:, 2] >= bbox[2]) & (in_pc[:, 2] <= bbox[5]) ] return out_pc def check_occupancy(obj_points, bbox): occupied_pts = obj_points[ (obj_points[:, 0]>= bbox[0]) & (obj_points[:, 0]<= bbox[3]) & (obj_points[:, 1]>= bbox[1]) & (obj_points[:, 1]<= bbox[4]) & (obj_points[:, 2]>= bbox[2]) & (obj_points[:, 2]<= bbox[5]) ] return occupied_pts.shape[0] def euc_dist(a, b): return np.sqrt(np.sum((a - b)**2)) def bounding_box(pc): """ Calculate bounding box as [xmin, ymin, ..., zmax] """ bbox = [ np.min(pc[:, 0]), np.min(pc[:, 1]), np.min(pc[:, 2]), np.max(pc[:, 0]), np.max(pc[:, 1]), np.max(pc[:, 2]) ] return np.array(bbox) def bbox_overlap(pc_a, pc_b): bbox_a = bounding_box(pc_a) bbox_b = bounding_box(pc_b) if ( bbox_a[3] >= bbox_b[0] and bbox_b[3] >= bbox_a[0] and bbox_a[4] >= bbox_b[1] and bbox_b[4] >= bbox_a[1] and bbox_a[5] >= bbox_b[2] and bbox_b[5] >= bbox_a[2] ): overlap = True else: overlap = False return overlap def rotate_boxes(boxes, centers, theta): pts_out = np.zeros((boxes.shape[0], 8, 3), np.float32) for i, (b, c, r) in enumerate(zip(boxes, centers, theta)): t = np.arctan2(r[1], r[0]) pts = np.array([ [b[0], b[1], b[2]], [b[3], b[1], b[2]], [b[3], b[4], b[2]], [b[0], b[4], b[2]], [b[0], b[1], b[5]], [b[3], b[1], b[5]], [b[3], b[4], b[5]], [b[0], b[4], b[5]] ]) for j, p in enumerate(pts): pts_out[i, j][0] = c[0] + ((p[1]-c[1])*np.sin(t) + (p[0]-c[0])*np.cos(t)) pts_out[i, j][1] = c[1] + ((p[1]-c[1])*np.cos(t) - (p[0]-c[0])*np.sin(t)) pts_out[i, j][2] = p[2] return pts_out def rotate_box(b, c, r): pts_out = np.zeros((8, 3), np.float32) t = np.arctan2(r[1], r[0]) pts = np.array([ [b[0], b[1], b[2]], [b[3], b[1], b[2]], [b[3], b[4], b[2]], [b[0], b[4], b[2]], [b[0], b[1], b[5]], [b[3], b[1], b[5]], [b[3], b[4], b[5]], [b[0], b[4], b[5]] ]) for j, p in enumerate(pts): pts_out[j][0] = c[0] + ((p[1]-c[1])*np.sin(t) + (p[0]-c[0])*np.cos(t)) pts_out[j][1] = c[1] + ((p[1]-c[1])*np.cos(t) - (p[0]-c[0])*np.sin(t)) pts_out[j][2] = p[2] return pts_out def make_lines(pts): lines = [ pv.Line(pts[0], pts[1]), pv.Line(pts[1], pts[2]), pv.Line(pts[2], pts[3]), pv.Line(pts[3], pts[0]), pv.Line(pts[4], pts[5]), pv.Line(pts[5], pts[6]), pv.Line(pts[6], pts[7]), pv.Line(pts[7], pts[4]), pv.Line(pts[0], pts[4]), pv.Line(pts[1], pts[5]), pv.Line(pts[2], pts[6]), pv.Line(pts[3], pts[7]), ] return lines def rotate_euler(in_pc, theta): out_pc = np.zeros_like((in_pc)) cosval = np.cos(theta) sinval = np.sin(theta) R = np.array([ [np.cos(theta), -np.sin(theta), 0.0], [np.sin(theta), np.cos(theta), 0.0], [0.0, 0.0, 1.0] ]) for idx, p in enumerate(in_pc): out_pc[idx] = np.dot(R, p) return out_pc def get_fixed_pts(in_pts, n_pts): out_pts = in_pts.copy() ret = True if out_pts.shape[0] == 0: out_pts = np.zeros((n_pts, 6)) ret = False elif out_pts.shape[0] < n_pts: dup_idx = np.arange(out_pts.shape[0]) np.random.shuffle(dup_idx) dup_idx = dup_idx[0:n_pts-out_pts.shape[0]] out_pts = np.vstack(( out_pts, out_pts[dup_idx] )) if in_pts.shape[0] < n_pts/2: out_pts = np.pad(out_pts, [[0, n_pts-out_pts.shape[0]], [0, 0]]) else: s_idx = np.arange(out_pts.shape[0]) np.random.shuffle(s_idx) out_pts = out_pts[s_idx[0:n_pts]] return ret, out_pts def iou(a, b): xx1 = np.maximum(a[0], b[0]) yy1 = np.maximum(a[1], b[1]) zz1 = np.maximum(a[2], b[2]) xx2 = np.minimum(a[3], b[3]) yy2 = np.minimum(a[4], b[4]) zz2 = np.minimum(a[5], b[5]) w = np.maximum(0.0, xx2 - xx1) h = np.maximum(0.0, yy2 - yy1) d = np.maximum(0.0, zz2 - zz1) inter = w * h * d area_a = (a[3] - a[0]) * (a[4] - a[1]) * (a[5] - a[2]) area_b = (b[3] - b[0]) * (b[4] - b[1]) * (b[5] - b[2]) return inter / float(area_a + area_b - inter) def make_boxes(xyz, extent): out_boxes = np.zeros((extent.shape[0], extent.shape[1], 6)) for b in range(xyz.shape[0]): centers = xyz[b, :, :3] hwd = extent[b, :, :3] theta = extent[b, :, 3:5] boxes_min = centers - (hwd / 2.) boxes_max = centers + (hwd / 2.) boxes = np.hstack((boxes_min, boxes_max)) boxes = rotate_boxes(boxes, centers, theta) for i, box in enumerate(boxes): out_boxes[b, i, 0] = np.min(box[:, 0]) out_boxes[b, i, 1] = np.min(box[:, 1]) out_boxes[b, i, 2] = np.min(box[:, 2]) out_boxes[b, i, 3] = np.max(box[:, 0]) out_boxes[b, i, 4] =
np.max(box[:, 1])
numpy.max
""" Module implements a binned maximum likelihood analysis with a flexible, energy-dependent ROI based on the PSF. $Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/like/roi_analysis.py,v 1.132 2013/05/07 04:17:43 lande Exp $ author: <NAME>, <NAME>, <NAME> """ import numpy as np import math, pickle, collections import numbers from . import roi_bands, roi_localize , specfitter from . pointspec_helpers import PointSource,get_default_diffuse_mapper from . roi_diffuse import ROIDiffuseModel,DiffuseSource from . roi_extended import ExtendedSource,BandFitExtended,ROIExtendedModel from . import roi_extended from . import roi_printing from . import roi_modify from . import roi_save from . import roi_image from . import sed_plotter from . import roi_upper_limits from . import mapplots from uw.utilities import keyword_options from uw.utilities import xml_parsers from uw.utilities import region_writer from uw.utilities import results_writer from scipy.optimize import fmin,fmin_powell,fmin_bfgs from . import roi_plotting from . import counts_plotter # special function to replace or extend a docstring from that of another function def decorate_with(other_func, append=False, append_init=False): """ append_init: If decorating with an object (which has an __init__ function), then append the doc for the __init__ after the doc for the overall class. """ def decorator(func): if append: func.__doc__ += other_func.__doc__ else: func.__doc__ = other_func.__doc__ if append_init and hasattr(other_func,'__init__'): func.__doc__ += other_func.__init__.__doc__ return func return decorator class ROIAnalysis(object): defaults = ( ("fit_emin",None,"""a two-element list giving front/back minimum energy. Independent energy ranges for front and back. 0th position is for event class 0. If not specified, default is read from SpectralAnalysis."""), ("fit_emax",None,"A two-element list giving front/back maximum energy. Same qualifications as fit_emax."), ("conv_type",-1,"Integer specifying front(0), back(1), or all(-1) events"), ("quiet",False,'Set True to suppress (some) output'), ("catalog_aperture",-1,"Pulsar catalog analysis only -- deprecate"), ("phase_factor",1.,"Pulsar phase. A correction that can be made if the data has undergone a phase selection -- between 0 and 1"), ("bracketing_function",None,"A function by which to multiply the counts in each band, e.g. 1.2 for a 20% 'high' IRF. It should be a function taking as arguments energy and conversion type."), ("skip_setup", False, "Set True to instantiate with data only" ), ) @keyword_options.decorate(defaults) def __init__(self,roi_dir,ps_manager,ds_manager,spectral_analysis,**kwargs): """ roi_dir -- the center of the ROI ps_manager -- an instance of ROIPointSourceManager ds_manager -- an instance of ROIDiffuseManager """ keyword_options.process(self, kwargs) self.__dict__.update(**kwargs) self.roi_dir = roi_dir self.psm = ps_manager self.dsm = ds_manager self.bgm = self.dsm ### bgm is deprecated, set here for convenience of interactive access self.sa = spectral_analysis self.logl = None self.prev_logl = None self.__setup_bands__() self.__warn_about_binning__() self.bin_centers = np.sort(list(set([b.e for b in self.bands]))) self.bin_edges = np.sort(list(set([b.emin for b in self.bands] + [b.emax for b in self.bands]))) self.param_state, self.param_vals = None,None if self.skip_setup: if not self.quiet: print ('No likelihood setup done: skip_setup is set') return self.__pre_fit__() self.logl = self.prev_logl =-self.logLikelihood(self.get_parameters()) # make sure everything initialized def setup(self): """ stuff that would not be done if skip_setup was set""" self.__setup_counts__() self.__pre_fit__() self.logl = self.prev_logl =-self.logLikelihood(self.get_parameters()) # make sure everything initialized def __setup_bands__(self): if self.fit_emin is None: self.fit_emin = self.sa.emin if self.fit_emax is None: self.fit_emax = self.sa.emax if isinstance(self.fit_emin,numbers.Real): self.fit_emin = [self.fit_emin]*2 if isinstance(self.fit_emax,numbers.Real): self.fit_emax = [self.fit_emax]*2 self.bands = collections.deque() band_kwargs = {'catalog_aperture':self.catalog_aperture, 'bracketing_function':self.bracketing_function, 'phase_factor':self.phase_factor} for band in self.sa.pixeldata.dmap: evcl = band.event_class() & 1 # protect high bits if ((band.emin() + 1) >= self.fit_emin[evcl] and (band.emax() - 1) < self.fit_emax[evcl] and (self.conv_type==-1 or self.conv_type==evcl)) : self.bands.append(roi_bands.ROIBand(band,self.sa, self.roi_dir,**band_kwargs)) self.bands = np.asarray(self.bands) if not self.skip_setup: self.__setup_counts__() def __setup_counts__(self): self.psm.setup_initial_counts(self.bands) self.dsm.setup_initial_counts(self.bands) def __warn_about_binning__(self): """ Add a user friendly warning if the binning selected by emin & emin in DataSpecification is inconsistent with the energy bins selected using fit_emin and fit_emax. """ if self.quiet: return for ct in [0,1]: if len([b for b in self.bands if b.ct==ct]) == 0: print ("Warning: No conversion type %s photons were selected." % ct) continue actual_emin=min(b.emin for b in self.bands if b.ct==ct) actual_emax=max(b.emax for b in self.bands if b.ct==ct) requested_emin,requested_emax=self.fit_emin[ct],self.fit_emax[ct] if
np.abs(actual_emin-requested_emin)
numpy.abs
import unittest import pandas as pd import numpy as np import random from cem.match import ExactMatching, Stratum class StratumTest(unittest.TestCase): def test_difference_calculation(self): s = Stratum(0, [0,1,2], [1,2,3]) delta = s.get_difference() self.assertEqual(delta, 1) def test_ci(self): correct, total = 0., 0. for i in range(5000): mu_1, mu_0 = np.random.normal(0, 10, 2) s_1, s_0 = np.abs(np.random.normal(0, 10, 2)) N = 1000 x_1 = np.random.normal(mu_1, s_1, N) x_0 = np.random.normal(mu_0, s_0, N) s = Stratum(0, x_0, x_1) l, u = s.get_difference_confint(.05) if l <= (mu_1 - mu_0) <= u: correct += 1 total += 1 self.assertEqual(round(correct / total, 2), 1. - .05) # Simulate a difference in mean: mu_1, mu_0, sigma_1, sigma_0; confirm that CI contains true mean alpha percent of the time class MatchTest(unittest.TestCase): def test_simple_match_one_stratum(self): X = pd.DataFrame({'match_var': ['A']*6}) t = [0, 0, 0, 1, 1, 1] y = [0, 0, 0, 1, 1, 1] m = ExactMatching() m.match(X, t, y) strata = m.get_strata() self.assertEqual(len(strata), 1) self.assertEqual(strata[('A',)].get_difference(), 1) self.assertEqual(m.get_att(), 1) self.assertEqual(m.get_atc(), 1) self.assertEqual(m.get_ate(), 1) def test_simple_match_two_stratum(self): pass @unittest.skip('make this faster') def test_confounding(self): def _sim_t(x): p = .25 if x == 1 else 0.75 return np.random.binomial(1, p, 1) def _sim_y(t, x): p = .4 if x == 1 else .6 if t == 1: p += 0.05 return np.random.binomial(1, p, 1) N = 100000 X = pd.DataFrame({'match_var':
np.random.binomial(1, 0.45, N)
numpy.random.binomial
import numpy import functools class LayerTMMO(): ''' Construct the layer information for the simulation. LayerTMMO(n, thickness=numpy.nan, layer_type="GT", n_wavelength_0=-eps) n: Index of refraction thickness: Thickness in nm for the "GT". Defaults to nan for semiinfinite layers layer_type: "GT" (geometrical thickness), or "OT" (optical thickness) n_wavelength_0: Central or reference lambda (mostly for multilayer structures) If it is not declared, it will default to numpy.mean(beam.wavelength) ''' def __init__( self, n, thickness=numpy.nan, layer_type="GT", n_wavelength_0=-numpy.finfo(float).eps ): self.index_refraction = n self.thickness = thickness self.layer_type = layer_type self.n_wavelength_0 = n_wavelength_0 class TMMOptics(): ''' Defines the structures for the results. ''' def __init__(self) -> None: pass def beam_parameters( self, wavelength, angle_incidence=0.0, polarisation=0.5, wavelength_0=-numpy.finfo(float).eps, ) -> None: assert(0.0 <= polarisation <= 1.0), "the polarisation should be between 0 and 1" if isinstance(wavelength, int) or isinstance(wavelength, float) or isinstance(wavelength, range) or isinstance(wavelength, list): wavelength = numpy.array([wavelength]).reshape(-1) assert(wavelength.all() > 0.0), "the wavelength should be > 0" if isinstance(angle_incidence, int) or isinstance(angle_incidence, float) or isinstance(angle_incidence, range) or isinstance(angle_incidence,list): angle_incidence = numpy.array([angle_incidence]).reshape(-1) assert(0.0 <= angle_incidence.all() <= 90.0), "the angle of incidence should be between 0 and 90 degrees" self.wavelength = wavelength self.angle_inc_deg = angle_incidence self.angle_inc_rad = angle_incidence*numpy.pi/180.0 self.polarisation = polarisation # Check if wavelength_0 is inside beam.wavelength self.wavelength_0 = _check_wavelength_0(self, wavelength_0) # Find beam.wavelength closest to wavelength_0 self.wavelength_0_idx = find_closest(wavelength_0, self.wavelength) def tmm_spectra(self, layers): ''' Calculates the reflectance and transmittance spectra. ''' # Build the sequence of n and d depending on the input self = _add_gt_thickness(self, layers) self = _transfer_matrix_spectra(self, layers) return self def tmm_emf(self, layers, layers_split=10): ''' Calculates the electromagnetic field distribution. ''' # Build the sequence of n and d depending on the input self = _add_gt_thickness(self, layers) self = _transfer_matrix_emf(self, layers, layers_split) self = _layers_depth(self, layers, layers_split) return self def tmm_spectra_emf(self, layers, layers_split=10): ''' Calculates the reflectance and transmittance spectra, and also the electromagnetic field distribution. ''' # Build the sequence of n and d depending on the input self = _add_gt_thickness(self, layers) self = _transfer_matrix_spectra_emf(self, layers, layers_split) self = _layers_depth(self, layers, layers_split) return self def photonic_dispersion(self, layers): assert(len(layers) > 3), "the number of layers must be greater than 3." d = self.physical_thickness[1:3] n = [ layers[1].index_refraction[self.wavelength_0_idx], layers[2].index_refraction[self.wavelength_0_idx], ] self.crystal_period = numpy.sum(d) self.wavevector_qz =
numpy.sin(self.angle_inc_rad)
numpy.sin
import os import nibabel as nib import numpy as np import pandas as pd from .harmonizationApply import applyModelOne def createMaskNIFTI(paths, threshold=0.0, output_path='thresholded_mask.nii.gz'): """ Creates a binary mask from a list of NIFTI images. Image intensities will be averaged, then thresholded across the entire dataset. Result will have the same affine matrix as the first image in the dataset. Arguments --------- paths : a pandas DataFrame must contain a single column "PATH" with file paths to NIFTIs dimensions must be identical for all images threshold : a float, default 0.0 the threshold at which to binarize the mask average intensity must be greater than threshold to be included in mask output_path : str, default "thresholded_mask.nii.gz" the output file path, must include extension (.nii.gz) Returns ------- nifti_avg : a numpy array array of average image intensities dimensions are identical to images in `paths` nifti_mask : a numpy array array of binarized mask (1=include, 0=exclude) dimensions are identical to images in `paths` affine : a numpy array affine matrix used to save mask """ # count number of images n_images = paths.shape[0] # begin summing image intensities i = 0 nifti_i = nib.load(paths.PATH[i]) affine_0 = nifti_i.affine hdr_0 = nifti_i.header nifti_sum = nifti_i.get_fdata() # iterate over all images for i in range(0, n_images): nifti_i = nib.load(paths.PATH[i]) nifti_sum += nifti_i.get_fdata() if (i==500): print('\n[neuroHarmonize]: loaded %d of %d images...' % (i, n_images)) # compute average intensities nifti_avg = nifti_sum / n_images # apply threshold nifti_avg[nifti_avg<threshold] = 0.0 # create mask and save as NIFTI image nifti_mask = nifti_avg.copy() nifti_mask[nifti_mask>0.0] = 1.0 img = nib.Nifti1Image(nifti_mask, affine_0,hdr_0) img.to_filename(output_path) return nifti_avg, nifti_mask, affine_0, hdr_0 def flattenNIFTIs(paths, mask_path, output_path='flattened_NIFTI_array.npy'): """ Flattens a dataset of NIFTI images to a 2D array. Arguments --------- paths : a pandas DataFrame must contain a single column "PATH" with file paths to NIFTIs dimensions must be identical for all images mask_path : a str file path to the mask, must be created with `createMaskNIFTI` output_path : a str, default "flattened_NIFTI_array.npy" Returns ------- nifti_array : a numpy array array of flattened image intensities dimensions are N_Images x N_Masked_Voxels """ print('\n[neuroHarmonize]: Flattening NIFTIs will consume large amounts of memory. Down-sampling may help.') # load mask (1=GM tissue, 0=Non-GM) # nifti_mask = (nib.load(mask_path).get_fdata().astype(int)==1) nifti_mask = (nib.load(mask_path).get_fdata().round().astype(int)==1) # fix bug n_voxels_flattened = np.sum(nifti_mask) n_images = paths.shape[0] # initialize empty container nifti_array =
np.zeros((n_images, n_voxels_flattened))
numpy.zeros
import numpy as np array = np.array([5, 9, 4, 4, 7, 6, 3]) newarray = np.sort(array) print(newarray) # [3 4 4 5 6 7 9] array = np.array(["cars","apple","bannana"]) newarray =
np.sort(array)
numpy.sort
"""! ####################################################################### @author <NAME> @date February 10, 2022 @brief Utilities for extracting colors from the image. ####################################################################### """ # ---- IMPORTS ---- import numpy import random from . import constants as const def extract_ratios(hsl_img_array): """! @brief Extracts the ratios of hues per pixel. @param hsl_img_array 2D Array of pixels in hsl array format. @return Dictionary of hue ratios (percentage) in set [0.000, 100.000] """ pixels = 0 red_pixel = 0 yellow_pixel = 0 green_pixel = 0 cyan_pixel = 0 blue_pixel = 0 magenta_pixel = 0 for pixel in hsl_img_array: pixels += 1 hue = pixel[0] if ((const.RED_HUE_RANGE_MAX[0] <= hue < const.RED_HUE_RANGE_MAX[1]) or (const.RED_HUE_RANGE_MIN[0] <= hue < const.RED_HUE_RANGE_MIN[1])): red_pixel += 1 elif const.YELLOW_HUE_RANGE[0] <= hue < const.YELLOW_HUE_RANGE[1]: yellow_pixel += 1 elif const.GREEN_HUE_RANGE[0] <= hue < const.GREEN_HUE_RANGE[1]: green_pixel += 1 elif const.CYAN_HUE_RANGE[0] <= hue < const.CYAN_HUE_RANGE[1]: cyan_pixel += 1 elif const.BLUE_HUE_RANGE[0] <= hue < const.BLUE_HUE_RANGE[1]: blue_pixel += 1 elif const.MAGENTA_HUE_RANGE[0] <= hue < const.MAGENTA_HUE_RANGE[1]: magenta_pixel += 1 # Calculate ratios. red_ratio = round((red_pixel / pixels) * 100, 3) yellow_ration = round((yellow_pixel / pixels) * 100, 3) green_ration = round((green_pixel / pixels) * 100, 3) cyan_ratio = round((cyan_pixel / pixels) * 100, 3) blue_ratio = round((blue_pixel / pixels) * 100, 3) magenta_ratio = round((magenta_pixel / pixels) * 100, 3) # Assign the ratio dictionary. ratio_dict = {'Red': red_ratio, 'Yellow': yellow_ration, 'Green': green_ration, 'Cyan': cyan_ratio, 'Blue': blue_ratio, 'Magenta': magenta_ratio} return ratio_dict # *********************************************************************** # *********************************************************************** def construct_base_color_dictionary(hsl_img_array): """! @brief Constructs dictionary of base colors from array of hsl pixel values. @param hsl_img_array 2D Array of pixels in hsl array format. @return Dictionary of base colors. """ # Using index slicing since array is sorted, and it's much faster. start_idx, end_idx = 0, 0 while end_idx < len(hsl_img_array) and ( const.RED_HUE_RANGE_MIN[0] <= hsl_img_array[end_idx][0] < const.RED_HUE_RANGE_MIN[1]): end_idx += 1 red = hsl_img_array[start_idx:end_idx] start_idx = end_idx while end_idx < len(hsl_img_array) and ( const.YELLOW_HUE_RANGE[0] <= hsl_img_array[end_idx][0] < const.YELLOW_HUE_RANGE[1]): end_idx += 1 yellow = hsl_img_array[start_idx:end_idx] start_idx = end_idx while end_idx < len(hsl_img_array) and ( const.GREEN_HUE_RANGE[0] <= hsl_img_array[end_idx][0] < const.GREEN_HUE_RANGE[1]): end_idx += 1 green = hsl_img_array[start_idx:end_idx] start_idx = end_idx while end_idx < len(hsl_img_array) and ( const.CYAN_HUE_RANGE[0] <= hsl_img_array[end_idx][0] < const.CYAN_HUE_RANGE[1]): end_idx += 1 cyan = hsl_img_array[start_idx:end_idx] start_idx = end_idx while end_idx < len(hsl_img_array) and ( const.BLUE_HUE_RANGE[0] <= hsl_img_array[end_idx][0] < const.BLUE_HUE_RANGE[1]): end_idx += 1 blue = hsl_img_array[start_idx:end_idx] start_idx = end_idx while end_idx < len(hsl_img_array) and ( const.MAGENTA_HUE_RANGE[0] <= hsl_img_array[end_idx][0] < const.MAGENTA_HUE_RANGE[1]): end_idx += 1 magenta = hsl_img_array[start_idx:end_idx] red =
numpy.concatenate([red, hsl_img_array[end_idx:]])
numpy.concatenate
""" Tests for snn.Weight. """ import unittest from unit_tests import ModuleTest import numpy as np from spikey.snn import weight def weight_generator(shape): matrix = np.random.uniform(0, 9999, size=shape) return np.ma.array(matrix, mask=(matrix == 0), fill_value=0) class TestWeight(unittest.TestCase, ModuleTest): """ Tests for snn.Weight. """ TYPES = [weight.Manual, weight.Random] BASE_CONFIG = { "n_inputs": 10, "n_neurons": 10, "max_weight": 1, "force_unidirectional": False, "matrix": weight_generator((10 + 10, 10)), "weight_generator": weight_generator, "matrix_mask": None, } def _check_matrix_types(self, weights): self.assertIsInstance(weights._matrix, np.ndarray) self.assertIsInstance(weights.matrix, np.ndarray) self.assertTrue(hasattr(weights._matrix, "mask")) self.assertTrue(not hasattr(weights.matrix, "mask")) self.assertEqual(weights._matrix.fill_value, 0) def _assert_clipped(self, weights): self.assertTrue( np.all(weights.matrix >= 0) & np.all(weights.matrix <= self.BASE_CONFIG["max_weight"]) ) @ModuleTest.run_all_types def test_arith(self): w_shape = ( self.BASE_CONFIG["n_inputs"] + self.BASE_CONFIG["n_neurons"], self.BASE_CONFIG["n_neurons"], ) weights = self.get_obj( max_weight=2, matrix=np.ma.array(np.ones(w_shape)), weight_generator=np.ones ) self.assertTrue(np.mean(weights._matrix.mask) <= 0.05) weights += np.ones((w_shape[0], 1)) self.assertTrue(np.mean(weights._matrix == 2) >= 0.95) self.assertTrue(np.mean(weights.matrix == 2) >= 0.95) weights = self.get_obj( max_weight=2, matrix=np.zeros(w_shape), weight_generator=np.zeros ) self.assertTrue(np.all(weights._matrix.mask)) weights += np.ones((w_shape[0], 1)) self.assertTrue(np.all(weights.matrix == 0)) @ModuleTest.run_all_types def test_usage(self): weights = self.get_obj() self._check_matrix_types(weights) self._assert_clipped(weights) spike_shape = (self.BASE_CONFIG["n_inputs"] + self.BASE_CONFIG["n_neurons"], 1) weights * np.random.uniform(0, 1, spike_shape) weights / np.random.uniform(0, 1, spike_shape) weights + np.random.uniform(0, 1, spike_shape) weights - np.random.uniform(0, 1, spike_shape) weights *= np.random.uniform(0, 1, spike_shape) weights /= np.random.uniform(0, 1, spike_shape) weights += np.random.uniform(0, 1, spike_shape) weights -= np.random.uniform(0, 1, spike_shape) weights.matrix self._check_matrix_types(weights) self._check_matrix_types(weights.copy()) layers = [np.ones((10, 5)), np.ones((4, 4)),
np.ones((1, 1))
numpy.ones
from typing import Any, Union import numpy as np import random import math from numba import njit from scipy.signal import find_peaks from scipy.optimize import curve_fit def get_rand_int_from_exp_distribution(mean): return np.round(np.random.exponential(mean)).astype(int) def get_rand_int_from_triangular_distribution(left, mode, right): return np.round(np.random.triangular(left, mode, right)).astype(int) def get_rand_n_ints_from_triangular_distribution(left, mode, right, n): vals = np.random.triangular(left, mode, right, n).round() return np.array(vals, dtype=np.int32) def get_S_and_exponents_for_sym_hist(bins: int) -> tuple[Union[int, Any], np.ndarray]: """Calculate values needed to create symmetrical histogram. Parameters ---------- bins : int Number of bins in desired histogram. Returns ------- S : int Surface of histogram. Bar width == 1, smallest bar height == 1. Example: bins=7 --> counts == [1, 2, 4, 8, 4 2, 1] --S-> 1+2+4+8+4+2+1=22 exponents : np.ndarray Palindrom list of length = `bins` starting with 0. This list represents exponents which doubles of halves previous values. Example: bins=5 --> [0, 1, 2, 1, 0] --exp-> [1, 2, 4, 2, 1]. """ if bins <= 0: raise ValueError(f"Number of bins must even positive integer," f" while {bins} were passed!") if not bins % 2: raise ValueError(f"Number of bins must be odd to create histogram with single peak," f" while {bins} were given!") if not isinstance(bins, int): raise ValueError(f"Number of bins must even positive integer," f" while {bins} were passed!") n = bins // 2 S = 2 * sum(2 ** i for i in range(n)) S += 2 ** n exponents = np.array([], dtype=int) first = list(range(bins // 2)) exponents = np.append(exponents, first) exponents = np.append(exponents, bins // 2) exponents = np.append(exponents, list(reversed(first))) return S, exponents @njit(cache=True) def int_from_hist(mean: int, bins: int, S: int, exponents: np.ndarray): norm_sum = 0 r = random.random() for i in range(bins): if norm_sum <= r < norm_sum + (2 ** exponents[i]) / S: return i + mean - bins//2 else: norm_sum += (2 ** exponents[i]) / S def get_needed_number_of_processes(num_of_cores, total_num_of_iterations): if total_num_of_iterations < num_of_cores: return total_num_of_iterations else: return num_of_cores @njit(cache=True) def nearest_neighbours(y, x): if x == y == 1: return 0 elif x*y == 2: return 1 elif (y == 1 and x >= 3) or (x == 1 and y >= 3) or x == y == 2: return 2 elif x*y >= 6 and (x == 2 or y == 2): return 3 else: return 4 # Signature of a function to fit def unknown_exp_func(t, A, tau): return A * np.exp(-t/tau) def calc_tau(x_data, y_data): # Find peaks peak_pos_indexes = find_peaks(y_data)[0] peak_pos = x_data[peak_pos_indexes] peak_height = y_data[peak_pos_indexes] # Initial guess for the parameters initial_guess = [np.max(y_data), 50] # Perform curve-fit try: popt, pcov = curve_fit(unknown_exp_func, peak_pos, peak_height, initial_guess) except ValueError('fit_exp_to_peaks function cannot perform fitting'): raise return popt[0], popt[1] # returns (A, tau) def calc_exec_time(grid_size, N, household_size, max_steps, iterations, betas, mortalities, visibilities): coef = (2100 / (20*20*1000*400*20*4*4*5)) / 60 runs = iterations*betas*mortalities*visibilities household_factor = 0.4*household_size + 0.6 coef = coef*household_factor val = int(grid_size[0]*grid_size[1]) * int(N*max_steps*runs) calc_time_minutes = val * coef if calc_time_minutes > 60: hours = calc_time_minutes // 60 minutes = round(calc_time_minutes % 60, 1) else: hours = 0 minutes = round(calc_time_minutes, 1) print(f'It will take {hours} hours and {minutes} minutes to evaluate {runs} simulations') def sort_df_indices_by_col(df, column) -> dict: """ Returns dict in which keys are indices of dataframe and val is pos of that index in df sorted by specified column """ df = df.sort_values(by=column) return {df_index: i for i, df_index in enumerate(df.index)} def sort_dict_by_values(dictionary): return dict(sorted(dictionary.items(), key=lambda key_val: key_val[1])) def window_derivative(y, half_win_size): x = np.arange(len(y)) y_prime = np.zeros_like(y) for i in range(len(y)): left = max(0, i - half_win_size) right = min(len(y) - 1, i + half_win_size) dy = y[right] - y[left] dx = x[right] - x[left] y_prime[i] = dy / dx return y_prime def complete_missing_data(values: np.ndarray): """ Completes nans in array of floats by interpolation. Example: [0, 1, 2, np.NaN, 4, np.NaN, np.NaN, 7] --> [0, 1, 2, 3, 4, 5, 6, 7] Returns completed copy of passed array. Note: if 'values' ends with np.NaN, then last sequence of nans is not modified e.g. [0, np.NaN, 2, np.NaN] --> [0, 1, 2, np.NaN]. :param values: numpy array of floats with missing entries. :type values: np.ndarray """ # copy values (not modify passed array) completed = np.copy(values) # iterate over all values in array for i, val in enumerate(completed): # is first value NaN? if math.isnan(val) and i == 0: completed[i] = 0 # is any other value NaN? elif math.isnan(val): # iterate over array items right after NaN appeared # to find out where NaN sequence ends for j in range(i + 1, len(completed)): # if NaN sequence ended, interpolate and fill 'completed' if not math.isnan(completed[j]): min_val = completed[i - 1] max_val = completed[j] delta_y = max_val - min_val delta_x = j - i + 1 dy = delta_y / delta_x complementary_indices = np.arange(i, j) complementary_values = [min_val + dy * step for step in range(1, delta_x)] # print('delta_y', delta_y) # print('delta_x', delta_x) # print('dy', dy) # print('min value', min_val) # print('complementary indices', complementary_indices) # print('complementary values', complementary_values) # print() completed[complementary_indices] = complementary_values break return completed def get_indices_of_missing_data(data: np.ndarray): """ Returns indices of nans in data array of floats by interpolation. Output is 2D list where each entry is an array of uninterrupted sequence of nans. Example: [0, 1, 2, np.NaN, 4, np.NaN, np.NaN, 7] --> [[3], [5, 6]] Note: if 'data' ends with np.NaN, then last sequence of nans is not returned e.g. [0, np.NaN, 2, 3, np.NaN] --> [[1]]. Implementation detail: I will iterate over data elem by elem if they are not nans. If I get nan I will start iterate from its index until I get first not nan value. From here I get uninterrupted sequence of nans. To not duplicate sequences I fill nans with zeros and continue top level iteration. To not modify data function operates on copy of passed data. :param data: numpy array of floats with missing entries. :type data: np.ndarray :return: list of np.ndarray, each np.ndarray contains uninterrupted sequence of indices nans :rtype: list """ # It will be filled and returned missing_indices = [] completed =
np.copy(data)
numpy.copy
import os import time import math from glob import glob import tensorflow as tf import numpy as np import h5py import cv2 import mcubes import datetime from ops import * from pointnet_plusplus_encoder import get_pointNet_code_of_singlePart from func_utils import * import random import time from partAE_model import PAE from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file from tensorflow.contrib.framework.python.framework import checkpoint_utils from distutils.dir_util import copy_tree class JSM(object): def __init__(self, sess, pointSampleDim, is_training = False, \ dataset_name='default', checkpoint_dir=None, data_dir='./data', rdDisplaceRange=0.0, rdScaleRange=0.1, num_of_parts=4, FLAGS=None ): self.PAE_list = [] for partLabel in range(1, num_of_parts+1): print("============================================================") print("=========== intialize PAE for part ", partLabel) pae = PAE( sess, pointSampleDim, FLAGS, is_training = False, dataset_name=dataset_name, checkpoint_dir=checkpoint_dir, data_dir=data_dir, rdDisplaceRange=rdDisplaceRange, rdScaleRange=rdScaleRange, partLabel=partLabel, loadDataset=False, shapeBatchSize=1 ) could_load, checkpoint_counter = pae.load(pae.checkpoint_dir) if could_load: print( "part ", partLabel, ", checpoint load success: epoch " , checkpoint_counter) else: print( "part ", partLabel, ", checpoint load failed!!!!!!!" ) self.PAE_list.append( pae ) self.workdir = os.path.split( data_dir )[0] if self.workdir[:2] == "./": self.workdir = self.workdir[2:] print("self.workdir = ", self.workdir) part_name_list, part_mesh_dir = getMeshInfo( self.workdir, data_dir) self.part_name_list = part_name_list self.part_mesh_dir = part_mesh_dir print( "self.part_name_list = ", self.part_name_list ) print( "self.part_mesh_dir = ", self.part_mesh_dir ) self.sess = sess self.ptsSampDim = pointSampleDim self.input_dim = pointSampleDim self.dataset_name = dataset_name self.checkpoint_dir = self.workdir + '/' + checkpoint_dir + "_jointSynthesis" self.res_sample_dir = self.checkpoint_dir + "/res_sample/" self.test_res_dir = self.workdir + '/' + "test_res_jointSynthesis/" self.data_dir = data_dir self.rdDisplaceRange = rdDisplaceRange self.rdScaleRange = rdScaleRange self.num_of_parts = num_of_parts self.is_training = is_training if not os.path.exists( self.workdir ): os.makedirs( self.workdir ) if not os.path.exists( self.checkpoint_dir ): os.makedirs( self.checkpoint_dir ) if not os.path.exists( self.res_sample_dir ): os.makedirs( self.res_sample_dir ) if not os.path.exists( self.test_res_dir ): os.makedirs( self.test_res_dir ) if os.path.exists(self.data_dir+'/'+self.dataset_name+'.hdf5') : self.data_dict = h5py.File(self.data_dir+ "/" + self.dataset_name+'.hdf5', 'r') self.ptsBatchSize = FLAGS.ptsBatchSize points_shape = self.data_dict['points_'+str(self.ptsSampDim)+'_aroundjoint'][:, :self.ptsBatchSize, :].shape self.trainSize = int( points_shape[0] * 0.8 ) trainSize = self.trainSize self.testSize = points_shape[0] - trainSize self.batch_size = self.ptsBatchSize print( "self.num_of_parts = ", self.num_of_parts ) print( "self.ptsBatchSize = ", self.ptsBatchSize ) print( "self.trainSize = ", self.trainSize ) print( "self.trainSize = ", self.trainSize ) # load obj list self.objlist_path = self.data_dir+'/'+self.dataset_name+'_obj_list.txt' if os.path.exists( self.objlist_path ): text_file = open(self.objlist_path, "r") self.objlist = text_file.readlines() for i in range(len(self.objlist)): self.objlist[i] = self.objlist[i].rstrip('\r\n') text_file.close() else: print("error: cannot load "+ self.objlist_path) exit(0) ######################## extract datasets if is_training: self.data_points_wholeShape = self.data_dict['points_'+str(self.ptsSampDim) + '_aroundjoint'][:trainSize, :self.ptsBatchSize, :] self.data_values_wholeShape = self.data_dict['jointValues_'+str(self.ptsSampDim) + '_aroundjoint'][:trainSize, :self.ptsBatchSize, :] self.allpartPts2048_ori = self.data_dict['allpartPts2048_ori_sorted'][:trainSize] self.allpartPts2048_ori_normal = self.data_dict['allpartPts2048_ori_normal_sorted'][:trainSize] self.allpartPts2048_ori_dis = self.data_dict['allpartPts2048_ori_dis_sorted'][:trainSize] self.objlist = self.objlist[:trainSize] self.data_examples_dir = self.checkpoint_dir + "/train_examples_10/" else: self.data_points_wholeShape = self.data_dict['points_'+str(self.ptsSampDim) + '_aroundjoint'][trainSize:, :self.ptsBatchSize, :] self.data_values_wholeShape = self.data_dict['jointValues_'+str(self.ptsSampDim) + '_aroundjoint'][trainSize:, :self.ptsBatchSize, :] self.allpartPts2048_ori = self.data_dict['allpartPts2048_ori_sorted'][trainSize:] self.allpartPts2048_ori_normal = self.data_dict['allpartPts2048_ori_normal_sorted'][trainSize:] self.allpartPts2048_ori_dis = self.data_dict['allpartPts2048_ori_dis_sorted'][trainSize:] self.objlist = self.objlist[trainSize:] self.data_examples_dir = self.checkpoint_dir + "/test_examples_10/" self.data_voxels_128 = self.data_dict['voxels_128' ][trainSize:] ######################## ouput samples of traing or test data print( "self.data_points_wholeShape.shape = ", self.data_points_wholeShape.shape ) print( "self.data_values_wholeShape.shape = ", self.data_values_wholeShape.shape ) print( "self.allpartPts2048_ori.shape = ", self.allpartPts2048_ori.shape ) #print( "self.singlePartPoints2048.shape = ", self.singlePartPoints2048.shape ) outputExamples = 1 if outputExamples: if not os.path.exists( self.data_examples_dir ): os.makedirs( self.data_examples_dir ) for t in range(5): print(self.objlist[t]) lables = np.ones( self.num_of_parts*2048, dtype=np.uint8 ) for lb in range(1, self.num_of_parts+1): lables[(lb-1)*2048 : lb*2048 ] = lb self.allpartPts2048_labels = lables write_colored_ply( self.data_examples_dir + self.objlist[t]+"_samples.ply", \ intGridNodes_2_floatPoints( self.data_points_wholeShape[t], self.ptsSampDim ), None, (
np.squeeze(self.data_values_wholeShape[t])
numpy.squeeze
'''Base class for LogisticRegression type methods''' import numpy as np import time import scipy.sparse import scipy import pandas as pd import warnings from sklearn import preprocessing class LogisticBase(object): def __init__(self, rho, accelerated=True, max_iter = 2000, tol = 10**-4, beta=0.5, fit_intercept = True, intercept_scaling = 1, feature_scaling = 1, verbosity=0, solver='lbfgs', var_init_type=1): # initialized member variables self.rho = float(rho) self.accelerated = accelerated self.max_iter = max_iter self.tol = float(tol) self.beta = float(beta) self.is_sparse = False self.fit_intercept = fit_intercept self.intercept_scaling = float(intercept_scaling) self.solver = solver # agm, lbfgs self.var_init_type = var_init_type self.feature_scaling = feature_scaling # uninitialized member variables self.coef_ = None self.labels = None # member variables for debugging self.iteration_objectives = [] self.verbosity = verbosity def _initialize_variables(self, shape): if self.var_init_type == 0: W = np.zeros(*shape) W_prev = np.zeros(*shape) warnings.warn("Initializing weights to zeros causes slow convergence") elif self.var_init_type == 1: W = np.random.randn(*shape) W_prev = np.random.randn(*shape) W[0] = W[0]/self.intercept_scaling W_prev[0] = W_prev[0]/self.intercept_scaling return W, W_prev def _check_data(self, y): class_labels = np.unique(y) num_tasks = len(class_labels) num_examples = y.shape[0] """ if num_tasks == 1: raise ValueError("The number of classes has to be greater than one.") elif num_tasks == 2: if 1 in class_labels and -1 in class_labels: num_tasks = 1 class_labels = np.array([-1, 1]) elif 1 in class_labels and 0 in class_labels: num_tasks = 1 class_labels = np.array([0, 1]) else: raise ValueError("Unable to decide postive label") """ if num_tasks == 2: if 1 in class_labels and -1 in class_labels: num_tasks = 1 class_labels = np.array([-1, 1]) elif 1 in class_labels and 0 in class_labels: num_tasks = 1 class_labels = np.array([0, 1]) lbin = preprocessing.LabelBinarizer(neg_label=-1, pos_label=1) lbin.fit(class_labels) y_bin = lbin.transform(y) return y_bin, class_labels, num_tasks def optimize_objective_lbfgs(self, X, y): '''Train the model''' X = self.append_unit_column(X) Y, self.labels, num_tasks = self._check_data(y) num_examples, num_features = X.shape W = self._initialize_variables((num_features,num_tasks))[0].flatten() W, fvalue, d = scipy.optimize.fmin_l_bfgs_b( self._function_value, W, fprime=self._gradient, args = (X, Y)) W.shape = (num_features, num_tasks) if self.fit_intercept: self.coef_ = W[1:,:] self.intercept_ = W[0,:]*self.intercept_scaling else: self.coef_ = W self.intercept_ = 0 if hasattr(self, 'feature_scaling') and self.feature_scaling != 1: self.coef_ *= self.feature_scaling if num_tasks == 1: self.coef_ = self.coef_.flatten() if self.verbosity == 2: print(d) def optimize_objective_agm(self, X, y): '''Train the model''' X = self.append_unit_column(X) Y, self.labels, num_tasks = self._check_data(y) inv_step_size = 1 n_term_check = 5 W, W_prev = self._initialize_variables((X.shape[1], Y.shape[1])) iterations_info_df = pd.DataFrame(columns = ["objective", "grad_W_norm", "step_size", "step_time", "obj_S", "grad_S"]) iterations_info_df.loc[0] = [self._function_value(W, X, Y), -1, 1, 0, 0, 0] for k in range(1,self.max_iter+1): iter_start_time = time.time() if self.accelerated: theta = (k-1)*1.0/(k+2) S = W + theta*(W-W_prev) else: S = W inv_step_size_temp = inv_step_size*(self.beta) grad_S = self._gradient(S, X, Y) func_value_S = self._function_value(S, X, Y) grad_S_norm = np.linalg.norm(grad_S) # convergence check # objective has not changed much in the last n_term_check iterations if k > n_term_check: if iterations_info_df.objective[-n_term_check:].std() < self.tol: break # backtracking line search while True: diff_US = -1*grad_S/inv_step_size_temp C = S + diff_US try: # apply proximal step if required U = self._prox(C, 1.0/inv_step_size) except AttributeError: U = C func_value_U = self._function_value(U, X, Y) quad_approx_U = func_value_S - 0.5/inv_step_size_temp*grad_S_norm**2 if func_value_U <= quad_approx_U: inv_step_size = inv_step_size_temp W, W_prev = U, W break else: inv_step_size_temp = inv_step_size_temp/self.beta grad_W_norm = np.linalg.norm(self._gradient(W, X, Y)) if self.verbosity == 2 else -1 iterations_info_df.loc[k] = [func_value_U, grad_W_norm, 1.0/inv_step_size, time.time() - iter_start_time, func_value_S, grad_S_norm] if self.fit_intercept: self.coef_ = W[1:,:] self.intercept_ = W[0,:]*self.intercept_scaling else: self.coef_ = W self.intercept_ = 0 if hasattr(self, 'feature_scaling') and self.feature_scaling != 1: self.coef_ *= self.feature_scaling if num_tasks == 1: self.coef_ = self.coef_.flatten() if self.verbosity == 2: self._print_full_df(iterations_info_df.astype(float)) def _print_full_df(self, dataframe): pd.set_option('display.max_rows', len(dataframe)) print(dataframe) pd.reset_option('display.max_rows') def append_unit_column(self, X): '''Add unit column in the first position''' if hasattr(self,'feature_scaling'): X = self.feature_scaling*X if self.fit_intercept: unit_col = self.intercept_scaling*np.ones((X.shape[0], 1)) newX = (scipy.sparse.hstack((unit_col, X))).tocsr() return newX def sparsify(self): self.coef_ = scipy.sparse.csc_matrix(self.coef_) self.is_sparse = True def decision_function(self, X): '''scores of each instance w.r.t. each class''' score = X.dot(self.coef_) + self.intercept_ if isinstance(score, (scipy.sparse.csc_matrix, scipy.sparse.csr_matrix)): score = score.todense().A if len(self.labels) == 2: score = score.flatten() return score def predict(self, X): '''predict the labels of each instance''' scores = self.decision_function(X) if len(self.labels) == 2: # binary case y_index = (scores > 0).astype(int) y_pred = self.labels[y_index] else: # multiclass case y_index = np.argmax(scores, 1) y_pred = self.labels[y_index] return y_pred.flatten() def score(self, X, y): '''Returns the mean accuracy on the given test data and labels.''' y_pred = self.predict(X) y_arr = np.array(y) return np.mean(y_arr == y_pred) def predict_proba(self, X): """Probability estimation for OvR logistic regression. Positive class probabilities are computed as 1. / (1. + np.exp(-self.decision_function(X))); multiclass is handled by normalizing that over all classes. """ prob = self.decision_function(X) prob *= -1 np.exp(prob, prob) prob += 1 np.reciprocal(prob, prob) if len(prob.shape) == 1: return
np.vstack([1 - prob, prob])
numpy.vstack
#!/usr/bin/env python3 import math import spiceypy import logging import os import numpy as np try: # Try import SpiceNOFRAMECONNECT exception from spiceypy 3.1.1 from spiceypy.utils.exceptions import SpiceNOFRAMECONNECT as SpiceNOFRAMECONNECT except ImportError: # Otherwise consider a SpiceNOFRAMECONNECT exception as an SpiceyError, for spiceypy 2.3.2 from spiceypy.utils.support_types import SpiceyError as SpiceNOFRAMECONNECT from spiceypy.utils.support_types import * from spiops.utils import time from spiops.utils.utils import plot from spiops.utils.utils import plot_attitude_error from spiops.utils.utils import target2frame from spiops.utils.utils import findIntersection from spiops.utils.utils import findNearest from spiops.utils.files import download_file from spiops.utils.files import list_files_from_ftp from spiops.utils.files import get_aem_quaternions from spiops.utils.files import get_aocs_quaternions from spiops.utils.files import download_tm_data from spiops.utils.naif import optiks # Do not remove, called from spival from spiops.utils.naif import brief # Do not remove, called from spival from spiops.classes.observation import TimeWindow # Do not remove, called from spival from spiops.classes.body import Target # Do not remove, called from spival from spiops.classes.body import Observer # Do not remove, called from spival import imageio import matplotlib as mpl import matplotlib.pyplot as plt from spiceypy import support_types as stypes from bokeh.plotting import figure, output_file, output_notebook, show from bokeh.models import ColumnDataSource, DatetimeTickFormatter, LabelSet from spiops.utils.time import et_to_datetime # from spiops.utils.webmust.webmust_handler import WebmustHandler """ The MIT License (MIT) Copyright (c) [2015-2017] [<NAME>] Copyright (c) [2015-2017] [<NAME>] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ def load(mk): return spiceypy.furnsh(mk) def adcsng_fill_template(template, file, replacements, cleanup=False): # # If the temp late file is equal to the output file then we need to create a temporary template - which will be # a duplicate - in order to write in the file. A situation where we would like to have them be the same is # for example if we call this function several times in a row, replacing keywords in the template in steps # if template == file: with open(file, "r") as f: with open('fill_template.temp', "w+") as t: for line in f: t.write(line) template = 'fill_template.temp' with open(file, "w+") as f: # # Items are replaced as per correspondance in between the replacements dictionary # with open(template, "r+") as t: for line in t: if '{' in line: for k, v in replacements.items(): if '{' + k + '}' in line: line = line.replace('{' + k + '}', v) f.write(line) # # If the option cleanup is set as true, we remove the keyword assignments in the filled templated which are # unfilled (they should be optional) # if cleanup: with open(file, "r") as f: with open('fill_template.temp', "w+") as t: for line in f: t.write(line) template = 'fill_template.temp' with open(file, "w+") as f: with open('fill_template.temp', "r") as t: for line in t: if '{' not in line: f.write(line) # # The temporary files are removed # if os.path.isfile('fill_template.temp'): os.remove('fill_template.temp') # Originally an adcsng funtion, needs to be re-arranged in adcsng to be made # more generic def adcsng_hk_quaternions2ck_reader(tm_file, input_time_format='UTC', input_time_field_number='1', delimiter=',', input_processing=False, qs_col=1, qx_col=2, qy_col=3, qz_col=4): # # We obtain the number of data fields and its correspondance # input_data_field_numbers = [qx_col, qy_col, qz_col, qs_col] tm_list = [] previous_row_time = '' sclk_partition = '1' sclk_delimiter = '.' filter_flag = False index = 0 row_prev = [] sclk_fraction_prev = '' with open(tm_file, 'r') as t: for line in t: # # TODO: Main difference from fucntion from adcsng # if '#' not in line and 'Date' not in line and input_time_format not in line: index += 1 row_data = [] # We need to remove the end of line character: line = line.split('\n')[0] try: if ',' in delimiter: if input_time_format == 'SCLK': if ',' in input_time_field_number: row_time = sclk_partition + '/' + str(line.split(delimiter)[ int(input_time_field_number[0]) - 1]) + \ sclk_delimiter + str(line.split(delimiter)[ int(input_time_field_number[2]) - 1]) else: input_time_field_number = int(input_time_field_number) row_time = str(line.split(delimiter)[ input_time_field_number - 1]) else: row_time = str(line.split(delimiter)[input_time_field_number-1]) if (' ' in row_time): if input_time_format == 'SCLK': row_time = row_time.replace(' ','') else: row_time = row_time.replace(' ','T') for data_element_field_number in input_data_field_numbers: row_data.append(float(line.split(',')[data_element_field_number-1])) else: proc_line = line.strip() row_time = str(proc_line.split(delimiter)[input_time_field_number - 1]) for data_element_field_number in input_data_field_numbers: # # We need to check that # row_data.append(float(line.split()[data_element_field_number-1])) except: logging.info(' HM TM Processing: Found incomplete data line in line {}:'.format(index)) logging.info(' {}'.format(line)) continue row = row_time + ' ' # As indicated by <NAME> in an e-mail "ROS and MEX "measured" CKs" # sometimes the scalar value is negative and the sign of the rest of the # components of the quaternions needs to be changed! if row_data[-1] < 0: neg_data = [-x for x in row_data] logging.info(' HM TM Processing: Found negative QS on input line {}:'.format(row_data)) logging.info(' ' + neg_data) row_data = neg_data for element in row_data: row += str(element) + ' ' # We filter out "bad quaternions" row += '\n' # We remove the latest entry if a time is duplicated if row_time == previous_row_time: logging.info( ' HM TM Processing: Found duplicate time at {}'.format( row_time)) else: # We do not include the entry if one element equals 1 or gt 1 append_bool = True for quaternion in row_data: if quaternion >= 1.0: append_bool = False logging.info( ' HM TM Processing: Found quaternion GT 1 on input line {}:'.format( row_data)) logging.info(' ' + str(row)) # This is a special filter that has been set for ExoMars2016 # More explanations in [1] if input_processing: sclk_fraction = line.split(':')[-1].split(' ')[0] if filter_flag: if sclk_fraction == sclk_fraction_prev: row_prev.append(row) elif len(row_prev) <= 5 and sclk_fraction == sclk_initial: logging.info( ' HM TM Processing: Coarse quaternion: Spurious SCLK fractions before input line {}:'.format( index)) for element in row_prev: logging.info(' ' + str(element).split('\n')[0]) tm_list.remove(element) filter_flag = False tm_list = [] row_prev = [] sclk_fraction_prev = sclk_fraction else: row_prev = [] filter_flag = False if sclk_fraction_prev and sclk_fraction != sclk_fraction_prev and not filter_flag: filter_flag = True row_prev.append(row) sclk_initial = sclk_fraction_prev sclk_fraction_prev = sclk_fraction if append_bool: tm_list.append(row) previous_row_time = row_time # We remove the carriage return from the last line last_line = tm_list[-1].split('\n')[0] tm_list = tm_list[:-1] tm_list.append(last_line) return(tm_list) def fov_illum(mk, sensor, time=None, angle='DEGREES', abcorr='LT+S', report=False, unload=False): """ Determine the Illumination of a given FoV (for light scattering computations for example). This function is based on the following SPICE APIs: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/getfov_c.html http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/spkezp_c.html :param mk: Meta-kernel to load the computation scenario :type mk: str :param sensor: Sensor ID code or name :type sensor: Union[str, int] :param time: Time to compute the quantity :type time: Union[str, float] :param angle: Angular unit; it can be 'DEGREES' or 'RADIANS'. Default is 'DEGREES' :type angle: str :param abcorr: Aberration correction. Default and recommended is 'LT+S' :type abcorr: str :param report: If True prints the resulting illumination angle on the screen :type report: bool :param unload: If True it will unload the input meta-kernel :type unload: bool :return: Angle in between a sensor's boresight and the sun-sc direction :rtype: float """ room = 99 shapelen = 1000 framelen = 1000 angle = angle.upper() spiceypy.furnsh(mk) if time: time = spiceypy.utc2et(time) else: time = spiceypy.utc2et('2016-08-10T00:00:00') if angle != 'DEGREES' and angle != 'RADIANS': print('angle should be either degrees or radians') if isinstance(sensor, str): instid = spiceypy.bodn2c(sensor) else: instid = sensor shape, frame, bsight, n, bounds = spiceypy.getfov(instid, room, shapelen, framelen) rotation = spiceypy.pxform(frame, 'J2000', time) bsight = spiceypy.mxv(rotation, bsight) # The following assumes that the IDs of the given S/C FK have been defined # according to the NAIF/ESS standards: # # -NXXX # # where: # N is the SC id and can consist on a given number of digits # XXX are three digits that identify the sensor sc_id = int(str(instid)[:-3]) ptarg, lt = spiceypy.spkezp(10, time, 'J2000', abcorr, sc_id) fov_illumination = spiceypy.vsep(bsight, ptarg) if unload: spiceypy.unload(mk) if angle == 'DEGREES': fov_illumination = math.degrees(fov_illumination) if report: print('Illumination angle of {} is {} [{}]'.format(sensor, fov_illumination, angle)) return fov_illumination def cov_spk_obj(mk, object, time_format='TDB', global_boundary=False, report=False, unload=False): """ Provides time coverage summary for a given object for a list of binary SPK files provided in a meta-kernel. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/spkcov_c.html The NAIF utility BRIEF can be used for the same purpose. :param mk: Meta-kernel to load the computation scenario :type mk: str :param object: Ephemeris Object to obtain the coverage from :type object: str :param time_format: Output time format; it can be 'UTC', 'CAL' (for TDB in calendar format) or 'TDB'. Default is 'TDB' :type time_format: str :param global_boundary: Boolean to indicate whether if we want all the coverage windows or only the absolute start and finish coverage times :type global_boundary: bool :param report: If True prints the resulting coverage on the screen :type report: bool :param unload: If True it will unload the input meta-kernel :type unload: bool :return: Returns a list with the coverage intervals :rtype: list """ spiceypy.furnsh(mk) boundaries_list = [] et_boundaries_list = [] object_id = spiceypy.bodn2c(object) maxwin = 2000 spk_count = spiceypy.ktotal('SPK') - 1 while spk_count >= 0: spk_kernel = spiceypy.kdata(spk_count, 'SPK', 155, 155, 155) spk_ids = spiceypy.spkobj(spk_kernel[0]) for id in spk_ids: if id == object_id: object_cov = SPICEDOUBLE_CELL(maxwin) spiceypy.spkcov(spk_kernel[0], object_id, object_cov) boundaries = time.cov_int(object_cov=object_cov, object_id=object_id, kernel=spk_kernel[0], global_boundary=global_boundary, time_format=time_format, report=report) boundaries_list.append(boundaries) # # We need to have the boundaries in TDB in order to sort out the # min and max to obtain the global ones for multiple kernels # if global_boundary: et_boundaries_list.append(time.cov_int( object_cov=object_cov, object_id=object_id, kernel=spk_kernel[0], global_boundary=True, time_format='TDB', report=False)) spk_count -= 1 if global_boundary: start_time = min(et_boundaries_list)[0] finish_time = max(et_boundaries_list)[1] boundaries_list = time.et2cal([start_time, finish_time], format=time_format) if report: print("Global Coverage for {} [{}]: {} - {}".format( str(spiceypy.bodc2n(object_id)), time_format, boundaries_list[0], boundaries_list[1])) if unload: spiceypy.unload(mk) return boundaries_list def cov_spk_ker(spk, object=False, time_format='TDB', support_ker ='', report=False, unload=True): """ Provides time coverage summary for a given object for a given SPK file. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/spkcov_c.html The NAIF utility BRIEF can be used for the same purpose. :param spk: SPK file to be used :type mk: str :param support_ker: Support kernels required to run the function. At least it should be a leapseconds kernel (LSK) and optionally a meta-kernel (MK) :type support_ker: Union[str, list] :param object: Ephemeris Object or list of objects to obtain the coverage from :type object: str :param time_format: Output time format; it can be 'UTC', 'CAL' or 'SPICE' (for TDB in calendar format) or 'TDB'. Default is 'TDB' :type time_format: str :param global_boundary: Boolean to indicate whether if we want all the coverage windows or only the absolute start and finish coverage times :type global_boundary: bool :param report: If True prints the resulting coverage on the screen :type report: bool :param unload: If True it will unload the input meta-kernel :type unload: bool :return: Returns a list with the coverage intervals :rtype: list """ spiceypy.furnsh(spk) object_id = [] boundaries = [] if object and not isinstance(object, list): object = [object] if support_ker: if isinstance(support_ker, str): support_ker = [support_ker] for ker in support_ker: spiceypy.furnsh(ker) maxwin = 2000 spk_ids = spiceypy.spkobj(spk) if not object: object_id = spk_ids object = [] for id in spk_ids: object.append(spiceypy.bodc2n(id)) else: for element in object: object_id.append(spiceypy.bodn2c(element)) for id in object_id: if id in spk_ids: object_cov = SPICEDOUBLE_CELL(maxwin) spiceypy.spkcov(spk, id, object_cov) cov = time.cov_int(object_cov=object_cov, object_id=id, kernel=spk, time_format=time_format, report=report) else: if report: print('{} with ID {} is not present in {}.'.format(object, id, spk)) if unload: spiceypy.unload(spk) if support_ker: if isinstance(support_ker, str): support_ker = [support_ker] for ker in support_ker: spiceypy.unload(ker) return False if time_format == 'SPICE': boundaries.append(object_cov) else: boundaries.append(cov) if unload: spiceypy.unload(spk) if support_ker: if isinstance(support_ker, str): support_ker = [support_ker] for ker in support_ker: spiceypy.unload(ker) return boundaries def spkVsOem(sc, spk, plot_style='line', notebook=True): spiceypy.timdef('SET', 'SYSTEM', 10, 'TDB') spiceypy.furnsh(spk) if sc == 'MPO': file = spk.split('/')[-1].replace('\n', '').replace('bc_mpo_fcp_', '').split('_')[0] file = 'BCCruiseOrbit__' + file + '.bc' download_file("data/ANCDR/BEPICOLOMBO/fdy", file) else: print('Unsupported spacecraft: ' + sc) return None, None print('OEM file: ' + file) if not os.path.isfile(file): print('OEM file cannot be downloaded!') return None, None oemfile = open(file) error = [] pos_norm_error = [] vel_norm_error = [] data_list = [] for line in oemfile.readlines(): if 'CENTER_NAME' in line: center = line.split('= ')[1].replace('\n', '') if line[:2] == '20': data = line.replace('\n', '').split() data_list.append(data) for i in range(0, len(data_list)-1, 1): # # skip OEM lines with repeated time tags (typically at the end of a # segment) as are superseeded by the latest line with that time tag # if data_list[i][0] != data_list[i+1][0]: data = data_list[i] et = spiceypy.str2et(data[0]) state = spiceypy.spkezr(sc, et, 'J2000', 'NONE', center)[0] curr_error = [et, abs(state[0] - float(data[1])), abs(state[1] - float(data[2])), abs(state[2] - float(data[3])), abs(state[3] - float(data[4])), abs(state[4] - float(data[5])), abs(state[5] - float(data[6]))] error.append(curr_error) pos = np.asarray(curr_error[1:4]) vel = np.asarray(curr_error[4:7]) pos_norm_error.append(spiceypy.vnorm(pos)) vel_norm_error.append(spiceypy.vnorm(vel)) max_pos_norm_error = max(pos_norm_error) max_vel_norm_error = max(vel_norm_error) error = np.asarray(error) print('Avg position error [km]: ' + str(np.mean(pos_norm_error)) + ' , max position error [km]: ' + str(max_pos_norm_error)) print('Avg velocity error [km/s]: ' + str(np.mean(vel_norm_error)) + ' , max velocity error [km/s]: ' + str(max_vel_norm_error)) plot(error[:, 0], [error[:, 1], error[:, 2], error[:, 3]], yaxis_name=['X', 'Y', 'Z'], title='Source OEM to generated SPK position difference', format=plot_style, yaxis_units='Position error Km', notebook=notebook) plot(error[:, 0], [error[:, 4], error[:, 5], error[:, 6]], yaxis_name=['VX', 'VY', 'VZ'], title='Source OEM to generated SPK velocity difference', format=plot_style, yaxis_units='Km/s', notebook=notebook) os.remove(file) spiceypy.timdef('SET', 'SYSTEM', 10, 'UTC') spiceypy.unload(spk) return max_pos_norm_error, max_vel_norm_error def ckVsAEM(sc, ck, plot_style='line', notebook=True): spiceypy.timdef('SET', 'SYSTEM', 10, 'TDB') spiceypy.furnsh(ck) if sc == 'MPO': file = ck.split('/')[-1].replace('\n', '').split('_')[4] file = 'AttitudePredictionST__' + file + '.bc' download_file("data/ANCDR/BEPICOLOMBO/fdy", file) else: print('Unsupported spacecraft: ' + sc) return None print('AEM file: ' + file) if not os.path.isfile(file): print('AEM file cannot be downloaded!') return None aem_guats = get_aem_quaternions(file) if len(aem_guats): # If any quaternion inserted, remove the first element to create a # margin with the start of the CK aem_guats.pop(0) error, max_ang_error = get_quats_ang_error(aem_guats, sc) plot_attitude_error(np.asarray(error), max_ang_error, 'Source AEM Quaternions to generated CK orientation difference', plot_style, notebook) os.remove(file) spiceypy.unload(ck) return max_ang_error def ckVsAocs(sc, ck, plot_style='line', notebook=True): spiceypy.timdef('SET', 'SYSTEM', 10, 'UTC') spiceypy.furnsh(ck) if sc == 'MPO': file = ck.split('/')[-1].replace('\n', '').split('_')[5] file = 'mpo_raw_hk_aocs_measured_attitude_' + file + '.tab' download_file("data/ANCDR/BEPICOLOMBO/hkt", file) else: print('Unsupported spacecraft: ' + sc) return None print('AOCS tab file: ' + file) if not os.path.isfile(file): print('AOCS tab file cannot be downloaded!') return None aocs_quats = get_aocs_quaternions(file) error, max_ang_error = get_quats_ang_error(aocs_quats, sc) plot_attitude_error(error, max_ang_error, 'Source AOCS Measured Quaternions to generated CK orientation difference', plot_style, notebook) os.remove(file) spiceypy.unload(ck) return max_ang_error def get_quats_ang_error(quats, sc): error = [] max_ang_error = 0 for quat in quats: et = quat[0] q_spice = spiceypy.m2q(spiceypy.pxform('J2000', sc + '_SPACECRAFT', et)) if quat[1] < 0: q_spice[0] *= -1 q_spice[1] *= -1 q_spice[2] *= -1 q_spice[3] *= -1 quat[2] *= -1 quat[3] *= -1 quat[4] *= -1 q_error = [abs(q_spice[0] - quat[1]), abs(q_spice[1] - quat[2]), abs(q_spice[2] - quat[3]), abs(q_spice[3] - quat[4])] mrot_spice = spiceypy.q2m(q_spice) mrot_quats = spiceypy.q2m(quat[1:5]) vz_spice = spiceypy.mxv(mrot_spice, [0, 0, 1]) vz_quats = spiceypy.mxv(mrot_quats, [0, 0, 1]) ang_error = spiceypy.vsep(vz_spice, vz_quats) max_ang_error = max(max_ang_error, abs(ang_error)) curr_error = [et] curr_error.extend(q_error) error.append(curr_error) max_ang_error = np.rad2deg(max_ang_error) * 1000 return np.asarray(error), max_ang_error def saa_vs_hk_sa_position(sc, plot_style='line', notebook=True): spiceypy.timdef('SET', 'SYSTEM', 10, 'UTC') sa_angles = [] # Read angles from TM, List of items as [et, angle_deg] if sc == 'MPO': # Set some mission specific constants sadm_frame = 'MPO_SA' # SA Rotating Frame sadm_ref_frame = 'MPO_SA_SADM' # SA Fixed Frame ref_vector = np.asarray([0, 0, 1]) # SA Rotating Plane normal ref_cross_vector = np.asarray([0, 1, 0]) # Common rotation vector btw SA Rotating Frm and Fixed Frm # For MPO SA the TM files are given in daily basis, so we need to # concatenate N of them to obtain a greater period coverage. hkt_path = "data/ANCDR/BEPICOLOMBO/hkt/" hkt_expression = 'mpo_raw_hk_sa_position_????????.tab' num_sa_files = 7 # Compare last week # Determine files to use to fetch TM data sa_files = list_files_from_ftp(hkt_path, hkt_expression) sa_files = sa_files[-num_sa_files:] # For each file, download it, add data to array, and remove it sa_angles = download_tm_data(sa_files, hkt_path, ",", [2], [180.0 / math.pi]) if not len(sa_angles): print("Cannot obtain required TM data, aborting.") return None elif sc == 'MTM': # Set some mission specific constants sadm_frame = 'MTM_SA+X' # SA Rotating Frame sadm_ref_frame = 'MTM_SA+X_ZERO' # SA Fixed Frame ref_vector = np.asarray([0, 1, 0]) # SA Rotating Plane normal ref_cross_vector = np.asarray([1, 0, 0]) # Common rotation vector btw SA Rotating Frm and Fixed Frm # For MTM SA the TM files are given in daily basis, so we need to # concatenate N of them to obtain a greater period coverage. hkt_path = "data/ANCDR/BEPICOLOMBO/hkt/" hkt_expression = 'mtm_raw_hk_sa_position_????????.tab' num_sa_files = 7 # Compare last week # Determine files to use to fetch TM data sa_files = list_files_from_ftp(hkt_path, hkt_expression) sa_files = sa_files[-num_sa_files:] # For each file, download it, add data to array, and remove it sa_angles = download_tm_data(sa_files, hkt_path, ",", [2], [180.0 / math.pi]) if not len(sa_angles): print("Cannot obtain required TM data, aborting.") return None else: print('Unsupported spacecraft: ' + sc) return None # Compare with SPICE SA Angles error = [] max_ang_error = 0 num_gaps = 0 for sa_angle in sa_angles: try: et = sa_angle[0] hk_sa_angle = sa_angle[1] # Determine the rotation matrix to pass from the SA Rotating Frame # to the SA Fixed frame sadm_rot = spiceypy.pxform(sadm_frame, sadm_ref_frame, et) # Covert the SA reference vector in the rotating frame into # the SA fixed frame sadm_vector = spiceypy.mxv(sadm_rot, ref_vector) sadm_angle = np.rad2deg(spiceypy.vsep(ref_vector, sadm_vector)) # Because vsep always is positive, we are going to get the cross product to # determine if is a positive or negative rotation sadm_cross_vector = np.cross(ref_vector, sadm_vector) # The dot product of the normalised vectors shall be or 1 or -1. sadm_angle = np.dot(spiceypy.unorm(ref_cross_vector)[0], spiceypy.unorm(sadm_cross_vector)[0]) * sadm_angle ang_error = abs(sadm_angle - hk_sa_angle) * 1000 # mdeg max_ang_error = max(max_ang_error, ang_error) error.append([et, ang_error]) except SpiceNOFRAMECONNECT: # There is a gap in the CK file, ignore this SA sample. num_gaps += 1 continue # Plot error if len(error): error = np.asarray(error) print('Max angular error [mdeg]: ' + str(max_ang_error)) plot(error[:, 0], [error[:, 1]], yaxis_name=['Angular error'], title=sc + " SA angular error between TM and SPICE", format=plot_style, yaxis_units='mdeg', notebook=notebook) return max_ang_error else: print('Angular error cannot be computed. Found ' + str(num_gaps) + ' of ' + str(len(sa_angles)) + ' samples without data.') return None """ def sadmCkVsMust(sc, start_time, end_time, plot_style='line', notebook=True): # TODO: METHOD NOT FINISHED!!! if sc == 'MPO': must_sadm_param = 'NCADAF41' # TODO: Set correct parameter for SADM sadm_frame = 'MPO_SA' sadm_ref_frame = 'MPO_SA_SADM' ref_vector = np.asarray([0, 0, 1]) mission_phase = 'BEPICRUISE' else: print('Unsupported spacecraft: ' + sc) return None et_start = spiceypy.utc2et(start_time) et_end = spiceypy.utc2et(end_time) start_time = et_to_datetime(et_start).strftime('%Y-%b-%d %H:%M:%S') end_time = et_to_datetime(et_end).strftime('%Y-%b-%d %H:%M:%S') error = [] max_ang_error = 0 tm = WebmustHandler(mission_phase=mission_phase) df_0 = tm.get_tm([must_sadm_param], start_time, end_time) for row in df_0: utc = row[0] must_angle = row[1] # TODO: Must be in degrees et = spiceypy.utc2et(utc) sadm_rot = spiceypy.pxform(sadm_ref_frame, sadm_frame, et) sadm_vector = spiceypy.mxv(sadm_rot, ref_vector) sadm_angle = np.rad2deg(spiceypy.vsep(ref_vector, sadm_vector)) ang_error = abs(sadm_angle - must_angle) * 1000 # mdeg max_ang_error = max(max_ang_error, ang_error) error.append([et, ang_error]) # Plot error error = np.asarray(error) print('Max angular error [mdeg]: ' + str(max_ang_error)) plot(error[:, 0], [error[:, 1]], yaxis_name=['Angular error'], title=sc + " SA angular error between WebMUST and SPICE", format=plot_style, yaxis_units='mdeg', notebook=notebook) return max_ang_error """ def cov_ck_obj(mk, object, time_format= 'UTC', global_boundary=False, report=False, unload=False): """ Provides time coverage summary for a given object for a list of binary CK files provided in a meta-kernel. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/ckcov_c.html The NAIF utility CKBRIEF can be used for the same purpose. :param mk: Meta-kernel to load the computation scenario. :type mk: str :param object: Ephemeris Object to obtain the coverage from. :type object: str :param time_format: Output time format; it can be 'UTC', 'CAL' (for TDB in calendar format) or 'TDB'. Default is 'TDB'. :type time_format: str :param global_boundary: Boolean to indicate whether if we want all the coverage windows or only the absolute start and finish coverage times. :type global_boundary: bool :param report: If True prints the resulting coverage on the screen. :type report: bool :param unload: If True it will unload the input meta-kernel. :type unload: bool :return: Returns a list with the coverage intervals. :rtype: list """ spiceypy.furnsh(mk) boundaries_list = [] et_boundaries_list = [] object_id = spiceypy.namfrm(object) MAXIV = 2000 ck_count = spiceypy.ktotal('CK') - 1 WINSIZ = 2 * MAXIV MAXOBJ = 10000 while ck_count >= 0: ck_ids = spiceypy.support_types.SPICEINT_CELL(MAXOBJ) ck_kernel = spiceypy.kdata(ck_count, 'CK', 155, 155, 155) try: ck_ids = spiceypy.ckobj(ck=ck_kernel[0], outCell=ck_ids) except: ck_ids = spiceypy.ckobj(ck=ck_kernel[0]) for id in ck_ids: if id == object_id: object_cov = spiceypy.support_types.SPICEDOUBLE_CELL(WINSIZ) object_cov = spiceypy.ckcov(ck=ck_kernel[0], idcode=object_id, needav=False, level='SEGMENT', tol=0.0, timsys='TDB', cover=object_cov) boundaries = time.cov_int(object_cov=object_cov, object_id=object_id, kernel=ck_kernel[0], global_boundary=global_boundary, time_format=time_format, report=report) boundaries_list.append(boundaries) # # We need to have the boundaries in TDB in order to sort out the # min and max to obtain the global ones for multiple kernels # if global_boundary: et_boundaries_list.append(time.cov_int( object_cov=object_cov, object_id=object_id, kernel=ck_kernel[0], global_boundary=True, time_format='TDB', report=False)) ck_count -= 1 if global_boundary: start_time = min(et_boundaries_list)[0] finish_time = max(et_boundaries_list)[1] boundaries_list = time.et2cal([start_time, finish_time], format=time_format) if report: try: body_name = spiceypy.bodc2n(object_id) except: body_name = spiceypy.frmnam(object_id, 60) print("Global Coverage for {} [{}]: {} - {}".format( body_name, time_format, boundaries_list[0], boundaries_list[1])) if unload: spiceypy.unload(mk) return boundaries_list def cov_ck_ker(ck, object, support_ker=list(), time_format='UTC', report=False, unload=True): """ Provides time coverage summary for a given object for a given CK file. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/ckcov_c.html The NAIF utility CKBRIEF can be used for the same purpose. :param ck: CK file to be used :type mk: str :param support_ker: Support kernels required to run the function. At least it should be a leapseconds kernel (LSK) and a Spacecraft clock kernel (SCLK) optionally a meta-kernel (MK) which is highly recommended. It is optional since the kernels could have been already loaded. :type support_ker: Union[str, list] :param object: Ephemeris Object to obtain the coverage from. :type object: str :param time_format: Output time format; it can be 'UTC', 'CAL' (for TDB in calendar format), 'TDB' or 'SPICE'. Default is 'TDB'. :type time_format: str :param global_boundary: Boolean to indicate whether if we want all the coverage windows or only the absolute start and finish coverage times. :type global_boundary: bool :param report: If True prints the resulting coverage on the screen. :type report: bool :param unload: If True it will unload the input meta-kernel. :type unload: bool :return: Returns a list with the coverage intervals. :rtype: list """ spiceypy.furnsh(ck) if support_ker: if isinstance(support_ker, str): support_ker = [support_ker] for ker in support_ker: spiceypy.furnsh(ker) object_id = spiceypy.namfrm(object) MAXIV = 200000 WINSIZ = 2 * MAXIV MAXOBJ = 100000 ck_ids = spiceypy.support_types.SPICEINT_CELL(MAXOBJ) try: ck_ids = spiceypy.ckobj(ck, outCell=ck_ids) except: ck_ids = spiceypy.ckobj(ck) if object_id in ck_ids: object_cov = spiceypy.support_types.SPICEDOUBLE_CELL(WINSIZ) spiceypy.scard, 0, object_cov object_cov = spiceypy.ckcov(ck=ck, idcode=object_id, needav=False, level='INTERVAL', tol=0.0, timsys='TDB', cover=object_cov) else: #print('{} with ID {} is not present in {}.'.format(object, # object_id, ck)) if unload: spiceypy.unload(ck) if support_ker: if isinstance(support_ker, str): support_ker = [support_ker] for ker in support_ker: spiceypy.unload(ker) return False if time_format == 'SPICE': boundaries = object_cov else: boundaries = time.cov_int(object_cov=object_cov, object_id=object_id, kernel=ck, time_format=time_format, report=report) if unload: spiceypy.unload(ck) if support_ker: if isinstance(support_ker, str): support_ker = [support_ker] for ker in support_ker: spiceypy.unload(ker) return boundaries def time_correlation(sc, ck, plot_style='line', notebook=True): # Downloads a telemetry file of a given CK and computes # the time difference between the UTC time (1st column) # and the clock string (2nd column) in milliseconds spiceypy.timdef('SET', 'SYSTEM', 10, 'UTC') if sc == 'MPO': file = ck.split('/')[-1].replace('\n', '').split('_')[5] file = 'mpo_raw_hk_aocs_measured_attitude_' + file + '.tab' download_file("data/ANCDR/BEPICOLOMBO/hkt", file) else: print('Unsupported spacecraft: ' + sc) return None print('AOCS tab file: ' + file) if not os.path.isfile(file): print('AOCS tab file cannot be downloaded!') return None tabfile = open(file) times = [] time_diff = [] try: sc_id = spiceypy.bodn2c(sc) except Exception as e: print('Spacecraft not found: ' + sc + ", err: " + str(e)) return None for line in tabfile.readlines(): data = line.replace('\n', '').replace(',', ' ').split() utc_et = spiceypy.str2et(data[0].replace('Z', '')) scs_et = spiceypy.scs2e(sc_id, data[1]) times.append(utc_et) time_diff.append((utc_et - scs_et) * 1000) time_diff = np.abs(np.asarray(time_diff)) max_time_diff = np.max(time_diff) print('Avg time difference [ms]: ' + str(np.mean(time_diff))) print('Max time difference [ms]: ' + str(max_time_diff)) plot(times, time_diff, yaxis_name='Time diff (UTC - SCS)', title='Time difference between UTC and Clock String in milliseconds', format=plot_style, yaxis_units='milliseconds', notebook=notebook) os.remove(file) return max_time_diff def flyby_ca_altitudes(sc, target, spk_expression, num_spk_files, from_date, to_date, distance_flyby, num_samples, plot_style='line', notebook=True, plot_prefix=""): spiceypy.timdef('SET', 'SYSTEM', 10, 'TDB') target = target.upper() target_frame = "IAU_" + target start_time = spiceypy.utc2et(from_date) stop_time = spiceypy.utc2et(to_date) times = np.linspace(start_time, stop_time, num_samples) maxwin = 200000 if sc == 'MPO': spk_path = "data/SPICE/BEPICOLOMBO/kernels/spk/" else: print('Unsupported spacecraft: ' + sc) return None # Download num_spk_files and find the flyby for each one spk_files = list_files_from_ftp(spk_path, spk_expression) spk_files = spk_files[-num_spk_files:] flybys_spks = [] flybys_ets = [] flybys_alts = [] flybys_alt_list = [] for spk_file in spk_files: # Download spk file download_file(spk_path, spk_file) if not os.path.isfile(spk_file): print('OEM file cannot be downloaded!') return None # Obtain the flyby data spiceypy.furnsh(spk_file) cnfine = SPICEDOUBLE_CELL(maxwin) result = SPICEDOUBLE_CELL(maxwin) spiceypy.scard(0, cnfine) spiceypy.wninsd(start_time, stop_time, cnfine) spiceypy.gfdist(target=target, abcorr='NONE', obsrvr=sc, relate='<', refval=distance_flyby, step=spiceypy.spd() / 4., nintvls=maxwin, cnfine=cnfine, adjust=0.0, result=result) final = SPICEDOUBLE_CELL(maxwin) spiceypy.gfdist(target=target, abcorr='NONE', obsrvr=sc, relate='LOCMIN', refval=distance_flyby, step=spiceypy.spd() / 4., nintvls=maxwin, cnfine=result, adjust=0.0, result=final) number_of_results = spiceypy.wncard(final) if number_of_results == 0: print('No ' + target + ' flyby found for that period at SPK: ' + spk_file) return None if number_of_results > 1: print('Error: Multiple ' + target + ' flybys found for that period at SPK: ' + spk_file) return None # Get the flyby closest approach time and distance flyby_et = spiceypy.wnfetd(final, 0)[0] (state, lt) = spiceypy.spkezr(target, flyby_et, target_frame, 'NONE', sc) spoint = spiceypy.sincpt('ELLIPSOID', target, flyby_et, target_frame, 'NONE', sc, target_frame, state[:3])[0] flyby_altitude = spiceypy.vnorm(spoint + state[:3]) flybys_spks.append(spk_file) flybys_ets.append(flyby_et) flybys_alts.append(flyby_altitude) # Get the flyby closest approach distance evolution altitudes = [] for et in times: (state, lt) = spiceypy.spkezr(target, et, target_frame, 'NONE', sc) spoint = spiceypy.sincpt('ELLIPSOID', target, et, target_frame, 'NONE', sc, target_frame, state[:3])[0] altitudes.append(spiceypy.vnorm(spoint + state[:3])) flybys_alt_list.append(altitudes) # Unload and clean spk file spiceypy.unload(spk_file) os.remove(spk_file) # Reduce the SPK names to only the SPK number to reduce the legend size spk_numbers = [] if sc == 'MPO': for spk in flybys_spks: spk_number = int(spk.split("_")[3]) spk_numbers.append(spk_number) if len(plot_prefix): plot_prefix = plot_prefix + " " # Plot Flyby CA altitude vs spk number plot(spk_numbers, flybys_alts, title=plot_prefix + target + ' Flyby CA altitude vs spk number', format="scatter", xaxis_name='SPK Number', yaxis_name=['Altitude'], yaxis_units='Km', notebook=notebook) # Plot Flyby CA time vs spk number plot(flybys_ets, spk_numbers, title=plot_prefix + target + ' Flyby CA spk number vs time', format="scatter", yaxis_name=['SPK Number'], yaxis_units='SPK Number', notebook=notebook) # Plot Flyby altitude evolution vs time per SPK plot(times, flybys_alt_list, yaxis_name=spk_numbers, title=plot_prefix + target + ' Flyby altitude evolution vs time', format=plot_style, yaxis_units='Km', plot_height=400, notebook=notebook) return np.max(flybys_alts) def fk_body_ifj2000(mission, body, pck, body_spk, frame_id, report=False, unload=False, file=True): """ Generates a given Solar System Natural Body Inertial frame at J2000. This function is based on a FORTRAN subroutine provided by <NAME> (NAIF/JPL) The frame definition would be as follows: {Body} Inertial Frame at J2000 ({MISSION}_{BODY}_IF_J2000) Definition: The {body} Inertial Frame at J2000 is defined as follows: - +Z axis is parallel to {body} rotation axis at J2000, pointing toward the North side of the invariable plane; - +X axis is aligned with the ascending node of the {Body} orbital plane with the {Body} equator plane at J2000; - +Y axis completes the right-handed system; - the origin of this frame is the center of mass of {Body}. All vectors are geometric: no aberration corrections are used. Remarks: This frame is defined as a fixed offset frame using constant vectors as the specification method. The fixed offset for these vectors were based on the following directions (that also define a two-vector frame): - +Z axis along Right Ascension (RA) and Declination (DEC) of {Body} pole at J2000 epoch in J2000 inertial frame; - +X axis along the RA/DEC of {Body} instantaneous orbital plane ascending node on {Body} equator at J2000 epoch in J2000 inertial frame; This frame has been defined based on the IAU_{BODY} frame, whose evaluation was based on the data included in the loaded PCK file. In addition {body_spk} ephemeris have been used to compute the {Body} instantaneous orbital plane ascending node on {Body} equator at J2000 epoch in J2000 inertial frame. :param mission: Name of the mission to use the frame :type mission: str :param body: Natural body for which the frame is defined :type body: str§ :param pck: Planetary Constants Kernel to be used to extract the Pole information from :type pck: str :param body_spk: SPK kernels that contain the ephemeris of the Natural body :type body_spk: Union[str, list] :param frame_id: ID for the new frame. It is recommended to follow the convention recommended by NAIF: -XYYY where X is the ID of the mission S/C and YYY is a number between 900 and 999. :type frame_id: str :param report: If True prints some intermediate results. :type report: bool :param unload: If True it will unload the input PCK and SPK. :type unload: bool :param file: If True it generates the frame definition in a file with the following name: {MISSION}_{BODY}_IF_J2000.tf :type file: bool :return: Returns the Euler angles to transform the computed frame with J2000. Only if parameter file is False :rtype: str """ body = body.upper() mission = mission.upper() spiceypy.furnsh(pck) # # This can actually be a list of bodies. # spiceypy.furnsh(body_spk) # # Get instantaneous Body state at J2000 and compute instantaneous # orbital normal. # state, lt = spiceypy.spkezr(body, 0.0, 'J2000', 'NONE', 'SUN') normal = spiceypy.ucrss(state[0:3:1], state[3:6:1]) # # Get J2000 -> IAU_{BODY} rotation at J2000 and compute Body pole # direction in J2000 at J2000. # mat = spiceypy.pxform('IAU_{}'.format(body), 'J2000', 0.0) z = spiceypy.vpack(0.0, 0.0, 1.0) pole = spiceypy.mxv(mat, z) # # Compute direction Body orbit's ascending node on Body equator at # J2000 in J2000 and print it and Body pole as RA/DEC in J2000 in # degrees # ascnod = spiceypy.ucrss(pole, normal) r, ra, dec = spiceypy.recrad(pole) if report: print('POLE RA/DEC = {}/{}'.format(ra*spiceypy.dpr(), dec*spiceypy.dpr())) r, ra, dec = spiceypy.recrad(ascnod) if report: print('ASCNOD RA/DEC = {}/{}'.format(ra * spiceypy.dpr(), dec * spiceypy.dpr())) # # Build two vector from a with POLE as Z and ASNOD as X and print rotation # from that frame to J200 as Euler angles. # mat = spiceypy.twovec(pole, 3, ascnod, 1) matxp = spiceypy.xpose(mat) r3, r2, r1 = spiceypy.m2eul(matxp, 3, 2, 3) if file: body_id = spiceypy.bodn2c(body) with open('{}_{}_IF_J2000.tf'.format(mission, body), 'w+') as f: f.write(r"\begindata") f.write('\n \n') f.write(' FRAME_{}_{}_IF_J2000 = {}\n'.format(mission, body, frame_id)) f.write(" FRAME_{}_NAME = '{}_{}_IF_J2000'\n".format( frame_id, mission, body)) f.write(' FRAME_{}_CLASS = 4\n'.format(frame_id)) f.write(' FRAME_{}_CLASS_ID = {}\n'.format(frame_id, frame_id)) f.write(' FRAME_{}_CENTER = {}\n'.format(frame_id, body_id)) f.write('\n') f.write(" TKFRAME_{}_SPEC = 'ANGLES'\n".format(frame_id)) f.write(" TKFRAME_{}_RELATIVE = 'J2000'\n".format(frame_id)) f.write(' TKFRAME_{}_ANGLES = (\n'.format(frame_id)) f.write(' {}\n'.format(r3 * spiceypy.dpr())) f.write(' {}\n'.format(r2 * spiceypy.dpr())) f.write(' {}\n'.format(r1 * spiceypy.dpr())) f.write(' )\n') f.write(' TKFRAME_{}_AXES = (\n'.format(frame_id)) f.write(' 3,\n') f.write(' 2,\n') f.write(' 3\n') f.write(' )\n') f.write(" TKFRAME_{}_UNITS = 'DEGREES'\n".format(frame_id)) f.write('\n') f.write(r"\begintext") else: return '{}_IF->J2000 (3-2-3): {} - {} - {}'.format(body, r3 * spiceypy.dpr(), r2 * spiceypy.dpr(), r1 * spiceypy.dpr()) if unload: spiceypy.unload(pck) spiceypy.unload(body_spk) return def eul_angle_report(et_list, eul_ck1, eul_ck2, eul_num, tolerance, name=''): eul_error = list(numpy.degrees(abs(numpy.array(eul_ck1) - numpy.array(eul_ck2)))) count = 0 interval_bool = False eul_tol_list = [] with open('euler_angle_{}_{}_report.txt'.format(eul_num, name), 'w+') as f: f.write('EULER ANGLE {} REPORT \n'.format(eul_num)) f.write('==================== \n') for element in eul_error: if element >= tolerance: if interval_bool: eul_tol_list.append(element) else: interval_bool = True eul_tol_list.append(element) utc_start = spiceypy.et2utc(et_list[count], 'ISOC', 2) else: if interval_bool: utc_finish = spiceypy.et2utc(et_list[count], 'ISOC', 2) f.write('TOLERANCE of ' + str(tolerance) + ' DEG exceeded from ' + utc_start + ' until ' + utc_finish + ' with an average angle of ' + str(numpy.mean(eul_tol_list)) + ' DEG \n') interval_bool = False count += 1 f.write('\nMAX Error: {} DEG\n'.format(str(max(eul_error)))) f.write('MIN Error: {} DEG\n'.format(str(min(eul_error)))) f.write('MEAN Error: {} DEG\n'.format(str(numpy.mean(eul_error)))) return def attitude_error_report(et_list, ang_ck1, ang_ck2, tolerance, name=''): ang_error = list(abs(numpy.array(ang_ck1) - numpy.array(ang_ck2))) count = 0 interval_bool = False ang_tol_list = [] with open('attitude_error_{}_report.txt'.format(name), 'w+') as f: f.write('ATTITUDE ERROR REPORT \n') f.write('==================== \n') for element in ang_error: if element >= tolerance: if interval_bool: ang_tol_list.append(element) else: interval_bool = True ang_tol_list.append(element) utc_start = spiceypy.et2utc(et_list[count], 'ISOC', 2) else: if interval_bool: utc_finish = spiceypy.et2utc(et_list[count], 'ISOC', 2) f.write('TOLERANCE of ' + str(tolerance) + ' DEG exceeded from ' + utc_start + ' until ' + utc_finish + ' with an average angle of ' + str(numpy.mean(ang_tol_list)) + ' DEG \n') interval_bool = False count += 1 f.write('\nMAX Error: {} ARCSECONDS\n'.format(str(max(ang_error)))) f.write('MIN Error: {} ARCSECONDS\n'.format(str(min(ang_error)))) f.write('MEAN Error: {} ARCSECONDS\n'.format(str(numpy.mean(ang_error)))) return def state_report(et_list, pos_spk1, pos_spk2, vel_spk1, vel_spk2, pos_tolerance, vel_tolerance, name=''): pos_error = list(abs(numpy.array(pos_spk1) - numpy.array(pos_spk2))) vel_error = list(abs(numpy.array(vel_spk1) - numpy.array(vel_spk2))) count = 0 interval_bool = False pos_tol_list = [] with open('state_{}_report.txt'.format(name), 'w+') as f: f.write('STATE REPORT \n') f.write('============ \n') for element in pos_error: if element >= pos_tolerance: if interval_bool: pos_tol_list.append(element) else: interval_bool = True pos_tol_list.append(element) utc_start = spiceypy.et2utc(et_list[count], 'ISOC', 2) else: if interval_bool: utc_finish = spiceypy.et2utc(et_list[count], 'ISOC', 2) f.write('TOLERANCE of ' + str(pos_tolerance) + ' KM exceeded from ' + utc_start + ' until ' + utc_finish + ' with an average distance of ' + str(numpy.mean(pos_tol_list)) + ' KM \n') interval_bool = False count += 1 count = 0 interval_bool = False vel_tol_list = [] for element in vel_error: if element >= vel_tolerance: if interval_bool: vel_tol_list.append(element) else: interval_bool = True vel_tol_list.append(element) utc_start = spiceypy.et2utc(et_list[count], 'ISOC', 2) else: if interval_bool: utc_finish = spiceypy.et2utc(et_list[count], 'ISOC', 2) f.write('TOLERANCE of ' + str(vel_tolerance) + ' KM/S exceeded from ' + utc_start + ' until ' + utc_finish + ' with an average velocity of ' + str(numpy.mean(vel_tol_list)) + ' KM/S \n') count += 1 f.write('\nMAX Error: {} KM\n'.format(str(max(pos_error)))) f.write('MIN Error: {} KM\n'.format(str(min(pos_error)))) f.write('MEAN Error: {} KM\n'.format(str(numpy.mean(pos_error)))) f.write('\nMAX Error: {} KM/S\n'.format(str(max(vel_error)))) f.write('MIN Error: {} KM/S\n'.format(str(min(vel_error)))) f.write('MEAN Error: {} KM/S\n'.format(str(numpy.mean(vel_error)))) return def ckdiff_euler(mk, ck1, ck2, spacecraft_frame, target_frame, resolution, tolerance, utc_start='', utc_finish='', plot_style='line', report=True, notebook=False): """ Provides time coverage summary for a given object for a given CK file. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/ckcov_c.html The NAIF utility CKBRIEF can be used for the same purpose. :param ck: CK file to be used :type mk: str :param support_ker: Support kernels required to run the function. At least it should be a leapseconds kernel (LSK) and a Spacecraft clock kernel (SCLK) optionally a meta-kernel (MK) which is highly recommended. :type support_ker: Union[str, list] :param object: Ephemeris Object to obtain the coverage from. :type object: str :param time_format: Output time format; it can be 'UTC', 'CAL' (for TDB in calendar format) or 'TDB'. Default is 'TDB'. :type time_format: str :param global_boundary: Boolean to indicate whether if we want all the coverage windows or only the absolute start and finish coverage times. :type global_boundary: bool :param report: If True prints the resulting coverage on the screen. :type report: bool :param unload: If True it will unload the input meta-kernel. :type unload: bool :return: Returns a list with the coverage intervals. :rtype: list """ # Compute time windows spiceypy.furnsh(mk) windows_ck1 = cov_ck_ker(ck1, object=spacecraft_frame, time_format='SPICE') spiceypy.unload(ck1) windows_ck2 = cov_ck_ker(ck2, object=spacecraft_frame, time_format='SPICE') spiceypy.unload(ck2) windows_intersected = spiceypy.wnintd(windows_ck1, windows_ck2) number_of_intervals = list(range(spiceypy.wncard(windows_intersected))) et_boundaries_list = [] for element in number_of_intervals: et_boundaries = spiceypy.wnfetd(windows_intersected, element) et_boundaries_list.append(et_boundaries[0]) et_boundaries_list.append(et_boundaries[1]) start = True for et_start, et_finish in zip(et_boundaries_list[0::2], et_boundaries_list[1::2]): if start: et_list = numpy.arange(et_start, et_finish, resolution) start = False et_list = numpy.append(et_list, numpy.arange(et_start, et_finish, resolution)) if utc_start: et_start = spiceypy.utc2et(utc_start) if utc_finish: et_finish = spiceypy.utc2et(utc_finish) et_list = numpy.arange(et_start, et_finish, resolution) # Process CK1 spiceypy.furnsh(ck1) eul1_ck1 = [] eul2_ck1 = [] eul3_ck1 = [] for et in et_list: rot_mat = spiceypy.pxform(spacecraft_frame, target_frame, et) euler = (spiceypy.m2eul(rot_mat, 1, 2, 3)) eul1_ck1.append(math.degrees(euler[0])) eul2_ck1.append(math.degrees(euler[1])) eul3_ck1.append(math.degrees(euler[2])) spiceypy.unload(ck1) # Process CK2 spiceypy.furnsh(ck2) eul1_ck2 = [] eul2_ck2 = [] eul3_ck2 = [] for et in et_list: rot_mat = spiceypy.pxform(spacecraft_frame, target_frame, et) euler = (spiceypy.m2eul(rot_mat, 1, 2, 3)) eul1_ck2.append(math.degrees(euler[0])) eul2_ck2.append(math.degrees(euler[1])) eul3_ck2.append(math.degrees(euler[2])) spiceypy.unload(ck2) # Plot angles ck1_filename = ck1.split('/')[-1].split('.')[0] ck2_filename = ck2.split('/')[-1].split('.')[0] eul1_name = '{}_{}'.format(ck1_filename, ck2_filename) eul2_name = '{}_{}'.format(ck1_filename, ck2_filename) eul3_name = '{}_{}'.format(ck1_filename, ck2_filename) plot(et_list, [eul1_ck1, eul1_ck2], yaxis_name=['Euler Angle 1 CK1', 'Euler Angle 1 CK2'], title='Euler Angle 1 {}'.format(eul1_name), format=plot_style, notebook=notebook) plot(et_list, [eul2_ck1, eul2_ck2], yaxis_name=['Euler Angle 2 CK1', 'Euler Angle 2 CK2'], title='Euler Angle 2 {}'.format(eul2_name), format=plot_style, notebook=notebook) plot(et_list, [eul3_ck1, eul3_ck2], yaxis_name=['Euler Angle 3 CK1', 'Euler Angle 3 CK2'], title='Euler Angle 3 {}'.format(eul3_name), format=plot_style, notebook=notebook) # Generate reports if report: eul_angle_report(et_list, eul1_ck1, eul1_ck2, 1, tolerance, name=eul1_name) eul_angle_report(et_list, eul2_ck1, eul2_ck2, 2, tolerance, name=eul2_name) eul_angle_report(et_list, eul3_ck1, eul3_ck2, 3, tolerance, name=eul3_name) return def ckdiff(ck1, ck2, spacecraft_frame, target_frame, resolution, tolerance, utc_start='', utc_finish='', mk='', output='boresight', boresight = [0,0,1], plot_style='line', report=False, notebook=False): """ Provides time coverage summary for a given object for a given CK file. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/ckcov_c.html The NAIF utility CKBRIEF can be used for the same purpose. :param ck: CK file to be used :type mk: str :param support_ker: Support kernels required to run the function. At least it should be a leapseconds kernel (LSK) and a Spacecraft clock kernel (SCLK) optionally a meta-kernel (MK) which is highly recommended. :type support_ker: Union[str, list] :param object: Ephemeris Object to obtain the coverage from. :type object: str :param time_format: Output time format; it can be 'UTC', 'CAL' (for TDB in calendar format) or 'TDB'. Default is 'TDB'. :type time_format: str :param global_boundary: Boolean to indicate whether if we want all the coverage windows or only the absolute start and finish coverage times. :type global_boundary: bool :param report: If True prints the resulting coverage on the screen. :type report: bool :param unload: If True it will unload the input meta-kernel. :type unload: bool :return: Returns a list with the coverage intervals. :rtype: list """ if mk: spiceypy.furnsh(mk) windows_ck1 = cov_ck_ker(ck1, object=spacecraft_frame, time_format='SPICE') spiceypy.unload(ck1) windows_ck2 = cov_ck_ker(ck2, object=spacecraft_frame, time_format='SPICE') spiceypy.unload(ck2) windows_intersected = spiceypy.wnintd(windows_ck1, windows_ck2) number_of_intervals = list(range(spiceypy.wncard(windows_intersected))) et_boundaries_list = [] for element in number_of_intervals: et_boundaries = spiceypy.wnfetd(windows_intersected, element) et_boundaries_list.append(et_boundaries[0]) et_boundaries_list.append(et_boundaries[1]) start = True for et_start, et_finish in zip(et_boundaries_list[0::2], et_boundaries_list[1::2]): if start: et_list = numpy.arange(et_start, et_finish, resolution) start = False et_list = numpy.append(et_list, numpy.arange(et_start, et_finish, resolution)) if utc_start: et_start = spiceypy.utc2et(utc_start) if utc_finish: et_finish = spiceypy.utc2et(utc_finish) et_list = numpy.arange(et_start, et_finish, resolution) spiceypy.furnsh(ck1) eul1_ck1 = [] eul2_ck1 = [] eul3_ck1 = [] bsight_ck1 = [] for et in et_list: rot_mat = spiceypy.pxform(spacecraft_frame, target_frame, et) euler = (spiceypy.m2eul(rot_mat, 1, 2, 3)) eul1_ck1.append(math.degrees(euler[0])) eul2_ck1.append(math.degrees(euler[1])) eul3_ck1.append(math.degrees(euler[2])) bsight = spiceypy.mxv(rot_mat, boresight) bsight_ang = spiceypy.vsep(bsight, boresight) bsight_ck1.append(bsight_ang*spiceypy.dpr()) spiceypy.unload(ck1) spiceypy.furnsh(ck2) eul1_ck2 = [] eul2_ck2 = [] eul3_ck2 = [] bsight_ck2 = [] for et in et_list: rot_mat = spiceypy.pxform(spacecraft_frame, target_frame, et) euler = (spiceypy.m2eul(rot_mat, 1, 2, 3)) eul1_ck2.append(math.degrees(euler[0])) eul2_ck2.append(math.degrees(euler[1])) eul3_ck2.append(math.degrees(euler[2])) bsight = spiceypy.mxv(rot_mat, boresight) bsight_ang = spiceypy.vsep(bsight, boresight) bsight_ck2.append(bsight_ang*spiceypy.dpr()) spiceypy.unload(ck2) ck1_filename = ck1.split('/')[-1].split('.')[0] ck2_filename = ck2.split('/')[-1].split('.')[0] title_name = '{}_{}'.format(ck1_filename, ck2_filename) if output == 'euler_angles': plot(et_list, [eul1_ck1,eul1_ck2], yaxis_name=['Degrees', 'Degrees'], title='Euler Angle 1 {}'.format(title_name), format=plot_style, notebook=notebook) plot(et_list, [eul2_ck1,eul2_ck2], yaxis_name=['Degrees', 'Degrees'], title='Euler Angle 2 {}'.format(title_name), format=plot_style, notebook=notebook) plot(et_list, [eul3_ck1,eul3_ck2], yaxis_name=['Degrees', 'Degrees'], title='Euler Angle 3 {}'.format(title_name), format=plot_style, notebook=notebook) else: plot(et_list, [bsight_ck1], yaxis_name=['Degrees', 'Degrees'], title='+Z Axis Angle Difference {}'.format(title_name), format=plot_style, notebook=notebook) if report: eul_angle_report(et_list, eul1_ck1, eul1_ck2, 1, tolerance, name=title_name) eul_angle_report(et_list, eul2_ck1, eul2_ck2, 2, tolerance, name=title_name) eul_angle_report(et_list, eul3_ck1, eul3_ck2, 3, tolerance, name=title_name) return def get_euler_boresights_angles(ck, et_list, spacecraft_frame, target_frame, boresight): spiceypy.furnsh(ck) eul1 = [] eul2 = [] eul3 = [] bsights = [] angles = [] for et in et_list: rot_mat = spiceypy.pxform(spacecraft_frame, target_frame, et) euler = (spiceypy.m2eul(rot_mat, 1, 2, 3)) eul1.append(math.degrees(euler[0])) eul2.append(math.degrees(euler[1])) eul3.append(math.degrees(euler[2])) bsight = spiceypy.mxv(rot_mat, boresight) bsight_ang = spiceypy.vsep(bsight, boresight) bsights.append(spiceypy.convrt(bsight_ang, 'RADIANS', 'ARCSECONDS')) (rot_axis, rot_angle) = spiceypy.raxisa(rot_mat) angles.append(spiceypy.convrt(rot_angle, 'RADIANS', 'ARCSECONDS')) spiceypy.unload(ck) return eul1, eul2, eul3, bsights, angles def ckdiff_error(ck1, ck2, spacecraft_frame, target_frame, resolution, tolerance, mk='', utc_start='', utc_finish='', output='', boresight=[0,0,1], plot_style='line', report=False, notebook=False): """ Provides time coverage summary for a given object for a given CK file. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/ckcov_c.html The NAIF utility CKBRIEF can be used for the same purpose. :param ck: CK file to be used :type mk: str :param support_ker: Support kernels required to run the function. At least it should be a leapseconds kernel (LSK) and a Spacecraft clock kernel (SCLK) optionally a meta-kernel (MK) which is highly recommended. :type support_ker: Union[str, list] :param object: Ephemeris Object to obtain the coverage from. :type object: str :param time_format: Output time format; it can be 'UTC', 'CAL' (for TDB in calendar format) or 'TDB'. Default is 'TDB'. :type time_format: str :param global_boundary: Boolean to indicate whether if we want all the coverage windows or only the absolute start and finish coverage times. :type global_boundary: bool :param report: If True prints the resulting coverage on the screen. :type report: bool :param unload: If True it will unload the input meta-kernel. :type unload: bool :return: Returns a list with the coverage intervals. :rtype: list """ if mk: spiceypy.furnsh(mk) try: windows_ck1 = cov_ck_ker(ck1, object=spacecraft_frame, time_format='SPICE') spiceypy.unload(ck1) windows_ck2 = cov_ck_ker(ck2, object=spacecraft_frame, time_format='SPICE') spiceypy.unload(ck2) except: print('WARNING: No Time Window could be determined') return None windows_intersected = spiceypy.wnintd(windows_ck1, windows_ck2) number_of_intervals = list(range(spiceypy.wncard(windows_intersected))) if not len(number_of_intervals): print('WARNING: No Time Windows intersected') return None et_boundaries_list = [] for element in number_of_intervals: et_boundaries = spiceypy.wnfetd(windows_intersected, element) et_boundaries_list.append(et_boundaries[0]) et_boundaries_list.append(et_boundaries[1]) start = True for et_start, et_finish in zip(et_boundaries_list[0::2], et_boundaries_list[1::2]): if start: et_list = numpy.arange(et_start, et_finish, resolution) start = False et_list = numpy.append(et_list, numpy.arange(et_start, et_finish, resolution)) if utc_start: et_start = spiceypy.utc2et(utc_start) if utc_finish: et_finish = spiceypy.utc2et(utc_finish) et_list = numpy.arange(et_start, et_finish, resolution) if not len(et_list): print('WARNING: No valid time period') return None eul1_ck1, eul2_ck1, eul3_ck1, bsight_ck1, angle_ck1 = get_euler_boresights_angles(ck1, et_list, spacecraft_frame, target_frame, boresight) eul1_ck2, eul2_ck2, eul3_ck2, bsight_ck2, angle_ck2 = get_euler_boresights_angles(ck2, et_list, spacecraft_frame, target_frame, boresight) angle_diff = [abs(i - j) for i, j in zip(angle_ck1, angle_ck2)] if output == 'euler_angles': eul1_diff = [i - j for i, j in zip(eul1_ck1, eul1_ck2)] eul2_diff = [i - j for i, j in zip(eul2_ck1, eul2_ck2)] eul3_diff = [i - j for i, j in zip(eul3_ck1, eul3_ck2)] plot(et_list, [eul1_diff, eul2_diff, eul3_diff], yaxis_name=['Degrees', 'Degrees', 'Degrees'], title='Euler Angle Differences', format=plot_style, yaxis_units='deg', notebook=notebook) elif output == 'boresight': bsight_diff = [np.abs(i - j) for i, j in zip(bsight_ck1, bsight_ck2)] plot(et_list, bsight_diff, yaxis_name='', title='Boresight Angle Difference', format=plot_style, yaxis_units='arcsec', notebook=notebook) # Attitude Error else: plot(et_list, angle_diff, yaxis_name='ang_diff', title='Attitude Error', format=plot_style, yaxis_units='arcsec', notebook=notebook) if report: ck1_filename = ck1.split('/')[-1].split('.')[0] ck2_filename = ck2.split('/')[-1].split('.')[0] bsight_name = '{}_{}'.format(ck1_filename, ck2_filename) attitude_error_report(et_list, bsight_ck1, bsight_ck2, tolerance, name=bsight_name) if output == 'euler_angles': eul1_name = '{}_{}'.format(ck1_filename, ck2_filename) eul2_name = '{}_{}'.format(ck1_filename, ck2_filename) eul3_name = '{}_{}'.format(ck1_filename, ck2_filename) eul_angle_report(et_list, eul1_ck1, eul1_ck2, 1, tolerance, name=eul1_name) eul_angle_report(et_list, eul2_ck1, eul2_ck2, 2, tolerance, name=eul2_name) eul_angle_report(et_list, eul3_ck1, eul3_ck2, 3, tolerance, name=eul3_name) elif output == 'rotaxis': rotaxis_name = '{}_{}'.format(ck1_filename, ck2_filename) attitude_error_report(et_list, angle_ck1, angle_ck2, tolerance, name=rotaxis_name) if mk: spiceypy.unload(mk) return np.max(angle_diff) def ckplot(ck1, spacecraft_frame, target_frame, resolution, mk = '', utc_start='', utc_finish='', notebook=False, plot_style='circle'): """ Provides time coverage summary for a given object for a given CK file. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/ckcov_c.html The NAIF utility CKBRIEF can be used for the same purpose. :param ck: CK file to be used :type mk: str :param support_ker: Support kernels required to run the function. At least it should be a leapseconds kernel (LSK) and a Spacecraft clock kernel (SCLK) optionally a meta-kernel (MK) which is highly recommended. :type support_ker: Union[str, list] :param object: Ephemeris Object to obtain the coverage from. :type object: str :param time_format: Output time format; it can be 'UTC', 'CAL' (for TDB in calendar format) or 'TDB'. Default is 'TDB'. :type time_format: str :param global_boundary: Boolean to indicate whether if we want all the coverage windows or only the absolute start and finish coverage times. :type global_boundary: bool :param report: If True prints the resulting coverage on the screen. :type report: bool :param unload: If True it will unload the input meta-kernel. :type unload: bool :return: Returns a list with the coverage intervals. :rtype: list """ if mk: spiceypy.furnsh(mk) spiceypy.furnsh(ck1) et_boundaries_list = cov_ck_ker(ck1, support_ker=mk, object=spacecraft_frame, time_format='TDB') start = True for et_start, et_finish in zip(et_boundaries_list[0::2], et_boundaries_list[1::2]): if start: et_list = numpy.arange(et_start, et_finish, resolution) start = False et_list = numpy.append(et_list, numpy.arange(et_start, et_finish, resolution)) # TODO: if we want to really use start and end times and intersect it with the available intervals we need to develop this if utc_start: et_start = spiceypy.utc2et(utc_start) if utc_finish: et_finish = spiceypy.utc2et(utc_finish) et_list = numpy.arange(et_start, et_finish, resolution) eul1 = [] eul2 = [] eul3 = [] for et in et_list: rot_mat = spiceypy.pxform(spacecraft_frame, target_frame,et) euler = spiceypy.m2eul(rot_mat, 1, 2, 3) eul1.append(math.degrees(euler[0])) eul2.append(math.degrees(euler[1])) eul3.append(math.degrees(euler[2])) spiceypy.unload(ck1) plot(et_list, [eul1,eul2,eul3], yaxis_name=['Euler Angle 1', 'Euler Angle 2', 'Euler Angle 3'], title='Euler Angles for {}'.format(ck1.split('/')[-1]), notebook=notebook, format=plot_style) return def spkdiff(mk, spk1, spk2, spacecraft, target, resolution, pos_tolerance, vel_tolerance, target_frame='', utc_start='', utc_finish='', plot_style='line', report=True): """ Provides time coverage summary for a given object for a given CK file. Several options are available. This function is based on the following SPICE API: http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/spiceypy/ckcov_c.html The NAIF utility CKBRIEF can be used for the same purpose. :param ck: CK file to be used :type mk: str :param support_ker: Support kernels required to run the function. At least it should be a leapseconds kernel (LSK) and a Spacecraft clock kernel (SCLK) optionally a meta-kernel (MK) which is highly recommended. :type support_ker: Union[str, list] :param object: Ephemeris Object to obtain the coverage from. :type object: str :param time_format: Output time format; it can be 'UTC', 'CAL' (for TDB in calendar format) or 'TDB'. Default is 'TDB'. :type time_format: str :param global_boundary: Boolean to indicate whether if we want all the coverage windows or only the absolute start and finish coverage times. :type global_boundary: bool :param report: If True prints the resulting coverage on the screen. :type report: bool :param unload: If True it will unload the input meta-kernel. :type unload: bool :return: Returns a list with the coverage intervals. :rtype: list """ if not target_frame: target_frame = 'IAU_{}'.format(target.upper()) spiceypy.furnsh(mk) windows_spk1 = cov_spk_ker(spk1, object=spacecraft, time_format='SPICE') spiceypy.unload(spk1) windows_spk2 = cov_spk_ker(spk2, object=spacecraft, time_format='SPICE') spiceypy.unload(spk2) windows_intersected = spiceypy.wnintd(windows_spk1, windows_spk2) number_of_intervals = list(range(spiceypy.wncard(windows_intersected))) et_boundaries_list = [] for element in number_of_intervals: et_boundaries = spiceypy.wnfetd(windows_intersected, element) et_boundaries_list.append(et_boundaries[0]) et_boundaries_list.append(et_boundaries[1]) start = True for et_start, et_finish in zip(et_boundaries_list[0::2], et_boundaries_list[1::2]): if start: et_list = np.arange(et_start, et_finish, resolution) start = False et_list = numpy.append(et_list, numpy.arange(et_start, et_finish, resolution)) if utc_start: et_start = spiceypy.utc2et(utc_start) if utc_finish: et_finish = spiceypy.utc2et(utc_finish) et_list = numpy.arange(et_start, et_finish, resolution) spiceypy.furnsh(spk1) state_spk1 = [] state_spk2 = [] pos_spk1 = [] pos_spk2 = [] vel_spk1 = [] vel_spk2 = [] for et in et_list: state = spiceypy.spkezr(target, et, target_frame, 'NONE', spacecraft)[0] state_spk1.append(state) pos_spk1.append(np.sqrt(state[0]*state[0] + state[1]*state[1] + state[2]*state[2])) vel_spk1.append(np.sqrt(state[3]*state[3] + state[4]*state[4] + state[5]*state[5])) spiceypy.unload(spk1) spiceypy.furnsh(spk2) for et in et_list: state = spiceypy.spkezr(target, et, target_frame, 'NONE', spacecraft)[0] state_spk2.append(state) pos_spk2.append(np.sqrt(state[0]*state[0] + state[1]*state[1] + state[2]*state[2])) vel_spk2.append(np.sqrt(state[3]*state[3] + state[4]*state[4] + state[5]*state[5])) plot(et_list, [pos_spk1, pos_spk2], yaxis_name=['Position SPK1', 'Position SPK2'], title='Position of {} w.r.t {} ({})'.format(spacecraft, target, target_frame), format=plot_style) spiceypy.unload(spk2) if report: spk1_filename = spk1.split('/')[-1].split('.')[0] spk2_filename = spk2.split('/')[-1].split('.')[0] state_report(et_list, pos_spk1, pos_spk2, vel_spk1, vel_spk2, pos_tolerance, vel_tolerance, name='{}_{}'.format(spk1_filename, spk2_filename)) return def pck_body_placeholder(bodies): """ :param bodies: :type bodies: :return: :rtype: """ with open('update_to_pck.tpc', 'w+') as f: pl_id = 517 for body in bodies: # # Get body NAIF ID. # try: id = spiceypy.bodn2c(str(body.upper)) except: id = pl_id pl_id += 1 f.write(' {0} {1} 1 1 1 - Placeholder radii\n'.format(id, body[:1].upper() + body[1:].lower())) f.write('\n\n') pl_id = 517 for body in bodies: # # Get body NAIF ID. # try: id = spiceypy.bodn2c(str(body.upper)) except: id = pl_id pl_id += 1 f.write('BODY{}_RADII = (1 1 1 )\n'.format(id)) f.write('\n\n') pl_id = 517 for body in bodies: # # Get body NAIF ID. # try: id = spiceypy.bodn2c(str(body.upper)) except: id = pl_id pl_id += 1 f.write(" FRAME_IAU_{0} = {1}\n".format(body.upper(), id)) f.write(" FRAME_{0}_NAME = 'IAU_{1}'\n".format(id, body.upper())) f.write(" FRAME_{}_CLASS = 2\n".format(id)) f.write(" FRAME_{0}_CLASS_ID = {0}\n".format(id)) f.write(" FRAME_{0}_CENTER = {0}\n".format(id)) f.write(" BODY{}_POLE_RA = ( 0. 0. 0. )\n".format(id)) f.write(" BODY{}_POLE_DEC = ( 90. 0. 0. )\n".format(id)) f.write(" BODY{}_PM = ( -90. 0. 0. )\n".format(id)) f.write(" BODY{}_LONG_AXIS = ( 0. )\n\n".format(id)) return def read_ik_with_sectors(sensor_name): # # Since all IK variable names contain NAIF ID of the instrument, # the input sensor acronym, NNN, needs to be expanded into its # full name, ROS_RPC_NNN, which then can be used to find the # sensor's NAIF ID code. # sensnm = sensor_name secsiz = 0 secsis = 0 try: sensid = spiceypy.bodn2c(sensnm) except: print('Cannot determine NAIF ID for {}'.format(sensnm)) return sensnm, 0, 0, secsiz, secsis, '', [] # # No IK routines can be used to retrieve loaded data. First, # retrieve the number of sectors provided in the # INS-NNNNNN_NUMBER_OF_SECTORS keyword (here -NNNNNN is the NAIF ID # of the sensor.) # ikkwd = 'INS#_NUMBER_OF_SECTORS' ikkwd = spiceypy.repmi(ikkwd, "#", sensid) try: secnum = spiceypy.gipool(ikkwd, 0, 2) except: print('Loaded IK does not contain {}.'.format(ikkwd)) return sensnm, sensid, 0, secsiz, secsis, '', [] # # Second, retrieve the sector size provided in the # INS-NNNNNN_SECTOR_SIZE or INS-NNNNNN_SECTOR_SIZES keyword. # ikkwd = 'INS#_SECTOR_SIZES' ikkwd = spiceypy.repmi(ikkwd, '#', sensid) try: secsis = spiceypy.gdpool(ikkwd, 0, 2) # # We need to search for INS-NNNNNN_SECTOR_SIZE in the second place # for it would also be found by INS-NNNNNN_SECTOR_SIZES # except: ikkwd = 'INS#_SECTOR_SIZE' ikkwd = spiceypy.repmi(ikkwd, '#', sensid) try: room = int(secnum[0]*secnum[1]*2) secsiz = spiceypy.gdpool(ikkwd, 0, room) except: print('Loaded IK does not contain {}.'.format(ikkwd)) return sensnm, sensid, secnum, secsiz, secsis, '', [] # # Third, retrieve the frame in which sector view direction are # defined. It is provided in the INS-NNNNNN_FRAME keyword. # ikkwd = 'INS#_FRAME' ikkwd = spiceypy.repmi(ikkwd, '#', sensid) try: secfrm = spiceypy.gcpool(ikkwd, 0, 1) except: print('Loaded IK does not contain {}.'.format(ikkwd)) return sensnm, sensid, secnum, secsiz, secsis, secfrm, [] # # Last, retrieve the sector view directions provided in the # INS-NNNNNN_SECTOR_DIRECTIONS keyword. # ikkwd = 'INS#_SECTOR_DIRECTIONS' ikkwd = spiceypy.repmi(ikkwd, '#', sensid) try: room = int(secnum[0]*secnum[1]*3) secdir = spiceypy.gdpool(ikkwd, 0, room) # # Re-arrange the secdir list into a list of lists in which each # individual list is a sector direction vector # secdir_list = [] secdir_line = [] count = 0 for element in secdir: # Start counting from 1 secdir_line.append(element) count += 1 if count % 3 == 0: secdir_list.append(secdir_line) secdir_line = [] count = 0 secdir = secdir_list except: print('Loaded IK does not contain {}.'.format(ikkwd)) return sensnm, sensid, secnum, secsiz, secsis, secfrm, [] return sensnm, sensid, secnum, secsiz, secsis, secfrm, secdir #def mex_tgo_occultations(interval, refval): # (out, radii) = spiceypy.bodvrd('MARS', 'RADII', 3) # # # Compute flattening coefficient. # re = radii[0] # rp = radii[2] # f = (re - rp) / re # # a = re # b = radii[1] # c = rp # # MAXIVL = 10000 # MAXWIN = 2 * MAXIVL # TDBFMT = 'YYYY MON DD HR:MN:SC.### (TDB) ::TDB' # # # Initialize the "confinement" window with the interval # # over which we'll conduct the search. # cnfine = stypes.SPICEDOUBLE_CELL(2) # spiceypy.wninsd(interval.start, interval.finish, cnfine) # # # # # In the call below, the maximum number of window # # intervals gfposc can store internally is set to MAXIVL. # # We set the cell size to MAXWIN to achieve this. # # # riswin = stypes.SPICEDOUBLE_CELL(MAXWIN) # # # # # Now search for the time period, within our confinement # # window, during which the apparent target has elevation # # at least equal to the elevation limit. # # # # VARIABLE I/O DESCRIPTION # # --------------- --- ------------------------------------------------- # # SPICE_GF_CNVTOL P Convergence tolerance. # # occtyp I Type of occultation. # # front I Name of body occulting the other. # # fshape I Type of shape model used for front body. # # fframe I Body-fixed, body-centered frame for front body. # # back I Name of body occulted by the other. # # bshape I Type of shape model used for back body. # # bframe I Body-fixed, body-centered frame for back body. # # abcorr I Aberration correction flag. # # obsrvr I Name of the observing body. # # step I Step size in seconds for finding occultation # # events. # # cnfine I-O SPICE window to which the search is restricted. # # result O SPICE window containing results. # # # spiceypy.gfoclt('ANY', 'MARS', 'ELLIPSOID', 'IAU_MARS', 'MEX', # 'POINT', '', 'NONE', 'TGO', 60, cnfine, riswin) # # # # # Now we perform another search to constrain the number of occultations by a # # distance criteria # # # cnfine = riswin # # riswin = stypes.SPICEDOUBLE_CELL(MAXWIN) # # # # # We're not using the adjustment feature, so # # we set `adjust' to zero. # # # adjust = 0.0 # # # # # We use a step size of 1 hour # # # step = 60 * 60 # # # nintvls = 2*n + ( m / step ) # # # # where # # # # n is the number of intervals in the confinement # # window # # # # m is the measure of the confinement window, in # # units of seconds # # # # step is the search step size in seconds # # # ndays = 100 # nintvls = int(2 * 1 + (ndays * 24 * 60 * 60 / step)) # # # # # Now search for the time period, within our confinement # # window, during which the apparent target has elevation # # at least equal to the elevation limit. # # # # VARIABLE I/O DESCRIPTION # # --------------- --- ------------------------------------------------ # # SPICE_GF_CNVTOL P Convergence tolerance # # target I Name of the target body. # # abcorr I Aberration correction flag. # # obsrvr I Name of the observing body. # # relate I Relational operator. # # refval I Reference value. # # adjust I Adjustment value for absolute extrema searches. # # step I Step size used for locating extrema and roots. # # nintvls I Workspace window interval count. # # # # cnfine I-O SPICE window to which the search is confined. # # result O SPICE window containing results. # # # spiceypy.gfdist('MEX', 'NONE', 'TGO', '<', refval, adjust, step, nintvls, # cnfine, riswin) # # # # # The function wncard returns the number of intervals # # in a SPICE window. # # # winsiz = spiceypy.wncard(riswin) # # lat_mid_list = [] # lon_mid_list = [] # dist_mid_list = [] # # lat_list = [] # lon_list = [] # dist_list = [] # # x, y, z = [], [], [] # # if winsiz == 0: # print('No events were found.') # # else: # # # # # Display the visibility time periods. # # # print( # 'Occultation times of {0:s} as seen from {1:s} when the distance is ' # 'less than {2:f} km:\n'.format('MEX', 'TGO', refval)) # # for i in range(winsiz): # # # # Fetch the start and stop times of # # the ith interval from the search result # # window riswin. # # # [intbeg, intend] = spiceypy.wnfetd(riswin, i) # # # # # Convert the rise time to a TDB calendar string. # # # timstr = spiceypy.timout(intbeg, TDBFMT) # et_rise = intbeg # # # # # Write the string to standard output. # # # # if i == 0: # # # # print('Occultation start time:' # # ' {:s}'.format(timstr)) # # else: # # # # print('Occultation start time:' # # ' {:s}'.format(timstr)) # # # # # # Convert the set time to a TDB calendar string. # # # timstr = spiceypy.timout(intend, TDBFMT) # et_set = intend # # # # # Write the string to standard output. # # # # if i == (winsiz - 1): # # # # print('Occultation or window stop time: ' # # ' {:s}'.format(timstr)) # # else: # # # # print('Occultation stop time: ' # # ' {:s}'.format(timstr)) # # # # print(' ') # # # # # Generate a Time Window with the rise and set times # # # utc_rise = spiceypy.et2utc(et_rise, 'ISOC', 3) # utc_set = spiceypy.et2utc(et_set, 'ISOC', 3) # # time_window = spiops.TimeWindow(utc_rise, utc_set, resolution=1) # # interval = time_window.window # num = 0 # for et in interval: # # num += 1 # # (linept, lt) = spiceypy.spkpos('MARS', et, 'IAU_MARS', 'NONE', # 'TGO') # (linedr, lt) = spiceypy.spkpos('MEX', et, 'IAU_MARS', 'NONE', # 'TGO') # # # # # Variable I/O Description # # -------- --- -------------------------------------------------- # # a I Length of ellipsoid's semi-axis in the x direction # # b I Length of ellipsoid's semi-axis in the y direction # # c I Length of ellipsoid's semi-axis in the z direction # # linept I Point on line # # linedr I Direction vector of line # # pnear O Nearest point on ellipsoid to line # # dist O Distance of ellipsoid from line # # # (pnear, dist) = spiceypy.npedln(a, b, c, linept, linedr) # # (lon, lat, alt) = spiceypy.recpgr('MARS', pnear, re, f) # # lon = spiceypy.dpr() * lon # lat = spiceypy.dpr() * lat # # lon_list.append(lon) # lat_list.append(lat) # dist_list.append(spiceypy.vnorm(linedr)) # # if num == int(len(interval) / 2): # lon_mid_list.append(lon) # lat_mid_list.append(lat) # dist_mid_list.append(spiceypy.vnorm(linedr)) # # spiops.plot(lon_mid_list, [lat_mid_list], # xaxis_name='Longitude [deg]', # yaxis_name=['Latitude [deg]'], # title='TGO-MEX Occultation Groundtrack for MEX-TGO Distance < {}km'.format( # refval), # plot_height=500, # plot_width=900, # format='circle', # background_image=True, # line_width=6) # # spiops.plot(lon_list, [lat_list], # xaxis_name='Longitude [deg]', # yaxis_name=['Latitude [deg]'], # title='TGO-MEX Occultation Groundtrack for MEX-TGO Distance < {}km'.format( # refval), # plot_height=500, # plot_width=900, # format='circle', # background_image=True, # line_width=1) # # return def sensor_with_sectors(sensor, mk, fk=''): # # Load ROS FK and RPC IK files. # spiceypy.furnsh(mk) if fk: spiceypy.furnsh(fk) # # Get ELS IK data. # sensnm, sensid, secnum, secsiz, secsis, secfrm, secdir = read_ik_with_sectors(sensor) # # Report ELS IK data. # print('SENSOR NAIF NAME: {}'.format(sensnm)) print('SENSOR NAIF ID: {}'.format(sensid)) print('NUMBER OF SECTORS: {}'.format(secnum)) #if secsiz != 0: # print('SECTOR SIZE: {}'.format(secsiz)) #else: # print('SECTOR SIZES: {}'.format(secsis)) print('REFERENCE FRAME: {}'.format(secfrm)) print('SECTOR DIRECTIONS: {}'.format(secdir)) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for element in secdir: x = element[0] y = element[1] z = element[2] ax.scatter(x, y, z, c='r', marker='o') ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') ax.set_zlabel('Z Axis') ax.autoscale(tight=True) plt.show() return def get_angle(frame1, frame2, et): angle = 0 angle_bool = False try: # Get the rotation matrix between two frames cmat = spiceypy.pxform(frame1, frame2, et) (angle3, angle2, angle1) = spiceypy.m2eul(cmat, 3, 2, 1) for tmp_angle in [angle3, angle2, angle1]: if np.around(tmp_angle, 2) != 0: angle = np.rad2deg(tmp_angle) angle_bool = True except ValueError as e: print(e) return angle, angle_bool def get_earth_angle(frame, et, obs): try: (earth_vec, lt) = spiceypy.spkezr('EARTH', et, frame, 'LT+S', obs) return np.rad2deg(spiceypy.vsep([0, 0, 1], earth_vec[:3])) except: return 0 def hga_angles(sc, et): hga_el_frame = sc + '_HGA_EL' hga_az_frame = sc + '_HGA_AZ' hga_frame = sc + '_HGA' if sc == 'MPO': # First azimuth and then the elevation hga_az, hga_az_bool = get_angle('MPO_HGA_APM', hga_az_frame, et) if hga_az_bool: hga_az = -hga_az + 180 # Invert azimuth and add half revolution hga_el, hga_el_bool = get_angle(hga_az_frame, hga_el_frame, et) elif sc == 'MTM': return [] else: hga_zero_frame = sc + '_SPACECRAFT' # First elevation and then the azimuth hga_el, hga_el_bool = get_angle(hga_zero_frame, hga_el_frame, et) hga_az, hga_az_bool = get_angle(hga_el_frame, hga_az_frame, et) hga_earth = get_earth_angle(hga_frame, et, sc) return [hga_az, hga_el], hga_earth def mga_angles(sc, et): if sc == 'MPO': # First azimuth and then the elevation mga_az, mga_az_bool = get_angle('MPO_MGA_BOOM-H', 'MPO_MGA_BOOM', et) mga_el, mga_el_bool = get_angle('MPO_MGA_ZERO', 'MPO_MGA', et) mga_earth = get_earth_angle('MPO_MGA', et, 'MPO') return [mga_az, mga_el], mga_earth return [0, 0], 0 def solar_aspect_angles(sc, time): sa_frame = '' if sc == 'TGO': sa_p_frame = sc+'_SA+Z' sa_n_frame = sc+'_SA-Z' elif sc == 'MPO': sa_frame = sc+'_SA' elif sc == 'MTM': sa_p_frame = sc + '_SA+X' sa_n_frame = sc + '_SA-X' else: sa_p_frame = sc+'_SA+Y' sa_n_frame = sc+'_SA-Y' sc_id = spiceypy.bodn2c(sc) try: # If there is only one Solar Array e.g.: BEPICOLOMBO MPO if sa_frame: (sun_vec, lt) = spiceypy.spkezp(10, time, sa_frame, 'NONE', sc_id) saa_sa = np.rad2deg(spiceypy.vsep([1, 0, 0], sun_vec)) else: (sun_vec, lt) = spiceypy.spkezp(10, time, sa_p_frame, 'NONE', sc_id) saa_sa_p = np.rad2deg(spiceypy.vsep([1, 0, 0], sun_vec)) (sun_vec, lt) = spiceypy.spkezp(10, time, sa_n_frame, 'NONE', sc_id) saa_sa_n = np.rad2deg(spiceypy.vsep([1, 0, 0], sun_vec)) (sun_vec, lt) = spiceypy.spkezp(10, time, sc+'_SPACECRAFT', 'NONE', sc_id) saa_sc_x = np.rad2deg(spiceypy.vsep([1, 0, 0], sun_vec)) saa_sc_y = np.rad2deg(spiceypy.vsep([0, 1, 0], sun_vec)) saa_sc_z = np.rad2deg(spiceypy.vsep([0, 0, 1], sun_vec)) except: #print('No CK information for {}'.format(time)) saa_sa, saa_sa_p, saa_sa_n, saa_sc_x, saa_sc_y, saa_sc_z = 0,0,0,0,0,0 if sa_frame: return([saa_sa], [saa_sc_x, saa_sc_y, saa_sc_z]) else: return ([saa_sa_p, saa_sa_n], [saa_sc_x, saa_sc_y, saa_sc_z]) def solar_array_angles(sa_frame, time): # Rotation axis must be angle 3 to have a range of [-pi, pi], the # rotation axis is derived from the FK. if 'MPO' in sa_frame: sa_zero_frame = 'MPO_SA_SADM' elif 'MEX' in sa_frame: sa_zero_frame = sa_frame + '_GIMBAL' else: sa_zero_frame = sa_frame + '_ZERO' try: #TODO This works for JUICE only in principle. # Get the rotation matrix between two frames cmat = spiceypy.pxform(sa_frame, sa_zero_frame, time) (angle3, angle2, angle1) = spiceypy.m2eul(cmat, 2, 3, 1) except: # print('No CK information for {}'.format(time)) angle3 = 0 angle2 = 0 angle1 = 0 return(np.round(angle3*spiceypy.dpr(),3), np.round(angle2*spiceypy.dpr(),3), np.round(angle1*spiceypy.dpr(),3)) def structures_position(sc_frame, kernel, time): return def body_distance_to_plane(body_distance, body_plane, time): body_1 = body_plane body_2 = body_distance if isinstance(time, str): time = spiceypy.utc2et(time) id_1 = spiceypy.bodn2c(body_1) id_2 = spiceypy.bodn2c(body_2) mat = spiceypy.pxform('MEX_SIDING_SPRING_PLANE','IAU_MARS', time) vec1_1 = spiceypy.mxv(mat, [1,0,0]) vec2_1 = spiceypy.mxv(mat, [0,1,0]) state_1 = spiceypy.spkgeo(id_2, time, 'IAU_MARS', id_1)[0] pos_1 = state_1[0:3] vel_1 = state_1[2:5] pos_2 = [0,0,0] norm_1 = np.cross(vec1_1,vec2_1) norm_1 = norm_1/np.linalg.norm(norm_1) # https://mathinsight.org/distance_point_plane a1, b1, c1 = norm_1[0], norm_1[1], norm_1[2] d1 = -1*norm_1[0]*pos_1[0] - norm_1[1]*pos_1[1] - norm_1[2]*pos_1[2] dist_1 = abs(a1 * pos_2[0] + b1 * pos_2[1] + c1 * pos_2[2] + d1) / np.sqrt( np.square(a1) + np.square(b1) +
np.square(c1)
numpy.square
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # s_order_imbal_signal [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_order_imbal_signal&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-signals-order-imbalance). # + import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import datetime from arpym.tools import trade_quote_processing, add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_order_imbal_signal-parameters) k_0 = 0 # index of the first trade within the time window k_1 = 192 # index of the last trade within the time window # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_order_imbal_signal-implementation-step00): Load data # + path = '../../../databases/global-databases/high-frequency/' + \ 'db_US_10yr_Future_quotestrades/' quotes = pd.read_csv(path + 'quotes.csv', index_col=0, parse_dates=True) trades = pd.read_csv(path + 'trades.csv', index_col=0, parse_dates=True) dates_quotes = pd.to_datetime(quotes.index).date # time vector of quotes t = np.array(list(map(lambda x: x.timestamp(), pd.to_datetime(quotes.index)))) p_bid = np.array(quotes.loc[:, 'bid']) # best bids p_ask = np.array(quotes.loc[:, 'ask']) # best asks q_bid = np.array(quotes.loc[:, 'bsiz']) # bid sizes q_ask = np.array(quotes.loc[:, 'asiz']) # ask sizes dates_trades = pd.to_datetime(trades.index).date # time vector of trades t_k = np.array(list(map(lambda x: x.timestamp(), pd.to_datetime(trades.index)))) p_last = np.array(trades.loc[:, 'price']) # last transaction values delta_q = np.array(trades.loc[:, 'siz']) # flow of traded contracts' sizes delta_sgn = np.array(trades.loc[:, 'aggress']) # trade sign flow match = np.array(trades.loc[:, 'mtch']) # match events # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_order_imbal_signal-implementation-step01): Process the database t, _, q_ask, p_ask, q_bid, p_bid, t_k, _, p_last, _, _,\ _ = trade_quote_processing(t, dates_quotes, q_ask, p_ask, q_bid, p_bid, t_k, dates_trades, p_last, delta_q, delta_sgn, match) # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_order_imbal_signal-implementation-step02): Compute the traded price, the bid/ask prices, the bid/ask sizes and the microprice # + tick_time = np.arange(len(p_last[k_0:k_1+1])+1) i_ = len(tick_time) # last transaction value within the time window as a function of tick time p_last_k = p_last[k_0:k_1] # indexes of bid/ask prices near to the traded prices ti =
np.zeros(i_, dtype=int)
numpy.zeros
#-*- coding:utf-8 -*- ''' 目的: 用于对复杂网络相关的分析,创建网络,计算网络特征等 结合了networkx, igraph, pygrahistry的接口 方法: * 从边数据生成网络 - get_graph_from_edgedata * 从边数据获取节点 - get_nodes_from_edgedata * 将有向边转化为无向边 - as_undirected_edgedata * 合并两个网络 - merge_edgedata * 计算网络的特征 - calculate_graph_features * 计算节点的特征 - calculate_node_features * 根据度来过滤网络 - degree_filter * 计算模块度 - modularity * 社区发现 - community_detect * 社区结构的相似度度量 - partition_similarity * 绘制网络 - draw_graph 主要数据: edgedata: DataFrame; 网络中边的信息,包含[Source,Target,Weight]信息,也可以是没有权重的 cluster_result DataFrame; 社区划分的结果,形式为['Id','modularity_class'] gephi导出的结果为['id','modularity_class'],注意 备注: * 2017.10.10 - 增加计算模块度方法和社区发现方法 - 增加 networkx2pandas方法 * 2017.10.17 - 增加计算节点特征的方法 * 2017.12.25 - 增加两种社区划分结果的相似度度量 * 2018.1.9 - 增加了合并边数据的方法,merge_edgedata! 需要改进: * 将有向图转化为无向图的方法还需要改! ''' import pandas as pd import numpy as np import networkx as nx class NetworkUnity(): def __init__(self): pass @staticmethod def as_undirected_edgedata(edgedata): #将有向边转化为无向边 index_droped = [] edgedata_directed = edgedata.copy() for ind in edgedata.index: source = edgedata.ix[ind, 'Source'] target = edgedata.ix[ind, 'Target'] if ind not in index_droped: ''' 如果该边没有被丢弃过--例如之前在A-B这条边时,发现存在B-A, 那么B-A这条边的index会被记录,之后会被丢弃 ''' data_target_as_source = edgedata[edgedata['Source'] == target] if len(data_target_as_source) >= 1: if source in data_target_as_source['Target'].values: index_2 = data_target_as_source[data_target_as_source['Target'] == source].index[0] edgedata_directed.ix[ind, 'Weight'] += edgedata_directed.ix[index_2, 'Weight'] index_droped.append(index_2) #被丢弃的边数据 # data_droped = edgedata.ix[index_droped,:] edgedata_directed.drop(index_droped, axis=0, inplace=True) return edgedata_directed @staticmethod def networkx2pandas(graph): ''' :param graph: networkx.Graph/DiGraph :return: edgedata, DataFrame ''' def _getedges(g): for es in list(g.edges(data=True)): yield dict({'Source': es[0], 'Target': es[1]}, **es[2]) edgedata = pd.DataFrame(_getedges(graph)) return edgedata @staticmethod def nodes_from_edgedata(edgedata,return_df=True): ''' :param edgedata: 边的数据 :param return_df: 是否返回Series,默认True,否则为list :return: 节点数据 ''' source = set(edgedata['Source']) target = set(edgedata['Target']) nodes = list(source.union(target)) if return_df: nodes = pd.DataFrame(nodes,columns=['Id']) return nodes @staticmethod def graph_from_edgedata(edgedata, attr='Weight', directed=True,connected_component=False): ''' :param edgedata: 边的数据 :param attr: string 或 list; 边的属性数据,如果没有权重,设置attr=None, :param directed: 有向图还是无向图 :param connected_component: 返回最大联通子图,默认为True,对于有向图为weakly_connected 未开发 :return: networkx.Graph 或 DiGraph ''' if len(edgedata) < 1: if directed: return nx.DiGraph() else: return nx.Graph() if directed: graph = nx.from_pandas_dataframe(edgedata, 'Source', 'Target', edge_attr=attr, create_using=nx.DiGraph()) if connected_component: #返回最大联通子图 graph = max(nx.weakly_connected_component_subgraphs(graph), key=len) else: graph = nx.from_pandas_dataframe(edgedata, 'Source', 'Target', edge_attr=attr, create_using=nx.Graph()) if connected_component: graph = max(nx.connected_component_subgraphs(graph), key=len) print('Directed Graph :', graph.is_directed()) return graph @staticmethod def merge_edgedata(edgedata_1, edgedata_2, dirceted=True, accumulate_attr='all'): ''' 合并2个图(edges),思路如下 有向边: ------ 直接用Dataframe的append, 拼接在后面,然后根据重复的边,累加属性值 无向边: ------ 图2中的边分为2类: 原图(edgedata1)中存在的边: 又分为2类,正向存在的(图1种是3-4 和 图2中是3-4) 反向存在的(如图1中是3-5,图2中5-3) -- 找到图2中这类边,将反向的边,source和target互换 -- 然后append这些边 原图(edgedata1)中不存在的边: 直接append 累加属性: -------- 根据source 和 target 找到重复的数据,然后累加 :param edgedata_1: Dataframe, 边数据1 :param edgedata_2: Dataframe, 边数据2 :param dirceted: bool,是否为有向 :param accumulate_attr: 需要累加的属性,str 或 list :return: Dataframe,合并以后的数据 ''' def _merge_directed(edgedata1, edgedata2): edgedata_merge = pd.concat([edgedata1, edgedata2], axis=0, ignore_index=True) return edgedata_merge def _merge_undirected(edgedata1, edgedata2): def _add_edge(edgedata_): edgedata = edgedata_.copy() source_str = edgedata['Source'].astype(dtype=str) target_str = edgedata['Target'].astype(dtype=str) edgedata['edges_pd'] = source_str + '-' + target_str edgedata['edges_nd'] = target_str + '-' + source_str return edgedata edgedata1 = _add_edge(edgedata1) edgedata2 = _add_edge(edgedata2) # 原edge中已经存在的边 idx_pd = edgedata2['edges_pd'].isin(edgedata1['edges_pd']) idx_nd = edgedata2['edges_nd'].isin(edgedata1['edges_pd']) idx_exist = idx_nd | idx_pd idx_new = ~ idx_exist # 反向的边先转为正向 tmp = edgedata2.loc[idx_nd, 'Target'].copy() edgedata2.loc[idx_nd, 'Target'] = edgedata2.loc[idx_nd, 'Source'] edgedata2.loc[idx_nd, 'Source'] = tmp edge_exist = edgedata2[idx_exist] edge_new = edgedata2[idx_new] # 合并 edgedata_merge = edgedata1.append([edge_exist, edge_new], ignore_index=True) edgedata_merge = edgedata_merge.drop(['edges_pd', 'edges_nd'], axis=1) return edgedata_merge if accumulate_attr == 'all': accumulate_attr = edgedata_1.columns.copy() accumulate_attr = accumulate_attr.drop(['Source', 'Target']) elif isinstance(accumulate_attr, str): accumulate_attr = [accumulate_attr, ] # 合并边 if dirceted: edgedata_merge = _merge_directed(edgedata_1, edgedata_2) else: edgedata_merge = _merge_undirected(edgedata_1, edgedata_2) # 处理属性 if len(accumulate_attr) > 0: # ---------------找到重复边----------------- duplicated_last = edgedata_merge[edgedata_merge.duplicated(subset=['Source', 'Target'], keep='first')].copy() duplicated_first = edgedata_merge[edgedata_merge.duplicated(subset=['Source', 'Target'], keep='last')].copy() # ----------------累加属性------------------ index_first = list(duplicated_first.index) duplicated_last.index = index_first edgedata_merge.loc[index_first, accumulate_attr] += duplicated_last[accumulate_attr] # ---------------去掉重复边------------------------------ edgedata_merge = edgedata_merge.drop_duplicates(subset=['Source', 'Target']) return edgedata_merge @staticmethod def calculate_graph_features(graph,centrality=False,save_path=None): ''' :param graph: graph对象,应该是连通的! :param centrality: 是否计算中心度信息 :param save_path: 信息保存地址 :return: graph的各种网络特征,pd.Series 用来计算图的各种网络特征,计算时间跟图的大小相关 大部分特征都是不加权计算的。 用字典来记载可能更好 ''' def _average(node_dic): if len(node_dic) < 1: return 0 else: return np.average(list(node_dic.values())) features = {} NODE_NUM = graph.number_of_nodes() if NODE_NUM < 1: print('Graph is empty') return pd.Series() features['Node'] = NODE_NUM features['Edge'] = graph.number_of_edges() features['Density'] = nx.density(graph) features['AveDegree'] = _average(graph.degree()) # features['Diameter'] = nx.diameter(graph) # 有向图和无向图 if not graph.is_directed(): features['Directed'] = 0 features['AveClusterCoefficent'] = nx.average_clustering(graph) features['AveShortestPathLength'] = nx.average_shortest_path_length(graph) else: features['Directed'] = 1 features['AveInDegree'] = _average(graph.in_degree()) features['AveOutDegree'] = _average(graph.out_degree()) # 中心性指标 if centrality: # 度中心性 node_degree_centrality = nx.degree_centrality(graph) ave_degree_centrality = _average(node_degree_centrality) # 特征向量中心度 node_eigenvector_centrality = nx.eigenvector_centrality_numpy(graph) ave_eigenvector_centrality = _average(node_eigenvector_centrality) #介数中心度 node_betweenness = nx.betweenness_centrality(graph) ave_betweenness_centrality = _average(node_betweenness) #接近中心度 node_closeness = nx.closeness_centrality(graph) ave_closeness_centrality = _average(node_closeness) features['AveDegreeCentrality'] = ave_degree_centrality features['AveEigenvectorCentrality'] = ave_eigenvector_centrality features['AveBetweennessCentrality'] = ave_betweenness_centrality features['AveClosenessCentrality'] = ave_closeness_centrality graph_info = pd.Series(features) if save_path is not None: graph_info.to_csv(save_path,index=True,header=None) print('File Saved : ', save_path) return graph_info @staticmethod def calculate_node_features(graph,weight=None,centrality=False, save_path=None): ''' :param graph: networkx.Graph \ Digraph :param weight: str, 某些指标是否使用边的权重,weight = 'Weight' :param centrality: 是否计算中心性指标 :param save_path: 保存地址 :return: DataFrame, node_features ''' if graph.number_of_nodes() < 1: return pd.DataFrame() features = {} features['Degree'] = nx.degree(graph) if graph.is_directed(): features['InDegree'] = graph.in_degree() features['OutDegree'] = graph.out_degree() if centrality: features['DegreeCentrality'] = nx.degree_centrality(graph) features['BetweennessCentrality'] = nx.betweenness_centrality(graph) features['EigenvectorCentrality'] = nx.eigenvector_centrality_numpy(graph) features['ClosenessCentrality'] = nx.closeness_centrality(graph) if weight is not None: features['WeightedDegree'] = nx.degree(graph,weight=weight) if graph.is_directed(): features['WeightedInDegree'] = graph.in_degree(weight=weight) features['WeightedOutDegree'] = graph.out_degree(weight=weight) if centrality: features['WeightedBetweennessCentrality'] = nx.betweenness_centrality(graph,weight=weight) features['WeightedEigenvectorCentrality'] = nx.eigenvector_centrality_numpy(graph,weight=weight) node_features = pd.DataFrame(features) node_features['Id'] = node_features.index if save_path is not None: node_features.to_csv(save_path,header=None) print('File Saved : ', save_path) return node_features @staticmethod def degree_filter(graph,lower=None,upper=None): ''' :param graph: Networkx.Graph/DiGraph :param lower: int/float,the lower limitation of degree :param upper: int/float,the upper limitation of degree :return: graph after filter ''' node_degree = graph.degree() nodes_all = list(graph.nodes()) print('Node num: ',graph.number_of_nodes()) data = pd.DataFrame(list(node_degree.items()),columns=['Id','Degree']) if lower is not None: data = data[data['Degree'] >= lower] if upper is not None: data = data[data['Degree'] <= upper] nodes_saved = list(data['Id']) nodes_drop = set(nodes_all).difference(nodes_saved) graph.remove_nodes_from(nodes_drop) print('Node num: ',graph.number_of_nodes()) return graph @staticmethod def draw_graph(graph,nodes=None): ''' 采用pygraphistry 来绘制网络图,节点颜色目前还不能超过12种 :param graph: networkx.Graph/DiGraph :param nodes: DataFrame,如果需要按社区颜色绘制,请传入带有社区信息的节点表, ['Id','modulraity_class'] :return: None ''' import graphistry graphistry.register(key='contact pygraphistry for api key') ploter = graphistry.bind(source='Source', destination='Target').graph(graph) if nodes is not None: ploter = ploter.bind(node='Id', point_color='modularity_class').nodes(nodes) ploter.plot() return None @staticmethod def community_detect(graph=None,edgedata=None,directed=True, use_method=1, use_weight=None): ''' :param edgedata: DataFrame, 边的数据 :param graph: Networkx.Graph/DiGraph,与edgedata给定一个就行 :param directed: Bool, 是否有向 :param use_method: Int, 使用方法 :param weight_name: String, 社区发现算法是否使用边权重,如果使用,例如weight_name='Weight' :return: 带有社区信息的节点表格 ''' #创建igraph.Graph类 if graph is None and edgedata is not None: graph = NetworkUnity.get_graph_from_edgedata(edgedata, attr=use_weight, directed=directed, connected_component=True) gr = graphistry.bind(source='Source', destination='Target', node='Id', edge_weight='Weight').graph(graph) edgedata = NetworkUnity.networkx2pandas(graph) ig = gr.pandas2igraph(edgedata, directed=directed) #-------------------------------------------------------- #如果使用边的数据edgedata # gr = graphistry.bind(source='Source',destination='Target',edge_weight='Weight').edges(edgedata) # nodes = NetworkUnity.get_nodes_from_edgedata(edgedata) # gr = gr.bind(node='Id').nodes(nodes) # ig = gr.pandas2igraph(edgedata,directed=directed) # -------------------------------------------------------- ''' 关于聚类的方法, 参考http://pythonhosted.org/python-igraph/igraph.Graph-class.html 希望以后可以对每一个算法添加一些简单的介绍 ''' method_dict = { 0:'''ig.community_fastgreedy(weights='%s')'''%str(use_weight), 1:'''ig.community_infomap(edge_weights='%s',trials=10)'''%str(use_weight), 2:'''ig.community_leading_eigenvector_naive(clusters=10)''', 3:'''ig.community_leading_eigenvector(clusters=10)''', 4:'''ig.community_label_propagation(weights='%s')'''%str(use_weight), 5:'''ig.community_multilevel(weights='%s')'''%str(use_weight), 6:'''ig.community_optimal_modularity()''', 7:'''ig.community_edge_betweenness()''', 8:'''ig.community_spinglass()''', } detect_method = method_dict.get(use_method) if use_weight is None: #如果为None,需要把公式里面的冒号去掉,注意如果有多个None,这个方法需要重新写 detect_method= detect_method.replace('\'','') # -------------开始实施社区发现算法----------- print('社区发现方法: ',detect_method) res_community = eval(detect_method) #将社区信息保存到节点信息中 ig.vs['modularity_class'] = res_community.membership #将节点信息转化为Dataframe表 edgedata_,nodedata = gr.igraph2pandas(ig) modularity = res_community.modularity print(res_community.summary()) print('community size:\n', res_community.sizes()) print('modularity:\n', modularity) return nodedata @staticmethod def modularity(cluster_result,edgedata=None,graph=None, directed=True, edge_weight='Weight'): ''' :param cluster_result: 聚类结果,参考gephi输出的表,[Id,modulraity_class] :param edgedata: 边数据,与graph给定其中一个 :param graph: networkx中的Graph/DiGraph :param directed: 是否为有向图 :param edge_weight: None/str, 计算模块度是否使用边的权重,如果使用,给定边权重的name 例如edge_weight='Weight' 如果不使用,请给定为None :return: Q值 ps: 1.edgedata 和 graph 至少要给定一个 2.与gephi中计算的模块度结果已经对比过了,结果一致 ''' import graphistry if edgedata is None and graph is not None: edgedata = NetworkUnity.networkx2pandas(graph) gr = graphistry.bind(source='Source', destination='Target', node='Id',edge_weight=edge_weight) ig = gr.pandas2igraph(edgedata,directed=directed) nodes = pd.DataFrame(list(ig.vs['Id']), columns=['Id']) community_data = pd.merge(nodes, cluster_result, left_on='Id', right_on='Id', how='left') if edge_weight is None: Q = ig.modularity(list(community_data['modularity_class']),weights=None) else: Q = ig.modularity(list(community_data['modularity_class']),weights=list(ig.es[edge_weight])) return Q @staticmethod def get_confusion_matrix(result_1, result_2, return_df=True): ''' 计算两个社区划分的混淆矩阵 :param result_1: 划分结果1,包含[Id,modularity_class]; DataFrame; :param result_2: 划分结果2,形式同result_1; DataFrame :param return_df: 是否返回DataFrame形式 :return: confusition matrix based on two classify result ''' result_1.columns = ['Id', 'modularity_class'] result_2.columns = ['Id', 'modularity_class'] clusters_1 = pd.unique(result_1['modularity_class']) clusters_2 = pd.unique(result_2['modularity_class']) NUM_1 = len(clusters_1) NUM_2 = len(clusters_2) clusters_1.sort() clusters_2.sort() def _get_matrix(): for cluster_1 in clusters_1: for cluster_2 in clusters_2: nodes_1 = result_1.loc[result_1['modularity_class'] == cluster_1, 'Id'] nodes_2 = result_2.loc[result_2['modularity_class'] == cluster_2, 'Id'] union_nodes = np.intersect1d(nodes_1, nodes_2) yield len(union_nodes) matrix = list(_get_matrix()) matrix = np.reshape(np.asarray(matrix), newshape=(NUM_1, NUM_2)) if return_df: matrix = pd.DataFrame(matrix, index=clusters_1, columns=clusters_2) return matrix @staticmethod def normalized_mutual_info_similarity(confusion_matrix): ''' # 计算社区划分的相似度,以及规范化的互信息 # Ref. Comparing community structure identification @<NAME> 结果验证: 跟sklearn.metric.normalized_mutual_info_score 的结果一致!! 那你写这玩意有啥用!! :param confusion_matrix: 混淆矩阵 :return: 社区划分的相似度 ''' confusion_matrix = np.asarray(confusion_matrix) NUM_NODES = np.sum(confusion_matrix, axis=None) nums_a = np.sum(confusion_matrix, axis=1) # 按列相加 nums_b = np.sum(confusion_matrix, axis=0) # 按行相加 print(np.all(nums_a), np.all(nums_b), NUM_NODES) def _cal_entropy(info): print(np.all(info / NUM_NODES)) return np.sum(np.multiply(info, np.log(info / NUM_NODES))) # 分母计算 entropy_a = _cal_entropy(nums_a) entropy_b = _cal_entropy(nums_b) # 分子计算 both_info = np.dot(np.asmatrix(nums_a).T, np.asmatrix(nums_b)) joint_mat = np.multiply(confusion_matrix, np.log(confusion_matrix / both_info * NUM_NODES + 1e-10)) mutual_info =
np.sum(joint_mat, axis=None)
numpy.sum
import sys import os import re import numpy as np evtth = .1 # 100 eV for WFI Geant4 simulations splitth = evtth # same as evtth for WFI Geant4 simulations xydep_min = -513 xydep_max = 513 # hash of codes indexed by particle type indexed ptypes = { 'proton': 0, 'gamma': 1, 'electron': 2, 'neutron': 3, 'pi+': 4, 'e+': 5, 'pi-': 6, 'nu_mu': 7, 'anti_nu_mu': 8, 'nu_e': 9, 'kaon+': 10, 'mu+': 11, 'deuteron': 12, 'kaon0L': 13, 'lambda': 14, 'kaon-': 15, 'mu-': 16, 'kaon0S': 17, 'alpha': 18, 'anti_proton': 19, 'triton': 20, 'anti_neutron': 21, 'sigma-': 22, 'sigma+': 23, 'He3': 24, 'anti_lambda': 25, 'anti_nu_e': 26, 'anti_sigma-': 27, 'xi0': 28, 'anti_sigma+': 29, 'xi-': 30, 'anti_xi0': 31, 'C12': 32, 'anti_xi-': 33, 'Li6': 34, 'Al27': 35, 'O16': 36, 'Ne19': 37, 'Mg24': 38, 'Li7': 39, 'He6': 40, 'Be8': 41, 'Be10': 42 } def match(regex: str, string: str): return re.compile(regex).search(string) def flow_test1(rf_name = 'flow_test1.txt'): with open(rf_name, 'r') as FH: f = FH.readlines() g = [] with open(infile, 'r') as dec: for line in dec: if match('^\s*#', line): #skip comments continue if match('^\s*$', line): #skip blank lines: continue if not match(',', line): continue g.append(line) fields = line.rstrip().split(',') if match('[a-zA-Z]', fields[0]): g.append("if\n") else: g.append("else\n") if len(f) != len(g): raise ValueError(f"The outputs had different number of lines {len(f)} vs {len(g)}") for i in range(len(g)): if f[i] != g[i]: raise ValueError(f"Different values found at index {i}: {f[i]}, {g[i]}") print("All good python") def flow_test2(rf_name = 'flow_test2.txt'): with open(rf_name, 'r') as FH: f = FH.readlines() g = [] with open(infile, 'r') as dec: for line in dec: if match('^\s*#', line): #skip comments continue if match('^\s*$', line): #skip blank lines: continue if not match(',', line): continue g.append(line) fields = line.rstrip().split(',') if match('[a-zA-Z]', fields[0]): g.append("if\n") else: if float(fields[2]) <= splitth: continue tmp_x, tmp_y = int(fields[0]), int(fields[1]) if tmp_x<xydep_min or tmp_y<xydep_min or tmp_x>xydep_max or tmp_y>xydep_max: continue # skip it if it's outside the 512x512 region of a quad g.append("else\n") if len(f) != len(g): raise TypeError for i in range(len(g)): if f[i] != g[i]: raise ValueError(f"Different values found at index {i}: {f[i]}, {g[i]}") print("All good python") def flow_test3(rf_name = 'flow_test3.txt'): state = 0 f = [] perl_ptype = {} perl_cproc = {} with open(rf_name, 'r') as FH: for line in FH: #print(line, end = '') if line == "next\n": state += 1 continue if state == 0: f.append(line) if state == 1: a = line.split() a[0] = a[0][1:] a[-1] = a[-1][:-1] perl_eid = np.array(a, dtype = int) if state == 2: key, value = line.split(',') perl_ptype[int(key)] = value.rstrip() if state == 3: key, value = line.split(',') perl_cproc[int(key)] = value.rstrip() if state == 4: deps = line.split(',')[:-1] perl_xdep = np.array(deps, dtype = int) if state == 5: deps = line.split(',')[:-1] perl_ydep = np.array(deps, dtype = int) if state == 6: deps = line.split(',')[:-1] perl_endep = np.array(deps, dtype = float) if state == 7: deps = line.split(',')[:-1] perl_rundep = np.array(deps, dtype = int) if state == 8: deps = line.split(',')[:-1] perl_detectordep = np.array(deps, dtype = int) if state == 9: deps = line.split(',')[:-1] perl_eiddep = np.array(deps, dtype = int) if state == 10: deps = line.split(',')[:-1] perl_framedep = np.array(deps, dtype = int) if state == 11: deps = line.split(',')[:-1] perl_piddep = np.array(deps, dtype = int) if state == 12: deps = line.split(',')[:-1] perl_ptypedep = np.array(deps, dtype = int) if state == 13: ids = line.split(',')[:-1] perl_blobid = np.array(ids, dtype = int) eid = np.zeros(0, dtype=int) # primary ID xdep = np.zeros(0, dtype=int) ydep = np.zeros(0, dtype=int) endep = np.zeros(0, dtype=float) rundep = np.zeros(0, dtype=int) detectordep = np.zeros(0, dtype=int) eiddep = np.zeros(0, dtype=int) framedep = np.zeros(0, dtype=int) piddep = np.zeros(0, dtype=int) ptypedep = np.zeros(0, dtype=int) blobid =
np.zeros(0, dtype=int)
numpy.zeros
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import gr3 import faulthandler from PyQt5 import QtCore, QtGui, QtWidgets import sys import os import gr import signal from . import spinVis_camera from . import spinVis_coor from PyQt5.QtWidgets import (QHBoxLayout, QCheckBox, QRadioButton, QButtonGroup, QLineEdit, QVBoxLayout, QPushButton, QLabel, QTableWidgetItem) # Import der versch. QtWidgets from PyQt5.QtCore import Qt import math import numpy as np class MainWindow(QtWidgets.QWidget): #Class MainWindow is the overall window, consisting of a GUI and a canvas part def __init__(self,ladestyle , *args, **kwargs): super().__init__(**kwargs) #Takes data from parent self.inputstyle = ladestyle #Shows if data comes from pipe or file selection self.initUI() #Initialize User Interfaces pass def initUI(self): self.setWindowTitle('SpinVis2 by PGI/JCNS-TA') self.draw_window = GLWidget() #Initialisation of the canvas window self.gui_window = GUIWindow( self.draw_window, self.inputstyle) #Initialisation of the GUI with the GLWindow as an parameter self.draw_window.setMinimumSize(700, 700) #Size 700x700 is the biggest window possible for the laptop display of a MacBook Pro self.gui_window.setSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) self.gui_window.setFocusPolicy(Qt.ClickFocus) self.complete_window_hbox = QHBoxLayout() # Horizontales Layout umd beides nebeneinander zulegen self.complete_window_hbox.addWidget(self.draw_window) self.complete_window_hbox.addWidget(self.gui_window) self.complete_window_hbox.setContentsMargins(0, 0, 0, 0) self.complete_window_hbox.setSpacing(0) # Abstand 0 setzen um beides direkt nebeneinander zu haben self.setLayout(self.complete_window_hbox) def keyPressEvent(self, QKeyEvent): #self.gui_window.p_win.perspective_check.setFocusPolicy(Qt.NoFocus) #self.gui_window.p_win.orthographic_check.setFocusPolicy(Qt.NoFocus) if QKeyEvent.key() == QtCore.Qt.Key_Right: self.draw_window.rotate_right() if QKeyEvent.key() == QtCore.Qt.Key_Left: self.draw_window.rotate_left() if QKeyEvent.key() == QtCore.Qt.Key_Up: self.draw_window.rotate_up() if QKeyEvent.key() == QtCore.Qt.Key_Down: self.draw_window.rotate_down() if QKeyEvent.key() == QtCore.Qt.Key_A: self.draw_window.move_left() if QKeyEvent.key() == QtCore.Qt.Key_D: self.draw_window.move_right() if QKeyEvent.key() == QtCore.Qt.Key_W: self.draw_window.move_up() if QKeyEvent.key() == QtCore.Qt.Key_S: self.draw_window.move_down() if QKeyEvent.key() == QtCore.Qt.Key_Z: spinVis_camera.zoom(0.1, self.draw_window.width(), self.draw_window.height()) if QKeyEvent.key() == QtCore.Qt.Key_X: spinVis_camera.zoom(- 0.1, self.draw_window.width(), self.draw_window.height()) self.draw_window.update() class GUIWindow( QtWidgets.QScrollArea): # GUI Window setzt sich aus einzelnen Windows die vertikal unteieinander gelegt wurden zusammen def __init__(self,glwindow, ladestyle, *args, **kwargs): super().__init__(*args, **kwargs) self._camera_angle = 0.0 self._glwindow = glwindow # Uebergabe des GLwindows als lokale private variable self.ladestyle = ladestyle self.initUI() pass def initUI(self): self.parent_widget = QtWidgets.QWidget() self.pgroup = QtWidgets.QGroupBox() self.p_win = ProjectionWindow(self._glwindow) self.slide_win = AngleWindow(self._glwindow) #Slider Boxlayout fuer Kamerasteuerung per Slider self.t_win = TranslationWindow(self._glwindow) self.bond_win = BondWindow(self._glwindow) self.screen_win = ScreenWindow(self._glwindow) # Screen Boxlayout fuer Screenshot steuerung self.cs_win = SpinColorWindow(self._glwindow) self.l_win = DataLoadWindow(self._glwindow, self.ladestyle, self.cs_win) # Lade Boxlayout um neuen Datensatz zu laden self.c_win = ColorWindow(self._glwindow, self.cs_win) # Color Boxlayout um Farbe für Hintergrund und Spins zu setzen self.v_win = VideoWindow(self._glwindow) self.vbox = QVBoxLayout() self.vbox.addWidget(self.p_win) self.vbox.addWidget(self.slide_win) self.vbox.addWidget(self.t_win) self.vbox.addWidget(self.bond_win) self.vbox.addWidget(self.screen_win) self.vbox.addWidget(self.l_win) self.vbox.addWidget(self.cs_win) self.vbox.addWidget(self.c_win) self.vbox.addWidget(self.v_win) self.vbox.addStretch(1) self.parent_widget.setLayout(self.vbox) self.setWidget(self.parent_widget) self.setWidgetResizable(True) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) class ProjectionWindow(QtWidgets.QWidget): # def __init__(self, glwindow, *args, **kwargs): super().__init__(*args, **kwargs) self._camera_angle = 0.0 self._glwindow = glwindow # Uebergabe des GLwindows als lokale private variable self.initUI() pass def initUI(self): self.projectiongroup = QtWidgets.QGroupBox("Projection Window") self.projectiongroup.setTitle("Projection Window") self.projectiongroup.setToolTip("The projectiontype defines how a 3D object is pictured on a 2D screen. \n" "The perspektive projection is simulating the effects of the real world. Objects \n" "farther away appear smaller. The orthographic projection depicts every object \n" "with the same size. It may reveal patterns in the data, that would else remain hidden") self.groupbox = QtWidgets.QVBoxLayout() self.groupbox.addWidget(self.projectiongroup) self.projection_box = QHBoxLayout() # Eine grosse HBox die ein Label und eine weite HBox beinhaltet. In der sind 2 VBoxLayouts mit jeweils einem HLabel und einem RadioButton # self.projection_box.addStretch(1) self.projection_label = QtWidgets.QLabel() self.projection_label.setText("Choose a perspective type:") # Pop-Up das Hilftext anzeigt self.checkboxbox = QHBoxLayout() # Checkboxbox beinhaltet 2 HBoxen, die je ein Label und ein Radiobutton haben self.perspective_box = QHBoxLayout() self.perspective_check = QRadioButton() self.perspective_check.setFocusPolicy(Qt.NoFocus) self.perspective_label = QLabel() self.perspective_label.setText("Perspektive") # self.perspective_check.toggle() self.perspective_box.addWidget(self.perspective_label) self.perspective_box.addWidget(self.perspective_check) self.checkboxmanagment = QButtonGroup() # Mit der Buttongroup werden die Radiobuttons auf exklusiv gestellt self.orthographic_box = QHBoxLayout() self.orthographic_check = QRadioButton() self.orthographic_check.setChecked(True) self.orthographic_check.setFocusPolicy(Qt.NoFocus) self.orthographic_label = QLabel() self.orthographic_label.setText("Orthographic") self.perspective_box.addWidget(self.orthographic_label) self.perspective_box.addWidget(self.orthographic_check) self.checkboxbox.addLayout(self.perspective_box) self.checkboxbox.addLayout(self.orthographic_box) self.orthographic_check.clicked.connect(self.radio_clicked) self.perspective_check.clicked.connect(self.radio_clicked) self.projection_box.addWidget(self.projection_label) self.projection_box.addLayout(self.checkboxbox) self.projectiongroup.setLayout(self.projection_box) self.groupbox.setContentsMargins(0, 0, 0, 0) self.setLayout(self.groupbox) pass def radio_clicked(self): if self.orthographic_check.isChecked(): spinVis_camera.is_orthograpghic = True spinVis_camera.set_projection_type_orthographic() else: spinVis_camera.is_orthograpghic = False spinVis_camera.set_projection_type_perspective() self._glwindow.update() def is_orthographic_projection(self): if self.orthographic_check.isChecked(): return True else: return False class SpinColorWindow(QtWidgets.QWidget): def __init__(self, glwindow, *args, **kwargs): super().__init__(*args, **kwargs) self._camera_angle = 0.0 self._glwindow = glwindow # Uebernahme des GLWindows zur Slidersteuerung self.initUI() pass def initUI(self): self.spincolorgroup = QtWidgets.QGroupBox("Spin Color Window") self.spincolorgroup.setTitle("Spin Color Window") self.spincolorgroup.setToolTip("Click on the cell under the symbol of the spins you want to change color.\n" "If you use the feature further down to change the color of all spins or \n" "change the data set that is in use, the selection will be reseted. \n" "If you want to load a color scheme, it must have the same list of symbols \n" "like the one you have loaded right now. A saved color scheme can be found \n" "under spinvis_color_save.txt") self.groupbox = QtWidgets.QVBoxLayout() self.groupbox.addWidget(self.spincolorgroup) self.table_box = QtWidgets.QHBoxLayout() self.button_box = QtWidgets.QVBoxLayout() self.load_scheme_button = QtWidgets.QPushButton("Load scheme") self.load_scheme_button.setFixedSize(130,30) self.load_scheme_button.clicked.connect(self.load_color) self.save_scheme_button = QtWidgets.QPushButton("Save scheme") self.save_scheme_button.setFixedSize(130,30) self.save_scheme_button.clicked.connect(self.save_color) self.button_box.addWidget(self.save_scheme_button) self.button_box.addWidget(self.load_scheme_button) self.color_table = QtWidgets.QTableWidget(0, 0) self.color_table.setFixedHeight(70) self.color_table.setFocusPolicy(Qt.ClickFocus) self.table_box.addWidget(self.color_table) self.table_box.addLayout(self.button_box) self.color_table.clicked.connect(self.on_click) self.spincolorgroup.setLayout(self.table_box) self.groupbox.setContentsMargins(0, 0, 0, 0) self.setLayout(self.groupbox) def load_color(self): options = QtWidgets.QFileDialog.Options() # File Dialog zum auswählen der Daten-Datei options |= QtWidgets.QFileDialog.DontUseNativeDialog input, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Choose your data", "", "All Files (*);;", options=options) list = [] if (not input): pass # Falls nichts ausgewählt wird, wird kein neuer Datensatz gewählt else: if not (input.endswith(".txt")): print("Please make sure that your file is a '.txt'") return try: # Es wird probiert den Pfad zu öffnen um eine Exception, bei nicht vorhandener Datei abzufangen (mit Path-Dialog eeigentlich unnötig) with open(input, 'r') as f: pass except FileNotFoundError: print("This path does not exist, please try again") return with open(input, 'r') as infile: # Fuer den Bereich die Datei oeffnen, fuer jede Zeile das ganze in 3 Tupel schreiben for line in infile.readlines(): line = line.strip() list.append(line) if len(list) == self.color_table.columnCount(): i= 0 for line in list: helf = line.split() # Leerzeichen als Trennzeichen if helf[0] == self.color_table.horizontalHeaderItem(i).text().title(): rgb_list = [int(helf[1]), int(helf[2]), int(helf[3])] rgb = QtGui.QColor.fromRgb(rgb_list[0], rgb_list[1], rgb_list[2]) self.color_table.item(0, i).setBackground(rgb) spinVis_camera.set_symbol_spin_color([helf[1], helf[2], helf[3]], self.color_table.horizontalHeaderItem( i).text().title()) i = i+1 def save_color(self): f = open("spinvis_color_save.txt", "w") for i in range(self.color_table.columnCount()): symbol = self.color_table.horizontalHeaderItem(i).text().title() rgbtuple = self.color_table.item(0, i).background().color().getRgb() print(symbol + "\t" + str(rgbtuple[0]) + "\t" + str(rgbtuple[1]) + "\t" + str(rgbtuple[2]), file=f) f.close() def on_click(self): spin_rgb = [c * 255 for c in spinVis_camera.spin_rgb] # Umrechnung der momentanen Farbe als Stndardwert, Multiplikation der Werte von 0-1 auf 0-255 for currentQTableWidgetItem in self.color_table.selectedItems(): currentQTableWidgetItem.setSelected(False) selectedColor = QtWidgets.QColorDialog.getColor(QtGui.QColor.fromRgb(*spin_rgb)) if selectedColor.isValid(): self.color_table.item(currentQTableWidgetItem.row(), currentQTableWidgetItem.column()).setBackground(selectedColor) spinVis_camera.set_symbol_spin_color(selectedColor.getRgb(), self.color_table.horizontalHeaderItem(currentQTableWidgetItem.column()).text().title()) self._glwindow.update() def fillTable(self, list): symbol_list = np.array(list) self.color_table.setRowCount(1) f = open("listtest.txt", 'w') for e in symbol_list: print(e, file=f) self.color_table.setColumnCount(len(symbol_list)) i = 0 symbol_list_int = symbol_list.tolist() for e in symbol_list_int: self.color_table.setHorizontalHeaderItem(i, QTableWidgetItem(str(e))) self.color_table.setItem(0, i, QTableWidgetItem("")) c = spinVis_camera.get_symbol_color(e) self.color_table.item(0, i).setBackground(QtGui.QColor.fromRgb(int(c[0]), int(c[1]), int(c[2]))) i = i+1 def color_all_spins(self, rgb): for e in range(self.color_table.columnCount().__int__()): self.color_table.item(0, e).setBackground(QtGui.QColor.fromRgb(rgb[0], rgb[1], rgb[2])) class DataLoadWindow(QtWidgets.QWidget): def __init__(self, glwindow, ladestyle, spin_colour_win,*args, **kwargs): super().__init__(*args, **kwargs) self._camera_angle = 0.0 self._glwindow = glwindow # Uebernahme des GLWindows zur Slidersteuerung self.lade_style = ladestyle self.spin_colour_win = spin_colour_win self.initUI() pass def initUI(self): self.loadgroup = QtWidgets.QGroupBox("Data Load Window") self.loadgroup.setTitle("Data Load Window") self.loadgroup.setToolTip("Please choose a '.txt' file to load that has the following structure: \n" "the position of the center of the spin, the direction of the spin, a symbol. \n" "For example: -1.819 6.300 -25.500 0.022 -0.075 0.355 54. \n" "Its important that the individual numbers are seperated by tabs. \n" "But you can also save a data file. If you do so you can find it under \n" "spinvis_save_data.txt.") self.groupbox = QtWidgets.QVBoxLayout() self.groupbox.addWidget(self.loadgroup) self.load_label = QtWidgets.QLabel() self.load_label.setText("Load new set of spins from a txt file:") self.load_button = QPushButton('Load set', self) self.load_button.setFixedSize(130, 30) self.load_button.clicked.connect(self.load_file) self.save_button = QPushButton('Save set', self) self.save_button.setFixedSize(130, 30) self.save_button.clicked.connect(self.save_data) self.hbox = QHBoxLayout() # HBox mit einem Label und einem Knopf zum Laden #self.hbox.addStretch(1) self.hbox.addWidget(self.load_label) self.hbox.addWidget(self.save_button) self.hbox.addWidget(self.load_button) self.loadgroup.setLayout(self.hbox) self.groupbox.setContentsMargins(0, 0, 0, 0) self.setLayout(self.groupbox) def save_data(self): spinVis_camera.save_file() def load_file(self): options = QtWidgets.QFileDialog.Options() # File Dialog zum auswählen der Daten-Datei options |= QtWidgets.QFileDialog.DontUseNativeDialog input, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Choose your data", "", "All Files (*);;", options=options) if (not input): pass # Falls nichts ausgewählt wird, wird kein neuer Datensatz gewählt else: self._glwindow.data_path = input # So wird der Eingabestring verwendet und der neue Datensatz gewählt #try: self._glwindow.setDataSet() ''' except TypeError: typ_err_box = QtWidgets.QMessageBox() typ_err_box.setIcon(2) # Gives warning Icon typ_err_box.setText("Error ocurred while trying to load a data set!") typ_err_box.setInformativeText( "Something went wrong trying to open the data file. Please make sure that the the selected file is a '.txt'-file with the schematic" " described in the tooltip.") typ_err_box.exec_()''' self.spin_colour_win.fillTable(spinVis_camera.fill_table()) class ColorWindow(QtWidgets.QWidget): def __init__(self, glwindow,spin_color_window, *args, **kwargs): super().__init__(*args, **kwargs) self._camera_angle = 0.0 self._glwindow = glwindow # Uebernahme des GLWindows zur Slidersteuerung self._spin_color_win = spin_color_window self.initUI() pass def initUI(self): self.colorgroup = QtWidgets.QGroupBox("Color Window") self.colorgroup.setTitle("Color Window") self.colorgroup.setToolTip("Click on either button to open a window where you can choose a color \n" "for either the background or the spins. This color will be saved for \n" "how long the app is running. However it will be reset if you restart \n" "the app.") self.groupbox = QtWidgets.QVBoxLayout() self.groupbox.addWidget(self.colorgroup) self.color_hbox = QHBoxLayout() # Hbox mt 2 Knöpfen und einem Label self.color_label = QLabel() self.color_label.setText("Choose a color:") self.sphere_switch = QtWidgets.QPushButton() self.sphere_switch.setText("Switch spheres") self.sphere_switch.clicked.connect(self.switch_sphere) self.bg_color_button = QPushButton('Background', self) self.bg_color_button.setFixedSize(100, 30) self.bg_color_button.clicked.connect(self.get_bg_color) self.spin_color_button = QPushButton('Spins', self) self.spin_color_button.setFixedSize(100, 30) self.spin_color_button.clicked.connect(self.get_spin_color) self.color_dialog = QtWidgets.QColorDialog() # Dialog Picker zum Farben auswählen self.color_hbox.addWidget(self.color_label) self.color_hbox.addWidget(self.sphere_switch) self.color_hbox.addWidget(self.bg_color_button) self.color_hbox.addWidget(self.spin_color_button) self.colorgroup.setLayout(self.color_hbox) self.groupbox.setContentsMargins(0, 0, 0, 0) self.setLayout(self.groupbox) def switch_sphere(self): if self._glwindow._issphere: self._glwindow._issphere = False else: self._glwindow._issphere = True self._glwindow.spinDraw() self._glwindow.update() def get_bg_color(self): bg_rgb = [c * 255 for c in spinVis_camera.bg_rgb] # Umrechnung der momentanen Farbe als Stndardwert, Multiplikation der Werte von 0-1 auf 0-255 selectedColor = QtWidgets.QColorDialog.getColor(QtGui.QColor.fromRgb( *bg_rgb)) # Speichert die Auswahl des Farbendialogs und setzt Standardwert auf vorher umgewandelte Farben if selectedColor.isValid(): self._glwindow.set_bg_color(selectedColor.getRgb()) def get_spin_color(self): spin_rgb = [c * 255 for c in spinVis_camera.spin_rgb] # Umrechnung der momentanen Farbe als Stndardwert, Multiplikation der Werte von 0-1 auf 0-255 selectedColor = QtWidgets.QColorDialog.getColor(QtGui.QColor.fromRgb( *spin_rgb)) # Speichert die Auswahl des Farbendialogs und setzt Standardwert auf vorher umgewandelte Farben if selectedColor.isValid(): self._spin_color_win.color_all_spins(selectedColor.getRgb()) spin_rgb[0] = selectedColor.getRgb()[0] / 255 spin_rgb[1] = selectedColor.getRgb()[1] / 255 spin_rgb[2] = selectedColor.getRgb()[2] / 255 self._glwindow.set_spin_color(selectedColor.getRgb()) class VideoWindow(QtWidgets.QWidget): def __init__(self, glwindow, *args, **kwargs): super().__init__(*args, **kwargs) self._camera_angle = 0.0 self._glwindow = glwindow # Uebernahme des GLWindows zur Slidersteuerung self.initUI() pass def initUI(self): self.vidgroup = QtWidgets.QGroupBox("Video Window") self.vidgroup.setTitle("Video Window") self.vidgroup.setToolTip("Create a video by clicking once on the 'Make a video' button. Pressing a second time\n" "will finish the video. The default parameters are 1920*1920 pixels and 60 fps.\n" "But if you enter valid value, they will be used instead. The default name is spinvis_output.mp4") self.groupbox = QtWidgets.QVBoxLayout() self.vidbox = QHBoxLayout() self.vidlabel = QLabel() self.vidlabel.setText("Create a video: ") self.groupbox.addWidget(self.vidgroup) self.namebox = QVBoxLayout() self.namelabel = QLabel() self.namelabel.setText("Name the video:") self.vidname = QtWidgets.QTextEdit() self.vidname.setFixedSize(100,25) self.namebox.addWidget(self.vidlabel) self.namebox.addWidget(self.vidname) self.fpsbox = QVBoxLayout() self.fpslabel = QLabel() self.fpslabel.setText("FPS:") self.validator = QtGui.QIntValidator(1, 120, self) self.fpscounter = QtWidgets.QLineEdit() self.fpscounter.setValidator(self.validator) self.fpscounter.setFixedSize(25,25) self.fpsbox.addWidget(self.fpslabel) self.fpsbox.addWidget(self.fpscounter) self.resolution_validator = QtGui.QIntValidator(1, 4000, self) self.widthbox = QVBoxLayout() self.widthlabel = QLabel() self.widthlabel.setText("Width: ") self.vidwidth = QtWidgets.QLineEdit() self.vidwidth.setValidator(self.resolution_validator) self.vidwidth.setFixedSize(50, 25) self.widthbox.addWidget(self.widthlabel) self.widthbox.addWidget(self.vidwidth) self.heighthbox = QVBoxLayout() self.heightlabel = QLabel() self.heightlabel.setText("Height: ") self.vidheight = QtWidgets.QLineEdit() self.vidheight.setValidator(self.resolution_validator) self.vidheight.setFixedSize(50, 25) self.heighthbox.addWidget(self.heightlabel) self.heighthbox.addWidget(self.vidheight) self.vidbutton = QPushButton("Make a video") self.vidbutton.clicked.connect(self.doVideo) self.vidbox.addLayout(self.namebox) self.vidbox.addLayout(self.fpsbox) self.vidbox.addLayout(self.widthbox) self.vidbox.addLayout(self.heighthbox) self.vidbox.addWidget(self.vidbutton) self.vidgroup.setLayout(self.vidbox) self.groupbox.setContentsMargins(0, 0, 0, 0) self.setLayout(self.groupbox) def doVideo(self): self._glwindow.make_video(self.vidname.toPlainText().title(), self.fpscounter.text().title(), self.vidwidth.text().title(), self.vidheight.text().title()) pass class ScreenWindow(QtWidgets.QWidget): def __init__(self, glwindow, *args, **kwargs): super().__init__(*args, **kwargs) self._camera_angle = 0.0 self._glwindow = glwindow # Uebernahme des GLWindows zur Slidersteuerung self.initUI() pass def initUI(self): self.screengroup = QtWidgets.QGroupBox("Screenshot Window") self.screengroup.setTitle("Screenshot Window") self.screengroup.setToolTip("Click the button to generate a screenshot. This screenshot contains only the\n" "coloured part of the window, not the gui. Currently length is the fixed size \n" "of 1000 * 1000px, but we are working on a setting for that. The screenshot can \n" "either be in the PNG or the HTML-format. Latter can be opend with your browser") self.outer_box = QVBoxLayout() # Position the screengroup on the widget (self) self.outer_box.addWidget(self.screengroup) self.fullbox = QHBoxLayout() # Fullbox beinhaltet Screenshotknopf, Radiobuttons und Eingabe Zeile, jeweils in VBox mit Labeln self.screenbox = QVBoxLayout() # Screenbox beinhaltet das Label und den Knopf names Screenshot self.lbl = QLabel() self.screenbutton = QPushButton('Screenshot', self) self.screenbutton.setFixedSize(100, 30) self.screenbutton.clicked.connect(self.doScreenshot) self.lbl.setText("Screenshot") self.lbl.setFixedSize(100, 30) self.screenbox.addWidget(self.lbl) self.screenbox.addWidget(self.screenbutton) self.fileVBox = QVBoxLayout() # Filebox beinhaltet die Eingabezeile und das Label self.fileName = QLineEdit() self.fileName.setFocusPolicy(Qt.ClickFocus) self.fileLabel = QLabel() self.fileLabel.setText("Filename:") self.fileVBox.addWidget(self.fileLabel) self.fileVBox.addWidget(self.fileName) self.checkboxbox = QHBoxLayout() # Checkboxbox beinhaltet 2 HBoxen, die je ein Label und ein Radiobutton haben self.pngbox = QVBoxLayout() self.pngcheck = QRadioButton() self.pngcheck.setChecked(True) self.pnglabel = QLabel() self.pnglabel.setText("PNG") self.pngcheck.toggle() self.pngbox.addWidget(self.pnglabel) self.pngbox.addWidget(self.pngcheck) self.checkboxmanagment = QButtonGroup() # Mit der Buttongroup werden die Radiobuttons auf exklusiv gestellt self.povbox = QVBoxLayout() self.povcheck = QRadioButton() self.povcheck.setChecked(False) self.povlabel = QLabel() self.povlabel.setText("POV") self.htmlbox = QVBoxLayout() self.htmlcheck = QRadioButton() self.htmlcheck.setChecked(False) self.htmllabel = QLabel() self.htmllabel.setText("HTML") # self.pngcheck..connect(self.pngChange) # self.htmlcheck.stateChanged.connect(self.htmlChange) self.checkboxmanagment.addButton( self.pngcheck) # Hinzufuegen der Radiobuttons und dann das setzen der Gruppe auf exklusiv self.checkboxmanagment.addButton(self.povcheck) self.checkboxmanagment.addButton(self.htmlcheck) self.checkboxmanagment.setExclusive(True) # Exklusiv, sodass immer nur genau ein Knopf an sein kann self.povbox.addWidget(self.povlabel) self.povbox.addWidget(self.povcheck) self.htmlbox.addWidget(self.htmllabel) self.htmlbox.addWidget(self.htmlcheck) self.checkboxbox.addLayout(self.pngbox) self.checkboxbox.addLayout(self.povbox) self.checkboxbox.addLayout(self.htmlbox) self.fullbox.addLayout(self.screenbox) # Hinzufuegen der einzelnen Boxen zu der Gesamtbox self.fullbox.addLayout(self.checkboxbox) self.fullbox.addLayout(self.fileVBox) self.screengroup.setLayout(self.fullbox) self.outer_box.setContentsMargins(0, 0, 0, 0) self.setLayout(self.outer_box) self.warning_box = QtWidgets.QMessageBox() self.warning_box.setText("The name must be at least one character long") pass def doScreenshot(self): if self.pngcheck.isChecked(): # Wenn die Png Box an ist dann wird der Dateiname auf Variable gesetzt und das ganze anf das dataname = self.fileName.text() # glwindw uebergeben, da ansonsten zu fehlern kommt if dataname != "": self._glwindow.export(dataname) else: self.warning_box.show() else: if self.htmlcheck.isChecked(): format = "html" else: format = "pov" filename = spinVis_camera.make_screenshot(self.fileName.text(), format, 1920, 1920) # Test.screenshot ruft gr3.export mit html/pov auf spinVis_camera.render_povray(filename, block=False) self._glwindow.update() self.update() pass class AngleWindow(QtWidgets.QWidget): def __init__(self, glwindow, *args, **kwargs): super().__init__(*args, **kwargs) self._camera_angle = 0.0 self._glwindow = glwindow # Uebergabe des glwindow self.initUI() pass def initUI(self): self.anglegroup = QtWidgets.QGroupBox("Angle Window") self.anglegroup.setTitle("Angle Window") self.anglegroup.setToolTip("These 3 angles allow you to set a specific camera position. While phi and thete\n" "depict your camera position, is alpha used to show the rotation of the upvector.\n" "Any tripel you enter gives a unique view. ") self.groupbox = QtWidgets.QHBoxLayout() self.groupbox.addWidget(self.anglegroup) self.anglebox = QHBoxLayout() self.theta_box = QHBoxLayout() self.theta_lbl = QLabel() self.theta_lbl.setText("Theta: ") self.theta_input = QtWidgets.QLineEdit() self.theta_input.setFocusPolicy(Qt.ClickFocus) self.theta_input.setFixedSize(70,25) self.theta_box.addWidget(self.theta_lbl) self.theta_box.addWidget(self.theta_input) #self.theta_validator = QtGui.QDoubleValidator(-1/2 * math.pi, math.pi/2,5, self) #self.theta_input.setValidator(self.theta_validator) self.phi_box = QHBoxLayout() self.phi_lbl = QLabel() self.phi_lbl.setText("Phi: ") self.phi_input = QtWidgets.QLineEdit() self.phi_input.setFocusPolicy(Qt.ClickFocus) self.phi_input.setFixedSize(75,25) self.phi_box.addWidget(self.phi_lbl) self.phi_box.addWidget(self.phi_input) #self.phi_validator = QtGui.QDoubleValidator(-1* math.pi, math.pi,5, self) #self.phi_input.setValidator(self.phi_validator) self.up_box = QHBoxLayout() self.up_lbl = QLabel() self.up_lbl.setText("Alpha: ") self.up_input = QtWidgets.QLineEdit() self.up_input.setFocusPolicy(Qt.ClickFocus) self.up_input.setFixedSize(75, 25) self.up_box.addWidget(self.up_lbl) self.up_box.addWidget(self.up_input) self.angle_button = QPushButton("Set camera") self.angle_button.setMaximumSize(150, 25) self.angle_button.clicked.connect(self.camera_change_from_angle) euler_norm = np.linalg.norm(spinVis_coor.camera_koordinates) euler_theta = math.acos(spinVis_coor.camera_koordinates[2] / euler_norm) euler_phi = np.arctan2(spinVis_coor.camera_koordinates[1], spinVis_coor.camera_koordinates[0]) self.theta_input.setText(str(round(euler_theta, 5))) self.phi_input.setText(str(round(euler_phi, 5))) r = np.array([-math.sin(euler_phi), math.cos(euler_phi), 0]) v = np.array([-math.cos(euler_phi) * math.cos(euler_theta), -math.sin(euler_phi) * math.cos(euler_theta), math.sin(euler_theta)]) alpha = math.atan2(-1 * np.dot(spinVis_camera.up_vector, r), np.dot(spinVis_camera.up_vector, v)) self.up_input.setText(str(round(alpha, 5))) self.anglebox.addLayout(self.theta_box) self.anglebox.addLayout(self.phi_box) self.anglebox.addLayout(self.up_box) self.anglebox.addWidget(self.angle_button) self.anglegroup.setLayout(self.anglebox) self._glwindow.register(self.theta_input) self._glwindow.register(self.phi_input) self._glwindow.register(self.up_input) self.groupbox.setContentsMargins(0,0,0,0) self.setLayout(self.groupbox) def keyPressEvent(self, QKeyEvent): if QKeyEvent.key() == QtCore.Qt.Key_Return or QKeyEvent.key() == QtCore.Qt.Key_Enter: self.camera_change_from_angle() def camera_change_from_angle(self): try: theta = float(self.theta_input.text().__str__()) phi = float(self.phi_input.text().__str__()) input_up = float(self.up_input.text().__str__()) r = np.array([-math.sin(phi), math.cos(phi), 0]) v = np.array([-math.cos(phi) * math.cos(theta), -math.sin(phi) * math.cos(theta), math.sin(theta)]) self._glwindow.new_up_v = v * math.cos(input_up) - r * math.sin(input_up) spinVis_coor.euler_angles_to_koordinates(theta, phi, np.linalg.norm(spinVis_coor.camera_koordinates), input_up) self._glwindow.update() except ValueError: val_err_box = QtWidgets.QMessageBox() val_err_box.setIcon(2) # Gives warning Icon val_err_box.setText("Error ocurred while trying to recalculate the camera position!") val_err_box.setInformativeText("Your entred value was not a floating number. Please make sure that your input is right, before trying to change the camera.") val_err_box.exec_() class BondWindow(QtWidgets.QWidget): def __init__(self, glwindow, *args, **kwargs): super().__init__(*args, **kwargs) self._distance_threshold = 0.0 self._glwindow = glwindow # Uebergabe des glwindow self.initUI() spinVis_camera.bond_distance_threshold_callback = lambda value: self.threshold_input.setText(str(round(value, 5))) def initUI(self): self.bondgroup = QtWidgets.QGroupBox("Bond Window") self.bondgroup.setTitle("Bond Window") self.bondgroup.setToolTip("Set a distance threshold for bond calculation. The default value is 150 per cent\n" "of the minimum distance between the centers of two spins.") self.groupbox = QtWidgets.QHBoxLayout() self.groupbox.addWidget(self.bondgroup) self.bondbox = QHBoxLayout() self.threshold_box = QHBoxLayout() self.threshold_checkbox = QCheckBox("Show bonds") self.threshold_checkbox.stateChanged.connect(self.update_bond_distance_threshold) self.threshold_lbl = QLabel() self.threshold_lbl.setText("Distance threshold: ") self.threshold_input = QtWidgets.QLineEdit() self.threshold_input.setFocusPolicy(Qt.ClickFocus) self.threshold_input.setFixedSize(70, 25) self.threshold_input.returnPressed.connect(self.update_bond_distance_threshold) self.threshold_box.addWidget(self.threshold_checkbox) self.threshold_box.addWidget(self.threshold_lbl) self.threshold_box.addWidget(self.threshold_input) self.bond_button = QPushButton("Set threshold") self.bond_button.setMaximumSize(150, 25) self.bond_button.clicked.connect(self.update_bond_distance_threshold) self.bondbox.addLayout(self.threshold_box) self.bondbox.addWidget(self.bond_button) self.bondgroup.setLayout(self.bondbox) self.groupbox.setContentsMargins(0, 0, 0, 0) self.setLayout(self.groupbox) def update_bond_distance_threshold(self): try: if self.threshold_input.text().strip() != "": threshold = float(self.threshold_input.text()) spinVis_camera.bond_distance_threshold = threshold else: spinVis_camera.bond_distance_threshold = None spinVis_camera.bond_is_activated = self.threshold_checkbox.isChecked() self._glwindow.spinDraw() self._glwindow.update() except ValueError: val_err_box = QtWidgets.QMessageBox() val_err_box.setIcon(2) # Gives warning Icon val_err_box.setText("Error ocurred while trying to recalculate the bonds!") val_err_box.setInformativeText("Your entred value was not a floating number. Please make sure that your input is right, before trying to change the bond distance threshold.") val_err_box.exec_() class TranslationWindow(QtWidgets.QWidget): def __init__(self, glwindow, *args, **kwargs): super().__init__(*args, **kwargs) self._camera_angle = 0.0 self._glwindow = glwindow # Uebergabe des glwindow self.initUI() pass def initUI(self): self.translationgroup = QtWidgets.QGroupBox("Angle Window") self.translationgroup.setTitle("Translation Window") self.translationgroup.setToolTip("These 3 angles allow you to set a specific camera position. While phi and thete\n" "depict your camera position, is alpha used to show the rotation of the upvector.\n" "Any tripel you enter gives a unique view. ") self.groupbox = QtWidgets.QHBoxLayout() self.groupbox.addWidget(self.translationgroup) self.translationbox = QHBoxLayout() self.x_box = QHBoxLayout() self.x_lbl = QLabel() self.x_lbl.setText("X: ") self.x_input = QtWidgets.QLineEdit() self.x_input.setFocusPolicy(Qt.ClickFocus) self.x_input.setFixedSize(70,25) self.x_box.addWidget(self.x_lbl) self.x_box.addWidget(self.x_input) #self.theta_validator = QtGui.QDoubleValidator(-1/2 * math.pi, math.pi/2,5, self) #self.theta_input.setValidator(self.theta_validator) self._glwindow._focus_observer.append(self.x_input.setText) self.y_box = QHBoxLayout() self.y_lbl = QLabel() self.y_lbl.setText("Y: ") self.y_input = QtWidgets.QLineEdit() self.y_input.setFocusPolicy(Qt.ClickFocus) self.y_input.setFixedSize(75,25) self.y_box.addWidget(self.y_lbl) self.y_box.addWidget(self.y_input) self._glwindow._focus_observer.append(self.y_input.setText) #self.phi_validator = QtGui.QDoubleValidator(-1* math.pi, math.pi,5, self) #self.phi_input.setValidator(self.phi_validator) self.z_box = QHBoxLayout() self.z_lbl = QLabel() self.z_lbl.setText("Z: ") self.z_input = QtWidgets.QLineEdit() self.z_input.setFocusPolicy(Qt.ClickFocus) self.z_input.setFixedSize(75, 25) self.z_box.addWidget(self.z_lbl) self.z_box.addWidget(self.z_input) self._glwindow._focus_observer.append(self.z_input.setText) self.translation_button = QPushButton("Translate focus") self.translation_button.setMaximumSize(150, 25) self.translation_button.clicked.connect(self.change_focus_point) self.x_input.setText(str(0)) self.y_input.setText(str(0)) self.z_input.setText(str(0)) self.translationbox.addLayout(self.x_box) self.translationbox.addLayout(self.y_box) self.translationbox.addLayout(self.z_box) self.translationbox.addWidget(self.translation_button) self.translationgroup.setLayout(self.translationbox) self.groupbox.setContentsMargins(0,0,0,0) self.setLayout(self.groupbox) def keyPressEvent(self, QKeyEvent): if QKeyEvent.key() == QtCore.Qt.Key_Return or QKeyEvent.key() == QtCore.Qt.Key_Enter: self.change_focus_point() def change_focus_point(self): spinVis_camera.focus_point = np.array([float(self.x_input.text()), float(self.y_input.text()), float(self.z_input.text())]) spinVis_camera.grLookAt() self._glwindow.update() class GLWidget(QtWidgets.QOpenGLWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._first_paint = True self._make_video = False self._camera_angle = 0.0 self._draw_spin = True # Verhindert das bei jeder Kamerabewegung die Spins neu gezeichnet werden self._export_screen = False # exportScreen wird beim Knopfdruck auf True gestellt und triggert so export() self.point_c_vektor = np.array([spinVis_coor.camera_koordinates[0], spinVis_coor.camera_koordinates[1], spinVis_coor.camera_koordinates[ 2]]) # Ortsvektor des Punktes andem die Kamerabewegung aufhört self.current_camera_vector = np.array([spinVis_coor.camera_koordinates[0], spinVis_coor.camera_koordinates[1], spinVis_coor.camera_koordinates[2]]) # Kameravektor self.camera_vektor_length = np.linalg.norm(spinVis_coor.camera_koordinates) # Norm des Kameravektors self.point_a_vektor = np.array([spinVis_coor.camera_koordinates[0], spinVis_coor.camera_koordinates[1], spinVis_coor.camera_koordinates[ 2]]) # Ortsvektor des Punktes andem die Kamerabewegung startet self._radius = 2 # Radius des Arcballs self.focus_point = np.array([0.0, 0.0, 0.0]) # Fokuspunkt self.new_up_v =
np.array([0.0, 0.0, 1.0])
numpy.array
#emcee analysis for GRB afterglow # #<NAME> 01/10/2018 <EMAIL> from multiprocessing import Pool import tqdm import numpy as np import corner import emcee from os.path import join from astropy.table import Table, Column import joelib.physics.jethead_expansion as Exp from joelib.constants.constants import * #I'VE LEFT THE DATA IN HERE, YOU CAN USE THIS TO TEST AGAINST YOUR OUTPUT - NOTE THAT THERE ARE FOUR(4) FREQUENCIES - BUT I'M SURE YOU CAN FIGURE IT OUT. #ALTERNATIVELY, JUST USE THE DATA YOU HAVE HOWEVER IS EASIEST ;-) time = np.array([ 9.2, 14.9, 16.4, 17.4, 18.3, 18.7, 19.4, 21.4, 22.4, 23.4, 24.2, 31.3, 35.3, 39.2, 46.3, 53.3, 54.3, 57.2, 65.9, 66.6, 67.2, 72.2, 75.5, 75.5, 77.6, 79.2, 80.1, 92.4, 93.1, 93.1, 93.2, 97.1, 107. , 107. , 109. , 109. , 111. , 112. , 115. , 115. , 115. , 125. , 125. , 126. , 133. , 137. , 149. , 150. , 152. , 158. , 161. , 163. , 163. , 163. , 163. , 165. , 167. , 170. , 172. , 183. , 197. , 197. , 207. , 209. , 216. , 217. , 217. , 217. , 217. , 218. , 218. , 222. , 229. , 252. , 257. , 259. , 261. , 267. , 267. , 273. , 273. , 289. , 289. , 294. , 297. , 298. , 320. , 324. , 328. , 357. , 359. , 362. , 380. , 489. , 545. , 580. , 581. , 741. , 767. , 938. ]) data = np.array([5.66e-04, 6.58e-04, 1.87e+01, 1.51e+01, 1.45e+01, 1.54e+01, 1.59e+01, 1.36e+01, 2.25e+01, 2.00e+01, 2.56e+01, 3.40e+01, 4.40e+01, 2.28e+01, 4.40e+01, 3.20e+01, 4.80e+01, 6.10e+01, 1.48e+02, 9.80e+01, 4.26e+01, 5.80e+01, 3.59e+01, 3.96e+01, 7.70e+01, 4.50e+01, 4.17e+01, 3.17e+01, 9.80e+01, 7.00e+01, 2.60e+01, 1.99e+02, 1.27e+02, 5.32e+01, 2.96e-03, 1.09e-01, 1.11e-01, 6.29e+01, 9.62e+01, 5.12e+01, 4.12e+01, 5.82e+01, 1.28e+02, 2.21e+02, 3.37e-03, 8.40e-02, 6.06e+01, 9.00e+01, 1.84e+02, 3.03e-03, 2.66e-03, 9.73e+01, 6.73e+01, 4.74e+01, 3.96e+01, 9.10e-02, 5.79e+01, 1.13e-01, 8.50e-02, 2.11e+02, 7.59e+01, 8.93e+01, 4.20e+01, 8.20e-02, 3.63e+01, 6.05e+01, 4.17e+01, 3.26e+01, 2.47e+01, 6.47e+01, 6.30e-02, 3.97e+01, 4.80e+01, 7.13e+01, 4.32e+01, 1.55e-03, 6.26e+01, 2.50e+01, 4.03e+01, 3.48e+01, 2.72e+01, 3.63e+01, 2.70e+01, 3.12e+01, 4.40e-02, 2.34e+01, 2.31e+01, 4.72e+01, 3.40e-02, 9.70e-04, 1.55e+01, 2.70e-02, 3.79e+01, 1.48e+01, 5.90e+00, 1.80e+01, 3.54e-04, 2.68e-04, 4.90e+00, 1.95e-04]) freq = np.array([2.41e+17, 2.41e+17, 3.00e+09, 3.00e+09, 3.00e+09, 7.25e+09, 6.20e+09, 6.20e+09, 3.00e+09, 6.00e+09, 3.00e+09, 3.00e+09, 1.50e+09, 6.00e+09, 3.00e+09, 6.00e+09, 3.00e+09, 3.00e+09, 6.70e+08, 1.30e+09, 6.00e+09, 4.50e+09, 7.35e+09, 7.35e+09, 1.40e+09, 4.50e+09, 6.00e+09, 7.25e+09, 1.50e+09, 3.00e+09, 1.50e+10, 6.70e+08, 1.30e+09, 1.30e+09, 2.41e+17, 3.80e+14, 5.06e+14, 6.00e+09, 3.00e+09, 1.00e+10, 1.50e+10, 7.25e+09, 1.30e+09, 6.70e+08, 2.41e+17, 5.06e+14, 7.25e+09, 5.10e+09, 1.30e+09, 2.41e+17, 2.41e+17, 3.00e+09, 6.00e+09, 1.00e+10, 1.50e+10, 5.06e+14, 7.25e+09, 3.80e+14, 5.06e+14, 6.50e+08, 3.00e+09, 1.30e+09, 5.00e+09, 5.06e+14, 1.00e+10, 3.00e+09, 6.00e+09, 1.00e+10, 1.50e+10, 3.00e+09, 5.06e+14, 7.25e+09, 4.50e+09, 1.30e+09, 3.00e+09, 2.41e+17, 1.30e+09, 7.25e+09, 3.00e+09, 3.00e+09, 6.00e+09, 3.00e+09, 6.00e+09, 3.00e+09, 5.06e+14, 7.25e+09, 7.25e+09, 1.30e+09, 5.06e+14, 2.41e+17, 7.25e+09, 5.06e+14, 1.30e+09, 3.00e+09, 6.00e+09, 7.25e+09, 2.41e+17, 2.41e+17, 3.00e+09, 2.41e+17]) err = np.array([1.70e-04, 1.30e-04, 6.30e+00, 3.90e+00, 3.70e+00, 4.80e+00, 5.50e+00, 2.90e+00, 3.40e+00, 3.10e+00, 2.90e+00, 3.60e+00, 1.00e+01, 2.60e+00, 4.00e+00, 4.00e+00, 6.00e+00, 9.00e+00, 2.20e+01, 2.00e+01, 4.10e+00, 5.00e+00, 4.30e+00, 7.00e+00, 1.90e+01, 7.00e+00, 4.70e+00, 4.30e+00, 1.40e+01, 5.70e+00, 4.40e+00, 1.60e+01, 1.80e+01, 4.50e+00, 2.60e-04, 1.70e-02, 1.90e-02, 3.20e+00, 8.00e+00, 3.40e+00, 1.90e+00, 5.00e+00, 2.10e+01, 1.90e+01, 4.00e-04, 1.80e-02, 4.30e+00, 3.00e+01, 1.90e+01, 2.60e-04, 2.70e-04, 1.13e+01, 4.10e+00, 3.60e+00, 2.00e+00, 1.60e-02, 6.90e+00, 1.90e-02, 1.70e-02, 3.40e+01, 5.20e+00, 1.39e+01, 1.20e+01, 2.00e-02, 3.60e+00, 7.50e+00, 7.50e+00, 4.00e+00, 3.10e+00, 2.70e+00, 1.80e-02, 7.20e+00, 6.00e+00, 6.70e+00, 5.80e+00, 1.90e-04, 7.00e+00, 4.10e+00, 2.70e+00, 4.90e+00, 2.10e+00, 3.90e+00, 2.80e+00, 3.60e+00, 1.40e-02, 4.20e+00, 4.00e+00, 1.28e+01, 1.10e-02, 1.90e-04, 5.00e+00, 7.00e-03, 1.18e+01, 2.90e+00, 1.90e+00, 4.20e+00, 9.00e-05, 9.00e-05, 1.80e+00, 7.00e-05]) print(np.shape(time),np.shape(freq), np.shape(data), np.shape(err)) #freqs = np.array([3.00e9, 6.00e9, 2.41e17, 5.06e14]) #fil = [(freq==3.00e9) | (freq==6.00e9) | (freq==2.41e17) | (freq==5.06e14)] #time = time[fil] #data = data[fil] #freq = freq[fil] #err = err[fil] freqs = np.unique(freq) data_ord = np.array([]) err_ord = np.array([]) time_ord = np.array([]) for frequency in freqs: print(frequency) data_ord = np.concatenate([data_ord, data[freq==frequency]]) err_ord = np.concatenate([err_ord, err[freq==frequency]]) time_ord = np.concatenate([time_ord, time[freq==frequency]]) print(np.shape(err_ord), np.shape(data_ord)) #The model afterglow --- Put your afterglow scipt here def lnlike(prior, time, data_ord, freq, err_ord): E1, G1, thc1, incl1, EB1, Ee1, n1, p = prior incl1 = np.arccos(incl1) #model parameters EB, Ee, pp, nn, Eps0, G0 = 10.**EB1, 10.**Ee1, p, 10.**n1, 10.**E1, G1 #microphysical magnetic EB, microphysical electric Ee, particle index p #ambient number density n, isotropic kinetic energy Eiso, Lorentz factor Gc #THESE ^ ARE THE MCMC PRIOR PARAMETERS #USE THESE TO FEED AN ITERATION OF YOUR CODE #PUT YOUR FIXED PARAMETERS HERE (I FIX THETA_J) AND CALL YOUR SCRIPT jet = Exp.jetHeadGauss(Eps0, G0, nn, Ee, EB, pp, 500, 1e14, 1e22, "peer", 50, 30.*pi/180., thc1, aa=1, withSpread=False) tt, lc, _, _ = Exp.light_curve_peer_SJ(jet, pp, incl1, freqs, 41.3e6*pc, "discrete", time, 1) LC= np.array([]) for frequency in freqs: LC = np.concatenate([LC, lc[freqs==frequency,time_ord[freq==frequency]]]) #RETURN AN ARRAY OF FLUX VALUES AT TIMES AND FREQUENCIES THAT ARE THE SAME AS THE OBSERVATIONS #I CALLED THIS flx AND IT IS IN THE SAME UNITS AS THE data AND err ARRAYS ABOVE flx = LC*1.e29 #erg/s/cm^2/Hz to mJy #THIS IS THE LIKLIHOOD FUNCTION - DON'T OVER THINK IT, WE JUST NEED TO MINIMISE THE ERROR, NOTHING FANCY -- IT USES THE data AND err WITH THE SCRIPT flx VALUES like = -0.5*(np.sum(((data_ord-flx)/err_ord)**2.))#+np.log(err**2) return like def lnprior(prior): E1, G1, thc1, incl1, EB1, Ee1, n1, p = prior #THESE ARE THE PRIOR LIMITS -- NOTE THAT SOME OF THESE ARE LOGARITHMIC (see line 37 above, or in cosine space) if 47. <= E1 <= 54. and 2. <= G1 <= 1000. and 0.0175 <= thc1 <= 0.4363 and 0.9004 <= incl1 <= 0.9689 and -5.<= EB1 <= -0.5 and -5. <= Ee1 <= -0.5 and -6. <= n1 <= 0. and 2.01 <= p <= 2.99: return 0 return -np.inf def lnprob(prior, time, data_ord, freq, err_ord): lp = lnprior(prior) if np.isinf(lp): return -np.inf return lp+lnlike(prior, time, data_ord, freq, err_ord) if __name__ == "__main__": nwalkers = 32 # minimum is 2*ndim, more the merrier ndim = 8 #THIS IS THE NUMBER OF FREE PARAMETERS THAT YOU ARE FITTING burnsteps = 1000 nsteps = 10000 # MCMC steps, should be >1e3 thin = 1 #THIS REMOVES SOME OF THE SAMPLE ie thin = 2 WOULD ONLY SAMPLE EVERY SECOND POSTERIOR (GOOD FOR VERY LARGE DATA SETS) p0 = np.zeros([nwalkers,ndim],float) # Initial parameter guess print ("Initial parameter guesses") p0[:, 0] = 51 + np.random.randn(nwalkers)*0.1 # sample E1 p0[:, 1] = 100 + np.random.randn(nwalkers)*10 # sample G1 p0[:, 2] = 0.12 + np.random.randn(nwalkers)*0.01 # sample thc1 p0[:, 3] = 0.91 + np.random.randn(nwalkers)*0.01 # sample cos(incl1) p0[:, 4] = -2.1 +
np.random.randn(nwalkers)
numpy.random.randn
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam, SGD from Renderer.model import * from DRL.rpm import rpm from DRL.actor import * from DRL.critic import * from DRL.wgan import * from utils.util import * device = torch.device("cuda" if torch.cuda.is_available() else "cpu") coord = torch.zeros([1, 2, 128, 128]) for i in range(128): for j in range(128): coord[0, 0, i, j] = i / 127. coord[0, 1, i, j] = j / 127. coord = coord.to(device) criterion = nn.MSELoss() Decoder = FCN() Decoder.load_state_dict(torch.load('renderer.pkl')) def decode(x, canvas): # b * (10 + 3) x = x.view(-1, 10 + 3) stroke = 1 - Decoder(x[:, :10]) stroke = stroke.view(-1, 128, 128, 1) color_stroke = stroke * x[:, -3:].view(-1, 1, 1, 3) stroke = stroke.permute(0, 3, 1, 2) color_stroke = color_stroke.permute(0, 3, 1, 2) stroke = stroke.view(-1, 5, 1, 128, 128) color_stroke = color_stroke.view(-1, 5, 3, 128, 128) for i in range(5): canvas = canvas * (1 - stroke[:, i]) + color_stroke[:, i] return canvas def cal_trans(s, t): return (s.transpose(0, 3) * t).transpose(0, 3) class TD3(object): def __init__(self, batch_size=64, env_batch=1, max_step=40, \ tau=0.001, discount=0.9, rmsize=800, \ writer=None, resume=None, output_path=None): self.max_step = max_step self.env_batch = env_batch self.batch_size = batch_size self.actor = ResNet(9, 18, 65) # target, canvas, stepnum, coordconv 3 + 3 + 1 + 2 self.actor_target = ResNet(9, 18, 65) self.critic = ResNet_wobn(3 + 9, 18, 1) # add the last canvas for better prediction self.critic_target = ResNet_wobn(3 + 9, 18, 1) print (self.critic) self.actor_optim = Adam(self.actor.parameters(), lr=1e-2) self.critic_optim = Adam(self.critic.parameters(), lr=1e-2) if (resume != None): self.load_weights(resume) hard_update(self.actor_target, self.actor) hard_update(self.critic_target, self.critic) # Create replay buffer self.memory = rpm(rmsize * max_step) # Hyper-parameters self.tau = tau self.discount = discount self.actor_update_freq = 3 self.actor_update_cur_iter = 0 # Tensorboard self.writer = writer self.log = 0 self.state = [None] * self.env_batch # Most recent state self.action = [None] * self.env_batch # Most recent action self.choose_device() def play(self, state, target=False): state = torch.cat((state[:, :6].float() / 255, state[:, 6:7].float() / self.max_step, coord.expand(state.shape[0], 2, 128, 128)), 1) if target: return self.actor_target(state) else: return self.actor(state) def update_gan(self, state): canvas = state[:, :3] gt = state[:, 3 : 6] fake, real, penal = update(canvas.float() / 255, gt.float() / 255) if self.log % 20 == 0: self.writer.add_scalar('train/gan_fake', fake, self.log) self.writer.add_scalar('train/gan_real', real, self.log) self.writer.add_scalar('train/gan_penal', penal, self.log) def evaluate(self, state, action, target=False): T = state[:, 6 : 7] gt = state[:, 3 : 6].float() / 255 canvas0 = state[:, :3].float() / 255 canvas1 = decode(action, canvas0) gan_reward = cal_reward(canvas1, gt) - cal_reward(canvas0, gt) # L2_reward = ((canvas0 - gt) ** 2).mean(1).mean(1).mean(1) - ((canvas1 - gt) ** 2).mean(1).mean(1).mean(1) coord_ = coord.expand(state.shape[0], 2, 128, 128) merged_state = torch.cat([canvas0, canvas1, gt, (T + 1).float() / self.max_step, coord_], 1) # canvas0 is not necessarily added if target: Q1, Q2 = self.critic_target(merged_state) Q = torch.min(Q1, Q2) return (Q + gan_reward), gan_reward else: Q1, Q2 = self.critic(merged_state) #Q = torch.min(Q1, Q2) if self.log % 20 == 0: self.writer.add_scalar('train/expect_reward', Q1.mean(), self.log) self.writer.add_scalar('train/gan_reward', gan_reward.mean(), self.log) return (Q1 + gan_reward), (Q2 + gan_reward), gan_reward def update_policy(self, lr): self.log += 1 for param_group in self.critic_optim.param_groups: param_group['lr'] = lr[0] for param_group in self.actor_optim.param_groups: param_group['lr'] = lr[1] # Sample batch state, action, reward, \ next_state, terminal = self.memory.sample_batch(self.batch_size, device) self.update_gan(next_state) with torch.no_grad(): next_action = self.play(next_state, True) target_q, _ = self.evaluate(next_state, next_action, True) target_q = self.discount * ((1 - terminal.float()).view(-1, 1)) * target_q cur_q1, cur_q2, step_reward = self.evaluate(state, action) target_q += step_reward.detach() value_loss = criterion(cur_q1, target_q) + criterion(cur_q2, target_q) self.critic.zero_grad() value_loss.backward(retain_graph=True) self.critic_optim.step() action = self.play(state) pre_q, _, _ = self.evaluate(state.detach(), action) policy_loss = -pre_q.mean() if self.actor_update_cur_iter % self.actor_update_freq == 0: self.actor.zero_grad() policy_loss.backward(retain_graph=True) self.actor_optim.step() soft_update(self.actor_target, self.actor, self.tau) self.actor_update_cur_iter += 1 soft_update(self.critic_target, self.critic, self.tau) # Target update return -policy_loss, value_loss def observe(self, reward, state, done, step): s0 = torch.tensor(self.state, device='cpu') a = to_tensor(self.action, "cpu") r = to_tensor(reward, "cpu") s1 = torch.tensor(state, device='cpu') d = to_tensor(done.astype('float32'), "cpu") for i in range(self.env_batch): self.memory.append([s0[i], a[i], r[i], s1[i], d[i]]) self.state = state def noise_action(self, noise_factor, state, action): noise = np.zeros(action.shape) for i in range(self.env_batch): action[i] = action[i] +
np.random.normal(0, self.noise_level[i], action.shape[1:])
numpy.random.normal
import functools from typing import Any, Callable, Optional, Tuple, TypeVar import numpy as np import pandas as pd from multimethod import multimethod from scipy.stats import chisquare from pandas_profiling.config import Settings T = TypeVar("T") def func_nullable_series_contains(fn: Callable) -> Callable: @functools.wraps(fn) def inner( config: Settings, series: pd.Series, state: dict, *args, **kwargs ) -> bool: if series.hasnans: series = series.dropna() if series.empty: return False return fn(config, series, state, *args, **kwargs) return inner def histogram_compute( config: Settings, finite_values: np.ndarray, n_unique: int, name: str = "histogram", weights: Optional[np.ndarray] = None, ) -> dict: stats = {} bins = config.plot.histogram.bins bins_arg = "auto" if bins == 0 else min(bins, n_unique) stats[name] = np.histogram(finite_values, bins=bins_arg, weights=weights) max_bins = config.plot.histogram.max_bins if bins_arg == "auto" and len(stats[name][1]) > max_bins: stats[name] = np.histogram(finite_values, bins=max_bins, weights=None) return stats def chi_square( values: Optional[np.ndarray] = None, histogram: Optional[np.ndarray] = None ) -> dict: if histogram is None: histogram, _ = np.histogram(values, bins="auto") return dict(chisquare(histogram)._asdict()) def series_hashable( fn: Callable[[Settings, pd.Series, dict], Tuple[Settings, pd.Series, dict]] ) -> Callable[[Settings, pd.Series, dict], Tuple[Settings, pd.Series, dict]]: @functools.wraps(fn) def inner( config: Settings, series: pd.Series, summary: dict ) -> Tuple[Settings, pd.Series, dict]: if not summary["hashable"]: return config, series, summary return fn(config, series, summary) return inner def series_handle_nulls( fn: Callable[[Settings, pd.Series, dict], Tuple[Settings, pd.Series, dict]] ) -> Callable[[Settings, pd.Series, dict], Tuple[Settings, pd.Series, dict]]: """Decorator for nullable series""" @functools.wraps(fn) def inner( config: Settings, series: pd.Series, summary: dict ) -> Tuple[Settings, pd.Series, dict]: if series.hasnans: series = series.dropna() return fn(config, series, summary) return inner def named_aggregate_summary(series: pd.Series, key: str) -> dict: summary = { f"max_{key}": np.max(series), f"mean_{key}":
np.mean(series)
numpy.mean
import matplotlib.pyplot as plt import numpy as np from . import pretty_plot def plot_butterfly(evoked, ax=None, sig=None, color=None, ch_type=None): from mne import pick_types if ch_type is not None: picks = pick_types(evoked.info, ch_type) evoked = evoked.copy() evoked = evoked.pick_types(ch_type) sig = sig[picks, :] if sig is not None else None times = evoked.times * 1e3 data = evoked.data ax = plt.gca() if ax is None else ax ax.plot(times, data.T, color='k', alpha=.5) gfp = np.vstack((data.max(0), data.min(0))) if sig is not None: sig = np.array(np.sum(sig, axis=0) > 0., dtype=int) ax.fill_between(np.hstack((times, times[::-1])), np.hstack((sig * gfp[0, :] + (1 - sig) * gfp[1, :], gfp[1, ::-1])), facecolor=color, edgecolor='none', alpha=.5, zorder=len(data) + 1) ax.axvline(0, color='k') ax.set_xlabel('Times (ms)') ax.set_xlim(min(times), max(times)) xticks = np.arange(np.ceil(min(times)/1e2) * 1e2, np.floor(max(times)/1e2) * 1e2 + 1e-10, 100) ax.set_xticks(xticks) ax.set_xticklabels(['%i' % t if t in [xticks[0], xticks[-1], 0] else '' for t in xticks]) ax.set_yticks([np.min(data), np.max(data)]) ax.set_ylim(np.min(data), np.max(data)) ax.set_xlim(np.min(times), np.max(times)) pretty_plot(ax) return ax def plot_gfp(evoked, ax=None, sig=None, color=None, ch_type='mag'): from mne import pick_types if ch_type is not None: picks = pick_types(evoked.info, ch_type) evoked = evoked.copy() evoked = evoked.pick_types(ch_type) sig = sig[picks, :] if sig is not None else None times = evoked.times * 1e3 gfp = np.std(evoked.data, axis=0) ax = plt.gca() if ax is None else ax ax.plot(times, gfp, color='k', alpha=.5) if sig is not None: sig = np.array(np.sum(sig, axis=0) > 0., dtype=int) ax.fill_between(np.hstack((times, times[::-1])), np.hstack((sig * gfp,
np.zeros_like(gfp)
numpy.zeros_like
import libmist as pld import numpy as np import pytest from multiprocessing import cpu_count def test_parallel_2(): filename = "sample_data.csv" cpus = cpu_count() total_ranks = cpus * 2 ranks_per = cpus # non-parallel mist = pld.Search() mist.load_file_column_major(filename) mist.tuple_size = 3 res = mist.start() # first ranks mist = pld.Search() mist.load_file_column_major(filename) mist.tuple_size = 3 mist.ranks = ranks_per mist.total_ranks = total_ranks res1 = mist.start() # second ranks mist = pld.Search() mist.load_file_column_major(filename) mist.tuple_size = 3 mist.ranks = ranks_per mist.total_ranks = total_ranks mist.start_rank = ranks_per res2 = mist.start() res_sort = np.sort(res, axis=0) res_parallel = np.concatenate([res1, res2]) res_parallel_sort = np.sort(res_parallel, axis=0) assert(res.shape[0] == res_parallel_sort.shape[0]) assert(res.shape[1] == res_parallel_sort.shape[1]) np.testing.assert_array_equal(res_sort, res_parallel_sort) def test_parallel_3_same_obj(): filename = "sample_data.csv" cpus = cpu_count() total_ranks = cpus * 3 ranks_per = cpus # non-parallel mist = pld.Search() mist.load_file_column_major(filename) mist.tuple_size = 3 res = mist.start() # first ranks mist.ranks = ranks_per mist.total_ranks = total_ranks res1 = mist.start() # second ranks mist.ranks = ranks_per mist.total_ranks = total_ranks mist.start_rank = ranks_per res2 = mist.start() # third ranks mist.ranks = ranks_per mist.total_ranks = total_ranks mist.start_rank = ranks_per * 2 res3 = mist.start() res_sort = np.sort(res, axis=0) res12 = np.concatenate([res1, res2]) res_parallel = np.concatenate([res12, res3]) res_parallel_sort =
np.sort(res_parallel, axis=0)
numpy.sort
"""Situation Awareness Module""" import enum import operator import time import numpy as np from sklearn.cluster import DBSCAN from driver_awareness_msgs.msg import ROI, SA class SituationAwareness: """Class to calculate the situation awareness""" def __init__(self, punishment_model): self.__optimal_sa = 0 self.__actual_sa = 0 self.__punishment = punishment_model @property def sa_msg(self): sa_msg = SA() sa_msg.optimal_sa = self.__optimal_sa sa_msg.actual_sa = self.__actual_sa return sa_msg def calculate_sa(self, se_array, non_roi_gazes): type_weights = [situation_element.type_weight for situation_element in se_array] classifications = [ situation_element.classification_value for situation_element in se_array ] self.__optimal_sa = sum(type_weights) actual_sa = sum(list(map(operator.mul, type_weights, classifications))) self.__actual_sa = actual_sa - self.__punishment.punishment(non_roi_gazes) self.__actual_sa = max(0.0, self.__actual_sa) class PunishmentModel: """Class to calculate the punishment score""" def __init__( self, dbscan_max_distance_px, dbscan_min_samples, punishment_factor=0.25 ): self.__dbscan = DBSCAN( eps=float(dbscan_max_distance_px), min_samples=dbscan_min_samples, ) self.__punishment_factor = punishment_factor def punishment(self, non_roi_gazes): if not non_roi_gazes: return 0.0 gaze_coordinates = [ (gaze.gaze_pixel.x, gaze.gaze_pixel.y) for gaze in non_roi_gazes ] labels = self.__dbscan.fit_predict(gaze_coordinates) num_clusters = len(set(labels)) - (1 if -1 in labels else 0) return self.__punishment_factor * num_clusters class GazeBuffer: """Buffer for gaze data""" def __init__(self): self.__data = [] self.__current_gaze = (0, 0) @property def data(self): return self.__data @property def current_gaze(self): return self.__current_gaze def push_array(self, gaze_array): self.__data.extend(gaze_array) self.__current_gaze = (gaze_array[-1].gaze_pixel.x, gaze_array[-1].gaze_pixel.y) def clear(self): self.__data = [] class SituationAwarenessParameter: """Collection of Parameter for detection/comprehension decisions""" def __init__( self, comprehension_alive_time, num_gaze_comprehended, num_gaze_detected ): self.__comprehension_alive_time = comprehension_alive_time self.__num_gaze_comprehended = num_gaze_comprehended self.__num_gaze_detected = num_gaze_detected @property def num_gaze_detected(self): return self.__num_gaze_detected @property def num_gaze_comprehended(self): return self.__num_gaze_comprehended @property def comprehension_alive_time(self): return self.__comprehension_alive_time class SituationElement: """Situation Element""" class TypeWeight: """Defines the type weights for situation elements""" REQUIRED = 2.0 DESIRED = 1.0 class ClassificationWeight: """Defines the classification weights for situation elements""" COMPREHENDED = 1.0 DETECTED = 0.5 UNDETECTED = 0.0 class Classification(enum.Enum): """Defines classification types for situation elements""" COMPREHENDED = "comprehended" DETECTED = "detected" SE_ALIVE_COUNTER = 1 def __init__(self, roi_msg, sa_parameter): self.__msg = roi_msg self.__sa_parameter = sa_parameter self.__changed = True self.__alive_counter = self.SE_ALIVE_COUNTER self.__time_last_looked = time.time() self.__num_gazes_inside = 0 @property def roi_msg(self): return self.__msg @property def is_alive(self): return self.__alive_counter > 0 @property def has_changed(self): return self.__changed def is_gaze_inside(self, gaze_data): return ( pow(gaze_data.gaze_pixel.x - self.roi_msg.roi.center.x, 2) + pow(gaze_data.gaze_pixel.y - self.roi_msg.roi.center.y, 2) ) <= pow(self.roi_msg.roi.radius, 2) def is_comprehension_expired(self): return ( time.time() - self.__time_last_looked > self.__sa_parameter.comprehension_alive_time and self.roi_msg.classification == SituationElement.Classification.COMPREHENDED ) def update_msg(self, roi_msg): self.__msg.roi = roi_msg.roi self.__msg.type = roi_msg.type self.__changed = True self.__alive_counter = self.SE_ALIVE_COUNTER def update(self, num_gazes_inside): self.__time_last_looked = time.time() self.__num_gazes_inside += num_gazes_inside if self.__num_gazes_inside > self.__sa_parameter.num_gaze_comprehended: self.__msg.classification = SituationElement.Classification.COMPREHENDED elif self.__num_gazes_inside >= self.__sa_parameter.num_gaze_detected: self.__msg.classification = SituationElement.Classification.DETECTED if self.is_comprehension_expired(): self.__num_gazes_inside = self.__sa_parameter.num_gaze_detected self.__msg.classification = SituationElement.Classification.DETECTED if self.__changed: self.__changed = False return self.__alive_counter -= 1 @property def classification_value(self): if self.__msg.classification == self.Classification.COMPREHENDED: return self.ClassificationWeight.COMPREHENDED if self.__msg.classification == self.Classification.DETECTED: return self.ClassificationWeight.DETECTED return self.ClassificationWeight.UNDETECTED @property def type_weight(self): return ( self.TypeWeight.DESIRED if self.__msg.type == ROI.DESIRED else self.TypeWeight.REQUIRED ) def distance_to(self, roi_msg): roi_center =
np.array([roi_msg.roi.center.x, roi_msg.roi.center.y])
numpy.array
# -*- coding: utf-8 -*- """Copy of rnn.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1hw5VX0w03qnA-pD4YmOck-HAmzP9_fO8 # Recurrent Neural Network ## Part 1 - Data Preprocessing ### Importing the libraries """ import numpy as np import matplotlib.pyplot as plt import pandas as pd """### Importing the training set""" dataset_train = pd.read_csv('Google_Stock_Price_Train.csv') training_set = dataset_train.iloc[:, 1:2].values #creates numpy array #only numpy arrays can be used as inputs to keras neural networks """### Feature Scaling""" #check difference between stardarization and normalizaton #in RNN, whenever there is sigmoid function in the output layer of the RNN, #normalization is recommended from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler(feature_range = (0, 1)) #creating object of the MinMaxScaler class # with feature range training_set_scaled = sc.fit_transform(training_set) """### Creating a data structure with 60 timesteps and 1 output""" #creation of time step is important # wrong timestep can leaad to overfiting # the 60 time steps correspond to the past 60 inputs at any particular time step. # hence X_train has 60 previous stock prices and Y_train has the next daay stock price, which is what # we want from the network, hence its the output to be estimated. X_train = [] y_train = [] for i in range(60, 1258): #hence the range starts from 60 and goes to end of the list X_train.append(training_set_scaled[i-60:i, 0]) y_train.append(training_set_scaled[i, 0]) X_train, y_train = np.array(X_train), np.array(y_train) """### Reshaping""" #reshaping so that the array dimensions are compatible with the inputs layer of the RNN X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) # the 1 in the end is the number of indicators i.e. dependent vars # new dimensions are also added to include more dependent variables. """## Part 2 - Building and Training the RNN ### Importing the Keras libraries and packages """ # explore keras documentation on the internet from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout """### Initialising the RNN""" regressor = Sequential() # we are making our RNN to be sequential. check documentations for the terms """### Adding the first LSTM layer and some Dropout regularisation""" regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1))) # return sequences == True, for back propagation, in last layer..it is false # units == neurons # input shape == last two dimensions of X_train regressor.add(Dropout(0.2)) # this is to add dropout regularization i.e. to drop the percent of neruons, for more info check internet """### Adding a second LSTM layer and some Dropout regularisation""" regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2)) """### Adding a third LSTM layer and some Dropout regularisation""" regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2)) """### Adding a fourth LSTM layer and some Dropout regularisation""" regressor.add(LSTM(units = 50)) regressor.add(Dropout(0.2)) """### Adding the output layer""" regressor.add(Dense(units = 1)) """### Compiling the RNN""" regressor.compile(optimizer = 'adam', loss = 'mean_squared_error') """### Fitting the RNN to the Training set""" regressor.fit(X_train, y_train, epochs = 100, batch_size = 32) """## Part 3 - Making the predictions and visualising the results ### Getting the real stock price of 2017 """ dataset_test = pd.read_csv('Google_Stock_Price_Test.csv') real_stock_price = dataset_test.iloc[:, 1:2].values """### Getting the predicted stock price of 2017""" dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0) inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values inputs = inputs.reshape(-1,1) inputs = sc.transform(inputs) X_test = [] for i in range(60, 80): X_test.append(inputs[i-60:i, 0]) X_test =
np.array(X_test)
numpy.array
""" Spatial correlation of elevation measurement errors =================================================== Digital elevation models have elevation measurement errors that can vary with terrain or instrument-related variables (see :ref:`sphx_glr_auto_examples_plot_nonstationary_error.py`), but those measurement errors are also often `correlated in space <https://en.wikipedia.org/wiki/Spatial_analysis#Spatial_auto-correlation>`_. While many DEM studies have been using short-range `variogram <https://en.wikipedia.org/wiki/Variogram>`_ to estimate the correlation of elevation measurement errors (e.g., `Howat et al. (2008) <https://doi.org/10.1029/2008GL034496>`_ , `W<NAME> (2015) <https://doi.org/10.3390/rs70810117>`_), recent studies show that variograms of multiple ranges provide larger, more reliable estimates of spatial correlation for DEMs (e.g., `Dehecq et al. (2020) <https://doi.org/10.3389/feart.2020.566802>`_ , `Hugonnet et al. (2021) <https://doi.org/10.1038/s41586-021-03436-z>`_). Quantifying the spatial correlation in elevation measurement errors is essential to integrate measurement errors over an area of interest (e.g, to estimate the error of a mean or sum of samples). Once the spatial correlations are quantified, several methods exist to derive the related measurement error integrated in space (`Rolstad et al. (2009) <https://doi.org/10.3189/002214309789470950>`_ , Hugonnet et al. (in prep)). More details are available in :ref:`spatialstats`. Here, we show an example in which we estimate spatially integrated elevation measurement errors for a DEM difference at Longyearbyen, demonstrated in :ref:`sphx_glr_auto_examples_plot_nuth_kaab.py`. We first quantify the spatial correlations using :func:`xdem.spatialstats.sample_empirical_variogram` based on routines of `scikit-gstat <https://mmaelicke.github.io/scikit-gstat/index.html>`_. We then model the empirical variogram using a sum of variogram models using :func:`xdem.spatialstats.fit_sum_model_variogram`. Finally, we integrate the variogram models for varying surface areas to estimate the spatially integrated elevation measurement errors using :func:`xdem.spatialstats.neff_circ`, and empirically validate the improved robustness of our results using :func:`xdem.spatialstats.patches_method`, an intensive Monte-Carlo sampling approach. """ # sphinx_gallery_thumbnail_number = 6 import matplotlib.pyplot as plt import numpy as np import xdem import geoutils as gu # %% # We start by loading example files including a difference of DEMs at Longyearbyen and the outlines to rasterize # a glacier mask. # Prior to differencing, the DEMs were aligned using :ref:`coregistration_nuthkaab` as shown in # the :ref:`sphx_glr_auto_examples_plot_nuth_kaab.py` example. We later refer to those elevation differences as *dh*. dh = xdem.DEM(xdem.examples.get_path("longyearbyen_ddem")) glacier_outlines = gu.Vector(xdem.examples.get_path("longyearbyen_glacier_outlines")) mask_glacier = glacier_outlines.create_mask(dh) # %% # We remove values on glacier terrain in order to isolate stable terrain, our proxy for elevation measurement errors. dh.data[mask_glacier] = np.nan # %% # We estimate the average per-pixel elevation measurement error on stable terrain, using both the standard deviation # and normalized median absolute deviation. For this example, we do not account for the non-stationarity in elevation # measurement errors quantified in :ref:`sphx_glr_auto_examples_plot_nonstationary_error.py`. print('STD: {:.2f} meters.'.format(np.nanstd(dh.data))) print('NMAD: {:.2f} meters.'.format(xdem.spatialstats.nmad(dh.data))) # %% # The two measures of dispersion are quite similar showing that, on average, there is a small influence of outliers on the # elevation differences. The per-pixel precision is about :math:`\pm` 2.5 meters. # **Does this mean that every pixel has an independent measurement error of** :math:`\pm` **2.5 meters?** # Let's plot the elevation differences to visually check the quality of the data. plt.figure(figsize=(8, 5)) _ = dh.show(ax=plt.gca(), cmap='RdYlBu', vmin=-4, vmax=4, cb_title='Elevation differences (m)') # %% # We clearly see that the residual elevation differences on stable terrain are not random. The positive and negative # differences (blue and red, respectively) appear correlated over large distances. These correlated errors are what # we aim to quantify. # %% # Additionally, we notice that the elevation differences are still polluted by unrealistically large elevation # differences near glaciers, probably because the glacier inventory is more recent than the data, and the outlines are too small. # To remedy this, we filter large elevation differences outside 4 NMAD. dh.data[np.abs(dh.data) > 4 * xdem.spatialstats.nmad(dh.data)] = np.nan # %% # We plot the elevation differences after filtering to check that we successively removed the reminaing glacier signals. plt.figure(figsize=(8, 5)) _ = dh.show(ax=plt.gca(), cmap='RdYlBu', vmin=-4, vmax=4, cb_title='Elevation differences (m)') # %% # To quantify the spatial correlation of the data, we sample an empirical variogram. # The empirical variogram describes the variance between the elevation differences of pairs of pixels depending on their # distance. This distance between pairs of pixels if referred to as spatial lag. # # To perform this procedure effectively, we use improved methods that provide efficient pairwise sampling methods for # large grid data in `scikit-gstat <https://mmaelicke.github.io/scikit-gstat/index.html>`_, which are encapsulated # conveniently by :func:`xdem.spatialstats.sample_empirical_variogram`: df = xdem.spatialstats.sample_empirical_variogram( values=dh.data, gsd=dh.res[0], subsample=50, runs=30, n_variograms=10, random_state=42) # %% # *Note: in this example, we add a* ``random_state`` *argument to yield a reproducible random sampling of pixels within # the grid, and a* ``runs`` *argument to reduce the computing time of* ``sgstat.MetricSpace.RasterEquidistantMetricSpace`` # *which, by default, samples more data for robustness.* # %% # We plot the empirical variogram: xdem.spatialstats.plot_vgm(df) # %% # With this plot, it is hard to conclude anything! Properly visualizing the empirical variogram is one of the most # important step. With grid data, we expect short-range correlations close to the resolution of the grid (~20-200 # meters), but also possibly longer range correlation due to instrument noise or alignment issues (~1-50 km) (Hugonnet et al., in prep). # # To better visualize the variogram, we can either change the axis to log-scale, but this might make it more difficult # to later compare to variogram models. # Another solution is to split the variogram plot into subpanels, each with # its own linear scale. Both are shown below. # %% # **Log scale:** xdem.spatialstats.plot_vgm(df, xscale='log') # %% # **Subpanels with linear scale:** xdem.spatialstats.plot_vgm(df, xscale_range_split=[100, 1000, 10000]) # %% # We identify: # - a short-range (i.e., correlation length) correlation, likely due to effects of resolution. It has a large partial sill (correlated variance), meaning that the elevation measurement errors are strongly correlated until a range of ~100 m. # - a longer range correlation, with a smaller partial sill, meaning the part of the elevation measurement errors remain correlated over a longer distance. # # In order to show the difference between accounting only for the most noticeable, short-range correlation, or adding the # long-range correlation, we fit this empirical variogram with two different models: a single spherical model, and # the sum of two spherical models (two ranges). For this, we use :func:`xdem.spatialstats.fit_sum_model_variogram`, which # is based on `scipy.optimize.curve_fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html>`_: fun, params1 = xdem.spatialstats.fit_sum_model_variogram(['Sph'], empirical_variogram=df) fun2, params2 = xdem.spatialstats.fit_sum_model_variogram(['Sph', 'Sph'], empirical_variogram=df) xdem.spatialstats.plot_vgm(df,list_fit_fun=[fun, fun2],list_fit_fun_label=['Single-range model', 'Double-range model'], xscale_range_split=[100, 1000, 10000]) # %% # The sum of two spherical models fits better, accouting for the small partial sill at longer ranges. Yet this longer # range partial sill (correlated variance) is quite small... # # **So one could ask himself: is it really important to account for this small additional "bump" in the variogram?** # # To answer this, we compute the precision of the DEM integrated over a certain surface area based on spatial integration of the # variogram models using :func:`xdem.spatialstats.neff_circ`, with areas varying from pixel size to grid size. # Numerical and exact integration of variogram is fast, allowing us to estimate errors for a wide range of areas radidly. areas = np.linspace(20**2, 10000**2, 1000) list_stderr_singlerange, list_stderr_doublerange, list_stderr_empirical = ([] for i in range(3)) for area in areas: # Number of effective samples integrated over the area for a single-range model neff_singlerange = xdem.spatialstats.neff_circ(area, [(params1[0], 'Sph', params1[1])]) # For a double-range model neff_doublerange = xdem.spatialstats.neff_circ(area, [(params2[0], 'Sph', params2[1]), (params2[2], 'Sph', params2[3])]) # Convert into a standard error stderr_singlerange = np.nanstd(dh.data)/np.sqrt(neff_singlerange) stderr_doublerange = np.nanstd(dh.data)/np.sqrt(neff_doublerange) list_stderr_singlerange.append(stderr_singlerange) list_stderr_doublerange.append(stderr_doublerange) # %% # We add an empirical error based on intensive Monte-Carlo sampling ("patches" method) to validate our results # (Dehecq et al. (2020), Hugonnet et al., in prep). This method is implemented in :func:`xdem.spatialstats.patches_method`. # Here, we sample fewer areas to avoid for the patches method to run over long processing times, increasing from areas # of 5 pixels to areas of 10000 pixels exponentially. areas_emp = [10 * 400 * 2 ** i for i in range(10)] for area_emp in areas_emp: # First, sample intensively circular patches of a given area, and derive the mean elevation differences df_patches = xdem.spatialstats.patches_method(dh.data.data, gsd=dh.res[0], area=area_emp, n_patches=200, random_state=42) # Second, estimate the dispersion of the means of each patch, i.e. the standard error of the mean stderr_empirical = np.nanstd(df_patches['nanmedian'].values) list_stderr_empirical.append(stderr_empirical) fig, ax = plt.subplots() plt.plot(np.asarray(areas)/1000000, list_stderr_singlerange, label='Single-range spherical model') plt.plot(np.asarray(areas)/1000000, list_stderr_doublerange, label='Double-range spherical model') plt.scatter(np.asarray(areas_emp)/1000000, list_stderr_empirical, label='Empirical estimate', color='black', marker='x') plt.xlabel('Averaging area (km²)') plt.ylabel('Uncertainty in the mean elevation difference (m)') plt.xscale('log') plt.yscale('log') plt.legend() plt.show() # %% # *Note: in this example, we add a* ``random_state`` *argument to the patches method to yield a reproducible random # sampling, and set* ``n_patches`` *to limit computing time.* # %% # Using a single-range variogram highly underestimates the measurement error integrated over an area, by over a factor # of ~100 for large surface areas. Using a double-range variogram brings us closer to the empirical error. # # **But, in this case, the error is still too small. Why?** # The small size of the sampling area against the very large range of the noise implies that we might not verify the # assumption of second-order stationarity (see :ref:`spatialstats`). Longer range correlations might be omitted by # our analysis, due to the limits of the variogram sampling. In other words, a small part of the variance could be # fully correlated over a large part of the grid: a vertical bias. # # As a first guess for this, let's examine the difference between mean and median to gain some insight on the central # tendency of our sample: diff_med_mean = np.nanmean(dh.data.data)-np.nanmedian(dh.data.data) print('Difference mean/median: {:.3f} meters.'.format(diff_med_mean)) # %% # If we now express it as a percentage of the dispersion: print('{:.1f} % of STD.'.format(diff_med_mean/
np.nanstd(dh.data.data)
numpy.nanstd
""" AE.py (author: <NAME> / git: ankonzoid) Autoencoder class (for both simple & convolutional) """ from .AE_base import AEBase import datetime, os, platform, pylab, time import numpy as np import matplotlib.pyplot as plt from keras.layers import Input, Dense from keras.layers import Conv2D, MaxPooling2D, UpSampling2D from keras.models import Model, load_model class AE(AEBase): def __init__(self): # ====================================== # Necessary parameters # ====================================== # For model architecture and weights (used for load/save) self.autoencoder = None self.autoencoder_input_shape = None self.autoencoder_output_shape = None self.encoder = None self.encoder_input_shape = None self.encoder_output_shape = None self.decoder = None self.decoder_input_shape = None self.decoder_output_shape = None # Some sanity parameters to be used in the middle of the run self.is_compiled = None # Encoding/decoding functions self.encode = None self.decode = None self.encoder_decode = None # Report text self.start_time = None self.current_time = None # ====================================== # Parameters for architecture # ====================================== self.model_name = None # ====================================== # Parameters for report # ====================================== super().__init__() ### ==================================================================== ### ### Training ### ### ==================================================================== """ Train the autoencoder """ def train(self, x_train, x_test, n_epochs=50, batch_size=256): self.autoencoder.fit(x_train, x_train, epochs = n_epochs, batch_size = batch_size, shuffle = True, validation_data = (x_test, x_test)) ### ==================================================================== ### ### Encoding / Decoding ### ### ==================================================================== """ Encode the image (using trained encoder) """ def encode(self, img): if not self.is_compiled: raise Exception("Not compiled yet!") x_encoded = self.encoder.predict(img) return x_encoded """ Decode the encoded image (using trained decoder) """ def decode(self, x_encoded): if not self.is_compiled: raise Exception("Not compiled yet!") img_decoded = self.decoder.predict(x_encoded) return img_decoded """ Encode then decode """ def encode_decode(self, img): if not self.is_compiled: raise Exception("Not compiled yet!") x_encoded = self.encoder.predict(img) img_decoded = self.decoder.predict(x_encoded) return img_decoded ### ==================================================================== ### ### Model IO ### ### ==================================================================== """ Load model architecture and weights of autoencoder, encoder, and decoded """ def load_model(self, dictfn): print("Loading models...") # Set model filenames autoencoder_filename = dictfn["autoencoder_filename"] encoder_filename = dictfn["encoder_filename"] decoder_filename = dictfn["decoder_filename"] # Load autoencoder architecture + weights + shapes self.autoencoder = load_model(autoencoder_filename) self.autoencoder_input_shape = self.autoencoder.input_shape # set input shape from loaded model self.autoencoder_output_shape = self.autoencoder.output_shape # set output shape from loaded model # Load encoder architecture + weights + shapes self.encoder = load_model(encoder_filename) self.encoder_input_shape = self.encoder.input_shape # set input shape from loaded model self.encoder_output_shape = self.encoder.output_shape # set output shape from loaded model # Load decoder architecture + weights + shapes self.decoder = load_model(decoder_filename) self.decoder_input_shape = self.decoder.input_shape # set input shape from loaded model self.decoder_output_shape = self.decoder.output_shape # set output shape from loaded model """ Save model architecture and weights to file """ def save_model(self, dictfn): print("Saving models...") self.autoencoder.save(dictfn["autoencoder_filename"]) self.encoder.save(dictfn["encoder_filename"]) self.decoder.save(dictfn["decoder_filename"]) ### ==================================================================== ### ### Architecture compilation ### ### ==================================================================== """ Set name """ def configure(self, model_name=None): self.model_name = model_name """ Set neural network architecture """ def set_arch(self, input_shape=None, output_shape=None): ### ### Create layers based on model name ### if self.model_name == "simpleAE": encode_dim = 128 # only single hidden layer ### Encoding hidden layers ### input_img = Input(shape=input_shape) encoded = Dense(encode_dim, activation='relu')(input_img) ### Decoding hidden layers ### decoded = Dense(output_shape[0], activation='sigmoid')(encoded) elif self.model_name == "convAE": n_hidden_1 = 16 # 1st hidden layer n_hidden_2 = 8 # 2nd hidden layer n_hidden_3 = 8 # 3rd hidden layer convkernel = (3, 3) # convolution (uses filters): n_filters_1 -> n_filters_2 poolkernel = (2, 2) # pooling (down/up samples image): ypix -> ypix/ypoolkernel, xpix -> xpix/ypoolkernel ### Encoding hidden layers ### input_img = Input(shape=input_shape) # input layer (ypixels, xpixels, n_channels) x = Conv2D(n_hidden_1, convkernel, activation='relu', padding='same')(input_img) x = MaxPooling2D(poolkernel, padding='same')(x) x = Conv2D(n_hidden_2, convkernel, activation='relu', padding='same')(x) x = MaxPooling2D(poolkernel, padding='same')(x) x = Conv2D(n_hidden_3, convkernel, activation='relu', padding='same')(x) encoded = MaxPooling2D(poolkernel, padding='same')(x) # encoding layer ### Decoding hidden layers ### x = Conv2D(n_hidden_3, convkernel, activation='relu', padding='same')(encoded) x = UpSampling2D(poolkernel)(x) x = Conv2D(n_hidden_2, convkernel, activation='relu', padding='same')(x) x = UpSampling2D(poolkernel)(x) x = Conv2D(n_hidden_1, convkernel, activation='relu')(x) x = UpSampling2D(poolkernel)(x) decoded = Conv2D(output_shape[2], convkernel, activation='sigmoid', padding='same')(x) # output layer else: raise Exception("Invalid model name given!") ### ### Create models ### ### Create autoencoder model ### autoencoder = Model(input_img, decoded) print("\n\nautoencoder.summary():") print(autoencoder.summary()) # Set encoder input/output dimensions input_autoencoder_shape = autoencoder.layers[0].input_shape[1:] output_autoencoder_shape = autoencoder.layers[-1].output_shape[1:] ### Create encoder model ### encoder = Model(input_img, encoded) # set encoder print("\n\nencoder.summary():") print(encoder.summary()) # Set encoder input/output dimensions input_encoder_shape = encoder.layers[0].input_shape[1:] output_encoder_shape = encoder.layers[-1].output_shape[1:] ### Create decoder model ### decoded_input = Input(shape=output_encoder_shape) if self.model_name == 'simpleAE': decoded_output = autoencoder.layers[-1](decoded_input) # single layer elif self.model_name == 'convAE': decoded_output = autoencoder.layers[-7](decoded_input) # Conv2D decoded_output = autoencoder.layers[-6](decoded_output) # UpSampling2D decoded_output = autoencoder.layers[-5](decoded_output) # Conv2D decoded_output = autoencoder.layers[-4](decoded_output) # UpSampling2D decoded_output = autoencoder.layers[-3](decoded_output) # Conv2D decoded_output = autoencoder.layers[-2](decoded_output) # UpSampling2D decoded_output = autoencoder.layers[-1](decoded_output) # Conv2D else: raise Exception("Invalid model name given!") decoder = Model(decoded_input, decoded_output) print("\n\ndecoder.summary():") print(decoder.summary()) # Set encoder input/output dimensions input_decoder_shape = decoder.layers[0].input_shape[1:] output_decoder_shape = decoder.layers[-1].output_shape[1:] ### ### Assign models ### self.autoencoder = autoencoder # untrained self.encoder = encoder # untrained self.decoder = decoder # untrained # Set model input/output dimensions # We provide two options for getting these numbers: # - via the individual layers # - via the models if 1: self.autoencoder_input_shape = input_autoencoder_shape self.autoencoder_output_shape = output_autoencoder_shape self.encoder_input_shape = input_encoder_shape self.encoder_output_shape = output_encoder_shape self.decoder_input_shape = input_decoder_shape self.decoder_output_shape = output_decoder_shape else: self.autoencoder_input_shape = autoencoder.input_shape self.autoencoder_output_shape = autoencoder.output_shape self.encoder_input_shape = encoder.input_shape self.encoder_output_shape = encoder.output_shape self.decoder_input_shape = decoder.input_shape self.decoder_output_shape = decoder.output_shape """ Compile the model before training """ def compile(self, loss="binary_crossentropy", optimizer="adam"): self.autoencoder.compile(optimizer=optimizer, loss=loss) self.is_compiled = True ### ==================================================================== ### ### Naming conventions ### ### ==================================================================== """ Naming conventions of filenames """ def generate_naming_conventions(self, model_name, output_dir): autoencoder_filename = os.path.join(output_dir, model_name + "_autoencoder.h5") encoder_filename = os.path.join(output_dir, model_name + "_encoder.h5") decoder_filename = os.path.join(output_dir, model_name + "_decoder.h5") plot_filename_pdf = os.path.join(output_dir, model_name + "_plot.pdf") plot_filename_png = os.path.join(output_dir, model_name + "_plot.png") report_filename = os.path.join(output_dir, model_name + "_report.txt") dictfn = { "autoencoder_filename": autoencoder_filename, "encoder_filename": encoder_filename, "decoder_filename": decoder_filename, "plot_filename_pdf": plot_filename_pdf, "plot_filename_png": plot_filename_png, "report_filename": report_filename } return dictfn ### ==================================================================== ### ### Saving plots ### ### ==================================================================== def plot_save_reconstruction(self, x_data_test, img_shape, dictfn, n_plot=10): ypixels = img_shape[0] xpixels = img_shape[1] n_channels = 3 # Extract the subset of test data to reconstruct and plot n = min(len(x_data_test), n_plot) x_data_test_plot = x_data_test[
np.arange(n)
numpy.arange
import logging import math import warnings import numpy as np import pandas as pd import pytest import scipy.stats from dask import array as da, dataframe as dd from distributed.utils_test import ( # noqa: F401 captured_logger, cluster, gen_cluster, loop, ) from sklearn.linear_model import SGDClassifier from dask_ml._compat import DISTRIBUTED_2_5_0 from dask_ml.datasets import make_classification from dask_ml.model_selection import ( HyperbandSearchCV, IncrementalSearchCV, SuccessiveHalvingSearchCV, ) from dask_ml.model_selection._hyperband import _get_hyperband_params from dask_ml.utils import ConstantFunction from dask_ml.wrappers import Incremental pytestmark = pytest.mark.skipif(not DISTRIBUTED_2_5_0, reason="hangs") @pytest.mark.parametrize( "array_type, library, max_iter", [ ("dask.array", "dask-ml", 9), ("numpy", "sklearn", 9), ("numpy", "ConstantFunction", 15), ("numpy", "ConstantFunction", 20), ], ) def test_basic(array_type, library, max_iter): @gen_cluster(client=True) def _test_basic(c, s, a, b): rng = da.random.RandomState(42) n, d = (50, 2) # create observations we know linear models can fit X = rng.normal(size=(n, d), chunks=n // 2) coef_star = rng.uniform(size=d, chunks=d) y = da.sign(X.dot(coef_star)) if array_type == "numpy": X, y = yield c.compute((X, y)) params = { "loss": ["hinge", "log", "modified_huber", "squared_hinge", "perceptron"], "average": [True, False], "learning_rate": ["constant", "invscaling", "optimal"], "eta0": np.logspace(-2, 0, num=1000), } model = SGDClassifier( tol=-np.inf, penalty="elasticnet", random_state=42, eta0=0.1 ) if library == "dask-ml": model = Incremental(model) params = {"estimator__" + k: v for k, v in params.items()} elif library == "ConstantFunction": model = ConstantFunction() params = {"value": np.linspace(0, 1, num=1000)} search = HyperbandSearchCV(model, params, max_iter=max_iter, random_state=42) classes = c.compute(da.unique(y)) yield search.fit(X, y, classes=classes) if library == "dask-ml": X, y = yield c.compute((X, y)) score = search.best_estimator_.score(X, y) assert score == search.score(X, y) assert 0 <= score <= 1 if library == "ConstantFunction": assert score == search.best_score_ else: # These are not equal because IncrementalSearchCV uses a train/test # split and we're testing on the entire train dataset, not only the # validation/test set. assert abs(score - search.best_score_) < 0.1 assert type(search.best_estimator_) == type(model) assert isinstance(search.best_params_, dict) num_fit_models = len(set(search.cv_results_["model_id"])) num_pf_calls = sum( [v[-1]["partial_fit_calls"] for v in search.model_history_.values()] ) models = {9: 17, 15: 17, 20: 17, 27: 49, 30: 49, 81: 143} pf_calls = {9: 69, 15: 101, 20: 144, 27: 357, 30: 379, 81: 1581} assert num_fit_models == models[max_iter] assert num_pf_calls == pf_calls[max_iter] best_idx = search.best_index_ if isinstance(model, ConstantFunction): assert search.cv_results_["test_score"][best_idx] == max( search.cv_results_["test_score"] ) model_ids = {h["model_id"] for h in search.history_} if math.log(max_iter, 3) % 1.0 == 0: # log(max_iter, 3) % 1.0 == 0 is the good case when max_iter is a # power of search.aggressiveness # In this case, assert that more models are tried then the max_iter assert len(model_ids) > max_iter else: # Otherwise, give some padding "almost as many estimators are tried # as max_iter". 3 is a fudge number chosen to be the minimum; when # max_iter=20, len(model_ids) == 17. assert len(model_ids) + 3 >= max_iter assert all("bracket" in id_ for id_ in model_ids) _test_basic() @pytest.mark.parametrize("max_iter,aggressiveness", [(27, 3), (30, 4)]) def test_hyperband_mirrors_paper_and_metadata(max_iter, aggressiveness): @gen_cluster(client=True) def _test_mirrors_paper(c, s, a, b): X, y = make_classification(n_samples=10, n_features=4, chunks=10) model = ConstantFunction() params = {"value":
np.random.rand(max_iter)
numpy.random.rand
import Torture import random import os import torch import numpy as np import torch.optim as optim import torch.nn.functional as F import torch.nn as nn import torchvision import MI from Torture.Models import resnet_3layer as resnet from Torture.Models import resnet as resnet_imagenet from MI import pgd from PIL import Image from Utils.checkpoints import plot_image, save_context from Utils import flags #torch.manual_seed(1234) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False #np.random.seed(12345) EVALUATE_EPOCH = 1 SAVE_EPOCH = 5 HYPERPARAMETERS = None DEFAULT_RESULTS_FOLDER_ARGUMENT = "Not Valid" DEFAULT_RESULTS_FOLDER = "~/results/" FILES_TO_BE_SAVED = ["./", "./Torture", "./Torture/Models", "./Utils", "MI"] KEY_ARGUMENTS = ["batch_size", "model", "data"] config = { "DEFAULT_RESULTS_FOLDER": DEFAULT_RESULTS_FOLDER, "FILES_TO_BE_SAVED": FILES_TO_BE_SAVED, "KEY_ARGUMENTS": KEY_ARGUMENTS } flags.DEFINE_argument("-gpu", "--gpu", default="-1") flags.DEFINE_argument("--results-folder", default=DEFAULT_RESULTS_FOLDER_ARGUMENT) flags.DEFINE_argument("-k", "-key", "--key", default="") flags.DEFINE_argument("-data", "--data", default="cifar10") flags.DEFINE_boolean("-o", "--overwrite-results", default=False) flags.DEFINE_argument("-bs", "-batch_size", "--batch_size", type=int, default=50) flags.DEFINE_argument("-nw", "-num_workers", "--num_workers", type=int, default=4) flags.DEFINE_argument("-oldmodel", "--oldmodel", default=None) flags.DEFINE_argument("-model", "--model", default="resnet34") flags.DEFINE_boolean("-targeted", "--targeted", default=False) flags.DEFINE_argument("-num_sample", type=int, default=30) flags.DEFINE_argument("-nbiter", type=int, default=10) flags.DEFINE_argument("-baseline", default="gaussian") flags.DEFINE_argument("-sigma", type=float, default=0.05) flags.DEFINE_argument("-Xielower", type=int, default=20) flags.DEFINE_argument("-Xieupper", type=int, default=28) flags.DEFINE_argument("-Guolower", type=int, default=20) flags.DEFINE_argument("-Guoupper", type=int, default=28) flags.DEFINE_argument("-Raffprobability", type=float, default=0.2) flags.DEFINE_argument("-Rotation", type=int, default=10) flags.DEFINE_argument("-Kurakin", type=float, default=0.1) flags.DEFINE_argument("-JPEGquality", type=int, default=75) flags.DEFINE_argument("-eps", type=float, default=8.) flags.DEFINE_argument("-numtest", type=int, default=50000) FLAGS = flags.FLAGS num_test = FLAGS.numtest #num of times to sample for MI num_sample = FLAGS.num_sample logger, MODELS_FOLDER, SUMMARIES_FOLDER = save_context(__file__, FLAGS, config) logger.info("build dataloader") def onehot(ind, num_cla): vector = np.zeros([num_cla]) vector[ind] = 1 return vector.astype(np.float32) eps_ = 2. img_size = 32 clip_min, clip_max = -1., 1. if FLAGS.data.lower() in ["cifar10"]: train_trans, test_trans = Torture.Models.transforms.cifar_transform() trainset = torchvision.datasets.CIFAR10( root='/home/LargeData/cifar/', train=False, download=True, transform=train_trans, target_transform=lambda x: onehot(x, 10)) testset = torchvision.datasets.CIFAR10( root='/home/LargeData/cifar/', train=False, download=True, transform=test_trans, target_transform=lambda x: onehot(x, 10)) num_classes = 10 model_set = resnet num_worker = 4 num_s = 10 elif FLAGS.data.lower() in ["cifar100"]: train_trans, test_trans = Torture.Models.transforms.cifar_transform() trainset = torchvision.datasets.CIFAR100( root='/home/LargeData/cifar/', train=False, download=True, transform=train_trans, target_transform=lambda x: onehot(x, 100)) testset = torchvision.datasets.CIFAR100( root='/home/LargeData/cifar/', train=False, download=True, transform=test_trans, target_transform=lambda x: onehot(x, 100)) num_classes = 100 model_set = resnet num_worker = 4 num_s = 100 elif FLAGS.data.lower() in ["imagenet"]: train_trans, test_trans = Torture.Models.transforms.imagenet_transform() trainset = torchvision.datasets.ImageNet( root='/home/LargeData/ImageNet/', split='train', download=True, transform=train_trans, target_transform=lambda x: onehot(x, 1000)) testset = torchvision.datasets.ImageNet( root='/home/LargeData/ImageNet/', split='val', download=True, transform=test_trans, target_transform=lambda x: onehot(x, 1000)) model_set = resnet_imagenet num_classes = 1000 num_worker = 64 num_s = 1000 clip_min, clip_max = -2.118, 2.64 eps_ = 1. img_size = 224 # for resnet-50 dataloader_train = torch.utils.data.DataLoader( trainset, # batch_size=FLAGS.batch_size, batch_size=1, shuffle=True, num_workers=2) dataloader_test = torch.utils.data.DataLoader( testset, # batch_size=FLAGS.batch_size, batch_size=1, shuffle=False, num_workers=2) if FLAGS.model.lower() in model_set.model_dict: CLASSIFIER = model_set.model_dict[FLAGS.model.lower()] else: raise ValueError("unknown model name") classifier = CLASSIFIER(num_classes=num_classes) if FLAGS.data.lower() in ["imagenet"]: classifier = nn.DataParallel(classifier) device = torch.device("cuda:0") classifier = classifier.to(device) logger.info("Load model from" + FLAGS.oldmodel) classifier.load_state_dict(torch.load(FLAGS.oldmodel)) def accu(pred, label): _, predicted = torch.max(pred.data, 1) _, label_ind = torch.max(label.data, 1) result = (predicted == label_ind).type(torch.float) return result.mean().item() pgd_kwargs = { "eps": FLAGS.eps / 255. * (clip_max - clip_min), "eps_iter": eps_ / 255. * (clip_max - clip_min), "nb_iter": FLAGS.nbiter, "norm": np.inf, "clip_min": clip_min, "clip_max": clip_max, "loss_fn": None, } logger.info("Start Attack") classifier.eval() accu_adv, accu_clean = [], [] accu_adv_mixup, accu_clean_mixup = [], [] cle_con_all, cle_con_mixup_all = [], [] adv_con_all, adv_con_mixup_all = [], [] soft_max = nn.Softmax(dim=-1) classifier.load_state_dict(torch.load(FLAGS.oldmodel)) classifier.eval() if FLAGS.targeted is True: pgd_kwargs.update({'targeted': True}) for i, data_batch in enumerate(dataloader_test): # get the inputs; data is a list of [inputs, labels] img_batch_cpu, label_batch_cpu = data_batch # Craft random y_target that not equal to the true labels if FLAGS.targeted is True: label_target = torch.zeros(label_batch_cpu.shape[0], dtype=torch.int64) for j in range(label_batch_cpu.shape[0]): l =
np.random.randint(num_classes)
numpy.random.randint