prompt
stringlengths
15
655k
completion
stringlengths
3
32.4k
api
stringlengths
8
52
from ROS.e_nose_classifier.src.e_nose_classification_publisher import eNoseClassificationPublisher from ROS.e_nose_classifier.src.e_nose_classification_test import eNoseClassificationTestPublisher from ROS.e_nose_classifier.src.e_nose_subscriber import eNoseSubscriber from classification.lstm_model import SmelLSTM from classification.knn import KNN from classification.naive_bayes import GNB from e_nose.measurements import DataType, StandardizationType from e_nose.online_reader import OnlineReader import time import numpy as np import rospy class ClassifierOrganizer: """ This class is responsible for the organization of receiving the pure data from the data gathering machine (dgm) via ROS. Then it is modeled to Measurment objects, similiar to the computation of the sampling files generated by the dgm. It computes the classification either by knn or by a lstm. It shares the predicted classification via ROS to OUI or to our demo view Has to be executed with on a computer connected to a keyboard as it is required to set the start and endpoints of a measurement manualy via a shortcut """ def __init__(self): print('Initialiting ROS node...') rospy.init_node('classifier_organizer', anonymous=True) print('Initialiting Subcomponents...') self.pub = eNoseClassificationPublisher() self.pub_test = eNoseClassificationTestPublisher() self.sub = eNoseSubscriber() failing_channels = [22, 31] working_channels = np.ones(64, bool) working_channels[failing_channels] = False num_working_channels =
np.count_nonzero(working_channels)
numpy.count_nonzero
# Copyright 2019 Systems & Technology Research, LLC # Use of this software is governed by the license.txt file. import numpy as np import scipy from scipy.ndimage import gaussian_filter # from subjectness import rise import skimage import skimage.filters # needed by python3 def create_threshold_masks( saliency_map, threshold_method, percentiles=None, thresholds=None, seed=None, max_noise=1e-9, include_zero_elements=True, blur_sigma=None, ): """ Args: include_zero_elements: extend mask beyond positive saliency elements. """ np.random.seed(seed) if include_zero_elements: nonzero_saliency = 1 else: # to prevent expansion of saliency masks past the # null elements nonzero_saliency = saliency_map != 0 saliency_map_noise = ( saliency_map + nonzero_saliency *
np.random.rand(*saliency_map.shape)
numpy.random.rand
import numpy as np import hetu as ht from hetu import gpu_links as gpu_op def test_array_set(): ctx = ht.gpu(0) shape = (500, 200) # oneslike arr_x = ht.empty(shape, ctx=ctx) gpu_op.array_set(arr_x, 1.) x = arr_x.asnumpy() np.testing.assert_allclose(np.ones(shape), x) # zeroslike gpu_op.array_set(arr_x, 0.) x = arr_x.asnumpy() np.testing.assert_allclose(np.zeros(shape), x) def test_broadcast_to(): ctx = ht.gpu(0) shape = (200, 300) to_shape = (130, 200, 300) x = np.random.uniform(-1, 1, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(to_shape, ctx=ctx) gpu_op.broadcast_to(arr_x, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(np.broadcast_to(x, to_shape), y) def test_reduce_sum_axis_zero(): ctx = ht.gpu(0) shape = (20, 1, 1) temp_shape = list(shape) temp_shape[0] = (temp_shape[0] + 1) // 2 temp_shape = tuple(temp_shape) to_shape = (1, 1) x = np.random.uniform(0, 20, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(to_shape, ctx=ctx) arr_workspace = ht.empty(shape=temp_shape, ctx=ctx) gpu_op.reduce_sum_axis_zero(arr_x, arr_y, arr_workspace) y = arr_y.asnumpy() y_ = np.sum(x, axis=0) for index, _ in np.ndenumerate(y): v = y[index] v_ = y_[index] if abs((v - v_) / v_) > 1e-4: print(index, v, v_) np.testing.assert_allclose(np.sum(x, axis=0), y, rtol=1e-5) def test_matrix_elementwise_add(): ctx = ht.gpu(0) shape = (500, 200) x = np.random.uniform(0, 10, size=shape).astype(np.float32) y = np.random.uniform(0, 10, size=shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.array(y, ctx=ctx) arr_z = ht.empty(shape, ctx=ctx) gpu_op.matrix_elementwise_add(arr_x, arr_y, arr_z) z = arr_z.asnumpy() np.testing.assert_allclose(x + y, z, rtol=1e-5) def test_matrix_elementwise_add_by_const(): shape = (2000, 3000) ctx = ht.gpu(0) x = np.random.uniform(0, 10, size=shape).astype(np.float32) val = np.random.uniform(-5, 5) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) gpu_op.matrix_elementwise_add_by_const(arr_x, val, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(x + val, y, rtol=1e-5) def test_matrix_elementwise_multiply(): ctx = ht.gpu(0) shape = (500, 200) x = np.random.uniform(0, 10, size=shape).astype(np.float32) y = np.random.uniform(0, 10, size=shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.array(y, ctx=ctx) arr_z = ht.empty(shape, ctx=ctx) gpu_op.matrix_elementwise_multiply(arr_x, arr_y, arr_z) z = arr_z.asnumpy() np.testing.assert_allclose(x * y, z, rtol=1e-5) def test_matrix_elementwise_multiply_by_const(): shape = (2000, 3000) ctx = ht.gpu(0) x = np.random.uniform(0, 10, size=shape).astype(np.float32) val = np.random.uniform(-5, 5) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) gpu_op.matrix_elementwise_multiply_by_const(arr_x, val, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(x * val, y, rtol=1e-5) def test_matrix_elementwise_divide(): ctx = ht.gpu(0) shape = (500, 200) x = np.random.uniform(0, 10, size=shape).astype(np.float32) y = np.random.uniform(1, 10, size=shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.array(y, ctx=ctx) arr_z = ht.empty(shape, ctx=ctx) gpu_op.matrix_elementwise_divide(arr_x, arr_y, arr_z) z = arr_z.asnumpy() np.testing.assert_allclose(x / y, z, rtol=1e-5) def test_matrix_elementwise_divide_const(): shape = (2000, 3000) ctx = ht.gpu(0) val = np.random.uniform(-5, 5) x = np.random.uniform(1, 10, size=shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) gpu_op.matrix_elementwise_divide_const(val, arr_x, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(val / x, y, rtol=1e-5) def test_matrix_opposite(): shape = (2000, 2500) ctx = ht.gpu(0) x = np.random.uniform(-1, 1, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) gpu_op.matrix_opposite(arr_x, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(-x, y) def test_matrix_multiply(): ctx = ht.gpu(0) x = np.random.uniform(0, 10, size=(500, 700)).astype(np.float32) y = np.random.uniform(0, 10, size=(700, 1000)).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.array(y, ctx=ctx) arr_z = ht.empty((500, 1000), ctx=ctx) gpu_op.matrix_multiply(arr_x, False, arr_y, False, arr_z) z = arr_z.asnumpy() np.testing.assert_allclose(np.dot(x, y), z, rtol=1e-5) x = np.random.uniform(0, 10, size=(1000, 500)).astype(np.float32) y = np.random.uniform(0, 10, size=(2000, 500)).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.array(y, ctx=ctx) arr_z = ht.empty((1000, 2000), ctx=ctx) gpu_op.matrix_multiply(arr_x, False, arr_y, True, arr_z) z = arr_z.asnumpy() np.testing.assert_allclose(np.dot(x, np.transpose(y)), z, rtol=1e-5) x = np.random.uniform(0, 10, size=(500, 1000)).astype(np.float32) y = np.random.uniform(0, 10, size=(2000, 500)).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.array(y, ctx=ctx) arr_z = ht.empty((1000, 2000), ctx=ctx) gpu_op.matrix_multiply(arr_x, True, arr_y, True, arr_z) z = arr_z.asnumpy() np.testing.assert_allclose(np.dot(np.transpose(x), np.transpose(y)), z, rtol=1e-5) def test_matrix_sqrt(): shape = (2000, 2500) ctx = ht.gpu(0) x = np.random.uniform(0, 10, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) gpu_op.matrix_sqrt(arr_x, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(np.sqrt(x), y, rtol=1e-5) def test_matrix_rsqrt(): shape = (2000, 2500) ctx = ht.gpu(0) x = np.random.uniform(0, 10, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) gpu_op.matrix_rsqrt(arr_x, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(1 / np.sqrt(x), y, rtol=1e-5) def test_relu(): shape = (2000, 2500) ctx = ht.gpu(0) x = np.random.uniform(-1, 1, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) gpu_op.relu(arr_x, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(np.maximum(x, 0).astype(np.float32), y) def test_leaky_relu(): shape = (2000, 2500) ctx = ht.gpu(0) x = np.random.uniform(-1, 1, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) alpha = 10 gpu_op.leaky_relu(arr_x, float(alpha), arr_y) y = arr_y.asnumpy() def test_relu_gradient(): shape = (2000, 2500) ctx = ht.gpu(0) x = np.random.uniform(-1, 1, shape).astype(np.float32) grad_x = np.random.uniform(-5, 5, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_grad_x = ht.array(grad_x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) gpu_op.relu_gradient(arr_x, arr_grad_x, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(((x > 0) * grad_x).astype(np.float32), y) def test_leaky_relu_gradient(): shape = (2000, 2500) ctx = ht.gpu(0) x = np.random.uniform(-1, 1, shape).astype(np.float32) grad_x = np.random.uniform(-5, 5, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_grad_x = ht.array(grad_x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) alpha = 10 gpu_op.leaky_relu_gradient(arr_x, arr_grad_x, alpha, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose( np.where(np.greater(x, 0), grad_x, alpha * grad_x).astype(np.float32), y) def test_softmax(): def softmax_func(y): """Numerically stable softmax.""" b = y - np.max(y, axis=1, keepdims=True) expb = np.exp(b) softmax = expb / np.sum(expb, axis=1, keepdims=True) return softmax ctx = ht.gpu(0) shape = (400, 1000) x = np.random.uniform(-5, 5, shape).astype(np.float32) arr_x = ht.array(x, ctx=ctx) arr_y = ht.empty(shape, ctx=ctx) gpu_op.softmax(arr_x, arr_y) y = arr_y.asnumpy() np.testing.assert_allclose(softmax_func(x), y, rtol=1e-5) def test_softmax_cross_entropy(): def softmax_func(y): """Numerically stable softmax.""" b = y - np.max(y, axis=1, keepdims=True) expb = np.exp(b) softmax = expb / np.sum(expb, axis=1, keepdims=True) return softmax ctx = ht.gpu(0) shape = (400, 1000) y = np.random.uniform(-5, 5, shape).astype(np.float32) y_ = np.random.uniform(-5, 5, shape).astype(np.float32) arr_y = ht.array(y, ctx=ctx) arr_y_ = ht.array(y_, ctx=ctx) arr_out = ht.empty((400,), ctx=ctx) gpu_op.softmax_cross_entropy(arr_y, arr_y_, arr_out) out = arr_out.asnumpy() # numpy calculation cross_entropy = -np.sum(y_ * np.log(softmax_func(y)), axis=1) np.testing.assert_allclose(cross_entropy, out, rtol=1e-4) # test cudnn gpu_op.CuDNN_softmax_cross_entropy(arr_y, arr_y_, arr_out) out = arr_out.asnumpy() np.testing.assert_allclose(cross_entropy, out, rtol=1e-4) def test_softmax_cross_entropy_gradient(): def softmax_func(y): """Numerically stable softmax.""" b = y - np.max(y, axis=1, keepdims=True) expb = np.exp(b) softmax = expb / np.sum(expb, axis=1, keepdims=True) return softmax ctx = ht.gpu(0) shape = (400, 1000) y = np.random.uniform(-5, 5, shape).astype(np.float32) y_ = np.random.uniform(-5, 5, shape).astype(np.float32) grad = np.random.uniform(-5, 5, (400,)).astype(np.float32) arr_y = ht.array(y, ctx=ctx) arr_y_ = ht.array(y_, ctx=ctx) arr_grad = ht.array(grad, ctx=ctx) arr_out = ht.empty(shape, ctx=ctx) gpu_op.softmax_cross_entropy_gradient(arr_y, arr_y_, arr_grad, arr_out) out = arr_out.asnumpy() # numpy calculation np_grad = (softmax_func(y) + -1 * y_) * np.expand_dims(grad, -1) np.testing.assert_allclose(np_grad, out, rtol=1e-4, atol=1e-8) # test cudnn gpu_op.CuDNN_softmax_cross_entropy_gradient( arr_grad, arr_y, arr_y_, arr_out) out = arr_out.asnumpy() np.testing.assert_allclose(np_grad, out, rtol=1e-4, atol=1e-8) def test_conv2d(): ctx = ht.gpu(0) # im2col and np_conv2d are helper functions def im2col(X, filter_H, filter_W, padding, stride): N, C, H, W = X.shape assert (H + 2 * padding - filter_H) % stride == 0 assert (W + 2 * padding - filter_W) % stride == 0 out_H = (H + 2 * padding - filter_H) // stride + 1 out_W = (W + 2 * padding - filter_W) // stride + 1 y_row_size = C * filter_H * filter_W y_col_size = out_H * out_W y_shape = (N, y_row_size, y_col_size) Y = np.empty(y_shape, dtype=X.dtype) for batch_index in range(N): for col_index in range(y_col_size): out_y = col_index // out_W out_x = col_index % out_W in_y = out_y * stride - padding in_x = out_x * stride - padding row_idx = 0 for c in range(0, C): for y in range(in_y, in_y + filter_H): for x in range(in_x, in_x + filter_W): if (x < 0 or x >= W or y < 0 or y >= H): Y[batch_index, row_idx, col_index] = 0 else: Y[batch_index, row_idx, col_index] = X[batch_index, c, y, x] row_idx += 1 return Y def np_conv2d(X, Filter, padding=0, stride=1): """Implement a conv2d as a matrix multiply after im2col.""" filter_outChannel, filter_inChannel, filter_H, filter_W = Filter.shape N, C, H, W = X.shape assert (H + 2 * padding - filter_H) % stride == 0 assert (W + 2 * padding - filter_W) % stride == 0 out_H = (H + 2 * padding - filter_H) // stride + 1 out_W = (W + 2 * padding - filter_W) // stride + 1 im2col_matrix = im2col(X, filter_H, filter_W, padding, stride) filter_matrix = Filter.reshape(filter_outChannel, -1) print("shape", im2col_matrix.shape) print("shape", filter_matrix.shape) print("shape",
np.matmul(filter_matrix, im2col_matrix)
numpy.matmul
import time from abc import ABCMeta import threading import numpy as np from scipy.ndimage.filters import gaussian_filter1d import anton.lights.config as config from anton.lights.audio.audioprocess import AudioProcess import anton.lights.audio.dsp as dsp from anton.lights.audio.pixels import Pixels # Helpers # ======================================================= def memoize(function): """Provides a decorator for memoizing functions""" from functools import wraps memo = {} @wraps(function) def wrapper(*args): if args in memo: return memo[args] else: rv = function(*args) memo[args] = rv return rv return wrapper @memoize def _normalized_linspace(size): return np.linspace(0, 1, size) def interpolate(y, new_length): """Intelligently resizes the array by linearly interpolating the values Parameters ---------- y : np.array Array that should be resized new_length : int The length of the new interpolated array Returns ------- z : np.array New array with length of new_length that contains the interpolated values of y. """ if len(y) == new_length: return y x_old = _normalized_linspace(len(y)) x_new = _normalized_linspace(new_length) z = np.interp(x_new, x_old, y) return z # Visualizer # ======================================================= melbank = dsp.MelBank() class Visualizer(Pixels): fft_window = np.hamming(int(config.MIC_RATE / config.FPS) * config.N_ROLLING_HISTORY) # Number of audio samples to read every time frame samples_per_frame = int(config.MIC_RATE / config.FPS) def __init__(self, packet_sender, mode_byte): Pixels.__init__(self,packet_sender, mode_byte) self._time_prev = time.time() * 1000.0 self._fps = dsp.ExpFilter(val=config.FPS, alpha_decay=0.2, alpha_rise=0.2) self.audio_process = AudioProcess() self.pixel_arr = np.tile(1.0, (3, config.N_PIXELS // 2)) self._prev_spectrum = np.tile(0.01, config.N_PIXELS // 2) self.prev_fps_update = time.time() # Array containing the rolling audio sample window self.audio_roll = np.random.rand(config.N_ROLLING_HISTORY, Visualizer.samples_per_frame) / 1e16 # Static Filtering Configurations self.r_filt = dsp.ExpFilter(np.tile(0.01, config.N_PIXELS // 2), alpha_decay=0.2, alpha_rise=0.99) self.g_filt = dsp.ExpFilter(np.tile(0.01, config.N_PIXELS // 2), alpha_decay=0.05, alpha_rise=0.3) self.b_filt = dsp.ExpFilter(np.tile(0.01, config.N_PIXELS // 2), alpha_decay=0.1, alpha_rise=0.5) self.common_mode = dsp.ExpFilter(np.tile(0.01, config.N_PIXELS // 2), alpha_decay=0.99, alpha_rise=0.01) self.p_filt = dsp.ExpFilter(np.tile(1, (3, config.N_PIXELS // 2)), alpha_decay=0.1, alpha_rise=0.99) self.gain = dsp.ExpFilter(np.tile(0.01, config.N_FFT_BINS), alpha_decay=0.001, alpha_rise=0.99) # Audio Rectification Configurations self.fft_plot_filter = dsp.ExpFilter(np.tile(1e-1, config.N_FFT_BINS), alpha_decay=0.5, alpha_rise=0.99) self.mel_gain = dsp.ExpFilter(np.tile(1e-1, config.N_FFT_BINS), alpha_decay=0.01, alpha_rise=0.99) self.mel_smoothing = dsp.ExpFilter(np.tile(1e-1, config.N_FFT_BINS), alpha_decay=0.5, alpha_rise=0.99) self.volume = dsp.ExpFilter(config.MIN_VOLUME_THRESHOLD, alpha_decay=0.02, alpha_rise=0.02) self.mel = None self.thread = None def start(self,visualization_type): self.set_effect(visualization_type) self.thread = threading.Thread(target=self.run) self.thread.start() def run(self): self.update() self.audio_process.start_stream(self.__audio_update) def stop(self): if self.thread is not None: if self.thread.is_alive(): self.audio_process.kill_stream() self.thread.join() self.audio_process.stop_stream() def __frames_per_second(self): """Return the estimated frames per second Returns the current estimate for frames-per-second (FPS). FPS is estimated by measured the amount of time that has elapsed since this function was previously called. The FPS estimate is low-pass filtered to reduce noise. This function is intended to be called one time for every iteration of the program's main loop. Returns ------- fps : float Estimated frames-per-second. This value is low-pass filtered to reduce noise. """ time_now = time.time() * 1000.0 dt = time_now - self._time_prev self._time_prev = time_now if dt == 0.0: return self._fps.value return self._fps.update(1000.0 / dt) def __scroll_effect(self,audio): """Effect that originates in the center and scrolls outwards""" audio = audio**2.0 self.gain.update(audio) audio /= self.gain.value audio *= 255.0 r = int(np.max(audio[:len(audio) // 3])) g = int(np.max(audio[len(audio) // 3: 2 * len(audio) // 3])) b = int(np.max(audio[2 * len(audio) // 3:])) # Scrolling effect window self.pixel_arr[:, 1:] = self.pixel_arr[:, :-1] self.pixel_arr *= 0.98 self.pixel_arr = gaussian_filter1d(self.pixel_arr, sigma=0.2) # Create new color originating at the center self.pixel_arr[0, 0] = r self.pixel_arr[1, 0] = g self.pixel_arr[2, 0] = b # Update the LED strip return np.concatenate((self.pixel_arr[:, ::-1], self.pixel_arr), axis=1) def __energy_effect(self,audio): """Effect that expands from the center with increasing sound energy""" audio = np.copy(audio) self.gain.update(audio) audio /= self.gain.value # Scale by the width of the LED strip audio *= float((config.N_PIXELS // 2) - 1) # Map color channels according to energy in the different freq bands scale = 0.9 r = int(np.mean(audio[:len(audio) // 3]**scale)) g = int(np.mean(audio[len(audio) // 3: 2 * len(audio) // 3]**scale)) b = int(np.mean(audio[2 * len(audio) // 3:]**scale)) # Assign color to different frequency regions self.pixel_arr[0, :r] = 255.0 self.pixel_arr[0, r:] = 0.0 self.pixel_arr[1, :g] = 255.0 self.pixel_arr[1, g:] = 0.0 self.pixel_arr[2, :b] = 255.0 self.pixel_arr[2, b:] = 0.0 self.p_filt.update(self.pixel_arr) self.pixel_arr = np.round(self.p_filt.value) # Apply substantial blur to smooth the edges self.pixel_arr[0, :] = gaussian_filter1d(self.pixel_arr[0, :], sigma=4.0) self.pixel_arr[1, :] = gaussian_filter1d(self.pixel_arr[1, :], sigma=4.0) self.pixel_arr[2, :] = gaussian_filter1d(self.pixel_arr[2, :], sigma=4.0) # Set the new pixel value return np.concatenate((self.pixel_arr[:, ::-1], self.pixel_arr), axis=1) def __spectrum_effect(self,audio): """Effect that maps the Mel filterbank frequencies onto the LED strip""" audio = np.copy(interpolate(audio, config.N_PIXELS // 2)) self.common_mode.update(audio) diff = audio - self._prev_spectrum self._prev_spectrum = np.copy(audio) # Color channel mappings r = self.r_filt.update(audio - self.common_mode.value) g = np.abs(diff) b = self.b_filt.update(np.copy(audio)) # Mirror the color channels for symmetric output r = np.concatenate((r[::-1], r)) g = np.concatenate((g[::-1], g)) b = np.concatenate((b[::-1], b)) return np.array([r, g,b]) * 255 @classmethod def set_effect(self,effect): if effect == 'scroll': self.visualization_effect = self.__scroll_effect elif effect == 'energy': self.visualization_effect = self.__energy_effect elif effect == 'spectrum': self.visualization_effect = self.__spectrum_effect else: raise ValueError def __audio_update(self,audio_samples): # Normalize samples between 0 and 1 audio = audio_samples / 2.0**15 # Construct a rolling window of audio samples self.audio_roll[:-1] = self.audio_roll[1:] self.audio_roll[-1, :] =
np.copy(audio)
numpy.copy
import tqdm import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() def entropy_loss(x): b = F.softmax(x, dim=1) * F.log_softmax(x, dim=1) b = -1.0 * b.sum() return b def train(i_epoch, filter, optimizer_filter, filter_discriminator, optimizer_filter_discriminator, generator, optimizer_generator, generator_discriminator, optimizer_generator_discriminator, dataloader, opt): """ Runs one training epoch. """ # set train mode filter.train() filter_discriminator.train() generator.train() generator_discriminator.train() # --------------------- # Train Discriminator # --------------------- # for i_batch, batch in tqdm.tqdm(enumerate(dataloader)): # x, s = batch # x = x.float().cuda() # s = s.long().cuda() # optimizer_filter_discriminator.zero_grad() # s_p = filter_discriminator(x.detach()) # d_loss = F.cross_entropy(s_p, s.long()) # d_loss.backward() # optimizer_filter.step() #for _ in range(1): for i_batch, batch in tqdm.tqdm(enumerate(dataloader)): x, s = batch x = x.float().cuda() s = s.long().cuda() batch_size = x.shape[0] # ----------------- # Train Filter # ----------------- optimizer_filter.zero_grad() # sample noise as filter input z = torch.randn(batch_size, opt['latent_dim']).float().cuda() # filter a batch of images x_ = filter(x, z) s_p = filter_discriminator(x_) # loss measures filters's ability to fool the discriminator under constrained distortion ones = torch.ones(s.shape).float().cuda() s_c = ones-s.float() s_c = s_c.flatten().long() if not opt['use_entropy_loss']: f_adversary_loss = F.cross_entropy(s_p, s_c) # force it towards complement else: f_adversary_loss = -entropy_loss(s_p) # maximise entropy f_distortion_loss = F.l1_loss(x_, x) f_loss = f_adversary_loss + opt['lambd'] * torch.pow(torch.relu(f_distortion_loss-opt['eps']), 2) f_loss.backward() optimizer_filter.step() # ------------------------ # Train Generator (Real/Fake) # ------------------------ optimizer_generator.zero_grad() # sample noise as filter input z1 = torch.randn(batch_size, opt['latent_dim']).cuda() # filter a batch of images x_ = filter(x, z1) # sample noise as generator input z2 = torch.randn(batch_size, opt['latent_dim']).cuda() # sample secret s_ = torch.tensor(np.random.choice([0.0, 1.0], batch_size)).long().cuda() # generate a batch of images x__ = generator(x_, z2, s_) # loss measures generator's ability to fool the discriminator s_p = generator_discriminator(x__) g_adversary_loss = F.cross_entropy(s_p, s_) g_distortion_loss = F.l1_loss(x__, x) g_loss = g_adversary_loss + opt['lambd'] * torch.pow(torch.relu(g_distortion_loss-opt['eps']), 2) g_loss.backward() optimizer_generator.step() # --------------------- # Train Discriminator # --------------------- optimizer_filter_discriminator.zero_grad() s_p = filter_discriminator(x_.detach()) d_loss = F.cross_entropy(s_p, s.long()) d_loss.backward() optimizer_filter.step() # -------------------------------- # Train Discriminator (Real/Fake) # -------------------------------- #if i_batch % opt['discriminator_update_interval'] == 0: optimizer_generator_discriminator.zero_grad() s_p = generator_discriminator(x) s_p_ = generator_discriminator(x__.detach()) s_fake = (torch.ones(s_p_.size(0))*2).long().cuda() # create class 2 d_rf_loss_real = F.cross_entropy(s_p, s.long()) d_rf_loss_fake = F.cross_entropy(s_p_, s_fake) d_rf_loss = (d_rf_loss_real + d_rf_loss_fake) / 2 d_rf_loss.backward() optimizer_generator_discriminator.step() print('loss/d_loss', d_loss.item(), i_batch + i_epoch*len(dataloader)) print('loss/f_loss', f_loss.item(), i_batch + i_epoch*len(dataloader)) print('loss/d_rf_loss', d_rf_loss.item(), i_batch + i_epoch*len(dataloader)) print('loss/g_loss', g_loss.item(), i_batch + i_epoch*len(dataloader)) class IllustrativeDataset(torch.utils.data.Dataset): def __init__(self, means, stds, nb_samples_per_class): self.nb_classes = len(means) x = [] s = [] for c in range(self.nb_classes): x.append(np.random.normal(loc=means[c], scale=stds[c], size=(nb_samples_per_class, len(means[c])))) s.append(np.repeat(c, nb_samples_per_class)) self.x = np.concatenate(x) self.s = np.concatenate(s) def __len__(self): return len(self.x) def __getitem__(self, idx): return self.x[idx], self.s[idx] class Filter(nn.Module): def __init__(self): super(Filter, self).__init__() self.filter = nn.Sequential( nn.Linear(2*2, 128), nn.Tanh(), nn.Linear(128, 256), nn.Tanh(), nn.Linear(256, 128), nn.Tanh(), nn.Dropout(0.2), nn.Linear(128, 2), ) def forward(self, x, z): return self.filter(torch.cat((x, z), dim=1)) class Generator(nn.Module): def __init__(self, nb_conditional_classes): super(Generator, self).__init__() self.generator = nn.Sequential( nn.Linear(2*3, 128), nn.Tanh(), nn.Linear(128, 256), nn.Tanh(), nn.Linear(256, 128), nn.Tanh(), nn.Dropout(0.2), nn.Linear(128, 2) ) self.embedding = nn.Embedding(nb_conditional_classes, 2) def forward(self, x, z, s): c = self.embedding(s) return self.generator(torch.cat((x, z, c), dim=1)) class Discriminator(nn.Module): def __init__(self, nb_classes): super(Discriminator, self).__init__() self.fc = nn.Sequential( nn.Linear(2, 128), nn.Tanh(), nn.Linear(128, 256), nn.Tanh(), nn.Dropout(0.2), nn.Linear(256, 128), nn.Tanh(), nn.Dropout(0.2), nn.Linear(128, nb_classes) ) def forward(self, x): return self.fc(x) def evaluate_privacy_and_utility(filter, generator, train_loader, valid_loader): # create adversarys adversary_f = Discriminator(2).cuda() adversary_fg = Discriminator(2).cuda() optimizer_adversary_f = torch.optim.Adam(params=adversary_f.parameters(), lr=1e-3) optimizer_adversary_fg = torch.optim.Adam(params=adversary_fg.parameters(), lr=1e-3) adversary_f.train() adversary_fg.train() for _ in range(5): for i_batch, batch in tqdm.tqdm(enumerate(train_loader)): x, s = batch x = x.float().cuda() s = s.long().cuda() batch_size = x.shape[0] # ---------------------------------- # Train filter adversary # ---------------------------------- optimizer_adversary_f.zero_grad() # sample noise as filter input z1 = torch.randn(batch_size, 2).float().cuda() # filter a batch of images x_ = filter(x, z1) s_f = adversary_f(x_.detach()) f_adversary_loss = F.cross_entropy(s_f, s) f_adversary_loss.backward() optimizer_adversary_f.step() # ---------------------------------- # Train filter + generator adversary # ---------------------------------- optimizer_adversary_fg.zero_grad() # sample noise as filter input z2 = torch.randn(batch_size, 2).cuda() # sample secret s_ = torch.tensor(np.random.choice([0.0, 1.0], batch_size)).long().cuda() # generate a batch of images x__ = generator(x_.detach(), z2, s_) # loss measures generator's ability to fool the discriminator s_fg = adversary_fg(x__.detach()) g_adversary_loss = F.cross_entropy(s_fg, s) g_adversary_loss.backward() optimizer_adversary_fg.step() adversary_f.eval() adversary_fg.eval() total_privacy_f = 0 total_privacy_fg = 0 total_utility_f = 0 total_utility_fg = 0 count = 0 for i_batch, batch in tqdm.tqdm(enumerate(valid_loader)): x, s = batch x = x.float().cuda() s = s.long().cuda() batch_size = x.shape[0] z1 = torch.randn(batch_size, 2).float().cuda() z2 = torch.randn(batch_size, 2).float().cuda() s_ = torch.tensor(np.random.choice([0.0, 1.0], batch_size)).long().cuda() x_ = filter(x, z1) x__ = generator(x_, z2, s_) s_f = adversary_f(x_) s_fg = adversary_fg(x__) total_privacy_f += F.cross_entropy(s_f, s).detach().cpu().item() total_privacy_fg += F.cross_entropy(s_fg, s).detach().cpu().item() total_utility_f += F.l1_loss(x, x_).detach().cpu().item() total_utility_fg += F.l1_loss(x, x__).detach().cpu().item() count+=1 return total_privacy_f/count, total_privacy_fg/count, total_utility_f/count, total_utility_fg/count def main(opt): nb_samples_per_class = 200000 train_dataset = IllustrativeDataset(means=[[-1, 1], [1, -1]], stds=[[0.7, 0.7], [0.7, 0.7]], nb_samples_per_class=nb_samples_per_class) valid_dataset = IllustrativeDataset(means=[[-1, 1], [1, -1]], stds=[[0.7, 0.7], [0.7, 0.7]], nb_samples_per_class=1000) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=128, shuffle=True) filter = Filter().cuda() generator = Generator(nb_conditional_classes=2).cuda() filter_discriminator = Discriminator(2).cuda() generator_discriminator = Discriminator(3).cuda() optimizer_filter = torch.optim.Adam(params=filter.parameters(), lr=1e-3) optimizer_filter_discriminator = torch.optim.Adam(params=filter_discriminator.parameters(), lr=1e-3) optimizer_generator = torch.optim.Adam(params=generator.parameters(), lr=1e-3) optimizer_generator_discriminator = torch.optim.Adam(params=generator_discriminator.parameters(), lr=1e-3) nb_epochs = opt['nb_epochs'] decision_boundaries = np.zeros((nb_epochs, 10000, 2)) x_samples = np.zeros((nb_epochs, 10000, 2)) for i_epoch in range(nb_epochs): train(i_epoch, filter, optimizer_filter, filter_discriminator, optimizer_filter_discriminator, generator, optimizer_generator, generator_discriminator, optimizer_generator_discriminator, train_loader, opt ) # TODO: store decision boundary filter_discriminator.eval() x_sample = torch.FloatTensor(10000, 2).uniform_(-3.0, 3.0).cuda() decision_boundary = F.softmax(filter_discriminator(x_sample), dim=1) print(decision_boundary.shape) print(decision_boundaries.shape) decision_boundaries[i_epoch,:,:] = decision_boundary[:,:].detach().cpu().numpy().copy() x_samples[i_epoch,:,:] = x_sample[:,:].cpu().numpy().copy() filter.eval() generator.eval() filter_discriminator.eval() generator_discriminator.eval() return filter, generator, filter_discriminator, generator_discriminator, train_dataset, decision_boundaries, x_samples def scatterplot(data, error, label, point_labels, ax, color): ax.errorbar([x[0] for x in data], [x[1] for x in data], error, linestyle='-', label=label, color=color) for i, txt in enumerate(point_labels): xy = (data[i][0]-0.02, data[i][1]+0.08) ax.annotate(r'$\epsilon = {}$'.format(txt), xy, fontsize=8) dataset = IllustrativeDataset(means=[[-1, 1], [1, -1]], stds=[[0.7, 0.7], [0.7, 0.7]], nb_samples_per_class=1000) fig = plt.figure(figsize=(10, 10)) sns.scatterplot(dataset.x[:,0], dataset.x[:,1], style=dataset.s) plt.show() opts = [] epss = [0.1, 0.5, 1.0, 1.5, 2.0, 3.0] for use_entropy_loss in [False, True]: for eps in epss: opt = { 'latent_dim' : 2, 'use_entropy_loss' : use_entropy_loss, 'lambd' : 100000, 'eps' : eps, 'nb_epochs' : 5, 'discriminator_update_interval' : 1 } opts.append(opt) nb_runs = 5 entropy_runs = [] likelihood_runs = [] for run in range(nb_runs): print("run: ", run) results = [] for opt in opts: filter, generator, filter_discriminator, generator_discriminator, train_dataset, _, _ = main(opt) valid_dataset = IllustrativeDataset(means=[[-1, 1], [1, -1]], stds=[[0.7, 0.7], [0.7, 0.7]], nb_samples_per_class=128*10) valid_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=128, shuffle=True) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=512, shuffle=True) res = evaluate_privacy_and_utility(filter, generator, train_loader, valid_loader) results.append(res) if opt['use_entropy_loss']: entropy_runs.append(results) else: likelihood_runs.append(results) sns.set_style("whitegrid") x_f = np.zeros(len(epss)) y_f = np.zeros(len(epss)) x_fg = np.zeros(len(epss)) y_fg = np.zeros(len(epss)) x_f = np.zeros((nb_runs, len(epss))) y_f = np.zeros((nb_runs, len(epss))) x_fg = np.zeros((nb_runs, len(epss))) y_fg = np.zeros((nb_runs, len(epss))) for i, results in enumerate(runs): x_f[i,:] = np.array([r[0] for r in results]) y_f[i,:] = np.array([r[2] for r in results]) x_fg[i,:] = np.array([r[1] for r in results]) y_fg[i,:] = np.array([r[3] for r in results]) y_f_std =
np.std(y_f, axis=0)
numpy.std
""" atomtools for geometry """ import os import math import itertools import numpy as np from numpy.linalg import norm import modlog import chemdata BASEDIR = os.path.dirname(os.path.abspath(__file__)) EXTREME_SMALL = 1e-5 logger = modlog.getLogger(__name__) def cos(theta, arc=False): factor = 1 if arc else math.pi/180.0 return math.cos(theta * factor) def sin(theta, arc=False): factor = 1 if arc else math.pi/180.0 return math.sin(theta * factor) def acos(result, arc=False): factor = 1 if arc else 180.0/math.pi return math.acos(result) * factor def asin(result, arc=False): factor = 1 if arc else 180.0/math.pi return math.asin(result) * factor def get_positions(positions): if hasattr(positions, 'positions'): positions = positions.positions return np.array(positions).reshape((-1, 3)) def get_atoms_size(positions): if hasattr(positions, 'positions'): positions = positions.positions assert isinstance(positions, (np.ndarray, list) ), 'Please give Atoms, list or ndarray' positions = np.array(positions).reshape((-1, 3)) size = [0.] * 3 for i in range(3): size[i] = positions[:, i].max() - positions[:, i].min() return tuple(size) def normed(v): v = np.array(v) if norm(v) < EXTREME_SMALL: return v return v/norm(v) def vector_angle(a, b): return acos(np.dot(a, b)/(norm(a)*norm(b))) def get_distance(positions, i, j): positions = get_positions(positions) return norm(positions[i]-positions[j]) def get_angle(positions, i, j, k): positions = get_positions(positions) v1 = positions[i] - positions[j] v2 = positions[k] - positions[j] return acos(normed(v1).dot(normed(v2))) return vector_angle(v1, v2) def get_dihedral(positions, i, j, k, l): positions = get_positions(positions) v1 = normed(positions[i] - positions[j]) v2 = normed(positions[l] - positions[k]) vl = normed(positions[k] - positions[j]) return acos(v1.dot(v2)) * np.sign(v2.dot(np.cross(v1, vl))) def cartesian_to_zmatrix(positions, zmatrix_dict=None, initial_num=0, indices=None): def get_zmat_data(zmatrix_dict, keywords): return zmatrix_dict[keywords] if zmatrix_dict is not None \ and keywords in zmatrix_dict else [] shown_length = get_zmat_data(zmatrix_dict, 'shown_length') shown_angle = get_zmat_data(zmatrix_dict, 'shown_angle') shown_dihedral = get_zmat_data(zmatrix_dict, 'shown_dihedral') same_length = get_zmat_data(zmatrix_dict, 'same_length') same_angle = get_zmat_data(zmatrix_dict, 'same_angle') same_dihedral = get_zmat_data(zmatrix_dict, 'same_dihedral') shown_length.sort() #shown_length = [] #shown_angle = [] #shown_dihedral = [] positions = np.array(positions).reshape((-1, 3)) natoms = len(positions) if indices is None: indices = np.arange(natoms) zmatrix = np.array([[[-1, -1], [-1, -1], [-1, -1]]]*natoms).tolist() same_bond_variables = [''] * len(same_length) variables = {} for ai in range(natoms): if ai == 0: continue elif ai == 1: zmatrix[ai][0] = [0, get_distance(positions, 0, 1)] continue for a0, a1 in shown_length: a0, a1 = indices[a0], indices[a1] logger.debug(f"{a0}, {a1}") if ai == a1: alpha = 'R_'+str(a0+initial_num)+'_'+str(a1+initial_num) write_variable = True for same_length, index in zip(same_length, range(len(same_length))): # print((a0, a1), same_length) if (a0, a1) in same_length: # print("UES") if same_bond_variables[index] == '': same_bond_variables[index] = alpha logger.debug(f"{index}, {same_bond_variables}") else: alpha = same_bond_variables[index] write_variable = False break zmatrix[ai][0] = [a0, alpha] if write_variable: variables[alpha] = [(a0, a1), get_distance(positions, a0, a1)] break a0 = -1 a1 = -1 a2 = -1 a0 = zmatrix[ai][0][0] if a0 == -1: a0 = 0 dist = get_distance(positions, ai, a0) logger.debug(f'dist:, {ai}, {a0}, {dist}') zmatrix[ai][0] = [a0, dist] a1 = zmatrix[ai][1][0] if a1 == -1: for a1 in range(0, ai): if not a1 in [a0]: break if a1 == -1: raise ValueError('a1 is still -1') angle = get_angle(positions, ai, a0, a1) logger.debug(f'angle:, {ai}, {a0}, {a1}, {angle}') zmatrix[ai][1] = [a1, angle] a2 = zmatrix[ai][2][0] if ai >= 3 and a2 == -1: for a2 in range(0, ai): if not a1 in [a0, a1]: break if a2 == -1: raise ValueError('a2 is still -1') dihedral = get_dihedral(positions, ai, a0, a1, a2) logger.debug(f'dihedral:, {dihedral}') zmatrix[ai][2] = [a2, dihedral] if initial_num != 0: for zmat in zmatrix: for zmat_x in zmat: if zmat_x[0] != -1: zmat_x[0] += initial_num logger.debug(f"{zmatrix}, {variables}, {indices}") return zmatrix, variables, indices def cartesian_to_spherical(pos_o, pos_s): pos_o = np.array(pos_o) pos_s = np.array(pos_s) logger.debug(f'cartesian to spherical:, {pos_o}, {pos_s}') v_os = pos_s - pos_o if norm(v_os) < 0.01: return (0, 0, 0) x, y, z = v_os length = np.linalg.norm(v_os) theta = acos(z/length) xy_length = math.sqrt(x*x+y*y) logger.debug(f'xy_length, {theta}, {xy_length}') if xy_length < 0.05: phi_x = 0.0 phi_y = 0.0 else: phi_x = acos(x/xy_length) phi_y = asin(y/xy_length) if y >= 0: phi = phi_x else: phi = -phi_x return (length, theta, phi) def spherical_to_cartesian(pos_o, length, space_angle, space_angle0=(0, 0)): theta, phi = space_angle theta0, phi0 = space_angle0 print(f'sperical to cartesian:, {theta}, {phi}') pos_site = np.array(pos_o) + length * \ np.array([sin(theta+theta0) * cos(phi+phi0), sin(theta+theta0) * sin(phi+phi0), cos(theta+theta0)]) return pos_site def rotate_site_angle(site_angle, theta, phi): for site_angle_i in site_angle: theta_i, phi_i = site_angle_i site_angle_i = [theta_i+theta, phi_i+phi] return site_angle def input_standard_pos_transform(inp_pos, std_pos, t_vals, std_to_inp=True, is_coord=False): t_vals = np.array(t_vals).copy() std_O = np.array(std_pos)[-1].copy() inp_O =
np.array(inp_pos)
numpy.array
import math import numpy as np import os from .utils.mygym import convert_to_gym import gym import opensim import random import pandas as pd import plugins.my_manager_factory import matplotlib.pyplot as plt ## OpenSim interface # The amin purpose of this class is to provide wrap all # the necessery elements of OpenSim in one place # The actual RL environment then only needs to: # - open a model # - actuate # - integrate # - read the high level description of the state # The objective, stop condition, and other gym-related # methods are enclosed in the OsimEnv class class OsimModel(object): # Initialize simulation stepsize = 0.01 start_point = 0 model = None state = None state0 = None starting_speed = None k_path = None # path to CMC tracking states file k_paths_dict = {} states = None states_trajectories_dict = {} walk = True init_traj_ix = None joints = [] bodies = [] brain = None verbose = False istep = 0 state_desc_istep = None prev_state_desc = None state_desc = None integrator_accuracy = None maxforces = [] curforces = [] # Takes a dict where the keys are the speeds of the corresponding paths pointing to motion clips def __init__(self, model_path, k_paths_dict, visualize, integrator_accuracy = 1e-3): # Reduced accuracy for greater speed self.integrator_accuracy = integrator_accuracy self.model = opensim.Model(model_path) self.model.initSystem() self.brain = opensim.PrescribedController() self.k_path = k_paths_dict[list(k_paths_dict.keys())[0]] self.states = pd.read_csv(self.k_path, index_col=False).drop('Unnamed: 0', axis=1) for speed in list(k_paths_dict.keys()): self.states_trajectories_dict[speed] = pd.read_csv(k_paths_dict[speed], index_col=False).drop('Unnamed: 0', axis=1) # Enable the visualizer self.model.setUseVisualizer(visualize) self.muscleSet = self.model.getMuscles() self.forceSet = self.model.getForceSet() self.bodySet = self.model.getBodySet() self.jointSet = self.model.getJointSet() self.markerSet = self.model.getMarkerSet() self.contactGeometrySet = self.model.getContactGeometrySet() self.actuatorSet = self.model.getActuators() if self.verbose: self.list_elements() for j in range(self.actuatorSet.getSize()): func = opensim.Constant(1.0) self.brain.addActuator(self.actuatorSet.get(j)) self.brain.prescribeControlForActuator(j, func) self.curforces.append(1.0) try: self.maxforces.append(self.muscleSet.get(j).getMaxIsometricForce()) except: self.maxforces.append(np.inf) self.noutput = self.actuatorSet.getSize() self.model.addController(self.brain) self.model.initSystem() def list_elements(self): print("JOINTS") for i in range(self.jointSet.getSize()): print(i,self.jointSet.get(i).getName()) print("\nBODIES") for i in range(self.bodySet.getSize()): print(i,self.bodySet.get(i).getName()) print("\nMUSCLES") for i in range(self.muscleSet.getSize()): print(i,self.muscleSet.get(i).getName()) print("\nFORCES") for i in range(self.forceSet.getSize()): print(i,self.forceSet.get(i).getName()) print("\nMARKERS") for i in range(self.markerSet.getSize()): print(i,self.markerSet.get(i).getName()) print("") def actuate(self, action): if np.any(np.isnan(action)): raise ValueError("NaN passed in the activation vector. Values in [0,1] interval are required.") # TODO: Check if actions within [0,1] self.last_action = action brain = opensim.PrescribedController.safeDownCast(self.model.getControllerSet().get(0)) functionSet = brain.get_ControlFunctions() for j in range(functionSet.getSize()): func = opensim.Constant.safeDownCast(functionSet.get(j)) func.setValue( float(action[j]) ) """ Directly modifies activations in the current state. """ def set_activations(self, activations): if np.any(
np.isnan(activations)
numpy.isnan
import pandas as pd import altair as alt import datetime import numpy as np import json import simple_disease_model as disease_model from scipy import stats from config import DATABASE_URL from model import DataSource from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker data_url = "https://docs.google.com/spreadsheets/d/e/2PACX-1vSrr9DRaC2fXzPdmOxLW-egSYtxmEp_RKoYGggt-zOKYXSx4RjPsM4EO19H7OJVX1esTtIoFvlKFWcn/pub?gid=1564028913&single=true&output=csv" def get_incidence(cumulative_cases): onset_dates = [] prev = 0 for date, n_cases in cumulative_cases.iteritems(): new_cases_t = int(n_cases - prev) onset_dates += [date]*new_cases_t prev += new_cases_t onset_dates = pd.Series(onset_dates) min_date = onset_dates.min() days = (onset_dates - min_date).dt.days max_days = np.max(days) incidence = [] result_dates = [] for i in range(max_days + 1): result_dates.append(min_date + datetime.timedelta(days=i)) incidence.append(np.sum(days == i)) incidence = np.array(incidence) return incidence, result_dates def get_and_predict(): print("Get and predict for ebola") engine = create_engine(DATABASE_URL) Session = sessionmaker(bind=engine) session = Session() data = pd.read_csv(data_url, skiprows=[1], parse_dates=["report_date", "publication_date"]) cases_by_time = data.groupby("report_date").sum() cases_by_time.to_sql("cases_by_time", engine, if_exists="replace") latest_update_date = data["publication_date"].max() incidence, result_dates = get_incidence(cases_by_time["total_cases"]) ebola_gamma_params = { "a": 2.41975308641975, "scale": 4.74428571428571 } ebola_gamma = disease_model.discrete_prob(stats.gamma, ebola_gamma_params) force_of_infection = disease_model.force_of_infection_time(incidence, ebola_gamma) mean_r, lower_r, upper_r, post_a, post_b = disease_model.estimated_r( incidence, force_of_infection, ebola_gamma) n_pred = 21 sims = disease_model.simulate_from_end_N(incidence, ebola_gamma, n_pred, lambda x: stats.gamma.mean(a=post_a[-1], scale=post_b[-1]), N=100) cum_sims = np.cumsum(sims, axis=1) results = pd.DataFrame() results["date"] = result_dates results["incidence"] = incidence results["cumulative_incidence"] = np.cumsum(incidence) results["estimated_r"] = [0] * 9 + mean_r results["estimated_r_lower"] = [0] * 9 + lower_r results["estimated_r_upper"] = [0] * 9 + upper_r predictions = pd.DataFrame() predictions["date"] = [result_dates[0] + datetime.timedelta(days=i) for i in range(len(result_dates) + n_pred)] predictions["incidence"] = np.mean(sims, axis=0) predictions["incidence_upper"] =
np.quantile(sims,0.95, axis=0)
numpy.quantile
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 5 12:13:33 2018 @author: <NAME> (<EMAIL> / <EMAIL>) """ # Python dependencies from __future__ import division import pandas as pd import numpy as np import mpmath as mp import matplotlib as mpl import seaborn as sns from scipy.constants import codata from pylab import * from lmfit import minimize, report_fit # from scipy.optimize import leastsq pd.options.mode.chained_assignment = None # Plotting mpl.rc("mathtext", fontset="stixsans", default="regular") mpl.rcParams.update({"axes.labelsize": 22}) mpl.rc("xtick", labelsize=16) mpl.rc("ytick", labelsize=16) mpl.rc("legend", fontsize=14) F = codata.physical_constants["Faraday constant"][0] Rg = codata.physical_constants["molar gas constant"][0] ### Importing PyEIS add-ons from .PyEIS_Data_extraction import * from .PyEIS_Lin_KK import * from .PyEIS_Advanced_tools import * ### Frequency generator ## # def freq_gen(f_start, f_stop, pts_decade=7): """ Frequency Generator with logspaced freqencies Inputs ---------- f_start = frequency start [Hz] f_stop = frequency stop [Hz] pts_decade = Points/decade, default 7 [-] Output ---------- [0] = frequency range [Hz] [1] = Angular frequency range [1/s] """ f_decades = np.log10(f_start) - np.log10(f_stop) f_range = np.logspace( np.log10(f_start), np.log10(f_stop), num=np.around(pts_decade * f_decades).astype(int), endpoint=True, ) w_range = 2 * np.pi * f_range return f_range, w_range ### Simulation Element Functions ## # def elem_L(w, L): """ Simulation Function: -L- Returns the impedance of an inductor <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] L = Inductance [ohm * s] """ return 1j * w * L def elem_C(w, C): """ Simulation Function: -C- Inputs ---------- w = Angular frequency [1/s] C = Capacitance [F] """ return 1 / (C * (w * 1j)) def elem_Q(w, Q, n): """ Simulation Function: -Q- Inputs ---------- w = Angular frequency [1/s] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] """ return 1 / (Q * (w * 1j) ** n) ### Simulation Curciuts Functions ## # def cir_RsC(w, Rs, C): """ Simulation Function: -Rs-C- Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] C = Capacitance [F] """ return Rs + 1 / (C * (w * 1j)) def cir_RsQ(w, Rs, Q, n): """ Simulation Function: -Rs-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] """ return Rs + 1 / (Q * (w * 1j) ** n) def cir_RQ(w, R="none", Q="none", n="none", fs="none"): """ Simulation Function: -RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RQ_fit() <NAME> (<EMAIL> / <EMAIL>) Inputs ---------- w = Angular frequency [1/s] R = Resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] fs = Summit frequency of RQ circuit [Hz] """ if R == "none": R = 1 / (Q * (2 * np.pi * fs) ** n) elif Q == "none": Q = 1 / (R * (2 * np.pi * fs) ** n) elif n == "none": n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) return R / (1 + R * Q * (w * 1j) ** n) def cir_RsRQ(w, Rs="none", R="none", Q="none", n="none", fs="none"): """ Simulation Function: -Rs-RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RQ_fit() <NAME> (<EMAIL> / <EMAIL>) Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] R = Resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] fs = Summit frequency of RQ circuit [Hz] """ if R == "none": R = 1 / (Q * (2 * np.pi * fs) ** n) elif Q == "none": Q = 1 / (R * (2 * np.pi * fs) ** n) elif n == "none": n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) return Rs + (R / (1 + R * Q * (w * 1j) ** n)) def cir_RC(w, C="none", R="none", fs="none"): """ Simulation Function: -RC- Returns the impedance of an RC circuit, using RQ definations where n=1. see cir_RQ() for details <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] R = Resistance [Ohm] C = Capacitance [F] fs = Summit frequency of RC circuit [Hz] """ return cir_RQ(w, R=R, Q=C, n=1, fs=fs) def cir_RsRQRQ( w, Rs, R="none", Q="none", n="none", fs="none", R2="none", Q2="none", n2="none", fs2="none", ): """ Simulation Function: -Rs-RQ-RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RQ_fit() <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [Ohm] R = Resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase element exponent [-] fs = Summit frequency of RQ circuit [Hz] R2 = Resistance [Ohm] Q2 = Constant phase element [s^n/ohm] n2 = Constant phase element exponent [-] fs2 = Summit frequency of RQ circuit [Hz] """ if R == "none": R = 1 / (Q * (2 * np.pi * fs) ** n) elif Q == "none": Q = 1 / (R * (2 * np.pi * fs) ** n) elif n == "none": n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if R2 == "none": R2 = 1 / (Q2 * (2 * np.pi * fs2) ** n2) elif Q2 == "none": Q2 = 1 / (R2 * (2 * np.pi * fs2) ** n2) elif n2 == "none": n2 = np.log(Q2 * R2) / np.log(1 / (2 * np.pi * fs2)) return ( Rs + (R / (1 + R * Q * (w * 1j) ** n)) + (R2 / (1 + R2 * Q2 * (w * 1j) ** n2)) ) def cir_RsRQQ(w, Rs, Q, n, R1="none", Q1="none", n1="none", fs1="none"): """ Simulation Function: -Rs-RQ-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] Q1 = Constant phase element in (RQ) circuit [s^n/ohm] n1 = Constant phase elelment exponent in (RQ) circuit [-] fs1 = Summit frequency of RQ circuit [Hz] Q = Constant phase element of series Q [s^n/ohm] n = Constant phase elelment exponent of series Q [-] """ return Rs + cir_RQ(w, R=R1, Q=Q1, n=n1, fs=fs1) + elem_Q(w, Q, n) def cir_RsRQC(w, Rs, C, R1="none", Q1="none", n1="none", fs1="none"): """ Simulation Function: -Rs-RQ-C- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] Q1 = Constant phase element in (RQ) circuit [s^n/ohm] n1 = Constant phase elelment exponent in (RQ) circuit [-] fs1 = summit frequency of RQ circuit [Hz] C = Constant phase element of series Q [s^n/ohm] """ return Rs + cir_RQ(w, R=R1, Q=Q1, n=n1, fs=fs1) + elem_C(w, C=C) def cir_RsRCC(w, Rs, R1, C1, C): """ Simulation Function: -Rs-RC-C- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] C1 = Constant phase element in (RQ) circuit [s^n/ohm] C = Capacitance of series C [s^n/ohm] """ return Rs + cir_RC(w, C=C1, R=R1, fs="none") + elem_C(w, C=C) def cir_RsRCQ(w, Rs, R1, C1, Q, n): """ Simulation Function: -Rs-RC-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] C1 = Constant phase element in (RQ) circuit [s^n/ohm] Q = Constant phase element of series Q [s^n/ohm] n = Constant phase elelment exponent of series Q [-] """ return Rs + cir_RC(w, C=C1, R=R1, fs="none") + elem_Q(w, Q, n) def Randles_coeff( w, n_electron, A, E="none", E0="none", D_red="none", D_ox="none", C_red="none", C_ox="none", Rg=Rg, F=F, T=298.15, ): """ Returns the Randles coefficient sigma [ohm/s^1/2]. Two cases: a) ox and red are both present in solution here both Cred and Dred are defined, b) In the particular case where initially only Ox species are present in the solution with bulk concentration C*_ox, the surface concentrations may be calculated as function of the electrode potential following Nernst equation. Here C_red and D_red == 'none' Ref.: - Lasia, A.L., ISBN: 978-1-4614-8932-0, "Electrochemical Impedance Spectroscopy and its Applications" - <NAME>., ISBN: 0-471-04372-9, <NAME>. (2001) "Electrochemical methods: Fundamentals and applications". New York: Wiley. <NAME> (<EMAIL> // <EMAIL>) Inputs ---------- n_electron = number of e- [-] A = geometrical surface area [cm2] D_ox = Diffusion coefficent of oxidized specie [cm2/s] D_red = Diffusion coefficent of reduced specie [cm2/s] C_ox = Bulk concetration of oxidized specie [mol/cm3] C_red = Bulk concetration of reduced specie [mol/cm3] T = Temperature [K] Rg = Gas constant [J/molK] F = Faradays consntat [C/mol] E = Potential [V] if reduced specie is absent == 'none' E0 = formal potential [V] if reduced specie is absent == 'none' Returns ---------- Randles coefficient [ohm/s^1/2] """ if C_red != "none" and D_red != "none": sigma = ((Rg * T) / ((n_electron ** 2) * A * (F ** 2) * (2 ** (1 / 2)))) * ( (1 / (D_ox ** (1 / 2) * C_ox)) + (1 / (D_red ** (1 / 2) * C_red)) ) elif C_red == "none" and D_red == "none" and E != "none" and E0 != "none": f = F / (Rg * T) x = (n_electron * f * (E - E0)) / 2 func_cosh2 = (np.cosh(2 * x) + 1) / 2 sigma = ( (4 * Rg * T) / ((n_electron ** 2) * A * (F ** 2) * C_ox * ((2 * D_ox) ** (1 / 2))) ) * func_cosh2 else: print("define E and E0") Z_Aw = sigma * (w ** (-0.5)) - 1j * sigma * (w ** (-0.5)) return Z_Aw def cir_Randles( w, n_electron, D_red, D_ox, C_red, C_ox, Rs, Rct, n, E, A, Q="none", fs="none", E0=0, F=F, Rg=Rg, T=298.15, ): """ Simulation Function: Randles -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit with full complity of the warbug constant NOTE: This Randles circuit is only meant for semi-infinate linear diffusion <NAME> (<EMAIL> / <EMAIL>) Inputs ---------- n_electron = number of e- [-] A = geometrical surface area [cm2] D_ox = Diffusion coefficent of oxidized specie [cm2/s] D_red = Diffusion coefficent of reduced specie [cm2/s] C_ox = Concetration of oxidized specie [mol/cm3] C_red = Concetration of reduced specie [mol/cm3] T = Temperature [K] Rg = Gas constant [J/molK] F = Faradays consntat [C/mol] E = Potential [V] if reduced specie is absent == 'none' E0 = Formal potential [V] if reduced specie is absent == 'none' Rs = Series resistance [ohm] Rct = charge-transfer resistance [ohm] Q = Constant phase element used to model the double-layer capacitance [F] n = expononent of the CPE [-] Returns ---------- The real and imaginary impedance of a Randles circuit [ohm] """ Z_Rct = Rct Z_Q = elem_Q(w, Q, n) Z_w = Randles_coeff( w, n_electron=n_electron, E=E, E0=E0, D_red=D_red, D_ox=D_ox, C_red=C_red, C_ox=C_ox, A=A, T=T, Rg=Rg, F=F, ) return Rs + 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) def cir_Randles_simplified(w, Rs, R, n, sigma, Q="none", fs="none"): """ Simulation Function: Randles -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit with a simplified NOTE: This Randles circuit is only meant for semi-infinate linear diffusion <NAME> (<EMAIL> / <EMAIL>) """ if R == "none": R = 1 / (Q * (2 * np.pi * fs) ** n) elif Q == "none": Q = 1 / (R * (2 * np.pi * fs) ** n) elif n == "none": n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) Z_Q = 1 / (Q * (w * 1j) ** n) Z_R = R Z_w = sigma * (w ** (-0.5)) - 1j * sigma * (w ** (-0.5)) return Rs + 1 / (1 / Z_Q + 1 / (Z_R + Z_w)) # Polymer electrolytes def cir_C_RC_C(w, Ce, Cb="none", Rb="none", fsb="none"): """ Simulation Function: -C-(RC)-C- This circuit is often used for modeling blocking electrodes with a polymeric electrolyte, which exhibts a immobile ionic species in bulk that gives a capacitance contribution to the otherwise resistive electrolyte Ref: - <NAME>., and <NAME>. "Polymer Electrolyte Reviews - 1" Elsevier Applied Science Publishers LTD, London, Bruce, P. "Electrical Measurements on Polymer Electrolytes" <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] Ce = Interfacial capacitance [F] Rb = Bulk/series resistance [Ohm] Cb = Bulk capacitance [F] fsb = summit frequency of bulk (RC) circuit [Hz] """ Z_C = elem_C(w, C=Ce) Z_RC = cir_RC(w, C=Cb, R=Rb, fs=fsb) return Z_C + Z_RC def cir_Q_RQ_Q(w, Qe, ne, Qb="none", Rb="none", fsb="none", nb="none"): """ Simulation Function: -Q-(RQ)-Q- Modified cir_C_RC_C() circuits that can be used if electrodes and bulk are not behaving like ideal capacitors <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] Qe = Interfacial capacitance modeled with a CPE [F] ne = Interfacial constant phase element exponent [-] Rb = Bulk/series resistance [Ohm] Qb = Bulk capacitance modeled with a CPE [s^n/ohm] nb = Bulk constant phase element exponent [-] fsb = summit frequency of bulk (RQ) circuit [Hz] """ Z_Q = elem_Q(w, Q=Qe, n=ne) Z_RQ = cir_RQ(w, Q=Qb, R=Rb, fs=fsb, n=nb) return Z_Q + Z_RQ def tanh(x): """ As numpy gives errors when tanh becomes very large, above 10^250, this functions is used for np.tanh """ return (1 - np.exp(-2 * x)) / (1 + np.exp(-2 * x)) def cir_RCRCZD( w, L, D_s, u1, u2, Cb="none", Rb="none", fsb="none", Ce="none", Re="none", fse="none", ): """ Simulation Function: -RC_b-RC_e-Z_D This circuit has been used to study non-blocking electrodes with an ioniocally conducting electrolyte with a mobile and immobile ionic specie in bulk, this is mixed with a ionically conducting salt. This behavior yields in a impedance response, that consists of the interfacial impendaces -(RC_e)-, the ionically conducitng polymer -(RC_e)-, and the diffusional impedance from the dissolved salt. Refs.: - <NAME>. and <NAME>., Electrochimica Acta, 27, 1671-1675, 1982, "Conductivity, Charge Transfer and Transport number - An AC-Investigation of the Polymer Electrolyte LiSCN-Poly(ethyleneoxide)" - <NAME>., and <NAME>. "Polymer Electrolyte Reviews - 1" Elsevier Applied Science Publishers LTD, London Bruce, P. "Electrical Measurements on Polymer Electrolytes" <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] L = Thickness of electrode [cm] D_s = Diffusion coefficient of dissolved salt [cm2/s] u1 = Mobility of the ion reacting at the electrode interface u2 = Mobility of other ion Re = Interfacial resistance [Ohm] Ce = Interfacial capacitance [F] fse = Summit frequency of the interfacial (RC) circuit [Hz] Rb = Bulk/series resistance [Ohm] Cb = Bulk capacitance [F] fsb = Summit frequency of the bulk (RC) circuit [Hz] """ Z_RCb = cir_RC(w, C=Cb, R=Rb, fs=fsb) Z_RCe = cir_RC(w, C=Ce, R=Re, fs=fse) alpha = ((w * 1j * L ** 2) / D_s) ** (1 / 2) Z_D = Rb * (u2 / u1) * (tanh(x=alpha) / alpha) return Z_RCb + Z_RCe + Z_D # Transmission lines def cir_RsTLsQ(w, Rs, L, Ri, Q="none", n="none"): """ Simulation Function: -Rs-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> / <EMAIL>) Inputs ----------- Rs = Series resistance [ohm] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] Q = Interfacial capacitance of non-faradaic interface [F/cm] n = exponent for the interfacial capacitance [-] """ Phi = 1 / (Q * (w * 1j) ** n) X1 = Ri # ohm/cm Lam = (Phi / X1) ** (1 / 2) # np.sqrt(Phi/X1) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLsQ = Lam * X1 * coth_mp return Rs + Z_TLsQ def cir_RsRQTLsQ(w, Rs, R1, fs1, n1, L, Ri, Q, n, Q1="none"): """ Simulation Function: -Rs-RQ-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance(Q) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> / <EMAIL>) Inputs ----------- Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = Exponent for RQ circuit [-] Q1 = Constant phase element of RQ circuit [s^n/ohm] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] Q = Interfacial capacitance of non-faradaic interface [F/cm] n = Exponent for the interfacial capacitance [-] Output ----------- Impdance of Rs-(RQ)1-TLsQ """ Z_RQ = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) Phi = 1 / (Q * (w * 1j) ** n) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append(float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j) Z_TLsQ = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLsQ def cir_RsTLs(w, Rs, L, Ri, R="none", Q="none", n="none", fs="none"): """ Simulation Function: -Rs-TLs- TLs = Simplified Transmission Line, with a faradaic interfacial impedance (RQ) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> / <EMAIL>) Inputs ----------- Rs = Series resistance [ohm] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] R = Interfacial Charge transfer resistance [ohm*cm] fs = Summit frequency of interfacial RQ circuit [Hz] n = Exponent for interfacial RQ circuit [-] Q = Constant phase element of interfacial capacitance [s^n/Ohm] Output ----------- Impedance of Rs-TLs(RQ) """ Phi = cir_RQ(w, R, Q, n, fs) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_TLs def cir_RsRQTLs(w, Rs, L, Ri, R1, n1, fs1, R2, n2, fs2, Q1="none", Q2="none"): """ Simulation Function: -Rs-RQ-TLs- TLs = Simplified Transmission Line, with a faradaic interfacial impedance (RQ) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - B<NAME>. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> / <EMAIL>) Inputs ----------- Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = Exponent for RQ circuit [-] Q1 = Constant phase element of RQ circuit [s^n/(ohm * cm)] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] R2 = Interfacial Charge transfer resistance [ohm*cm] fs2 = Summit frequency of interfacial RQ circuit [Hz] n2 = Exponent for interfacial RQ circuit [-] Q2 = Constant phase element of interfacial capacitance [s^n/Ohm] Output ----------- Impedance of Rs-(RQ)1-TLs(RQ)2 """ Z_RQ = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) Phi = cir_RQ(w=w, R=R2, Q=Q2, n=n2, fs=fs2) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLs ### Support function def sinh(x): """ As numpy gives errors when sinh becomes very large, above 10^250, this functions is used instead of np/mp.sinh() """ return (1 - np.exp(-2 * x)) / (2 * np.exp(-x)) def coth(x): """ As numpy gives errors when coth becomes very large, above 10^250, this functions is used instead of np/mp.coth() """ return (1 + np.exp(-2 * x)) / (1 - np.exp(-2 * x)) ### def cir_RsTLQ(w, L, Rs, Q, n, Rel, Ri): """ Simulation Function: -R-TLQ- (interfacial non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] Q = Constant phase element for the interfacial capacitance [s^n/ohm] n = exponenet for interfacial RQ element [-] Rel = electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTLQ(w, L, Rs, Q, n, Rel, Ri, R1, n1, fs1, Q1="none"): """ Simulation Function: -R-RQ-TLQ- (interfacial non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = exponent for RQ circuit [-] Q1 = constant phase element of RQ circuit [s^n/(ohm * cm)] Q = Constant phase element for the interfacial capacitance [s^n/ohm] n = exponenet for interfacial RQ element [-] Rel = electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ # The impedance of the series resistance Z_Rs = Rs # The (RQ) circuit in series with the transmission line Z_RQ1 = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL(w, L, Rs, R, fs, n, Rel, Ri, Q="none"): """ Simulation Function: -R-TL- (interfacial reacting, i.e. non-blocking) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R = Interfacial charge transfer resistance [ohm * cm] fs = Summit frequency for the interfacial RQ element [Hz] n = Exponenet for interfacial RQ element [-] Q = Constant phase element for the interfacial capacitance [s^n/ohm] Rel = Electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = Thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Phi = cir_RQ(w, R=R, Q=Q, n=n, fs=fs) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL(w, L, Rs, R1, fs1, n1, R2, fs2, n2, Rel, Ri, Q1="none", Q2="none"): """ Simulation Function: -R-RQ-TL- (interfacial reacting, i.e. non-blocking) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = exponent for RQ circuit [-] Q1 = constant phase element of RQ circuit [s^n/(ohm * cm)] R2 = interfacial charge transfer resistance [ohm * cm] fs2 = Summit frequency for the interfacial RQ element [Hz] n2 = exponenet for interfacial RQ element [-] Q2 = Constant phase element for the interfacial capacitance [s^n/ohm] Rel = electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ # The impedance of the series resistance Z_Rs = Rs # The (RQ) circuit in series with the transmission line Z_RQ1 = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) # The Interfacial impedance is given by an -(RQ)- circuit Phi = cir_RQ(w, R=R2, Q=Q2, n=n2, fs=fs2) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL # Transmission lines with solid-state transport def cir_RsTL_1Dsolid(w, L, D, radius, Rs, R, Q, n, R_w, n_w, Rel, Ri): """ Simulation Function: -R-TL(Q(RW))- Transmission line w/ full complexity, which both includes Ri and Rel Warburg element is specific for 1D solid-state diffusion Refs: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - <NAME>. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Illig, J., Physically based Impedance Modelling of Lithium-ion Cells, KIT Scientific Publishing (2014) - Scipioni, et al., ECS Transactions, 69 (18) 71-80 (2015) <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R = particle charge transfer resistance [ohm*cm^2] Q = Summit frequency peak of RQ element in the modified randles element of a particle [Hz] n = exponenet for internal RQ element in the modified randles element of a particle [-] Rel = electronic resistance of electrode [ohm/cm] Ri = ionic resistance of solution in flooded pores of electrode [ohm/cm] R_w = polarization resistance of finite diffusion Warburg element [ohm] n_w = exponent for Warburg element [-] L = thickness of porous electrode [cm] D = solid-state diffusion coefficient [cm^2/s] radius = average particle radius [cm] Output -------------- Impedance of Rs-TL(Q(RW)) """ # The impedance of the series resistance Z_Rs = Rs # The impedance of a 1D Warburg Element time_const = (radius ** 2) / D x = (time_const * w * 1j) ** n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) Z_w = R_w * np.array(warburg_coth_mp) / x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R Z_Q = elem_Q(w, Q=Q, n=n) Z_Randles = 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) # Ohm # The Impedance of the Transmission Line lamb = (Z_Randles / (Rel + Ri)) ** (1 / 2) x = L / lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * lamb) / sinh(x))) + lamb * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL_1Dsolid( w, L, D, radius, Rs, R1, fs1, n1, R2, Q2, n2, R_w, n_w, Rel, Ri, Q1="none" ): """ Simulation Function: -R-RQ-TL(Q(RW))- Transmission line w/ full complexity, which both includes Ri and Rel Warburg element is specific for 1D solid-state diffusion Refs: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" - <NAME>., Physically based Impedance Modelling of Lithium-ion Cells, KIT Scientific Publishing (2014) - Scipioni, et al., ECS Transactions, 69 (18) 71-80 (2015) <NAME> (<EMAIL>) <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R1 = charge transfer resistance of the interfacial RQ element [ohm*cm^2] fs1 = max frequency peak of the interfacial RQ element[Hz] n1 = exponenet for interfacial RQ element R2 = particle charge transfer resistance [ohm*cm^2] Q2 = Summit frequency peak of RQ element in the modified randles element of a particle [Hz] n2 = exponenet for internal RQ element in the modified randles element of a particle [-] Rel = electronic resistance of electrode [ohm/cm] Ri = ionic resistance of solution in flooded pores of electrode [ohm/cm] R_w = polarization resistance of finite diffusion Warburg element [ohm] n_w = exponent for Warburg element [-] L = thickness of porous electrode [cm] D = solid-state diffusion coefficient [cm^2/s] radius = average particle radius [cm] Output ------------------ Impedance of R-RQ-TL(Q(RW)) """ # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Z_RQ = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) # The impedance of a 1D Warburg Element time_const = (radius ** 2) / D x = (time_const * w * 1j) ** n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) Z_w = R_w * np.array(warburg_coth_mp) / x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R2 Z_Q = elem_Q(w, Q=Q2, n=n2) Z_Randles = 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) # Ohm # The Impedance of the Transmission Line lamb = (Z_Randles / (Rel + Ri)) ** (1 / 2) x = L / lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * lamb) / sinh(x))) + lamb * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ + Z_TL ### Fitting Circuit Functions ## # def elem_C_fit(params, w): """ Fit Function: -C- """ C = params["C"] return 1 / (C * (w * 1j)) def elem_Q_fit(params, w): """ Fit Function: -Q- Constant Phase Element for Fitting """ Q = params["Q"] n = params["n"] return 1 / (Q * (w * 1j) ** n) def cir_RsC_fit(params, w): """ Fit Function: -Rs-C- """ Rs = params["Rs"] C = params["C"] return Rs + 1 / (C * (w * 1j)) def cir_RsQ_fit(params, w): """ Fit Function: -Rs-Q- """ Rs = params["Rs"] Q = params["Q"] n = params["n"] return Rs + 1 / (Q * (w * 1j) ** n) def cir_RC_fit(params, w): """ Fit Function: -RC- Returns the impedance of an RC circuit, using RQ definations where n=1 """ if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["C"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("C") == -1: # elif Q == 'none': R = params["R"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["C"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] Q = params["C"] return cir_RQ(w, R=R, Q=C, n=1, fs=fs) def cir_RQ_fit(params, w): """ Fit Function: -RQ- Return the impedance of an RQ circuit: Z(w) = R / (1+ R*Q * (2w)^n) See Explanation of equations under cir_RQ() The params.keys()[10:] finds the names of the user defined parameters that should be interated over if X == -1, if the paramter is not given, it becomes equal to 'none' <NAME> (<EMAIL> / <EMAIL>) """ if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("Q") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] n = params["n"] Q = params["Q"] return R / (1 + R * Q * (w * 1j) ** n) def cir_RsRQ_fit(params, w): """ Fit Function: -Rs-RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RsRQ_fit() <NAME> (<EMAIL> / <EMAIL>) """ if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("Q") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] Q = params["Q"] n = params["n"] Rs = params["Rs"] return Rs + (R / (1 + R * Q * (w * 1j) ** n)) def cir_RsRQRQ_fit(params, w): """ Fit Function: -Rs-RQ-RQ- Return the impedance of an Rs-RQ circuit. See details under cir_RsRQRQ() <NAME> (<EMAIL> / <EMAIL>) """ if str(params.keys())[10:].find("'R'") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("'Q'") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("'n'") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("'fs'") == -1: # elif fs == 'none': R = params["R"] Q = params["Q"] n = params["n"] if str(params.keys())[10:].find("'R2'") == -1: # if R == 'none': Q2 = params["Q2"] n2 = params["n2"] fs2 = params["fs2"] R2 = 1 / (Q2 * (2 * np.pi * fs2) ** n2) if str(params.keys())[10:].find("'Q2'") == -1: # elif Q == 'none': R2 = params["R2"] n2 = params["n2"] fs2 = params["fs2"] Q2 = 1 / (R2 * (2 * np.pi * fs2) ** n2) if str(params.keys())[10:].find("'n2'") == -1: # elif n == 'none': R2 = params["R2"] Q2 = params["Q2"] fs2 = params["fs2"] n2 = np.log(Q2 * R2) / np.log(1 / (2 * np.pi * fs2)) if str(params.keys())[10:].find("'fs2'") == -1: # elif fs == 'none': R2 = params["R2"] Q2 = params["Q2"] n2 = params["n2"] Rs = params["Rs"] return ( Rs + (R / (1 + R * Q * (w * 1j) ** n)) + (R2 / (1 + R2 * Q2 * (w * 1j) ** n2)) ) def cir_Randles_simplified_Fit(params, w): """ Fit Function: Randles simplified -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit. See more under cir_Randles_simplified() NOTE: This Randles circuit is only meant for semi-infinate linear diffusion <NAME> (<EMAIL> || <EMAIL>) """ if str(params.keys())[10:].find("'R'") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("'Q'") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("'n'") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("'fs'") == -1: # elif fs == 'none': R = params["R"] Q = params["Q"] n = params["n"] Rs = params["Rs"] sigma = params["sigma"] Z_Q = 1 / (Q * (w * 1j) ** n) Z_R = R Z_w = sigma * (w ** (-0.5)) - 1j * sigma * (w ** (-0.5)) return Rs + 1 / (1 / Z_Q + 1 / (Z_R + Z_w)) def cir_RsRQQ_fit(params, w): """ Fit Function: -Rs-RQ-Q- See cir_RsRQQ() for details """ Rs = params["Rs"] Q = params["Q"] n = params["n"] Z_Q = 1 / (Q * (w * 1j) ** n) if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) return Rs + Z_RQ + Z_Q def cir_RsRQC_fit(params, w): """ Fit Function: -Rs-RQ-C- See cir_RsRQC() for details """ Rs = params["Rs"] C = params["C"] Z_C = 1 / (C * (w * 1j)) if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) return Rs + Z_RQ + Z_C def cir_RsRCC_fit(params, w): """ Fit Function: -Rs-RC-C- See cir_RsRCC() for details """ Rs = params["Rs"] R1 = params["R1"] C1 = params["C1"] C = params["C"] return Rs + cir_RC(w, C=C1, R=R1, fs="none") + elem_C(w, C=C) def cir_RsRCQ_fit(params, w): """ Fit Function: -Rs-RC-Q- See cir_RsRCQ() for details """ Rs = params["Rs"] R1 = params["R1"] C1 = params["C1"] Q = params["Q"] n = params["n"] return Rs + cir_RC(w, C=C1, R=R1, fs="none") + elem_Q(w, Q, n) # Polymer electrolytes def cir_C_RC_C_fit(params, w): """ Fit Function: -C-(RC)-C- See cir_C_RC_C() for details <NAME> (<EMAIL> || <EMAIL>) """ # Interfacial impedance Ce = params["Ce"] Z_C = 1 / (Ce * (w * 1j)) # Bulk impendance if str(params.keys())[10:].find("Rb") == -1: # if R == 'none': Cb = params["Cb"] fsb = params["fsb"] Rb = 1 / (Cb * (2 * np.pi * fsb)) if str(params.keys())[10:].find("Cb") == -1: # elif Q == 'none': Rb = params["Rb"] fsb = params["fsb"] Cb = 1 / (Rb * (2 * np.pi * fsb)) if str(params.keys())[10:].find("fsb") == -1: # elif fs == 'none': Rb = params["Rb"] Cb = params["Cb"] Z_RC = Rb / (1 + Rb * Cb * (w * 1j)) return Z_C + Z_RC def cir_Q_RQ_Q_Fit(params, w): """ Fit Function: -Q-(RQ)-Q- See cir_Q_RQ_Q() for details <NAME> (<EMAIL> || <EMAIL>) """ # Interfacial impedance Qe = params["Qe"] ne = params["ne"] Z_Q = 1 / (Qe * (w * 1j) ** ne) # Bulk impedance if str(params.keys())[10:].find("Rb") == -1: # if R == 'none': Qb = params["Qb"] nb = params["nb"] fsb = params["fsb"] Rb = 1 / (Qb * (2 * np.pi * fsb) ** nb) if str(params.keys())[10:].find("Qb") == -1: # elif Q == 'none': Rb = params["Rb"] nb = params["nb"] fsb = params["fsb"] Qb = 1 / (Rb * (2 * np.pi * fsb) ** nb) if str(params.keys())[10:].find("nb") == -1: # elif n == 'none': Rb = params["Rb"] Qb = params["Qb"] fsb = params["fsb"] nb = np.log(Qb * Rb) / np.log(1 / (2 * np.pi * fsb)) if str(params.keys())[10:].find("fsb") == -1: # elif fs == 'none': Rb = params["Rb"] nb = params["nb"] Qb = params["Qb"] Z_RQ = Rb / (1 + Rb * Qb * (w * 1j) ** nb) return Z_Q + Z_RQ def cir_RCRCZD_fit(params, w): """ Fit Function: -RC_b-RC_e-Z_D See cir_RCRCZD() for details <NAME> (<EMAIL> || <EMAIL>) """ # Interfacial impendace if str(params.keys())[10:].find("Re") == -1: # if R == 'none': Ce = params["Ce"] fse = params["fse"] Re = 1 / (Ce * (2 * np.pi * fse)) if str(params.keys())[10:].find("Ce") == -1: # elif Q == 'none': Re = params["Rb"] fse = params["fsb"] Ce = 1 / (Re * (2 * np.pi * fse)) if str(params.keys())[10:].find("fse") == -1: # elif fs == 'none': Re = params["Re"] Ce = params["Ce"] Z_RCe = Re / (1 + Re * Ce * (w * 1j)) # Bulk impendance if str(params.keys())[10:].find("Rb") == -1: # if R == 'none': Cb = params["Cb"] fsb = params["fsb"] Rb = 1 / (Cb * (2 * np.pi * fsb)) if str(params.keys())[10:].find("Cb") == -1: # elif Q == 'none': Rb = params["Rb"] fsb = params["fsb"] Cb = 1 / (Rb * (2 * np.pi * fsb)) if str(params.keys())[10:].find("fsb") == -1: # elif fs == 'none': Rb = params["Rb"] Cb = params["Cb"] Z_RCb = Rb / (1 + Rb * Cb * (w * 1j)) # Mass transport impendance L = params["L"] D_s = params["D_s"] u1 = params["u1"] u2 = params["u2"] alpha = ((w * 1j * L ** 2) / D_s) ** (1 / 2) Z_D = Rb * (u2 / u1) * (tanh(alpha) / alpha) return Z_RCb + Z_RCe + Z_D # Transmission lines def cir_RsTLsQ_fit(params, w): """ Fit Function: -Rs-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) See more under cir_RsTLsQ() <NAME> (<EMAIL> / <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Q = params["Q"] n = params["n"] Phi = 1 / (Q * (w * 1j) ** n) X1 = Ri # ohm/cm Lam = (Phi / X1) ** (1 / 2) # np.sqrt(Phi/X1) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # # Z_TLsQ = Lam * X1 * coth_mp Z_TLsQ = Lam * X1 * coth(x) return Rs + Z_TLsQ def cir_RsRQTLsQ_Fit(params, w): """ Fit Function: -Rs-RQ-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) See more under cir_RsRQTLsQ <NAME> (<EMAIL> / <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Q = params["Q"] n = params["n"] if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) Phi = 1 / (Q * (w * 1j) ** n) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLsQ = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLsQ def cir_RsTLs_Fit(params, w): """ Fit Function: -Rs-RQ-TLs- TLs = Simplified Transmission Line, with a faradaic interfacial impedance (RQ) See mor under cir_RsTLs() <NAME> (<EMAIL> / <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("Q") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] n = params["n"] Q = params["Q"] Phi = R / (1 + R * Q * (w * 1j) ** n) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_TLs def cir_RsRQTLs_Fit(params, w): """ Fit Function: -Rs-RQ-TLs- TLs = Simplified Transmission Line with a faradaic interfacial impedance (RQ) See more under cir_RsRQTLs() <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) if str(params.keys())[10:].find("R2") == -1: # if R == 'none': Q2 = params["Q2"] n2 = params["n2"] fs2 = params["fs2"] R2 = 1 / (Q2 * (2 * np.pi * fs2) ** n2) if str(params.keys())[10:].find("Q2") == -1: # elif Q == 'none': R2 = params["R2"] n2 = params["n2"] fs2 = params["fs2"] Q2 = 1 / (R2 * (2 * np.pi * fs2) ** n1) if str(params.keys())[10:].find("n2") == -1: # elif n == 'none': R2 = params["R2"] Q2 = params["Q2"] fs2 = params["fs2"] n2 = np.log(Q2 * R2) / np.log(1 / (2 * np.pi * fs2)) if str(params.keys())[10:].find("fs2") == -1: # elif fs == 'none': R2 = params["R2"] n2 = params["n2"] Q2 = params["Q2"] Phi = R2 / (1 + R2 * Q2 * (w * 1j) ** n2) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLs def cir_RsTLQ_fit(params, w): """ Fit Function: -R-TLQ- (interface non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Rel = params["Rel"] Q = params["Q"] n = params["n"] # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTLQ_fit(params, w): """ Fit Function: -R-RQ-TLQ- (interface non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Rel = params["Rel"] Q = params["Q"] n = params["n"] # The impedance of the series resistance Z_Rs = Rs # The (RQ) circuit in series with the transmission line if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ1 = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL_Fit(params, w): """ Fit Function: -R-TLQ- (interface reacting, i.e. non-blocking) Transmission line w/ full complexity, which both includes Ri and Rel See cir_RsTL() for details <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Rel = params["Rel"] # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("Q") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] n = params["n"] Q = params["Q"] Phi = R / (1 + R * Q * (w * 1j) ** n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL_fit(params, w): """ Fit Function: -R-RQ-TL- (interface reacting, i.e. non-blocking) Transmission line w/ full complexity including both includes Ri and Rel <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Rel = params["Rel"] # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) elif str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) elif str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) elif str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ1 = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) # # # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R2") == -1: # if R == 'none': Q2 = params["Q2"] n2 = params["n2"] fs2 = params["fs2"] R2 = 1 / (Q2 * (2 * np.pi * fs2) ** n2) elif str(params.keys())[10:].find("Q2") == -1: # elif Q == 'none': R2 = params["R2"] n2 = params["n2"] fs2 = params["fs2"] Q2 = 1 / (R2 * (2 * np.pi * fs2) ** n1) elif str(params.keys())[10:].find("n2") == -1: # elif n == 'none': R2 = params["R2"] Q2 = params["Q2"] fs2 = params["fs2"] n2 = np.log(Q2 * R2) / np.log(1 / (2 * np.pi * fs2)) elif str(params.keys())[10:].find("fs2") == -1: # elif fs == 'none': R2 = params["R2"] n2 = params["n2"] Q2 = params["Q2"] Phi = R2 / (1 + R2 * Q2 * (w * 1j) ** n2) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float((mp.coth(x_mp[i]).imag))*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(((1-mp.exp(-2*x_mp[i]))/(2*mp.exp(-x_mp[i]))).real) + float(((1-mp.exp(-2*x_mp[i]))/(2*mp.exp(-x_mp[i]))).real)*1j) # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float((mp.sinh(x_mp[i]).imag))*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL_1Dsolid_fit(params, w): """ Fit Function: -R-TL(Q(RW))- Transmission line w/ full complexity See cir_RsTL_1Dsolid() for details <NAME> (<EMAIL>) <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] radius = params["radius"] D = params["D"] R = params["R"] Q = params["Q"] n = params["n"] R_w = params["R_w"] n_w = params["n_w"] Rel = params["Rel"] Ri = params["Ri"] # The impedance of the series resistance Z_Rs = Rs # The impedance of a 1D Warburg Element time_const = (radius ** 2) / D x = (time_const * w * 1j) ** n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) Z_w = R_w * np.array(warburg_coth_mp) / x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R Z_Q = elem_Q(w=w, Q=Q, n=n) Z_Randles = 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) # Ohm # The Impedance of the Transmission Line lamb = (Z_Randles / (Rel + Ri)) ** (1 / 2) x = L / lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * lamb) / sinh(x))) + lamb * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL_1Dsolid_fit(params, w): """ Fit Function: -R-RQ-TL(Q(RW))- Transmission line w/ full complexity, which both includes Ri and Rel. The Warburg element is specific for 1D solid-state diffusion See cir_RsRQTL_1Dsolid() for details <NAME> (<EMAIL>) <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] radius = params["radius"] D = params["D"] R2 = params["R2"] Q2 = params["Q2"] n2 = params["n2"] R_w = params["R_w"] n_w = params["n_w"] Rel = params["Rel"] Ri = params["Ri"] # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) elif str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) elif str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) elif str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ1 = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) # The impedance of a 1D Warburg Element time_const = (radius ** 2) / D x = (time_const * w * 1j) ** n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) Z_w = R_w * np.array(warburg_coth_mp) / x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R2 Z_Q = elem_Q(w, Q=Q2, n=n2) Z_Randles = 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) # Ohm # The Impedance of the Transmission Line lamb = (Z_Randles / (Rel + Ri)) ** (1 / 2) x = L / lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * lamb) / sinh(x))) + lamb * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL ### Least-Squares error function def leastsq_errorfunc(params, w, re, im, circuit, weight_func): """ Sum of squares error function for the complex non-linear least-squares fitting procedure (CNLS). The fitting function (lmfit) will use this function to iterate over until the total sum of errors is minimized. During the minimization the fit is weighed, and currently three different weigh options are avaliable: - modulus - unity - proportional Modulus is generially recommended as random errors and a bias can exist in the experimental data. <NAME> (<EMAIL> || <EMAIL>) Inputs ------------ - params: parameters needed for CNLS - re: real impedance - im: Imaginary impedance - circuit: The avaliable circuits are shown below, and this this parameter needs it as a string. - C - Q - R-C - R-Q - RC - RQ - R-RQ - R-RQ-RQ - R-RQ-Q - R-(Q(RW)) - R-(Q(RM)) - R-RC-C - R-RC-Q - R-RQ-Q - R-RQ-C - RC-RC-ZD - R-TLsQ - R-RQ-TLsQ - R-TLs - R-RQ-TLs - R-TLQ - R-RQ-TLQ - R-TL - R-RQ-TL - R-TL1Dsolid (reactive interface with 1D solid-state diffusion) - R-RQ-TL1Dsolid - weight_func Weight function - modulus - unity - proportional """ if circuit == "C": re_fit = elem_C_fit(params, w).real im_fit = -elem_C_fit(params, w).imag elif circuit == "Q": re_fit = elem_Q_fit(params, w).real im_fit = -elem_Q_fit(params, w).imag elif circuit == "R-C": re_fit = cir_RsC_fit(params, w).real im_fit = -cir_RsC_fit(params, w).imag elif circuit == "R-Q": re_fit = cir_RsQ_fit(params, w).real im_fit = -cir_RsQ_fit(params, w).imag elif circuit == "RC": re_fit = cir_RC_fit(params, w).real im_fit = -cir_RC_fit(params, w).imag elif circuit == "RQ": re_fit = cir_RQ_fit(params, w).real im_fit = -cir_RQ_fit(params, w).imag elif circuit == "R-RQ": re_fit = cir_RsRQ_fit(params, w).real im_fit = -cir_RsRQ_fit(params, w).imag elif circuit == "R-RQ-RQ": re_fit = cir_RsRQRQ_fit(params, w).real im_fit = -cir_RsRQRQ_fit(params, w).imag elif circuit == "R-RC-C": re_fit = cir_RsRCC_fit(params, w).real im_fit = -cir_RsRCC_fit(params, w).imag elif circuit == "R-RC-Q": re_fit = cir_RsRCQ_fit(params, w).real im_fit = -cir_RsRCQ_fit(params, w).imag elif circuit == "R-RQ-Q": re_fit = cir_RsRQQ_fit(params, w).real im_fit = -cir_RsRQQ_fit(params, w).imag elif circuit == "R-RQ-C": re_fit = cir_RsRQC_fit(params, w).real im_fit = -cir_RsRQC_fit(params, w).imag elif circuit == "R-(Q(RW))": re_fit = cir_Randles_simplified_Fit(params, w).real im_fit = -cir_Randles_simplified_Fit(params, w).imag elif circuit == "R-(Q(RM))": re_fit = cir_Randles_uelectrode_fit(params, w).real im_fit = -cir_Randles_uelectrode_fit(params, w).imag elif circuit == "C-RC-C": re_fit = cir_C_RC_C_fit(params, w).real im_fit = -cir_C_RC_C_fit(params, w).imag elif circuit == "Q-RQ-Q": re_fit = cir_Q_RQ_Q_Fit(params, w).real im_fit = -cir_Q_RQ_Q_Fit(params, w).imag elif circuit == "RC-RC-ZD": re_fit = cir_RCRCZD_fit(params, w).real im_fit = -cir_RCRCZD_fit(params, w).imag elif circuit == "R-TLsQ": re_fit = cir_RsTLsQ_fit(params, w).real im_fit = -cir_RsTLsQ_fit(params, w).imag elif circuit == "R-RQ-TLsQ": re_fit = cir_RsRQTLsQ_Fit(params, w).real im_fit = -cir_RsRQTLsQ_Fit(params, w).imag elif circuit == "R-TLs": re_fit = cir_RsTLs_Fit(params, w).real im_fit = -cir_RsTLs_Fit(params, w).imag elif circuit == "R-RQ-TLs": re_fit = cir_RsRQTLs_Fit(params, w).real im_fit = -cir_RsRQTLs_Fit(params, w).imag elif circuit == "R-TLQ": re_fit = cir_RsTLQ_fit(params, w).real im_fit = -cir_RsTLQ_fit(params, w).imag elif circuit == "R-RQ-TLQ": re_fit = cir_RsRQTLQ_fit(params, w).real im_fit = -cir_RsRQTLQ_fit(params, w).imag elif circuit == "R-TL": re_fit = cir_RsTL_Fit(params, w).real im_fit = -cir_RsTL_Fit(params, w).imag elif circuit == "R-RQ-TL": re_fit = cir_RsRQTL_fit(params, w).real im_fit = -cir_RsRQTL_fit(params, w).imag elif circuit == "R-TL1Dsolid": re_fit = cir_RsTL_1Dsolid_fit(params, w).real im_fit = -cir_RsTL_1Dsolid_fit(params, w).imag elif circuit == "R-RQ-TL1Dsolid": re_fit = cir_RsRQTL_1Dsolid_fit(params, w).real im_fit = -cir_RsRQTL_1Dsolid_fit(params, w).imag else: print("Circuit is not defined in leastsq_errorfunc()") error = [(re - re_fit) ** 2, (im - im_fit) ** 2] # sum of squares # Different Weighing options, see Lasia if weight_func == "modulus": weight = [ 1 / ((re_fit ** 2 + im_fit ** 2) ** (1 / 2)), 1 / ((re_fit ** 2 + im_fit ** 2) ** (1 / 2)), ] elif weight_func == "proportional": weight = [1 / (re_fit ** 2), 1 / (im_fit ** 2)] elif weight_func == "unity": unity_1s = [] for k in range(len(re)): unity_1s.append( 1 ) # makes an array of [1]'s, so that the weighing is == 1 * sum of squres. weight = [unity_1s, unity_1s] else: print("weight not defined in leastsq_errorfunc()") S = np.array(weight) * error # weighted sum of squares return S ### Fitting Class class EIS_exp: """ This class is used to plot and/or analyze experimental impedance data. The class has three major functions: - EIS_plot() - Lin_KK() - EIS_fit() - EIS_plot() is used to plot experimental data with or without fit - Lin_KK() performs a linear Kramers-Kronig analysis of the experimental data set. - EIS_fit() performs complex non-linear least-squares fitting of the experimental data to an equivalent circuit <NAME> (<EMAIL> || <EMAIL>) Inputs ----------- - path: path of datafile(s) as a string - data: datafile(s) including extension, e.g. ['EIS_data1', 'EIS_data2'] - cycle: Specific cycle numbers can be extracted using the cycle function. Default is 'none', which includes all cycle numbers. Specific cycles can be extracted using this parameter, insert cycle numbers in brackets, e.g. cycle number 1,4, and 6 are wanted. cycle=[1,4,6] - mask: ['high frequency' , 'low frequency'], if only a high- or low-frequency is desired use 'none' for the other, e.g. maks=[10**4,'none'] """ def __init__(self, path, data, cycle="off", mask=["none", "none"]): self.df_raw0 = [] self.cycleno = [] for j, f in enumerate(data, start=0): if f.endswith("mpt"): # file is a .mpt file self.df_raw0.append( extract_mpt(path=path, EIS_name=f) ) # reads all datafiles elif f.endswith("DTA"): # file is a .dta file self.df_raw0.append( extract_dta(path=path, EIS_name=f) ) # reads all datafiles elif f.endswith("z"): # file is a .z file self.df_raw0.append( extract_solar(path=path, EIS_name=f) ) # reads all datafiles elif f.endswith("txt"): self.df_raw0.append(extract_csv(path=path, EIS_name=f)) else: print("Data file(s) could not be identified") self.cycleno.append(self.df_raw0[j].cycle_number) if np.min(self.cycleno[j]) <= np.max(self.cycleno[j - 1]): if j > 0: # corrects cycle_number except for the first data file self.df_raw0[j].update( {"cycle_number": self.cycleno[j] + np.max(self.cycleno[j - 1])} ) # corrects cycle number # currently need to append a cycle_number coloumn to gamry files # adds individual dataframes into one if len(self.df_raw0) == 1: self.df_raw = self.df_raw0[0] elif len(self.df_raw0) == 2: self.df_raw = pd.concat([self.df_raw0[0], self.df_raw0[1]], axis=0) elif len(self.df_raw0) == 3: self.df_raw = pd.concat( [self.df_raw0[0], self.df_raw0[1], self.df_raw0[2]], axis=0 ) elif len(self.df_raw0) == 4: self.df_raw = pd.concat( [self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3]], axis=0, ) elif len(self.df_raw0) == 5: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], ], axis=0, ) elif len(self.df_raw0) == 6: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], ], axis=0, ) elif len(self.df_raw0) == 7: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], ], axis=0, ) elif len(self.df_raw0) == 8: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], ], axis=0, ) elif len(self.df_raw0) == 9: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], ], axis=0, ) elif len(self.df_raw0) == 10: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], ], axis=0, ) elif len(self.df_raw0) == 11: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], ], axis=0, ) elif len(self.df_raw0) == 12: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], self.df_raw0[11], ], axis=0, ) elif len(self.df_raw0) == 13: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], self.df_raw0[11], self.df_raw0[12], ], axis=0, ) elif len(self.df_raw0) == 14: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], self.df_raw0[11], ], self.df_raw0[12], self.df_raw0[13], axis=0, ) elif len(self.df_raw0) == 15: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], self.df_raw0[11], ], self.df_raw0[12], self.df_raw0[13], self.df_raw0[14], axis=0, ) else: print("Too many data files || 15 allowed") self.df_raw = self.df_raw.assign( w=2 * np.pi * self.df_raw.f ) # creats a new coloumn with the angular frequency # Masking data to each cycle self.df_pre = [] self.df_limited = [] self.df_limited2 = [] self.df = [] if mask == ["none", "none"] and cycle == "off": for i in range(len(self.df_raw.cycle_number.unique())): # includes all data self.df.append( self.df_raw[ self.df_raw.cycle_number == self.df_raw.cycle_number.unique()[i] ] ) elif mask == ["none", "none"] and cycle != "off": for i in range(len(cycle)): self.df.append( self.df_raw[self.df_raw.cycle_number == cycle[i]] ) # extracting dataframe for each cycle elif mask[0] != "none" and mask[1] == "none" and cycle == "off": self.df_pre = self.df_raw.mask(self.df_raw.f > mask[0]) self.df_pre.dropna(how="all", inplace=True) for i in range( len(self.df_pre.cycle_number.unique()) ): # Appending data based on cycle number self.df.append( self.df_pre[ self.df_pre.cycle_number == self.df_pre.cycle_number.unique()[i] ] ) elif ( mask[0] != "none" and mask[1] == "none" and cycle != "off" ): # or [i for i, e in enumerate(mask) if e == 'none'] == [0] self.df_limited = self.df_raw.mask(self.df_raw.f > mask[0]) for i in range(len(cycle)): self.df.append( self.df_limited[self.df_limited.cycle_number == cycle[i]] ) elif mask[0] == "none" and mask[1] != "none" and cycle == "off": self.df_pre = self.df_raw.mask(self.df_raw.f < mask[1]) self.df_pre.dropna(how="all", inplace=True) for i in range(len(self.df_raw.cycle_number.unique())): # includes all data self.df.append( self.df_pre[ self.df_pre.cycle_number == self.df_pre.cycle_number.unique()[i] ] ) elif mask[0] == "none" and mask[1] != "none" and cycle != "off": self.df_limited = self.df_raw.mask(self.df_raw.f < mask[1]) for i in range(len(cycle)): self.df.append( self.df_limited[self.df_limited.cycle_number == cycle[i]] ) elif mask[0] != "none" and mask[1] != "none" and cycle != "off": self.df_limited = self.df_raw.mask(self.df_raw.f < mask[1]) self.df_limited2 = self.df_limited.mask(self.df_raw.f > mask[0]) for i in range(len(cycle)): self.df.append( self.df_limited[self.df_limited2.cycle_number == cycle[i]] ) elif mask[0] != "none" and mask[1] != "none" and cycle == "off": self.df_limited = self.df_raw.mask(self.df_raw.f < mask[1]) self.df_limited2 = self.df_limited.mask(self.df_raw.f > mask[0]) for i in range(len(self.df_raw.cycle_number.unique())): self.df.append( self.df_limited[ self.df_limited2.cycle_number == self.df_raw.cycle_number.unique()[i] ] ) else: print("__init__ error (#2)") def Lin_KK( self, num_RC="auto", legend="on", plot="residuals", bode="off", nyq_xlim="none", nyq_ylim="none", weight_func="Boukamp", savefig="none", ): """ Plots the Linear Kramers-Kronig (KK) Validity Test The script is based on Boukamp and Schōnleber et al.'s papers for fitting the resistances of multiple -(RC)- circuits to the data. A data quality analysis can hereby be made on the basis of the relative residuals Ref.: - Schōnleber, M. et al. Electrochimica Acta 131 (2014) 20-27 - Boukamp, B.A. J. Electrochem. Soc., 142, 6, 1885-1894 The function performs the KK analysis and as default the relative residuals in each subplot Note, that weigh_func should be equal to 'Boukamp'. <NAME> (<EMAIL> || <EMAIL>) Optional Inputs ----------------- - num_RC: - 'auto' applies an automatic algorithm developed by Schōnleber, M. et al. Electrochimica Acta 131 (2014) 20-27 that ensures no under- or over-fitting occurs - can be hardwired by inserting any number (RC-elements/decade) - plot: - 'residuals' = plots the relative residuals in subplots correspoding to the cycle numbers picked - 'w_data' = plots the relative residuals with the experimental data, in Nyquist and bode plot if desired, see 'bode =' in description - nyq_xlim/nyq_xlim: Change the x/y-axis limits on nyquist plot, if not equal to 'none' state [min,max] value - legend: - 'on' = displays cycle number - 'potential' = displays average potential which the spectra was measured at - 'off' = off bode = Plots Bode Plot - options: 'on' = re, im vs. log(freq) 'log' = log(re, im) vs. log(freq) 're' = re vs. log(freq) 'log_re' = log(re) vs. log(freq) 'im' = im vs. log(freq) 'log_im' = log(im) vs. log(freq) """ if num_RC == "auto": print("cycle || No. RC-elements || u") self.decade = [] self.Rparam = [] self.t_const = [] self.Lin_KK_Fit = [] self.R_names = [] self.KK_R0 = [] self.KK_R = [] self.number_RC = [] self.number_RC_sort = [] self.KK_u = [] self.KK_Rgreater = [] self.KK_Rminor = [] M = 2 for i in range(len(self.df)): self.decade.append( np.log10(np.max(self.df[i].f)) - np.log10(np.min(self.df[i].f)) ) # determine the number of RC circuits based on the number of decades measured and num_RC self.number_RC.append(M) self.number_RC_sort.append(M) # needed for self.KK_R self.Rparam.append( KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC[i]), )[0] ) # Creates intial guesses for R's self.t_const.append( KK_timeconst(w=self.df[i].w, num_RC=int(self.number_RC[i])) ) # Creates time constants values for self.number_RC -(RC)- circuits self.Lin_KK_Fit.append( minimize( KK_errorfunc, self.Rparam[i], method="leastsq", args=( self.df[i].w.values, self.df[i].re.values, self.df[i].im.values, self.number_RC[i], weight_func, self.t_const[i], ), ) ) # maxfev=99 self.R_names.append( KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC[i]), )[1] ) # creates R names for j in range(len(self.R_names[i])): self.KK_R0.append( self.Lin_KK_Fit[i].params.get(self.R_names[i][j]).value ) self.number_RC_sort.insert(0, 0) # needed for self.KK_R for i in range(len(self.df)): self.KK_R.append( self.KK_R0[ int(np.cumsum(self.number_RC_sort)[i]) : int( np.cumsum(self.number_RC_sort)[i + 1] ) ] ) # assigns resistances from each spectra to their respective df self.KK_Rgreater.append( np.where(np.array(self.KK_R)[i] >= 0, np.array(self.KK_R)[i], 0) ) self.KK_Rminor.append( np.where(np.array(self.KK_R)[i] < 0, np.array(self.KK_R)[i], 0) ) self.KK_u.append( 1 - ( np.abs(np.sum(self.KK_Rminor[i])) / np.abs(np.sum(self.KK_Rgreater[i])) ) ) for i in range(len(self.df)): while self.KK_u[i] <= 0.75 or self.KK_u[i] >= 0.88: self.number_RC_sort0 = [] self.KK_R_lim = [] self.number_RC[i] = self.number_RC[i] + 1 self.number_RC_sort0.append(self.number_RC) self.number_RC_sort = np.insert(self.number_RC_sort0, 0, 0) self.Rparam[i] = KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC[i]), )[ 0 ] # Creates intial guesses for R's self.t_const[i] = KK_timeconst( w=self.df[i].w, num_RC=int(self.number_RC[i]) ) # Creates time constants values for self.number_RC -(RC)- circuits self.Lin_KK_Fit[i] = minimize( KK_errorfunc, self.Rparam[i], method="leastsq", args=( self.df[i].w.values, self.df[i].re.values, self.df[i].im.values, self.number_RC[i], weight_func, self.t_const[i], ), ) # maxfev=99 self.R_names[i] = KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC[i]), )[ 1 ] # creates R names self.KK_R0 = np.delete( np.array(self.KK_R0), np.s_[0 : len(self.KK_R0)] ) self.KK_R0 = [] for q in range(len(self.df)): for j in range(len(self.R_names[q])): self.KK_R0.append( self.Lin_KK_Fit[q].params.get(self.R_names[q][j]).value ) self.KK_R_lim = np.cumsum(self.number_RC_sort) # used for KK_R[i] self.KK_R[i] = self.KK_R0[ self.KK_R_lim[i] : self.KK_R_lim[i + 1] ] # assigns resistances from each spectra to their respective df self.KK_Rgreater[i] = np.where( np.array(self.KK_R[i]) >= 0, np.array(self.KK_R[i]), 0 ) self.KK_Rminor[i] = np.where( np.array(self.KK_R[i]) < 0, np.array(self.KK_R[i]), 0 ) self.KK_u[i] = 1 - ( np.abs(np.sum(self.KK_Rminor[i])) / np.abs(np.sum(self.KK_Rgreater[i])) ) else: print( "[" + str(i + 1) + "]" + " " + str(self.number_RC[i]), " " + str(np.round(self.KK_u[i], 2)), ) elif num_RC != "auto": # hardwired number of RC-elements/decade print("cycle || u") self.decade = [] self.number_RC0 = [] self.number_RC = [] self.Rparam = [] self.t_const = [] self.Lin_KK_Fit = [] self.R_names = [] self.KK_R0 = [] self.KK_R = [] for i in range(len(self.df)): self.decade.append( np.log10(np.max(self.df[i].f)) - np.log10(np.min(self.df[i].f)) ) # determine the number of RC circuits based on the number of decades measured and num_RC self.number_RC0.append(np.round(num_RC * self.decade[i])) self.number_RC.append( np.round(num_RC * self.decade[i]) ) # Creats the the number of -(RC)- circuits self.Rparam.append( KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC0[i]), )[0] ) # Creates intial guesses for R's self.t_const.append( KK_timeconst(w=self.df[i].w, num_RC=int(self.number_RC0[i])) ) # Creates time constants values for self.number_RC -(RC)- circuits self.Lin_KK_Fit.append( minimize( KK_errorfunc, self.Rparam[i], method="leastsq", args=( self.df[i].w.values, self.df[i].re.values, self.df[i].im.values, self.number_RC0[i], weight_func, self.t_const[i], ), ) ) # maxfev=99 self.R_names.append( KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC0[i]), )[1] ) # creates R names for j in range(len(self.R_names[i])): self.KK_R0.append( self.Lin_KK_Fit[i].params.get(self.R_names[i][j]).value ) self.number_RC0.insert(0, 0) # print(report_fit(self.Lin_KK_Fit[i])) # prints fitting report self.KK_circuit_fit = [] self.KK_rr_re = [] self.KK_rr_im = [] self.KK_Rgreater = [] self.KK_Rminor = [] self.KK_u = [] for i in range(len(self.df)): self.KK_R.append( self.KK_R0[ int(np.cumsum(self.number_RC0)[i]) : int( np.cumsum(self.number_RC0)[i + 1] ) ] ) # assigns resistances from each spectra to their respective df self.KK_Rx = np.array(self.KK_R) self.KK_Rgreater.append(np.where(self.KK_Rx[i] >= 0, self.KK_Rx[i], 0)) self.KK_Rminor.append(np.where(self.KK_Rx[i] < 0, self.KK_Rx[i], 0)) self.KK_u.append( 1 - ( np.abs(np.sum(self.KK_Rminor[i])) / np.abs(np.sum(self.KK_Rgreater[i])) ) ) # currently gives incorrect values print( "[" + str(i + 1) + "]" + " " + str(np.round(self.KK_u[i], 2)) ) else: print("num_RC incorrectly defined") self.KK_circuit_fit = [] self.KK_rr_re = [] self.KK_rr_im = [] for i in range(len(self.df)): if int(self.number_RC[i]) == 2: self.KK_circuit_fit.append( KK_RC2( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 3: self.KK_circuit_fit.append( KK_RC3( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 4: self.KK_circuit_fit.append( KK_RC4( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 5: self.KK_circuit_fit.append( KK_RC5( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 6: self.KK_circuit_fit.append( KK_RC6( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 7: self.KK_circuit_fit.append( KK_RC7( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 8: self.KK_circuit_fit.append( KK_RC8( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 9: self.KK_circuit_fit.append( KK_RC9( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 10: self.KK_circuit_fit.append( KK_RC10( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 11: self.KK_circuit_fit.append( KK_RC11( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 12: self.KK_circuit_fit.append( KK_RC12( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 13: self.KK_circuit_fit.append( KK_RC13( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 14: self.KK_circuit_fit.append( KK_RC14( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 15: self.KK_circuit_fit.append( KK_RC15( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 16: self.KK_circuit_fit.append( KK_RC16( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 17: self.KK_circuit_fit.append( KK_RC17( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 18: self.KK_circuit_fit.append( KK_RC18( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 19: self.KK_circuit_fit.append( KK_RC19( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 20: self.KK_circuit_fit.append( KK_RC20( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 21: self.KK_circuit_fit.append( KK_RC21( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 22: self.KK_circuit_fit.append( KK_RC22( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 23: self.KK_circuit_fit.append( KK_RC23( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 24: self.KK_circuit_fit.append( KK_RC24( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 25: self.KK_circuit_fit.append( KK_RC25( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 26: self.KK_circuit_fit.append( KK_RC26( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 27: self.KK_circuit_fit.append( KK_RC27( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 28: self.KK_circuit_fit.append( KK_RC28( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 29: self.KK_circuit_fit.append( KK_RC29( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 30: self.KK_circuit_fit.append( KK_RC30( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 31: self.KK_circuit_fit.append( KK_RC31( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 32: self.KK_circuit_fit.append( KK_RC32( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 33: self.KK_circuit_fit.append( KK_RC33( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 34: self.KK_circuit_fit.append( KK_RC34( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 35: self.KK_circuit_fit.append( KK_RC35( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 36: self.KK_circuit_fit.append( KK_RC36( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 37: self.KK_circuit_fit.append( KK_RC37( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 38: self.KK_circuit_fit.append( KK_RC38( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 39: self.KK_circuit_fit.append( KK_RC39( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 40: self.KK_circuit_fit.append( KK_RC40( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 41: self.KK_circuit_fit.append( KK_RC41( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 42: self.KK_circuit_fit.append( KK_RC42( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 43: self.KK_circuit_fit.append( KK_RC43( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 44: self.KK_circuit_fit.append( KK_RC44( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 45: self.KK_circuit_fit.append( KK_RC45( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 46: self.KK_circuit_fit.append( KK_RC46( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 47: self.KK_circuit_fit.append( KK_RC47( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 48: self.KK_circuit_fit.append( KK_RC48( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 49: self.KK_circuit_fit.append( KK_RC49( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 50: self.KK_circuit_fit.append( KK_RC50( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 51: self.KK_circuit_fit.append( KK_RC51( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 52: self.KK_circuit_fit.append( KK_RC52( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 53: self.KK_circuit_fit.append( KK_RC53( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 54: self.KK_circuit_fit.append( KK_RC54( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 55: self.KK_circuit_fit.append( KK_RC55( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 56: self.KK_circuit_fit.append( KK_RC56( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 57: self.KK_circuit_fit.append( KK_RC57( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 58: self.KK_circuit_fit.append( KK_RC58( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 59: self.KK_circuit_fit.append( KK_RC59( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 60: self.KK_circuit_fit.append( KK_RC60( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 61: self.KK_circuit_fit.append( KK_RC61( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 62: self.KK_circuit_fit.append( KK_RC62( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 63: self.KK_circuit_fit.append( KK_RC63( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 64: self.KK_circuit_fit.append( KK_RC64( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 65: self.KK_circuit_fit.append( KK_RC65( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 66: self.KK_circuit_fit.append( KK_RC66( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 67: self.KK_circuit_fit.append( KK_RC67( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 68: self.KK_circuit_fit.append( KK_RC68( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 69: self.KK_circuit_fit.append( KK_RC69( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 70: self.KK_circuit_fit.append( KK_RC70( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 71: self.KK_circuit_fit.append( KK_RC71( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 72: self.KK_circuit_fit.append( KK_RC72( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 73: self.KK_circuit_fit.append( KK_RC73( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 74: self.KK_circuit_fit.append( KK_RC74( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 75: self.KK_circuit_fit.append( KK_RC75( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 76: self.KK_circuit_fit.append( KK_RC76( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 77: self.KK_circuit_fit.append( KK_RC77( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 78: self.KK_circuit_fit.append( KK_RC78( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 79: self.KK_circuit_fit.append( KK_RC79( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 80: self.KK_circuit_fit.append( KK_RC80( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) else: print("RC simulation circuit not defined") print(" Number of RC = ", self.number_RC) self.KK_rr_re.append( residual_real( re=self.df[i].re, fit_re=self.KK_circuit_fit[i].real, fit_im=-self.KK_circuit_fit[i].imag, ) ) # relative residuals for the real part self.KK_rr_im.append( residual_imag( im=self.df[i].im, fit_re=self.KK_circuit_fit[i].real, fit_im=-self.KK_circuit_fit[i].imag, ) ) # relative residuals for the imag part ### Plotting Linear_kk results ## # ### Label functions self.label_re_1 = [] self.label_im_1 = [] self.label_cycleno = [] if legend == "on": for i in range(len(self.df)): self.label_re_1.append("Z' (#" + str(i + 1) + ")") self.label_im_1.append("Z'' (#" + str(i + 1) + ")") self.label_cycleno.append("#" + str(i + 1)) elif legend == "potential": for i in range(len(self.df)): self.label_re_1.append( "Z' (" + str(np.round(np.average(self.df[i].E_avg), 2)) + " V)" ) self.label_im_1.append( "Z'' (" + str(np.round(np.average(self.df[i].E_avg), 2)) + " V)" ) self.label_cycleno.append( str(np.round(np.average(self.df[i].E_avg), 2)) + " V" ) if plot == "w_data": fig = figure(figsize=(6, 8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust(left=0.1, right=0.95, hspace=0.5, bottom=0.1, top=0.95) ax = fig.add_subplot(311, aspect="equal") ax1 = fig.add_subplot(312) ax2 = fig.add_subplot(313) colors = sns.color_palette("colorblind", n_colors=len(self.df)) colors_real = sns.color_palette("Blues", n_colors=len(self.df) + 2) colors_imag = sns.color_palette("Oranges", n_colors=len(self.df) + 2) ### Nyquist Plot for i in range(len(self.df)): ax.plot( self.df[i].re, self.df[i].im, marker="o", ms=4, lw=2, color=colors[i], ls="-", alpha=0.7, label=self.label_cycleno[i], ) ### Bode Plot if bode == "on": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), self.df[i].re, color=colors_real[i + 1], marker="D", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_re_1[i], ) ax1.plot( np.log10(self.df[i].f), self.df[i].im, color=colors_imag[i + 1], marker="s", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_im_1[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("Z', -Z'' [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "re": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), self.df[i].re, color=colors_real[i + 1], marker="D", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_cycleno[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("Z' [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "log_re": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), np.log10(self.df[i].re), color=colors_real[i + 1], marker="D", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_cycleno[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("log(Z') [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "im": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), self.df[i].im, color=colors_imag[i + 1], marker="s", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_cycleno[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("-Z'' [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "log_im": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), np.log10(self.df[i].im), color=colors_imag[i + 1], marker="s", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_cycleno[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("log(-Z'') [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "log": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), np.log10(self.df[i].re), color=colors_real[i + 1], marker="D", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_re_1[i], ) ax1.plot( np.log10(self.df[i].f), np.log10(self.df[i].im), color=colors_imag[i + 1], marker="s", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_im_1[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("log(Z', -Z'') [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ### Kramers-Kronig Relative Residuals for i in range(len(self.df)): ax2.plot( np.log10(self.df[i].f), self.KK_rr_re[i] * 100, color=colors_real[i + 1], marker="D", ls="--", ms=6, alpha=0.7, label=self.label_re_1[i], ) ax2.plot( np.log10(self.df[i].f), self.KK_rr_im[i] * 100, color=colors_imag[i + 1], marker="s", ls="--", ms=6, alpha=0.7, label=self.label_im_1[i], ) ax2.set_xlabel("log(f) [Hz]") ax2.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]") if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and write 'KK-Test' on RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if np.min(self.KK_rr_im_min) > np.min(self.KK_rr_re_min): ax2.set_ylim( np.min(self.KK_rr_re_min) * 100 * 1.5, np.max(np.abs(self.KK_rr_re_min)) * 100 * 1.5, ) ax2.annotate( "Lin-KK", xy=[ np.min(np.log10(self.df[0].f)), np.max(self.KK_rr_re_max) * 100 * 0.9, ], color="k", fontweight="bold", ) elif np.min(self.KK_rr_im_min) < np.min(self.KK_rr_re_min): ax2.set_ylim( np.min(self.KK_rr_im_min) * 100 * 1.5, np.max(self.KK_rr_im_max) * 100 * 1.5, ) ax2.annotate( "Lin-KK", xy=[ np.min(np.log10(self.df[0].f)), np.max(self.KK_rr_im_max) * 100 * 0.9, ], color="k", fontweight="bold", ) ### Figure specifics if legend == "on" or legend == "potential": ax.legend(loc="best", fontsize=10, frameon=False) ax.set_xlabel("Z' [$\Omega$]") ax.set_ylabel("-Z'' [$\Omega$]") if nyq_xlim != "none": ax.set_xlim(nyq_xlim[0], nyq_xlim[1]) if nyq_ylim != "none": ax.set_ylim(nyq_ylim[0], nyq_ylim[1]) # Save Figure if savefig != "none": fig.savefig(savefig) ### Illustrating residuals only elif plot == "residuals": colors = sns.color_palette("colorblind", n_colors=9) colors_real = sns.color_palette("Blues", n_colors=9) colors_imag = sns.color_palette("Oranges", n_colors=9) ### 1 Cycle if len(self.df) == 1: fig = figure(figsize=(12, 3.8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax = fig.add_subplot(231) ax.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax.set_xlabel("log(f) [Hz]") ax.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]") if legend == "on" or legend == "potential": ax.legend(loc="best", fontsize=10, frameon=False) ax.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and write 'KK-Test' on RR subplot self.KK_rr_im_min = np.min(self.KK_rr_im) self.KK_rr_im_max = np.max(self.KK_rr_im) self.KK_rr_re_min = np.min(self.KK_rr_re) self.KK_rr_re_max = np.max(self.KK_rr_re) if self.KK_rr_re_max > self.KK_rr_im_max: self.KK_ymax = self.KK_rr_re_max else: self.KK_ymax = self.KK_rr_im_max if self.KK_rr_re_min < self.KK_rr_im_min: self.KK_ymin = self.KK_rr_re_min else: self.KK_ymin = self.KK_rr_im_min if np.abs(self.KK_ymin) > self.KK_ymax: ax.set_ylim( self.KK_ymin * 100 * 1.5, np.abs(self.KK_ymin) * 100 * 1.5 ) if legend == "on": ax.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin) < self.KK_ymax: ax.set_ylim( np.negative(self.KK_ymax) * 100 * 1.5, np.abs(self.KK_ymax) * 100 * 1.5, ) if legend == "on": ax.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax * 100 * 1.3, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 2 Cycles elif len(self.df) == 2: fig = figure(figsize=(12, 5), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax2.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.3, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.3, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 3 Cycles elif len(self.df) == 3: fig = figure(figsize=(12, 5), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax2.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax3.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.3, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.3, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[2]) > self.KK_ymax[2]: ax3.set_ylim( self.KK_ymin[2] * 100 * 1.5, np.abs(self.KK_ymin[2]) * 100 * 1.5 ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[2]) < self.KK_ymax[2]: ax3.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[2]) * 100 * 1.5, ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymax[2]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), self.KK_ymax[2] * 100 * 1.3, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 4 Cycles elif len(self.df) == 4: fig = figure(figsize=(12, 3.8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax2.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax3.set_xlabel("log(f) [Hz]") ax3.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 4 ax4.plot( np.log10(self.df[3].f), self.KK_rr_re[3] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax4.plot( np.log10(self.df[3].f), self.KK_rr_im[3] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax4.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax4.legend(loc="best", fontsize=10, frameon=False) ax4.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[2]) > self.KK_ymax[2]: ax3.set_ylim( self.KK_ymin[2] * 100 * 1.5, np.abs(self.KK_ymin[2]) * 100 * 1.5 ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[2]) < self.KK_ymax[2]: ax3.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[2]) * 100 * 1.5, ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymax[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), self.KK_ymax[2] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[3]) > self.KK_ymax[3]: ax4.set_ylim( self.KK_ymin[3] * 100 * 1.5, np.abs(self.KK_ymin[3]) * 100 * 1.5 ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[3]) < self.KK_ymax[3]: ax4.set_ylim( np.negative(self.KK_ymax[3]) * 100 * 1.5, np.abs(self.KK_ymax[3]) * 100 * 1.5, ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymax[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), self.KK_ymax[3] * 100 * 1.2, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 5 Cycles elif len(self.df) == 5: fig = figure(figsize=(12, 3.8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax3.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 4 ax4.plot( np.log10(self.df[3].f), self.KK_rr_re[3] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax4.plot( np.log10(self.df[3].f), self.KK_rr_im[3] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax4.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) ax4.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax4.legend(loc="best", fontsize=10, frameon=False) ax4.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 5 ax5.plot( np.log10(self.df[4].f), self.KK_rr_re[4] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax5.plot( np.log10(self.df[4].f), self.KK_rr_im[4] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax5.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax5.legend(loc="best", fontsize=10, frameon=False) ax5.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[2]) > self.KK_ymax[2]: ax3.set_ylim( self.KK_ymin[2] * 100 * 1.5, np.abs(self.KK_ymin[2]) * 100 * 1.5 ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[2]) < self.KK_ymax[2]: ax3.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[2]) * 100 * 1.5, ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymax[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), self.KK_ymax[2] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[3]) > self.KK_ymax[3]: ax4.set_ylim( self.KK_ymin[3] * 100 * 1.5, np.abs(self.KK_ymin[3]) * 100 * 1.5 ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[3]) < self.KK_ymax[3]: ax4.set_ylim( np.negative(self.KK_ymax[3]) * 100 * 1.5, np.abs(self.KK_ymax[3]) * 100 * 1.5, ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymax[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), self.KK_ymax[3] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[4]) > self.KK_ymax[4]: ax5.set_ylim( self.KK_ymin[4] * 100 * 1.5, np.abs(self.KK_ymin[4]) * 100 * 1.5 ) if legend == "on": ax5.annotate( "Lin-KK, #5", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymin[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax5.annotate( "Lin-KK (" + str(np.round(np.average(self.df[4].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymin[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[4]) < self.KK_ymax[4]: ax5.set_ylim( np.negative(self.KK_ymax[4]) * 100 * 1.5, np.abs(self.KK_ymax[4]) * 100 * 1.5, ) if legend == "on": ax5.annotate( "Lin-KK, #5", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymax[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax5.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[4].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[4].f)), self.KK_ymax[4] * 100 * 1.2, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 6 Cycles elif len(self.df) == 6: fig = figure(figsize=(12, 3.8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) ax6 = fig.add_subplot(236) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=15) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 4 ax4.plot( np.log10(self.df[3].f), self.KK_rr_re[3] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax4.plot( np.log10(self.df[3].f), self.KK_rr_im[3] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax4.set_xlabel("log(f) [Hz]") ax4.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=15) if legend == "on" or legend == "potential": ax4.legend(loc="best", fontsize=10, frameon=False) ax4.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 5 ax5.plot( np.log10(self.df[4].f), self.KK_rr_re[4] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax5.plot( np.log10(self.df[4].f), self.KK_rr_im[4] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax5.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax5.legend(loc="best", fontsize=10, frameon=False) ax5.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 6 ax6.plot( np.log10(self.df[5].f), self.KK_rr_re[5] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax6.plot( np.log10(self.df[5].f), self.KK_rr_im[5] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax6.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax6.legend(loc="best", fontsize=10, frameon=False) ax6.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[2]) > self.KK_ymax[2]: ax3.set_ylim( self.KK_ymin[2] * 100 * 1.5, np.abs(self.KK_ymin[2]) * 100 * 1.5 ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[2]) < self.KK_ymax[2]: ax3.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[2]) * 100 * 1.5, ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymax[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), self.KK_ymax[2] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[3]) > self.KK_ymax[3]: ax4.set_ylim( self.KK_ymin[3] * 100 * 1.5, np.abs(self.KK_ymin[3]) * 100 * 1.5 ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[3]) < self.KK_ymax[3]: ax4.set_ylim( np.negative(self.KK_ymax[3]) * 100 * 1.5, np.abs(self.KK_ymax[3]) * 100 * 1.5, ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymax[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), self.KK_ymax[3] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[4]) > self.KK_ymax[4]: ax5.set_ylim( self.KK_ymin[4] * 100 * 1.5, np.abs(self.KK_ymin[4]) * 100 * 1.5 ) if legend == "on": ax5.annotate( "Lin-KK, #5", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymin[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax5.annotate( "Lin-KK (" + str(np.round(np.average(self.df[4].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymin[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[4]) < self.KK_ymax[4]: ax5.set_ylim( np.negative(self.KK_ymax[4]) * 100 * 1.5, np.abs(self.KK_ymax[4]) * 100 * 1.5, ) if legend == "on": ax5.annotate( "Lin-KK, #5", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymax[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax5.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[4].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[4].f)), self.KK_ymax[4] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[5]) > self.KK_ymax[5]: ax6.set_ylim( self.KK_ymin[5] * 100 * 1.5, np.abs(self.KK_ymin[5]) * 100 * 1.5 ) if legend == "on": ax6.annotate( "Lin-KK, #6", xy=[ np.min(np.log10(self.df[5].f)), np.abs(self.KK_ymin[5]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax6.annotate( "Lin-KK (" + str(np.round(np.average(self.df[5].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[5].f)), np.abs(self.KK_ymin[5]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[5]) < self.KK_ymax[5]: ax6.set_ylim( np.negative(self.KK_ymax[5]) * 100 * 1.5, np.abs(self.KK_ymax[5]) * 100 * 1.5, ) if legend == "on": ax6.annotate( "Lin-KK, #6", xy=[ np.min(np.log10(self.df[5].f)), np.abs(self.KK_ymax[5]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax6.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[5].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[5].f)), self.KK_ymax[5] * 100 * 1.2, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 7 Cycles elif len(self.df) == 7: fig = figure(figsize=(12, 5), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333) ax4 = fig.add_subplot(334) ax5 = fig.add_subplot(335) ax6 = fig.add_subplot(336) ax7 = fig.add_subplot(337) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=15) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax3.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 4 ax4.plot( np.log10(self.df[3].f), self.KK_rr_re[3] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax4.plot( np.log10(self.df[3].f), self.KK_rr_im[3] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax4.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=15) if legend == "on" or legend == "potential": ax4.legend(loc="best", fontsize=10, frameon=False) ax4.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 5 ax5.plot( np.log10(self.df[4].f), self.KK_rr_re[4] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax5.plot( np.log10(self.df[4].f), self.KK_rr_im[4] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax5.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax5.legend(loc="best", fontsize=10, frameon=False) ax5.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 6 ax6.plot( np.log10(self.df[5].f), self.KK_rr_re[5] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax6.plot( np.log10(self.df[5].f), self.KK_rr_im[5] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax6.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax6.legend(loc="best", fontsize=10, frameon=False) ax6.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 7 ax7.plot( np.log10(self.df[6].f), self.KK_rr_re[6] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax7.plot( np.log10(self.df[6].f), self.KK_rr_im[6] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax7.set_xlabel("log(f) [Hz]") ax7.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=15) if legend == "on" or legend == "potential": ax7.legend(loc="best", fontsize=10, frameon=False) ax7.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[2]) > self.KK_ymax[2]: ax3.set_ylim( self.KK_ymin[2] * 100 * 1.5, np.abs(self.KK_ymin[2]) * 100 * 1.5 ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[2]) < self.KK_ymax[2]: ax3.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[2]) * 100 * 1.5, ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymax[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), self.KK_ymax[2] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[3]) > self.KK_ymax[3]: ax4.set_ylim( self.KK_ymin[3] * 100 * 1.5, np.abs(self.KK_ymin[3]) * 100 * 1.5 ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[3]) < self.KK_ymax[3]: ax4.set_ylim( np.negative(self.KK_ymax[3]) * 100 * 1.5, np.abs(self.KK_ymax[3]) * 100 * 1.5, ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymax[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), self.KK_ymax[3] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[4]) > self.KK_ymax[4]: ax5.set_ylim( self.KK_ymin[4] * 100 * 1.5, np.abs(self.KK_ymin[4]) * 100 * 1.5 ) if legend == "on": ax5.annotate( "Lin-KK, #5", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymin[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax5.annotate( "Lin-KK (" + str(np.round(np.average(self.df[4].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymin[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[4]) < self.KK_ymax[4]: ax5.set_ylim( np.negative(self.KK_ymax[4]) * 100 * 1.5, np.abs(self.KK_ymax[4]) * 100 * 1.5, ) if legend == "on": ax5.annotate( "Lin-KK, #5", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymax[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax5.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[4].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[4].f)), self.KK_ymax[4] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[5]) > self.KK_ymax[5]: ax6.set_ylim( self.KK_ymin[5] * 100 * 1.5, np.abs(self.KK_ymin[5]) * 100 * 1.5 ) if legend == "on": ax6.annotate( "Lin-KK, #6", xy=[ np.min(np.log10(self.df[5].f)), np.abs(self.KK_ymin[5]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax6.annotate( "Lin-KK (" + str(np.round(np.average(self.df[5].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[5].f)), np.abs(self.KK_ymin[5]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[5]) < self.KK_ymax[5]: ax6.set_ylim( np.negative(self.KK_ymax[5]) * 100 * 1.5, np.abs(self.KK_ymax[5]) * 100 * 1.5, ) if legend == "on": ax6.annotate( "Lin-KK, #6", xy=[ np.min(np.log10(self.df[5].f)), np.abs(self.KK_ymax[5]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax6.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[5].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[5].f)), self.KK_ymax[5] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[6]) > self.KK_ymax[6]: ax7.set_ylim( self.KK_ymin[6] * 100 * 1.5, np.abs(self.KK_ymin[6]) * 100 * 1.5 ) if legend == "on": ax7.annotate( "Lin-KK, #7", xy=[ np.min(np.log10(self.df[6].f)), np.abs(self.KK_ymin[6]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax7.annotate( "Lin-KK (" + str(np.round(np.average(self.df[6].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[6].f)), np.abs(self.KK_ymin[6]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[6]) < self.KK_ymax[6]: ax7.set_ylim( np.negative(self.KK_ymax[6]) * 100 * 1.5, np.abs(self.KK_ymax[6]) * 100 * 1.5, ) if legend == "on": ax7.annotate( "Lin-KK, #7", xy=[ np.min(np.log10(self.df[6].f)), np.abs(self.KK_ymax[6]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax7.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[6].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[6].f)), self.KK_ymax[6] * 100 * 1.2, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 8 Cycles elif len(self.df) == 8: fig = figure(figsize=(12, 5), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(331) ax2 = fig.add_subplot(332) ax3 = fig.add_subplot(333) ax4 = fig.add_subplot(334) ax5 = fig.add_subplot(335) ax6 = fig.add_subplot(336) ax7 = fig.add_subplot(337) ax8 = fig.add_subplot(338) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=14) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 4 ax4.plot( np.log10(self.df[3].f), self.KK_rr_re[3] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax4.plot( np.log10(self.df[3].f), self.KK_rr_im[3] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax4.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=14) if legend == "on" or legend == "potential": ax4.legend(loc="best", fontsize=10, frameon=False) ax4.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 5 ax5.plot( np.log10(self.df[4].f), self.KK_rr_re[4] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax5.plot( np.log10(self.df[4].f), self.KK_rr_im[4] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax5.legend(loc="best", fontsize=10, frameon=False) ax5.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 6 ax6.plot( np.log10(self.df[5].f), self.KK_rr_re[5] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax6.plot( np.log10(self.df[5].f), self.KK_rr_im[5] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax6.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax6.legend(loc="best", fontsize=10, frameon=False) ax6.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 7 ax7.plot( np.log10(self.df[6].f), self.KK_rr_re[6] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax7.plot( np.log10(self.df[6].f), self.KK_rr_im[6] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax7.set_xlabel("log(f) [Hz]") ax7.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=14) if legend == "on" or legend == "potential": ax7.legend(loc="best", fontsize=10, frameon=False) ax7.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 8 ax8.plot( np.log10(self.df[7].f), self.KK_rr_re[7] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax8.plot(
np.log10(self.df[7].f)
numpy.log10
import rospy from pointcloud_to_rangeimage.msg import RangeImage as RangeImage_msg from pointcloud_to_rangeimage.msg import RangeImageEncoded as RangeImageEncoded_msg import cv2 from cv_bridge import CvBridge import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Add, Subtract, Lambda, Layer from tensorflow.keras.layers import Conv2D, ZeroPadding2D import tensorflow_compression as tfc import numpy as np class RnnConv(Layer): """ Convolutional LSTM cell See detail in formula (4-6) in paper "Full Resolution Image Compression with Recurrent Neural Networks" https://arxiv.org/pdf/1608.05148.pdf Args: name: name of current ConvLSTM layer filters: number of filters for each convolutional operation strides: strides size kernel_size: kernel size of convolutional operation hidden_kernel_size: kernel size of convolutional operation for hidden state Input: inputs: input of the layer hidden: hidden state and cell state of the layer Output: newhidden: updated hidden state of the layer newcell: updated cell state of the layer """ def __init__(self, name, filters, strides, kernel_size, hidden_kernel_size): super(RnnConv, self).__init__() self.filters = filters self.strides = strides self.conv_i = Conv2D(filters=4 * self.filters, kernel_size=kernel_size, strides=self.strides, padding='same', use_bias=False, name=name + '_i') self.conv_h = Conv2D(filters=4 * self.filters, kernel_size=hidden_kernel_size, padding='same', use_bias=False, name=name + '_h') def call(self, inputs, hidden): # with tf.variable_scope(name, reuse=tf.AUTO_REUSE): conv_inputs = self.conv_i(inputs) conv_hidden = self.conv_h(hidden[0]) # all gates are determined by input and hidden layer in_gate, f_gate, out_gate, c_gate = tf.split( conv_inputs + conv_hidden, 4, axis=-1) # each gate get the same number of filters in_gate = tf.nn.sigmoid(in_gate) # input/update gate f_gate = tf.nn.sigmoid(f_gate) out_gate = tf.nn.sigmoid(out_gate) c_gate = tf.nn.tanh(c_gate) # candidate cell, calculated from input # forget_gate*old_cell+input_gate(update)*candidate_cell newcell = tf.multiply(f_gate, hidden[1]) + tf.multiply(in_gate, c_gate) newhidden = tf.multiply(out_gate, tf.nn.tanh(newcell)) return newhidden, newcell class EncoderRNN(Layer): """ Encoder layer for one iteration. Args: bottleneck: bottleneck size of the layer name: name of encoder layer Input: input: output array from last iteration. In the first iteration, it is the normalized image patch hidden2, hidden3, hidden4: hidden and cell states of corresponding ConvLSTM layers training: boolean, whether the call is in inference mode or training mode Output: encoded: encoded binary array in each iteration hidden2, hidden3, hidden4: hidden and cell states of corresponding ConvLSTM layers """ def __init__(self, bottleneck, name=None): super(EncoderRNN, self).__init__(name=name) self.bottleneck = bottleneck self.Conv_e1 = Conv2D(64, kernel_size=(3,3), strides=(2, 2), padding="same", use_bias=False, name='Conv_e1') self.GDN = tfc.GDN(alpha_parameter=2, epsilon_parameter=0.5, name="gdn") self.RnnConv_e1 = RnnConv("RnnConv_e1", 256, (2, 2), kernel_size=(3, 3), hidden_kernel_size=(3, 3)) self.RnnConv_e2 = RnnConv("RnnConv_e2", 512, (2, 2), kernel_size=(3, 3), hidden_kernel_size=(3, 3)) self.RnnConv_e3 = RnnConv("RnnConv_e3", 512, (2, 2), kernel_size=(3, 3), hidden_kernel_size=(3, 3)) self.Conv_b = Conv2D(bottleneck, kernel_size=(1, 1), activation=tf.nn.tanh, use_bias=False, name='b_conv') self.Sign = Lambda(lambda x: tf.sign(x), name="sign") def call(self, input, hidden2, hidden3, hidden4, training=False): # with tf.compat.v1.variable_scope("encoder", reuse=True): # input size (32,32,3) x = self.Conv_e1(input) x = self.GDN(x) # (16,16,64) hidden2 = self.RnnConv_e1(x, hidden2) x = hidden2[0] # (8,8,256) hidden3 = self.RnnConv_e2(x, hidden3) x = hidden3[0] # (4,4,512) hidden4 = self.RnnConv_e3(x, hidden4) x = hidden4[0] # (2,2,512) # binarizer x = self.Conv_b(x) # (2,2,bottleneck) encoded = self.Sign(x) return encoded, hidden2, hidden3, hidden4 class DecoderRNN(Layer): """ Decoder layer for one iteration. Args: name: name of decoder layer Input: input: decoded array in each iteration hidden2, hidden3, hidden4, hidden5: hidden and cell states of corresponding ConvLSTM layers training: boolean, whether the call is in inference mode or training mode Output: decoded: decoded array in each iteration hidden2, hidden3, hidden4, hidden5: hidden and cell states of corresponding ConvLSTM layers """ def __init__(self, name=None): super(DecoderRNN, self).__init__(name=name) self.Conv_d1 = Conv2D(512, kernel_size=(1, 1), use_bias=False, name='d_conv1') self.iGDN = tfc.GDN(alpha_parameter=2, epsilon_parameter=0.5, inverse=True, name="igdn") self.RnnConv_d2 = RnnConv("RnnConv_d2", 512, (1, 1), kernel_size=(3, 3), hidden_kernel_size=(3, 3)) self.RnnConv_d3 = RnnConv("RnnConv_d3", 512, (1, 1), kernel_size=(3, 3), hidden_kernel_size=(3, 3)) self.RnnConv_d4 = RnnConv("RnnConv_d4", 256, (1, 1), kernel_size=(3, 3), hidden_kernel_size=(3, 3)) self.RnnConv_d5 = RnnConv("RnnConv_d5", 128, (1, 1), kernel_size=(3, 3), hidden_kernel_size=(3, 3)) self.Conv_d6 = Conv2D(1, kernel_size=(1, 1), padding='same', name='d_conv6', use_bias=False, activation=tf.nn.tanh) self.DTS1 = Lambda(lambda x: tf.nn.depth_to_space(x, 2), name="dts_1") self.DTS2 = Lambda(lambda x: tf.nn.depth_to_space(x, 2), name="dts_2") self.DTS3 = Lambda(lambda x: tf.nn.depth_to_space(x, 2), name="dts_3") self.DTS4 = Lambda(lambda x: tf.nn.depth_to_space(x, 2), name="dts_4") self.Add = Add(name="add") self.Out = Lambda(lambda x: x*0.5, name="out") def call(self, input, hidden2, hidden3, hidden4, hidden5, training=False): # (2,2,bottleneck) x = self.Conv_d1(input) x_igdn = self.iGDN(x) # (2,2,512) hidden2 = self.RnnConv_d2(x_igdn, hidden2) x = hidden2[0] # (2,2,512) x = self.Add([x, x_igdn]) x = self.DTS1(x) # (4,4,128) hidden3 = self.RnnConv_d3(x, hidden3) x = hidden3[0] # (4,4,512) x = self.DTS2(x) # (8,8,128) hidden4 = self.RnnConv_d4(x, hidden4) x = hidden4[0] # (8,8,256) x = self.DTS3(x) # (16,16,64) hidden5 = self.RnnConv_d5(x, hidden5) x = hidden5[0] # (16,16,128) x = self.DTS4(x) # (32,32,32) # output in range (-0.5,0.5) x = self.Conv_d6(x) decoded = self.Out(x) return decoded, hidden2, hidden3, hidden4, hidden5 class EncoderModel(Model): """ Encoder engine consisting of encoder layer and decoder layer. Args: bottleneck: bottleneck size of the network num_iters: number of iterations Input: input: decoded array in each iteration training: boolean, whether the call is in inference mode or training mode Output: codes: list of compressed binary codewords generated through iterations """ def __init__(self, bottleneck, num_iters): super(EncoderModel, self).__init__() self.num_iters = num_iters self.encoder = EncoderRNN(bottleneck, name="encoder") self.decoder = DecoderRNN(name="decoder") self.normalize = Lambda(lambda x: tf.subtract(x, 0.5), name="normalization") self.subtract = Subtract() self.inputs = tf.keras.layers.Input(shape=(32, 1824, 1)) self.DIM1 = 1824 // 2 self.DIM2 = self.DIM1 // 2 self.DIM3 = self.DIM2 // 2 self.DIM4 = self.DIM3 // 2 self.beta = 1.0 / self.num_iters def initial_hidden(self, batch_size, hidden_size, filters): """Initialize hidden and cell states, all zeros""" shape = [batch_size] + hidden_size + [filters] hidden = tf.zeros(shape) cell = tf.zeros(shape) return hidden, cell def call(self, inputs, training=False): # Initialize the hidden states when a new batch comes in batch_size = inputs.shape[0] hidden_e2 = self.initial_hidden(batch_size, [8, self.DIM2], 256) hidden_e3 = self.initial_hidden(batch_size, [4, self.DIM3], 512) hidden_e4 = self.initial_hidden(batch_size, [2, self.DIM4], 512) hidden_d2 = self.initial_hidden(batch_size, [2, self.DIM4], 512) hidden_d3 = self.initial_hidden(batch_size, [4, self.DIM3], 512) hidden_d4 = self.initial_hidden(batch_size, [8, self.DIM2], 256) hidden_d5 = self.initial_hidden(batch_size, [16, self.DIM1], 128) codes = [] inputs = self.normalize(inputs) res = inputs for i in range(self.num_iters-1): code, hidden_e2, hidden_e3, hidden_e4 = \ self.encoder(res, hidden_e2, hidden_e3, hidden_e4, training=training) decoded, hidden_d2, hidden_d3, hidden_d4, hidden_d5 = \ self.decoder(code, hidden_d2, hidden_d3, hidden_d4, hidden_d5, training=training) # Update res as predicted output in this iteration subtract the original input res = self.subtract([decoded, inputs]) codes.append(code) code, hidden_e2, hidden_e3, hidden_e4 = self.encoder(res, hidden_e2, hidden_e3, hidden_e4, training=training) codes.append(code) return codes def predict_step(self, data): inputs, labels = data codes = self(inputs, training=False) return codes class DecoderModel(Model): """ Decoder engine iteratively calling the decoder layer. Args: bottleneck: bottleneck size of the network num_iters: number of iterations Input: codes: output of Encoder engine training: boolean, whether the call is in inference mode or training mode Output: output_tensor: decoded image patch """ def __init__(self, bottleneck, num_iters): super(DecoderModel, self).__init__() self.num_iters = num_iters self.DIM1 = 1824 // 2 self.DIM2 = self.DIM1 // 2 self.DIM3 = self.DIM2 // 2 self.DIM4 = self.DIM3 // 2 self.decoder = DecoderRNN(name="decoder") self.subtract = Subtract() self.inputs = [] # inputs of shape [(bs, 2, 114, bottleneck), (bs, 2, 114, bottleneck), (bs, 2, 114, bottleneck), ...] for i in range(self.num_iters): self.inputs.append(tf.keras.layers.Input(shape=(2, self.DIM4, bottleneck))) def initial_hidden(self, batch_size, hidden_size, filters): """Initialize hidden and cell states, all zeros""" shape = [batch_size] + hidden_size + [filters] hidden = tf.zeros(shape) cell = tf.zeros(shape) return hidden, cell def call(self, codes, training=False): batch_size = codes[0].shape[0] hidden_d2 = self.initial_hidden(batch_size, [2, self.DIM4], 512) hidden_d3 = self.initial_hidden(batch_size, [4, self.DIM3], 512) hidden_d4 = self.initial_hidden(batch_size, [8, self.DIM2], 256) hidden_d5 = self.initial_hidden(batch_size, [16, self.DIM1], 128) for i in range(self.num_iters): decoded, hidden_d2, hidden_d3, hidden_d4, hidden_d5 = \ self.decoder(codes[i], hidden_d2, hidden_d3, hidden_d4, hidden_d5, training=training) output_tensor = tf.clip_by_value(tf.add(decoded, 0.5), 0, 1) return output_tensor def predict_step(self, data): inputs, labels = data outputs = self(inputs, training=False) return outputs class MsgEncoder: """ Subscribe to topic /pointcloud_to_rangeimage_node/msg_out, compress range image using RNN image compression model, azimuth image using JPEG2000 and intensity image using PNG compression. Publish message type RangeImageEncoded to topic /msg_encoded. """ def __init__(self): self.pub = rospy.Publisher('msg_encoded', RangeImageEncoded_msg, queue_size=10) self.sub = rospy.Subscriber("/pointcloud_to_rangeimage_node/msg_out", RangeImage_msg, self.callback) self.bridge = CvBridge() bottleneck = rospy.get_param("/rnn_compression/bottleneck") num_iters = rospy.get_param("/rnn_compression/num_iters") weights_path = rospy.get_param("/rnn_compression/weights_path") # load model self.encoder = EncoderModel(bottleneck, num_iters) self.encoder(
np.zeros((1, 32, 1824, 1))
numpy.zeros
""" aspec_doa.py Angular spectrum-based DOA estimation Copyright (c) 2017 Idiap Research Institute, http://www.idiap.ch/ Written by <NAME> <<EMAIL>> """ import sys import math import numpy as np import scipy.interpolate from .basic import steering_vector, compute_delay from .doa import azimuth_distance def phi_mvdr_snr(ecov, delay, fbins=None): """Local angular spectrum function: MVDR (SNR) Args: ecov : empirical covariance matrix, indices (cctf) delay : the set of delays to probe, indices (dc) fbins : (default None) if fbins is not over all frequencies, use fins to specify centers of frequency bins as discrete values. Returns: phi : local angular spectrum function, indices (dt), here 'd' is the index of delay """ # compute inverse of empirical covariance matrix eta = 1e-10 nch, _, nframe, nfbin = ecov.shape iecov = np.zeros(ecov.shape, dtype=ecov.dtype) for i in range(nframe): for j in range(nfbin): iecov[:,:,i,j] = np.asmatrix(ecov[:,:,i,j] + np.eye(nch) * eta).I # total power: trace mean tpow = np.einsum('cctf->tf', ecov).real / nch + eta phi = np.zeros((len(delay), nframe)) for i in range(len(delay)): if fbins is None: stv = steering_vector(delay[i], nfbin) else: stv = steering_vector(delay[i], fbins=fbins) denom = np.einsum('cf,cdtf,df->tf', stv.conj(), iecov, stv, optimize='optimal').real assert np.all(denom > 0) # iecov positive definite isnr = np.maximum(tpow * denom - 1.0, eta) # 1 / snr phi[i] = np.sum(1. / isnr, axis=1) / nfbin # average over frequency return phi def phi_mvdr(ecov, delay, fbins=None): """Local angular spectrum function: MVDR Args: ecov : empirical covariance matrix, indices (cctf) delay : the set of delays to probe, indices (dc) fbins : (default None) if fbins is not over all frequencies, use fins to specify centers of frequency bins as discrete values. Returns: phi : local angular spectrum function, indices (dt), here 'd' is the index of delay """ # compute inverse of empirical covariance matrix eta = 1e-10 nch, _, nframe, nfbin = ecov.shape iecov = np.zeros(ecov.shape, dtype=ecov.dtype) for i in range(nframe): for j in range(nfbin): iecov[:,:,i,j] = np.asmatrix(ecov[:,:,i,j] + np.eye(nch) * eta).I phi = np.zeros((len(delay), nframe)) for i in range(len(delay)): if fbins is None: stv = steering_vector(delay[i], nfbin) else: stv = steering_vector(delay[i], fbins=fbins) denom = np.einsum('cf,cdtf,df->tf', stv.conj(), iecov, stv, optimize='optimal').real assert np.all(denom > 0) # iecov positive definite phi[i] = np.sum(1. / denom, axis=1) # sum over frequency return phi def phi_srp_phat(ecov, delay, fbins=None): """Local angular spectrum function: SRP-PHAT Args: ecov : empirical covariance matrix, indices (cctf) delay : the set of delays to probe, indices (dc) fbins : (default None) if fbins is not over all frequencies, use fins to specify centers of frequency bins as discrete values. Returns: phi : local angular spectrum function, indices (dt), here 'd' is the index of delay """ # compute inverse of empirical covariance matrix nch, _, nframe, nfbin = ecov.shape mask = np.asarray([[c < d for d in range(nch)] for c in range(nch)]) ecov_upper_tri = ecov[mask] cpsd_phat = np.zeros(ecov_upper_tri.shape, dtype=ecov_upper_tri.dtype) ampl = np.abs(ecov_upper_tri) non_zero_mask = ampl > 1e-20 cpsd_phat[non_zero_mask] = ecov_upper_tri[non_zero_mask] / ampl[non_zero_mask] phi = np.zeros((len(delay), nframe)) for i in range(len(delay)): if fbins is None: stv = steering_vector(delay[i], nfbin) else: stv = steering_vector(delay[i], fbins=fbins) x = np.asarray([stv[c] * stv[d].conj() for c in range(nch) for d in range (nch) if c < d]) phi[i] = np.einsum('itf,if->t', cpsd_phat, x.conj(), optimize='optimal').real / nfbin / len(x) return phi def phi_srp_phat_nonlin(ecov, delay, fbins=None): """Local angular spectrum function: SRP-PHAT non-linear Args: ecov : empirical covariance matrix, indices (cctf) delay : the set of delays to probe, indices (dc) fbins : (default None) if fbins is not over all frequencies, use fins to specify centers of frequency bins as discrete values. Returns: phi : local angular spectrum function, indices (dt), here 'd' is the index of delay """ # compute inverse of empirical covariance matrix nch, _, nframe, nfbin = ecov.shape mask = np.asarray([[c < d for d in range(nch)] for c in range(nch)]) ecov_upper_tri = ecov[mask] cpsd_phat = np.zeros(ecov_upper_tri.shape, dtype=ecov_upper_tri.dtype) ampl = np.abs(ecov_upper_tri) non_zero_mask = ampl > 1e-20 cpsd_phat[non_zero_mask] = ecov_upper_tri[non_zero_mask] / ampl[non_zero_mask] phi = np.zeros((len(delay), nframe)) for i in range(len(delay)): if fbins is None: stv = steering_vector(delay[i], nfbin) else: stv = steering_vector(delay[i], fbins=fbins) x = np.asarray([stv[c] * stv[d].conj() for c in range(nch) for d in range (nch) if c < d]) phi_if = np.einsum('itf,if->itf', cpsd_phat, x.conj(), optimize='optimal').real phi_nonlin = 1 - np.tanh(2 * np.sqrt(1 - np.minimum(phi_if, 1.0))) phi[i] = np.einsum('itf->t', phi_nonlin, optimize='optimal') / nfbin / len(x) return phi class MVDR_NCOV: """MVDR with known noise covariance matrix""" def __init__(self, ncov): """ Args: ncov : noise spatial covariance matrix, indexed by (ccf) """ self.incov = np.moveaxis(np.linalg.inv(np.moveaxis(ncov, 2, 0)), 0, 2) def __call__(self, ecov, delay, fbins=None): """Local angular spectrum function: MVDR-NCOV Args: ecov : empirical covariance matrix, indices (cctf) delay : the set of delays to probe, indices (dc) fbins : (default None) if fbins is not over all frequencies, use fins to specify centers of frequency bins as discrete values. Returns: phi : local angular spectrum function, indices (dt), here 'd' is the index of delay """ nch, _, nframe, nfbin = ecov.shape phi = np.zeros((len(delay), nframe)) for i in range(len(delay)): if fbins is None: stv = steering_vector(delay[i], nfbin) else: stv = steering_vector(delay[i], fbins=fbins) w = np.einsum('cdf,df->cf', self.incov, stv) n = np.einsum('cf,cf->f', stv.conj(), w) w = np.einsum('cf,f->cf', w, 1.0 / n) phi[i] = np.einsum('cf,cdtf,df->t', w.conj(), ecov, w, optimize='optimal').real return phi class MVDR_NCOV_SNR: """MVDR with known noise covariance matrix""" def __init__(self, ncov): """ Args: ncov : noise spatial covariance matrix, indexed by (ccf) """ self.incov = np.moveaxis(np.linalg.inv(np.moveaxis(ncov, 2, 0)), 0, 2) def __call__(self, ecov, delay, fbins=None): """Local angular spectrum function: MVDR-NCOV Args: ecov : empirical covariance matrix, indices (cctf) delay : the set of delays to probe, indices (dc) fbins : (default None) if fbins is not over all frequencies, use fins to specify centers of frequency bins as discrete values. Returns: phi : local angular spectrum function, indices (dt), here 'd' is the index of delay """ nch, _, nframe, nfbin = ecov.shape phi = np.zeros((len(delay), nframe)) # total power pt = np.einsum('cctf->tf', ecov).real for i in range(len(delay)): if fbins is None: stv = steering_vector(delay[i], nfbin) else: stv = steering_vector(delay[i], fbins=fbins) w =
np.einsum('cdf,df->cf', self.incov, stv)
numpy.einsum
"""Functions for rendering the final result in PyVista.""" import time import numpy as np import pyvista as pv from matplotlib.colors import LinearSegmentedColormap from util import latlon2xyz, find_percent_val, find_val_percent import cmocean # zmaps = cmocean.tools.get_dict(cmocean.cm.thermal, N=9) # zmaps = cmocean.cm.thermal # zmaps = cmocean.cm.get_cmap("thermal").copy() def add_points(pl, points): # Is it strictly necessary that these be np.arrays? for key, data in points.items(): dots = pv.PolyData(np.array(data)) pl.add_mesh(dots, point_size=10.0, color=key) def add_lines(pl, radius, tilt): x_axisline = pv.Line([-1.5*radius,0,0],[1.5*radius,0,0]) y_axisline = pv.Line([0,-1.5*radius,0],[0,1.5*radius,0]) z_axisline = pv.Line([0,0,-1.5*radius],[0,0,1.5*radius]) # Axial tilt line # ax, ay, az = latlon2xyz(tilt, 45, radius) ax, ay, az = latlon2xyz(tilt, 0, radius) t_axisline = pv.Line([0,0,0], [ax * 1.5, ay * 1.5, az * 1.5]) # Sun tilt line (line that is perpendicular to the incoming solar flux) # ax, ay, az = latlon2xyz(90-tilt, -135, radius) ax, ay, az = latlon2xyz(90-tilt, 180, radius) s_axisline = pv.Line([0,0,0], [ax * 1.5, ay * 1.5, az * 1.5]) pl.add_mesh(x_axisline, line_width=5, color = "red") pl.add_mesh(y_axisline, line_width=5, color = "green") pl.add_mesh(z_axisline, line_width=5, color = "blue") pl.add_mesh(t_axisline, line_width=5, color = "magenta") pl.add_mesh(s_axisline, line_width=5, color = "yellow") def visualize(verts, tris, heights=None, scalars=None, zero_level=0.0, surf_points=None, radius=1.0, tilt=0.0): """Visualize the output.""" pl = pv.Plotter() if scalars["s-mode"] in ("insolation", "temperature"): show_ocean_shell = False else: show_ocean_shell = True # pyvista expects that faces have a leading number telling it how many # vertices a face has, e.g. [3, 0, 11, 5] where 3 means triangle. # https://docs.pyvista.org/examples/00-load/create-poly.html # So we fill an array with the number '3' and merge it with the cells # from meshzoo to get a 'proper' array for pyvista. time_start = time.perf_counter() tri_size = np.full((len(tris), 1), 3) new_tris = np.hstack((tri_size, tris)) time_end = time.perf_counter() print(f"Time to reshape triangle array: {time_end - time_start :.5f} sec") tri_size = None # Create pyvista mesh from our icosphere time_start = time.perf_counter() planet_mesh = pv.PolyData(verts, new_tris) time_end = time.perf_counter() print(f"Time to create the PyVista planet mesh: {time_end - time_start :.5f} sec") # Separate mesh for ocean water if show_ocean_shell: ocean_shell = pv.ParametricEllipsoid(radius, radius, radius, u_res=300, v_res=300) pl.add_mesh(ocean_shell, show_edges=False, smooth_shading=True, color="blue", opacity=0.15) # Add any surface marker points or other floating marker points if surf_points is not None: add_points(pl, surf_points) # Add axis lines add_lines(pl, radius, tilt) # minval = np.amin(scalars["scalars"]) # maxval = np.amax(scalars["scalars"]) # heights = np.clip(heights, minval*1.001, maxval) # Prepare scalar gradient, scalar bar, and annotations color_map, anno = make_scalars(scalars["s-mode"], scalars["scalars"]) sargs = dict(n_labels=0, label_font_size=12, position_y=0.07) # ToDo: Add title to the scalar bar sargs and dynamically change it based on what is being visualized (e.g. Elevation, Surface Temperature, etc.) # title="whatever" (remove the quotes and make 'whatever' into a variable, like the s-mode or whatever. like title=scalars["s-mode"]) # "Current"? ".items()"? https://stackoverflow.com/questions/3545331/how-can-i-get-dictionary-key-as-variable-directly-in-python-not-by-searching-fr # https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python # pl.add_mesh(planet_mesh, show_edges=False, smooth_shading=True, color="white", below_color="blue", culling="back", scalars=scalars["scalars"], cmap=custom_cmap, scalar_bar_args=sargs, annotations=anno) pl.add_mesh(planet_mesh, show_edges=False, smooth_shading=True, color="white", culling="back", scalars=scalars["scalars"], cmap=color_map, scalar_bar_args=sargs, annotations=anno) pl.show_axes() pl.enable_terrain_style(mouse_wheel_zooms=True) # Use turntable style navigation print("Sending to PyVista.") pl.show() def make_scalars(mode, scalars): # Define the colors we want to use (NOT BEING USED AT THE MOMENT) blue = np.array([12/256, 238/256, 246/256, 1]) black = np.array([11/256, 11/256, 11/256, 1]) grey =
np.array([189/256, 189/256, 189/256, 1])
numpy.array
import numpy as np from numpy.testing import assert_almost_equal, assert_allclose import pickle import os from skcv import data_dir from skcv.multiview.two_views.fundamental_matrix import * from skcv.multiview.util.points_functions import * from skcv.multiview.util.camera import * def test_fundamental_from_cameras(): center1 = np.array((0, 0, 0)) center2 = np.array((1, 0, 0)) look_at1 = np.array((0, 0, 10)) look_at2 = np.array((1, 0, 10)) camera1 = look_at_matrix(center1, look_at1) camera2 = look_at_matrix(center2, look_at2) f_matrix = fundamental_matrix_from_two_cameras(camera1, camera2) def test_epipoles(): f_matrix = np.array(((0, 0, 0), (0, 0, -1), (0, 1, 0))) re = right_epipole(f_matrix) le = left_epipole(f_matrix) assert_almost_equal(re, [1, 0, 0]) assert_almost_equal(le, [1, 0, 0]) def test_canonical_cameras(): camera1 = np.array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.]]) camera2 = np.array([[0., 0., 0., 1.], [0., -1., 0., 0.], [0., 0., -1., 0.]]) f_matrix = np.array([[0, 0, 0], [0, 0, -1], [0, 1, 0]]) p1, p2 = canonical_cameras_from_f(f_matrix) assert_almost_equal(p1, camera1) assert_almost_equal(p2, camera2) def test_sampson_error(): f_matrix = np.array([[0, 0, 0], [0, 0, -1], [0, 1, 0]]) x = np.linspace(0, 10, 11) y = np.linspace(0, 10, 11) ones = np.ones(11) x1 = np.vstack((x, y, ones)) x2 = np.vstack((x + 1, y + 1, ones)) x3 = np.vstack((x + 1, y, ones)) error = sampson_error(x1, x2, f_matrix) gt_err = np.array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5])
assert_almost_equal(gt_err, error)
numpy.testing.assert_almost_equal
import pandas as pd import numpy as np import os from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.metrics import precision_recall_fscore_support import xgboost as xgb from tqdm import tqdm import argparse from pk_classifier.bootstrap import simple_tokenizer, TextSelector, f1_eval, update, read_in_bow, make_ids_per_test, \ split_train_val_test from pk_classifier.stats import plot_df def process_them(input_tuple, rounds, test_prop, out_path_results, out_path_figure, out_path_bootstrap, use_idf): all_features, all_labs = read_in_bow(input_tuple[0], input_tuple[1]) ids_per_test = make_ids_per_test(inp_df=all_labs) all_metrics_test = [] optimal_epochs = [] median_optimal_epochs = [] median_f1s = [] a = 0 for round_i in tqdm(np.arange(rounds)): rd_seed = 10042006 + round_i per = test_prop # ===================================================================================================== # Make splits: 60% train, 20% validation, 20% temp test # ====================================================================================================== x_train, x_val, x_test, y_train, y_val, y_test, pmids_train, pmids_val, pmids_test = \ split_train_val_test(features=all_features, labels=all_labs, test_size=per, seed=rd_seed) # ===================================================================================================== # Decide max number of iterations using early stopping criteria on the validation set # ====================================================================================================== balancing_factor = y_train.value_counts()["Not Relevant"] / y_train.value_counts()["Relevant"] if round_i == 0: print("Training with--- ", y_train.value_counts()["Relevant"], " ---Relevant instances") encoder = CountVectorizer(tokenizer=simple_tokenizer, ngram_range=(1, 1), lowercase=False, preprocessor=None, min_df=2) normalizer = TfidfTransformer(norm="l1", use_idf=use_idf) decoder = xgb.XGBClassifier(random_state=rd_seed, n_jobs=-1, n_estimators=2000, objective='binary:logistic', max_depth=4, learning_rate=0.1, colsample_bytree=1., scale_pos_weight=balancing_factor, nthread=-1) # Define encoding pipeline enc_pip = Pipeline([ ('encoder', FeatureUnion(transformer_list=[ ('bow', Pipeline([ ('selector', TextSelector('BoW_Ready', emb=False)), ('vect', encoder), ('norm', normalizer) ]) ) ])) ]) x_train_features = enc_pip.fit_transform(x_train) x_val_features = enc_pip.transform(x_val) if a == 0: print("Using: ", x_train_features.shape[1], "features") a = 1 eval_set = [(x_train_features, y_train), (x_val_features, y_val)] decoder.fit(x_train_features, y_train, eval_set=eval_set, verbose=False, early_stopping_rounds=200, eval_metric=f1_eval) optimal_epochs.append(decoder.best_ntree_limit) median_epochs = np.median(optimal_epochs) median_optimal_epochs.append(median_epochs) if round_i in np.arange(0, rounds, 20): print("Median number of epochs:", median_epochs) # ===================================================================================================== # Apply predictions to the temp test set # ====================================================================================================== x_test_encoded = enc_pip.transform(x_test) pred_test = decoder.predict(x_test_encoded) test_results = pd.DataFrame(pred_test == y_test.values, columns=['Result']) test_results['Result'] = test_results['Result'].astype(int) test_results['pmid'] = pmids_test.values """Update for output""" for index, x in test_results.iterrows(): ids_per_test = update(x, ids_per_test) precision_test, recall_test, f1_test, support_test = precision_recall_fscore_support(y_test, pred_test, average='binary', pos_label="Relevant") current_metrics_test = [precision_test, recall_test, f1_test] all_metrics_test.append(current_metrics_test) all_f1s = [x[2] for x in all_metrics_test] temp_median_f1 =
np.median(all_f1s)
numpy.median
import numpy as np from scipy.optimize import minimize from mushroom_rl.algorithms.policy_search.black_box_optimization import BlackBoxOptimization from mushroom_rl.utils.parameters import to_parameter from mushroom_rl.approximators import Regressor from mushroom_rl.approximators.parametric import LinearApproximator from mushroom_rl.features import Features from mushroom_rl.features.basis.polynomial import PolynomialBasis from mushroom_rl.distributions import GaussianCholeskyDistribution class MORE(BlackBoxOptimization): """ Model-Based Relative Entropy Stochastic Search algorithm. "Model-Based Relative Entropy Stochastic Search", Abdolmaleki, Abbas and <NAME> and <NAME> and <NAME> and <NAME> and <NAME>. 2015. """ def __init__(self, mdp_info, distribution, policy, eps, h0=-75, kappa=0.99, features=None): """ Constructor. Args: distribution (GaussianCholeskyDistribution): the distribution of policy parameters. eps ([float, Parameter]): the maximum admissible value for the Kullback-Leibler divergence between the new distribution and the previous one at each update step. h0 ([float, Parameter]): minimum exploration policy. kappa ([float, Parameter]): regularization parameter for the entropy decrease. """ self.eps = to_parameter(eps) self.h0 = to_parameter(h0) self.kappa = to_parameter(kappa) assert isinstance(distribution, GaussianCholeskyDistribution) poly_basis_quadratic = PolynomialBasis().generate(2, policy.weights_size) self.phi_quadratic_ = Features(basis_list=poly_basis_quadratic) self.regressor_quadratic = Regressor(LinearApproximator, input_shape=(len(poly_basis_quadratic),), output_shape=(1,)) poly_basis_linear = PolynomialBasis().generate(1, policy.weights_size) self.phi_linear_ = Features(basis_list=poly_basis_linear) self.regressor_linear = Regressor(LinearApproximator, input_shape=(len(poly_basis_linear),), output_shape=(1,)) self._add_save_attr(eps='primitive') self._add_save_attr(h0='primitive') self._add_save_attr(kappa='primitive') super().__init__(mdp_info, distribution, policy, features) def _update(self, Jep, theta): beta = self.kappa() * (self.distribution.entropy() - self.h0()) + self.h0() n = len(self.distribution._mu) dist_params = self.distribution.get_parameters() mu_t = dist_params[:n][:,np.newaxis] chol_sig_empty = np.zeros((n,n)) chol_sig_empty[np.tril_indices(n)] = dist_params[n:] sig_t = chol_sig_empty.dot(chol_sig_empty.T) R, r, r_0 = self._fit_quadratic_surrogate(theta, Jep, n) eta_omg_start = np.ones(2) res = minimize(MORE._dual_function, eta_omg_start, bounds=((
np.finfo(np.float32)
numpy.finfo
""" Functions to perform conversions between certain coordinate systems """ import math import warnings from scipy import linalg import numpy as np from scipy.spatial.transform import Rotation from utilities.Constants import EARTH_RADIUS # This takes geographic as a numpy vector of coordinates, or single coordinates # (latitude: degrees, longitude: degrees, altitude: meters) # It returns # (radius: meters, polar: radians, azimuthal: radians) from utilities import Vector def geographic_to_spherical(geographic: np.ndarray) -> np.ndarray: """ Converts coordinates in (latitude, longitude) format with angles in degrees to spherical coordinates with angles in radians :param geographic: An array of shape (N, 3) with rows being (latitude, longitude, altitude) :return: An array of shape (N, 3) with rows the spherical coordinates corresponding to the provided locations """ if np.any(geographic[..., 2] < - EARTH_RADIUS): warnings.warn(RuntimeWarning("Getting at least one geographic vectors with altitudes less than -EARTH_RADIUS")) spherical = np.empty_like(geographic, dtype=float) spherical[..., 0] = geographic[..., 2] + EARTH_RADIUS spherical[..., 1] = (90 + geographic[..., 0]) * math.pi / 180 spherical[..., 2] = geographic[..., 1] * math.pi / 180 return spherical.reshape(geographic.shape) # This performs the inverse of geographic_to_spherical def spherical_to_geographic(spherical: np.ndarray) -> np.ndarray: """ Converts spherical coordinates to geographic :param spherical: An array of size (N, 3) with rows corresponding to spherical coordinates :return: An array of size (N, 2) with rows being (latitude, longitude), which correspond to the provided coordinates """ if np.any(spherical[..., 0] < 0): warnings.warn(RuntimeWarning("Getting at least one spherical vectors with radius's less than 0")) geographic = np.empty_like(spherical, dtype=float) geographic[..., 0] = 180 / math.pi * spherical[..., 1] - 90 geographic[..., 1] = spherical[..., 2] * 180 / math.pi geographic[..., 2] = spherical[..., 0] - EARTH_RADIUS return geographic.reshape(spherical.shape) def spherical_to_cartesian(spherical: np.ndarray) -> np.ndarray: """Returns the cartesian form of the spherical vector. spherical_vector can be a numpy array where rows are spherical vectors (or a single vector)""" cartesian = np.empty_like(spherical, dtype=float) cartesian[..., 0] = spherical[..., 0] * np.sin(spherical[..., 1]) * np.cos(spherical[..., 2]) cartesian[..., 1] = spherical[..., 0] * np.sin(spherical[..., 1]) * np.sin(spherical[..., 2]) cartesian[..., 2] = spherical[..., 0] * np.cos(spherical[..., 1]) return cartesian def cartesian_to_spherical(cartesian: np.ndarray) -> np.ndarray: """Returns the spherical form of the cartesian vector. cartesian can be a numpy array where rows are cartesian vectors (or a single vector)""" spherical = np.empty_like(cartesian, dtype=float) r = linalg.norm(cartesian, axis=-1) spherical[..., 0] = r spherical[..., 1] = np.arccos(cartesian[..., 2] / r) spherical[..., 2] = np.arctan2(cartesian[..., 1], cartesian[..., 0]) return spherical.reshape(cartesian.shape) # Converts a spherical coordinate to a coordinate in the form of # (radius, 'distance in radians along path', 'normal distance in radians to path') def standard_to_path_component( standard: np.ndarray, cartesian_start: np.ndarray, cartesian_end: np.ndarray) -> np.ndarray: """ Converts coordinates to path component form (distance along path (along earths surface), distance normal to path (along earths surface), height (above earths surface)) :param standard: the coordinate or array of coordinates to rotate (in some standard form) :param cartesian_start: the coordinate of path start (spherical coordinates) :param cartesian_end: the coordinate of the path end (spherical coordinates) :return: coordinate or array of coordinates in path component form """ cartesian = standard path_components = np.empty_like(cartesian, dtype=float) normal_vec_to_plane = np.cross(cartesian_start, cartesian_end) unit_normal_vec = normal_vec_to_plane / linalg.norm(normal_vec_to_plane) vector_normal_component = Vector.row_dot_product(cartesian, unit_normal_vec) vectors_projected_onto_plane = cartesian - \ np.outer(vector_normal_component, unit_normal_vec) path_components[..., 1] = Vector.angle_between_vector_collections( cartesian_start, vectors_projected_onto_plane ) * np.sign(Vector.row_dot_product( np.cross(np.atleast_2d(cartesian_start), vectors_projected_onto_plane), normal_vec_to_plane )) path_components[..., 2] = Vector.angle_between_vector_collections( vectors_projected_onto_plane, cartesian ) * np.sign(vector_normal_component) path_components[..., 0] = linalg.norm(cartesian, axis=-1) return path_components def path_component_to_standard( path_components: np.ndarray, path_start_cartesian: np.ndarray, path_end_cartesian: np.ndarray) -> np.ndarray: """ NOTE: path_start and path_end cannot be at opposite poles (obviously, because then path between them is arbitrary) :param path_components: the coordinate or array of coordinates to rotate (in path component form) :param path_start_cartesian: the coordinate of path start (spherical coordinates) :param path_end_cartesian: the coordinate of the path end (spherical coordinates) :return: coordinate or array of coordinates in spherical coordinates """ normal_vector_to_path = np.cross(path_start_cartesian, path_end_cartesian) unit_normal_vector_to_path = normal_vector_to_path / linalg.norm(normal_vector_to_path) # Make sure we have positive rotation vector rotations = Rotation.from_rotvec(
np.outer(path_components[..., 1], unit_normal_vector_to_path)
numpy.outer
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Class of variatonal Gaussian Mixture Image models. It serves as a baseline for a hidden Potts-MRF for Bayesian unsupervised image segmentation. Author: <NAME> Date: 29-11-2018 """ import numpy as np import numpy.random as rnd from numpy.linalg import inv, cholesky, slogdet from scipy.misc import logsumexp from scipy.special import betaln, digamma, gammaln, multigammaln from scipy.spatial.distance import cdist from scipy.optimize import minimize from sklearn.cluster import KMeans from sklearn.neighbors import KNeighborsClassifier from sklearn.feature_extraction.image import extract_patches_2d import matplotlib.pyplot as plt class VariationalMixture(object): """ Superclass of variational mixture models. Methods are functions common to all submixture models. """ def multidigamma(self, n, p): """ Multivariate digamma function. This function is necessary for expectations and partition functions of Wishart distributions. See also: https://en.wikipedia.org/wiki/Multivariate_gamma_function Parameters ---------- nu : float Degrees of freedom. p : int Dimensionality. Returns ------- Pp : float p-th order multivariate digamma function. """ # Check for appropriate degree of freedom if not n > (p-1): raise ValueError('Degrees of freedom too low for dimensionality.') # Preallocate Pp = 0 # Sum from d=1 to D for d in range(1, p+1): # Digamma function of degrees of freedom and dimension Pp += digamma((n + 1 - d)/2) return Pp def log_partition_Wishart(self, W, n): """ Logarithmic partition function of the Wishart distribution. To compute variational expectations, the partition of the Wishart distribution is sometimes needed. The current computation follows Appendix B, equations B.78 to B.82 from Bishop's "Pattern Recognition & Machine Learning." Parameters ---------- W : array Positive definite, symmetric precision matrix. nu : int Degrees of freedom. Returns ------- B : float Partition of Wishart distribution. """ # Extract dimensionality D, D_ = W.shape # Check for symmetric matrix if not D == D_: raise ValueError('Matrix is not symmetric.') # Check for appropriate degree of freedom if not n > D-1: raise ValueError('Degrees of freedom too low for dimensionality.') # Compute partition function B = (-n/2)*slogdet(W)[1] - (n*D/2)*np.log(2) - multigammaln(n, D) return B def entropy_Wishart(self, W, n): """ Entropy of the Wishart distribution. To compute variational expectations, the entropy of the Wishart distribution is sometimes needed. The current computation follows Appendix B, equations B.78 to B.82 from Bishop's "Pattern Recognition & Machine Learning." Parameters ---------- W : array Positive definite, symmetric precision matrix. nu : int Degrees of freedom. Returns ------- H : float Entropy of Wishart distribution. """ # Extract dimensionality D, D_ = W.shape # Check for symmetric matrix if not D == D_: raise ValueError('Matrix is not symmetric.') # Check for appropriate degree of freedom if not n > D-1: raise ValueError('Degrees of freedom too low for dimensionality.') # Expected log-determinant of precision matrix E = self.multidigamma(n, D) + D*np.log(2) + slogdet(W)[1] # Entropy H = -self.log_partition_Wishart(W, n) - (n - D - 1)/2 * E + n*D/2 return H def distW(self, X, S): """ Compute weighted distance. Parameters ---------- X : array Vectors (N by D) or (H by W by D). W : array Weights (D by D). Returns ------- array Weighted distance for each vector. """ if not S.shape[0] == S.shape[1]: raise ValueError('Weight matrix not symmetric.') if not X.shape[-1] == S.shape[0]: raise ValueError('Dimensionality of data and weights mismatch.') if len(X.shape) == 2: # Shapes N, D = X.shape # Preallocate A = np.zeros((N,)) # Loop over samples for n in range(N): # Compute weighted inner product between vectors A[n] = X[n, :] @ S @ X[n, :].T elif len(X.shape) == 3: # Shape H, W, D = X.shape # Preallocate A = np.zeros((H, W)) # Loop over samples for h in range(H): for w in range(W): # Compute weighted inner product between vectors A[h, w] = X[h, w, :] @ S @ X[h, w, :].T return A def one_hot(self, A): """ Map array to pages with binary encodings. Parameters ---------- A : array 2-dimensional array of integers Returns ------- B : array (height by width by number of unique integers in A) 3-dimensional array with each page as an indicator of value in A. """ # Unique values labels = np.unique(A) # Preallocate new array B = np.zeros((*A.shape, len(labels))) # Loop over unique values for i, label in enumerate(labels): B[:, :, i] = (A == label) return B class VariationalGaussianMixture(VariationalMixture): """ Variational Gaussian Mixture Image model. This implementation multivariate images (height by width by channel). It is based on the RPubs note by <NAME>: https://rpubs.com/cakapourani/variational-bayes-gmm """ def __init__(self, num_channels=1, num_components=2, init_params='nn', max_iter=10, tol=1e-5): """ Model-specific constructors. Parameters ---------- num_channels : int Number of channels of image (def: 1). num_components : int Number of components (def: 2). theta0 : tuple Prior hyperparameters. max_iter : int Maximum number of iterations to run for (def: 10). tol : float Tolerance on change in x-value (def: 1e-5). Returns ------- None """ # Store data dimensionality if num_channels >= 1: self.D = num_channels else: raise ValueError('Number of channels must be larger than 0.') # Store model parameters if num_components >= 2: self.K = num_components else: raise ValueError('Too few components specified') # Optimization parameters self.init_params = init_params self.max_iter = max_iter self.tol = tol # Set prior hyperparameters self.set_prior_hyperparameters(D=num_channels, K=num_components) def set_prior_hyperparameters(self, D, K, a0=np.array([0.1]), b0=np.array([0.1]), n0=np.array([2.0]), m0=np.array([0.0]), W0=np.array([1.0])): """ Set hyperparameters of prior distributions. Default prior hyperparameters are minimally informative symmetric parameters. Parameters ---------- D : int Dimensionality of data. K : int Number of components. a0 : float / array (components by None) Hyperparameters of Dirichlet distribution on component weights. b0 : float / array (components by None) Scale parameters for hypermean normal distribution. n0 : array (components by None) Degrees of freedom for Wishart precision prior. m0 : array (components by dimensions) Hypermeans. W0 : array (dimensions by dimensions by components) Wishart precision parameters. Returns ------- theta : tuple """ # Expand alpha's if necessary if not a0.shape[0] == K: a0 = np.tile(a0[0], (K,)) # Expand beta's if necessary if not b0.shape[0] == K: b0 = np.tile(b0[0], (K,)) # Expand nu's if necessary if not n0.shape[0] == K: # Check for sufficient degrees of freedom if n0[0] < D: print('Cannot set Wishart degrees of freedom lower than data \ dimensionality.\n Setting it to data dim.') n0 = np.tile(D, (K,)) else: n0 = np.tile(n0[0], (K,)) # Expand hypermeans if necessary if not np.all(m0.shape == (K, D)): # If mean vector given, replicate to each component if len(m0.shape) == 2: if m0.shape[1] == D: m0 = np.tile(m0, (K, 1)) else: m0 = np.tile(m0[0], (K, D)) # Expand hypermeans if necessary if not np.all(W0.shape == (D, D, K)): # If single covariance matrix given, replicate to each component if len(W0.shape) == 2: if np.all(m0.shape[:2] == (D, D)): W0 = np.tile(W0, (1, 1, K)) else: W0_ = np.zeros((D, D, K)) for k in range(K): W0_[:, :, k] = W0[0]*np.eye(D) # Store tupled parameters as model attribute self.theta0 = (a0, b0, n0, m0, W0_) def initialize_posteriors(self, X, Y): """ Initialize posterior hyperparameters Parameters ---------- X : array Observed image (height by width by channels) Returns ------- theta : tuple Set of parameters. """ # Current shape H, W, D = X.shape # Reshape arrays X = X.reshape((H*W, D)) Y = Y.reshape((H*W, self.K)) if self.init_params == 'random': # Dirichlet concentration hyperparameters at = np.ones((self.K,))*(H*W)/2 # Normal precision-scale hyperparameters bt = np.ones((self.K,))*(H*W)/2 # Wishart degrees of freedom nt = np.ones((self.K,))*(H*W)/2 mt = np.zeros((self.K, D)) Wt = np.zeros((D, D, self.K)) for k in range(self.K): # Hypermeans mt[k, :] = np.mean(X, axis=0) + rnd.randn(1, D)*.1 # Hyperprecisions Wt[:, :, k] = np.cov(X.T) / bt[k] + rnd.randn(D, D)*.1 # Initialize variational posterior responsibilities rho = np.ones((H, W, self.K)) / self.K elif self.init_params in ('kmeans', 'k-means'): # Fit k-means to data and obtain cluster assignment label = KMeans(n_clusters=self.K, n_init=1).fit(X).labels_ # Set rho based on cluster labels rho = np.zeros((H*W, self.K)) rho[np.arange(H*W), label] = 1 # Dirichlet concentration hyperparameters at = np.sum(rho, axis=0) # Normal precision-scale hyperparameters bt = np.sum(rho, axis=0) # Wishart degrees of freedom nt = np.sum(rho, axis=0) mt = np.zeros((self.K, D)) Wt = np.zeros((D, D, self.K)) for k in range(self.K): # Hypermeans mt[k, :] = np.sum(rho[:, [k]] * X, axis=0) / np.sum(rho[:, k]) # Weighted covariance C = (rho[:, [k]] * (X - mt[k, :])).T @ (X - mt[k, :]) # Check for zero precision C = np.maximum(1e-24, C) # Set hyperprecisions if D == 1: Wt[:, :, k] = 1 / (nt[k] * C) else: Wt[:, :, k] = inv(nt[k] * C) # Reshape responsibilities rho = rho.reshape((H, W, self.K)) elif self.init_params in ('nn', 'knn'): # Observation indicator vector O = np.any(Y == 1, axis=1) if np.sum(O) == 0.0: raise ValueError('Cannot use \'nn\' without labels.') # Call instance of k-nearest neighbour classifier kNN = KNeighborsClassifier(n_neighbors=1, weights='distance') # Fit classifier to labeled data kNN.fit(X[O, :], np.argmax(Y[O, :], axis=1)) # Set responsibilities based on kNN prediction rho = np.zeros((H*W, self.K)) rho[~O, :] = kNN.predict_proba(X[~O, :]) rho[O, :] = Y[O, :].astype('float64') # Concentration hyperparameters at = np.sum(rho, axis=0) # Precision-scale hyperparameters bt = np.sum(rho, axis=0) # Wishart degrees of freedom nt = np.sum(rho, axis=0) mt = np.zeros((self.K, D)) Wt = np.zeros((D, D, self.K)) for k in range(self.K): # Hypermeans mt[k, :] = X[Y[:, k] == 1, :] # Hyperprecisions Wt[:, :, k] = np.eye(D) # Reshape responsibilities rho = rho.reshape((H, W, self.K)) else: raise ValueError('Provided method not recognized.') return (at, bt, nt, mt, Wt), rho def free_energy(self, X, rho, thetat, report=True): """ Compute free energy term to monitor progress. Parameters ---------- X : array Observed image (height by width by channels). rho : array Array of variational parameters (height by width by channels). thetat : array Parameters of variational posteriors. theta0 : array Parameters of variational priors. report : bool Print value of free energy function. Returns ------- rho : array Updated array of variational parameters. """ # Shapes H, W, D = X.shape # Reshape arrays X = X.reshape((H*W, D)) rho = rho.reshape((H*W, self.K)) # Unpack parameter sets a0, b0, n0, m0, W0 = self.theta0 at, bt, nt, mt, Wt = thetat # Preallocate terms for energy function E1 = 0 E2 = 0 E3 = 0 E4 = 0 E5 = 0 E6 = 0 E7 = 0 # Loop over classes for k in range(self.K): ''' Convenience variables ''' # Proportion assigned to each component Nk = np.sum(rho[:, k], axis=0) # Responsibility-weighted mean xk = np.sum(rho[:, [k]] * X, axis=0) / Nk # Reponsibility-weighted variance Sk = ((X - xk) * rho[:, [k]]).T @ (X - xk) / Nk # Mahalanobis distance from hypermean mWm = (mt[k, :] - m0[k, :]).T @ Wt[:, :, k] @ (mt[k, :] - m0[k, :]) # Mahalanobis distance from responsibility-weighted mean xWx = (xk - mt[k, :]) @ Wt[:, :, k] @ (xk - mt[k, :]).T # Entropy-based terms Elog_pik = digamma(at[k]) - digamma(np.sum(at)) Elog_Lak = (D*np.log(2) + slogdet(Wt[:, :, k])[1] + self.multidigamma(nt[k], D)) ''' Energy function ''' # First term E1 += Nk/2*(Elog_Lak - D / bt[k] - nt[k]*(np.trace(Sk @ Wt[:, :, k]) + xWx) - D*np.log(2*np.pi)) # Second term E2 += np.sum(rho[:, k] * Elog_pik, axis=0) # Third term E3 += (a0[k] - 1)*Elog_pik + (gammaln(np.sum(a0)) - np.sum(gammaln(a0))) / self.K # Fourth term E4 += 1/2*(D*np.log(b0[k] / (2*np.pi)) + Elog_Lak - D*b0[k]/bt[k] - b0[k]*nt[k]*mWm + (n0[k] - D - 1)*Elog_Lak - 2*self.log_partition_Wishart(Wt[:, :, k], nt[k]) + nt[k]*np.trace(inv(W0[:, :, k])*Wt[:, :, k])) # Ignore underflow error from log rho with np.errstate(under='ignore') and np.errstate(divide='ignore'): # Set -inf to most negative number lrho = np.maximum(np.log(rho[:, k]), np.finfo(rho.dtype).min) # Fifth term E5 += np.sum(rho[:, k] * lrho, axis=0) # Sixth term E6 += (at[k] - 1)*Elog_pik + (gammaln(np.sum(at)) - np.sum(gammaln(at))) / self.K # Seventh term E7 += (Elog_Lak/2 + D/2*np.log(bt[k] / (2*np.pi)) - D/2 - self.entropy_Wishart(Wt[:, :, k], nt[k])) # Compute free energy term F = E1 + E2 + E3 + E4 - E5 - E6 - E7 # Print free energy if report: print('Free energy = ' + str(F)) return F def expectation_step(self, X, Y, rho, thetat, savefn=''): """ Perform expectation step. Parameters ---------- X : array Observed image (height by width by channels). thetat : array Current iteration of parameters of variational posteriors. Returns ------- rho : array Updated array of variational parameters / responsibilities. """ # Shape of variational parameter array H, W, D = X.shape # Reshape arrays X = X.reshape((H*W, D)) Y = Y.reshape((H*W, self.K)) rho = rho.reshape((H*W, self.K)) # Observation indicator vector O = np.any(Y != 0, axis=1) # Unpack tuple of hyperparameters at, bt, nt, mt, Wt = thetat # Initialize logarithmic rho lrho = np.zeros((np.sum(~O), self.K)) for k in range(self.K): # Compute expected log mixing coefficient E1 = digamma(at[k]) - digamma(np.sum(at)) # Compute exponentiated expected log precision E2 = (D*np.log(2) + slog_det(Wt[:, :, k])[1] + self.multidigamma(nt[k], D)) # Compute expected hypermean and hyperprecision E3 = D/bt[k] + self.distW(X[~O, :] - mt[k, :], nt[k]*Wt[:, :, k]) # Update variational parameter at current pixels lrho[:, k] = E1 + E2/2 - E3/2 # Subtract largest number from log_rho lrho = lrho - np.max(lrho, axis=1)[:, np.newaxis] # Exponentiate and normalize rho[~O, :] = np.exp(lrho) / np.sum(np.exp(lrho), axis=1)[:, np.newaxis] # Check for underflow problems if np.any(np.sum(rho, axis=1) == 0.0): raise RuntimeError('Variational parameter underflow.') return rho.reshape((H, W, self.K)) def maximization_step(self, X, rho, thetat): """ Perform maximization step from variational-Bayes-EM. Parameters ---------- X : array Observed image (height by width by channels). rho : array Array of variational parameters (height by width by classes). thetat : array Current iteration of hyperparameters of posteriors. Returns ------- thetat : array Next iteration of hyperparameters of posteriors. """ # Shape of image H, W, D = X.shape # Reshape arrays X = X.reshape((H*W, D)) rho = rho.reshape((H*W, self.K)) # Unpack parameter sets a0, b0, n0, m0, W0 = self.theta0 at, bt, nt, mt, Wt = thetat # Iterate over classes for k in range(self.K): # Total responsibility for class k Nk = np.sum(rho[:, k], axis=0) # Responsibility-weighted mean for class k xk = np.sum(rho[:, [k]] * X, axis=0) / Nk # Responsibility-weighted covariance for class k Sk = ((X - xk) * rho[:, [k]]).T @ (X - xk) / Nk # Update alpha at[k] = a0[k] + Nk # Update nu nt[k] = n0[k] + Nk # Update beta bt[k] = b0[k] + Nk # Update hypermean mt[k, :] = (b0[k]*m0[k, :] + Nk*xk) / (b0[k] + Nk) # Update hyperprecision Wt[:, :, k] = inv(inv(W0[:, :, k]) + Nk*Sk + (b0[k]*Nk) / bt[k] * (xk - m0[k, :]).T @ (xk - m0[k, :])) return at, bt, nt, mt, Wt def expectation_maximization(self, X, Y): """ Perform Variational Bayes Expectation-Maximization. Parameters ---------- X : array (instances by features) Data array. Y : array Observed labels (height by width by classes). Returns ------- rho : array (instances by components) Variational parameters of posterior for label image. """ # Get shape of image H, W, D = X.shape # Initialize posterior hyperparameters thetat, rho = self.initialize_posteriors(X, Y) # Initialize old energy variable F_ = np.inf for t in range(self.max_iter): # Monitor progress every tenth iteration if t % (self.max_iter/10) == 0: # Report progress print('Iteration ' + '{0:03}'.format(t+1) + '/' + str(self.max_iter) + '\t', end='') # Compute free energy to monitor progress F = self.free_energy(X, rho, thetat, report=True) if np.abs(F - F_) <= self.tol: print('Step size is below tolerance threshold.') break # Update old energy F_ = F # Expectation step rho = self.expectation_step(X, Y, rho, thetat) # Expectation step thetat = self.maximization_step(X, rho, thetat) # Return segmentation along with estimated parameters return rho, thetat def segment(self, X, Y=None): """ Fit model to data and segment image. Parameters ---------- X : array. Observed image (height by width by channels). Y : array Observed labels (height by width by classes). Returns ------- pred : array Segmentation produced by the model. post : array Posterior indicator distributions. theta : tuple of arrays Posterior hyperparameters of parameter distributions. """ # Check shape of image H, W, D = X.shape # Check if dimensionality of given data matches prior dimensionality. if not self.D == D: # Report print('Re-setting priors.') # Set dimensionality attribute self.D = D # Set prior hyperparameters self.set_prior_hyperparameters(D=D, K=self.K) # If no Y is provided if Y is None: Y = np.zeros((H, W, self.K)) # Perform VB-EM for segmenting the image post, params = self.expectation_maximization(X, Y) # Compute most likely class pred = np.argmax(post, axis=2) # Return segmented image, variational posteriors and parameters return pred, post, params class VariationalHiddenPotts(VariationalMixture): """ Variational Gaussian Mixture model with a hidden Potts-Markov Random Field. This implementation multivariate images (height by width by channel). It is based on the RPubs note by <NAME>: https://rpubs.com/cakapourani/variational-bayes-gmm and the paper "Variational Bayes for estimating the parameters of a hidden Potts model" by McGrory, Titterington, Reeves and Pettitt (2008). """ def __init__(self, num_channels=1, num_components=2, tissue_specific=False, init_params='kmeans', max_iter=10, tol=1e-5): """ Model-specific constructors. Parameters ---------- num_channels : int Number of channels of image (def: 1). num_components : int Number of components (def: 2). tissue_specific : bool Whether to model each tissue's smoothness separately (def: False). init_params : str How to initialize posterior parameters. Options: 'random', 'kmeans', 'nn' (def: 'kmeans'). max_iter : int Maximum number of iterations to run for (def: 10). tol : float Tolerance on change in x-value (def: 1e-5). Returns ------- None """ # Store data dimensionality if num_channels >= 1: self.D = num_channels else: raise ValueError('Number of channels must be larger than 0.') # Store model parameters if num_components >= 2: self.K = num_components else: raise ValueError('Too few components specified') # Whether to use tissue-specific smoothness parameters self.Bk = tissue_specific # Optimization parameters self.init_params = init_params self.max_iter = max_iter self.tol = tol # Set prior hyperparameters self.set_prior_hyperparameters(D=num_channels, K=num_components) def set_prior_hyperparameters(self, D, K, a0=np.array([0.1]), b0=np.array([0.1]), n0=np.array([2.0]), m0=np.array([0.0]), W0=np.array([1.0])): """ Set hyperparameters of prior distributions. Default prior hyperparameters are minimally informative symmetric parameters. Parameters ---------- D : int Dimensionality of data. K : int Number of components. a0 : float / array (components by None) Hyperparameters of Dirichlet distribution on component weights. b0 : float / array (components by None) Scale parameters for hypermean normal distribution. n0 : array (components by None) Degrees of freedom for Wishart precision prior. m0 : array (components by dimensions) Hypermeans. W0 : array (dimensions by dimensions by components) Wishart precision parameters. Returns ------- theta : tuple """ # Expand alpha's if necessary if not a0.shape[0] == K: a0 = np.tile(a0[0], (K,)) # Expand beta's if necessary if not b0.shape[0] == K: b0 = np.tile(b0[0], (K,)) # Expand nu's if necessary if not n0.shape[0] == K: # Check for sufficient degrees of freedom if n0[0] < D: print('Cannot set Wishart degrees of freedom lower than data \ dimensionality.\n Setting it to data dim.') n0 = np.tile(D, (K,)) else: n0 = np.tile(n0[0], (K,)) # Expand hypermeans if necessary if not np.all(m0.shape == (K, D)): # If mean vector given, replicate to each component if len(m0.shape) == 2: if m0.shape[1] == D: m0 = np.tile(m0, (K, 1)) else: m0 = np.tile(m0[0], (K, D)) # Expand hypermeans if necessary if not np.all(W0.shape == (D, D, K)): # If single covariance matrix given, replicate to each component if len(W0.shape) == 2: if np.all(m0.shape[:2] == (D, D)): W0 = np.tile(W0, (1, 1, K)) else: W0_ = np.zeros((D, D, K)) for k in range(K): W0_[:, :, k] = W0[0]*np.eye(D) # Store tupled parameters as model attribute self.theta0 = (a0, b0, n0, m0, W0_) def initialize_posteriors(self, X, Y): """ Initialize posterior hyperparameters Parameters ---------- X : array Observed image (height by width by channels) Returns ------- theta : tuple Set of parameters. """ # Current shape H, W, D = X.shape # Reshape arrays X = X.reshape((H*W, D)) Y = Y.reshape((H*W, self.K)) if self.init_params == 'random': # Dirichlet concentration hyperparameters at = np.ones((self.K,))*(H*W)/2 # Normal precision-scale hyperparameters bt = np.ones((self.K,))*(H*W)/2 # Wishart degrees of freedom nt = np.ones((self.K,))*(H*W)/2 mt = np.zeros((self.K, D)) Wt = np.zeros((D, D, self.K)) for k in range(self.K): # Hypermeans mt[k, :] = np.mean(X, axis=0) + rnd.randn(1, D)*.1 # Hyperprecisions Wt[:, :, k] = np.cov(X.T) / bt[k] + rnd.randn(D, D)*.1 # Initialize variational posterior responsibilities rho = np.ones((H, W, self.K)) / self.K elif self.init_params in ('kmeans', 'k-means'): # Fit k-means to data and obtain cluster assignment label = KMeans(n_clusters=self.K, n_init=1).fit(X).labels_ # Set rho based on cluster labels rho = np.zeros((H*W, self.K)) rho[np.arange(H*W), label] = 1 # Dirichlet concentration hyperparameters at = np.sum(rho, axis=0) # Normal precision-scale hyperparameters bt = np.sum(rho, axis=0) # Wishart degrees of freedom nt = np.sum(rho, axis=0) mt = np.zeros((self.K, D)) Wt = np.zeros((D, D, self.K)) for k in range(self.K): # Hypermeans mt[k, :] = np.sum(rho[:, [k]] * X, axis=0) / np.sum(rho[:, k]) # Hyperprecisions Wt[:, :, k] = np.eye(D) # Reshape responsibilities rho = rho.reshape((H, W, self.K)) elif self.init_params in ('nn', 'knn'): # Observation indicator vector O = np.any(Y == 1, axis=1) if np.sum(O) == 0.0: raise ValueError('Cannot use \'nn\' without labels.') # Call instance of k-nearest neighbour classifier kNN = KNeighborsClassifier(n_neighbors=1) # Fit classifier to labeled data kNN.fit(X[O, :], np.argmax(Y[O, :], axis=1)) # Set responsibilities based on kNN prediction rho = np.zeros((H*W, self.K)) rho[~O, :] = kNN.predict_proba(X[~O, :]) rho[O, :] = Y[O, :].astype('float64') # Concentration hyperparameters at = np.sum(rho, axis=0) # Precision-scale hyperparameters bt = np.sum(rho, axis=0) # Wishart degrees of freedom nt = np.sum(rho, axis=0) mt = np.zeros((self.K, D)) Wt = np.zeros((D, D, self.K)) for k in range(self.K): # Focuse hypermeans on labeled pixels mt[k, :] = np.mean(X[Y[:, k] == 1, :], axis=0) # Hyperprecisions Wt[:, :, k] = np.eye(D) # Reshape responsibilities rho = rho.reshape((H, W, self.K)) else: raise ValueError('Provided method not recognized.') return (at, bt, nt, mt, Wt), rho def neighbourhood(self, A, index, pad=False): """ Extract a neighbourhood of pixels around current pixel. Parameters ---------- A : array Array from which to extract the pixel's neighbourhood. index : [int, int] Row and column index of current pixel. pad : bool Whether to pad a border with zeros to the array (def: False) Returns ------- delta_i : vector of neighbours of current pixel """ if pad: # Check for list index if not isinstance(index, list): raise ValueError('If padding, index must be a list.') # Pad array with zeros A = np.pad(A, [1, 1], mode='constant', constant_values=0) # Correct index due to padding index[0] += 1 index[1] += 1 # Preallocate neighbourhood list delta_i = [] # Left delta_i.append(A[index[0]-1, index[1]]) # Top delta_i.append(A[index[0], index[1]-1]) # Right delta_i.append(A[index[0]+1, index[1]]) # Bottom delta_i.append(A[index[0], index[1]+1]) return np.array(delta_i) def mean_field_Potts(self, beta, Z): r""" Mean-field variational approximation to Potts log-likelihood function. logp(z_i | z_{d_i}, beta) = \sum_{k=1}^{K} beta_k * z_{ik} \sum_{j \in \delta_{ik}} z_{jk} - \log \sum_{z_{i'}} \exp(\sum_{k=1}^{K} beta_k*z_{i'k} \sum_{j \in \delta_{ik}} z_{jk}) Parameters ---------- beta : float Smoothing parameter / granularity coefficient Z : array (height x width x number of classes) Label field to fit Returns ------- nlogq : float Negative log-likelihood of current label field given current beta. """ # Shape H, W, K = Z.shape # Test for binary label image for k in range(K): if not np.all(np.unique(Z[:, :, k]) == [0, 1]): raise ValueError("Label field is not binary in page " + str(k)) # Pad array to avoid repeated padding during neighbourhood extraction Z0 = np.pad(Z, [(1, 1), (1, 1), (0, 0)], mode='constant', constant_values=0) if self.Bk: # Initialize intermediate terms chi_i = 0 ksi_i = 0 # Select current class for k in range(K): # Extract neighbourhoods d_ik = extract_patches_2d(Z0[:, :, k], patch_size=(3, 3)) # Compute sum over neighbourhood d_ik = np.sum(d_ik, axis=(1, 2)) # First sum is neighbourhood comparison chi_i += beta[k] * Z[:, :, k].reshape((-1,)) * d_ik # Second sum is purely over neighbourhood ksi_i += np.exp(beta[k] * d_ik) # Update negative log-likelihood nll = np.sum(-chi_i + np.log(ksi_i), axis=0) return nll else: # Initialize intermediate terms chi_i = 0 ksi_i = 0 # Select current class for k in range(K): # Extract neighbourhoods d_ik = extract_patches_2d(Z0[:, :, k], patch_size=(3, 3)) # Compute sum over neighbourhood d_ik = np.sum(d_ik, axis=(1, 2)) # First sum is neighbourhood comparison chi_i += beta * Z[:, :, k].reshape((-1,)) * d_ik # Second sum is purely over neighbourhood ksi_i +=
np.exp(beta * d_ik)
numpy.exp
import os import sys import torch import numpy as np import importlib import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import linear_sum_assignment import trimesh from colors import colors from sklearn.metrics.pairwise import pairwise_distances def printout(flog, strout): print(strout) flog.write(strout+'\n') def get_model_module(model_def): importlib.invalidate_caches() return importlib.import_module(model_def) def worker_init_fn(worker_id): """ The function is designed for pytorch multi-process dataloader. Note that we use the pytorch random generator to generate a base_seed. Please try to be consistent. References: https://pytorch.org/docs/stable/notes/faq.html#dataloader-workers-random-seed """ base_seed = torch.IntTensor(1).random_().item() #print(worker_id, base_seed) np.random.seed(base_seed + worker_id) def render_pc(out_fn, pc, figsize=(8, 8)): fig = plt.figure(figsize=figsize) ax = fig.add_subplot(1, 1, 1, projection='3d') ax.view_init(elev=20, azim=60) x = pc[:, 0] y = pc[:, 2] z = pc[:, 1] ax.scatter(x, y, z, marker='.') miv = np.min([np.min(x), np.min(y), np.min(z)]) # Multiply with 0.7 to squeeze free-space. mav = np.max([np.max(x), np.max(y), np.max(z)]) ax.set_xlim(miv, mav) ax.set_ylim(miv, mav) ax.set_zlim(miv, mav) plt.tight_layout() fig.savefig(out_fn, bbox_inches='tight') plt.close(fig) def convert_color_to_hexcode(rgb): r, g, b = rgb return '#%02x%02x%02x' % (int(r*255), int(g*255), int(b*255)) def render_part_pcs(pcs_list, title_list=None, out_fn=None, \ subplotsize=(1, 1), figsize=(8, 8), azim=60, elev=20, scale=0.3): num_pcs = len(pcs_list) fig = plt.figure(figsize=figsize) for k in range(num_pcs): pcs = pcs_list[k] ax = fig.add_subplot(subplotsize[0], subplotsize[1], k+1, projection='3d') ax.view_init(elev=elev, azim=azim) xs = []; ys = []; zs = []; for i in range(pcs.shape[0]): x = pcs[i, :, 0] y = pcs[i, :, 2] z = pcs[i, :, 1] xs.append(x) ys.append(y) zs.append(z) if out_fn is None: ax.scatter(x, y, z, marker='.', s=scale, c=convert_color_to_hexcode(colors[i % len(colors)])) else: ax.scatter(x, y, z, marker='.', c=convert_color_to_hexcode(colors[i % len(colors)])) xs = np.concatenate(xs, axis=0) ys = np.concatenate(ys, axis=0) zs = np.concatenate(zs, axis=0) miv = np.min([np.min(xs), np.min(ys), np.min(zs)]) mav = np.max([np.max(xs), np.max(ys), np.max(zs)]) ax.set_xlim(miv, mav) ax.set_ylim(miv, mav) ax.set_zlim(miv, mav) if title_list is not None: ax.set_title(title_list[k]) plt.tight_layout() if out_fn is not None: fig.savefig(out_fn, bbox_inches='tight') plt.close(fig) else: plt.show() def export_pc(out_fn, pc): with open(out_fn, 'w') as fout: for i in range(pc.shape[0]): fout.write('v %f %f %f\n' % (pc[i, 0], pc[i, 1], pc[i, 2])) def export_part_pcs(out_dir, pcs): os.mkdir(out_dir) num_part = pcs.shape[0] num_point = pcs.shape[1] for i in range(num_part): with open(os.path.join(out_dir, 'part-%02d.obj' % i), 'w') as fout: for j in range(num_point): fout.write('v %f %f %f\n' % (pcs[i, j, 0], pcs[i, j, 1], pcs[i, j, 2])) # out shape: (label_count, in shape) def one_hot(inp, label_count): out = torch.zeros(label_count, inp.numel(), dtype=torch.uint8, device=inp.device) out[inp.view(-1), torch.arange(out.shape[1])] = 1 out = out.view((label_count,) + inp.shape) return out def collate_feats(b): return list(zip(*b)) # row_counts, col_counts: row and column counts of each distance matrix (assumed to be full if given) def linear_assignment(distance_mat, row_counts=None, col_counts=None): batch_ind = [] row_ind = [] col_ind = [] for i in range(distance_mat.shape[0]): # print(f'{i} / {distance_mat.shape[0]}') dmat = distance_mat[i, :, :] if row_counts is not None: dmat = dmat[:row_counts[i], :] if col_counts is not None: dmat = dmat[:, :col_counts[i]] rind, cind = linear_sum_assignment(dmat.to('cpu').numpy()) rind = list(rind) cind = list(cind) if len(rind) > 0: rind, cind = zip(*sorted(zip(rind, cind))) rind = list(rind) cind = list(cind) # complete the assignemnt for any remaining non-active elements (in case row_count or col_count was given), # by assigning them randomly #if len(rind) < distance_mat.shape[1]: # rind.extend(set(range(distance_mat.shape[1])).difference(rind)) # cind.extend(set(range(distance_mat.shape[1])).difference(cind)) batch_ind += [i]*len(rind) row_ind += rind col_ind += cind return batch_ind, row_ind, col_ind def load_pts(fn): with open(fn, 'r') as fin: lines = [item.rstrip() for item in fin] pts = np.array([[float(line.split()[0]), float(line.split()[1]), float(line.split()[2])] for line in lines], dtype=np.float32) return pts def export_pts(out, v): with open(out, 'w') as fout: for i in range(v.shape[0]): fout.write('%f %f %f\n' % (v[i, 0], v[i, 1], v[i, 2])) def load_obj(fn): fin = open(fn, 'r') lines = [line.rstrip() for line in fin] fin.close() vertices = []; faces = []; for line in lines: if line.startswith('v '): vertices.append(np.float32(line.split()[1:4])) elif line.startswith('f '): faces.append(np.int32([item.split('/')[0] for item in line.split()[1:4]])) if len(faces) > 0: f = np.vstack(faces) else: f = None v = np.vstack(vertices) return v, f def export_obj(out, v, f): with open(out, 'w') as fout: for i in range(v.shape[0]): fout.write('v %f %f %f\n' % (v[i, 0], v[i, 1], v[i, 2])) for i in range(f.shape[0]): fout.write('f %d %d %d\n' % (f[i, 0], f[i, 1], f[i, 2])) def qrot(q, v): """ Rotate vector(s) v about the rotation described by quaternion(s) q. Expects a tensor of shape (*, 4) for q and a tensor of shape (*, 3) for v, where * denotes any number of dimensions. Returns a tensor of shape (*, 3). """ assert q.shape[-1] == 4 assert v.shape[-1] == 3 assert q.shape[:-1] == v.shape[:-1] original_shape = list(v.shape) q = q.view(-1, 4) v = v.view(-1, 3) qvec = q[:, 1:] uv = torch.cross(qvec, v, dim=1) uuv = torch.cross(qvec, uv, dim=1) return (v + 2 * (q[:, :1] * uv + uuv)).view(original_shape) # pc is N x 3, feat is 10-dim def transform_pc(pc, feat): num_point = pc.size(0) center = feat[:3] shape = feat[3:6] quat = feat[6:] pc = pc * shape.repeat(num_point, 1) pc = qrot(quat.repeat(num_point, 1), pc) pc = pc + center.repeat(num_point, 1) return pc # pc is N x 3, feat is B x 10-dim def transform_pc_batch(pc, feat, anchor=False): batch_size = feat.size(0) num_point = pc.size(0) pc = pc.repeat(batch_size, 1, 1) center = feat[:, :3].unsqueeze(dim=1).repeat(1, num_point, 1) shape = feat[:, 3:6].unsqueeze(dim=1).repeat(1, num_point, 1) quat = feat[:, 6:].unsqueeze(dim=1).repeat(1, num_point, 1) if not anchor: pc = pc * shape pc = qrot(quat.view(-1, 4), pc.view(-1, 3)).view(batch_size, num_point, 3) if not anchor: pc = pc + center return pc def get_surface_reweighting(xyz, cube_num_point): x = xyz[0] y = xyz[1] z = xyz[2] assert cube_num_point % 6 == 0, 'ERROR: cube_num_point %d must be dividable by 6!' % cube_num_point np = cube_num_point // 6 out = torch.cat([(x*y).repeat(np*2), (y*z).repeat(np*2), (x*z).repeat(np*2)]) out = out / (out.sum() + 1e-12) return out def get_surface_reweighting_batch(xyz, cube_num_point): x = xyz[:, 0] y = xyz[:, 1] z = xyz[:, 2] assert cube_num_point % 6 == 0, 'ERROR: cube_num_point %d must be dividable by 6!' % cube_num_point np = cube_num_point // 6 out = torch.cat([(x*y).unsqueeze(dim=1).repeat(1, np*2), \ (y*z).unsqueeze(dim=1).repeat(1, np*2), \ (x*z).unsqueeze(dim=1).repeat(1, np*2)], dim=1) out = out / (out.sum(dim=1).unsqueeze(dim=1) + 1e-12) return out def gen_obb_mesh(obbs): # load cube cube_v, cube_f = load_obj('cube.obj') all_v = []; all_f = []; vid = 0; for pid in range(obbs.shape[0]): p = obbs[pid, :] center = p[0: 3] lengths = p[3: 6] dir_1 = p[6: 9] dir_2 = p[9: ] dir_1 = dir_1/
np.linalg.norm(dir_1)
numpy.linalg.norm
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= import unittest from builtins import str from singa import tensor from singa import singa_wrap as singa from singa import autograd from singa import layer from singa import singa_wrap from cuda_helper import gpu_dev, cpu_dev import numpy as np autograd.training = True CTensor = singa.Tensor dy = CTensor([2, 1, 2, 2]) singa.Gaussian(0.0, 1.0, dy) def _tuple_to_string(t): lt = [str(x) for x in t] return '(' + ', '.join(lt) + ')' def axis_helper(y_shape, x_shape): """ check which axes the x has been broadcasted Args: y_shape: the shape of result x_shape: the shape of x Return: a tuple refering the axes """ res = [] j = len(x_shape) - 1 for i in range(len(y_shape) - 1, -1, -1): if j < 0 or x_shape[j] != y_shape[i]: res.append(i) j -= 1 return tuple(res[::-1]) def prepare_inputs_targets_for_rnn_test(dev): x_0 = np.random.random((2, 3)).astype(np.float32) x_1 = np.random.random((2, 3)).astype(np.float32) x_2 = np.random.random((2, 3)).astype(np.float32) h_0 = np.zeros((2, 2)).astype(np.float32) t_0 = np.random.random((2, 2)).astype(np.float32) t_1 = np.random.random((2, 2)).astype(np.float32) t_2 = np.random.random((2, 2)).astype(np.float32) x0 = tensor.Tensor(device=dev, data=x_0) x1 = tensor.Tensor(device=dev, data=x_1) x2 = tensor.Tensor(device=dev, data=x_2) h0 = tensor.Tensor(device=dev, data=h_0) t0 = tensor.Tensor(device=dev, data=t_0) t1 = tensor.Tensor(device=dev, data=t_1) t2 = tensor.Tensor(device=dev, data=t_2) inputs = [x0, x1, x2] targets = [t0, t1, t2] return inputs, targets, h0 class TestPythonOperation(unittest.TestCase): def check_shape(self, actual, expect): self.assertEqual( actual, expect, 'shape mismatch, actual shape is %s' ' exepcted is %s' % (_tuple_to_string(actual), _tuple_to_string(expect))) def _greater_helper(self, dev): x0 = np.array([-0.9, -0.3, -0.1, 0.1, 0.5, 0.9]).reshape(3, 2).astype(np.float32) x1 = np.array([0, -0.3, 0, 0.1, 0, 0.9]).reshape(3, 2).astype(np.float32) y = np.greater(x0, x1) x0 = tensor.from_numpy(x0) x1 = tensor.from_numpy(x1) x0.to_device(dev) x1.to_device(dev) result = autograd.greater(x0, x1) np.testing.assert_array_almost_equal(tensor.to_numpy(result), y, decimal=5) def test_Greater_cpu(self): self._greater_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_Greater_gpu(self): self._greater_helper(gpu_dev) def _conv2d_helper(self, dev): # (out_channels, kernel_size) conv_0 = layer.Conv2d(1, 2) conv_without_bias_0 = layer.Conv2d(1, 2, bias=False) cpu_input_tensor = tensor.Tensor(shape=(2, 3, 3, 3), device=dev) cpu_input_tensor.gaussian(0.0, 1.0) dy = tensor.Tensor(shape=(2, 1, 2, 2), device=dev) dy.gaussian(0.0, 1.0) y = conv_0(cpu_input_tensor) # PyTensor dx, dW, db = y.creator.backward(dy.data) # CTensor self.check_shape(y.shape, (2, 1, 2, 2)) self.check_shape(dx.shape(), (2, 3, 3, 3)) self.check_shape(dW.shape(), (1, 3, 2, 2)) self.check_shape(db.shape(), (1,)) # forward without bias y_without_bias = conv_without_bias_0(cpu_input_tensor) self.check_shape(y_without_bias.shape, (2, 1, 2, 2)) def test_conv2d_cpu(self): self._conv2d_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_conv2d_gpu(self): self._conv2d_helper(gpu_dev) def _conv_same_pad(self, dev, pad_mode, is_2d): if is_2d: x_h, w_h, k_h, p_h = 32, 4, 4, 1 else: x_h, w_h, k_h, p_h = 1, 1, 1, 0 x = tensor.Tensor(shape=(3, 3, x_h, 32), device=dev) x.gaussian(0.0, 1.0) # with the same padding, the padding should be 3 # for SAME_UPPER, is (1, 1) + (0, 1) # for SAME_LOWER, is (1, 1) + (1, 0) kernel = (k_h, 4) padding = (p_h, 1) stride = (1, 1) group = 1 bias = False out_channels = 3 conv_0 = layer.Conv2d(out_channels, kernel, stride=stride, group=group, bias=bias, pad_mode=pad_mode) y = conv_0(x) dy = np.ones((3, 3, x_h, 32), dtype=np.float32) dy = tensor.from_numpy(dy) dy.to_device(dev) dx, dW = y.creator.backward(dy.data) self.check_shape(y.shape, (3, 3, x_h, 32)) self.check_shape(dx.shape(), (3, 3, x_h, 32)) self.check_shape(dW.shape(), (3, 3, w_h, 4)) def test_conv2d_same_pad_cpu(self): self._conv_same_pad(cpu_dev, "SAME_LOWER", True) self._conv_same_pad(cpu_dev, "SAME_UPPER", True) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_conv2d_same_pad_gpu(self): self._conv_same_pad(gpu_dev, "SAME_LOWER", True) self._conv_same_pad(gpu_dev, "SAME_UPPER", True) def test_conv1d_same_pad_cpu(self): self._conv_same_pad(cpu_dev, "SAME_LOWER", False) self._conv_same_pad(cpu_dev, "SAME_UPPER", False) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_conv1d_same_pad_gpu(self): self._conv_same_pad(gpu_dev, "SAME_LOWER", False) self._conv_same_pad(gpu_dev, "SAME_UPPER", False) def _pooling_same_pad(self, dev, pad_mode, is_2d): if is_2d: x_h, k_h, p_h = 32, 4, 1 else: x_h, k_h, p_h = 1, 1, 0 x = tensor.Tensor(shape=(3, 3, x_h, 32), device=dev) x.gaussian(0.0, 1.0) # with the same padding, the padding should be 3 # for SAME_UPPER, is (1, 1) + (0, 1) # for SAME_LOWER, is (1, 1) + (1, 0) kernel = (k_h, 4) # we add 4 padding here and hope the conv and trim one padding then padding = (p_h, 1) stride = (1, 1) pooling = layer.Pooling2d(kernel, stride=stride, pad_mode=pad_mode) y = pooling(x) dy = np.ones((3, 3, x_h, 32), dtype=np.float32) dy = tensor.from_numpy(dy) dy.to_device(dev) dx = y.creator.backward(dy.data) self.check_shape(y.shape, (3, 3, x_h, 32)) self.check_shape(dx.shape(), (3, 3, x_h, 32)) def test_pooling2d_same_pad_cpu(self): self._pooling_same_pad(cpu_dev, "SAME_LOWER", True) self._pooling_same_pad(cpu_dev, "SAME_UPPER", True) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_pooling2d_same_pad_gpu(self): self._pooling_same_pad(gpu_dev, "SAME_LOWER", True) self._pooling_same_pad(gpu_dev, "SAME_UPPER", True) def test_pooling1d_same_pad_cpu(self): self._pooling_same_pad(cpu_dev, "SAME_LOWER", False) self._pooling_same_pad(cpu_dev, "SAME_UPPER", False) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_pooling1d_same_pad_gpu(self): self._pooling_same_pad(gpu_dev, "SAME_LOWER", False) self._pooling_same_pad(gpu_dev, "SAME_UPPER", False) def _sum_helper(self, dev): x = np.array([0.1, -1.0, 0.4, 4.0, -0.9, 9.0]).reshape(3, 2).astype(np.float32) x1 = np.array([0.1, 1.0, 0.4, 4.0, 0.9, 9.0]).reshape(3, 2).astype(np.float32) y = x + x1 dy = np.ones((3, 2), dtype=np.float32) grad0 = dy grad1 = dy x = tensor.from_numpy(x) x1 = tensor.from_numpy(x1) dy = tensor.from_numpy(dy) x.to_device(dev) x1.to_device(dev) dy.to_device(dev) result = autograd.sum(x, x1) dx0, dx1 = result.creator.backward(dy.data) np.testing.assert_array_almost_equal(tensor.to_numpy(result), y, decimal=5) np.testing.assert_array_almost_equal(tensor.to_numpy( tensor.from_raw_tensor(dx0)), grad0, decimal=5) np.testing.assert_array_almost_equal(tensor.to_numpy( tensor.from_raw_tensor(dx1)), grad1, decimal=5) def test_sum_cpu(self): self._sum_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_sum_gpu(self): self._sum_helper(gpu_dev) def _SeparableConv2d_helper(self, dev): # SeparableConv2d(in_channels, out_channels, kernel_size) if dev == cpu_dev: in_channels = 1 else: in_channels = 8 separ_conv = layer.SeparableConv2d(16, 3, padding=1) x = np.random.random((10, in_channels, 28, 28)).astype(np.float32) x = tensor.Tensor(device=dev, data=x) y = separ_conv(x) self.check_shape(y.shape, (10, 16, 28, 28)) y1 = separ_conv.depthwise_conv(x) y2 = separ_conv.point_conv(y1) dy1, dW_depth = y2.creator.backward(y2.data) dx, dW_spacial = y1.creator.backward(dy1) self.check_shape(y2.shape, (10, 16, 28, 28)) self.check_shape(dy1.shape(), (10, in_channels, 28, 28)) self.check_shape(dW_depth.shape(), (16, in_channels, 1, 1)) self.check_shape(dx.shape(), (10, in_channels, 28, 28)) self.check_shape(dW_spacial.shape(), (in_channels, 1, 3, 3)) def test_SeparableConv2d_cpu(self): self._SeparableConv2d_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_SeparableConv2d_gpu(self): self._SeparableConv2d_helper(gpu_dev) def _batchnorm2d_helper(self, dev): batchnorm_0 = layer.BatchNorm2d(3) cpu_input_tensor = tensor.Tensor(shape=(2, 3, 3, 3), device=dev) cpu_input_tensor.gaussian(0.0, 1.0) dy = cpu_input_tensor.clone().data y = batchnorm_0(cpu_input_tensor) dx, ds, db = y.creator.backward(dy) self.check_shape(y.shape, (2, 3, 3, 3)) self.check_shape(dx.shape(), (2, 3, 3, 3)) self.check_shape(ds.shape(), (3,)) self.check_shape(db.shape(), (3,)) def test_batchnorm2d_cpu(self): self._batchnorm2d_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_batchnorm2d_gpu(self): self._batchnorm2d_helper(gpu_dev) def gradients_check(self, func, param, autograds, h=0.0005, df=1, dev=cpu_dev): # param: PyTensor # autograds: numpy_tensor p = tensor.to_numpy(param) it = np.nditer(p, flags=['multi_index'], op_flags=['readwrite']) while not it.finished: idx = it.multi_index diff = np.zeros_like(p) diff[idx] += h diff = tensor.from_numpy(diff) diff.to_device(dev) param += diff pos = func() pos = tensor.to_numpy(pos) param -= diff param -= diff neg = func() neg = tensor.to_numpy(neg) numerical_grad = np.sum((pos - neg) * df) / (2 * h) #print((autograds[idx] - numerical_grad)/numerical_grad) # threshold set as -5% to +5% #self.assertAlmostEqual((autograds[idx] - numerical_grad)/(numerical_grad+0.0000001), 0., places=1) self.assertAlmostEqual(autograds[idx] - numerical_grad, 0., places=2) it.iternext() def _vanillaRNN_gpu_tiny_ops_shape_check_helper(self, dev): # gradients shape check. inputs, target, h0 = prepare_inputs_targets_for_rnn_test(dev) rnn = layer.RNN(3, 2) hs, _ = rnn(inputs, h0) loss = autograd.softmax_cross_entropy(hs[0], target[0]) for i in range(1, len(hs)): l = autograd.softmax_cross_entropy(hs[i], target[i]) loss = autograd.add(loss, l) # d=autograd.infer_dependency(loss.creator) # print(d) for t, dt in autograd.backward(loss): self.check_shape(t.shape, dt.shape) def test_vanillaRNN_gpu_tiny_ops_shape_check_cpu(self): self._vanillaRNN_gpu_tiny_ops_shape_check_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_vanillaRNN_gpu_tiny_ops_shape_check_gpu(self): self._vanillaRNN_gpu_tiny_ops_shape_check_helper(gpu_dev) def _LSTM_gpu_tiny_ops_shape_check_helper(self, dev): # gradients shape check. inputs, target, h0 = prepare_inputs_targets_for_rnn_test(dev) c_0 = np.random.random((2, 1)).astype(np.float32) c0 = tensor.Tensor(device=dev, data=c_0) rnn = layer.LSTM(3, 2) hs, _, _ = rnn(inputs, (h0, c0)) loss = autograd.softmax_cross_entropy(hs[0], target[0]) for i in range(1, len(hs)): l = autograd.softmax_cross_entropy(hs[i], target[i]) loss = autograd.add(loss, l) # d=autograd.infer_dependency(loss.creator) # print(d) for t, dt in autograd.backward(loss): self.check_shape(t.shape, dt.shape) def test_LSTM_gpu_tiny_ops_shape_check_cpu(self): self._LSTM_gpu_tiny_ops_shape_check_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_LSTM_gpu_tiny_ops_shape_check_gpu(self): self._LSTM_gpu_tiny_ops_shape_check_helper(gpu_dev) def _numerical_gradients_check_for_vallina_rnn_helper(self, dev): inputs, target, h0 = prepare_inputs_targets_for_rnn_test(dev) rnn = layer.RNN(3, 2) def valinna_rnn_forward(): hs, _ = rnn(inputs, h0) loss = autograd.softmax_cross_entropy(hs[0], target[0]) for i in range(1, len(hs)): l = autograd.softmax_cross_entropy(hs[i], target[i]) loss = autograd.add(loss, l) #grads = autograd.gradients(loss) return loss loss1 = valinna_rnn_forward() auto_grads = autograd.gradients(loss1) params = rnn.get_params() for key, param in params.items(): auto_grad = tensor.to_numpy(auto_grads[id(param)]) self.gradients_check(valinna_rnn_forward, param, auto_grad, dev=dev) def _gradient_check_cudnn_rnn(self, mode="vanilla", dev=gpu_dev): seq = 10 bs = 2 fea = 10 hid = 10 x = np.random.random((seq, bs, fea)).astype(np.float32) tx = tensor.Tensor(device=dev, data=x) y = np.random.random((seq, bs, hid)).astype(np.float32) y = np.reshape(y, (-1, hid)) ty = tensor.Tensor(device=dev, data=y) rnn = layer.CudnnRNN(hid, rnn_mode=mode, return_sequences=True) def vanilla_rnn_forward(): out = rnn(tx) out = autograd.reshape(out, (-1, hid)) loss = autograd.softmax_cross_entropy(out, ty) return loss loss = vanilla_rnn_forward() auto_grads = autograd.gradients(loss) params = rnn.get_params() for key, param in params.items(): auto_grad = tensor.to_numpy(auto_grads[id(param)]) self.gradients_check(vanilla_rnn_forward, param, auto_grad, dev=dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_gradient_check_cudnn_rnn_vanilla(self): self._gradient_check_cudnn_rnn(mode="vanilla", dev=gpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_gradient_check_cudnn_rnn_lstm(self): self._gradient_check_cudnn_rnn(mode="lstm", dev=gpu_dev) # Cos Sim Gradient Check def _gradient_check_cossim(self, dev=gpu_dev): bs = 2 vec = 3 ta = tensor.random((bs, vec), dev) tb = tensor.random((bs, vec), dev) # treat ta, tb as params ta.stores_grad = True tb.stores_grad = True ty = tensor.random((bs,), dev) def _forward(): out = autograd.cossim(ta, tb) loss = autograd.mse_loss(out, ty) return loss loss = _forward() auto_grads = autograd.gradients(loss) params = {id(ta): ta, id(tb): tb} for key, param in params.items(): auto_grad = tensor.to_numpy(auto_grads[id(param)]) self.gradients_check(_forward, param, auto_grad, dev=dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_gradient_check_cossim_gpu(self): self._gradient_check_cossim(dev=gpu_dev) def test_gradient_check_cossim_cpu(self): self._gradient_check_cossim(dev=cpu_dev) def test_numerical_gradients_check_for_vallina_rnn_cpu(self): self._numerical_gradients_check_for_vallina_rnn_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_numerical_gradients_check_for_vallina_rnn_gpu(self): self._numerical_gradients_check_for_vallina_rnn_helper(gpu_dev) def _numerical_gradients_check_for_lstm_helper(self, dev): inputs, target, h0 = prepare_inputs_targets_for_rnn_test(dev) c_0 = np.zeros((2, 2)).astype(np.float32) c0 = tensor.Tensor(device=dev, data=c_0) rnn = layer.LSTM(3, 2) def lstm_forward(): hs, _, _ = rnn(inputs, (h0, c0)) loss = autograd.softmax_cross_entropy(hs[0], target[0]) for i in range(1, len(hs)): l = autograd.softmax_cross_entropy(hs[i], target[i]) loss = autograd.add(loss, l) return loss loss1 = lstm_forward() auto_grads = autograd.gradients(loss1) params = rnn.get_params() for key, param in params.items(): auto_grad = tensor.to_numpy(auto_grads[id(param)]) self.gradients_check(lstm_forward, param, auto_grad, dev=dev) def test_numerical_gradients_check_for_lstm_cpu(self): self._numerical_gradients_check_for_lstm_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_numerical_gradients_check_for_lstm_gpu(self): self._numerical_gradients_check_for_lstm_helper(gpu_dev) def _MeanSquareError_helper(self, dev): X = np.array([4.3, 5.4, 3.3, 3.6, 5.7, 6.0]).reshape(3, 2).astype(np.float32) T = np.array([4.4, 5.3, 3.2, 3.7, 5.4, 6.3]).reshape(3, 2).astype(np.float32) x = tensor.from_numpy(X) t = tensor.from_numpy(T) x.to_device(dev) t.to_device(dev) loss = autograd.mse_loss(x, t) dx = loss.creator.backward() loss_np = tensor.to_numpy(loss)[0] self.assertAlmostEqual(loss_np, 0.0366666, places=4) self.check_shape(dx.shape(), (3, 2)) def test_MeanSquareError_cpu(self): self._MeanSquareError_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_MeanSquareError_gpu(self): self._MeanSquareError_helper(gpu_dev) def _Abs_helper(self, dev): X = np.array([0.8, -1.2, 3.3, -3.6, -0.5, 0.5]).reshape(3, 2).astype(np.float32) XT = np.array([0.8, 1.2, 3.3, 3.6, 0.5, 0.5]).reshape(3, 2).astype(np.float32) x = tensor.from_numpy(X) x.to_device(dev) result = autograd.abs(x) dx = result.creator.backward(x.data) np.testing.assert_array_almost_equal(tensor.to_numpy(result), XT) self.check_shape(dx.shape(), (3, 2)) def test_Abs_cpu(self): self._Abs_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_Abs_gpu(self): self._Abs_helper(gpu_dev) def _Mean_helper(self, dev): x0 = np.array([-0.9, -0.3, -0.1, 0.1, 0.5, 0.9]).reshape(3, 2).astype(np.float32) x1 = np.array([0, -0.3, 0, 0.1, 0, 0.9]).reshape(3, 2).astype(np.float32) y = (x0 + x1) / 2 grad = np.ones(x0.shape) / 2 x0 = tensor.from_numpy(x0) x1 = tensor.from_numpy(x1) x0.to_device(dev) x1.to_device(dev) result = autograd.mean(x0, x1) dy = tensor.from_numpy(np.ones((3, 2)).astype(np.float32)) dy.to_device(dev) dx0, dx1 = result.creator.backward(dy.data) np.testing.assert_array_almost_equal(tensor.to_numpy(result), y, decimal=5) np.testing.assert_array_almost_equal(tensor.to_numpy( tensor.from_raw_tensor(dx0)), grad, decimal=5) np.testing.assert_array_almost_equal(tensor.to_numpy( tensor.from_raw_tensor(dx1)), grad, decimal=5) def test_Mean_cpu(self): self._Mean_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_Mean_gpu(self): self._Mean_helper(gpu_dev) def _Exp_helper(self, dev): X = np.array([0.8, -1.2, 3.3, -3.6, -0.5, 0.5]).reshape(3, 2).astype(np.float32) XT = np.exp(X) x = tensor.from_numpy(X) x.to_device(dev) result = autograd.exp(x) dx = result.creator.backward(x.data) np.testing.assert_array_almost_equal(tensor.to_numpy(result), XT, decimal=5) self.check_shape(dx.shape(), (3, 2)) def test_Exp_cpu(self): self._Exp_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_Exp_gpu(self): self._Exp_helper(gpu_dev) def _Identity_helper(self, dev): x = np.array([-0.9, -0.3, -0.1, 0.1, 0.5, 0.9]).reshape(3, 2).astype(np.float32) y = x.copy() grad = np.ones(x.shape) x = tensor.from_numpy(x) x.to_device(dev) result = autograd.identity(x) dy = tensor.from_numpy(np.ones((3, 2)).astype(np.float32)) dy.to_device(dev) dx = result.creator.backward(dy.data) np.testing.assert_array_almost_equal(tensor.to_numpy(result), y, decimal=5) np.testing.assert_array_almost_equal(tensor.to_numpy( tensor.from_raw_tensor(dx)), grad, decimal=5) self.check_shape(dx.shape(), (3, 2)) def test_Identity_cpu(self): self._Identity_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_Identity_gpu(self): self._Identity_helper(gpu_dev) def _LeakyRelu_helper(self, dev): X = np.array([0.8, -1.2, 3.3, -3.6, -0.5, 0.5]).reshape(3, 2).astype(np.float32) XT = np.array([0.8, -0.012, 3.3, -0.036, -0.005, 0.5]).reshape(3, 2).astype(np.float32) x = tensor.from_numpy(X) x.to_device(dev) result = autograd.leakyrelu(x) dx = result.creator.backward(x.data) np.testing.assert_array_almost_equal(tensor.to_numpy(result), XT) self.check_shape(dx.shape(), (3, 2)) def test_LeakyRelu_cpu(self): self._LeakyRelu_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_LeakyRelu_gpu(self): self._LeakyRelu_helper(gpu_dev) def _Relu_helper(self, dev): X = np.array([0.8, -1.2, 3.3, -3.6, -0.5, 0.5]).reshape(3, 2).astype(np.float32) XT = np.maximum(X, 0) DY = np.ones((3, 2), dtype=np.float32) x = tensor.from_numpy(X) dy = tensor.from_numpy(DY) x.to_device(dev) dy.to_device(dev) result = autograd.relu(x) dx = result.creator.backward(dy.data) G = (X > 0).astype(np.float32) DX = np.multiply(G, DY) np.testing.assert_array_almost_equal(tensor.to_numpy(result), XT, decimal=5) np.testing.assert_array_almost_equal(tensor.to_numpy( tensor.from_raw_tensor(dx)), DX, decimal=5) def test_Relu_cpu(self): self._Relu_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_Relu_gpu(self): self._Relu_helper(gpu_dev) def _Cos_helper(self, dev): X = np.array([0.8, -1.2, 3.3, -3.6, -0.5, 0.5]).reshape(3, 2).astype(np.float32) XT = np.cos(X) DY = np.ones((3, 2), dtype=np.float32) x = tensor.from_numpy(X) dy = tensor.from_numpy(DY) x.to_device(dev) dy.to_device(dev) result = autograd.cos(x) dx = result.creator.backward(dy.data) G = -np.sin(X) DX = np.multiply(G, DY) np.testing.assert_array_almost_equal(tensor.to_numpy(result), XT, decimal=5) np.testing.assert_array_almost_equal(tensor.to_numpy( tensor.from_raw_tensor(dx)), DX, decimal=5) def test_Cos_cpu(self): self._Cos_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_Cos_gpu(self): self._Cos_helper(gpu_dev) def _Cosh_helper(self, dev): X = np.array([0.8, -1.2, 3.3, -3.6, -0.5, 0.5]).reshape(3, 2).astype(np.float32) XT = np.cosh(X) DY = np.ones((3, 2), dtype=np.float32) x = tensor.from_numpy(X) dy = tensor.from_numpy(DY) x.to_device(dev) dy.to_device(dev) result = autograd.cosh(x) dx = result.creator.backward(dy.data) G = np.sinh(X) DX = np.multiply(G, DY) np.testing.assert_array_almost_equal(tensor.to_numpy(result), XT, decimal=5) np.testing.assert_array_almost_equal(tensor.to_numpy( tensor.from_raw_tensor(dx)), DX, decimal=5) def test_Cosh_cpu(self): self._Cosh_helper(cpu_dev) @unittest.skipIf(not singa_wrap.USE_CUDA, 'CUDA is not enabled') def test_Cosh_gpu(self): self._Cosh_helper(gpu_dev) def _Acos_helper(self, dev): X = np.array([-0.9, -0.3, -0.1, 0.1, 0.5, 0.9]).reshape(3, 2).astype(np.float32) XT = np.arccos(X) DY = np.ones((3, 2), dtype=np.float32) x = tensor.from_numpy(X) dy = tensor.from_numpy(DY) x.to_device(dev) dy.to_device(dev) result = autograd.acos(x) dx = result.creator.backward(dy.data) G = -1.0 / np.sqrt(1.0 - np.square(X)) DX =
np.multiply(G, DY)
numpy.multiply
""" parse CP2K output to Trajectory type 1: cp2k_shell log, generated by ASE, with "out" in the filename type 2: ENERGY_FORCE type, input file and xyz force output still exits type 3: """ import logging import numpy as np from glob import glob from os.path import isfile, getctime from thyme import Trajectory from thyme._key import * from thyme.parsers.monty import read_pattern, read_table_pattern from thyme.routines.folders import find_folders, find_folders_matching HARTREE = 27.2114 HARTREE_BOHR = 51.42208619083232 nc_fl_num = r"[+-]?\d+\.*\d*[eE]?[+-]?\d*" fl_num = r"(" + nc_fl_num + ")" nc_sfl_num = r"\s+" + nc_fl_num sfl_num = r"\s+" + fl_num def get_childfolders(path): return find_folders_matching(["*.xyz", "*.inp", "*out*"], path) def pack_folder_trj(folder: str, data_filter): """ For one plain folder (without looking into its children folder), search for all the simulation store in this folder It can be a single CP2K run, multiple MD runs or multiple ASE call. We assume all trajectories in this folder has the same number of atoms, species And the same DFT set up. Args: folder (str): folder path for parsing Return: Trajectory instance """ has_xyz = len(glob(f"{folder}/*.xyz")) > 0 has_out = len(glob(f"{folder}/*out*")) > 0 has_inp = (len(glob(f"{folder}/*.inp")) > 0) or ( len(glob(f"{folder}/*.restart")) > 0 ) has_pair = (len(glob(f"{folder}/*.inp")) > 0) and (has_out or has_xyz) has_xyzs = (len(glob(f"{folder}/*-frc*.xyz")) > 0) and ( len(glob(f"{folder}/*-pos*.xyz")) > 0 ) conditions = [has_xyzs, has_pair, has_out] trj = Trajectory() if np.sum(conditions) == 0: return trj # first identify force_eval pair MD_xyz = {} if has_out: # sort files from new to old outfile_list = [] outfile_mtime = [] for outfile in glob(f"{folder}/*out*"): outfile_list += [outfile] outfile_mtime += [-getctime(outfile)] sort_id = np.argsort(outfile_mtime) outfile_list = np.array(outfile_list, dtype=str) outfile_list = outfile_list[sort_id] for outfile in outfile_list: if not isfile(outfile): continue outfile_dict = parse_std_out(outfile) if "abort" in outfile_dict: continue _trj = Trajectory() if "send" in outfile_dict: logging.info(f"parsing {outfile} as shell product") _trj = parse_ase_shell_out(folder, outfile) elif "run_type" in outfile_dict: run_type = outfile_dict["run_type"] proj_name = outfile_dict["proj_name"] if run_type == "ENERGY_FORCE": logging.info(f"parsing {outfile} as force_eval type product") _trj = parse_force_eval_pairs(folder, outfile, outfile_dict) elif run_type == "MD": if "xyzout" in outfile_dict: MD_xyz[proj_name] = f"{folder}/" + outfile_dict["inputfile"] else: raise NotImplementedError( f"cannot parse MD without xyz {run_type}" ) else: raise NotImplementedError(f"cannot parse RUN_TYPE {run_type}") if _trj.nframes > 0: logging.info(f"repr {repr(_trj)}") logging.info(f"add {_trj}") logging.info(f"to {trj}") trj.add_trj(_trj) for k in MD_xyz: _trj = parse_md(folder, inp=MD_xyz[k], proj_name=k) logging.info(f"repr {repr(_trj)}") trj.add_trj(_trj) if has_xyz and has_inp and len(MD_xyz) == 0: mtime = 10e9 mfile = "" proj_name = "" # choose the earliest input for inputfile in glob(f"{folder}/*.inp") + glob(f"{folder}/*.restart"): _mtime = getctime(inputfile) if _mtime < mtime: metadata = parse_std_inp_metadata(inputfile) if metadata["run_type"] == "MD": mtime = _mtime mfile = inputfile proj_name = metadata["proj_name"] if isfile(f"{folder}/{proj_name}-pos-1.xyz"): _trj = parse_md(folder, inp=inputfile, proj_name=proj_name) logging.info(f"repr {repr(_trj)}") trj.add_trj(_trj) logging.info(trj) logging.info(repr(trj)) return trj # elif np.sum(conditions) == 0: # logging.info(f"! {folder} skip for no file matching") # else: # logging.info(f"! {folder} skip for incomplete files") # if folder == "./": # folder = "." # return Trajectory() def parse_md(folder: str, inp: str, proj_name: str): """ Args: folder (str): path of the folder inp (str): the input file for CP2K proj_name (str): the CP2K project name. The prefix used for MD dumps """ logging.info(f"parse md in folder {folder}") # if above strings are found find_input = False try: find_input = ( isfile(inp) and isfile(f"{folder}/{proj_name}-pos-1.xyz") and isfile(f"{folder}/{proj_name}-frc-1.xyz") ) except Exception as e: logging.info(f"It is not a MD {e}") if not find_input: return Trajectory() metadata = parse_std_inp_metadata(inp) data = parse_std_inp_pos(inp) return parse_cp2k_xyzs( f"{folder}/{proj_name}-pos-1.xyz", f"{folder}/{proj_name}-frc-1.xyz", data["cells"], metadata, ) def parse_std_out(filename): logging.info(f"parse {filename}") d = read_pattern( filename, { "inputfile": r"Input file name\s+(\S+)", "abort": r"(ABORT)", "run_type": r"Run type\s+(\S+)", "proj_name": r"Project name\s+(\S+)", "xyzout": r"Coordinates\s+\d+\s+(\S+)", "send": r"Sending: (GET_E)", "receive": r"Received: * (READY)", "energy": r"Total energy:" + sfl_num, }, ) del_keys = [] for k in d: d[k] =
np.array(d[k], dtype=str)
numpy.array
#!/usr/bin/env python # Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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 import os from collections import OrderedDict import pandas as pd import pickle import time import subprocess import utils.dataloader_utils as dutils # batch generator tools from https://github.com/MIC-DKFZ/batchgenerators from batchgenerators.dataloading.data_loader import SlimDataLoaderBase from batchgenerators.transforms.spatial_transforms import MirrorTransform as Mirror from batchgenerators.transforms.abstract_transforms import Compose from batchgenerators.dataloading.multi_threaded_augmenter import MultiThreadedAugmenter from batchgenerators.dataloading import SingleThreadedAugmenter from batchgenerators.transforms.spatial_transforms import SpatialTransform from batchgenerators.transforms.crop_and_pad_transforms import CenterCropTransform from batchgenerators.transforms.utility_transforms import ConvertSegToBoundingBoxCoordinates GET_ROIS_FROM_SEG = False DO_MULTITHREADED = False def get_train_generators(cf, logger): """ wrapper function for creating the training batch generator pipeline. returns the train/val generators. selects patients according to cv folds (generated by first run/fold of experiment): splits the data into n-folds, where 1 split is used for val, 1 split for testing and the rest for training. (inner loop test set) If cf.hold_out_test_set is True, adds the test split to the training data. """ all_data = load_dataset(cf, logger) all_pids_list = np.unique([v['pid'] for (k, v) in all_data.items()]) assert cf.n_train_val_data <= len(all_pids_list), \ "requested {} train val samples, but dataset only has {} train val samples.".format( cf.n_train_val_data, len(all_pids_list)) train_pids = all_pids_list[:int(2*cf.n_train_val_data//3)] val_pids = all_pids_list[int(np.ceil(2*cf.n_train_val_data//3)):cf.n_train_val_data] train_data = {k: v for (k, v) in all_data.items() if any(p == v['pid'] for p in train_pids)} val_data = {k: v for (k, v) in all_data.items() if any(p == v['pid'] for p in val_pids)} logger.info("data set loaded with: {} train / {} val patients".format(len(train_pids), len(val_pids))) batch_gen = {} batch_gen['train'] = create_data_gen_pipeline(train_data, cf=cf, do_aug=False) batch_gen['val_sampling'] = create_data_gen_pipeline(val_data, cf=cf, do_aug=False) if cf.val_mode == 'val_patient': batch_gen['val_patient'] = PatientBatchIterator(val_data, cf=cf) batch_gen['n_val'] = len(val_pids) if cf.max_val_patients is None else min(len(val_pids), cf.max_val_patients) else: batch_gen['n_val'] = cf.num_val_batches return batch_gen def get_test_generator(cf, logger): """ wrapper function for creating the test batch generator pipeline. selects patients according to cv folds (generated by first run/fold of experiment) If cf.hold_out_test_set is True, gets the data from an external folder instead. """ if cf.hold_out_test_set: pp_name = cf.pp_test_name test_ix = None else: pp_name = None with open(os.path.join(cf.exp_dir, 'fold_ids.pickle'), 'rb') as handle: fold_list = pickle.load(handle) _, _, test_ix, _ = fold_list[cf.fold] # warnings.warn('WARNING: using validation set for testing!!!') test_data = load_dataset(cf, logger, test_ix, pp_data_path=cf.pp_test_data_path, pp_name=pp_name) logger.info("data set loaded with: {} test patients from {}".format(len(test_data.keys()), cf.pp_test_data_path)) batch_gen = {} batch_gen['test'] = PatientBatchIterator(test_data, cf=cf) batch_gen['n_test'] = len(test_data.keys()) if cf.max_test_patients=="all" else \ min(cf.max_test_patients, len(test_data.keys())) return batch_gen def load_dataset(cf, logger, subset_ixs=None, pp_data_path=None, pp_name=None): """ loads the dataset. if deployed in cloud also copies and unpacks the data to the working directory. :param subset_ixs: subset indices to be loaded from the dataset. used e.g. for testing to only load the test folds. :return: data: dictionary with one entry per patient (in this case per patient-breast, since they are treated as individual images for training) each entry is a dictionary containing respective meta-info as well as paths to the preprocessed numpy arrays to be loaded during batch-generation """ if pp_data_path is None: pp_data_path = cf.pp_data_path if pp_name is None: pp_name = cf.pp_name if cf.server_env: copy_data = True target_dir = os.path.join(cf.data_dest, pp_name) if not os.path.exists(target_dir): cf.data_source_dir = pp_data_path os.makedirs(target_dir) subprocess.call('rsync -av {} {}'.format( os.path.join(cf.data_source_dir, cf.input_df_name), os.path.join(target_dir, cf.input_df_name)), shell=True) logger.info('created target dir and info df at {}'.format(os.path.join(target_dir, cf.input_df_name))) elif subset_ixs is None: copy_data = False pp_data_path = target_dir p_df = pd.read_pickle(os.path.join(pp_data_path, cf.input_df_name)) if subset_ixs is not None: subset_pids = [np.unique(p_df.pid.tolist())[ix] for ix in subset_ixs] p_df = p_df[p_df.pid.isin(subset_pids)] logger.info('subset: selected {} instances from df'.format(len(p_df))) if cf.server_env: if copy_data: copy_and_unpack_data(logger, p_df.pid.tolist(), cf.fold_dir, cf.data_source_dir, target_dir) class_targets = p_df['class_id'].tolist() pids = p_df.pid.tolist() imgs = [os.path.join(pp_data_path, '{}.npy'.format(pid)) for pid in pids] segs = [os.path.join(pp_data_path,'{}.npy'.format(pid)) for pid in pids] data = OrderedDict() for ix, pid in enumerate(pids): data[pid] = {'data': imgs[ix], 'seg': segs[ix], 'pid': pid, 'class_target': [class_targets[ix]]} return data def create_data_gen_pipeline(patient_data, cf, do_aug=True): """ create mutli-threaded train/val/test batch generation and augmentation pipeline. :param patient_data: dictionary containing one dictionary per patient in the train/test subset. :param is_training: (optional) whether to perform data augmentation (training) or not (validation/testing) :return: multithreaded_generator """ # create instance of batch generator as first element in pipeline. data_gen = BatchGenerator(patient_data, batch_size=cf.batch_size, cf=cf) # add transformations to pipeline. my_transforms = [] if do_aug: mirror_transform = Mirror(axes=np.arange(2, cf.dim+2, 1)) my_transforms.append(mirror_transform) spatial_transform = SpatialTransform(patch_size=cf.patch_size[:cf.dim], patch_center_dist_from_border=cf.da_kwargs['rand_crop_dist'], do_elastic_deform=cf.da_kwargs['do_elastic_deform'], alpha=cf.da_kwargs['alpha'], sigma=cf.da_kwargs['sigma'], do_rotation=cf.da_kwargs['do_rotation'], angle_x=cf.da_kwargs['angle_x'], angle_y=cf.da_kwargs['angle_y'], angle_z=cf.da_kwargs['angle_z'], do_scale=cf.da_kwargs['do_scale'], scale=cf.da_kwargs['scale'], random_crop=cf.da_kwargs['random_crop']) my_transforms.append(spatial_transform) else: my_transforms.append(CenterCropTransform(crop_size=cf.patch_size[:cf.dim])) my_transforms.append(ConvertSegToBoundingBoxCoordinates(cf.dim, get_rois_from_seg_flag=GET_ROIS_FROM_SEG, class_specific_seg_flag=cf.class_specific_seg_flag)) all_transforms = Compose(my_transforms) if DO_MULTITHREADED: multithreaded_generator = MultiThreadedAugmenter(data_gen, all_transforms, num_processes=cf.n_workers, seeds=range(cf.n_workers)) else: multithreaded_generator = SingleThreadedAugmenter(data_gen, all_transforms) return multithreaded_generator class BatchGenerator(SlimDataLoaderBase): """ creates the training/validation batch generator. Samples n_batch_size patients (draws a slice from each patient if 2D) from the data set while maintaining foreground-class balance. Returned patches are cropped/padded to pre_crop_size. Actual patch_size is obtained after data augmentation. :param data: data dictionary as provided by 'load_dataset'. :param batch_size: number of patients to sample for the batch :return dictionary containing the batch data (b, c, y, x, (z)) / seg (b, 1, y, x, (z)) / pids / class_target """ def __init__(self, data, batch_size, cf): super(BatchGenerator, self).__init__(data, batch_size) self.cf = cf def generate_train_batch(self): batch_data, batch_segs, batch_pids, batch_targets = [], [], [], [] class_targets_list = [v['class_target'] for (k, v) in self._data.items()] #samples patients towards equilibrium of foreground classes on a roi-level (after randomly sampling the ratio "batch_sample_slack). batch_ixs = dutils.get_class_balanced_patients( class_targets_list, self.batch_size, self.cf.head_classes - 1, slack_factor=self.cf.batch_sample_slack) patients = list(self._data.items()) for b in batch_ixs: patient = patients[b][1] all_data = np.load(patient['data'], mmap_mode='r') data = all_data[0] seg = all_data[1].astype('uint8') batch_pids.append(patient['pid']) batch_targets.append(patient['class_target']) batch_data.append(data[np.newaxis]) batch_segs.append(seg[np.newaxis]) data =
np.array(batch_data)
numpy.array
from __future__ import division, unicode_literals, print_function, absolute_import import pytest import traitlets as tl import numpy as np import xarray as xr import podpac from podpac.core.algorithm.algorithm import BaseAlgorithm, Algorithm, UnaryAlgorithm class TestBaseAlgorithm(object): def test_eval_not_implemented(self): node = BaseAlgorithm() c = podpac.Coordinates([]) with pytest.raises(NotImplementedError): node.eval(c) def test_inputs(self): class MyAlgorithm(BaseAlgorithm): x = tl.Instance(podpac.Node).tag(attr=True) y = tl.Instance(podpac.Node).tag(attr=True) node = MyAlgorithm(x=podpac.Node(), y=podpac.Node()) assert "x" in node.inputs assert "y" in node.inputs def test_find_coordinates(self): class MyAlgorithm(BaseAlgorithm): x = tl.Instance(podpac.Node).tag(attr=True) y = tl.Instance(podpac.Node).tag(attr=True) node = MyAlgorithm( x=podpac.data.Array(coordinates=podpac.Coordinates([[0, 1, 2]], dims=["lat"])), y=podpac.data.Array(coordinates=podpac.Coordinates([[10, 11, 12], [100, 200]], dims=["lat", "lon"])), ) l = node.find_coordinates() assert isinstance(l, list) assert len(l) == 2 assert node.x.coordinates in l assert node.y.coordinates in l class TestAlgorithm(object): def test_algorithm_not_implemented(self): node = Algorithm() c = podpac.Coordinates([]) with pytest.raises(NotImplementedError): node.eval(c) def test_eval(self): class MyAlgorithm(Algorithm): def algorithm(self, inputs, coordinates): data = np.arange(coordinates.size).reshape(coordinates.shape) return self.create_output_array(coordinates, data=data) coords = podpac.Coordinates([[0, 1, 2], [10, 20]], dims=["lat", "lon"]) node = MyAlgorithm() output = node.eval(coords) assert isinstance(output, podpac.UnitsDataArray) assert output.dims == ("lat", "lon") np.testing.assert_array_equal(output, np.arange(6).reshape(3, 2)) def test_eval_algorithm_returns_xarray(self): class MyAlgorithm(Algorithm): def algorithm(self, inputs, coordinates): data = np.arange(coordinates.size).reshape(coordinates.shape) return xr.DataArray( data, coords=coordinates.xcoords, dims=coordinates.dims, attrs={"crs": coordinates.crs} ) coords = podpac.Coordinates([[0, 1, 2], [10, 20]], dims=["lat", "lon"]) node = MyAlgorithm() output = node.eval(coords) assert isinstance(output, podpac.UnitsDataArray) assert output.dims == ("lat", "lon") np.testing.assert_array_equal(output, np.arange(6).reshape(3, 2)) def test_eval_algorithm_returns_numpy_array(self): class MyAlgorithm(Algorithm): def algorithm(self, inputs, coordinates): data = np.arange(coordinates.size).reshape(coordinates.shape) return data coords = podpac.Coordinates([[0, 1, 2], [10, 20]], dims=["lat", "lon"]) node = MyAlgorithm() with pytest.raises(podpac.NodeException, match="algorithm returned unsupported type"): output = node.eval(coords) def test_eval_algorithm_drops_dimension(self): class MyAlgorithm(Algorithm): drop = tl.Unicode() def algorithm(self, inputs, coordinates): c = coordinates.drop(self.drop) data = np.arange(c.size).reshape(c.shape) return self.create_output_array(c, data=data) coords = podpac.Coordinates([[0, 1, 2], [10, 20]], dims=["lat", "lon"]) node = MyAlgorithm(drop="lat") output = node.eval(coords) assert isinstance(output, podpac.UnitsDataArray) assert output.dims == ("lon",) np.testing.assert_array_equal(output, np.arange(2)) coords = podpac.Coordinates([[0, 1, 2], [10, 20]], dims=["lat", "lon"]) node = MyAlgorithm(drop="lon") output = node.eval(coords) assert isinstance(output, podpac.UnitsDataArray) assert output.dims == ("lat",) np.testing.assert_array_equal(output, np.arange(3)) def test_eval_algorithm_adds_dimension(self): class MyAlgorithm(Algorithm): def algorithm(self, inputs, coordinates): c = podpac.Coordinates( [["2020-01-01", "2020-01-02"], coordinates["lat"], coordinates["lon"]], dims=["time", "lat", "lon"] ) data = np.arange(c.size).reshape(c.shape) return self.create_output_array(c, data=data) coords = podpac.Coordinates([[0, 1, 2], [10, 20]], dims=["lat", "lon"]) node = MyAlgorithm() output = node.eval(coords) assert isinstance(output, podpac.UnitsDataArray) assert output.dims == ("lat", "lon", "time") np.testing.assert_array_equal(output, np.arange(12).reshape(2, 3, 2).transpose(1, 2, 0)) def test_eval_algorithm_transposes(self): class MyAlgorithm(Algorithm): def algorithm(self, inputs, coordinates): c = coordinates.transpose("lon", "lat") data = np.arange(c.size).reshape(c.shape) return self.create_output_array(c, data=data) coords = podpac.Coordinates([[0, 1, 2], [10, 20]], dims=["lat", "lon"]) node = MyAlgorithm() output = node.eval(coords) assert isinstance(output, podpac.UnitsDataArray) assert output.dims == ("lat", "lon") np.testing.assert_array_equal(output,
np.arange(6)
numpy.arange
#!/usr/bin/env python # -*- coding: UTF-8 -*- ##---------------------------------------------------------------------------- ## Title : Workload ##---------------------------------------------------------------------------- ## File : Workload.py ## Author : <NAME> ## Company : Institut Pascal - DREAM ## Last update: 30-04-2018 ##---------------------------------------------------------------------------- import sys import os import io import numpy as np import math import matplotlib.pyplot as plt import pylab as P os.environ['GLOG_minloglevel'] = '2' # Supresses Display on console import caffe; def listLayers(protoFile, modelFile): cnn = caffe.Net(protoFile,1,weights=modelFile) params = cnn.params blobs = cnn.blobs #~ print("\n".join(map(str, cnn._layer_names))) #~ print blobs for layerName in cnn._layer_names: layerId = list(cnn._layer_names).index(layerName) layerType = cnn.layers[layerId].type print(layerName,"\t",layerType) def workload(protoFile, modelFile): convLayerName = np.array([]) convWorkload = np.array([]) convMemory = np.array([]) fcLayerName =
np.array([])
numpy.array
# gaussfit.py - Routines to fit single Gaussian peaks ## ---- Import python routines ---- import sys import numpy as np ## ---- Caruana's linear least square fitting ---- def caruana(x, y): """ Linear least square fitting routine to fit a quadratic polynomial to Gaussian peak. Parabola is fitted to (x,lny) to determine fitted values of height, position, and FWHM of Gaussian peak. Parameters ---------- x : ndarray x-axis data y : ndarray y-axis data Returns ------- height, position, width : float height, position and FWHM of fitted Gaussian peaki Reference --------- Routine is based on Caruana algorithm mention in paper by <NAME>. 'A Simple Algorithm for Fitting a Gaussian Function', IEEE Signal Processing Magazine, September 2011 """ # Common variables N = len(x) Sx = np.sum(x) Sx2 = np.sum(x**2) Sx3 = np.sum(x**3) Sx4 = np.sum(x**4) # To avoid undefined ln(y) maxy =np.max(y) ind = np.arange(len(y)) mody = np.array(map(lambda i: maxy/100.0 if y[i] < maxy/100.0 else y[i], ind)) # Create a 3x3 matrix and a 3 dimensional vector X = np.array([[N, Sx, Sx2], [Sx, Sx2, Sx3], [Sx2, Sx3, Sx4]]) Y = np.vstack(np.array([np.sum(np.log(mody)), np.sum(x * np.log(mody)), np.sum(x**2 * np.log(mody))])) # Solve linear equation using least square a, b, c = np.linalg.lstsq(X,Y)[0] # Calculate fitted values of height, position and width height = np.exp(a - ((b**2) / (4 * c))) position = -b/(2*c) width = 1.66511 / np.sqrt(-c) return np.array([height, position, width]) ## ---- Weighted linear least square fitting ---- def wlstsq(x, y): """ Weighted Linear least square fitting routine to fit a quadratic polynomial to Gaussian peak. Parabola is fitted to (x,lny) to determine fitted values of height, position and fwhm of Gaussian peak. Parameters ---------- x : ndarray x-axis data y : ndarray y-axis data Returns ------- height, position, width : float height, position and FWHM of fitted Gaussian peak References ---------- Routine is based on weighted algorithm mention in paper by <NAME>. 'A Simple Algorithm for Fitting a Gaussian Function', IEEE Signal Processing Magazine, September 2011 """ # To avoid undefined ln(y) maxy =np.max(y) ind = np.arange(len(y)) mody = np.array(map(lambda i: maxy/100.0 if y[i] < maxy/100.0 else y[i], ind)) # Common variables Sy2 = np.sum(mody**2) Sxy2 =
np.sum(x * mody**2)
numpy.sum
import argparse import cv2 import csv import keras from keras.callbacks import CSVLogger import numpy as np import os from tqdm import tqdm from keras.layers import Lambda, Cropping2D import matplotlib.pyplot as plt class steering_model(object): def __init__(self): self.layers = [{'type': "dense", 'units': 1}] def preprocessing_flatten(self): self.model.add(keras.layers.Flatten(input_shape=(160, 320, 3))) def def_model_arbitrary(self): self.model = keras.models.Sequential() self.model.add(Cropping2D(cropping=((50, 20), (0, 0)), input_shape=(160, 320, 3))) self.model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160, 320, 3))) self.preprocessing_flatten() for layer in self.layers: if layer['type'] == 'dense': self.model.add(keras.layers.Dense(layer['units'])) return self.model def def_model_lenet(self): self.model = keras.Sequential() self.model.add(Cropping2D(cropping=((50, 20), (0, 0)), input_shape=(160, 320, 3))) self.model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160, 320, 3))) self.model.add(keras.layers.Conv2D(filters=6, kernel_size=(3, 3), activation='relu')) self.model.add(keras.layers.AveragePooling2D()) self.model.add(keras.layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu')) self.model.add(keras.layers.AveragePooling2D()) self.model.add(keras.layers.Flatten()) self.model.add(keras.layers.Dense(units=120, activation='relu')) self.model.add(keras.layers.Dense(units=84, activation='relu')) self.model.add(keras.layers.Dense(units=1)) return self.model def main(log_results, model_name, data_path): callbacks = [] data = [] with open(data_path + '/driving_log.csv') as csv_file: lines = csv.reader(csv_file) for line in lines: data.append(line) data = np.array(data) input_images_paths_old = {} input_images_paths_old["center"] = data[:, 0] input_images_paths_old["left"] = data[:, 1] input_images_paths_old["right"] = data[:, 2] Label_data_str = data[:, 3] #steering Input_image_data = [] Label_data = [] print("Extracting images from repository ...") for i in tqdm(range(data.shape[0])): correction = {"center": 0, "left": 0.2, "right": -0.2} for position in input_images_paths_old.keys(): path_new = os.path.join(data_path, 'IMG', input_images_paths_old[position][i].split('/')[-1]) Input_image_data.append(cv2.imread(path_new)) Label_data.append(float(Label_data_str[i]) + correction[position]) # flipped recording Input_image_data.append(np.fliplr(cv2.imread(path_new))) Label_data.append(-(float(Label_data_str[i]) + correction[position])) Input_image_data = np.array(Input_image_data, dtype=np.float32) Label_data =
np.array(Label_data)
numpy.array
# !/usr/bin/env python3 # -*-coding:utf-8-*- # @file: main_GCNet.py # @brief: # @author: <NAME>, <EMAIL>, <EMAIL> # @version: 0.0.1 # @creation date: 07-01-2020 # @last modified: Thu 09 Apr 2020 02:21:58 PM EDT from __future__ import print_function import sys import shutil import os from os.path import join as pjoin import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import cv2 from torch.utils.data import DataLoader import torch.nn.functional as F #from .loaddata.data import get_training_set, get_valid_set, load_test_data, test_transform from src.loaddata.data import get_training_set, load_test_data, test_transform from src.loaddata.dataset import get_virtual_kitti2_filelist from torch.utils.tensorboard import SummaryWriter from src.dispColor import colormap_jet_batch_image,KT15FalseColorDisp,KT15LogColorDispErr #from src.utils import writeKT15FalseColors # this is numpy fuction, it is SO SLOW !!! # this is cython fuction, it is SO QUICK !!! from src.cython import writeKT15FalseColor as KT15FalseClr from src.cython import writeKT15ErrorLogColor as KT15LogClr import numpy as np import src.pfmutil as pfm import time from .models.loss import valid_accu3, MyLoss2 from .models.gcnet import GCNet from datetime import datetime #added by CCJ: def get_epe_rate2(disp, prediction, max_disp = 192, threshold = 1.0): mask =
np.logical_and(disp >= 0.001, disp <= max_disp)
numpy.logical_and
import numpy as np import numpy.testing as npt import freud import unittest import warnings import util class TestPMFTR12(unittest.TestCase): def test_box(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32) angles = np.array([0.0, 0.0], dtype=np.float32) maxR = 5.23 nbinsR = 10 nbinsT1 = 20 nbinsT2 = 30 myPMFT = freud.pmft.PMFTR12(maxR, nbinsR, nbinsT1, nbinsT2) myPMFT.accumulate(box, points, angles, points, angles) npt.assert_equal(myPMFT.box, freud.box.Box.square(boxSize)) # Ensure expected errors are raised box = freud.box.Box.cube(boxSize) with self.assertRaises(ValueError): myPMFT.accumulate(box, points, angles, points, angles) def test_r_cut(self): maxR = 5.23 nbinsR = 10 nbinsT1 = 20 nbinsT2 = 30 myPMFT = freud.pmft.PMFTR12(maxR, nbinsR, nbinsT1, nbinsT2) npt.assert_allclose(myPMFT.r_cut, maxR, atol=1e-6) def test_bins(self): maxR = 5.23 nbinsR = 10 nbinsT1 = 20 nbinsT2 = 30 dr = (maxR / float(nbinsR)) dT1 = (2.0 * np.pi / float(nbinsT1)) dT2 = (2.0 * np.pi / float(nbinsT2)) # make sure the radius for each bin is generated correctly listR = np.zeros(nbinsR, dtype=np.float32) listT1 = np.zeros(nbinsT1, dtype=np.float32) listT2 = np.zeros(nbinsT2, dtype=np.float32) for i in range(nbinsR): r = float(i) * dr nextr = float(i + 1) * dr listR[i] = 2.0/3.0 * ( nextr*nextr*nextr - r*r*r)/(nextr*nextr - r*r) for i in range(nbinsT1): t = float(i) * dT1 nextt = float(i + 1) * dT1 listT1[i] = ((t + nextt) / 2.0) for i in range(nbinsT2): t = float(i) * dT2 nextt = float(i + 1) * dT2 listT2[i] = ((t + nextt) / 2.0) myPMFT = freud.pmft.PMFTR12(maxR, nbinsR, nbinsT1, nbinsT2) # Compare expected bins to the info from pmft npt.assert_allclose(myPMFT.R, listR, atol=1e-3) npt.assert_allclose(myPMFT.T1, listT1, atol=1e-3) npt.assert_allclose(myPMFT.T2, listT2, atol=1e-3) npt.assert_equal(nbinsR, myPMFT.n_bins_R) npt.assert_equal(nbinsT1, myPMFT.n_bins_T1) npt.assert_equal(nbinsT2, myPMFT.n_bins_T2) inverse_jacobian = np.array( [[[1/(R*dr*dT1*dT2) for T1 in listT1] for T2 in listT2] for R in listR]) npt.assert_allclose(myPMFT.inverse_jacobian, inverse_jacobian, atol=1e-5) def test_attribute_access(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.1, 0.0]], dtype=np.float32) points.flags['WRITEABLE'] = False angles = np.array([0.0, np.pi/2], dtype=np.float32) angles.flags['WRITEABLE'] = False maxR = 5.23 nbinsR = 10 nbinsT1 = 20 nbinsT2 = 30 myPMFT = freud.pmft.PMFTR12(maxR, nbinsR, nbinsT1, nbinsT2) with self.assertRaises(AttributeError): myPMFT.PCF with self.assertRaises(AttributeError): myPMFT.bin_counts with self.assertRaises(AttributeError): myPMFT.box with self.assertRaises(AttributeError): myPMFT.PMFT myPMFT.accumulate(box, points, angles, points, angles) myPMFT.PCF myPMFT.bin_counts myPMFT.PMFT myPMFT.box npt.assert_equal(myPMFT.bin_counts.shape, (nbinsR, nbinsT2, nbinsT1)) npt.assert_equal(myPMFT.PCF.shape, (nbinsR, nbinsT2, nbinsT1)) npt.assert_equal(myPMFT.PMFT.shape, (nbinsR, nbinsT2, nbinsT1)) myPMFT.reset() with self.assertRaises(AttributeError): myPMFT.PCF with self.assertRaises(AttributeError): myPMFT.bin_counts with self.assertRaises(AttributeError): myPMFT.box with self.assertRaises(AttributeError): myPMFT.PMFT myPMFT.compute(box, points, angles, points, angles) myPMFT.PCF myPMFT.bin_counts myPMFT.PMFT myPMFT.box def test_two_particles(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.1, 0.0]], dtype=np.float32) points.flags['WRITEABLE'] = False angles = np.array([0.0, np.pi/2], dtype=np.float32) angles.flags['WRITEABLE'] = False maxR = 5.23 nbinsR = 10 nbinsT1 = 20 nbinsT2 = 30 dr = (maxR / float(nbinsR)) dT1 = (2.0 * np.pi / float(nbinsT1)) dT2 = (2.0 * np.pi / float(nbinsT2)) # calculation for array idxs def get_bin(point_i, point_j, angle_i, angle_j): delta_x = point_j - point_i r_bin = np.floor(np.linalg.norm(delta_x)/dr) delta_t1 = np.arctan2(delta_x[1], delta_x[0]) delta_t2 = np.arctan2(-delta_x[1], -delta_x[0]) t1_bin = np.floor(((angle_i - delta_t1) % (2. * np.pi))/dT1) t2_bin = np.floor(((angle_j - delta_t2) % (2. * np.pi))/dT2) return np.array([r_bin, t2_bin, t1_bin], dtype=np.int32) correct_bin_counts = np.zeros(shape=(nbinsR, nbinsT2, nbinsT1), dtype=np.int32) bins = get_bin(points[0], points[1], angles[0], angles[1]) correct_bin_counts[bins[0], bins[1], bins[2]] = 1 bins = get_bin(points[1], points[0], angles[1], angles[0]) correct_bin_counts[bins[0], bins[1], bins[2]] = 1 absoluteTolerance = 0.1 myPMFT = freud.pmft.PMFTR12(maxR, nbinsR, nbinsT1, nbinsT2) myPMFT.accumulate(box, points, angles, points, angles) npt.assert_allclose(myPMFT.bin_counts, correct_bin_counts, atol=absoluteTolerance) myPMFT.reset() myPMFT.compute(box, points, angles, points, angles) npt.assert_allclose(myPMFT.bin_counts, correct_bin_counts, atol=absoluteTolerance) myPMFT.compute(box, points, angles) npt.assert_allclose(myPMFT.bin_counts, correct_bin_counts, atol=absoluteTolerance) def test_repr(self): maxR = 5.23 nbinsR = 10 nbinsT1 = 20 nbinsT2 = 30 myPMFT = freud.pmft.PMFTR12(maxR, nbinsR, nbinsT1, nbinsT2) self.assertEqual(str(myPMFT), str(eval(repr(myPMFT)))) def test_ref_points_ne_points(self): r_max = 2.3 n_r = 10 n_t1 = 10 n_t2 = 10 pmft = freud.pmft.PMFTR12(r_max, n_r, n_t1, n_t2) lattice_size = 10 box = freud.box.Box.square(lattice_size*5) ref_points, points = util.make_alternating_lattice( lattice_size, 0.01, 2) ref_orientations = np.array([0]*len(ref_points)) orientations = np.array([0]*len(points)) pmft.compute(box, ref_points, ref_orientations, points, orientations) self.assertEqual(np.count_nonzero(np.isinf(pmft.PMFT) == 0), 12) self.assertEqual(len(np.unique(pmft.PMFT)), 3) class TestPMFTXYT(unittest.TestCase): def test_box(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32) angles = np.array([0.0, 0.0], dtype=np.float32) maxX = 3.6 maxY = 4.2 nbinsX = 20 nbinsY = 30 nbinsT = 40 myPMFT = freud.pmft.PMFTXYT(maxX, maxY, nbinsX, nbinsY, nbinsT) myPMFT.accumulate(box, points, angles, points, angles) npt.assert_equal(myPMFT.box, freud.box.Box.square(boxSize)) # Ensure expected errors are raised box = freud.box.Box.cube(boxSize) with self.assertRaises(ValueError): myPMFT.accumulate(box, points, angles, points, angles) def test_r_cut(self): maxX = 3.6 maxY = 4.2 nbinsX = 20 nbinsY = 30 nbinsT = 40 myPMFT = freud.pmft.PMFTXYT(maxX, maxY, nbinsX, nbinsY, nbinsT) npt.assert_allclose(myPMFT.r_cut, np.linalg.norm([maxX, maxY]), atol=1e-6) def test_bins(self): maxX = 3.6 maxY = 4.2 nbinsX = 20 nbinsY = 30 nbinsT = 40 dx = (2.0 * maxX / float(nbinsX)) dy = (2.0 * maxY / float(nbinsY)) dT = (2.0 * np.pi / float(nbinsT)) # make sure the center for each bin is generated correctly listX = np.zeros(nbinsX, dtype=np.float32) listY = np.zeros(nbinsY, dtype=np.float32) listT = np.zeros(nbinsT, dtype=np.float32) for i in range(nbinsX): x = float(i) * dx nextX = float(i + 1) * dx listX[i] = -maxX + ((x + nextX) / 2.0) for i in range(nbinsY): y = float(i) * dy nextY = float(i + 1) * dy listY[i] = -maxY + ((y + nextY) / 2.0) for i in range(nbinsT): t = float(i) * dT nextt = float(i + 1) * dT listT[i] = ((t + nextt) / 2.0) myPMFT = freud.pmft.PMFTXYT(maxX, maxY, nbinsX, nbinsY, nbinsT) # Compare expected bins to the info from pmft npt.assert_allclose(myPMFT.X, listX, atol=1e-3) npt.assert_allclose(myPMFT.Y, listY, atol=1e-3) npt.assert_allclose(myPMFT.T, listT, atol=1e-3) npt.assert_equal(nbinsX, myPMFT.n_bins_X) npt.assert_equal(nbinsY, myPMFT.n_bins_Y) npt.assert_equal(nbinsT, myPMFT.n_bins_T) npt.assert_allclose(myPMFT.jacobian, dx*dy*dT) def test_attribute_access(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.1, 0.0]], dtype=np.float32) angles = np.array([0.0, np.pi/2], dtype=np.float32) maxX = 3.6 maxY = 4.2 nbinsX = 20 nbinsY = 30 nbinsT = 40 myPMFT = freud.pmft.PMFTXYT(maxX, maxY, nbinsX, nbinsY, nbinsT) with self.assertRaises(AttributeError): myPMFT.PCF with self.assertRaises(AttributeError): myPMFT.bin_counts with self.assertRaises(AttributeError): myPMFT.box with self.assertRaises(AttributeError): myPMFT.PMFT myPMFT.accumulate(box, points, angles, points, angles) myPMFT.PCF myPMFT.bin_counts myPMFT.PMFT myPMFT.box npt.assert_equal(myPMFT.bin_counts.shape, (nbinsT, nbinsY, nbinsX)) npt.assert_equal(myPMFT.PCF.shape, (nbinsT, nbinsY, nbinsX)) npt.assert_equal(myPMFT.PMFT.shape, (nbinsT, nbinsY, nbinsX)) myPMFT.reset() with self.assertRaises(AttributeError): myPMFT.PCF with self.assertRaises(AttributeError): myPMFT.bin_counts with self.assertRaises(AttributeError): myPMFT.box with self.assertRaises(AttributeError): myPMFT.PMFT myPMFT.compute(box, points, angles, points, angles) myPMFT.PCF myPMFT.bin_counts myPMFT.PMFT myPMFT.box def test_two_particles(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.1, 0.0]], dtype=np.float32) angles = np.array([0.0, np.pi/2], dtype=np.float32) maxX = 3.6 maxY = 4.2 nbinsX = 20 nbinsY = 30 nbinsT = 40 dx = (2.0 * maxX / float(nbinsX)) dy = (2.0 * maxY / float(nbinsY)) dT = (2.0 * np.pi / float(nbinsT)) # calculation for array idxs def get_bin(point_i, point_j, angle_i, angle_j): delta_x = point_j - point_i rot_mat = np.array([[np.cos(-angle_i), -np.sin(-angle_i)], [np.sin(-angle_i), np.cos(-angle_i)]]) rot_delta_x = np.matmul(rot_mat, delta_x[:2]) xy_bins = np.floor((rot_delta_x + [maxX, maxY]) / [dx, dy]).astype(np.int32) angle_bin = np.floor( ((angle_j - np.arctan2(-delta_x[1], -delta_x[0])) % (2. * np.pi)) / dT).astype(np.int32) return [xy_bins[0], xy_bins[1], angle_bin] correct_bin_counts = np.zeros(shape=(nbinsT, nbinsY, nbinsX), dtype=np.int32) bins = get_bin(points[0], points[1], angles[0], angles[1]) correct_bin_counts[bins[2], bins[1], bins[0]] = 1 bins = get_bin(points[1], points[0], angles[1], angles[0]) correct_bin_counts[bins[2], bins[1], bins[0]] = 1 absoluteTolerance = 0.1 myPMFT = freud.pmft.PMFTXYT(maxX, maxY, nbinsX, nbinsY, nbinsT) myPMFT.accumulate(box, points, angles, points, angles) npt.assert_allclose(myPMFT.bin_counts, correct_bin_counts, atol=absoluteTolerance) myPMFT.reset() myPMFT.compute(box, points, angles, points, angles) npt.assert_allclose(myPMFT.bin_counts, correct_bin_counts, atol=absoluteTolerance) myPMFT.compute(box, points, angles) npt.assert_allclose(myPMFT.bin_counts, correct_bin_counts, atol=absoluteTolerance) def test_repr(self): maxX = 3.0 maxY = 4.0 nbinsX = 20 nbinsY = 30 nbinsT = 40 myPMFT = freud.pmft.PMFTXYT(maxX, maxY, nbinsX, nbinsY, nbinsT) self.assertEqual(str(myPMFT), str(eval(repr(myPMFT)))) def test_ref_points_ne_points(self): x_max = 2.5 y_max = 2.5 n_x = 10 n_y = 10 n_t = 4 pmft = freud.pmft.PMFTXYT(x_max, y_max, n_x, n_y, n_t) lattice_size = 10 box = freud.box.Box.square(lattice_size*5) ref_points, points = util.make_alternating_lattice( lattice_size, 0.01, 2) ref_orientations = np.array([0]*len(ref_points)) orientations = np.array([0]*len(points)) pmft.compute(box, ref_points, ref_orientations, points, orientations) # when rotated slightly, for each ref point, each quadrant # (corresponding to two consecutive bins) should contain 3 points. for i in range(n_t): self.assertEqual(np.count_nonzero(np.isinf(pmft.PMFT[i]) == 0), 3) self.assertEqual(len(np.unique(pmft.PMFT)), 2) class TestPMFTXY2D(unittest.TestCase): def test_box(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32) angles = np.array([0.0, 0.0], dtype=np.float32) maxX = 3.6 maxY = 4.2 nbinsX = 100 nbinsY = 110 myPMFT = freud.pmft.PMFTXY2D(maxX, maxY, nbinsX, nbinsY) myPMFT.accumulate(box, points, angles, points, angles) npt.assert_equal(myPMFT.box, freud.box.Box.square(boxSize)) # Ensure expected errors are raised box = freud.box.Box.cube(boxSize) with self.assertRaises(ValueError): myPMFT.accumulate(box, points, angles, points, angles) def test_r_cut(self): maxX = 3.6 maxY = 4.2 nbinsX = 100 nbinsY = 110 myPMFT = freud.pmft.PMFTXY2D(maxX, maxY, nbinsX, nbinsY) npt.assert_allclose(myPMFT.r_cut, np.linalg.norm([maxX, maxY]), atol=1e-6) def test_bins(self): maxX = 3.6 maxY = 4.2 nbinsX = 20 nbinsY = 30 dx = (2.0 * maxX / float(nbinsX)) dy = (2.0 * maxY / float(nbinsY)) # make sure the center for each bin is generated correctly listX = np.zeros(nbinsX, dtype=np.float32) listY = np.zeros(nbinsY, dtype=np.float32) for i in range(nbinsX): x = float(i) * dx nextX = float(i + 1) * dx listX[i] = -maxX + ((x + nextX) / 2.0) for i in range(nbinsY): y = float(i) * dy nextY = float(i + 1) * dy listY[i] = -maxY + ((y + nextY) / 2.0) myPMFT = freud.pmft.PMFTXY2D(maxX, maxY, nbinsX, nbinsY) # Compare expected bins to the info from pmft npt.assert_allclose(myPMFT.X, listX, atol=1e-3) npt.assert_allclose(myPMFT.Y, listY, atol=1e-3) npt.assert_equal(nbinsX, myPMFT.n_bins_X) npt.assert_equal(nbinsY, myPMFT.n_bins_Y) npt.assert_allclose(myPMFT.jacobian, dx*dy) def test_attribute_access(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32) angles = np.array([0.0, 0.0], dtype=np.float32) maxX = 3.6 maxY = 4.2 nbinsX = 100 nbinsY = 110 myPMFT = freud.pmft.PMFTXY2D(maxX, maxY, nbinsX, nbinsY) with self.assertRaises(AttributeError): myPMFT.PCF with self.assertRaises(AttributeError): myPMFT.bin_counts with self.assertRaises(AttributeError): myPMFT.box with self.assertRaises(AttributeError): myPMFT.PMFT myPMFT.accumulate(box, points, angles, points, angles) myPMFT.PCF myPMFT.bin_counts myPMFT.PMFT myPMFT.box npt.assert_equal(myPMFT.bin_counts.shape, (nbinsY, nbinsX)) npt.assert_equal(myPMFT.PCF.shape, (nbinsY, nbinsX)) npt.assert_equal(myPMFT.PMFT.shape, (nbinsY, nbinsX)) myPMFT.reset() with self.assertRaises(AttributeError): myPMFT.PCF with self.assertRaises(AttributeError): myPMFT.bin_counts with self.assertRaises(AttributeError): myPMFT.box with self.assertRaises(AttributeError): myPMFT.PMFT myPMFT.compute(box, points, angles, points, angles) myPMFT.PCF myPMFT.bin_counts myPMFT.PMFT myPMFT.box def test_two_particles(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32) angles = np.array([0.0, 0.0], dtype=np.float32) maxX = 3.6 maxY = 4.2 nbinsX = 100 nbinsY = 110 dx = (2.0 * maxX / float(nbinsX)) dy = (2.0 * maxY / float(nbinsY)) correct_bin_counts = np.zeros(shape=(nbinsY, nbinsX), dtype=np.int32) # calculation for array idxs def get_bin(point_i, point_j): return np.floor((point_i - point_j + [maxX, maxY, 0]) / [dx, dy, 1]).astype(np.int32)[:2] bins = get_bin(points[0], points[1]) correct_bin_counts[bins[1], bins[0]] = 1 bins = get_bin(points[1], points[0]) correct_bin_counts[bins[1], bins[0]] = 1 absoluteTolerance = 0.1 myPMFT = freud.pmft.PMFTXY2D(maxX, maxY, nbinsX, nbinsY) myPMFT.accumulate(box, points, angles, points, angles) npt.assert_allclose(myPMFT.bin_counts, correct_bin_counts, atol=absoluteTolerance) myPMFT.reset() myPMFT.compute(box, points, angles, points, angles) npt.assert_allclose(myPMFT.bin_counts, correct_bin_counts, atol=absoluteTolerance) myPMFT.compute(box, points, angles) npt.assert_allclose(myPMFT.bin_counts, correct_bin_counts, atol=absoluteTolerance) def test_repr(self): maxX = 3.0 maxY = 4.0 nbinsX = 100 nbinsY = 110 myPMFT = freud.pmft.PMFTXY2D(maxX, maxY, nbinsX, nbinsY) self.assertEqual(str(myPMFT), str(eval(repr(myPMFT)))) def test_repr_png(self): boxSize = 16.0 box = freud.box.Box.square(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32) angles = np.array([0.0, 0.0], dtype=np.float32) maxX = 3.6 maxY = 4.2 nbinsX = 100 nbinsY = 110 myPMFT = freud.pmft.PMFTXY2D(maxX, maxY, nbinsX, nbinsY) with self.assertRaises(AttributeError): myPMFT.plot() self.assertEqual(myPMFT._repr_png_(), None) myPMFT.accumulate(box, points, angles, points, angles) myPMFT._repr_png_() def test_ref_points_ne_points(self): x_max = 2.5 y_max = 2.5 n_x = 20 n_y = 20 pmft = freud.pmft.PMFTXY2D(x_max, y_max, n_x, n_y) lattice_size = 10 box = freud.box.Box.square(lattice_size*5) ref_points, points = util.make_alternating_lattice( lattice_size, 0.01, 2) ref_orientations = np.array([0]*len(ref_points)) orientations = np.array([0]*len(points)) pmft.compute(box, ref_points, ref_orientations, points, orientations) self.assertEqual(np.count_nonzero(np.isinf(pmft.PMFT) == 0), 12) self.assertEqual(len(np.unique(pmft.PMFT)), 2) class TestPMFTXYZ(unittest.TestCase): def test_box(self): boxSize = 25.0 box = freud.box.Box.cube(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32) orientations = np.array([[1, 0, 0, 0], [1, 0, 0, 0]], dtype=np.float32) maxX = 5.23 maxY = 6.23 maxZ = 7.23 nbinsX = 100 nbinsY = 110 nbinsZ = 120 myPMFT = freud.pmft.PMFTXYZ(maxX, maxY, maxZ, nbinsX, nbinsY, nbinsZ) myPMFT.accumulate(box, points, orientations, points, orientations) npt.assert_equal(myPMFT.box, freud.box.Box.cube(boxSize)) # Ensure expected errors are raised box = freud.box.Box.square(boxSize) with self.assertRaises(ValueError): myPMFT.accumulate(box, points, orientations, points, orientations) def test_r_cut(self): maxX = 5.23 maxY = 6.23 maxZ = 7.23 nbinsX = 100 nbinsY = 110 nbinsZ = 120 myPMFT = freud.pmft.PMFTXYZ(maxX, maxY, maxZ, nbinsX, nbinsY, nbinsZ) r_cut = np.linalg.norm([maxX, maxY, maxZ]) npt.assert_allclose(myPMFT.r_cut, r_cut, atol=1e-6) def test_bins(self): maxX = 5.23 maxY = 6.23 maxZ = 7.23 nbinsX = 100 nbinsY = 110 nbinsZ = 120 dx = (2.0 * maxX / float(nbinsX)) dy = (2.0 * maxY / float(nbinsY)) dz = (2.0 * maxZ / float(nbinsZ)) listX = np.zeros(nbinsX, dtype=np.float32) listY = np.zeros(nbinsY, dtype=np.float32) listZ = np.zeros(nbinsZ, dtype=np.float32) for i in range(nbinsX): x = float(i) * dx nextX = float(i + 1) * dx listX[i] = -maxX + ((x + nextX) / 2.0) for i in range(nbinsY): y = float(i) * dy nextY = float(i + 1) * dy listY[i] = -maxY + ((y + nextY) / 2.0) for i in range(nbinsZ): z = float(i) * dz nextZ = float(i + 1) * dz listZ[i] = -maxZ + ((z + nextZ) / 2.0) myPMFT = freud.pmft.PMFTXYZ(maxX, maxY, maxZ, nbinsX, nbinsY, nbinsZ) # Compare expected bins to the info from pmft npt.assert_allclose(myPMFT.X, listX, atol=1e-3) npt.assert_allclose(myPMFT.Y, listY, atol=1e-3) npt.assert_allclose(myPMFT.Z, listZ, atol=1e-3) npt.assert_equal(nbinsX, myPMFT.n_bins_X) npt.assert_equal(nbinsY, myPMFT.n_bins_Y) npt.assert_equal(nbinsZ, myPMFT.n_bins_Z) npt.assert_allclose(myPMFT.jacobian, dx*dy*dz) def test_attribute_access(self): boxSize = 25.0 box = freud.box.Box.cube(boxSize) points = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32) orientations =
np.array([[1, 0, 0, 0], [1, 0, 0, 0]], dtype=np.float32)
numpy.array
##################################################################### # # # /NovaTechDDS9M.py # # # # Copyright 2013, Monash University # # # # This file is part of the module labscript_devices, in the # # labscript suite (see http://labscriptsuite.org), and is # # licensed under the Simplified BSD License. See the license.txt # # file in the root of the project for the full license. # # # ##################################################################### from labscript_devices import runviewer_parser, BLACS_tab from labscript import IntermediateDevice, DDS, StaticDDS, Device, config, LabscriptError, set_passed_properties from labscript_utils.unitconversions import NovaTechDDS9mFreqConversion, NovaTechDDS9mAmpConversion import numpy as np import labscript_utils.h5_lock, h5py import labscript_utils.properties bauds = {9600: b'Kb 78', 19200: b'Kb 3c', 38400: b'Kb 1e', 57600: b'Kb 14', 115200: b'Kb 0a'} class NovaTechDDS9M(IntermediateDevice): """ This class is initilzed with the key word argument 'update_mode' -- synchronous or asynchronous\ 'baud_rate', -- operating baud rate 'default_baud_rate' -- assumed baud rate at startup """ description = 'NT-DDS9M' allowed_children = [DDS, StaticDDS] clock_limit = 9990 # This is a realistic estimate of the max clock rate (100us for TS/pin10 processing to load next value into buffer and 100ns pipeline delay on pin 14 edge to update output values) @set_passed_properties( property_names={ 'connection_table_properties': [ 'com_port', 'baud_rate', 'default_baud_rate', 'update_mode', 'synchronous_first_line_repeat', 'phase_mode', ] } ) def __init__( self, name, parent_device, com_port="", baud_rate=115200, default_baud_rate=None, update_mode='synchronous', synchronous_first_line_repeat=False, phase_mode='continuous', **kwargs ): IntermediateDevice.__init__(self, name, parent_device, **kwargs) self.BLACS_connection = '%s,%s'%(com_port, str(baud_rate)) if not update_mode in ['synchronous', 'asynchronous']: raise LabscriptError('update_mode must be \'synchronous\' or \'asynchronous\'') if not baud_rate in bauds: raise LabscriptError('baud_rate must be one of {0}'.format(list(bauds))) if not default_baud_rate in bauds and default_baud_rate is not None: raise LabscriptError('default_baud_rate must be one of {0} or None (to indicate no default)'.format(list(bauds))) if not phase_mode in ['aligned', 'continuous']: raise LabscriptError('phase_mode must be \'aligned\' or \'continuous\'') self.update_mode = update_mode self.phase_mode = phase_mode self.synchronous_first_line_repeat = synchronous_first_line_repeat def add_device(self, device): Device.add_device(self, device) # The Novatech doesn't support 0Hz output; set the default frequency of the DDS to 0.1 Hz: device.frequency.default_value = 0.1 def get_default_unit_conversion_classes(self, device): """Child devices call this during their __init__ (with themselves as the argument) to check if there are certain unit calibration classes that they should apply to their outputs, if the user has not otherwise specified a calibration class""" return NovaTechDDS9mFreqConversion, NovaTechDDS9mAmpConversion, None def quantise_freq(self, data, device): if not isinstance(data, np.ndarray): data = np.array(data) # Ensure that frequencies are within bounds: if
np.any(data > 171e6 )
numpy.any
# import standard plotting and animation import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec from matplotlib.ticker import FormatStrFormatter import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D from IPython.display import clear_output import matplotlib.ticker as ticker # import standard libraries import math import time import copy from inspect import signature class Visualizer: ''' animators for time series ''' #### animate moving average #### def animate_system(self,x,y,T,savepath,**kwargs): # produce figure fig = plt.figure(figsize = (9,4)) gs = gridspec.GridSpec(1, 3, width_ratios=[1,7,1]) ax = plt.subplot(gs[0]); ax.axis('off') ax1 = plt.subplot(gs[1]); ax2 = plt.subplot(gs[2]); ax2.axis('off') artist = fig # view limits xmin = -3 xmax = len(x) + 3 ymin = np.min(x) ymax = np.max(x) ygap = (ymax - ymin)*0.15 ymin -= ygap ymax += ygap # start animation num_frames = len(y) - T + 1 print ('starting animation rendering...') def animate(k): # clear panels ax1.cla() # print rendering update if np.mod(k+1,25) == 0: print ('rendering animation frame ' + str(k+1) + ' of ' + str(num_frames)) if k == num_frames - 1: print ('animation rendering complete!') time.sleep(1.5) clear_output() # plot x ax1.scatter(np.arange(1,x.size + 1),x,c = 'k',edgecolor = 'w',s = 40,linewidth = 1,zorder = 3); ax1.plot(np.arange(1,x.size + 1),x,alpha = 0.5,c = 'k',zorder = 3); # plot moving average - initial conditions if k == 1: # plot x ax1.scatter(np.arange(1,T + 1), y[:T],c = 'darkorange',edgecolor = 'w',s = 120,linewidth = 1,zorder = 2); ax1.plot(np.arange(1,T + 1), y[:T],alpha = 0.5,c = 'darkorange',zorder = 2); # make vertical visual guides ax1.axvline(x = 1, c='deepskyblue') ax1.axvline(x = T, c='deepskyblue') # plot moving average - everything after and including initial conditions if k > 1: j = k-1 # plot ax1.scatter(np.arange(1,T + j + 1),y[:T + j],c = 'darkorange',edgecolor = 'w',s = 120,linewidth = 1,zorder = 2); ax1.plot(np.arange(1,T + j + 1),y[:T + j],alpha = 0.5,c = 'darkorange',zorder = 2); # make vertical visual guides ax1.axvline(x = j, c='deepskyblue') ax1.axvline(x = j + T - 1, c='deepskyblue') # label axes ax1.set_xlim([xmin,xmax]) ax1.set_ylim([ymin,ymax]) return artist, anim = animation.FuncAnimation(fig, animate ,frames=num_frames, interval=num_frames, blit=True) # produce animation and save fps = 50 if 'fps' in kwargs: fps = kwargs['fps'] anim.save(savepath, fps=fps, extra_args=['-vcodec', 'libx264']) clear_output() #### animate range of moving average calculations #### def animate_system_range(self,x,func,params,savepath,**kwargs): playback = 1 if 'playback' in kwargs: playback = kwargs['playback'] # produce figure fig = plt.figure(figsize = (9,4)) gs = gridspec.GridSpec(1, 3, width_ratios=[1,7,1]) ax = plt.subplot(gs[0]); ax.axis('off') ax1 = plt.subplot(gs[1]); ax2 = plt.subplot(gs[2]); ax2.axis('off') artist = fig # view limits xmin = -3 xmax = len(x) + 3 ymin = np.min(x) ymax = np.max(x) ygap = (ymax - ymin)*0.15 ymin -= ygap ymax += ygap # start animation num_frames = len(params)+1 print ('starting animation rendering...') def animate(k): # clear panels ax1.cla() # print rendering update if np.mod(k+1,25) == 0: print ('rendering animation frame ' + str(k+1) + ' of ' + str(num_frames)) if k == num_frames - 1: print ('animation rendering complete!') time.sleep(1.5) clear_output() # plot x ax1.scatter(np.arange(1,x.size + 1),x,c = 'k',edgecolor = 'w',s = 40,linewidth = 1,zorder = 3); ax1.plot(np.arange(1,x.size + 1),x,alpha = 0.5,c = 'k',zorder = 3); # create y if k == 0: T = params[0] y = func(x,T) ax1.set_title(r'Original data') if k > 0: T = params[k-1] y = func(x,T) ax1.scatter(np.arange(1,y.size + 1),y,c = 'darkorange',edgecolor = 'w',s = 120,linewidth = 1,zorder = 2); ax1.plot(np.arange(1,y.size + 1),y,alpha = 0.5,c = 'darkorange',zorder = 2); ax1.set_title(r'$D = $ ' + str(T)) # label axes ax1.set_xlabel(r'$p$',fontsize = 13) ax1.set_xlim([xmin,xmax]) ax1.set_ylim([ymin,ymax]) return artist, anim = animation.FuncAnimation(fig, animate ,frames=num_frames, interval=num_frames, blit=True) # produce animation and save if 'fps' in kwargs: fps = kwargs['fps'] anim.save(savepath, fps=1, extra_args=['-vcodec', 'libx264']) clear_output() #### animate vector system with heatmap #### def animate_vector_system(self,x,D,model,func,savepath,**kwargs): x = np.array(x) h,old_bins = func([0]) bins = [] for i in range(len(old_bins)-1): b1 = old_bins[i] b2 = old_bins[i+1] n = (b1 + b2)/2 n = np.round(n,2) bins.append(n) y = model(x,D,func) num_windows = len(y) - 1 # produce figure fig = plt.figure(figsize = (11,10)) gs = gridspec.GridSpec(2, 3, width_ratios=[1,7,1],height_ratios=[0.75,1]) ax1 = plt.subplot(gs[0]); ax1.axis('off') ax2 = plt.subplot(gs[1]); ax3 = plt.subplot(gs[2]); ax3.axis('off') ax4 = plt.subplot(gs[3]); ax4.axis('off') ax5 = plt.subplot(gs[4]); ax6 = plt.subplot(gs[5]); ax6.axis('off') artist = fig # view limits xmin = -3 xmax = len(x) + 3 ymin = np.min(x) ymax = np.max(x) ygap = (ymax - ymin)*0.15 ymin -= ygap ymax += ygap # make colormap # a,b = np.meshgrid(np.arange(num_windows+1),np.arange(len(bins)-1)) # s = ax1.pcolormesh(a, b, np.array(y).T,cmap = 'hot',vmin = 0,vmax = 1) #,edgecolor = 'k') # hot, gist_heat, cubehelix # ax1.cla(); ax1.axis('off'); # fig.colorbar(s, ax=ax5) # start animation num_frames = len(x) - D + 2 print ('starting animation rendering...') def animate(k): # clear panels ax2.cla() ax5.cla() # print rendering update if np.mod(k+1,25) == 0: print ('rendering animation frame ' + str(k+1) + ' of ' + str(num_frames)) if k == num_frames - 1: print ('animation rendering complete!') time.sleep(1.5) clear_output() # plot x ax2.scatter(np.arange(1,x.size + 1),x,c = 'k',edgecolor = 'w',s = 80,linewidth = 1,zorder = 3); ax2.plot(np.arange(1,x.size + 1),x,alpha = 0.5,c = 'k',zorder = 3); # plot moving average - initial conditions if k == 0: # plot x ax2.scatter(np.arange(1,D + 1), x[:D],c = 'darkorange',edgecolor = 'w',s = 200,linewidth = 1,zorder = 2); ax2.plot(np.arange(1,D + 1), x[:D],alpha = 0.5,c = 'darkorange',zorder = 2); # make vertical visual guides ax2.axvline(x = 1, c='deepskyblue') ax2.axvline(x = D, c='deepskyblue') # plot histogram self.plot_heatmap(ax5,y[:2],bins,num_windows) # plot moving average - everything after and including initial conditions if k > 0: j = k # plot ax2.scatter(np.arange(j,D + j),x[j-1:D + j - 1],c = 'darkorange',edgecolor = 'w',s = 200,linewidth = 1,zorder = 2); ax2.plot(np.arange(j,D + j),x[j-1:D + j - 1],alpha = 0.5,c = 'darkorange',zorder = 2); # make vertical visual guides ax2.axvline(x = j, c='deepskyblue') ax2.axvline(x = j + D - 1, c='deepskyblue') # plot histogram self.plot_heatmap(ax5,y[:j+1],bins,num_windows) # label axes ax2.set_xlim([xmin,xmax]) ax2.set_ylim([ymin,ymax]) return artist, anim = animation.FuncAnimation(fig, animate ,frames=num_frames, interval=num_frames, blit=True) # produce animation and save fps = 50 if 'fps' in kwargs: fps = kwargs['fps'] anim.save(savepath, fps=fps, extra_args=['-vcodec', 'libx264']) clear_output() def plot_heatmap(self,ax,y,bins,num_windows): y=np.array(y).T ### plot ### num_chars,num_samples = y.shape num_chars += 1 a,b = np.meshgrid(np.arange(num_samples),np.arange(num_chars)) ### y-axis Customize minor tick labels ### # make custom labels num_bins = len(bins)+1 y_ticker_range = np.arange(0.5,num_bins,10).tolist() new_bins = [bins[v] for v in range(0,len(bins),10)] y_char_range = [str(s) for s in new_bins] # assign major or minor ticklabels? - chosen major by default ax.yaxis.set_major_locator(ticker.FixedLocator(y_ticker_range)) ax.yaxis.set_major_formatter(ticker.FixedFormatter(y_char_range)) ax.xaxis.set_ticks_position('bottom') # the rest is the same ax.set_xticks([],[]) ax.set_yticks([],[]) ax.set_ylabel('values',rotation = 90,fontsize=15) ax.set_xlabel('window',fontsize=15) # ax.set_title(title,fontsize = 15) cmap = 'hot_r' #cmap = 'RdPu' s = ax.pcolormesh(a, b, 4*y,cmap = cmap,vmin = 0,vmax = 1) #,edgecolor = 'k') # hot, gist_heat, cubehelix ax.set_ylim([-1,len(bins)]) ax.set_xlim([0,num_windows]) # for i in range(len(bins)): # ax.hlines(y=i, xmin=0, xmax=num_windows, linewidth=1, color='k',alpha = 0.75) #### animate vector system with heatmap #### def animate_vector_histogram(self,x,D,model,func,savepath,**kwargs): x = np.array(x) h,old_bins = func([0]) bins = [] for i in range(len(old_bins)-1): b1 = old_bins[i] b2 = old_bins[i+1] n = (b1 + b2)/2 n = np.round(n,2) bins.append(n) y = model(x,D,func) num_windows = len(y) - 1 # produce figure fig = plt.figure(figsize = (11,10)) gs = gridspec.GridSpec(3, 3, width_ratios=[1,7,1],height_ratios=[1,1,1.5]) ax1 = plt.subplot(gs[0]); ax1.axis('off') ax2 = plt.subplot(gs[1]); ax3 = plt.subplot(gs[2]); ax3.axis('off') axa = plt.subplot(gs[3]); axa.axis('off') axb = plt.subplot(gs[7]); axc = plt.subplot(gs[5]); axc.axis('off') ax4 = plt.subplot(gs[6]); ax4.axis('off') ax5 = plt.subplot(gs[4]); ax6 = plt.subplot(gs[8]); ax6.axis('off') artist = fig # view limits xmin = -3 xmax = len(x) + 3 ymin = np.min(x) ymax = np.max(x) ygap = (ymax - ymin)*0.15 ymin -= ygap ymax += ygap # start animation num_frames = len(x) - D + 2 print ('starting animation rendering...') def animate(k): # clear panels ax2.cla() ax5.cla() axb.cla() # print rendering update if np.mod(k+1,25) == 0: print ('rendering animation frame ' + str(k+1) + ' of ' + str(num_frames)) if k == num_frames - 1: print ('animation rendering complete!') time.sleep(1.5) clear_output() # plot x ax2.scatter(np.arange(1,x.size + 1),x,c = 'k',edgecolor = 'w',s = 80,linewidth = 1,zorder = 3); ax2.plot(np.arange(1,x.size + 1),x,alpha = 0.5,c = 'k',zorder = 3); # plot moving average - initial conditions if k == 0: # plot x ax2.scatter(np.arange(1,D + 1), x[:D],c = 'darkorange',edgecolor = 'w',s = 200,linewidth = 1,zorder = 2); ax2.plot(np.arange(1,D + 1), x[:D],alpha = 0.5,c = 'darkorange',zorder = 2); # make vertical visual guides ax2.axvline(x = 1, c='deepskyblue') ax2.axvline(x = D, c='deepskyblue') # plot histogram self.plot_histogram(ax5,y[0],bins) self.plot_heatmap(axb,y[:2],bins,num_windows) # plot moving average - everything after and including initial conditions if k > 0: j = k # plot ax2.scatter(np.arange(j,D + j),x[j-1:D + j - 1],c = 'darkorange',edgecolor = 'w',s = 200,linewidth = 1,zorder = 2); ax2.plot(np.arange(j,D + j),x[j-1:D + j - 1],alpha = 0.5,c = 'darkorange',zorder = 2); # make vertical visual guides ax2.axvline(x = j, c='deepskyblue') ax2.axvline(x = j + D - 1, c='deepskyblue') # plot histogram self.plot_histogram(ax5,y[j],bins) # plot histogram self.plot_heatmap(axb,y[:j+1],bins,num_windows) # label axes ax2.set_xlim([xmin,xmax]) ax2.set_ylim([ymin,ymax]) ax2.set_xlabel(r'$p$',fontsize=14) ax2.set_ylabel(r'$x_p$',rotation=0,fontsize=14) return artist, anim = animation.FuncAnimation(fig, animate ,frames=num_frames, interval=num_frames, blit=True) # produce animation and save fps = 50 if 'fps' in kwargs: fps = kwargs['fps'] anim.save(savepath, fps=fps, extra_args=['-vcodec', 'libx264']) clear_output() def plot_histogram(self,ax,h,bins,**kwargs): # plot hist ax.bar(bins,h,align='center',width=0.1,edgecolor='k',color='magenta',linewidth=1.5) # label axes ax.set_xlabel(r'$values$',fontsize = 13) ax.set_ylabel(r'count',fontsize = 13,rotation = 90,labelpad = 15) ymin = 0 xmin = min(bins) - 0.1 xmax = max(bins) + 0.1 ymax = 0.5 ax.set_xlim([xmin,xmax]) ax.set_ylim([ymin,ymax]) #### animate spectrogram construction #### def animate_dct_spectrogram(self,x,D,model,func,savepath,**kwargs): # produce heatmap y = model(x,D,func) num_windows = y.shape[1]-1 # produce figure fig = plt.figure(figsize = (12,8)) gs = gridspec.GridSpec(2, 3, width_ratios=[1,7,1],height_ratios=[1,1]) ax1 = plt.subplot(gs[0]); ax1.axis('off') ax2 = plt.subplot(gs[1]); ax3 = plt.subplot(gs[2]); ax3.axis('off') ax4 = plt.subplot(gs[3]); ax4.axis('off') ax5 = plt.subplot(gs[4]); ax5.set_yticks([],[]) ax5.axis('off') ax6 = plt.subplot(gs[5]); ax6.axis('off') artist = fig # view limits for top panel xmin = -3 xmax = len(x) + 3 ymin = np.min(x) ymax = np.max(x) ygap = (ymax - ymin)*0.15 ymin -= ygap ymax += ygap vmin = np.min(np.log(1 + y).flatten()) vmax = np.max(np.log(1 + y).flatten()) # start animation num_frames = len(x) - D + 2 print ('starting animation rendering...') def animate(k): # clear panels ax2.cla() ax5.cla() # print rendering update if np.mod(k+1,25) == 0: print ('rendering animation frame ' + str(k+1) + ' of ' + str(num_frames)) if k == num_frames - 1: print ('animation rendering complete!') time.sleep(1.5) clear_output() # plot signal ax2.plot(np.arange(1,x.size + 1),x,alpha = 0.5,c = 'k',zorder = 3); # plot moving average - initial conditions if k == 0: # plot x ax2.plot(np.arange(1,D + 1), x[:D],alpha = 0.5,c = 'magenta',zorder = 2,linewidth=8); # plot spectrogram ax5.imshow(np.log(1 + y[:,:1]),aspect='auto',cmap='jet',origin='lower',vmin = vmin, vmax = vmax) # plot moving average - everything after and including initial conditions if k > 0: j = k # plot ax2.plot(np.arange(j,D + j),x[j-1:D + j - 1],alpha = 0.5,c = 'magenta',zorder = 2,linewidth=8); # plot histogram ax5.imshow(np.log(1 + y[:,:j+1]),aspect='auto',cmap='jet',origin='lower', vmin = vmin, vmax = vmax) # label axes ax2.set_xlim([xmin,xmax]) ax2.set_ylim([ymin,ymax]) ax2.set_xlabel(r'$p$',fontsize=14) ax2.set_ylabel(r'$x_p$',rotation=0,fontsize=14) ax5.set_xlim([0,num_windows]) return artist, anim = animation.FuncAnimation(fig, animate ,frames=num_frames, interval=num_frames, blit=True) # produce animation and save fps = 50 if 'fps' in kwargs: fps = kwargs['fps'] anim.save(savepath, fps=fps, extra_args=['-vcodec', 'libx264']) clear_output() #### animate spectrogram construction #### def animate_mlp_outputs(self,x,D,model,func,savepath,**kwargs): # produce heatmap y = model(x,D,func) num_windows = y.shape[1]-1 # produce figure fig = plt.figure(figsize = (12,8)) gs = gridspec.GridSpec(2, 3, width_ratios=[1,7,1],height_ratios=[1,1]) ax1 = plt.subplot(gs[0]); ax1.axis('off') ax2 = plt.subplot(gs[1]); ax3 = plt.subplot(gs[2]); ax3.axis('off') ax4 = plt.subplot(gs[3]); ax4.axis('off') ax5 = plt.subplot(gs[4]); ax5.set_yticks([],[]) ax5.axis('off') ax6 = plt.subplot(gs[5]); ax6.axis('off') artist = fig # view limits for top panel xmin = -3 xmax = len(x) + 3 ymin = np.min(x) ymax = np.max(x) ygap = (ymax - ymin)*0.15 ymin -= ygap ymax += ygap vmin = np.min(
np.log(1 + y)
numpy.log
import os import cv2 import tqdm import torch import numpy as np import seaborn as sns import pandas as pd import codecs import json import matplotlib.pyplot as plt plt.switch_backend('agg') from solver import Solver from models.model import Model from datasets.steel_dataset import provider from utils.set_seed import seed_torch from utils.cal_dice_iou import compute_dice_class from config import get_seg_config class ChooseThresholdMinArea(): ''' 选择每一类的像素阈值和最小连通域 ''' def __init__(self, model, model_name, valid_loader, fold, save_path, class_num=4): ''' 模型初始化 Args: model: 使用的模型 model_name: 当前模型的名称 valid_loader: 验证数据的Dataloader fold: 当前为多少折 save_path: 保存结果的路径 class_num: 有多少个类别 ''' self.model = model self.model_name = model_name self.valid_loader = valid_loader self.fold = fold self.save_path = save_path self.class_num = class_num self.model.eval() self.solver = Solver(model) def choose_threshold_minarea(self): ''' 采用网格法搜索各个类别最优像素阈值和最优最小连通域,并画出各个类别搜索过程中的热力图 Return: best_thresholds_little: 每一个类别的最优阈值 best_minareas_little: 每一个类别的最优最小连通取余 max_dices_little: 每一个类别的最大dice值 ''' init_thresholds_range, init_minarea_range = np.arange(0.50, 0.71, 0.03), np.arange(768, 2305, 256) # 阈值列表和最小连通域列表,大小为 Nx4 thresholds_table_big = np.array([init_thresholds_range, init_thresholds_range, \ init_thresholds_range, init_thresholds_range]) # 阈值列表 minareas_table_big = np.array([init_minarea_range, init_minarea_range, \ init_minarea_range, init_minarea_range]) # 最小连通域列表 f, axes = plt.subplots(figsize=(28.8, 18.4), nrows=2, ncols=self.class_num) cmap = sns.cubehelix_palette(start=1.5, rot=3, gamma=0.8, as_cmap=True) best_thresholds_big, best_minareas_big, max_dices_big = self.grid_search(thresholds_table_big, minareas_table_big, axes[0,:], cmap) print('best_thresholds_big:{}, best_minareas_big:{}, max_dices_big:{}'.format(best_thresholds_big, best_minareas_big, max_dices_big)) # 开始细分类 thresholds_table_little, minareas_table_little = list(), list() for best_threshold_big, best_minarea_big in zip(best_thresholds_big, best_minareas_big): thresholds_table_little.append(np.arange(best_threshold_big-0.03, best_threshold_big+0.03, 0.015)) # 阈值列表 minareas_table_little.append(np.arange(best_minarea_big-256, best_minarea_big+257, 128)) # 像素阈值列表 thresholds_table_little, minareas_table_little = np.array(thresholds_table_little), np.array(minareas_table_little) best_thresholds_little, best_minareas_little, max_dices_little = self.grid_search(thresholds_table_little, minareas_table_little, axes[1,:], cmap) print('best_thresholds_little:{}, best_minareas_little:{}, max_dices_little:{}'.format(best_thresholds_little, best_minareas_little, max_dices_little)) f.savefig(os.path.join(self.save_path, self.model_name + '_fold'+str(self.fold)), bbox_inches='tight') # plt.show() plt.close() return best_thresholds_little, [float(x) for x in best_minareas_little], max_dices_little def grid_search(self, thresholds_table, minareas_table, axes, cmap): ''' 给定包含各个类别搜索区间的thresholds_table和minareas_table,求的各个类别的最优像素阈值,最优最小连通域,最高dice; 并画出各个类别搜索过程中的热力图 Args: thresholds_table: 待搜索的阈值范围,维度为[4, N],numpy类型 minareas_table: 待搜索的最小连通域范围,维度为[4, N],numpy类型 axes: 画各个类别搜索热力图时所需要的画柄,尺寸为[class_num] cmap: 画图时所需要的cmap return: best_thresholds: 各个类别的最优像素阈值,尺寸为[class_num] best_minareas: 各个类别的最优最小连通域,尺寸为[class_num] max_dices: 各个类别的最大dice,尺寸为[class_num] ''' dices_table = np.zeros((self.class_num, np.shape(thresholds_table)[1], np.shape(minareas_table)[1])) tbar = tqdm.tqdm(self.valid_loader) with torch.no_grad(): for i, samples in enumerate(tbar): if len(samples) == 0: continue images, masks = samples[0], samples[1] # 完成网络的前向传播 masks_predict_allclasses = self.solver.forward(images) dices_table += self.grid_search_batch(thresholds_table, minareas_table, masks_predict_allclasses, masks) dices_table = dices_table/len(tbar) best_thresholds, best_minareas, max_dices = list(), list(), list() # 处理每一类的预测结果 for each_class, dices_oneclass_table in enumerate(dices_table): max_dice = np.max(dices_oneclass_table) max_location = np.unravel_index(np.argmax(dices_oneclass_table, axis=None), dices_oneclass_table.shape) best_thresholds.append(thresholds_table[each_class, max_location[0]]) best_minareas.append(minareas_table[each_class, max_location[1]]) max_dices.append(max_dice) data = pd.DataFrame(data=dices_oneclass_table, index=np.around(thresholds_table[each_class,:], 3), columns=minareas_table[each_class,:]) sns.heatmap(data, linewidths=0.05, ax=axes[each_class], vmax=np.max(dices_oneclass_table), vmin=np.min(dices_oneclass_table), cmap=cmap, annot=True, fmt='.4f') axes[each_class].set_title('search result') return best_thresholds, best_minareas, max_dices def grid_search_batch(self, thresholds_table, minareas_table, masks_predict_allclasses, masks_allclasses): '''给定thresholds、minareas矩阵、一个batch的预测结果和真实标签,遍历每个类的每一个组合得到对应的dice值 Args: thresholds_table: 待搜索的阈值范围,维度为[4, N],numpy类型 minareas_table: 待搜索的最小连通域范围,维度为[4, N],numpy类型 masks_predict_allclasses: 所有类别的某个batch的预测结果且未经过sigmoid,维度为[batch_size, class_num, height, width] masks_allclasses: 所有类别的某个batch的真实类标,维度为[batch_size, class_num, height, width] Return: dices_table: 各个类别在其各自的所有搜索组合中所得到的dice值,维度为[4, M, N] ''' # 得到每一个类别的搜索阈值区间和最小连通域搜索区间 dices_table = list() for each_class, (thresholds_range, minareas_range) in enumerate(zip(thresholds_table, minareas_table)): # 得到每一类的预测结果和真实类标 masks_predict_oneclass = masks_predict_allclasses[:, each_class, ...] masks_oneclasses = masks_allclasses[:, each_class, ...] dices_range = self.post_process(thresholds_range, minareas_range, masks_predict_oneclass, masks_oneclasses) dices_table.append(dices_range) # 得到的大小为 4 x len(thresholds_range) x len(minareas_range) return np.array(dices_table) def post_process(self, thresholds_range, minareas_range, masks_predict_oneclass, masks_oneclasses): '''给定某个类别的某个batch的数据,遍历所有搜索组合,得到每个组合的dice值 Args: thresholds_range: 具体某个类别的像素阈值搜索区间,尺寸为[M] minareas_range: 具体某个类别的最小连通域搜索区间,尺寸为[N] masks_predict_oneclass: 预测出的某个类别的该batch的tensor向量且未经过sigmoid,维度为[batch_size, height, width] masks_oneclasses: 某个类别的该batch的真实类标,维度为[batch_size, height, width] Return: dices_range: 某个类别的该batch的所有搜索组合得到dice矩阵,维度为[M, N] ''' # 注意,损失函数中包含sigmoid函数,一般情况下需要手动经过sigmoid函数 masks_predict_oneclass = torch.sigmoid(masks_predict_oneclass).detach().cpu().numpy() dices_range = np.zeros((len(thresholds_range), len(minareas_range))) # 遍历每一个像素阈值和最小连通域 for index_threshold, threshold in enumerate(thresholds_range): for index_minarea, minarea in enumerate(minareas_range): batch_preds = list() # 遍历每一张图片 for pred in masks_predict_oneclass: mask = cv2.threshold(pred, threshold, 1, cv2.THRESH_BINARY)[1] # 将背景标记为 0,其他的块从 1 开始的正整数标记 num_component, component = cv2.connectedComponents(mask.astype(np.uint8)) predictions =
np.zeros((256, 1600), np.float32)
numpy.zeros
from typing import Dict from pathlib import Path import yaml import numpy as np from sklearn.experimental import enable_hist_gradient_boosting # noqa from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier from sklearn.linear_model import LogisticRegression, Ridge from sklearn.metrics import roc_auc_score from sklearn.base import BaseEstimator import pytest from obp.ope import RegressionModel from obp.types import BanditFeedback from conftest import generate_action_dist np.random.seed(1) binary_model_dict = dict( logistic_regression=LogisticRegression, lightgbm=HistGradientBoostingClassifier, random_forest=RandomForestClassifier, ) # hyperparameter settings for the base ML model in regression model cd_path = Path(__file__).parent.resolve() with open(cd_path / "hyperparams.yaml", "rb") as f: hyperparams = yaml.safe_load(f) # action_context, n_actions, len_list, fitting_method, base_model, description n_rounds = 1000 n_actions = 3 len_list = 3 invalid_input_of_initializing_regression_models = [ ( np.random.uniform(size=(n_actions, 8)), "a", # len_list, "normal", Ridge(**hyperparams["ridge"]), "n_actions must be an integer larger than 1", ), ( np.random.uniform(size=(n_actions, 8)), 1, # len_list, "normal", Ridge(**hyperparams["ridge"]), "n_actions must be an integer larger than 1", ), ( np.random.uniform(size=(n_actions, 8)), n_actions, "a", # "normal", Ridge(**hyperparams["ridge"]), "len_list must be a positive integer", ), ( np.random.uniform(size=(n_actions, 8)), n_actions, 0, # "normal", Ridge(**hyperparams["ridge"]), "len_list must be a positive integer", ), ( np.random.uniform(size=(n_actions, 8)), n_actions, len_list, 1, # Ridge(**hyperparams["ridge"]), "fitting_method must be one of", ), ( np.random.uniform(size=(n_actions, 8)), n_actions, len_list, "awesome", # Ridge(**hyperparams["ridge"]), "fitting_method must be one of", ), ( np.random.uniform(size=(n_actions, 8)), n_actions, len_list, "normal", "RandomForest", # "base_model must be BaseEstimator or a child class of BaseEstimator", ), ] # context, action, reward, pscore, position, action_context, n_actions, len_list, fitting_method, base_model, action_dist, description invalid_input_of_fitting_regression_models = [ ( None, # np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "context must be ndarray", ), ( np.random.uniform(size=(n_rounds, 7)), None, # np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "action must be ndarray", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), None, # np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "reward must be ndarray", ), ( np.random.uniform(size=(n_rounds, 7, 3)), # np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "context must be 2-dimensional", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=(n_rounds, 3)), # np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "action must be 1-dimensional", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=(n_rounds, 3)), # np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "reward must be 1-dimensional", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(["1", "a"], size=n_rounds), # np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "action elements must be non-negative integers", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice([-1, -3], size=n_rounds), # np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "action elements must be non-negative integers", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), "3", # np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "iw", Ridge(**hyperparams["ridge"]), generate_action_dist(n_rounds, n_actions, len_list), 3, 1, "pscore must be ndarray", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.ones((n_rounds, 2)) * 2, # np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "iw", Ridge(**hyperparams["ridge"]), generate_action_dist(n_rounds, n_actions, len_list), 3, 1, "pscore must be 1-dimensional", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.ones(n_rounds - 1) * 2, # np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "iw", Ridge(**hyperparams["ridge"]), generate_action_dist(n_rounds, n_actions, len_list), 3, 1, "context, action, reward, and pscore must be the same size.", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.arange(n_rounds), # np.random.choice(len_list, size=n_rounds), None, n_actions, len_list, "iw", Ridge(**hyperparams["ridge"]), generate_action_dist(n_rounds, n_actions, len_list), 3, 1, "pscore must be positive", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, "3", # None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "position must be ndarray", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=(n_rounds, 3)), # None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "position must be 1-dimensional", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds - 1), # None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "context, action, reward, and position must be the same size.", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(["a", "1"], size=n_rounds), # None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "position elements must be non-negative integers", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds), np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice([-1, -3], size=n_rounds), # None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "position elements must be non-negative integers", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds - 1), # np.random.uniform(size=n_rounds), None, None, None, n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "context, action, and reward must be the same size", ), ( np.random.uniform(size=(n_rounds, 7)), np.random.choice(n_actions, size=n_rounds - 1), # np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, None, None, n_actions, len_list, "iw", Ridge(**hyperparams["ridge"]), generate_action_dist(n_rounds, n_actions, len_list), 3, 1, "context, action, reward, and pscore must be the same size", ), ( np.random.uniform(size=(n_rounds, 7)), np.arange(n_rounds) % n_actions, np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), "3", # n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "action_context must be ndarray", ), ( np.random.uniform(size=(n_rounds, 7)), np.arange(n_rounds) % n_actions, np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), np.random.uniform(size=(n_actions, 8, 3)), # n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "action_context must be 2-dimensional", ), ( np.random.uniform(size=(n_rounds, 7)), (np.arange(n_rounds) % n_actions) + 1, # np.random.uniform(size=n_rounds), np.ones(n_rounds) * 2, np.random.choice(len_list, size=n_rounds), np.random.uniform(size=(n_actions, 8)), n_actions, len_list, "normal", Ridge(**hyperparams["ridge"]), None, 3, 1, "action elements must be smaller than the size of the first dimension of action_context", ), ( np.random.uniform(size=(n_rounds, 7)), np.arange(n_rounds) % n_actions,
np.random.uniform(size=n_rounds)
numpy.random.uniform
import torch import torch.nn as nn from torch.multiprocessing import Pool from torch.optim.optimizer import required from torch.optim import Optimizer as Optimizer import higher from higher.optim import _add from higher.optim import DifferentiableOptimizer from higher.optim import _GroupedGradsType import uutils from uutils.torch_uu import functional_diff_norm, ned_torch, r2_score_from_torch, calc_accuracy_from_logits, \ normalize_matrix_for_similarity from uutils.torch_uu import tensorify import numpy as np Spt_x, Spt_y, Qry_x, Qry_y = torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor Task = tuple[Spt_x, Spt_y, Qry_x, Qry_y] Batch = list ## class EmptyOpt(Optimizer): # This is just an example def __init__(self, params, *args, **kwargs): defaults = {'args': args, 'kwargs': kwargs} super().__init__(params, defaults) class NonDiffMAML(Optimizer): # copy pasted from torch.optim.SGD def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False): if lr is not required and lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov) if nesterov and (momentum <= 0 or dampening != 0): raise ValueError("Nesterov momentum requires a momentum and zero dampening") super().__init__(params, defaults) class MAML(DifferentiableOptimizer): # copy pasted from DifferentiableSGD but with the g.detach() line of code def _update(self, grouped_grads: _GroupedGradsType, **kwargs) -> None: zipped = zip(self.param_groups, grouped_grads) for group_idx, (group, grads) in enumerate(zipped): weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = group['nesterov'] for p_idx, (p, g) in enumerate(zip(group['params'], grads)): if g is None: continue if weight_decay != 0: g = _add(g, weight_decay, p) if momentum != 0: param_state = self.state[group_idx][p_idx] if 'momentum_buffer' not in param_state: buf = param_state['momentum_buffer'] = g else: buf = param_state['momentum_buffer'] buf = _add(buf.mul(momentum), 1 - dampening, g) param_state['momentum_buffer'] = buf if nesterov: g = _add(g, momentum, buf) else: g = buf if self.fo: # first-order g = g.detach() # dissallows flow of higher order grad while still letting params track gradients. group['params'][p_idx] = _add(p, -group['lr'], g) higher.register_optim(NonDiffMAML, MAML) class MAMLMetaLearner(nn.Module): def __init__( self, args, base_model, lr_inner=1e-1, # careful with setting this to small or doing to few inner adaptation steps fo=False, inner_debug=False, target_type='classification' ): super().__init__() self.args = args # args for experiment self.base_model = base_model self.lr_inner = lr_inner self.fo = fo self.inner_debug = inner_debug self.target_type = target_type def forward(self, spt_x, spt_y, qry_x, qry_y, training: bool = True, debug: bool = False): """Does L(A(theta,S), Q) = sum^N_{t=1} L(A(theta,S_t),Q_t) where A(theta,S) is the inner-adaptation loop. It also accumulates the gradient (for memory efficiency) for the outer-optimizer to later use Decision for BN/eval: - during training always use .train(). During eval use the meta-train stats so do .eval() (and using .train() is always wrong since it cheats). Having track_running_stats=False seems overly complicated and nobody seems to use it...so why use it? ref for BN/eval: - https://stats.stackexchange.com/questions/544048/what-does-the-batch-norm-layer-for-maml-model-agnostic-meta-learning-do-for-du - https://github.com/tristandeleu/pytorch-maml/issues/19 Args: spt_x ([type]): x's for support set. Example shape [N,k_shot,D] D=1 or D=[C,H,W] spt_y ([type]): y's/target value for support set. Example shape [N,k_eval] or [N,k_eval,D] qry_x ([type]): x's for query set. Example shape [N,C,D] D=1 or D=[C,H,W] qry_y ([type]): y's/target value for query set. Example shape [N,k_eval] or [N,k_eval,D] Returns: [type]: [description] """ print('USING NEW!') if debug else None # inner_opt = torch_uu.optim.SGD(self.base_model.parameters(), lr=self.lr_inner) inner_opt = NonDiffMAML(self.base_model.parameters(), lr=self.lr_inner) # print(f'{inner_opt=}') # inner_opt = torch_uu.optim.Adam(self.base_model.parameters(), lr=self.lr_inner) self.args.inner_opt_name = str(inner_opt) # self.base_model.train() if self.args.split == 'train' else self.base_model.eval() # - todo: warning, make sure this works if using in the future self.base_model.train() if training else self.base_model.eval() meta_batch_size = spt_x.size(0) meta_losses, meta_accs = [], [] for t in range(meta_batch_size): spt_x_t, spt_y_t, qry_x_t, qry_y_t = spt_x[t], spt_y[t], qry_x[t], qry_y[t] # - Inner Loop Adaptation with higher.innerloop_ctx(self.base_model, inner_opt, copy_initial_weights=self.args.copy_initial_weights, track_higher_grads=self.args.track_higher_grads) as (fmodel, diffopt): diffopt.fo = self.fo # print(f'>maml_old (before inner adapt): {fmodel.model.features.conv1.weight.norm(2)=}') for i_inner in range(self.args.nb_inner_train_steps): # fmodel.train() # omniglot doesn't have this here, it has a single one at the top https://github.com/facebookresearch/higher/blob/main/examples/maml-omniglot.py#L116 # base/child model forward pass spt_logits_t = fmodel(spt_x_t) inner_loss = self.args.criterion(spt_logits_t, spt_y_t) # inner_train_err = calc_error(mdl=fmodel, X=S_x, Y=S_y) # for more advanced learners like meta-lstm # inner-opt update diffopt.step(inner_loss) # print(f'>>maml_old (after inner adapt): {fmodel.model.features.conv1.weight.norm(2)=}') # Evaluate on query set for current task qry_logits_t = fmodel(qry_x_t) qry_loss_t = self.args.criterion(qry_logits_t, qry_y_t) # Accumulate gradients wrt meta-params for each task: https://github.com/facebookresearch/higher/issues/104 (qry_loss_t / meta_batch_size).backward() # note this is more memory efficient (as it removes intermediate data that used to be needed since backward has already been called) # get accuracy if self.target_type == 'classification': qry_acc_t = calc_accuracy_from_logits(y_logits=qry_logits_t, y=qry_y_t) else: qry_acc_t = r2_score_from_torch(qry_y_t, qry_logits_t) # qry_acc_t = compressed_r2_score(y_true=qry_y_t.detach().numpy(), y_pred=qry_logits_t.detach().numpy()) # collect losses & accs for logging/debugging meta_losses.append(qry_loss_t.item()) meta_accs.append(qry_acc_t) assert len(meta_losses) == meta_batch_size meta_loss = np.mean(meta_losses) meta_acc = np.mean(meta_accs) meta_loss_std = np.std(meta_losses) meta_acc_std =
np.std(meta_accs)
numpy.std
# -*- coding: utf-8 -* """ pyHRV - Frequency Domain Module -------------------------------- This module provides function to compute frequency domain HRV parameters using R-peak locations or NN intervals extracted from an ECG lead I-like signal. The implemented Power Spectral Estimation (PSD) estimation methods are: * Welch's Method * Lomb-Scargle * Autoregressive Notes ----- .. Up to v.0.3 this work has been developed within the master thesis "Development of an Open-Source Python Toolbox for Heart Rate Variability (HRV)". .. You find the API reference for this module here: https://pyhrv.readthedocs.io/en/latest/_pages/api/frequency.html .. See 'references.txt' for a full detailed list of references Author ------ .. <NAME>, <EMAIL> Contributors (and former Thesis Supervisors) -------------------------------------------- .. <NAME>, PhD, Instituto de Telecomunicacoes & PLUX wireless biosignals S.A. .. Prof. Dr. <NAME>, University of Applied Sciences Hamburg Last Update ----------- 12-11-2019 :copyright: (c) 2019 by <NAME> :license: BSD 3-clause, see LICENSE for more details. """ # Compatibility from __future__ import absolute_import, division, print_function # Imports import time import warnings import spectrum import numpy as np import scipy as sp import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D from matplotlib.collections import LineCollection from scipy.signal import welch, lombscargle from matplotlib import pyplot as plt # biosppy imports import biosppy # Local imports/HRV toolbox imports import pyhrv # Suppress Lapack bug 0038 warning from scipy (may occur with older versions of the packages above) warnings.filterwarnings(action="ignore", module="scipy") def welch_psd(nni=None, rpeaks=None, fbands=None, nfft=2**12, detrend=True, window='hamming', show=True, show_param=True, legend=True, figsize=None, mode='normal'): """Computes a Power Spectral Density (PSD) estimation from the NNI series using the Welch’s method and computes all frequency domain parameters from this PSD according to the specified frequency bands. References: [Electrophysiology1996], [Umberto2017], [Welch2017] Docs: https://pyhrv.readthedocs.io/en/latest kwa/_pages/api/frequency.html#welch-s-method-welch-psd Parameters ---------- nni : array NN-Intervals in [ms] or [s] rpeaks : array R-peak locations in [ms] or [s] fbands : dict, optional Dictionary with frequency bands (2-element tuples or list) Value format: (lower_freq_band_boundary, upper_freq_band_boundary) Keys: 'ulf' Ultra low frequency (default: none) optional 'vlf' Very low frequency (default: (0.000Hz, 0.04Hz)) 'lf' Low frequency (default: (0.04Hz - 0.15Hz)) 'hf' High frequency (default: (0.15Hz - 0.4Hz)) nfft : int, optional Number of points computed for the FFT result (default: 2**12) detrend : bool optional If True, detrend NNI series by subtracting the mean NNI (default: True) window : scipy window function, optional Window function used for PSD estimation (default: 'hamming') show : bool, optional If true, show PSD plot (default: True) show_param : bool, optional If true, list all computed PSD parameters next to the plot (default: True) legend : bool, optional If true, add a legend with frequency bands to the plot (default: True) figsize : tuple, optional Matplotlib figure size (width, height) (default: None: (12, 4)) mode : string, optional Return mode of the function; available modes: 'normal' Returns frequency domain parameters and PSD plot figure in a ReturnTuple object 'dev' Returns frequency domain parameters, frequency and power arrays, no plot figure 'devplot' Returns frequency domain parameters, frequency array, power array, and the plot figure Returns (biosppy.utils.ReturnTuple Object) ------------------------------------------ results : biosppy.utils.ReturnTuple object All results of the Welch's method's PSD estimation (see list and keys below) Returned Parameters & Keys -------------------------- .. Peak frequencies of all frequency bands in [Hz] (key: 'fft_peak') .. Absolute powers of all frequency bands in [ms^2][(key: 'fft_abs') .. Relative powers of all frequency bands [%] (key: 'fft_rel') .. Logarithmic powers of all frequency bands [-] (key: 'fft_log') .. Normalized powers of all frequency bands [-] (key: 'fft_norms') .. LF/HF ratio [-] (key: 'fft_ratio') .. Total power over all frequency bands in [ms^2] (key: 'fft_total') .. Interpolation method used for NNI interpolation (key: 'fft_interpolation') .. Resampling frequency used for NNI interpolation (key: 'fft_resampling_frequency') .. Spectral window used for PSD estimation of the Welch's method (key: 'fft_spectral_window)' Notes ----- .. The returned BioSPPy ReturnTuple object contains all frequency band parameters in parameter specific tuples of length 4 when using the ULF frequency band or of length 3 when NOT using the ULF frequency band. The structures of those tuples are shown in this example below (fft_results = ReturnTuple object returned by this function): Using ULF, VLF, LF and HF frequency bands: fft_results['fft_peak'] = (ulf_peak, vlf_peak, lf_peak, hf_peak) Using VLF, LF and HF frequency bands: fft_results['fft_peak'] = (vlf_peak, lf_peak, hf_peak) .. If 'show_param' is true, the parameters (incl. frequency band limits) will be listed next to the graph and no legend with frequency band limits will be added to the plot graph itself, i.e. the effect of 'show_param' will be used over the 'legend' effect. .. Only one type of input data is required. .. If both 'nni' and 'rpeaks' are provided, 'rpeaks' will be chosen over the 'nni' and the 'nni' data will be computed from the 'rpeaks'. .. NN and R-peak series provided in [s] format will be converted to [ms] format. """ # Check input values nn = pyhrv.utils.check_input(nni, rpeaks) # Verify or set default frequency bands fbands = _check_freq_bands(fbands) # Resampling (with 4Hz) and interpolate # Because RRi are unevenly spaced we must interpolate it for accurate PSD estimation. fs = 4 t = np.cumsum(nn) t -= t[0] f_interpol = sp.interpolate.interp1d(t, nn, 'cubic') t_interpol = np.arange(t[0], t[-1], 1000./fs) nn_interpol = f_interpol(t_interpol) # Subtract mean value from each sample for suppression of DC-offsets if detrend: nn_interpol = nn_interpol - np.mean(nn_interpol) # Adapt 'nperseg' according to the total duration of the NNI series (5min threshold = 300000ms) if t.max() < 300000: nperseg = nfft else: nperseg = 300 # Compute power spectral density estimation (where the magic happens) frequencies, powers = welch( x=nn_interpol, fs=fs, window=window, nperseg=nperseg, nfft=nfft, scaling='density' ) # Metadata args = (nfft, window, fs, 'cubic') names = ('fft_nfft', 'fft_window', 'fft_resampling_frequency', 'fft_interpolation',) meta = biosppy.utils.ReturnTuple(args, names) if mode not in ['normal', 'dev', 'devplot']: warnings.warn("Unknown mode '%s'. Will proceed with 'normal' mode." % mode, stacklevel=2) mode = 'normal' # Normal Mode: # Returns frequency parameters, PSD plot figure and no frequency & power series/arrays if mode == 'normal': # Compute frequency parameters params, freq_i = _compute_parameters('fft', frequencies, powers, fbands) # Plot PSD figure = _plot_psd('fft', frequencies, powers, freq_i, params, show, show_param, legend, figsize) figure = biosppy.utils.ReturnTuple((figure, ), ('fft_plot', )) # Output return pyhrv.utils.join_tuples(params, figure, meta) # Dev Mode: # Returns frequency parameters and frequency & power series/array; does not create a plot figure nor plot the data elif mode == 'dev': # Compute frequency parameters params, _ = _compute_parameters('fft', frequencies, powers, fbands) # Output return pyhrv.utils.join_tuples(params, meta), frequencies, np.asarray((powers / 10 ** 6)) # Devplot Mode: # Returns frequency parameters, PSD plot figure, and frequency & power series/arrays elif mode == 'devplot': # Compute frequency parameters params, freq_i = _compute_parameters('fft', frequencies, powers, fbands) # Plot PSD figure = _plot_psd('fft', frequencies, powers, freq_i, params, show, show_param, legend, figsize) figure = biosppy.utils.ReturnTuple((figure, ), ('fft_plot', )) # Output return pyhrv.utils.join_tuples(params, figure, meta), frequencies, np.asarray((powers / 10 ** 6)) def lomb_psd( nni=None, rpeaks=None, fbands=None, nfft=2**8, ma_size=None, show=True, show_param=True, legend=True, figsize=None, mode='normal' ): """Computes a Power Spectral Density (PSD) estimation from the NNI series using the Lomb-Scargle Periodogram and computes all frequency domain parameters from this PSD according to the specified frequency bands. References: [Lomb1976], [Scargle1982], [Kuusela2014], [Laguna1995] Docs: https://pyhrv.readthedocs.io/en/latest/_pages/api/frequency.html#lomb-scargle-periodogram-lomb-psd Parameters ---------- rpeaks : array R-peak locations in [ms] or [s] nni : array NN-Intervals in [ms] or [s] fbands : dict, optional Dictionary with frequency bands (2-element tuples or list) Value format: (lower_freq_band_boundary, upper_freq_band_boundary) Keys: 'ulf' Ultra low frequency (default: none) optional 'vlf' Very low frequency (default: (0.003Hz, 0.04Hz)) 'lf' Low frequency (default: (0.04Hz - 0.15Hz)) 'hf' High frequency (default: (0.15Hz - 0.4Hz))´ nfft : int, optional Number of points computed for the FFT result (default: 2**8) ma_size : int, optional Window size of the optional moving average filter (default: None) show : bool, optional If true, show PSD plot (default: True) show_param : bool, optional If true, list all computed PSD parameters next to the plot (default: True) legend : bool, optional If true, add a legend with frequency bands to the plot (default: True) figsize : tuple, optional Matplotlib figure size (width, height) (default: None: (12, 4)) mode : string, optional Return mode of the function; available modes: 'normal' Returns frequency domain parameters and PSD plot figure in a ReturnTuple object 'dev' Returns frequency domain parameters, frequency and power arrays, no plot figure 'devplot' Returns frequency domain parameters, frequency array, power array, and the plot figure Returns (biosppy.utils.ReturnTuple Object) ------------------------------------------ results : biosppy.utils.ReturnTuple object All results of the Lomb-Scargle PSD estimation (see list and keys below) Returned Parameters & Keys -------------------------- .. Peak frequencies of all frequency bands in [Hz] (key: 'lomb_peak') .. Absolute powers of all frequency bands in [ms^2][(key: 'lomb_abs') .. Relative powers of all frequency bands [%] (key: 'lomb_rel') .. Logarithmic powers of all frequency bands [-] (key: 'lomb_log') .. Normalized powers of all frequency bands [-] (key: 'lomb_norms') .. LF/HF ratio [-] (key: 'lomb_ratio') .. Total power over all frequency bands in [ms^2] (key: 'lomb_total') .. Number of PSD samples (key: 'lomb_nfft') .. Moving average filter order (key: 'lomb_ma') Notes ----- .. The returned BioSPPy ReturnTuple object contains all frequency band parameters in parameter specific tuples of length 4 when using the ULF frequency band or of length 3 when NOT using the ULF frequency band. The structures of those tuples are shown in this example below (lomb_results = ReturnTuple object returned by this function): Using ULF, VLF, LF and HF frequency bands: lomb['fft_peak'] = (ulf_peak, vlf_peak, lf_peak, hf_peak) Using VLF, LF and HF frequency bands: lomb['fft_peak'] = (vlf_peak, lf_peak, hf_peak) .. If 'show_param' is true, the parameters (incl. frequency band limits) will be listed next to the graph and no legend with frequency band limits will be added to the plot graph itself, i.e. the effect of 'show_param' will be used over the 'legend' effect. .. Only one type of input data is required. .. If both 'nni' and 'rpeaks' are provided, 'rpeaks' will be chosen over the 'nni' and the 'nni' data will be computed from the 'rpeaks'. .. NN and R-peak series provided in [s] format will be converted to [ms] format. """ # Check input nn = pyhrv.utils.check_input(nni, rpeaks) # Verify or set default frequency bands fbands = _check_freq_bands(fbands) t = np.cumsum(nn) t -= t[0] # Compute PSD according to the Lomb-Scargle method # Specify frequency grid frequencies = np.linspace(0, 0.41, nfft) # Compute angular frequencies a_frequencies = np.asarray(2 * np.pi / frequencies) powers = np.asarray(lombscargle(t, nn, a_frequencies, normalize=True)) # Fix power = inf at f=0 powers[0] = 0 # Apply moving average filter if ma_size is not None: powers = biosppy.signals.tools.smoother(powers, size=ma_size)['signal'] # Define metadata meta = biosppy.utils.ReturnTuple((nfft, ma_size, ), ('lomb_nfft', 'lomb_ma')) if mode not in ['normal', 'dev', 'devplot']: warnings.warn("Unknown mode '%s'. Will proceed with 'normal' mode." % mode, stacklevel=2) mode = 'normal' # Normal Mode: # Returns frequency parameters, PSD plot figure and no frequency & power series/arrays if mode == 'normal': # ms^2 to s^2 powers = powers * 10 ** 6 # Compute frequency parameters params, freq_i = _compute_parameters('lomb', frequencies, powers, fbands) # Plot parameters figure = _plot_psd('lomb', frequencies, powers, freq_i, params, show, show_param, legend, figsize) figure = biosppy.utils.ReturnTuple((figure, ), ('lomb_plot', )) # Complete output return pyhrv.utils.join_tuples(params, figure, meta) # Dev Mode: # Returns frequency parameters and frequency & power series/array; does not create a plot figure nor plot the data elif mode == 'dev': # Compute frequency parameters params, _ = _compute_parameters('lomb', frequencies, powers, fbands) # Complete output return pyhrv.utils.join_tuples(params, meta), frequencies, powers # Devplot Mode: # Returns frequency parameters, PSD plot figure, and frequency & power series/arrays elif mode == 'devplot': # ms^2 to s^2 powers = powers * 10**6 # Compute frequency parameters params, freq_i = _compute_parameters('lomb', frequencies, powers, fbands) # Plot parameters figure = _plot_psd('lomb', frequencies, powers, freq_i, params, show, show_param, legend, figsize) figure = biosppy.utils.ReturnTuple((figure, ), ('lomb_plot', )) # Complete output return pyhrv.utils.join_tuples(params, figure, meta), frequencies, powers def ar_psd(nni=None, rpeaks=None, fbands=None, nfft=2**12, order=16, show=True, show_param=True, legend=True, figsize=None, mode='normal'): """Computes a Power Spectral Density (PSD) estimation from the NNI series using the Autoregressive method and computes all frequency domain parameters from this PSD according to the specified frequency bands. References: [Electrophysiology1996], [Kuusela2014], [Kallas2012], [Boardman2002] (additionally recommended: [Miranda2012]) Docs: https://pyhrv.readthedocs.io/en/latest/_pages/api/frequency.html#autoregressive-method-ar-psd Parameters ---------- rpeaks : array R-peak locations in [ms] or [s] nni : array NN-Intervals in [ms] or [s] fbands : dict, optional Dictionary with frequency bands (2-element tuples or list) Value format: (lower_freq_band_boundary, upper_freq_band_boundary) Keys: 'ulf' Ultra low frequency (default: none) optional 'vlf' Very low frequency (default: (0.003Hz, 0.04Hz)) 'lf' Low frequency (default: (0.04Hz - 0.15Hz)) 'hf' High frequency (default: (0.15Hz - 0.4Hz))´ nfft : int, optional Number of points computed for the entire AR result (default: 2**12) order : int, optional Autoregressive model order (default: 16) show : bool, optional If true, show PSD plot (default: True) show_param : bool, optional If true, list all computed PSD parameters next to the plot (default: True) legend : bool, optional If true, add a legend with frequency bands to the plot (default: True) figsize : tuple, optional Matplotlib figure size (width, height) (default: None: (12, 4)) mode : string, optional Return mode of the function; available modes: 'normal' Returns frequency domain parameters and PSD plot figure in a ReturnTuple object 'dev' Returns frequency domain parameters, frequency and power arrays, no plot figure 'devplot' Returns frequency domain parameters, frequency array, power array, and the plot figure Returns (biosppy.utils.ReturnTuple Object) ------------------------------------------ results : biosppy.utils.ReturnTuple object All results of the Autoregressive PSD estimation (see list and keys below) Returned Parameters & Keys -------------------------- .. Peak frequencies of all frequency bands in [Hz] (key: 'ar_peak') .. Absolute powers of all frequency bands in [ms^2][(key: 'ar_abs') .. Relative powers of all frequency bands [%] (key: 'ar_rel') .. Logarithmic powers of all frequency bands [-] (key: 'ar_log') .. Normalized powers of all frequency bands [-] (key: 'ar_norms') .. LF/HF ratio [-] (key: 'ar_ratio') .. Total power over all frequency bands in [ms^2] (key: 'ar_total') .. Interpolation method (key: 'ar_interpolation') .. Resampling frequency (key: 'ar_resampling_frequency') .. AR model order (key: 'ar_order') .. Number of PSD samples (key: 'ar_nfft') Notes ----- .. The returned BioSPPy ReturnTuple object contains all frequency band parameters in parameter specific tuples of length 4 when using the ULF frequency band or of length 3 when NOT using the ULF frequency band. The structures of those tuples are shown in this example below (lomb_results = ReturnTuple object returned by this function): Using ULF, VLF, LF and HF frequency bands: lomb['ar_peak'] = (ulf_peak, vlf_peak, lf_peak, hf_peak) Using VLF, LF and HF frequency bands: lomb['ar_peak'] = (vlf_peak, lf_peak, hf_peak) .. If 'show_param' is true, the parameters (incl. frequency band limits) will be listed next to the graph and no legend with frequency band limits will be added to the plot graph itself, i.e. the effect of 'show_param' will be used over the 'legend' effect. .. Only one type of input data is required. .. If both 'nni' and 'rpeaks' are provided, 'rpeaks' will be chosen over the 'nni' and the 'nni' data will be computed from the 'rpeaks'. .. NN and R-peak series provided in [s] format will be converted to [ms] format. """ # Check input nn = pyhrv.utils.check_input(nni, rpeaks) # Verify or set default frequency bands fbands = _check_freq_bands(fbands) # Resampling (with 4Hz) and interpolate # Because RRi are unevenly spaced we must interpolate it for accurate PSD estimation. fs = 4 t = np.cumsum(nn) t -= t[0] f_interpol = sp.interpolate.interp1d(t, nn, 'cubic') t_interpol = np.arange(t[0], t[-1], 1000./fs) nn_interpol = f_interpol(t_interpol) # Compute autoregressive PSD ar = spectrum.pyule(data=nn_interpol, order=order, NFFT=nfft, sampling=fs, scale_by_freq=False) ar() # Get frequencies and powers frequencies = np.asarray(ar.frequencies()) psd = np.asarray(ar.psd) powers = np.asarray(10 * np.log10(psd) * 10**3) # * 10**3 to compensate with ms^2 to s^2 conversion # in the upcoming steps # Define metadata meta = biosppy.utils.ReturnTuple((nfft, order, fs, 'cubic'), ('ar_nfft', 'ar_order', 'ar_resampling_frequency', 'ar_interpolation')) if mode not in ['normal', 'dev', 'devplot']: warnings.warn("Unknown mode '%s'. Will proceed with 'normal' mode." % mode, stacklevel=2) mode = 'normal' # Normal Mode: # Returns frequency parameters, PSD plot figure and no frequency & power series/arrays if mode == 'normal': # Compute frequency parameters params, freq_i = _compute_parameters('ar', frequencies, powers, fbands) params = pyhrv.utils.join_tuples(params, meta) # Plot PSD figure = _plot_psd('ar', frequencies, powers, freq_i, params, show, show_param, legend, figsize) figure = biosppy.utils.ReturnTuple((figure, ), ('ar_plot', )) # Complete output return pyhrv.utils.join_tuples(params, figure) # Dev Mode: # Returns frequency parameters and frequency & power series/array; does not create a plot figure nor plot the data elif mode == 'dev': # Compute frequency parameters params, _ = _compute_parameters('ar', frequencies, powers, fbands) # Output return pyhrv.utils.join_tuples(params, meta), frequencies, (powers / 10 ** 6) # Devplot Mode: # Returns frequency parameters, PSD plot figure, and frequency & power series/arrays elif mode == 'devplot': # Compute frequency parameters params, freq_i = _compute_parameters('ar', frequencies, powers, fbands) # Plot PSD figure = _plot_psd('ar', frequencies, powers, freq_i, params, show, show_param, legend, figsize) figure = biosppy.utils.ReturnTuple((figure, ), ('ar_plot', )) # Complete output return pyhrv.utils.join_tuples(params, figure, meta), frequencies, (powers / 10 ** 6) def _compute_parameters(method, frequencies, power, freq_bands): """Computes PSD HRV parameters from the PSD frequencies and powers. References: [Electrophysiology1996], [Basak2014] Docs: https://pyhrv.readthedocs.io/en/latest/_pages/api/frequency.html#frequency-parameters Parameters ---------- method : str Method identifier ('fft', 'ar', 'lomb') frequencies Series of frequencies of the power spectral density computation. power : array Series of power-values of the power spectral density computation. freq_indices : array Indices of the frequency samples within each frequency band. freq_bands : dict, optional Dictionary with frequency bands (tuples or list). Value format: (lower_freq_band_boundary, upper_freq_band_boundary) Keys: 'ulf' Ultra low frequency (default: none) optional 'vlf' Very low frequency (default: (0.003Hz, 0.04Hz)) 'lf' Low frequency (default: (0.04Hz - 0.15Hz)) 'hf' High frequency (default: (0.15Hz - 0.4Hz)) Returns ------- results : biosppy.utils.ReturnTuple object All results of the Lomb-Scargle PSD estimation (see list and keys below) Returned Parameters & Keys -------------------------- (below, X = method identifier 'fft', 'ar' or 'lomb' .. Peak frequencies of all frequency bands in [Hz] (key: 'X_peak') .. Absolute powers of all frequency bands in [ms^2] (key: 'X_abs') .. Relative powers of all frequency bands in [%] (key: 'X_rel') .. Logarithmic powers of all frequency bands [-] (key: 'X_log') .. Normalized powers of all frequency bands [-](key: 'X_norms') .. LF/HF ratio [–] (key: 'X_ratio') .. Total power over all frequency bands in [ms^] (key: 'X_total') Raises ------ ValueError If parameter computation could not be made due to the lack of PSD samples ('nfft' too low) """ # Compute frequency resolution df = (frequencies[1] - frequencies[0]) # Get indices of freq values within the specified freq bands ulf_i, vlf_i, lf_i, hf_i = _get_frequency_indices(frequencies, freq_bands) ulf_f, vlf_f, lf_f, hf_f = _get_frequency_arrays(frequencies, ulf_i, vlf_i, lf_i, hf_i) # Absolute powers if freq_bands['ulf'] is not None: ulf_power = np.sum(power[ulf_i]) * df vlf_power = np.sum(power[vlf_i]) * df lf_power = np.sum(power[lf_i]) * df hf_power = np.sum(power[hf_i]) * df abs_powers = (vlf_power, lf_power, hf_power, ) if freq_bands['ulf'] is None else (ulf_power, vlf_power, lf_power, hf_power,) total_power = np.sum(abs_powers) # Peak frequencies if freq_bands['ulf'] is not None: ulf_peak = ulf_f[np.argmax(power[ulf_i])] # Compute Peak values and catch exception caused if the number of PSD samples is too low try: vlf_peak = vlf_f[np.argmax(power[vlf_i])] lf_peak = lf_f[np.argmax(power[lf_i])] hf_peak = hf_f[
np.argmax(power[hf_i])
numpy.argmax
import numpy as np import cv2 import math import copy from opensfm import context from opensfm import pygeometry from opensfm import pymap from opensfm import types from scipy.stats import special_ortho_group from scipy.spatial.transform import Rotation """ Trying to imitate the following structure reconstruction = { "cameras": { "theta": { "projection_type": "equirectangular" } }, "shots" : { 'im1': { "camera": "theta", "rotation": [0.0, 0.0, 0.0], "translation": [0.0, 0.0, 0.0], }, 'im2': { "camera": "theta", "rotation": [0, 0, 0.0], "translation": [-1, 0, 0.0], }, }, "points" : { }, } """ # Define original Pose class Pose(object): """Defines the pose parameters of a camera. The extrinsic parameters are defined by a 3x1 rotation vector which maps the camera rotation respect to the origin frame (rotation) and a 3x1 translation vector which maps the camera translation respect to the origin frame (translation). Attributes: rotation (vector): the rotation vector. translation (vector): the rotation vector. """ def __init__(self, rotation=(0, 0, 0), translation=(0, 0, 0)): self.rotation = rotation self.translation = translation @property def rotation(self): """Rotation in angle-axis format.""" return self._rotation @rotation.setter def rotation(self, value): self._rotation = np.asarray(value, dtype=float) @property def translation(self): """Translation vector.""" return self._translation @translation.setter def translation(self, value): self._translation = np.asarray(value, dtype=float) def transform(self, point): """Transform a point from world to this pose coordinates.""" return self.get_rotation_matrix().dot(point) + self.translation def transform_many(self, points): """Transform points from world coordinates to this pose.""" return points.dot(self.get_rotation_matrix().T) + self.translation def transform_inverse(self, point): """Transform a point from this pose to world coordinates.""" return self.get_rotation_matrix().T.dot(point - self.translation) def transform_inverse_many(self, points): """Transform points from this pose to world coordinates.""" return (points - self.translation).dot(self.get_rotation_matrix()) def get_rotation_matrix(self): """Get rotation as a 3x3 matrix.""" return cv2.Rodrigues(self.rotation)[0] def set_rotation_matrix(self, rotation_matrix, permissive=False): """Set rotation as a 3x3 matrix. >>> pose = Pose() >>> pose.rotation = np.array([0., 1., 2.]) >>> R = pose.get_rotation_matrix() >>> pose.set_rotation_matrix(R) >>> np.allclose(pose.rotation, [0., 1., 2.]) True >>> pose.set_rotation_matrix([[3,-4, 1], [ 5, 3,-7], [-9, 2, 6]]) Traceback (most recent call last): ... ValueError: Not orthogonal >>> pose.set_rotation_matrix([[0, 0, 1], [-1, 0, 0], [0, 1, 0]]) Traceback (most recent call last): ... ValueError: Determinant not 1 """ R = np.array(rotation_matrix, dtype=float) if not permissive: if not np.isclose(np.linalg.det(R), 1): raise ValueError("Determinant not 1") if not np.allclose(np.linalg.inv(R), R.T): raise ValueError("Not orthogonal") self.rotation = cv2.Rodrigues(R)[0].ravel() def get_origin(self): """The origin of the pose in world coordinates.""" return -self.get_rotation_matrix().T.dot(self.translation) def set_origin(self, origin): """Set the origin of the pose in world coordinates. >>> pose = Pose() >>> pose.rotation = np.array([0., 1., 2.]) >>> origin = [1., 2., 3.] >>> pose.set_origin(origin) >>> np.allclose(origin, pose.get_origin()) True """ self.translation = -self.get_rotation_matrix().dot(origin) def get_Rt(self): """Get pose as a 3x4 matrix (R|t).""" Rt = np.empty((3, 4)) Rt[:, :3] = self.get_rotation_matrix() Rt[:, 3] = self.translation return Rt def compose(self, other): """Get the composition of this pose with another. composed = self * other """ selfR = self.get_rotation_matrix() otherR = other.get_rotation_matrix() R = np.dot(selfR, otherR) t = selfR.dot(other.translation) + self.translation res = Pose() res.set_rotation_matrix(R) res.translation = t return res def inverse(self): """Get the inverse of this pose.""" inverse = Pose() R = self.get_rotation_matrix() inverse.set_rotation_matrix(R.T) inverse.translation = -R.T.dot(self.translation) return inverse class Camera(object): """Abstract camera class. A camera is unique defined for its identification description (id), the projection type (projection_type) and its internal calibration parameters, which depend on the particular Camera sub-class. Attributes: id (str): camera description. projection_type (str): projection type. """ pass class PerspectiveCamera(Camera): """Define a perspective camera. Attributes: width (int): image width. height (int): image height. focal (real): estimated focal length. k1 (real): estimated first distortion parameter. k2 (real): estimated second distortion parameter. """ def __init__(self): """Defaut constructor.""" self.id = None self.projection_type = 'perspective' self.width = None self.height = None self.focal = None self.k1 = None self.k2 = None def __repr__(self): return '{}({!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r})'.format( self.__class__.__name__, self.id, self.projection_type, self.width, self.height, self.focal, self.k1, self.k2) def project(self, point): """Project a 3D point in camera coordinates to the image plane.""" # Normalized image coordinates xn = point[0] / point[2] yn = point[1] / point[2] # Radial distortion r2 = xn * xn + yn * yn distortion = 1.0 + r2 * (self.k1 + self.k2 * r2) return np.array([self.focal * distortion * xn, self.focal * distortion * yn]) def project_many(self, points): """Project 3D points in camera coordinates to the image plane.""" distortion = np.array([self.k1, self.k2, 0, 0, 0]) K, R, t = self.get_K(), np.zeros(3), np.zeros(3) pixels, _ = cv2.projectPoints(points, R, t, K, distortion) return pixels.reshape((-1, 2)) def pixel_bearing(self, pixel): """Unit vector pointing to the pixel viewing direction.""" point = np.asarray(pixel).reshape((1, 1, 2)) distortion = np.array([self.k1, self.k2, 0., 0.]) x, y = cv2.undistortPoints(point, self.get_K(), distortion).flat l = np.sqrt(x * x + y * y + 1.0) return np.array([x / l, y / l, 1.0 / l]) def pixel_bearing_many(self, pixels): """Unit vectors pointing to the pixel viewing directions.""" points = pixels.reshape((-1, 1, 2)).astype(np.float64) distortion = np.array([self.k1, self.k2, 0., 0.]) up = cv2.undistortPoints(points, self.get_K(), distortion) up = up.reshape((-1, 2)) x = up[:, 0] y = up[:, 1] l = np.sqrt(x * x + y * y + 1.0) return np.column_stack((x / l, y / l, 1.0 / l)) def pixel_bearings(self, pixels): """Deprecated: use pixel_bearing_many.""" return self.pixel_bearing_many(pixels) def back_project(self, pixel, depth): """Project a pixel to a fronto-parallel plane at a given depth.""" bearing = self.pixel_bearing(pixel) scale = depth / bearing[2] return scale * bearing def back_project_many(self, pixels, depths): """Project pixels to fronto-parallel planes at given depths.""" bearings = self.pixel_bearing_many(pixels) scales = depths / bearings[:, 2] return scales[:, np.newaxis] * bearings def get_K(self): """The calibration matrix.""" return np.array([[self.focal, 0., 0.], [0., self.focal, 0.], [0., 0., 1.]]) def get_K_in_pixel_coordinates(self, width=None, height=None): """The calibration matrix that maps to pixel coordinates. Coordinates (0,0) correspond to the center of the top-left pixel, and (width - 1, height - 1) to the center of bottom-right pixel. You can optionally pass the width and height of the image, in case you are using a resized versior of the original image. """ w = width or self.width h = height or self.height f = self.focal * max(w, h) return np.array([[f, 0, 0.5 * (w - 1)], [0, f, 0.5 * (h - 1)], [0, 0, 1.0]]) class BrownPerspectiveCamera(Camera): """Define a perspective camera. Attributes: width (int): image width. height (int): image height. focal_x (real): estimated focal length for the X axis. focal_y (real): estimated focal length for the Y axis. c_x (real): estimated principal point X. c_y (real): estimated principal point Y. k1 (real): estimated first radial distortion parameter. k2 (real): estimated second radial distortion parameter. p1 (real): estimated first tangential distortion parameter. p2 (real): estimated second tangential distortion parameter. k3 (real): estimated third radial distortion parameter. """ def __init__(self): """Defaut constructor.""" self.id = None self.projection_type = 'brown' self.width = None self.height = None self.focal_x = None self.focal_y = None self.c_x = None self.c_y = None self.k1 = None self.k2 = None self.p1 = None self.p2 = None self.k3 = None def __repr__(self): return '{}({})'.format(self.__class__.__name__, self.__dict__) def project(self, point): """Project a 3D point in camera coordinates to the image plane.""" # Normalized image coordinates xn = point[0] / point[2] yn = point[1] / point[2] # Radial and tangential distortion r2 = xn * xn + yn * yn radial_distortion = 1.0 + r2 * (self.k1 + r2 * (self.k2 + r2 * self.k3)) x_tangential_distortion = 2 * self.p1 * xn * yn + self.p2 * (r2 + 2 * xn * xn) x_distorted = xn * radial_distortion + x_tangential_distortion y_tangential_distortion = self.p1 * (r2 + 2 * yn * yn) + 2 * self.p2 * xn * yn y_distorted = yn * radial_distortion + y_tangential_distortion return np.array([self.focal_x * x_distorted + self.c_x, self.focal_y * y_distorted + self.c_y]) def project_many(self, points): """Project 3D points in camera coordinates to the image plane.""" distortion = np.array([self.k1, self.k2, self.p1, self.p2, self.k3]) K, R, t = self.get_K(), np.zeros(3), np.zeros(3) pixels, _ = cv2.projectPoints(points, R, t, K, distortion) return pixels.reshape((-1, 2)) def pixel_bearing(self, pixel): """Unit vector pointing to the pixel viewing direction.""" point = np.asarray(pixel).reshape((1, 1, 2)) distortion = np.array([self.k1, self.k2, self.p1, self.p2, self.k3]) x, y = cv2.undistortPoints(point, self.get_K(), distortion).flat l = np.sqrt(x * x + y * y + 1.0) return np.array([x / l, y / l, 1.0 / l]) def pixel_bearing_many(self, pixels): """Unit vector pointing to the pixel viewing directions.""" points = pixels.reshape((-1, 1, 2)).astype(np.float64) distortion = np.array([self.k1, self.k2, self.p1, self.p2, self.k3]) up = cv2.undistortPoints(points, self.get_K(), distortion) up = up.reshape((-1, 2)) x = up[:, 0] y = up[:, 1] l = np.sqrt(x * x + y * y + 1.0) return np.column_stack((x / l, y / l, 1.0 / l)) def pixel_bearings(self, pixels): """Deprecated: use pixel_bearing_many.""" return self.pixel_bearing_many(pixels) def back_project(self, pixel, depth): """Project a pixel to a fronto-parallel plane at a given depth.""" bearing = self.pixel_bearing(pixel) scale = depth / bearing[2] return scale * bearing def back_project_many(self, pixels, depths): """Project pixels to fronto-parallel planes at given depths.""" bearings = self.pixel_bearing_many(pixels) scales = depths / bearings[:, 2] return scales[:, np.newaxis] * bearings def get_K(self): """The calibration matrix.""" return np.array([[self.focal_x, 0., self.c_x], [0., self.focal_y, self.c_y], [0., 0., 1.]]) def get_K_in_pixel_coordinates(self, width=None, height=None): """The calibration matrix that maps to pixel coordinates. Coordinates (0,0) correspond to the center of the top-left pixel, and (width - 1, height - 1) to the center of bottom-right pixel. You can optionally pass the width and height of the image, in case you are using a resized versior of the original image. """ w = width or self.width h = height or self.height s = max(w, h) normalized_to_pixel = np.array([ [s, 0, (w - 1) / 2.0], [0, s, (h - 1) / 2.0], [0, 0, 1], ]) return np.dot(normalized_to_pixel, self.get_K()) class FisheyeCamera(Camera): """Define a fisheye camera. Attributes: width (int): image width. height (int): image height. focal (real): estimated focal length. k1 (real): estimated first distortion parameter. k2 (real): estimated second distortion parameter. """ def __init__(self): """Defaut constructor.""" self.id = None self.projection_type = 'fisheye' self.width = None self.height = None self.focal = None self.k1 = None self.k2 = None def project(self, point): """Project a 3D point in camera coordinates to the image plane.""" x, y, z = point l = np.sqrt(x**2 + y**2) theta = np.arctan2(l, z) theta_d = theta * (1.0 + theta**2 * (self.k1 + theta**2 * self.k2)) s = self.focal * theta_d / l return np.array([s * x, s * y]) def project_many(self, points): """Project 3D points in camera coordinates to the image plane.""" points = points.reshape((-1, 1, 3)).astype(np.float64) distortion = np.array([self.k1, self.k2, 0., 0.]) K, R, t = self.get_K(), np.zeros(3), np.zeros(3) pixels, _ = cv2.fisheye.projectPoints(points, R, t, K, distortion) return pixels.reshape((-1, 2)) def pixel_bearing(self, pixel): """Unit vector pointing to the pixel viewing direction.""" point = np.asarray(pixel).reshape((1, 1, 2)) distortion = np.array([self.k1, self.k2, 0., 0.]) x, y = cv2.fisheye.undistortPoints(point, self.get_K(), distortion).flat l = np.sqrt(x * x + y * y + 1.0) return np.array([x / l, y / l, 1.0 / l]) def pixel_bearing_many(self, pixels): """Unit vector pointing to the pixel viewing directions.""" points = pixels.reshape((-1, 1, 2)).astype(np.float64) distortion = np.array([self.k1, self.k2, 0., 0.]) up = cv2.fisheye.undistortPoints(points, self.get_K(), distortion) up = up.reshape((-1, 2)) x = up[:, 0] y = up[:, 1] l = np.sqrt(x * x + y * y + 1.0) return np.column_stack((x / l, y / l, 1.0 / l)) def pixel_bearings(self, pixels): """Deprecated: use pixel_bearing_many.""" return self.pixel_bearing_many(pixels) def back_project(self, pixel, depth): """Project a pixel to a fronto-parallel plane at a given depth.""" bearing = self.pixel_bearing(pixel) scale = depth / bearing[2] return scale * bearing def back_project_many(self, pixels, depths): """Project pixels to fronto-parallel planes at given depths.""" bearings = self.pixel_bearing_many(pixels) scales = depths / bearings[:, 2] return scales[:, np.newaxis] * bearings def get_K(self): """The calibration matrix.""" return np.array([[self.focal, 0., 0.], [0., self.focal, 0.], [0., 0., 1.]]) def get_K_in_pixel_coordinates(self, width=None, height=None): """The calibration matrix that maps to pixel coordinates. Coordinates (0,0) correspond to the center of the top-left pixel, and (width - 1, height - 1) to the center of bottom-right pixel. You can optionally pass the width and height of the image, in case you are using a resized version of the original image. """ w = width or self.width h = height or self.height f = self.focal * max(w, h) return np.array([[f, 0, 0.5 * (w - 1)], [0, f, 0.5 * (h - 1)], [0, 0, 1.0]]) class FisheyeExtendedCamera(Camera): """Define a fisheye camera using full OpenCV model. Attributes: width (int): image width. height (int): image height. focal_x (real): estimated focal length for the X axis. focal_y (real): estimated focal length for the Y axis. c_x (real): estimated principal point X. c_y (real): estimated principal point Y. k1 (real): estimated first radial distortion parameter. k2 (real): estimated second radial distortion parameter. k3 (real): estimated third radial distortion parameter. k4 (real): estimated fourth radial distortion parameter. """ def __init__(self): """Defaut constructor.""" self.id = None self.projection_type = 'fisheye_opencv' self.width = None self.height = None self.focal_x = None self.focal_y = None self.c_x = None self.c_y = None self.k1 = None self.k2 = None self.k3 = None self.k4 = None def project(self, point): """Project a 3D point in camera coordinates to the image plane.""" x, y, z = point a = x / z b = y / z r = np.sqrt(a**2 + b**2) theta = np.arctan(r) theta2 = theta**2 theta_d = theta * (1.0 + theta2 * (self.k1 + theta2 * (self.k2 + theta2 * (self.k3 + theta2 * self.k4)))) inv_r = 1.0 / r if r > 1e-8 else 1.0 cdist = theta_d * inv_r if r > 1e-8 else 1.0 x_p = cdist * a y_p = cdist * b return np.array([self.focal_x * x_p + self.c_x, self.focal_y * y_p + self.c_y]) def project_many(self, points): """Project 3D points in camera coordinates to the image plane.""" points = points.reshape((-1, 1, 3)).astype(np.float64) distortion = np.array([self.k1, self.k2, self.k3, self.k4]) K, R, t = self.get_K(), np.zeros(3), np.zeros(3) pixels, _ = cv2.fisheye.projectPoints(points, R, t, K, distortion) return pixels.reshape((-1, 2)) def pixel_bearing(self, pixel): """Unit vector pointing to the pixel viewing direction.""" point = np.asarray(pixel).reshape((1, 1, 2)) distortion = np.array([self.k1, self.k2, self.k3, self.k4]) x, y = cv2.fisheye.undistortPoints(point, self.get_K(), distortion).flat l = np.sqrt(x * x + y * y + 1.0) return np.array([x / l, y / l, 1.0 / l]) def pixel_bearing_many(self, pixels): """Unit vector pointing to the pixel viewing directions.""" points = pixels.reshape((-1, 1, 2)).astype(np.float64) distortion = np.array([self.k1, self.k2, self.k3, self.k4]) up = cv2.fisheye.undistortPoints(points, self.get_K(), distortion) up = up.reshape((-1, 2)) x = up[:, 0] y = up[:, 1] l = np.sqrt(x * x + y * y + 1.0) return np.column_stack((x / l, y / l, 1.0 / l)) def pixel_bearings(self, pixels): """Deprecated: use pixel_bearing_many.""" return self.pixel_bearing_many(pixels) def back_project(self, pixel, depth): """Project a pixel to a fronto-parallel plane at a given depth.""" bearing = self.pixel_bearing(pixel) scale = depth / bearing[2] return scale * bearing def back_project_many(self, pixels, depths): """Project pixels to fronto-parallel planes at given depths.""" bearings = self.pixel_bearing_many(pixels) scales = depths / bearings[:, 2] return scales[:, np.newaxis] * bearings def get_K(self): """The calibration matrix.""" return np.array([[self.focal_x, 0., self.c_x], [0., self.focal_y, self.c_y], [0., 0., 1.]]) def get_K_in_pixel_coordinates(self, width=None, height=None): """The calibration matrix that maps to pixel coordinates. Coordinates (0,0) correspond to the center of the top-left pixel, and (width - 1, height - 1) to the center of bottom-right pixel. You can optionally pass the width and height of the image, in case you are using a resized version of the original image. """ w = width or self.width h = height or self.height s = max(w, h) normalized_to_pixel = np.array([ [s, 0, (w - 1) / 2.0], [0, s, (h - 1) / 2.0], [0, 0, 1], ]) return np.dot(normalized_to_pixel, self.get_K()) class DualCamera(Camera): """Define a camera that seamlessly transition between fisheye and perspective camera. Attributes: width (int): image width. height (int): image height. focal (real): estimated focal length. k1 (real): estimated first distortion parameter. k2 (real): estimated second distortion parameter. transition (real): parametrize between perpective (1.0) and fisheye (0.0) """ def __init__(self, projection_type='unknown'): """Defaut constructor.""" self.id = None self.projection_type = 'dual' self.width = None self.height = None self.focal = None self.k1 = None self.k2 = None if projection_type == 'perspective': self.transition = 1.0 elif projection_type == 'fisheye': self.transition = 0.0 else: self.transition = 0.5 def project(self, point): """Project a 3D point in camera coordinates to the image plane.""" x, y, z = point l = np.sqrt(x**2 + y**2) theta = np.arctan2(l, z) x_fish = theta / l * x y_fish = theta / l * y x_persp = point[0] / point[2] y_persp = point[1] / point[2] x_dual = self.transition*x_persp + (1.0 - self.transition)*x_fish y_dual = self.transition*y_persp + (1.0 - self.transition)*y_fish r2 = x_dual * x_dual + y_dual * y_dual distortion = 1.0 + r2 * (self.k1 + self.k2 * r2) return np.array([self.focal * distortion * x_dual, self.focal * distortion * y_dual]) def project_many(self, points): """Project 3D points in camera coordinates to the image plane.""" projected = [] for point in points: projected.append(self.project(point)) return np.array(projected) def pixel_bearing(self, pixel): """Unit vector pointing to the pixel viewing direction.""" point = np.asarray(pixel).reshape((1, 1, 2)) distortion = np.array([self.k1, self.k2, 0., 0.]) no_K = np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) point = point / self.focal x_u, y_u = cv2.undistortPoints(point, no_K, distortion).flat r = np.sqrt(x_u**2 + y_u**2) # inverse iteration for finding theta from r theta = 0 for i in range(5): f = self.transition*math.tan(theta) + (1.0 - self.transition)*theta - r secant = 1.0/math.cos(theta) d = (self.transition*secant**2 - self.transition + 1) if i < 1: theta -= 0.5*f/d else: theta -= f/d s = math.tan(theta)/(self.transition*math.tan(theta) + (1.0 - self.transition)*theta) x_dual = x_u*s y_dual = y_u*s l = math.sqrt(x_dual * x_dual + y_dual * y_dual + 1.0) return np.array([x_dual / l, y_dual / l, 1.0 / l]) def pixel_bearing_many(self, pixels): """Unit vector pointing to the pixel viewing directions.""" points = pixels.reshape((-1, 1, 2)).astype(np.float64) distortion = np.array([self.k1, self.k2, 0., 0.]) no_K = np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) points = points / self.focal undistorted = cv2.undistortPoints(points, no_K, distortion) undistorted = undistorted.reshape((-1, 2)) r = np.sqrt(undistorted[:, 0]**2 + undistorted[:, 1]**2) # inverse iteration for finding theta from r theta = 0 for i in range(5): f = self.transition*np.tan(theta) + (1.0 - self.transition)*theta - r secant = 1.0/np.cos(theta) d = (self.transition*secant**2 - self.transition + 1) if i < 1: theta -= 0.5*f/d else: theta -= f/d s = np.tan(theta)/(self.transition*np.tan(theta) + (1.0 - self.transition)*theta) x_dual = undistorted[:, 0]*s y_dual = undistorted[:, 1]*s l = np.sqrt(x_dual * x_dual + y_dual * y_dual + 1.0) return np.column_stack([x_dual / l, y_dual / l, 1.0 / l]) def pixel_bearings(self, pixels): """Deprecated: use pixel_bearing_many.""" return self.pixel_bearing_many(pixels) def back_project(self, pixel, depth): """Project a pixel to a fronto-parallel plane at a given depth.""" bearing = self.pixel_bearing(pixel) scale = depth / bearing[2] return scale * bearing def back_project_many(self, pixels, depths): """Project pixels to fronto-parallel planes at given depths.""" bearings = self.pixel_bearing_many(pixels) scales = depths / bearings[:, 2] return scales[:, np.newaxis] * bearings def get_K(self): """The calibration matrix.""" return np.array([[self.focal, 0., 0.], [0., self.focal, 0.], [0., 0., 1.]]) def get_K_in_pixel_coordinates(self, width=None, height=None): """The calibration matrix that maps to pixel coordinates. Coordinates (0,0) correspond to the center of the top-left pixel, and (width - 1, height - 1) to the center of bottom-right pixel. You can optionally pass the width and height of the image, in case you are using a resized version of the original image. """ w = width or self.width h = height or self.height f = self.focal * max(w, h) return np.array([[f, 0, 0.5 * (w - 1)], [0, f, 0.5 * (h - 1)], [0, 0, 1.0]]) class SphericalCamera(Camera): """A spherical camera generating equirectangular projections. Attributes: width (int): image width. height (int): image height. """ def __init__(self): """Defaut constructor.""" self.id = None self.projection_type = 'equirectangular' self.width = None self.height = None def project(self, point): """Project a 3D point in camera coordinates to the image plane.""" x, y, z = point lon = np.arctan2(x, z) lat = np.arctan2(-y, np.sqrt(x**2 + z**2)) return np.array([lon / (2 * np.pi), -lat / (2 * np.pi)]) def project_many(self, points): """Project 3D points in camera coordinates to the image plane.""" x, y, z = points.T lon = np.arctan2(x, z) lat = np.arctan2(-y, np.sqrt(x**2 + z**2)) return np.column_stack([lon / (2 * np.pi), -lat / (2 * np.pi)]) def pixel_bearing(self, pixel): """Unit vector pointing to the pixel viewing direction.""" lon = pixel[0] * 2 * np.pi lat = -pixel[1] * 2 * np.pi x = np.cos(lat) * np.sin(lon) y = -np.sin(lat) z = np.cos(lat) *
np.cos(lon)
numpy.cos
''' 3D GRID -> implement cell proliferations (cell cycle), proton transport (irradiation survival probability) @author : singh The entire file is based on Moreau's work (2D version): https://github.com/gregoire-moreau/radio_rl Link to my repo : https://github.com/amanpreetsingh-BE/DeepRL-Protontherapy ''' import numpy as np import random from model.cell import HealthyCell, CancerCell from model.get_voxel_index import get_voxel_index from model.cdirect import cdirect # constants (same naming as Fippel document) for proton transport m_p = 938.272 # [MeV] m_e = 0.511 # [MeV] m_o = 16.0 * m_p # [MeV] r_e = 2.818E-12 # [mm] z = 1.0 # [/] X_w = 360.86 # [mm] Es = 6 # simulation parameter Tmin_e = float('inf') # [MeV] class CellList: """ Used to hold lists of cells on each voxel while keeping cancer cells and healthy cells sorted """ def __init__(self): self.size = 0 # total numbers of cells self.num_c_cells = 0 # number of cancer cell => size - num_c_cells = num_h_cells self.cancer_cells = [] self.healthy_cells = [] def __iter__(self): """Needed to iterate on the list object""" self._iter_count = -1 return self def __next__(self): """Needed to iterate on the list object""" self._iter_count += 1 if self._iter_count < self.num_c_cells: return self.cancer_cells[self._iter_count] elif self._iter_count < self.size: return self.healthy_cells[self._iter_count - self.num_c_cells] else: raise StopIteration def append(self, cell): """Add a cell to the list, keep the API of a Python list""" if cell.cell_type() < 0: self.cancer_cells.append(cell) self.num_c_cells += 1 else: self.healthy_cells.append(cell) self.size += 1 def __len__(self): """Return the size of the list, keep the API of a Python list""" return self.size def __getitem__(self, key): if key < self.size: if key < self.num_c_cells: return self.cancer_cells[key] else: return self.healthy_cells[key - self.num_c_cells] else: raise IndexError def delete_dead(self): """Delete dead cells from the list and update size""" self.cancer_cells = [cell for cell in self.cancer_cells if cell.alive] self.healthy_cells = [cell for cell in self.healthy_cells if cell.alive] self.num_c_cells = len(self.cancer_cells) self.size = self.num_c_cells + len(self.healthy_cells) def pixel_type(self): """Used for observation of types on the grid""" if self.size == 0: # if there is no cell return 0 elif self.num_c_cells: # if number of cancers cells > 1 return -1 else: return 1 def pixel_density(self): """Used for observation of densities on the grid""" if self.num_c_cells: return - self.num_c_cells else: return self.size class Particle: """Proton particle defined by state values """ def __init__(self, position, direction , energy): self.position = position self.direction = direction self.energy = energy class Grid: """ The grid is a 3D phantom of size xSize*ySize*zSize [mm3]. The voxels are cubic and of size defined by voxelSize [mm] Each voxel contains [CellList, glucose, oxygen, density, scoring] """ def __init__(self, width, height, length, voxelSize, density, materialMap, numSources): """ Constructor of the Grid. Parameters : width : in mm height : in mm length : in mm voxelSize : size of a voxel (always cubic !) in mm, i.e resolution densityMap : matrix of size [width, height, length]/voxelSize representing density of tissues for each voxel materialMap : materialMap[i,j,k] is a integer representing a tissue, for accessing SPdatabase numSources : number of nutrient sources on the grid """ # Geometry parameters : self.voxelSize = voxelSize # Size of voxel self.xSize = int(width/voxelSize) # Frontal axis self.ySize = int(height/voxelSize) # Longitudinal axis self.zSize = int(length/voxelSize) # Sagittal axis self.voxelNumbers = self.xSize*self.ySize*self.zSize # Number of voxels # Voxel's data : self.glucose = np.full((self.xSize, self.ySize, self.zSize), 100.0) # oxygen amount of a voxel, with initial scaled value 100 self.oxygen = np.full((self.xSize, self.ySize, self.zSize), 1000.0) # glucose amount of a voxel, with initial scaled value 1000 self.cells = np.empty((self.xSize, self.ySize, self.zSize), dtype=object) # keep track of cells in a voxel, initialize with empty lists for k in range(self.zSize): for i in range(self.xSize): for j in range(self.ySize): self.cells[i, j, k] = CellList() self.scoring = np.zeros((self.xSize, self.ySize, self.zSize), dtype=float) # keep track of deposited energy in a voxel by proton [MeV] self.density = density # density (bone, water, ... ) matrix of voxels [g/cm3] self.materialMap = materialMap # materialMap[i,j,k] = integer representing a tissue, for accesing SPdatabase self.doseMap = None # keep track of deposited dose in a voxel by proton [MeV] # Placement of random sources representing endothelial cells : self.numSources = numSources self.sources = random_sources(self.xSize, self.ySize, self.zSize, numSources) # list of (x,y,z) positions of numSources placed random # Precompute neighboor cells self.neigh_counts = np.zeros((self.xSize, self.ySize, self.zSize), dtype=int) # neigh_counts contains for each voxel on the grid, # the number of cells on neigboring pixels # "Front" face for i in range(self.xSize): # up and down borders self.neigh_counts[i,0,0] += 4 self.neigh_counts[i, self.ySize - 1,0] += 4 for j in range(self.ySize): # left and right borders self.neigh_counts[0, j, 0] += 4 self.neigh_counts[self.xSize - 1, j, 0] += 4 # "Back" face for i in range(self.xSize): # up and down borders self.neigh_counts[i,0,self.zSize-1] += 4 self.neigh_counts[i, self.ySize - 1,self.zSize-1] += 4 for j in range(self.ySize): # left and right borders self.neigh_counts[0, j, self.zSize-1] += 4 self.neigh_counts[self.xSize - 1, j, self.zSize-1] += 4 # "left" face for k in range(self.zSize): # up and down borders self.neigh_counts[0, 0, k] += 4 self.neigh_counts[0, self.ySize-1 ,k] += 4 for j in range(self.ySize): # left and right borders self.neigh_counts[0, j, 0] += 4 self.neigh_counts[0, j, self.zSize-1] += 4 # "right" face for k in range(self.zSize): # up and down borders self.neigh_counts[self.xSize-1, 0, k] += 4 self.neigh_counts[self.xSize-1, self.ySize-1 ,k] += 4 for j in range(self.ySize): # left and right borders self.neigh_counts[self.xSize-1, j, 0] += 4 self.neigh_counts[self.xSize-1, j, self.zSize-1] += 4 self.neigh_counts[0, 0, 0] -= 1 self.neigh_counts[self.xSize-1, 0, 0] -= 1 self.neigh_counts[0, 0, self.zSize-1] -= 1 self.neigh_counts[self.xSize-1, self.ySize-1, 0] -= 1 self.neigh_counts[0, 0, self.zSize-1] -= 1 self.neigh_counts[self.xSize-1, 0, self.zSize-1] -= 1 self.neigh_counts[0, self.ySize-1, self.zSize-1] -= 1 self.neigh_counts[self.xSize-1, self.ySize-1, self.zSize-1] -= 1 # Compute center of the tumor (for tumor placement, cancer cell at the center initially) self.centerX = self.xSize // 2 self.centerY = self.ySize // 2 self.centerZ = self.zSize // 2 # Generate stopping power database (!! path depends on emplacement of running script) self.SP_water = np.loadtxt("DeepRL-PT/model/SPdata/SP_water.txt", 'float', '#', None, None, 8) self.SP_bone = np.loadtxt("DeepRL-PT/model/SPdata/SP_bone.txt", 'float', '#', None, None, 8) # ADDED ONE FOR TESTING self.SP_database = [] self.SP_database.append([]) # index 0 is empty to be consistant with matlab code self.SP_database.append(self.SP_water) # index 1 = water print(SP_database[1][x,y]) self.SP_database.append(self.SP_bone) # index 2 = bone print(SP_database[2][x,y]) #### cells proliferation functions related : def fill_source(self, glucose=0, oxygen=0): """Sources of nutrients are refilled.""" for i in range(len(self.sources)): self.glucose[self.sources[i][0], self.sources[i][1], self.sources[i][2]] += glucose self.oxygen[self.sources[i][0], self.sources[i][1], self.sources[i][2]] += oxygen if random.randint(0, 23) == 0: self.sources[i] = self.source_move(self.sources[i][0], self.sources[i][1], self.sources[i][2]) def source_move(self, x, y, z): """"Random walk of sources for angiogenesis""" if random.randint(0, 50000) < CancerCell.cell_count: # Move towards tumour center if x < self.centerX: x += 1 elif x > self.centerX: x -= 1 if y < self.centerY: y += 1 elif y > self.centerY: y -= 1 if z < self.centerZ: z += 1 elif z > self.centerZ: z -= 1 return x, y, z else: return self.rand_neigh(x, y, z) def rand_neigh(self, x, y, z): """ take a random voxel neighbor of (x,y,z) """ ind = [] for (i, j, k) in [(x - 1, y - 1,z), (x - 1, y,z), (x - 1, y + 1,z), (x, y - 1,z), (x, y + 1,z), (x + 1, y - 1,z), (x + 1, y,z), (x + 1, y + 1,z),(x - 1, y - 1,z-1), (x - 1, y,z-1), (x - 1, y + 1,z-1), (x, y - 1,z-1), (x, y + 1,z-1), (x + 1, y - 1,z-1), (x + 1, y,z-1), (x + 1, y + 1,z-1),(x - 1, y - 1,z+1), (x - 1, y,z+1), (x - 1, y + 1,z+1), (x, y - 1,z+1), (x, y + 1,z+1), (x + 1, y - 1,z+1), (x + 1, y,z+1), (x + 1, y + 1,z+1)]: if (i >= 0 and i < self.xSize and j >= 0 and j < self.ySize and k >=0 and k < self.zSize): ind.append((i, j, k)) return random.choice(ind) def diffuse_glucose(self, drate): """ diffusion of glucose """ self.glucose = (1 - drate) * self.glucose + (0.083 * drate) * self.neighbors_glucose() def diffuse_oxygen(self, drate): """ diffusion of oxygen """ self.oxygen = (1 - drate) * self.oxygen + (0.083 * drate) * self.neighbors_oxygen() def neighbors_glucose(self): """ utility function for diffusion of glucose """ down = np.roll(self.glucose, 1, axis=0) up = np.roll(self.glucose, -1, axis=0) right = np.roll(self.glucose, 1, axis=(0, 1)) left =
np.roll(self.glucose, -1, axis=(0, 1))
numpy.roll
import os import numpy as np import pytest from autolens import exc from autolens.data.array.util import array_util, grid_util from autolens.data.array import mask as msk from autolens.data.array import scaled_array test_data_dir = "{}/../../test_files/array/".format(os.path.dirname(os.path.realpath(__file__))) @pytest.fixture(name="array_grid") def make_array_grid(): return scaled_array.ScaledSquarePixelArray(np.zeros((5, 5)), pixel_scale=0.5) @pytest.fixture(name="array_grid_rectangular") def make_array_grid_rectangular(): return scaled_array.ScaledRectangularPixelArray(np.zeros((5, 5)), pixel_scales=(1.0, 0.5)) class TestArrayGeometry: class TestArrayAndTuples: def test__square_pixel_array__input_data_grid_3x3__centre_is_origin(self): data_grid = scaled_array.ScaledSquarePixelArray(array=np.ones((3, 3)), pixel_scale=1.0) assert data_grid.pixel_scale == 1.0 assert data_grid.shape == (3, 3) assert data_grid.central_pixel_coordinates == (1.0, 1.0) assert data_grid.shape_arc_seconds == pytest.approx((3.0, 3.0)) assert data_grid.arc_second_maxima == (1.5, 1.5) assert data_grid.arc_second_minima == (-1.5, -1.5) assert (data_grid == np.ones((3, 3))).all() def test__square_pixel_array__input_data_grid_rectangular__change_origin(self): data_grid = scaled_array.ScaledSquarePixelArray(array=np.ones((4, 3)), pixel_scale=0.1, origin=(1.0, 1.0)) assert (data_grid == np.ones((4, 3))).all() assert data_grid.pixel_scale == 0.1 assert data_grid.shape == (4, 3) assert data_grid.central_pixel_coordinates == (1.5, 1.0) assert data_grid.shape_arc_seconds == pytest.approx((0.4, 0.3)) assert data_grid.arc_second_maxima == pytest.approx((1.2, 1.15), 1e-4) assert data_grid.arc_second_minima == pytest.approx((0.8, 0.85), 1e-4) data_grid = scaled_array.ScaledSquarePixelArray(array=np.ones((3, 4)), pixel_scale=0.1) assert (data_grid == np.ones((3, 4))).all() assert data_grid.pixel_scale == 0.1 assert data_grid.shape == (3, 4) assert data_grid.central_pixel_coordinates == (1.0, 1.5) assert data_grid.shape_arc_seconds == pytest.approx((0.3, 0.4)) assert data_grid.arc_second_maxima == pytest.approx((0.15, 0.2), 1e-4) assert data_grid.arc_second_minima == pytest.approx((-0.15, -0.2), 1e-4) def test__rectangular_pixel_grid__input_data_grid_3x3(self): data_grid = scaled_array.ScaledRectangularPixelArray(array=np.ones((3, 3)), pixel_scales=(2.0, 1.0)) assert data_grid == pytest.approx(np.ones((3, 3)), 1e-4) assert data_grid.pixel_scales == (2.0, 1.0) assert data_grid.shape == (3, 3) assert data_grid.central_pixel_coordinates == (1.0, 1.0) assert data_grid.shape_arc_seconds == pytest.approx((6.0, 3.0)) assert data_grid.arc_second_maxima == pytest.approx((3.0, 1.5), 1e-4) assert data_grid.arc_second_minima == pytest.approx((-3.0, -1.5), 1e-4) def test__rectangular_pixel_grid__input_data_grid_rectangular(self): data_grid = scaled_array.ScaledRectangularPixelArray(array=np.ones((4, 3)), pixel_scales=(0.2, 0.1)) assert data_grid == pytest.approx(np.ones((4, 3)), 1e-4) assert data_grid.pixel_scales == (0.2, 0.1) assert data_grid.shape == (4, 3) assert data_grid.central_pixel_coordinates == (1.5, 1.0) assert data_grid.shape_arc_seconds == pytest.approx((0.8, 0.3), 1e-3) assert data_grid.arc_second_maxima == pytest.approx((0.4, 0.15), 1e-4) assert data_grid.arc_second_minima == pytest.approx((-0.4, -0.15), 1e-4) data_grid = scaled_array.ScaledRectangularPixelArray(array=np.ones((3, 4)), pixel_scales=(0.1, 0.2)) assert data_grid == pytest.approx(np.ones((3, 4)), 1e-4) assert data_grid.pixel_scales == (0.1, 0.2) assert data_grid.shape == (3, 4) assert data_grid.central_pixel_coordinates == (1.0, 1.5) assert data_grid.shape_arc_seconds == pytest.approx((0.3, 0.8), 1e-3) assert data_grid.arc_second_maxima == pytest.approx((0.15, 0.4), 1e-4) assert data_grid.arc_second_minima == pytest.approx((-0.15, -0.4), 1e-4) def test__rectangular_pixel_array__input_data_grid_3x3__centre_is_yminus1_xminuss2(self): data_grid = scaled_array.ScaledRectangularPixelArray(array=np.ones((3, 3)), pixel_scales=(2.0, 1.0), origin=(-1.0, -2.0)) assert data_grid == pytest.approx(np.ones((3, 3)), 1e-4) assert data_grid.pixel_scales == (2.0, 1.0) assert data_grid.shape == (3, 3) assert data_grid.central_pixel_coordinates == (1.0, 1.0) assert data_grid.shape_arc_seconds == pytest.approx((6.0, 3.0)) assert data_grid.origin == (-1.0, -2.0) assert data_grid.arc_second_maxima == pytest.approx((2.0, -0.5), 1e-4) assert data_grid.arc_second_minima == pytest.approx((-4.0, -3.5), 1e-4) class TestCentralPixel: def test__square_pixel_grid(self): grid = scaled_array.ScaledSquarePixelArray(np.zeros((3, 3)), pixel_scale=0.1) assert grid.central_pixel_coordinates == (1, 1) grid = scaled_array.ScaledSquarePixelArray(np.zeros((4, 4)), pixel_scale=0.1) assert grid.central_pixel_coordinates == (1.5, 1.5) grid = scaled_array.ScaledSquarePixelArray(np.zeros((5, 3)), pixel_scale=0.1, origin=(1.0, 2.0)) assert grid.central_pixel_coordinates == (2.0, 1.0) def test__rectangular_pixel_grid(self): grid = scaled_array.ScaledRectangularPixelArray(np.zeros((3, 3)), pixel_scales=(2.0, 1.0)) assert grid.central_pixel_coordinates == (1, 1) grid = scaled_array.ScaledRectangularPixelArray(np.zeros((4, 4)), pixel_scales=(2.0, 1.0)) assert grid.central_pixel_coordinates == (1.5, 1.5) grid = scaled_array.ScaledRectangularPixelArray(np.zeros((5, 3)), pixel_scales=(2.0, 1.0), origin=(1.0, 2.0)) assert grid.central_pixel_coordinates == (2, 1) class TestGrids: def test__square_pixel_grid__grid_2d__compare_to_array_util(self): grid_2d_util = grid_util.regular_grid_2d_from_shape_pixel_scales_and_origin(shape=(4, 7), pixel_scales=(0.56, 0.56)) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((4, 7)), pixel_scale=0.56) assert sca.grid_2d == pytest.approx(grid_2d_util, 1e-4) def test__square_pixel_grid__array_3x3__sets_up_arc_second_grid(self): sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((3, 3)), pixel_scale=1.0) assert (sca.grid_2d == np.array([[[1., -1.], [1., 0.], [1., 1.]], [[0., -1.], [0., 0.], [0., 1.]], [[-1., -1.], [-1., 0.], [-1., 1.]]])).all() def test__square_pixel_grid__grid_1d__compare_to_array_util(self): grid_1d_util = grid_util.regular_grid_1d_from_shape_pixel_scales_and_origin(shape=(4, 7), pixel_scales=(0.56, 0.56)) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((4, 7)), pixel_scale=0.56) assert sca.grid_1d == pytest.approx(grid_1d_util, 1e-4) def test__square_pixel_grid__nonzero_centres__compure_to_array_util(self): grid_2d_util = grid_util.regular_grid_2d_from_shape_pixel_scales_and_origin(shape=(4, 7), pixel_scales=(0.56, 0.56), origin=(1.0, 3.0)) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((4, 7)), pixel_scale=0.56, origin=(1.0, 3.0)) assert sca.grid_2d == pytest.approx(grid_2d_util, 1e-4) grid_1d_util = grid_util.regular_grid_1d_from_shape_pixel_scales_and_origin(shape=(4, 7), pixel_scales=(0.56, 0.56), origin=(-1.0, -4.0)) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((4, 7)), pixel_scale=0.56, origin=(-1.0, -4.0)) assert sca.grid_1d == pytest.approx(grid_1d_util, 1e-4) def test__rectangular_pixel_grid__grid_2d__compare_to_array_util(self): grid_2d_util = grid_util.regular_grid_2d_from_shape_pixel_scales_and_origin(shape=(4, 7), pixel_scales=(0.8, 0.56)) sca = scaled_array.ScaledRectangularPixelArray(array=np.zeros((4, 7)), pixel_scales=(0.8, 0.56)) assert sca.grid_2d == pytest.approx(grid_2d_util, 1e-4) def test__rectangular_pixel_grid__array_3x3__sets_up_arcsecond_grid(self): sca = scaled_array.ScaledRectangularPixelArray(array=np.zeros((3, 3)), pixel_scales=(1.0, 2.0)) assert (sca.grid_2d == np.array([[[1., -2.], [1., 0.], [1., 2.]], [[0., -2.], [0., 0.], [0., 2.]], [[-1., -2.], [-1., 0.], [-1., 2.]]])).all() def test__rectangular_pixel_grid__grid_1d__compare_to_array_util(self): grid_1d_util = grid_util.regular_grid_1d_from_shape_pixel_scales_and_origin(shape=(4, 7), pixel_scales=(0.8, 0.56)) sca = scaled_array.ScaledRectangularPixelArray(array=np.zeros((4, 7)), pixel_scales=(0.8, 0.56)) assert sca.grid_1d == pytest.approx(grid_1d_util, 1e-4) def test__rectangular_pixel_grid__nonzero_centres__compure_to_array_util(self): grid_2d_util = grid_util.regular_grid_2d_from_shape_pixel_scales_and_origin(shape=(4, 7), pixel_scales=(0.8, 0.56), origin=(1.0, 2.0)) sca = scaled_array.ScaledRectangularPixelArray(array=np.zeros((4, 7)), pixel_scales=(0.8, 0.56), origin=(1.0, 2.0)) assert sca.grid_2d == pytest.approx(grid_2d_util, 1e-4) grid_1d_util = grid_util.regular_grid_1d_from_shape_pixel_scales_and_origin(shape=(4, 7), pixel_scales=(0.8, 0.56), origin=(-1.0, -4.0)) sca = scaled_array.ScaledRectangularPixelArray(array=np.zeros((4, 7)), pixel_scales=(0.8, 0.56), origin=(-1.0, -4.0)) assert sca.grid_1d == pytest.approx(grid_1d_util, 1e-4) class TestConversion: def test__arc_second_coordinates_to_pixel_coordinates__arc_seconds_are_pixel_centres(self): sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((2, 2)), pixel_scale=2.0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(1.0, -1.0)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(1.0, 1.0)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-1.0, -1.0)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-1.0, 1.0)) == (1, 1) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((3, 3)), pixel_scale=3.0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(3.0, -3.0)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(3.0, 0.0)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(3.0, 3.0)) == (0, 2) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.0, -3.0)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.0, 0.0)) == (1, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.0, 3.0)) == (1, 2) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-3.0, -3.0)) == (2, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-3.0, 0.0)) == (2, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-3.0, 3.0)) == (2, 2) def test__arc_second_coordinates_to_pixel_coordinates__arc_seconds_are_pixel_corners(self): sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((2, 2)), pixel_scale=2.0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(1.99, -1.99)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(1.99, -0.01)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.01, -1.99)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.01, -0.01)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(2.01, 0.01)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(2.01, 1.99)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.01, 0.01)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.01, 1.99)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-0.01, -1.99)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-0.01, -0.01)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-1.99, -1.99)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-1.99, -0.01)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-0.01, 0.01)) == (1, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-0.01, 1.99)) == (1, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-1.99, 0.01)) == (1, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-1.99, 1.99)) == (1, 1) def test__arc_second_coordinates_to_pixel_coordinates__arc_seconds_are_pixel_centres__nonzero_centre(self): sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((2, 2)), pixel_scale=2.0, origin=(1.0, 1.0)) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(2.0, 0.0)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(2.0, 2.0)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.0, 0.0)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.0, 2.0)) == (1, 1) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((3, 3)), pixel_scale=3.0, origin=(3.0, 3.0)) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(6.0, 0.0)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(6.0, 3.0)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(6.0, 6.0)) == (0, 2) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(3.0, 0.0)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(3.0, 3.0)) == (1, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(3.0, 6.0)) == (1, 2) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.0, 0.0)) == (2, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.0, 3.0)) == (2, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.0, 6.0)) == (2, 2) def test__arc_second_coordinates_to_pixel_coordinates__arc_seconds_are_pixel_corners__nonzero_centre(self): sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((2, 2)), pixel_scale=2.0, origin=(1.0, 1.0)) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(2.99, -0.99)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(2.99, 0.99)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(1.01, -0.99)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(1.01, 0.99)) == (0, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(3.01, 1.01)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(3.01, 2.99)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(1.01, 1.01)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(1.01, 2.99)) == (0, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.99, -0.99)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.99, 0.99)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-0.99, -0.99)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-0.99, 0.99)) == (1, 0) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.99, 1.01)) == (1, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(0.99, 2.99)) == (1, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-0.99, 1.01)) == (1, 1) assert sca.arc_second_coordinates_to_pixel_coordinates(arc_second_coordinates=(-0.99, 2.99)) == (1, 1) def test__square_pixel_grid__1d_arc_second_grid_to_1d_pixel_centred_grid__same_as_imaging_util(self): grid_arc_seconds = np.array([[0.5, -0.5], [0.5, 0.5], [-0.5, -0.5], [-0.5, 0.5]]) grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixel_centres_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 2.0)) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((2, 2)), pixel_scale=2.0) grid_pixels = sca.grid_arc_seconds_to_grid_pixel_centres(grid_arc_seconds=grid_arc_seconds) assert (grid_pixels == grid_pixels_util).all() def test__square_pixel_grid__1d_arc_second_grid_to_1d_pixel_indexes_grid__same_as_imaging_util(self): grid_arc_seconds = np.array([[1.0, -1.0], [1.0, 1.0], [-1.0, -1.0], [-1.0, 1.0]]) grid_pixel_indexes_util = grid_util.grid_arc_seconds_1d_to_grid_pixel_indexes_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 2.0)) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((2, 2)), pixel_scale=2.0) grid_pixel_indexes = sca.grid_arc_seconds_to_grid_pixel_indexes(grid_arc_seconds=grid_arc_seconds) assert (grid_pixel_indexes == grid_pixel_indexes_util).all() def test__rectangular_pixel_grid__1d_arc_second_grid_to_1d_pixel_centred_grid__same_as_imaging_util(self): grid_arc_seconds = np.array([[1.0, -2.0], [1.0, 2.0], [-1.0, -2.0], [-1.0, 2.0]]) grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixel_centres_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(7.0, 2.0)) sca = scaled_array.ScaledRectangularPixelArray(array=np.zeros((2, 2)), pixel_scales=(7.0, 2.0)) grid_pixels = sca.grid_arc_seconds_to_grid_pixel_centres(grid_arc_seconds=grid_arc_seconds) assert (grid_pixels == grid_pixels_util).all() def test__rectangular_pixel_grid__1d_arc_second_grid_to_1d_pixel_indexes_grid__same_as_imaging_util(self): grid_arc_seconds = np.array([[1.0, -2.0], [1.0, 2.0], [-1.0, -2.0], [-1.0, 2.0]]) grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixel_indexes_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 4.0)) sca = scaled_array.ScaledRectangularPixelArray(array=np.zeros((2, 2)), pixel_scales=(2.0, 4.0)) grid_pixels = sca.grid_arc_seconds_to_grid_pixel_indexes(grid_arc_seconds=grid_arc_seconds) assert (grid_pixels == grid_pixels_util).all() def test__rectangular_pixel_grid__1d_arc_second_grid_to_1d_pixel_grid__same_as_imaging_util(self): grid_arc_seconds = np.array([[1.0, -2.0], [1.0, 2.0], [-1.0, -2.0], [-1.0, 2.0]]) grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixels_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 4.0)) sca = scaled_array.ScaledRectangularPixelArray(array=np.zeros((2, 2)), pixel_scales=(2.0, 4.0)) grid_pixels = sca.grid_arc_seconds_to_grid_pixels(grid_arc_seconds=grid_arc_seconds) assert (grid_pixels == grid_pixels_util).all() def test__square_pixel_grid__1d_pixel_grid_to_1d_pixel_centred_grid__same_as_imaging_util(self): grid_pixels = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) grid_pixels_util = grid_util.grid_pixels_1d_to_grid_arc_seconds_1d( grid_pixels_1d=grid_pixels, shape=(2, 2), pixel_scales=(2.0, 2.0)) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((2, 2)), pixel_scale=2.0) grid_pixels = sca.grid_pixels_to_grid_arc_seconds(grid_pixels=grid_pixels) assert (grid_pixels == grid_pixels_util).all() def test__square_pixel_grid__1d_pixel_grid_to_1d_pixel_grid__same_as_imaging_util(self): grid_pixels = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) grid_pixels_util = grid_util.grid_pixels_1d_to_grid_arc_seconds_1d( grid_pixels_1d=grid_pixels, shape=(2, 2), pixel_scales=(2.0, 2.0)) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((2, 2)), pixel_scale=2.0) grid_pixels = sca.grid_pixels_to_grid_arc_seconds(grid_pixels=grid_pixels) assert (grid_pixels == grid_pixels_util).all() def test__square_pixel_grid__grids_with_nonzero_centres__same_as_imaging_util(self): grid_arc_seconds = np.array([[1.0, -2.0], [1.0, 2.0], [-1.0, -2.0], [-1.0, 2.0]]) sca = scaled_array.ScaledSquarePixelArray(array=np.zeros((2, 2)), pixel_scale=2.0, origin=(1.0, 2.0)) grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixels_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 2.0), origin=(1.0, 2.0)) grid_pixels = sca.grid_arc_seconds_to_grid_pixels(grid_arc_seconds=grid_arc_seconds) assert (grid_pixels == grid_pixels_util).all() grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixel_indexes_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 2.0), origin=(1.0, 2.0)) grid_pixels = sca.grid_arc_seconds_to_grid_pixel_indexes(grid_arc_seconds=grid_arc_seconds) assert grid_pixels == pytest.approx(grid_pixels_util, 1e-4) grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixel_centres_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 2.0), origin=(1.0, 2.0)) grid_pixels = sca.grid_arc_seconds_to_grid_pixel_centres(grid_arc_seconds=grid_arc_seconds) assert grid_pixels == pytest.approx(grid_pixels_util, 1e-4) grid_pixels = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) grid_arc_seconds_util = grid_util.grid_pixels_1d_to_grid_arc_seconds_1d(grid_pixels_1d=grid_pixels, shape=(2, 2), pixel_scales=(2.0, 2.0), origin=(1.0, 2.0)) grid_arc_seconds = sca.grid_pixels_to_grid_arc_seconds(grid_pixels=grid_pixels) assert (grid_arc_seconds == grid_arc_seconds_util).all() def test__rectangular_pixel_grid__grids_with_nonzero_centres__same_as_imaging_util(self): grid_arc_seconds = np.array([[1.0, -2.0], [1.0, 2.0], [-1.0, -2.0], [-1.0, 2.0]]) sca = scaled_array.ScaledRectangularPixelArray(array=np.zeros((2, 2)), pixel_scales=(2.0, 1.0), origin=(1.0, 2.0)) grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixels_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 1.0), origin=(1.0, 2.0)) grid_pixels = sca.grid_arc_seconds_to_grid_pixels(grid_arc_seconds=grid_arc_seconds) assert (grid_pixels == grid_pixels_util).all() grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixel_indexes_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 1.0), origin=(1.0, 2.0)) grid_pixels = sca.grid_arc_seconds_to_grid_pixel_indexes(grid_arc_seconds=grid_arc_seconds) assert (grid_pixels == grid_pixels_util).all() grid_pixels_util = grid_util.grid_arc_seconds_1d_to_grid_pixel_centres_1d( grid_arc_seconds_1d=grid_arc_seconds, shape=(2, 2), pixel_scales=(2.0, 1.0), origin=(1.0, 2.0)) grid_pixels = sca.grid_arc_seconds_to_grid_pixel_centres(grid_arc_seconds=grid_arc_seconds) assert grid_pixels == pytest.approx(grid_pixels_util, 1e-4) grid_pixels = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) grid_arc_seconds_util = grid_util.grid_pixels_1d_to_grid_arc_seconds_1d(grid_pixels_1d=grid_pixels, shape=(2, 2), pixel_scales=(2.0, 1.0), origin=(1.0, 2.0)) grid_arc_seconds = sca.grid_pixels_to_grid_arc_seconds(grid_pixels=grid_pixels) assert (grid_arc_seconds == grid_arc_seconds_util).all() class TestTicks: def test__square_pixel_grid__yticks(self): sca = scaled_array.ScaledSquarePixelArray(array=np.ones((3, 3)), pixel_scale=1.0) assert sca.yticks == pytest.approx(np.array([-1.5, -0.5, 0.5, 1.5]), 1e-3) sca = scaled_array.ScaledSquarePixelArray(array=np.ones((3, 3)), pixel_scale=0.5) assert sca.yticks == pytest.approx(np.array([-0.75, -0.25, 0.25, 0.75]), 1e-3) sca = scaled_array.ScaledSquarePixelArray(array=np.ones((6, 3)), pixel_scale=1.0) assert sca.yticks == pytest.approx(np.array([-3.0, -1.0, 1.0, 3.0]), 1e-3) sca = scaled_array.ScaledSquarePixelArray(array=np.ones((3, 1)), pixel_scale=1.0) assert sca.yticks == pytest.approx(np.array([-1.5, -0.5, 0.5, 1.5]), 1e-3) def test__square_pixel_grid__xticks(self): sca = scaled_array.ScaledSquarePixelArray(array=np.ones((3, 3)), pixel_scale=1.0) assert sca.xticks == pytest.approx(np.array([-1.5, -0.5, 0.5, 1.5]), 1e-3) sca = scaled_array.ScaledSquarePixelArray(array=np.ones((3, 3)), pixel_scale=0.5) assert sca.xticks == pytest.approx(np.array([-0.75, -0.25, 0.25, 0.75]), 1e-3) sca = scaled_array.ScaledSquarePixelArray(array=np.ones((3, 6)), pixel_scale=1.0) assert sca.xticks == pytest.approx(
np.array([-3.0, -1.0, 1.0, 3.0])
numpy.array
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Dict, List, Optional, Type, Union import json import math import torch import numpy as np from gym import spaces from habitat.config import Config from habitat.core.registry import registry from habitat.core.simulator import ( AgentState, Sensor, SensorTypes, Simulator, ) from habitat.core.utils import try_cv2_import from habitat.tasks.utils import cartesian_to_polar from habitat_extensions.geometry_utils import ( compute_updated_pose, quaternion_from_coeff, quaternion_xyzw_to_wxyz, quaternion_rotate_vector, compute_egocentric_delta, compute_heading_from_quaternion, ) from habitat.tasks.nav.nav import PointGoalSensor from habitat_extensions.utils import truncated_normal_noise_distr from habitat.utils.visualizations import fog_of_war, maps from occant_utils.map import ( subtract_pose, grow_projected_map, spatial_transform_map, ) cv2 = try_cv2_import() from einops import rearrange, asnumpy @registry.register_sensor(name="GTPoseSensor") class GTPoseSensor(Sensor): r"""The agents current ground-truth pose in the coordinate frame defined by the episode, i.e. the axis it faces along and the origin is defined by its state at t=0. Args: sim: reference to the simulator for calculating task observations. config: not needed """ def __init__(self, sim: Simulator, config: Config, *args: Any, **kwargs: Any): self._sim = sim super().__init__(config=config) def _get_uuid(self, *args: Any, **kwargs: Any): return "pose_gt" def _get_sensor_type(self, *args: Any, **kwargs: Any): return SensorTypes.POSITION def _get_observation_space(self, *args: Any, **kwargs: Any): sensor_shape = (3,) return spaces.Box( low=np.finfo(np.float32).min, high=np.finfo(np.float32).max, shape=sensor_shape, dtype=np.float32, ) def _quat_to_xy_heading(self, quat): direction_vector = np.array([0, 0, -1]) heading_vector = quaternion_rotate_vector(quat, direction_vector) phi = cartesian_to_polar(-heading_vector[2], heading_vector[0])[1] return np.array(phi) def get_observation(self, *args: Any, observations, episode, **kwargs: Any): agent_state = self._sim.get_agent_state() origin = np.array(episode.start_position, dtype=np.float32) rotation_world_start = quaternion_from_coeff(episode.start_rotation) agent_position = agent_state.position agent_position = quaternion_rotate_vector( rotation_world_start.inverse(), agent_position - origin ) rotation_world_agent = agent_state.rotation rotation_world_start = quaternion_from_coeff(episode.start_rotation) agent_heading = self._quat_to_xy_heading( rotation_world_agent.inverse() * rotation_world_start ) # This is rotation from -Z to -X. We want -Z to X for this particular sensor. agent_heading = -agent_heading return np.array( [-agent_position[2], agent_position[0], agent_heading], dtype=np.float32, ) @registry.register_sensor(name="NoisyPoseSensor") class NoisyPoseSensor(Sensor): r"""The agents current estimated pose in the coordinate frame defined by the episode, i.e. the axis it faces along and the origin is defined by its state at t=0 The estimate is obtained by accumulating noisy odometer readings over time. Args: sim: reference to the simulator for calculating task observations. config: Contains the NOISE_SCALING field for the amount of noise added to the odometer. Attributes: _estimated_position: the estimated agent position in real-world [X, Y, Z]. _estimated_rotation: the estimated agent rotation expressed as quaternion. """ def __init__(self, sim: Simulator, config: Config, *args: Any, **kwargs: Any): self._sim = sim super().__init__(config=config) self.current_episode_id = None self._estimated_position = None self._estimated_rotation = None cfg = self.config self._fwd_tn_distr = truncated_normal_noise_distr( cfg.FORWARD_MEAN, cfg.FORWARD_VARIANCE, 2 ) self._rot_tn_distr = truncated_normal_noise_distr( cfg.ROTATION_MEAN, cfg.ROTATION_VARIANCE, 2 ) def _get_uuid(self, *args: Any, **kwargs: Any): return "pose" def _get_sensor_type(self, *args: Any, **kwargs: Any): return SensorTypes.POSITION def _get_observation_space(self, *args: Any, **kwargs: Any): sensor_shape = (3,) return spaces.Box( low=np.finfo(np.float32).min, high=np.finfo(np.float32).max, shape=sensor_shape, dtype=np.float32, ) def _quat_to_xy_heading(self, quat): direction_vector = np.array([0, 0, -1]) heading_vector = quaternion_rotate_vector(quat, direction_vector) phi = cartesian_to_polar(-heading_vector[2], heading_vector[0])[1] return np.array(phi) def _get_noisy_delta(self, agent_state): current_agent_position = agent_state.position current_agent_rotation = agent_state.rotation past_agent_position = self._past_gt_position past_agent_rotation = self._past_gt_rotation # GT delta delta_xz_gt = compute_egocentric_delta( past_agent_position, past_agent_rotation, current_agent_position, current_agent_rotation, ) delta_y_gt = current_agent_position[1] - past_agent_position[0] # Add noise to D_rho, D_theta D_rho, D_phi, D_theta = delta_xz_gt D_rho_noisy = (D_rho + self._fwd_tn_distr.rvs() * np.sign(D_rho)).item() D_phi_noisy = D_phi D_theta_noisy = (D_theta + self._rot_tn_distr.rvs() * np.sign(D_theta)).item() # Compute noisy delta delta_xz_noisy = (D_rho_noisy, D_phi_noisy, D_theta_noisy) delta_y_noisy = delta_y_gt return delta_xz_noisy, delta_y_noisy def get_observation(self, *args: Any, observations, episode, **kwargs: Any): episode_id = (episode.episode_id, episode.scene_id) agent_state = self._sim.get_agent_state() # At the start of a new episode, reset pose estimate if self.current_episode_id != episode_id: self.current_episode_id = episode_id # Initialize with the ground-truth position, rotation self._estimated_position = agent_state.position self._estimated_rotation = agent_state.rotation self._past_gt_position = agent_state.position self._past_gt_rotation = agent_state.rotation # Compute noisy delta delta_xz_noisy, delta_y_noisy = self._get_noisy_delta(agent_state) # Update past gt states self._past_gt_position = agent_state.position self._past_gt_rotation = agent_state.rotation # Update noisy pose estimates (self._estimated_position, self._estimated_rotation,) = compute_updated_pose( self._estimated_position, self._estimated_rotation, delta_xz_noisy, delta_y_noisy, ) # Compute sensor readings with noisy estimates origin = np.array(episode.start_position, dtype=np.float32) rotation_world_start = quaternion_from_coeff(episode.start_rotation) agent_position = self._estimated_position agent_position = quaternion_rotate_vector( rotation_world_start.inverse(), agent_position - origin ) rotation_world_agent = self._estimated_rotation rotation_world_start = quaternion_from_coeff(episode.start_rotation) agent_heading = self._quat_to_xy_heading( rotation_world_agent.inverse() * rotation_world_start ) # This is rotation from -Z to -X. We want -Z to X for this particular sensor. agent_heading = -agent_heading return np.array( [-agent_position[2], agent_position[0], agent_heading], dtype=np.float32, ) @registry.register_sensor(name="NoiseFreePoseSensor") class NoiseFreePoseSensor(Sensor): r"""The agents current ground-truth pose in the coordinate frame defined by the episode, i.e. the axis it faces along and the origin is defined by its state at t=0. Args: sim: reference to the simulator for calculating task observations. config: not needed """ def __init__(self, sim: Simulator, config: Config, *args: Any, **kwargs: Any): self._sim = sim super().__init__(config=config) def _get_uuid(self, *args: Any, **kwargs: Any): return "pose" def _get_sensor_type(self, *args: Any, **kwargs: Any): return SensorTypes.POSITION def _get_observation_space(self, *args: Any, **kwargs: Any): sensor_shape = (3,) return spaces.Box( low=np.finfo(np.float32).min, high=np.finfo(np.float32).max, shape=sensor_shape, dtype=np.float32, ) def _quat_to_xy_heading(self, quat): direction_vector = np.array([0, 0, -1]) heading_vector = quaternion_rotate_vector(quat, direction_vector) phi = cartesian_to_polar(-heading_vector[2], heading_vector[0])[1] return np.array(phi) def get_observation(self, *args: Any, observations, episode, **kwargs: Any): agent_state = self._sim.get_agent_state() origin = np.array(episode.start_position, dtype=np.float32) rotation_world_start = quaternion_from_coeff(episode.start_rotation) agent_position = agent_state.position agent_position = quaternion_rotate_vector( rotation_world_start.inverse(), agent_position - origin ) rotation_world_agent = agent_state.rotation rotation_world_start = quaternion_from_coeff(episode.start_rotation) agent_heading = self._quat_to_xy_heading( rotation_world_agent.inverse() * rotation_world_start ) # This is rotation from -Z to -X. We want -Z to X for this particular sensor. agent_heading = -agent_heading return np.array( [-agent_position[2], agent_position[0], agent_heading], dtype=np.float32, ) @registry.register_sensor(name="GTEgoMap") class GTEgoMap(Sensor): r"""Estimates the top-down occupancy based on current depth-map. Args: sim: reference to the simulator for calculating task observations. config: contains the MAP_SCALE, MAP_SIZE, HEIGHT_THRESH fields to decide grid-size, extents of the projection, and the thresholds for determining obstacles and explored space. """ def __init__(self, sim: Simulator, config: Config, *args: Any, **kwargs: Any): self._sim = sim super().__init__(config=config) # Map statistics self.map_size = self.config.MAP_SIZE self.map_scale = self.config.MAP_SCALE if self.config.MAX_SENSOR_RANGE > 0: self.max_forward_range = self.config.MAX_SENSOR_RANGE else: self.max_forward_range = self.map_size * self.map_scale # Agent height for pointcloud tranforms self.camera_height = self._sim.habitat_config.DEPTH_SENSOR.POSITION[1] # Compute intrinsic matrix depth_H = self._sim.habitat_config.DEPTH_SENSOR.HEIGHT depth_W = self._sim.habitat_config.DEPTH_SENSOR.WIDTH hfov = float(self._sim.habitat_config.DEPTH_SENSOR.HFOV) * np.pi / 180 vfov = 2 * np.arctan((depth_H / depth_W) * np.tan(hfov / 2.0)) self.intrinsic_matrix = np.array( [ [1 / np.tan(hfov / 2.0), 0.0, 0.0, 0.0], [0.0, 1 / np.tan(vfov / 2.0), 0.0, 0.0], [0.0, 0.0, 1, 0], [0.0, 0.0, 0, 1], ] ) self.inverse_intrinsic_matrix = np.linalg.inv(self.intrinsic_matrix) # Height thresholds for obstacles self.height_thresh = self.config.HEIGHT_THRESH # Depth processing self.min_depth = float(self._sim.habitat_config.DEPTH_SENSOR.MIN_DEPTH) self.max_depth = float(self._sim.habitat_config.DEPTH_SENSOR.MAX_DEPTH) # Pre-compute a grid of locations for depth projection W = self._sim.habitat_config.DEPTH_SENSOR.WIDTH H = self._sim.habitat_config.DEPTH_SENSOR.HEIGHT self.proj_xs, self.proj_ys = np.meshgrid( np.linspace(-1, 1, W), np.linspace(1, -1, H) ) def _get_uuid(self, *args: Any, **kwargs: Any): return "ego_map_gt" def _get_sensor_type(self, *args: Any, **kwargs: Any): return SensorTypes.COLOR def _get_observation_space(self, *args: Any, **kwargs: Any): sensor_shape = (self.config.MAP_SIZE, self.config.MAP_SIZE, 2) return spaces.Box(low=0, high=1, shape=sensor_shape, dtype=np.uint8,) def convert_to_pointcloud(self, depth): """ Inputs: depth = (H, W, 1) numpy array Returns: xyz_camera = (N, 3) numpy array for (X, Y, Z) in egocentric world coordinates """ depth_float = depth.astype(np.float32)[..., 0] # =========== Convert to camera coordinates ============ W = depth.shape[1] xs = np.copy(self.proj_xs).reshape(-1) ys = np.copy(self.proj_ys).reshape(-1) depth_float = depth_float.reshape(-1) # Filter out invalid depths valid_depths = (depth_float != self.min_depth) & ( depth_float <= self.max_forward_range ) xs = xs[valid_depths] ys = ys[valid_depths] depth_float = depth_float[valid_depths] # Unproject # negate depth as the camera looks along -Z xys = np.vstack( ( xs * depth_float, ys * depth_float, -depth_float, np.ones(depth_float.shape), ) ) inv_K = self.inverse_intrinsic_matrix xyz_camera = np.matmul(inv_K, xys).T # XYZ in the camera coordinate system xyz_camera = xyz_camera[:, :3] / xyz_camera[:, 3][:, np.newaxis] return xyz_camera def safe_assign(self, im_map, x_idx, y_idx, value): try: im_map[x_idx, y_idx] = value except IndexError: valid_idx1 = np.logical_and(x_idx >= 0, x_idx < im_map.shape[0]) valid_idx2 = np.logical_and(y_idx >= 0, y_idx < im_map.shape[1]) valid_idx = np.logical_and(valid_idx1, valid_idx2) im_map[x_idx[valid_idx], y_idx[valid_idx]] = value def _get_depth_projection(self, sim_depth): """ Project pixels visible in depth-map to ground-plane """ if self._sim.habitat_config.DEPTH_SENSOR.NORMALIZE_DEPTH: depth = sim_depth * (self.max_depth - self.min_depth) + self.min_depth else: depth = sim_depth XYZ_ego = self.convert_to_pointcloud(depth) # Adding agent's height to the pointcloud XYZ_ego[:, 1] += self.camera_height # Convert to grid coordinate system V = self.map_size Vby2 = V // 2 points = XYZ_ego grid_x = (points[:, 0] / self.map_scale) + Vby2 grid_y = (points[:, 2] / self.map_scale) + V # Filter out invalid points valid_idx = ( (grid_x >= 0) & (grid_x <= V - 1) & (grid_y >= 0) & (grid_y <= V - 1) ) points = points[valid_idx, :] grid_x = grid_x[valid_idx].astype(int) grid_y = grid_y[valid_idx].astype(int) # Create empty maps for the two channels obstacle_mat = np.zeros((self.map_size, self.map_size), np.uint8) explore_mat = np.zeros((self.map_size, self.map_size), np.uint8) # Compute obstacle locations high_filter_idx = points[:, 1] < self.height_thresh[1] low_filter_idx = points[:, 1] > self.height_thresh[0] obstacle_idx = np.logical_and(low_filter_idx, high_filter_idx) self.safe_assign(obstacle_mat, grid_y[obstacle_idx], grid_x[obstacle_idx], 1) kernel = np.ones((3, 3), np.uint8) obstacle_mat = cv2.dilate(obstacle_mat, kernel, iterations=1) # Compute explored locations explored_idx = high_filter_idx self.safe_assign(explore_mat, grid_y[explored_idx], grid_x[explored_idx], 1) kernel = np.ones((3, 3), np.uint8) obstacle_mat = cv2.dilate(obstacle_mat, kernel, iterations=1) # Smoothen the maps kernel = np.ones((3, 3), np.uint8) obstacle_mat = cv2.morphologyEx(obstacle_mat, cv2.MORPH_CLOSE, kernel) explore_mat = cv2.morphologyEx(explore_mat, cv2.MORPH_CLOSE, kernel) # Ensure all expanded regions in obstacle_mat are accounted for in explored_mat explore_mat = np.logical_or(explore_mat, obstacle_mat) return np.stack([obstacle_mat, explore_mat], axis=2) def get_observation(self, *args: Any, observations, episode, **kwargs: Any): sim_depth = asnumpy(observations["depth"]) ego_map_gt = self._get_depth_projection(sim_depth) return ego_map_gt @registry.register_sensor(name="GTEgoWallMap") class GTEgoWallMap(Sensor): r"""Estimates the top-down wall occupancy based on current depth-map. Args: sim: reference to the simulator for calculating task observations. config: contains the MAP_SCALE, MAP_SIZE, HEIGHT_THRESH fields to decide grid-size, extents of the projection, and the thresholds for determining obstacles and explored space. """ def __init__(self, sim: Simulator, config: Config, *args: Any, **kwargs: Any): self._sim = sim super().__init__(config=config) # Map statistics self.map_size = self.config.MAP_SIZE self.map_scale = self.config.MAP_SCALE if self.config.MAX_SENSOR_RANGE > 0: self.max_forward_range = self.config.MAX_SENSOR_RANGE else: self.max_forward_range = self.map_size * self.map_scale # Agent height for pointcloud tranforms self.camera_height = self._sim.habitat_config.DEPTH_SENSOR.POSITION[1] # Compute intrinsic matrix depth_H = self._sim.habitat_config.DEPTH_SENSOR.HEIGHT depth_W = self._sim.habitat_config.DEPTH_SENSOR.WIDTH hfov = float(self._sim.habitat_config.DEPTH_SENSOR.HFOV) * np.pi / 180 vfov = 2 * np.arctan((depth_H / depth_W) * np.tan(hfov / 2.0)) self.intrinsic_matrix = np.array( [ [1 / np.tan(hfov / 2.0), 0.0, 0.0, 0.0], [0.0, 1 / np.tan(vfov / 2.0), 0.0, 0.0], [0.0, 0.0, 1, 0], [0.0, 0.0, 0, 1], ] ) self.inverse_intrinsic_matrix = np.linalg.inv(self.intrinsic_matrix) # Height thresholds for obstacles self.height_thresh = self.config.HEIGHT_THRESH # Depth processing self.min_depth = float(self._sim.habitat_config.DEPTH_SENSOR.MIN_DEPTH) self.max_depth = float(self._sim.habitat_config.DEPTH_SENSOR.MAX_DEPTH) # Pre-compute a grid of locations for depth projection W = self._sim.habitat_config.DEPTH_SENSOR.WIDTH H = self._sim.habitat_config.DEPTH_SENSOR.HEIGHT self.proj_xs, self.proj_ys = np.meshgrid( np.linspace(-1, 1, W), np.linspace(1, -1, H) ) def _get_uuid(self, *args: Any, **kwargs: Any): return "ego_wall_map_gt" def _get_sensor_type(self, *args: Any, **kwargs: Any): return SensorTypes.COLOR def _get_observation_space(self, *args: Any, **kwargs: Any): sensor_shape = (self.config.MAP_SIZE, self.config.MAP_SIZE, 2) return spaces.Box(low=0, high=1, shape=sensor_shape, dtype=np.uint8,) def convert_to_pointcloud(self, depth): """ Inputs: depth = (H, W, 1) numpy array Returns: xyz_camera = (N, 3) numpy array for (X, Y, Z) in egocentric world coordinates """ depth_float = depth.astype(np.float32)[..., 0] # =========== Convert to camera coordinates ============ W = depth.shape[1] xs = np.copy(self.proj_xs).reshape(-1) ys = np.copy(self.proj_ys).reshape(-1) depth_float = depth_float.reshape(-1) # Filter out invalid depths valid_depths = (depth_float != 0.0) & (depth_float <= self.max_forward_range) xs = xs[valid_depths] ys = ys[valid_depths] depth_float = depth_float[valid_depths] # Unproject # negate depth as the camera looks along -Z xys = np.vstack( ( xs * depth_float, ys * depth_float, -depth_float, np.ones(depth_float.shape), ) ) inv_K = self.inverse_intrinsic_matrix xyz_camera = np.matmul(inv_K, xys).T # XYZ in the camera coordinate system xyz_camera = xyz_camera[:, :3] / xyz_camera[:, 3][:, np.newaxis] return xyz_camera def safe_assign(self, im_map, x_idx, y_idx, value): try: im_map[x_idx, y_idx] = value except IndexError: valid_idx1 = np.logical_and(x_idx >= 0, x_idx < im_map.shape[0]) valid_idx2 = np.logical_and(y_idx >= 0, y_idx < im_map.shape[1]) valid_idx = np.logical_and(valid_idx1, valid_idx2) im_map[x_idx[valid_idx], y_idx[valid_idx]] = value def _get_depth_projection(self, sim_depth): """ Project pixels visible in depth-map to ground-plane """ if self._sim.habitat_config.DEPTH_SENSOR.NORMALIZE_DEPTH: depth = sim_depth * (self.max_depth - self.min_depth) + self.min_depth else: depth = sim_depth XYZ_ego = self.convert_to_pointcloud(depth) # Adding agent's height to the pointcloud XYZ_ego[:, 1] += self.camera_height # Convert to grid coordinate system V = self.map_size Vby2 = V // 2 points = XYZ_ego grid_x = (points[:, 0] / self.map_scale) + Vby2 grid_y = (points[:, 2] / self.map_scale) + V # Filter out invalid points valid_idx = ( (grid_x >= 0) & (grid_x <= V - 1) & (grid_y >= 0) & (grid_y <= V - 1) ) points = points[valid_idx, :] grid_x = grid_x[valid_idx].astype(int) grid_y = grid_y[valid_idx].astype(int) # Create empty maps for the wall obstacle channel obstacle_mat = np.zeros((self.map_size, self.map_size), np.uint8) # Compute wall obstacle locations high_filter_idx = points[:, 1] < self.height_thresh[1] low_filter_idx = points[:, 1] > self.height_thresh[0] obstacle_idx = np.logical_and(low_filter_idx, high_filter_idx) self.safe_assign(obstacle_mat, grid_y[obstacle_idx], grid_x[obstacle_idx], 1) kernel = np.ones((3, 3), np.uint8) obstacle_mat = cv2.dilate(obstacle_mat, kernel, iterations=1) # Smoothen the maps kernel = np.ones((3, 3), np.uint8) obstacle_mat = cv2.morphologyEx(obstacle_mat, cv2.MORPH_CLOSE, kernel) return np.stack([obstacle_mat, obstacle_mat], axis=2) def get_observation(self, *args: Any, observations, episode, **kwargs: Any): sim_depth = asnumpy(observations["depth"]) ego_wall_map_gt = self._get_depth_projection(sim_depth) return ego_wall_map_gt @registry.register_sensor(name="GTEgoMapAnticipated") class GTEgoMapAnticipated(GTEgoMap): r"""Anticipates the top-down occupancy based on current depth-map grown using the ground-truth occupancy map. Args: sim: reference to the simulator for calculating task observations. config: contains the MAP_SCALE, MAP_SIZE, HEIGHT_THRESH fields to decide grid-size, extents of the projection, and the thresholds for determining obstacles and explored space. """ def __init__(self, sim: Simulator, config: Config, *args: Any, **kwargs: Any): self._sim = sim super().__init__(sim, config=config) self._num_samples = config.NUM_TOPDOWN_MAP_SAMPLE_POINTS self._coordinate_min = maps.COORDINATE_MIN self._coordinate_max = maps.COORDINATE_MAX resolution = (self._coordinate_max - self._coordinate_min) / self.map_scale self._map_resolution = (int(resolution), int(resolution)) self.current_episode_id = None if hasattr(config, "REGION_GROWING_ITERATIONS"): self._region_growing_iterations = config.REGION_GROWING_ITERATIONS else: self._region_growing_iterations = 2 if self.config.GT_TYPE == "wall_occupancy": maps_info_path = self.config.ALL_MAPS_INFO_PATH self._all_maps_info = json.load(open(maps_info_path, "r")) self.current_wall_episode_id = None self._scene_maps_info = None self._scene_maps = None def _get_uuid(self, *args: Any, **kwargs: Any): return "ego_map_gt_anticipated" def get_original_map(self): top_down_map = maps.get_topdown_map( self._sim, self._map_resolution, self._num_samples, False, ) return top_down_map def _get_wall_occupancy(self, episode, agent_state): episode_id = (episode.episode_id, episode.scene_id) # Load the episode specific maps only if the episode has changed if self.current_wall_episode_id != episode_id: self.current_wall_episode_id = episode_id if self.config.GT_TYPE == "wall_occupancy": scene_id = episode.scene_id.split("/")[-1] self._scene_maps_info = self._all_maps_info[scene_id] # Load the maps per floor seen_maps, wall_maps = self._load_transformed_wall_maps( self._scene_maps_info, episode, ) self._scene_maps = {} self._scene_maps["seen_maps"] = seen_maps self._scene_maps["wall_maps"] = wall_maps agent_state = self._sim.get_agent_state() current_height = agent_state.position[1] best_floor_idx = None best_floor_dist = math.inf for floor_idx, floor_data in enumerate(self._scene_maps_info): floor_height = floor_data["floor_height"] if abs(current_height - floor_height) < best_floor_dist: best_floor_idx = floor_idx best_floor_dist = abs(current_height - floor_height) assert best_floor_idx is not None current_wall_map = self._scene_maps["wall_maps"][best_floor_idx] # Take only channel 0 as both channels have save values current_wall_map = current_wall_map[..., 0] # ========= Get local egocentric crop of the current wall map ========= # Compute relative pose of agent from start location start_position = episode.start_position # (X, Y, Z) start_rotation = quaternion_xyzw_to_wxyz(episode.start_rotation) start_heading = compute_heading_from_quaternion(start_rotation) start_pose = torch.Tensor( [[-start_position[2], start_position[0], start_heading]] ) agent_position = agent_state.position agent_heading = compute_heading_from_quaternion(agent_state.rotation) agent_pose = torch.Tensor( [[-agent_position[2], agent_position[0], agent_heading]] ) rel_pose = subtract_pose(start_pose, agent_pose)[0] # (3,) # Compute agent position on the map image map_scale = self.config.MAP_SCALE H, W = current_wall_map.shape[:2] Hby2, Wby2 = (H + 1) // 2, (W + 1) // 2 agent_map_x = int(rel_pose[1].item() / map_scale + Wby2) agent_map_y = int(-rel_pose[0].item() / map_scale + Hby2) # Crop the region around the agent. mrange = int(1.5 * self.map_size) # Add extra padding if map range is coordinates go out of bounds y_start = agent_map_y - mrange y_end = agent_map_y + mrange x_start = agent_map_x - mrange x_end = agent_map_x + mrange x_l_pad, y_l_pad, x_r_pad, y_r_pad = 0, 0, 0, 0 H, W = current_wall_map.shape if x_start < 0: x_l_pad = int(-x_start) x_start += x_l_pad x_end += x_l_pad if x_end >= W: x_r_pad = int(x_end - W + 1) if y_start < 0: y_l_pad = int(-y_start) y_start += y_l_pad y_end += y_l_pad if y_end >= H: y_r_pad = int(y_end - H + 1) ego_map = np.pad(current_wall_map, ((y_l_pad, y_r_pad), (x_l_pad, x_r_pad))) ego_map = ego_map[y_start : (y_end + 1), x_start : (x_end + 1)] agent_heading = rel_pose[2].item() agent_heading = math.degrees(agent_heading) half_size = ego_map.shape[0] // 2 center = (half_size, half_size) M = cv2.getRotationMatrix2D(center, agent_heading, scale=1.0) ego_map = cv2.warpAffine( ego_map, M, (ego_map.shape[1], ego_map.shape[0]), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, borderValue=(1,), ) ego_map = ego_map.astype(np.float32) mrange = int(self.map_size) ego_map = ego_map[ (half_size - mrange) : (half_size + mrange), (half_size - mrange) : (half_size + mrange), ] # Get forward region infront of the agent half_size = ego_map.shape[0] // 2 quarter_size = ego_map.shape[0] // 4 center = (half_size, half_size) ego_map = ego_map[0:half_size, quarter_size : (quarter_size + half_size)] # Append explored status in the 2nd channel #ego_map = np.stack([ego_map, ego_map], axis=2) return ego_map[:,:,np.newaxis] def _load_transformed_wall_maps(self, scene_map_info, episode): seen_maps = [] wall_maps = [] start_position = episode.start_position # (X, Y, Z) start_rotation = quaternion_xyzw_to_wxyz(episode.start_rotation) start_heading = compute_heading_from_quaternion(start_rotation) for floor_data in scene_map_info: seen_map = np.load(floor_data["seen_map_path"]) wall_map = np.load(floor_data["wall_map_path"]) # ===== Transform the maps relative to the episode start pose ===== map_view_position = floor_data["world_position"] map_view_heading = floor_data["world_heading"] # Originally, Z is downward and X is rightward. # Convert it to X upward and Y rightward x_map, y_map = -map_view_position[2], map_view_position[0] if(type(map_view_heading) is list): map_rotation = quaternion_xyzw_to_wxyz(map_view_heading) theta_map = compute_heading_from_quaternion(map_rotation) else: theta_map=map_view_heading x_start, y_start = -start_position[2], start_position[0] theta_start = start_heading # Compute relative coordinates r_rel = math.sqrt((x_start - x_map) ** 2 + (y_start - y_map) ** 2) phi_rel = math.atan2(y_start - y_map, x_start - x_map) - theta_map x_rel = r_rel * math.cos(phi_rel) / self.config.MAP_SCALE y_rel = r_rel * math.sin(phi_rel) / self.config.MAP_SCALE theta_rel = theta_start - theta_map # Convert these to image coordinates with X being rightward and Y # being downward x_img_rel = y_rel y_img_rel = -x_rel theta_img_rel = theta_rel x_trans = torch.Tensor([[x_img_rel, y_img_rel, theta_img_rel]]) # Perform the transformations p_seen_map = rearrange(torch.Tensor(seen_map), "h w c -> () c h w") p_wall_map = rearrange(torch.Tensor(wall_map), "h w c -> () c h w") p_seen_map_trans = spatial_transform_map(p_seen_map, x_trans) p_wall_map_trans = spatial_transform_map(p_wall_map, x_trans) seen_map_trans = asnumpy(p_seen_map_trans) seen_map_trans = rearrange(seen_map_trans, "() c h w -> h w c") wall_map_trans = asnumpy(p_wall_map_trans) wall_map_trans = rearrange(wall_map_trans, "() c h w -> h w c") seen_maps.append(seen_map_trans) wall_maps.append(wall_map_trans) return seen_maps, wall_maps def _get_mesh_occupancy(self, episode, agent_state): episode_id = (episode.episode_id, episode.scene_id) # Load the episode specific maps only if the episode has changed if self.current_wall_episode_id != episode_id: self.current_wall_episode_id = episode_id if self.config.GT_TYPE == "wall_occupancy": scene_id = episode.scene_id.split("/")[-1] self._scene_maps_info = self._all_maps_info[scene_id] # Load the maps per floor seen_maps, wall_maps = self._load_transformed_wall_maps( self._scene_maps_info, episode, ) self._scene_maps = {} self._scene_maps["seen_maps"] = seen_maps self._scene_maps["wall_maps"] = wall_maps agent_state = self._sim.get_agent_state() current_height = agent_state.position[1] best_floor_idx = None best_floor_dist = math.inf for floor_idx, floor_data in enumerate(self._scene_maps_info): floor_height = floor_data["floor_height"] if abs(current_height - floor_height) < best_floor_dist: best_floor_idx = floor_idx best_floor_dist = abs(current_height - floor_height) assert best_floor_idx is not None current_wall_map = self._scene_maps["seen_maps"][best_floor_idx] # Take only channel 0 as both channels have save values current_wall_map = current_wall_map[..., 0] # ========= Get local egocentric crop of the current wall map ========= # Compute relative pose of agent from start location start_position = episode.start_position # (X, Y, Z) start_rotation = quaternion_xyzw_to_wxyz(episode.start_rotation) start_heading = compute_heading_from_quaternion(start_rotation) start_pose = torch.Tensor( [[-start_position[2], start_position[0], start_heading]] ) agent_position = agent_state.position agent_heading = compute_heading_from_quaternion(agent_state.rotation) agent_pose = torch.Tensor( [[-agent_position[2], agent_position[0], agent_heading]] ) rel_pose = subtract_pose(start_pose, agent_pose)[0] # (3,) # Compute agent position on the map image map_scale = self.config.MAP_SCALE H, W = current_wall_map.shape[:2] Hby2, Wby2 = (H + 1) // 2, (W + 1) // 2 agent_map_x = int(rel_pose[1].item() / map_scale + Wby2) agent_map_y = int(-rel_pose[0].item() / map_scale + Hby2) # Crop the region around the agent. mrange = int(1.5 * self.map_size) # Add extra padding if map range is coordinates go out of bounds y_start = agent_map_y - mrange y_end = agent_map_y + mrange x_start = agent_map_x - mrange x_end = agent_map_x + mrange x_l_pad, y_l_pad, x_r_pad, y_r_pad = 0, 0, 0, 0 H, W = current_wall_map.shape if x_start < 0: x_l_pad = int(-x_start) x_start += x_l_pad x_end += x_l_pad if x_end >= W: x_r_pad = int(x_end - W + 1) if y_start < 0: y_l_pad = int(-y_start) y_start += y_l_pad y_end += y_l_pad if y_end >= H: y_r_pad = int(y_end - H + 1) ego_map =
np.pad(current_wall_map, ((y_l_pad, y_r_pad), (x_l_pad, x_r_pad)))
numpy.pad
""" Takes an image cube (as a .fits) and measures the emission surface folling the approach outlined in Pinte et al. (2018) [1]. This needs to know the disk inclination and position angle of the source (along with any offsets in the source center relative to the image center). If you use the command line verion it will save the results as a Numpy .npz file as *.emission_height.npy. Alternatively you can import the function which which has slightly more functionality. Uses the `detect_peaks` code from <NAME> [2]. References: [1] - https://ui.adsabs.harvard.edu/abs/2018A%26A...609A..47P/abstract [2] - https://github.com/demotu/BMC """ import argparse import numpy as np from gofish import imagecube __all__ = ['get_emission_surface'] def get_emission_surface(path, inc, PA, dx0=0.0, dy0=0.0, chans=None, rmax=None, threshold=0.95, smooth=2, detect_peaks_kwargs=None, verbose=True, auto_correct=True): """ Returns the emission height of the provided image cube following Pinte et al. (2018). Args: path (str): Path to the fits cube. inc (float): Inclination of the disk in [deg]. PA (float): Position angle of the disk in [deg]. dx0 (Optional[float]): Offset in Right-Ascenion in [arcsec]. dy0 (Optional[float]): Offset in delincation in [arcsec]. chans (Optional[list]): A list of the first and last channel to use. rmax (Optional[float]) Maximum radius to consider in [arcsec]. threshold (Optional[float]): At a given radius, remove all pixels below ``threshold`` times the azimuthally averaged peak intensity value. smooth (Optional[int]): Size of top hat kernel to smooth each column prior to finding the peak. detect_peaks_kwargs (Optional[dict]): Kwargs for ``detect_peaks``. verbose (Opional[bool]): Print out messages. auto_correct (Optional[bool]): Will check to see if the disk is the correct orientation for the code (rotated such that the far edge of the disk is to the top). If ``auto_correct=True``, will include an additional rotation of 180 [deg] to correct this. Returns: list: A list of the midplane radius [arcsec], height [arcsec] and flux density [Jy/beam] at that location. """ # Import dependencies. from scipy.interpolate import interp1d # Load up the image cube. cube = imagecube(path, FOV=2.2*rmax) rmax = rmax if rmax is not None else cube.xaxis.max() # Determine the channels to fit. chans = [0, cube.data.shape[0]-1] if chans is None else chans if len(chans) != 2: raise ValueError("`chans` must be a length 2 list of channels.") if chans[1] >= cube.data.shape[0]: raise ValueError("`chans` extends beyond the number of channels.") chans[0], chans[1] = int(min(chans)), int(max(chans)) data = cube.data[chans[0]:chans[1]+1] if verbose: velo = [cube.velax[chans[0]] / 1e3, cube.velax[chans[1]] / 1e3] print("Using {:.2f} km/s to {:.2f} km/s,".format(min(velo), max(velo)) + ' and 0" to {:.2f}".'.format(rmax)) # Shift and rotate the data. if dx0 != 0.0 or dy0 != 0.0: if verbose: print("Centering data cube...") data = shift_center(data, dx0 / cube.dpix, dy0 / cube.dpix) if verbose: print("Rotating data cube...") data = rotate_image(data, PA) # Check to see if the disk is tilted correctly. Tb = np.max(data, axis=0) median_top = np.nanmedian(Tb[int(Tb.shape[0] / 2):]) median_bottom = np.nanmedian(Tb[:int(Tb.shape[0] / 2)]) if median_bottom > median_top: if verbose: print("WARNING: " + "The far side of the disk looks like it is to the south.") if auto_correct: if verbose: print("\t Rotating the disk by 180 degrees...\n" + "\t To ignore this step, use `auto_correct=False`.") data = data[:, ::-1, ::-1] # Make a (smoothed) radial profile of the peak values and clip values. if verbose: print("Removing low SNR pixels...") rbins, _ = cube.radial_sampling() rvals = cube.disk_coords(x0=0.0, y0=0.0, inc=inc, PA=0.0)[0] Tb = Tb.flatten() ridxs = np.digitize(rvals.flatten(), rbins) avgTb = [] for r in range(1, rbins.size): avgTb_tmp = Tb[ridxs == r] avgTb += [np.mean(avgTb_tmp[avgTb_tmp > 0.0])] kernel = np.ones(
np.ceil(cube.bmaj / cube.dpix)
numpy.ceil
import cv2,torch import numpy as np from PIL import Image import torchvision.transforms as T import torch.nn.functional as F import scipy.signal mse2psnr = lambda x : -10. * torch.log(x) / torch.log(torch.Tensor([10.])) def visualize_depth_numpy(depth, minmax=None, cmap=cv2.COLORMAP_JET): """ depth: (H, W) """ x = np.nan_to_num(depth) # change nan to 0 if minmax is None: mi = np.min(x[x>0]) # get minimum positive depth (ignore background) ma = np.max(x) else: mi,ma = minmax x = (x-mi)/(ma-mi+1e-8) # normalize to 0~1 x = (255*x).astype(np.uint8) x_ = cv2.applyColorMap(x, cmap) return x_, [mi,ma] def init_log(log, keys): for key in keys: log[key] = torch.tensor([0.0], dtype=float) return log def visualize_depth(depth, minmax=None, cmap=cv2.COLORMAP_JET): """ depth: (H, W) """ if type(depth) is not np.ndarray: depth = depth.cpu().numpy() x = np.nan_to_num(depth) # change nan to 0 if minmax is None: mi = np.min(x[x>0]) # get minimum positive depth (ignore background) ma = np.max(x) else: mi,ma = minmax x = (x-mi)/(ma-mi+1e-8) # normalize to 0~1 x = (255*x).astype(np.uint8) x_ = Image.fromarray(cv2.applyColorMap(x, cmap)) x_ = T.ToTensor()(x_) # (3, H, W) return x_, [mi,ma] def N_to_reso(n_voxels, bbox): xyz_min, xyz_max = bbox voxel_size = ((xyz_max - xyz_min).prod() / n_voxels).pow(1 / 3) return ((xyz_max - xyz_min) / voxel_size).long().tolist() def cal_n_samples(reso, step_ratio=0.5): return int(np.linalg.norm(reso)/step_ratio) __LPIPS__ = {} def init_lpips(net_name, device): assert net_name in ['alex', 'vgg'] import lpips print(f'init_lpips: lpips_{net_name}') return lpips.LPIPS(net=net_name, version='0.1').eval().to(device) def rgb_lpips(np_gt, np_im, net_name, device): if net_name not in __LPIPS__: __LPIPS__[net_name] = init_lpips(net_name, device) gt = torch.from_numpy(np_gt).permute([2, 0, 1]).contiguous().to(device) im = torch.from_numpy(np_im).permute([2, 0, 1]).contiguous().to(device) return __LPIPS__[net_name](gt, im, normalize=True).item() def findItem(items, target): for one in items: if one[:len(target)]==target: return one return None ''' Evaluation metrics (ssim, lpips) ''' def rgb_ssim(img0, img1, max_val, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03, return_map=False): # Modified from https://github.com/google/mipnerf/blob/16e73dfdb52044dcceb47cda5243a686391a6e0f/internal/math.py#L58 assert len(img0.shape) == 3 assert img0.shape[-1] == 3 assert img0.shape == img1.shape # Construct a 1D Gaussian blur filter. hw = filter_size // 2 shift = (2 * hw - filter_size + 1) / 2 f_i = ((np.arange(filter_size) - hw + shift) / filter_sigma)**2 filt = np.exp(-0.5 * f_i) filt /= np.sum(filt) # Blur in x and y (faster than the 2D convolution). def convolve2d(z, f): return scipy.signal.convolve2d(z, f, mode='valid') filt_fn = lambda z: np.stack([ convolve2d(convolve2d(z[...,i], filt[:, None]), filt[None, :]) for i in range(z.shape[-1])], -1) mu0 = filt_fn(img0) mu1 = filt_fn(img1) mu00 = mu0 * mu0 mu11 = mu1 * mu1 mu01 = mu0 * mu1 sigma00 = filt_fn(img0**2) - mu00 sigma11 = filt_fn(img1**2) - mu11 sigma01 = filt_fn(img0 * img1) - mu01 # Clip the variances and covariances to valid values. # Variance must be non-negative: sigma00 = np.maximum(0., sigma00) sigma11 = np.maximum(0., sigma11) sigma01 = np.sign(sigma01) * np.minimum( np.sqrt(sigma00 * sigma11), np.abs(sigma01)) c1 = (k1 * max_val)**2 c2 = (k2 * max_val)**2 numer = (2 * mu01 + c1) * (2 * sigma01 + c2) denom = (mu00 + mu11 + c1) * (sigma00 + sigma11 + c2) ssim_map = numer / denom ssim =
np.mean(ssim_map)
numpy.mean
import os import cv2 from skimage import io import tensorflow as tf import sys sys.path.append('../') import numpy as np import matplotlib.pyplot as plt import argparse import segmentation_models_v1 as sm from segmentation_models_v1 import Unet, Linknet, PSPNet, FPN, AtUnet from unet import unet as unet_std from helper_function import plot_history_flu, plot_set_prediction, generate_folder, plot_prediction_zx, plot_prediction_live from helper_function import precision, recall, f1_score, calculate_psnr, calculate_pearsonr from helper_function import plot_flu_prediction, plot_psnr_histogram sm.set_framework('tf.keras') import glob from natsort import natsorted import time def read_txt(txt_dir): lines = [] with open(txt_dir, 'r+') as f: lines = [line.strip() for line in f.readlines()] return lines parser = argparse.ArgumentParser() parser.add_argument("--model_file", type=str, default = 'live_models.txt') parser.add_argument("--index", type=int, default = 0) parser.add_argument("--gpu", type=str, default = '2') parser.add_argument("--ch_in", type=int, default = 3) args = parser.parse_args() print(args) os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu model_names, epoch_list = [], [] with open(args.model_file, 'r+') as f: lines = f.readlines() for i, line in enumerate(lines): model_names.append(line.strip().split(',')[0]) epoch_list.append(int(line.strip().split(',')[1])) index = args.index model_name = model_names[index] epoch = epoch_list[index] print(model_name) ## parse model name splits = model_name.split('-') dataset = 'neuron_wbx1' val_dim = 608 scale = 100 subset = 'train2' chi, cho = 3,3 fl_ch = 'fl2' for v in range(len(splits)): if splits[v] == 'net': net_arch = splits[v+1] elif splits[v] == 'bone': backbone = splits[v+1] elif splits[v] == 'scale': scale = float(splits[v+1]) elif splits[v] == 'act': act_fun = splits[v+1] elif splits[v] == 'scale': scale = int(splits[v+1]) elif splits[v] == 'set': dataset = splits[v+1] elif splits[v] == 'subset': subset = splits[v+1] elif splits[v] == 'chi': chi = int(splits[v+1]) elif splits[v] == 'cho': cho = int(splits[v+1]) elif splits[v] == 'chf': fl_ch = splits[v+1] model_folder = '/data/2d_models/{}/{}/'.format(dataset, model_name) chi = args.ch_in if args.ch_in == 1 else chi dataset = 'live-neuron_float' DATA_DIR = '/data/datasets/{}/data/'.format(dataset) if dataset == 'live-neuron_float': val_dim = 1760 # 1744 offset = 8 volume_fns = [fn for fn in os.listdir(DATA_DIR) if 'output' in fn] ## volum formulation def extract_vol(vol): vol_extr = [] for i in range(vol.shape[0]): if i == 0: vol_extr.append(vol[i,:,:,0]) vol_extr.append(vol[i,:,:,1]) elif i>0 and i< vol.shape[0]-1: vol_extr.append(vol[i,:,:,1]) else: vol_extr.append(vol[i,:,:,1]) vol_extr.append(vol[i,:,:,2]) return np.stack(vol_extr) ## metrics SMOOTH= 1e-6; seed = 0 def calculate_pearsonr(vol1, vol2): from scipy import stats import numpy as np SMOOTH_ = np.random.random(vol1.flatten().shape)*SMOOTH flat1 = vol1.flatten(); flat2 = vol2.flatten().flatten() flat1 = SMOOTH_ + flat1; flat2 = SMOOTH_ + flat2 score, _= stats.pearsonr(flat1, flat2) return score def calculate_psnr(vol1, vol2): print('value in map: max {}, min {}'.format(vol1.max(),vol2.min())) mse = np.mean((vol1-vol2)**2) psnr_score = 20*np.log10(255/np.sqrt(mse)) return psnr_score # classes for data loading and preprocessing class Dataset: """CamVid Dataset. Read images, apply augmentation and preprocessing transformations. Args: images_dir (str): path to images folder masks_dir (str): path to segmentation masks folder class_values (list): values of classes to extract from segmentation mask augmentation (albumentations.Compose): data transfromation pipeline (e.g. flip, scale, etc.) preprocessing (albumentations.Compose): data preprocessing (e.g. noralization, shape manipulation, etc.) """ def __init__( self, images_dir, masks_dir1, masks_dir2, fl_ch = None, scale = 1.0, channels = [3,3], nb_data=None, augmentation=None, preprocessing=None, ): #self.ids = os.listdir(images_dir) id_list = natsorted(os.listdir(images_dir)) if nb_data ==None: self.ids = id_list else: self.ids = id_list[:int(min(nb_data,len(id_list)))] self.images_fps = [os.path.join(images_dir, image_id) for image_id in self.ids] self.masks1_fps = [os.path.join(masks_dir1, image_id) for image_id in self.ids] self.masks2_fps = [os.path.join(masks_dir2, image_id) for image_id in self.ids] print('Load files: image {}, fl1: {}, fl2:{}'.format(len(self.images_fps),len(self.masks1_fps),len(self.masks2_fps))) self.scale = scale self.augmentation = augmentation self.preprocessing = preprocessing self.channels = channels self.fl_ch = fl_ch def __getitem__(self, i): # load image and fl1 or fl2 or both # image = io.imread(self.images_fps[i]) # if self.fl_ch == 'fl1': # mask = io.imread(self.masks1_fps[i]) # mask = mask/255.*self.scale # elif self.fl_ch == 'fl2': # mask = io.imread(self.masks2_fps[i]) # mask = mask/255.*self.scale # elif self.fl_ch == 'fl12': # mask1 = io.imread(self.masks1_fps[i]) # mask2 = io.imread(self.masks2_fps[i]) # mask = np.stack([mask1[:,:,1], mask2[:,:,1]], axis = -1) # mask = mask/255.*self.scale # load image and fl1 or fl2 or both image = np.load(self.images_fps[i]) * 255. if self.fl_ch == 'fl1': mask = np.load(self.masks1_fps[i]) mask = mask *self.scale elif self.fl_ch == 'fl2': mask = np.load(self.masks2_fps[i]) mask = mask *self.scale elif self.fl_ch == 'fl12': mask1 = np.load(self.masks1_fps[i]) mask2 = np.load(self.masks2_fps[i]) mask = np.stack([mask1[:,:,1], mask2[:,:,1]], axis = -1) mask = mask *self.scale # decide the input and output channels if self.channels[0] == 1: image[:,:,0], image[:,:,2] = image[:,:,1], image[:,:,1] elif self.channels[0] == 2: image[:,:,2] = image[:,:,1] if self.channels[1] == 1 and not (self.fl_ch=='fl12'): mask = mask[:,:,1:2] # apply augmentations if self.augmentation: sample = self.augmentation(image=image, mask=mask) image, mask = sample['image'], sample['mask'] # apply preprocessing if self.preprocessing: sample = self.preprocessing(image=image, mask=mask) image, mask = sample['image'], sample['mask'] return image, mask def __len__(self): return len(self.ids) class Dataloder(tf.keras.utils.Sequence): """Load data from dataset and form batches Args: dataset: instance of Dataset class for image loading and preprocessing. batch_size: Integet number of images in batch. shuffle: Boolean, if `True` shuffle image indexes each epoch. """ def __init__(self, dataset, batch_size=1, shuffle=False): self.dataset = dataset self.batch_size = batch_size self.shuffle = shuffle self.indexes = np.arange(len(dataset)) self.on_epoch_end() def __getitem__(self, i): # collect batch data start = i * self.batch_size stop = (i + 1) * self.batch_size data = [] for j in range(start, stop): data.append(self.dataset[j]) # transpose list of lists batch = [
np.stack(samples, axis=0)
numpy.stack
# coding: utf-8 # # Task description # In[ ]: # from IPython.display import IFrame # IFrame('project2.pdf', width=600, height=1200) # # Preparation # To use this notebook, make sure you have placed the following into a ```./data/``` subdirectory: # - Place all cloze task files for training and validation as in the polybox directory into ```./data/cloze/``` # - Download and place Stanford's GloVe 6B vector set [glove.6B](http://nlp.stanford.edu/data/glove.6B.zip) as in the polybox directory into ```./data/glove/``` # # Import statements # In[ ]: import tensorflow as tf import numpy as np import pandas as pd import time from collections import OrderedDict # # Config variables # In[ ]: N_SENT_IN_STORY = 5 ENCODER_DIM = 600 MAX_SEQ_LENGTH = 30 MAX_VOCAB_SIZE = 400000 EMBEDDING_DIM = 300 ENCODER_TYPE = 'GRU' OOV_TOKEN = '<unk>' CONTEXT_SIZE = 1 LEARNING_RATE = 0.001 CLIP_GRAD_NORM = 5.0 EPOCHS = 5 BATCH_SIZE = 100 DROPOUT_RATE = 0.25 SAVE_DIR = './checkpoints/' SUMMARIES_DIR = './summaries/' MAX_TO_KEEP = 1 DISPLAY_STEP = 100 VALIDATE_STEP = 20 SAVE_STEP = 5000 # # Functions # In[ ]: def get_word2vec(word2vec_file='./data/glove.6B/glove.6B.{}d.txt'.format(EMBEDDING_DIM)): word2vec = {} # with open(os.path.join(word2vec_file), encoding='utf8') as f: with open(word2vec_file, encoding='utf8') as f: for row in f: values = row.split() word = values[0] vec = np.asarray(values[1:], dtype='float32') word2vec[word] = vec return word2vec # In[ ]: def get_training_data(train_file='./data/cloze/train_stories.csv'): train = pd.read_csv(train_file) train.drop_duplicates(subset='storyid') # make sure we have no duplicates titles = np.expand_dims(train['storytitle'].values, axis=1) sentences_1 = np.expand_dims(train['sentence1'].values, axis=1) sentences_2 = np.expand_dims(train['sentence2'].values, axis=1) sentences_3 = np.expand_dims(train['sentence3'].values, axis=1) sentences_4 = np.expand_dims(train['sentence4'].values, axis=1) sentences_5 = np.expand_dims(train['sentence5'].values, axis=1) mains = np.column_stack((sentences_1, sentences_2, sentences_3, sentences_4)) stories = np.hstack((mains, sentences_5)) sentences = [s for story in stories for s in story] print('{} has {} stories with a total of {} sentences.'.format(train_file, len(stories), len(sentences))) return sentences # In[ ]: def get_val_data(val_file='./data/cloze/cloze_test_val__spring2016 - cloze_test_ALL_val.csv'): validation = pd.read_csv(val_file) sentences_4 = np.expand_dims(validation['InputSentence4'].values, axis=1) quiz_1 = np.expand_dims(validation['RandomFifthSentenceQuiz1'].values, axis=1) quiz_2 = np.expand_dims(validation['RandomFifthSentenceQuiz2'].values, axis=1) answers = np.expand_dims(validation['AnswerRightEnding'].values, axis=1) quizzes = np.hstack((sentences_4, quiz_1, quiz_2)) sentences = [s for quiz in quizzes for s in quiz] print('{} has {} quizzes with a total of {} sentences.'.format(val_file, len(quizzes), len(sentences))) return sentences, answers # In[ ]: def get_test_data(test_file='./data/cloze/cloze_test_test__spring2016 - cloze_test_ALL_test.csv'): test = pd.read_csv(test_file) sentences_4 = np.expand_dims(test['InputSentence4'].values, axis=1) quiz_1 = np.expand_dims(test['RandomFifthSentenceQuiz1'].values, axis=1) quiz_2 = np.expand_dims(test['RandomFifthSentenceQuiz2'].values, axis=1) answers = np.expand_dims(test['AnswerRightEnding'].values, axis=1) quizzes = np.hstack((sentences_4, quiz_1, quiz_2)) sentences = [s for quiz in quizzes for s in quiz] print('{} has {} quizzes with a total of {} sentences.'.format(test_file, len(quizzes), len(sentences))) return sentences, answers # In[ ]: # This is an ugly-but-necessary hack thx to the NLU test data being of a different format than all the other data files def get_NLU_test_data(test_file='./data/cloze/test_nlu18.csv'): test = pd.read_csv(test_file, header=None, encoding='latin-1') sentences_4 = np.expand_dims(test[3].values, axis=1) quiz_1 = np.expand_dims(test[4].values, axis=1) quiz_2 = np.expand_dims(test[5].values, axis=1) quizzes = np.hstack((sentences_4, quiz_1, quiz_2)) sentences = [s for quiz in quizzes for s in quiz] print('{} has {} quizzes with a total of {} sentences.'.format(test_file, len(quizzes), len(sentences))) return sentences # In[ ]: def text_to_word_sequence(text): filters = '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n' split = ' ' text = text.lower().translate({ord(c): split for c in filters}) seq = text.split(split) return [t for t in seq if t] # In[ ]: def generate_vocabs(texts): word_counts = OrderedDict() max_seq_len = 0 for text in texts: if isinstance(text, list): seq = text else: seq = text_to_word_sequence(text) if len(seq) > max_seq_len: max_seq_len = len(seq) for w in seq: if w in word_counts: word_counts[w] += 1 else: word_counts[w] = 1 word_counts = list(word_counts.items()) word_counts.sort(key = lambda x: x[1], reverse=True) sorted_vocab = [word_count[0] for word_count in word_counts] word2idx = dict(list(zip(sorted_vocab, list(range(1, len(sorted_vocab) + 1))))) i = word2idx.get(OOV_TOKEN) if i is None: word2idx[OOV_TOKEN] = len(word2idx) + 1 idx2word = {value : key for key, value in word2idx.items()} return word2idx, idx2word, max_seq_len # In[ ]: def tokenize_pad_mask(texts, seq_length): vectors, masks = [], [] for text in texts: if isinstance(text, list): seq = text else: seq = text_to_word_sequence(text) seq = seq[:seq_length] vector, mask = [], [] for w in seq: vector.append(word2idx.get(w, word2idx[OOV_TOKEN])) mask.append(1) while len(vector) < seq_length: vector.append(0) mask.append(0) vectors.append(vector) masks.append(mask) return np.array(vectors, dtype='int64'), np.array(masks, dtype='int8') # In[ ]: def get_inputs(): encoder_inputs = tf.placeholder(tf.int64, [None, None], name='encoder_inputs') encoder_input_masks = tf.placeholder(tf.int8, [None, None], name='input_masks') encoder_targets = tf.placeholder(tf.float32, [None, None], name='encoder_targets') label_weights = tf.placeholder(tf.float32, [None,], name='label_weights') dropout_rate = tf.placeholder(tf.float32, [], name='dropout_rate') return encoder_inputs, encoder_input_masks, encoder_targets, label_weights, dropout_rate # In[ ]: def get_embedding_matrix(num_words): embedding_matrix = np.zeros((num_words, EMBEDDING_DIM)) for word, idx in word2idx.items(): if idx < num_words: embedding_vector = word2vec.get(word) if embedding_vector is not None: embedding_matrix[idx] = embedding_vector return embedding_matrix # In[ ]: def get_embeddings(encode_ids, trainable=False): word_embeddings = [] encode_emb = [] for suffix in ['_f', '_g']: word_emb = tf.get_variable(name='word_embedding'+suffix, shape=embedding_matrix.shape, trainable=trainable) word_emb.assign(embedding_matrix) word_embeddings.append(word_emb) encode_ = tf.nn.embedding_lookup(word_emb, encode_ids) encode_emb.append(encode_) return word_embeddings, encode_emb # In[ ]: def make_rnn_cells(num_units, cell_type): if cell_type == 'GRU': return tf.nn.rnn_cell.GRUCell(num_units=num_units) elif cell_type == 'LSTM': return tf.nn.rnn_cell.LSTMCell(num_units=num_units) else: raise ValueError('Invalid cell type given') # In[ ]: def rnn_encoder(embeds, mask, scope, num_units=600, cell_type='GRU'): sequence_length = tf.to_int32(tf.reduce_sum(mask, 1), name='length') cell_fw = make_rnn_cells(num_units, cell_type) cell_bw = make_rnn_cells(num_units, cell_type) outputs, states = tf.nn.bidirectional_dynamic_rnn(cell_fw=cell_fw, cell_bw=cell_bw, inputs=embeds, sequence_length=sequence_length, dtype=tf.float32, scope=scope) if cell_type == 'LSTM': states = [states[0][1], states[1][1]] state = tf.concat(states, 1) return state # In[ ]: def bow_encoder(embeds, mask): mask_expand = tf.expand_dims(tf.cast(mask, tf.float32), -1) embeds_masked = embeds * mask_expand return tf.reduce_sum(embeds_masked, axis=1) # In[ ]: def get_thought_vectors(encode_emb, encode_mask): suffixes = ['_f', '_g'] thought_vectors = [] for i in range(len(suffixes)): with tf.variable_scope('encoder' + suffixes[i]) as scope: if ENCODER_TYPE == 'GRU': encoded = rnn_encoder(encode_emb[i], encode_mask, scope, ENCODER_DIM, ENCODER_TYPE) elif ENCODER_TYPE == 'LSTM': encoded = rnn_encoder(encode_emb[i], encode_mask, scope, ENCODER_DIM, ENCODER_TYPE) elif ENCODER_TYPE == 'bow': encoded = bow_encoder(encode_emb[i], encode_mask) else: raise ValueError('Invalid encoder type given') thought_vector = tf.identity(encoded, name='thought_vector' + suffixes[i]) thought_vectors.append(thought_vector) return thought_vectors # In[ ]: def get_targets_weights(batch_size, is_cloze, n_sent_in_story, is_quiz=False, quiz_answer=None): if is_quiz: assert quiz_answer in [1, 2], 'must indicate correct quiz answer' targets = np.zeros((3, 3), dtype='float32') targets[0, quiz_answer] = 1 targets[quiz_answer, 0] = 1 weights = np.array([1,0]) else: context_idx = list(range(-CONTEXT_SIZE, CONTEXT_SIZE + 1)) context_idx.remove(0) weights = np.ones(batch_size - 1) if is_cloze: sub_targets = np.zeros((n_sent_in_story, n_sent_in_story), dtype='float32') for i in context_idx: sub_targets += np.eye(n_sent_in_story, k=i) targets = np.zeros((batch_size, batch_size), dtype='float32') weights = np.ones(batch_size - 1) for i in range(n_sent_in_story - 1, len(weights), n_sent_in_story): weights[i] = 0 for i in range(0, batch_size, n_sent_in_story): targets[i:i+n_sent_in_story, i:i+n_sent_in_story] += sub_targets else: targets = np.zeros((batch_size, batch_size), dtype='float32') for i in context_idx: targets += np.eye(batch_size, k=i) targets /= np.sum(targets, axis=1, keepdims=True) return targets, weights # In[ ]: def get_scores(thought_vectors, dropout_rate): def use_dropout(): a, b = thought_vectors[0], thought_vectors[1] dropout_mask_shape = tf.transpose(tf.shape(a)) dropout_mask = tf.random_uniform(dropout_mask_shape) > DROPOUT_RATE dropout_mask = tf.where(dropout_mask, tf.ones(dropout_mask_shape), tf.zeros(dropout_mask_shape)) dropout_mask *= (1/dropout_rate) a *= dropout_mask b *= dropout_mask return a, b def no_dropout(): return thought_vectors[0], thought_vectors[1] a, b = tf.cond(dropout_rate > 0, use_dropout, no_dropout) scores = tf.matmul(a, b, transpose_b=True) scores = tf.matrix_set_diag(scores, tf.zeros_like(scores[0])) return scores # In[ ]: def get_labels_predictions(scores, n_sent_in_story=N_SENT_IN_STORY, is_cloze=True): bwd_scores = scores[1: ] fwd_scores = scores[ :-1] bwd_predictions = tf.to_int64(tf.argmax(bwd_scores, axis=1)) fwd_predictions = tf.to_int64(tf.argmax(fwd_scores, axis=1)) bwd_labels = tf.range(tf.shape(bwd_scores)[0]) fwd_labels = bwd_labels + 1 return (bwd_labels, fwd_labels), (bwd_predictions, fwd_predictions)#, label_weights # In[ ]: def get_batch_acc(labels, predictions, label_weights): total_weight = tf.reduce_sum(label_weights) bwd_acc = tf.cast(tf.equal(tf.to_int64(labels[0]) , predictions[0]), tf.float32) bwd_acc *= label_weights bwd_acc = tf.reduce_sum(bwd_acc) bwd_acc /= total_weight fwd_acc = tf.cast(tf.equal(tf.to_int64(labels[1]), predictions[1]), tf.float32) fwd_acc *= label_weights fwd_acc = tf.reduce_sum(fwd_acc) fwd_acc /= total_weight return bwd_acc, fwd_acc # In[ ]: def get_batches(inputs, masks, batch_size, is_cloze=True, n_sent_in_story=5, is_quiz=False, quiz_answers=None, shuffle=True): if is_cloze: assert (batch_size % n_sent_in_story) == 0, 'batch_size must be multiple of n_sent_in_story for cloze task training.' rows, cols = inputs.shape if shuffle and is_cloze and not is_quiz: row_blocks = rows // n_sent_in_story shuffle_idx = np.random.permutation(row_blocks) inputs = inputs.reshape((row_blocks, -1, cols))[shuffle_idx].reshape((-1, cols)) masks = masks.reshape((row_blocks, -1, cols))[shuffle_idx].reshape((-1, cols)) n_batches = len(inputs) // batch_size for batch_i in range(n_batches): start_i = batch_i * batch_size batch_inputs = inputs[start_i : start_i + batch_size] batch_masks = masks[start_i : start_i + batch_size] if is_quiz: batch_targets, batch_weights = get_targets_weights(batch_size, is_cloze, n_sent_in_story, is_quiz, quiz_answers[batch_i]) else: batch_targets, batch_weights = get_targets_weights(batch_size, is_cloze, n_sent_in_story) yield batch_inputs, batch_masks, batch_targets, batch_weights # # Setup actions # In[ ]: print('Loading cloze story training data...') sentences = get_training_data() print('Loaded training stories.') # In[ ]: print('Loading cloze story validation data...') validation_sentences, validation_answers = get_val_data() print('Loaded validation stories.') # In[ ]: print('Loading cloze story test data...') test_sentences, test_answers = get_test_data() print('Loaded test stories.') # In[ ]: print('Loading NLU 2018 story test data...') NLU_test_sentences = get_NLU_test_data() print('Loaded NLU 2018 test stories.') # In[ ]: print('Generating vocabulary from training data ...') word2idx, idx2word, max_seq_len = generate_vocabs(sentences) print('Found {} unique word tokens\n Longest sentence has {} tokens.'.format(len(word2idx), max_seq_len)) # In[ ]: print('Loading pretrained word embedding vectors...') word2vec = get_word2vec() print('Loaded {} word vectors.'.format(len(word2vec))) # In[ ]: num_words = min(MAX_VOCAB_SIZE, len(word2idx) + 1) print('Constructing embedding matrix...') embedding_matrix = get_embedding_matrix(num_words) print('Finished embedding matrix has shape {}.'.format(embedding_matrix.shape)) # In[ ]: seq_length = min(max_seq_len, MAX_SEQ_LENGTH) print('Word2idx, pad and mask training sentences to length {} ...'.format(seq_length)) enc_sentences, enc_masks = tokenize_pad_mask(sentences, seq_length) print('{} training sentences processed.'.format(len(enc_sentences))) # In[ ]: print('Word2idx, pad and mask validation sentences to length {} ...'.format(seq_length)) validation_inputs, validation_masks = tokenize_pad_mask(validation_sentences, seq_length) print('{} validation sentences sentences processed.'.format(len(validation_inputs))) # In[ ]: print('Word2idx, pad and mask test sentences to length {} ...'.format(seq_length)) test_inputs, test_masks = tokenize_pad_mask(test_sentences, seq_length) print('{} test sentences sentences processed.'.format(len(test_inputs))) # In[ ]: print('Word2idx, pad and mask NLU 2018 test sentences to length {} ...'.format(seq_length)) NLU_test_inputs, NLU_test_masks = tokenize_pad_mask(NLU_test_sentences, seq_length) print('{} NLU 2018 test sentences sentences processed.'.format(len(NLU_test_inputs))) # # Build graph # In[ ]: print('Building graph...') tf.reset_default_graph() train_graph = tf.Graph() with train_graph.as_default(): with tf.name_scope('input_data'): encoder_inputs, encoder_input_masks, encoder_targets, label_weights, dropout_rate = get_inputs() with tf.name_scope('embeddings'): word_embeddings, encode_emb = get_embeddings(encoder_inputs, trainable=True) with tf.name_scope('encoders'): thoughts = get_thought_vectors(encode_emb, encoder_input_masks) with tf.name_scope('losses_accuracies'): scores = get_scores(thoughts, dropout_rate) labels, predictions = get_labels_predictions(scores) loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits_v2(labels=encoder_targets, logits=scores)) tf.summary.scalar('batch_ent_loss', loss) bwd_acc, fwd_acc = get_batch_acc(labels, predictions, label_weights) tf.summary.scalar('batch_bwd_accuracy', bwd_acc) tf.summary.scalar('batch_fwd_accuracy', fwd_acc) _, stream_bwd_acc = tf.metrics.accuracy(labels[0], predictions[0], weights=label_weights) _, stream_fwd_acc = tf.metrics.accuracy(labels[1], predictions[1], weights=label_weights) tf.summary.scalar('stream_bwd_accuracy', stream_bwd_acc) tf.summary.scalar('stream_fwd_accuracy', stream_fwd_acc) with tf.name_scope('optimization'): tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(loss, tvars), CLIP_GRAD_NORM) optimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE) train_op = optimizer.apply_gradients(zip(grads, tvars)) merged = tf.summary.merge_all() print('Graph assembled.') # # Run training # In[ ]: ### BEGIN TRAINING SECTION - comment out if you want to use the latest trained model in SAVE_DIR #print('Starting training...') #print('Run "tensorboard --logdir {}" in the current directory to keep you from doing other work in the meantime.'.format(SUMMARIES_DIR)) #start_time = time.strftime('%y-%m-%d-%H-%M-%S') #with tf.Session(graph=train_graph) as sess: # sess.run(tf.global_variables_initializer()) # sess.run(tf.local_variables_initializer()) # saver = tf.train.Saver(max_to_keep=MAX_TO_KEEP) # train_writer = tf.summary.FileWriter('{}run-{}/{}'.format(SUMMARIES_DIR, start_time, 'train'), sess.graph) # valid_writer = tf.summary.FileWriter('{}run-{}/{}'.format(SUMMARIES_DIR, start_time, 'valid'), sess.graph) # step = 0 # for e in range(EPOCHS): # valid_batch = get_batches(validation_inputs, validation_masks, batch_size=3, n_sent_in_story=3, # is_quiz=True, quiz_answers=answers, shuffle=False) # for batch_i, (batch_inputs, batch_masks, batch_targets, batch_weights) in enumerate(get_batches(enc_sentences, enc_masks, batch_size=BATCH_SIZE, n_sent_in_story=5, shuffle=True)): # # feed_dict = {encoder_inputs: batch_inputs, # encoder_input_masks: batch_masks, # encoder_targets: batch_targets, # label_weights: batch_weights, # dropout_rate: DROPOUT_RATE} # # _, batch_loss, bwd_accuracy, fwd_accuracy, summary = sess.run([train_op, # loss, # bwd_acc, # fwd_acc, # merged], # feed_dict=feed_dict) # train_writer.add_summary(summary, step) # # if batch_i % DISPLAY_STEP == 0 and batch_i > 0: # print('Epoch {:>3} Batch {:>4}/{} - Batch bwd acc: {:>3.2%}, Batch fwd acc: {:>3.2%}, Batch loss: {:>6.4f}' # .format(e, batch_i, len(enc_sentences) // BATCH_SIZE, bwd_accuracy, fwd_accuracy, batch_loss)) # # if batch_i % VALIDATE_STEP == 0 and batch_i > 0: # valid_input, valid_mask, valid_target, valid_weight = next(valid_batch) # feed_dict = {encoder_inputs: valid_input, # encoder_input_masks: valid_mask, # encoder_targets: valid_target, # label_weights: valid_weight, # dropout_rate: 0} # # valid_loss, stream_bwd_accuracy, stream_fwd_accuracy, summary = sess.run([loss, # stream_bwd_acc, # stream_fwd_acc, # merged], # feed_dict=feed_dict) # # valid_writer.add_summary(summary, step) # # if batch_i % SAVE_STEP == 0 and batch_i > 0: # saver.save(sess, '{}/run-{}_ep_{}_step_{}_enc_{}_bsize_{}.ckpt'.format( # SAVE_DIR, start_time, e, step, ENCODER_TYPE, BATCH_SIZE)) # # step += 1 # # saver.save(sess, '{}/run-{}_ep_{}_step_{}_enc_{}_bsize_{}.ckpt'.format( # SAVE_DIR, start_time, e, step, ENCODER_TYPE, BATCH_SIZE)) # train_writer.close() # valid_writer.close() #print('Training finished.') ### END OF TRAINING SECTION # # Get _cloze_ predictions # In[ ]: print('Checking for trained model at latest checkpoint...') checkpoint = tf.train.latest_checkpoint(SAVE_DIR) assert checkpoint is not None, 'No checkpoints found, check SAVE_DIR & README.txt' print('Found model {}.'.format(checkpoint)) # In[ ]: print('Checking validation score...') cloze_preds = [] with tf.Session(graph=train_graph) as sess: saver = tf.train.Saver() saver.restore(sess, checkpoint) for valid_i, (valid_input, valid_mask, valid_target, valid_weight) in enumerate(get_batches(validation_inputs, validation_masks, batch_size=3, n_sent_in_story=3, is_quiz=True, quiz_answers=validation_answers, shuffle=False)): scr = sess.run(scores, {encoder_inputs: valid_input, encoder_input_masks: valid_mask, encoder_targets: valid_target, label_weights: valid_weight, dropout_rate: 0}) cloze_pred = np.argmax(scr[0, 1:]) + 1 cloze_preds.append(cloze_pred) cloze_preds = np.array(cloze_preds).reshape((-1, 1)) cloze_score = np.mean((validation_answers == cloze_preds)) print('For checkpoint {}:'.format(checkpoint)) print('Validation score: {:>3.2%}'.format(cloze_score)) # In[ ]: # Only run at very end after training & when everything else is done print('Checking test score...') cloze_preds = [] with tf.Session(graph=train_graph) as sess: saver = tf.train.Saver() saver.restore(sess, checkpoint) for test_i, (test_input, test_mask, test_target, test_weight) in enumerate(get_batches(test_inputs, test_masks, batch_size=3, n_sent_in_story=3, is_quiz=True, quiz_answers=test_answers, shuffle=False)): scr = sess.run(scores, {encoder_inputs: test_input, encoder_input_masks: test_mask, encoder_targets: test_target, label_weights: test_weight, dropout_rate: 0}) cloze_pred = np.argmax(scr[0, 1:]) + 1 cloze_preds.append(cloze_pred) cloze_preds = np.array(cloze_preds).reshape((-1, 1)) cloze_score = np.mean((test_answers == cloze_preds)) print('For checkpoint {}:'.format(checkpoint)) print('Test score: {:>3.2%}'.format(cloze_score)) # In[ ]: # Only run at very end after training & when everything else is done print('Generating NLU 2018 test predictions...') cloze_preds = [] with tf.Session(graph=train_graph) as sess: saver = tf.train.Saver() saver.restore(sess, checkpoint) for test_i, (test_input, test_mask, test_target, test_weight) in enumerate(get_batches(NLU_test_inputs, NLU_test_masks, batch_size=3, n_sent_in_story=3, is_quiz=True, quiz_answers=np.ones((len(NLU_test_inputs), 1), dtype='int8'), shuffle=False)): scr = sess.run(scores, {encoder_inputs: test_input, encoder_input_masks: test_mask, encoder_targets: test_target, label_weights: test_weight, dropout_rate: 0}) cloze_pred =
np.argmax(scr[0, 1:])
numpy.argmax
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data # (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP # (c) 07/2019-present : DESY PHOTON SCIENCE # authors: # <NAME>, <EMAIL> import collections import numpy as np from matplotlib import pyplot as plt from scipy.ndimage.measurements import center_of_mass import pathlib import vtk from vtk.util import numpy_support import os import tkinter as tk from tkinter import filedialog from skimage import measure import logging import sys import gc import bcdi.graph.graph_utils as gu import bcdi.facet_recognition.facet_utils as fu import bcdi.simulation.simulation_utils as simu import bcdi.postprocessing.postprocessing_utils as pu helptext = """ Script for detecting facets on a 3D crytal reconstructed by a phasing algorithm (Bragg CDI) and making some statistics about strain by facet. The correct threshold for support determination should be given as input, as well as voxel sizes for a correct calculation of facet angle. Input: a reconstruction .npz file with fields: 'amp' and 'strain' Output: a log file with strain statistics by plane, a VTK file for 3D visualization of detected planes. """ scan = 1585 # spec scan number datadir = "C:/Users/carnisj/Documents/data/david/S" + str(scan) + "/" support_threshold = 0.35 # threshold for support determination voxel_size = [ 11.4, 10.4, 11.3, ] # tuple of 3 numbers, voxel size of the real-space reconstruction in each dimension upsampling_factor = 2 # integer, factor for upsampling the reconstruction # in order to have a smoother surface savedir = datadir reflection = np.array([1, 1, 1]) # measured crystallographic reflection projection_axis = 1 # the projection will be performed on the equatorial plane # perpendicular to that axis (0, 1 or 2) debug = False # set to True to see all plots for debugging smoothing_iterations = 5 # number of iterations in Taubin smoothing, # bugs if smoothing_iterations larger than 10 smooth_lamda = 0.33 # lambda parameter in Taubin smoothing smooth_mu = 0.34 # mu parameter in Taubin smoothing radius_normals = ( 0.1 # radius of integration for the calculation of the density of normals ) projection_method = "stereographic" # 'stereographic' or 'equirectangular' peak_min_distance = 10 # pixel separation between peaks in corner_peaks() max_distance_plane = ( 0.75 # in pixels, maximum allowed distance to the facet plane of a voxel ) edges_coord = ( 360 # coordination threshold for isolating edges, 360 seems to work reasonably well ) corners_coord = 310 # coordination threshold for isolating corners, # 310 seems to work reasonably well ######################################################## # parameters only used in the stereographic projection # ######################################################## threshold_south = -2500 # background threshold in the stereographic projection # from South of the density of normals threshold_north = ( -500 ) # background threshold in the stereographic projection from North # of the density of normals max_angle = 95 # maximum angle in degree of the stereographic projection # (should be larger than 90) stereo_scale = ( "linear" # 'linear' or 'log', scale of the colorbar in the stereographic plot ) ########################################################## # parameters only used in the equirectangular projection # ########################################################## bw_method = 0.03 # bandwidth in the gaussian kernel density estimation kde_threshold = ( -0.2 ) # threshold for defining the background in the density estimation of normals ################################################## # define crystallographic planes of interest for # # the stereographic projection (cubic lattice) # ################################################## planes_south = {} # create dictionnary for the projection from the South pole, # the reference is +reflection # planes_south['0 2 0'] = # simu.angle_vectors(ref_vector=reflection, test_vector=np.array([0, 2, 0])) planes_south["1 1 1"] = simu.angle_vectors( ref_vector=reflection, test_vector=np.array([1, 1, 1]) ) planes_south["1 0 0"] = simu.angle_vectors( ref_vector=reflection, test_vector=np.array([1, 0, 0]) ) planes_south["1 1 0"] = simu.angle_vectors( ref_vector=reflection, test_vector=np.array([1, 1, 0]) ) planes_south["-1 1 0"] = simu.angle_vectors( ref_vector=reflection, test_vector=np.array([-1, 1, 0]) ) planes_south["1 -1 1"] = simu.angle_vectors( ref_vector=reflection, test_vector=np.array([1, -1, 1]) ) # planes_south['-1 -1 1'] = # simu.angle_vectors(ref_vector=reflection, test_vector=np.array([-1, -1, 1])) # planes_south['2 1 0'] = # simu.angle_vectors(ref_vector=reflection, test_vector=np.array([2, 1, 0])) # planes_south['2 -1 0'] = # simu.angle_vectors(ref_vector=reflection, test_vector=np.array([2, -1, 0])) # planes_south['1 2 0'] = # simu.angle_vectors(ref_vector=reflection, test_vector=np.array([1, 2, 0])) planes_north = {} # create dictionnary for the projection from the North pole, # the reference is -reflection # planes_north['0 -2 0'] = # simu.angle_vectors(ref_vector=-reflection, test_vector=np.array([0, -2, 0])) planes_north["-1 -1 -1"] = simu.angle_vectors( ref_vector=-reflection, test_vector=np.array([-1, -1, -1]) ) planes_north["-1 0 0"] = simu.angle_vectors( ref_vector=-reflection, test_vector=np.array([-1, 0, 0]) ) planes_north["-1 -1 0"] = simu.angle_vectors( ref_vector=-reflection, test_vector=np.array([-1, -1, 0]) ) planes_north["-1 1 0"] = simu.angle_vectors( ref_vector=-reflection, test_vector=np.array([-1, 1, 0]) ) planes_north["-1 -1 1"] = simu.angle_vectors( ref_vector=-reflection, test_vector=np.array([-1, -1, 1]) ) # planes_north['-1 1 1'] = # simu.angle_vectors(ref_vector=-reflection, test_vector=np.array([-1, 1, 1])) planes_north["-2 1 0"] = simu.angle_vectors( ref_vector=-reflection, test_vector=np.array([-2, 1, 0]) ) planes_north["-2 -1 0"] = simu.angle_vectors( ref_vector=-reflection, test_vector=np.array([-2, -1, 0]) ) # planes_north['1 -2 0'] = # simu.angle_vectors(ref_vector=-reflection, test_vector=np.array([1, -2, 0])) ########################## # end of user parameters # ########################## ########################################################### # create directory and initialize error logger # ########################################################### pathlib.Path(savedir).mkdir(parents=True, exist_ok=True) logger = logging.getLogger() ################### # define colormap # ################### colormap = gu.Colormap() my_cmap = colormap.cmap ############# # load data # ############# plt.ion() root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename(initialdir=datadir, filetypes=[("NPZ", "*.npz")]) npzfile = np.load(file_path) amp = npzfile["amp"] amp = amp / amp.max() nz, ny, nx = amp.shape print("Initial data size: (", nz, ",", ny, ",", nx, ")") strain = npzfile["strain"] ################# # upsample data # ################# if upsampling_factor > 1: amp, _ = fu.upsample( array=amp, upsampling_factor=upsampling_factor, voxelsizes=voxel_size, title="modulus", debugging=debug, ) strain, voxel_size = fu.upsample( array=strain, upsampling_factor=upsampling_factor, voxelsizes=voxel_size, title="strain", debugging=debug, ) nz, ny, nx = amp.shape print("Upsampled data size: (", nz, ",", ny, ",", nx, ")") print("New voxel sizes: ", voxel_size) ##################################################################### # Use marching cubes to obtain the surface mesh of these ellipsoids # ##################################################################### vertices_old, faces, _, _ = measure.marching_cubes_lewiner( amp, level=support_threshold, allow_degenerate=False, step_size=1 ) # vertices_old is a list of 3d coordinates of all vertices points # faces is a list of facets defined by the indices of 3 vertices_old # from scipy.io import savemat # savemat('//win.desy.de/home/carnisj/My Documents/MATLAB/TAUBIN/vertices.mat', # {'V': vertices_old}) # savemat('//win.desy.de/home/carnisj/My Documents/MATLAB/TAUBIN/faces.mat', # {'F': faces}) # Display mesh before smoothing if debug: gu.plot_3dmesh(vertices_old, faces, (nz, ny, nx), title="Mesh after marching cubes") plt.ion() ####################################### # smooth the mesh using taubin_smooth # ####################################### vertices_new, normals, _, intensity, faces, _ = fu.taubin_smooth( faces, vertices_old, iterations=smoothing_iterations, lamda=smooth_lamda, mu=smooth_mu, radius=radius_normals, debugging=debug, ) del vertices_old gc.collect() nb_vertices = vertices_new.shape[0] # Display smoothed triangular mesh if debug: gu.plot_3dmesh( vertices_new, faces, (nz, ny, nx), title="Mesh after Taubin smoothing" ) plt.ion() ##################################################################### # 2D projection of normals, peak finding and watershed segmentation # ##################################################################### nb_normals = normals.shape[0] if projection_method == "stereographic": labels_top, labels_bottom, stereo_proj, remove_row = fu.stereographic_proj( normals=normals, intensity=intensity, background_south=threshold_south, background_north=threshold_north, min_distance=peak_min_distance, savedir=savedir, save_txt=False, plot_planes=True, planes_south=planes_south, planes_north=planes_north, max_angle=max_angle, voxel_size=voxel_size, projection_axis=projection_axis, scale=stereo_scale, debugging=debug, ) # labels_south and labels_north are 2D arrays for projections from South and North # stereo_proj is a (Nx4) array containint the projected coordinates of normals # from South (u column 0, v column 1) and North (u column2 , v column 3). The # coordinates are in degrees, not indices. # remove rows containing nan values normals = np.delete(normals, remove_row, axis=0) faces = np.delete(faces, remove_row, axis=0) nb_normals = normals.shape[0] numy, numx = labels_top.shape # identical to labels_bottom.shape max_label = max(labels_top.max(), labels_bottom.max()) if stereo_proj.shape[0] != nb_normals: print(projection_method, "projection output: incompatible number of normals") sys.exit() # look for potentially duplicated labels (labels crossing the 90 degree circle) duplicated_labels = [ 0 ] # do not consider background points when looking for duplicates # (label 0 is the background) # duplicated_labels stores bottom_labels which are duplicate from top_labels # [0 duplicated_labels unique_label ...] for label in range(1, labels_top.max() + 1, 1): label_points = np.argwhere(labels_top == label) # rescale label_points to angles instead of indices, # the angular range is [-max_angle max_angle] label_points[:, 0] = (label_points[:, 0] * 2 * max_angle / numy) - max_angle label_points[:, 1] = (label_points[:, 1] * 2 * max_angle / numx) - max_angle label_distances = np.sqrt( label_points[:, 0] ** 2 + label_points[:, 1] ** 2 ) # distance in angle from the origin if (label_distances <= 90).sum() == label_points.shape[ 0 ]: # all points inside the 90deg border continue # do nothing, the facet is valid if (label_distances > 90).sum() == label_points.shape[ 0 ]: # all points outside the 90deg border continue # do nothing, the facet will be filtered out # in next section by distance check print("Label ", str(label), "is potentially duplicated") # look for the corresponding label in the bottom projection for idx in range(nb_normals): # calculate the corresponding index coordinates # by rescaling from [-max_angle max_angle] to [0 numy] or [0 numx] u_top = int( np.rint((stereo_proj[idx, 0] + max_angle) * numx / (2 * max_angle)) ) # u axis horizontal v_top = int( np.rint((stereo_proj[idx, 1] + max_angle) * numy / (2 * max_angle)) ) # v axis vertical u_bottom = int( np.rint((stereo_proj[idx, 2] + max_angle) * numx / (2 * max_angle)) ) # u axis horizontal v_bottom = int( np.rint((stereo_proj[idx, 3] + max_angle) * numy / (2 * max_angle)) ) # v axis vertical try: if ( labels_top[v_top, u_top] == label and labels_bottom[v_bottom, u_bottom] not in duplicated_labels ): # only the first duplicated point will be checked, # then the whole bottom_label is changed # to label and there is no need to check anymore duplicated_labels.append(labels_bottom[v_bottom, u_bottom]) duplicated_labels.append(label) print( " Corresponding label :", labels_bottom[v_bottom, u_bottom], "changed to", label, ) labels_bottom[ labels_bottom == labels_bottom[v_bottom, u_bottom] ] = label except IndexError: # the IndexError exception arises because we are spanning all normals # for labels_top, even those whose stereographic projection is # farther than max_angle. continue del label_points, label_distances gc.collect() # reorganize stereo_proj to keep only the projected point # which is in the angular range [-90 90] # stereo_proj coordinates are in polar degrees, we want coordinates to be in indices coordinates = np.zeros((nb_normals, 3), dtype=stereo_proj.dtype) # 1st and 2nd columns are coordinates # the 3rd column is a flag for using the South (0) # or North (1) projected coordinates for idx in range(nb_normals): if np.sqrt(stereo_proj[idx, 0] ** 2 + stereo_proj[idx, 1] ** 2) > 90: coordinates[idx, 0] = stereo_proj[ idx, 3 ] # use v values for the projection from North pole coordinates[idx, 1] = stereo_proj[ idx, 2 ] # use u values for the projection from North pole coordinates[ idx, 2 ] = 1 # use values from labels_bottom (projection from North pole) else: coordinates[idx, 0] = stereo_proj[ idx, 1 ] # use v values for the projection from South pole coordinates[idx, 1] = stereo_proj[ idx, 0 ] # use u values for the projection from South pole coordinates[ idx, 2 ] = 0 # use values from labels_top (projection from South pole) del stereo_proj gc.collect() # rescale euclidian v axis from [-max_angle max_angle] to [0 numy] coordinates[:, 0] = (coordinates[:, 0] + max_angle) * numy / (2 * max_angle) # rescale euclidian u axis from [-max_angle max_angle] to [0 numx] coordinates[:, 1] = (coordinates[:, 1] + max_angle) * numx / (2 * max_angle) # change coordinates to an array of integer indices coordinates = coordinates.astype(int) ########################################################## # now that we have the labels and coordinates in indices # # we can assign back labels to normals and vertices # ########################################################## normals_label = np.zeros(nb_normals, dtype=int) vertices_label = np.zeros( nb_vertices, dtype=int ) # the number of vertices is: vertices_new.shape[0] for idx in range(nb_normals): # check to which label belongs this normal if ( coordinates[idx, 2] == 0 ): # use values from labels_top (projection from South pole) label_idx = labels_top[coordinates[idx, 0], coordinates[idx, 1]] elif ( coordinates[idx, 2] == 1 ): # use values from labels_bottom (projection from North pole) label_idx = labels_bottom[coordinates[idx, 0], coordinates[idx, 1]] else: label_idx = 0 # duplicated facet, set it to the background normals_label[idx] = label_idx # attribute the label to the normal vertices_label[ faces[idx, :] ] = label_idx # attribute the label to the corresponding vertices del labels_top, labels_bottom elif projection_method == "equirectangular": labels, longitude_latitude = fu.equirectangular_proj( normals=normals, intensity=intensity, bw_method=bw_method, background_threshold=kde_threshold, min_distance=peak_min_distance, debugging=debug, ) if longitude_latitude.shape[0] != nb_normals: print(projection_method, "projection output: incompatible number of normals") sys.exit() numy, numx = labels.shape # rescale the horizontal axis from [-pi pi] to [0 numx] longitude_latitude[:, 0] = ( (longitude_latitude[:, 0] + np.pi) * numx / (2 * np.pi) ) # longitude # rescale the vertical axis from [-pi/2 pi/2] to [0 numy] longitude_latitude[:, 1] = ( (longitude_latitude[:, 1] + np.pi / 2) * numy / np.pi ) # latitude # change longitude_latitude to an array of integer indices coordinates = np.rint(np.fliplr(longitude_latitude)).astype( int ) # put the vertical axis in first position duplicated_labels = [] max_label = labels.max() del longitude_latitude gc.collect() ############################################## # assign back labels to normals and vertices # ############################################## normals_label = np.zeros(nb_normals, dtype=int) vertices_label = np.zeros( nb_vertices, dtype=int ) # the number of vertices is: vertices_new.shape[0] for idx in range(nb_normals): label_idx = labels[coordinates[idx, 0], coordinates[idx, 1]] normals_label[idx] = label_idx # attribute the label to the normal vertices_label[ faces[idx, :] ] = label_idx # attribute the label to the corresponding vertices else: print("Invalid value for projection_method") sys.exit() unique_labels = [ label for label in np.arange(1, max_label + 1) if label not in duplicated_labels[1::2] ] # label 0 is the background if len(duplicated_labels[1::2]) == 0: print("\nNo duplicated label") print("\nBackground: ", str((normals_label == 0).sum()), "normals") for label in unique_labels: print( "Facet", str(label), ": ", str((normals_label == label).sum()), "normals detected", ) del normals, normals_label, coordinates, faces, duplicated_labels, intensity gc.collect() ############################################### # assign back labels to voxels using vertices # ############################################### all_planes = np.zeros((nz, ny, nx), dtype=int) planes_counter = np.zeros( (nz, ny, nx), dtype=int ) # check if a voxel is used several times duplicated_counter = 0 for idx in range(nb_vertices): temp_indices = np.rint(vertices_new[idx, :]).astype(int) planes_counter[temp_indices[0], temp_indices[1], temp_indices[2]] = ( planes_counter[temp_indices[0], temp_indices[1], temp_indices[2]] + 1 ) # check duplicated voxels and discard them if they belong to different planes # it happens when some vertices are close and they give # the same voxel after rounding their position to integers # one side effect is that the border of areas obtained by # watershed segmentation will be set to the background if ( planes_counter[temp_indices[0], temp_indices[1], temp_indices[2]] > 1 ): # a rounded voxel was already added if ( all_planes[temp_indices[0], temp_indices[1], temp_indices[2]] != vertices_label[idx] ): # belongs to different labels, therefore it is set as background (label 0) all_planes[temp_indices[0], temp_indices[1], temp_indices[2]] = 0 duplicated_counter = duplicated_counter + 1 else: # non duplicated pixel all_planes[temp_indices[0], temp_indices[1], temp_indices[2]] = vertices_label[ idx ] print("\nRounded vertices belonging to multiple labels = ", duplicated_counter, "\n") del planes_counter, vertices_label, vertices_new gc.collect() for label in unique_labels: print( "Facet", str(label), ": ", str((all_planes == label).sum()), "voxels detected" ) ############################################ # define the support, surface layer & bulk # ############################################ support = np.zeros(amp.shape) support[abs(amp) > support_threshold * abs(amp).max()] = 1 zcom_support, ycom_support, xcom_support = center_of_mass(support) print( "\nCOM at (z, y, x): (", str("{:.2f}".format(zcom_support)), ",", str("{:.2f}".format(ycom_support)), ",", str("{:.2f}".format(xcom_support)), ")", ) coordination_matrix = pu.calc_coordination( support, kernel=np.ones((3, 3, 3)), debugging=False ) surface = np.copy(support) surface[coordination_matrix > 22] = 0 # remove the bulk 22 del coordination_matrix gc.collect() ######################################################## # define edges using the coordination number of voxels # ######################################################## edges = pu.calc_coordination(support, kernel=np.ones((9, 9, 9)), debugging=False) edges[support == 0] = 0 if debug: gu.multislices_plot(edges, vmin=0, title="Coordination matrix") edges[edges > edges_coord] = 0 # remove facets and bulk edges[np.nonzero(edges)] = 1 # edge support gu.scatter_plot( array=np.asarray(np.nonzero(edges)).T, markersize=2, markercolor="b", labels=("axis 0", "axis 1", "axis 2"), title="edges", ) ######################################################## # define corners using the coordination number of voxels # ######################################################## corners = pu.calc_coordination(support, kernel=np.ones((9, 9, 9)), debugging=False) corners[support == 0] = 0 if debug: gu.multislices_plot(corners, vmin=0, title="Coordination matrix") corners[corners > corners_coord] = 0 # remove edges, facets and bulk corners[np.nonzero(corners)] = 1 # corner support gu.scatter_plot( array=np.asarray(np.nonzero(corners)).T, markersize=2, markercolor="b", labels=("axis 0", "axis 1", "axis 2"), title="corners", ) ###################################### # Initialize log files and .vti file # ###################################### summary_file = open( os.path.join( savedir, "S" + str(scan) + "_planes_iso" + str(support_threshold) + ".dat" ), "w", ) summary_file.write( "{0: <10}".format("Plane #") + "\t" + "{0: <10}".format("angle") + "\t" + "{0: <10}".format("points #") + "\t" + "{0: <10}".format("<strain>") + "\t" + "{0: <10}".format("std dev") + "\t" + "{0: <10}".format("A (x)") + "\t" + "{0: <10}".format("B (y)") + "\t" + "{0: <10}".format("C (z)") + "\t" + "D (Ax+By+CZ+D=0)" + "\t" "normal X" + "\t" + "normal Y" + "\t" + "normal Z" + "\n" ) allpoints_file = open( os.path.join( savedir, "S" + str(scan) + "_strain_iso" + str(support_threshold) + ".dat" ), "w", ) allpoints_file.write( "{0: <10}".format("Plane #") + "\t" + "{0: <10}".format("angle") + "\t" + "{0: <10}".format("strain") + "\t" + "{0: <10}".format("Z") + "\t" + "{0: <10}".format("Y") + "\t" + "{0: <10}".format("X") + "\n" ) # prepare amp for vti file amp_array = np.transpose(np.flip(amp, 2)).reshape(amp.size) # VTK axis 2 is flipped amp_array = numpy_support.numpy_to_vtk(amp_array) image_data = vtk.vtkImageData() image_data.SetOrigin(0, 0, 0) image_data.SetSpacing(voxel_size[0], voxel_size[1], voxel_size[2]) image_data.SetExtent(0, nz - 1, 0, ny - 1, 0, nx - 1) pd = image_data.GetPointData() pd.SetScalars(amp_array) pd.GetArray(0).SetName("amp") # update vti file with edges edges_array = np.transpose((np.flip(edges, 2))).reshape(edges.size) edges_array = numpy_support.numpy_to_vtk(edges_array) pd.AddArray(edges_array) pd.GetArray(1).SetName("edges") pd.Update() index_vti = 2 del amp, amp_array, edges_array gc.collect() ######################################################### # save surface, edges and corners strain to the logfile # ######################################################### fu.update_logfile( support=surface, strain_array=strain, summary_file=summary_file, allpoints_file=allpoints_file, label="surface", ) fu.update_logfile( support=edges, strain_array=strain, summary_file=summary_file, allpoints_file=allpoints_file, label="edges", ) fu.update_logfile( support=corners, strain_array=strain, summary_file=summary_file, allpoints_file=allpoints_file, label="corners", ) del corners gc.collect() ####################################################################################### # Iterate over the planes to find the corresponding surface facet # # Effect of meshing/smoothing: the meshed support is smaller than the initial support # ####################################################################################### summary_dict = {} for label in unique_labels: print("\nPlane", label) # raw fit including all points plane = np.copy(all_planes) plane[plane != label] = 0 plane[plane == label] = 1 if plane[plane == 1].sum() == 0: # no points on the plane print("Raw fit: no points for plane", label) continue ################################################################ # fit a plane to the voxels isolated by watershed segmentation # ################################################################ # Why not using directly the centroid to find plane equation? # Because it does not distinguish pixels coming from different but parallel facets coeffs, plane_indices, errors, stop = fu.fit_plane( plane=plane, label=label, debugging=debug ) if stop: print("No points remaining after raw fit for plane", label) continue # update plane by filtering out pixels too far from the fit plane plane, stop = fu.distance_threshold( fit=coeffs, indices=plane_indices, plane_shape=plane.shape, max_distance=max_distance_plane, ) grown_points = plane[plane == 1].sum().astype(int) if stop: # no points on the plane print("Refined fit: no points for plane", label) continue print( "Plane", label, ", ", str(grown_points), "points after checking distance to plane", ) plane_indices = np.nonzero(plane) # plane_indices is a tuple of 3 arrays # check that the plane normal is not flipped using # the support gradient at the center of mass of the facet zcom_facet, ycom_facet, xcom_facet = center_of_mass(plane) mean_gradient = fu.surface_gradient( (zcom_facet, ycom_facet, xcom_facet), support=support )[0] plane_normal = np.array( [coeffs[0], coeffs[1], coeffs[2]] ) # normal is [a, b, c] if ax+by+cz+d=0 plane_normal = plane_normal / np.linalg.norm(plane_normal) if np.dot(plane_normal, mean_gradient) < 0: # normal is in the reverse direction print("Flip normal direction plane", str(label)) plane_normal = -1 * plane_normal coeffs = (-coeffs[0], -coeffs[1], -coeffs[2], -coeffs[3]) ######################################################### # Look for the surface: correct for the offset between # # the plane equation and the outer shell of the support # ######################################################### # crop the support to a small ROI included in the plane box surf0, surf1, surf2 = fu.surface_indices( surface=surface, plane_indices=plane_indices, margin=3 ) if debug: gu.scatter_plot_overlaid( arrays=( np.asarray(plane_indices).T, np.concatenate( (surf0[:, np.newaxis], surf1[:, np.newaxis], surf2[:, np.newaxis]), axis=1, ), ), markersizes=(8, 2), markercolors=("b", "r"), labels=("axis 0", "axis 1", "axis 2"), title="Plane" + str(label) + " before shifting", ) # find the direction in which the plane should be shifted to cross the surface dist = np.zeros(len(surf0)) for point in range(len(surf0)): dist[point] = ( coeffs[0] * surf0[point] + coeffs[1] * surf1[point] + coeffs[2] * surf2[point] + coeffs[3] ) / np.linalg.norm(plane_normal) mean_dist = dist.mean() print( "Mean distance of plane ", label, " to outer shell = " + str("{:.2f}".format(mean_dist)) + " pixels", ) # offset the plane by mean_dist/2 and see if the plane is closer to # the surface or went in the wrong direction dist = np.zeros(len(surf0)) offset = mean_dist / 2 for point in range(len(surf0)): dist[point] = ( coeffs[0] * surf0[point] + coeffs[1] * surf1[point] + coeffs[2] * surf2[point] + coeffs[3] - offset ) / np.linalg.norm(plane_normal) new_dist = dist.mean() print( "<distance> of plane ", label, " to outer shell after offsetting by mean_distance/2 = " + str("{:.2f}".format(new_dist)) + " pixels", ) # these directions are for a mesh smaller than the support step_shift = 0.5 # will scan with subpixel step through the crystal # in order to not miss voxels if mean_dist * new_dist < 0: # crossed the support surface, correct direction step_shift = np.sign(mean_dist) * step_shift elif ( abs(new_dist) - abs(mean_dist) < 0 ): # moving towards the surface, correct direction step_shift = np.sign(mean_dist) * step_shift else: # moving away from the surface, wrong direction step_shift = -1 * np.sign(mean_dist) * step_shift ############################################## # shift the fit plane along its normal until # # the normal is crossed and go back one step # ############################################## total_offset = fu.find_facet( refplane_indices=plane_indices, surf_indices=(surf0, surf1, surf2), original_shape=surface.shape, step_shift=step_shift, plane_label=label, plane_coeffs=coeffs, min_points=grown_points / 5, debugging=debug, ) # correct the offset of the fit plane to match the surface coeffs = list(coeffs) coeffs[3] = coeffs[3] - total_offset # shift plane indices plane_newindices0, plane_newindices1, plane_newindices2 = fu.offset_plane( indices=plane_indices, offset=total_offset, plane_normal=plane_normal ) plane = np.zeros(surface.shape) plane[plane_newindices0, plane_newindices1, plane_newindices2] = 1 # use only pixels belonging to the outer shell of the support plane = plane * surface if debug: # plot plane points overlaid with the support plane_indices = np.nonzero(plane == 1) gu.scatter_plot_overlaid( arrays=( np.asarray(plane_indices).T, np.concatenate( (surf0[:, np.newaxis], surf1[:, np.newaxis], surf2[:, np.newaxis]), axis=1, ), ), markersizes=(8, 2), markercolors=("b", "r"), labels=("axis 0", "axis 1", "axis 2"), title="Plane" + str(label) + " after finding the surface\n" + "Points number=" + str(len(plane_indices[0])), ) if plane[plane == 1].sum() == 0: # no point belongs to the support print("Plane ", label, " , no point belongs to support") continue ################################# # grow the facet on the surface # ################################# print("Growing the facet at the surface") iterate = 0 while stop == 0: previous_nb = plane[plane == 1].sum() plane, stop = fu.grow_facet( fit=coeffs, plane=plane, label=label, support=support, max_distance=1.5 * max_distance_plane, debugging=debug, ) # here the distance threshold is larger in order to reach # voxels missed by the first plane fit when rounding vertices to integer. # Anyway we intersect it with the surface therefore it can not go crazy. plane_indices = np.nonzero(plane) iterate = iterate + 1 plane = ( plane * surface ) # use only pixels belonging to the outer shell of the support if plane[plane == 1].sum() == previous_nb: print("Growth: maximum size reached") break if iterate == 50: # it is likely that we are stuck in an infinite loop # after this number of iterations print("Growth: maximum iteration number reached") break grown_points = plane[plane == 1].sum().astype(int) print( "Plane ", label, ", ", str(grown_points), "points after growing facet at the surface", ) if debug: plane_indices = np.nonzero(plane == 1) surf0, surf1, surf2 = fu.surface_indices( surface=surface, plane_indices=plane_indices, margin=3 ) gu.scatter_plot_overlaid( arrays=( np.asarray(plane_indices).T, np.concatenate( (surf0[:, np.newaxis], surf1[:, np.newaxis], surf2[:, np.newaxis]), axis=1, ), ), markersizes=(8, 2), markercolors=("b", "r"), labels=("axis 0", "axis 1", "axis 2"), title="Plane" + str(label) + " after 1st growth at the surface\n iteration" + str(iterate) + "- Points number=" + str(len(plane_indices[0])), ) ################################################################ # refine plane fit, now we are sure that we are at the surface # ################################################################ coeffs, plane_indices, errors, stop = fu.fit_plane( plane=plane, label=label, debugging=debug ) if stop: print("No points remaining after refined fit for plane", label) continue if debug: surf0, surf1, surf2 = fu.surface_indices( surface=surface, plane_indices=plane_indices, margin=3 ) gu.scatter_plot_overlaid( arrays=( np.asarray(plane_indices).T, np.concatenate( (surf0[:, np.newaxis], surf1[:, np.newaxis], surf2[:, np.newaxis]), axis=1, ), ), markersizes=(8, 2), markercolors=("b", "r"), labels=("axis 0", "axis 1", "axis 2"), title="Plane" + str(label) + " after refined fit at surface\n iteration" + str(iterate) + "- Points number=" + str(len(plane_indices[0])), ) # update plane by filtering out pixels too far from the fit plane plane, stop = fu.distance_threshold( fit=coeffs, indices=plane_indices, plane_shape=plane.shape, max_distance=max_distance_plane, ) if stop: # no points on the plane print("Refined fit: no points for plane", label) continue print( "Plane", label, ", ", str(plane[plane == 1].sum()), "points after refined fit" ) plane_indices = np.nonzero(plane) if debug: surf0, surf1, surf2 = fu.surface_indices( surface=surface, plane_indices=plane_indices, margin=3 ) gu.scatter_plot_overlaid( arrays=( np.asarray(plane_indices).T, np.concatenate( (surf0[:, np.newaxis], surf1[:, np.newaxis], surf2[:, np.newaxis]), axis=1, ), ), markersizes=(8, 2), markercolors=("b", "r"), labels=("axis 0", "axis 1", "axis 2"), title="Plane" + str(label) + " after distance threshold at surface\n" + "Points number=" + str(len(plane_indices[0])), ) # check that the plane normal is not flipped using the support gradient # at the center of mass of the facet zcom_facet, ycom_facet, xcom_facet = center_of_mass(plane) mean_gradient = fu.surface_gradient( (zcom_facet, ycom_facet, xcom_facet), support=support )[0] plane_normal = np.array( [coeffs[0], coeffs[1], coeffs[2]] ) # normal is [a, b, c] if ax+by+cz+d=0 plane_normal = plane_normal / np.linalg.norm(plane_normal) if np.dot(plane_normal, mean_gradient) < 0: # normal is in the reverse direction print("Flip normal direction plane", str(label)) plane_normal = -1 * plane_normal coeffs = (-coeffs[0], -coeffs[1], -coeffs[2], -coeffs[3]) ############################################ # final growth of the facet on the surface # ############################################ print("Final growth of the facet") iterate = 0 while stop == 0: previous_nb = plane[plane == 1].sum() plane, stop = fu.grow_facet( fit=coeffs, plane=plane, label=label, support=support, max_distance=1.5 * max_distance_plane, debugging=debug, ) plane = ( plane * surface ) # use only pixels belonging to the outer shell of the support iterate = iterate + 1 if plane[plane == 1].sum() == previous_nb: print("Growth: maximum size reached") break if iterate == 50: # it is likely that we are stuck in an infinite loop # after this number of iterations print("Growth: maximum iteration number reached") break grown_points = plane[plane == 1].sum().astype(int) # plot plane points overlaid with the support print( "Plane ", label, ", ", str(grown_points), "points after the final growth of the facet", ) if debug: plane_indices = np.nonzero(plane) surf0, surf1, surf2 = fu.surface_indices( surface=surface, plane_indices=plane_indices, margin=3 ) gu.scatter_plot_overlaid( arrays=( np.asarray(plane_indices).T, np.concatenate( (surf0[:, np.newaxis], surf1[:, np.newaxis], surf2[:, np.newaxis]), axis=1, ), ), markersizes=(8, 2), markercolors=("b", "r"), labels=("axis 0", "axis 1", "axis 2"), title="Plane" + str(label) + " final growth at the surface\nPoints number=" + str(len(plane_indices[0])), ) ##################################### # remove point belonging to an edge # ##################################### plane[np.nonzero(edges)] = 0 plane_indices = np.nonzero(plane) if debug: surf0, surf1, surf2 = fu.surface_indices( surface=surface, plane_indices=plane_indices, margin=3 ) gu.scatter_plot_overlaid( arrays=( np.asarray(plane_indices).T, np.concatenate( (surf0[:, np.newaxis], surf1[:, np.newaxis], surf2[:, np.newaxis]), axis=1, ), ), markersizes=(8, 2), markercolors=("b", "r"), labels=("axis 0", "axis 1", "axis 2"), title="Plane" + str(label) + " after edge removal\nPoints number=" + str(len(plane_indices[0])), ) print( "Plane ", label, ", ", str(len(plane_indices[0])), "points after removing edges" ) ############################################################################## # calculate the angle between the plane normal and the measurement direction # ############################################################################## # correct plane_normal for the eventual anisotropic voxel size plane_normal = np.array( [ plane_normal[0] * 2 * np.pi / voxel_size[0], plane_normal[1] * 2 * np.pi / voxel_size[1], plane_normal[2] * 2 * np.pi / voxel_size[2], ] ) plane_normal = plane_normal / np.linalg.norm(plane_normal) # check where is the measurement direction if projection_axis == 0: # q aligned along the 1st axis ref_axis =
np.array([1, 0, 0])
numpy.array
""" Auxiliary code for section 3. Application of Synthetic Control Method in the main notebook. Contents include functions for: - data preparation - dynamic graphs - optimization with CVXPY - SCM( ) application - dataframes for RMSPE and outputs """ # All notebook dependencies: import cvxpy as cp import numpy as np import pandas as pd import numpy.linalg as LA import statsmodels.api as sm import plotly.graph_objs as go from qpsolvers import solve_qp import matplotlib.pyplot as plt import scipy.optimize as optimize from joblib import Parallel, delayed import statsmodels.formula.api as smf from scipy.optimize import differential_evolution, NonlinearConstraint, Bounds def data_prep_1(data): """ Specify conditions for treated unit and control units as per Pinotti's paper (c.f. F216), where 21 are regions "NEW" with recent mafia presence: Apulia and Basilicata """ treat_unit = data[data.reg == 21] treat_unit = treat_unit[treat_unit.year <= 1960] # Matching period: 1951 to 1960 treat_unit_all = data[data.reg == 21] # Entire period: 1951 to 2007 control_units = data[(data.reg <= 14) | (data.reg ==20)] control_units = control_units[control_units.year <= 1960] control_units_all = data[(data.reg <= 14) | (data.reg ==20)] y_treat = np.array(treat_unit.gdppercap).reshape(1, 10) # Matching period: 1951 to 1960 y_treat_all = np.array(treat_unit_all.gdppercap).reshape(1, 57) # Entire period: 1951 to 2007 y_control = np.array(control_units.gdppercap).reshape(15, 10) y_control_all = np.array(control_units_all.gdppercap).reshape(15, 57) Z1 = y_treat.T Z0 = y_control.T # Prepare matrices with only the relevant variables into CVXPY format, predictors k = 8 predictor_variables = ['gdppercap', 'invrate', 'shvain', 'shvaag', 'shvams', 'shvanms', 'shskill', 'density'] X = data.loc[data['year'].isin(list(range(1951, 1961)))] X.index = X.loc[:,'reg'] # k x J matrix: mean values of k predictors for J untreated units X0 = X.loc[(X.index <= 14) | (X.index ==20),(predictor_variables)] X0 = X0.groupby(X0.index).mean().values.T # k x 1 vector: mean values of k predictors for 1 treated unit X1 = X.loc[(X.index == 21),(predictor_variables)] X1 = X1.groupby(X1.index).mean().values.T w_pinotti = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.6244443, 0.3755557, 0]).reshape(15, 1) w_becker = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.4303541, 0.4893414, 0.0803045]).reshape(15,1) v_pinotti = [0.464413137,0.006141563,0.464413137,0.006141563,0.013106925,0.006141563,0.033500548,0.006141563] v_becker = [0,0.018382899,0.778844583,0.013064060,0.013064060,0.013064060,0.150516278,0.013064060] return (treat_unit, treat_unit_all, control_units, control_units_all, y_treat, y_treat_all, y_control, y_control_all, Z1, Z0, X0, X1, w_pinotti, w_becker, v_pinotti, v_becker) def cvxpy_basic_solution(control_units, X0, X1): """ Initial CVXPY setup: defines function to call and output a vector of weights function """ def w_optimize(v_diag,solver=cp.ECOS): V = np.zeros(shape=(8, 8)) np.fill_diagonal(V,v_diag) W = cp.Variable((15, 1), nonneg=True) ## Creates a 15x1 positive nonnegative variable objective_function = cp.Minimize(cp.norm(V @ (X1 - X0 @ W))) objective_constraints = [cp.sum(W) == 1] objective_problem = cp.Problem(objective_function, objective_constraints) objective_solution = objective_problem.solve(solver) return (W.value,objective_problem.constraints[0].violation(),objective_solution) # CVXPY Solution v_diag = [1/8]*8 w_basic, constraint_violation, objective_solution = w_optimize(v_diag) print('\nObjective Value: ', objective_solution) solution_frame_1 = pd.DataFrame({'Region':control_units.region.unique(), 'Weights': np.round(w_basic.T[0], decimals=3)}) display(solution_frame_1.transpose()) return w_basic def data_compare_df(w_basic, X0, X1, w_pinotti): """ Outputs a dataframe to show predicted versus actual values of variables """ ['gdppercap', 'invrate', 'shvain', 'shvaag', 'shvams', 'shvanms', 'shskill', 'density'] x_pred_pinotti = (X0 @ w_pinotti) x_pred_basic = (X0 @ w_basic) pred_error_pinotti = x_pred_pinotti - X1 pred_error_basic = x_pred_basic - X1 rounded_x1 = np.array([2395.0, 0.32, 0.22, 0.15, 0.4, 0.23, 0.17, 134.78]) data_compare = pd.DataFrame({'Observed': rounded_x1, 'Pinotti Predicted':np.round(x_pred_pinotti.T[0],2), 'Optimizer Predicted':np.round(x_pred_basic.T[0],2), 'Pinotti Differential': np.round(pred_error_pinotti.T[0],2), 'Optimizer Differential': np.round(pred_error_basic.T[0],2)}, index= ['GDP per Capita','Investment Rate','Industry VA','Agriculture VA', 'Market Services VA','Non-market Services VA','Human Capital', 'Population Density']) display(data_compare) def fig3_dynamic_graph(w_basic, w_pinotti, w_becker, y_control_all, y_treat_all, data): """ Plots Figure 3: Evolution of observed GDP per capita vs. synthetic estimates across different donor weights """ y_synth_pinotti = w_pinotti.T @ y_control_all y_synth_becker = w_becker.T @ y_control_all y_synth_basic = w_basic.T @ y_control_all fig = go.Figure() fig.add_trace(go.Scatter(x=list(data.year.unique()), y=y_synth_basic[0], mode='lines', name='Optimizer')) fig.add_trace(go.Scatter(x=list(data.year.unique()), y=y_synth_pinotti[0], mode='lines', name='Pinotti')) fig.add_trace(go.Scatter(x=list(data.year.unique()), y=y_synth_becker[0], mode='lines', name='Becker and Klößner')) fig.add_trace(go.Scatter(x=list(data.year.unique()), y=y_treat_all[0], mode='lines', name='Treated unit')) fig.add_shape(dict(type="line", x0=1960, y0=0, x1=1960, y1=11000, line=dict(color="Black", width=1))) fig.add_shape(dict(type="line", x0=1974, y0=0, x1=1974, y1=11000, line=dict(color="Black", width=1))) fig.add_shape(dict(type="line", x0=1980, y0=0, x1=1980, y1=11000, line=dict(color="Black", width=1))) fig.add_trace(go.Scatter(x=[1960], y=[12000], mode="text", name="Matching", text=["End of Matching<br>Period"])) fig.add_trace(go.Scatter(x=[1974], y=[12000], mode="text", name="Event 1", text=["Drug<br>Smuggling"])) fig.add_trace(go.Scatter(x=[1981], y=[12000], mode="text", name="Event 2", text=["Basilicata<br>Earthquake"])) fig.update_layout(xaxis_title='Time', yaxis_title='GDP per Capita') fig.show() def RMSPE_compare_df(Z1, Z0, w_basic, w_pinotti, w_becker): """ Defines function for Root Mean Squared Prediction Error (RMSPE) and generates dataframe for RMSPE values comparison between CVXPY output, Pinotti, Becker """ # Function RMSPE def RMSPE(w): return np.sqrt(np.mean((Z1 - Z0 @ w)**2)) # Dataframe to compare RMSPE values RMSPE_values = [RMSPE(w_basic), RMSPE(w_pinotti), RMSPE(w_becker)] method = ['RMSPE CVXPY','RMSPE Pinotti','RMSPE Becker'] RMSPE_compare = pd.DataFrame({'Outcome':RMSPE_values}, index=method) display(RMSPE_compare) ################################## ## Iterative implementation ## ################################## def V_iterative(solution_frame_2,control_units): """ Iterative implementation with CXPYS's SCS, ECOS, CPLEX and scipy's SLSQP packages Generates - Figure 4: Minimum RMSPEs with increasing iterations and the average violations of the sum constraint - Predictors' weights - Regional weights per package - Optimal values and constraint violation values per package """ class Solution: def solve(self, nums): if not nums: return [] j=nums[0] nums[0]=nums[0] for i in range(1,len(nums)): k=nums[i] nums[i]=j j=min(j,k) return nums ob = Solution() ECOS_min = ob.solve(list(solution_frame_2['RMSPE ECOS'].values)) SCS_min = ob.solve(list(solution_frame_2['RMSPE SCS'].values)) CPLEX_min = ob.solve(list(solution_frame_2['RMSPE CPLEX'].values)) SLSQP_min = ob.solve(list(solution_frame_2['RMSPE SLSQP'].values)) figure, axes = plt.subplots(1, 2,figsize=(10,5)) ax1 = axes[0] ax2 = axes[1] ax1.plot(ECOS_min,label = 'ECOS') ax1.plot(SCS_min,label = 'SCS') ax1.plot(CPLEX_min,label = 'CPLEX') ax1.plot(SLSQP_min,label = 'SLSQP') ax1.set_xlabel('Iterations') ax1.set_ylabel('Value of Outer Objective Function') ax1.set_ylim(129.5,133) ax1.title.set_text('Fig 4(a) Convergence of RMSPE') ax1.legend(loc = 'upper center', bbox_to_anchor = (0.5, -0.13), shadow = True, ncol = 4) methods = ['ECOS', 'SCS', 'CPLEX'] violations = [solution_frame_2['ECOS Violation'].mean(), solution_frame_2['SCS Violation'].mean(), solution_frame_2['CPLEX Violation'].mean()] ax2.set_yscale("log") ax2.bar(methods,violations,color=['blue', 'orange','green']) ax2.set_xlabel('Methods') ax2.set_ylabel('Constraint Violation') ax2.set_ylim(10**-15,10**-2) ax2.title.set_text('Fig 4(b) Average Constraint Violation') plt.show() sorted_df = solution_frame_2.sort_values(by='RMSPE ECOS', ascending=True) sorted_df_SCS = solution_frame_2.sort_values(by='RMSPE SCS', ascending=True) w_ECOS = sorted_df.iloc[0][5] w_SCS = sorted_df_SCS.iloc[0][6] w_CPLEX = sorted_df.iloc[0][7] w_SLSQP = sorted_df.iloc[0][8] best_weights_region = pd.DataFrame({'ECOS' : np.round(w_ECOS.ravel(), decimals=3), 'SCS' : np.round(w_SCS.ravel(), decimals=3), 'SLSQP' : np.round(w_SLSQP.ravel(), decimals=3), 'CPLEX' : np.round(w_CPLEX.ravel(), decimals=3)}, index = control_units.region.unique()) best_weights_predictor = pd.DataFrame({'v*': np.round(sorted_df.iloc[0][0].ravel(),decimals=3)}, index= ['GDP per Capita','Investment Rate','Industry VA','Agriculture VA', 'Market Services VA','Non-market Services VA','Human Capital', 'Population Density']) display(best_weights_predictor.T) display(best_weights_region.T) # Organize output into dataframe print("\noptimal value with SCS: ",np.round(sorted_df_SCS.iloc[0][2],3), "| constraint violation: ", sorted_df_SCS.iloc[0][9]) print("optimal value with ECOS: ",np.round(sorted_df.iloc[0][1],3), "| constraint violation: ", sorted_df.iloc[0][10]) print("optimal value with CPLEX:",np.round(sorted_df.iloc[0][3],3), "| constraint violation: ", sorted_df.iloc[0][11]) print("optimal value with SLSQP:",np.round(sorted_df.iloc[0][4],3), "| constraint violation: n.a.") def data_prep(data,unit_identifier,time_identifier,matching_period,treat_unit,control_units,outcome_variable, predictor_variables, normalize=False): """ Prepares the data by normalizing X for section 3.3. in order to replicate Becker and Klößner (2017) """ X = data.loc[data[time_identifier].isin(matching_period)] X.index = X.loc[:,unit_identifier] X0 = X.loc[(X.index.isin(control_units)),(predictor_variables)] X0 = X0.groupby(X0.index).mean().values.T #control predictors X1 = X.loc[(X.index == treat_unit),(predictor_variables)] X1 = X1.groupby(X1.index).mean().values.T #treated predictors # outcome variable realizations in matching period - Z0: control, Z1: treated Z0 = np.array(X.loc[(X.index.isin(control_units)),(outcome_variable)]).reshape(len(control_units),len(matching_period)).T #control outcome Z1 = np.array(X.loc[(X.index == treat_unit),(outcome_variable)]).reshape(len(matching_period),1) #treated outcome if normalize == True: # Scaling nvarsV = X0.shape[0] big_dataframe = pd.concat([pd.DataFrame(X0), pd.DataFrame(X1)], axis=1) divisor = np.sqrt(big_dataframe.apply(np.var, axis=1)) V = np.zeros(shape=(len(predictor_variables), len(predictor_variables))) np.fill_diagonal(V, np.diag(np.repeat(big_dataframe.shape[0],1))) scaled_matrix = ((big_dataframe.T) @ (np.array(1/(divisor)).reshape(len(predictor_variables),1) * V)).T X0 = np.array(scaled_matrix.iloc[:,0:len(control_units)]) X1 = np.array(scaled_matrix.iloc[:,len(control_units):(len(control_units)+1)]) Z0 = Z0.astype('float64') Z1 = Z1.astype('float64') return X0, X1, Z0, Z1 def SCM_print(data,output_object,w_pinotti,Z1,Z0): """ Organizes output from SCM into dataframe """ def RMSPE(w): return np.sqrt(np.mean((Z1 - Z0 @ w)**2)) solution_frame_4 = output_object[0] w_nested = output_object[1] v_nested = output_object[2] control_units = data[(data.reg <= 14) | (data.reg == 20)] best_weights_region3 = pd.DataFrame({'Region':control_units.region.unique(), 'W(V*)': np.round(w_nested.ravel(), decimals=3)}) best_weights_importance3 = pd.DataFrame({'v*': np.round(v_nested, 3)}, index= ['GDP per Capita','Investment Rate','Industry VA','Agriculture VA', 'Market Services VA','Non-market Services VA','Human Capital', 'Population Density']) print('\nV* Constraint Violation: {} \nW*(V*) Constraint Violation: {}'\ .format(1-sum(v_nested.ravel()), abs(1-sum(w_nested.ravel())))) print('\nOptimizer Weights: {} \nPinotti Weights: {}'\ .format(np.round(w_nested.T,3), np.round(w_pinotti,3).T)) print('\nRMSPE Nested: {} \nRMSPE Pinotti: {}'\ .format(np.round(RMSPE(w_nested),5), np.round(RMSPE(w_pinotti),5))) display(best_weights_importance3.T) display(best_weights_region3.T) def SCM_v1(data,unit_identifier,time_identifier,matching_period,treat_unit,control_units,outcome_variable, predictor_variables,reps=1,solver=cp.ECOS,seed=1): """ Section 3.2.3. Approach 2: Nested Optimization """ X0, X1, Z0, Z1 = data_prep(data,unit_identifier,time_identifier,matching_period,treat_unit, control_units,outcome_variable,predictor_variables) #inner optimization def w_optimize(v): V = np.zeros(shape=(len(predictor_variables), len(predictor_variables))) np.fill_diagonal(V,v) W = cp.Variable((len(control_units), 1), nonneg=True) objective_function = cp.Minimize(cp.norm(V @ (X1 - X0 @ W))) objective_constraints = [cp.sum(W) == 1] objective_problem = cp.Problem(objective_function, objective_constraints) objective_solution = objective_problem.solve(solver) return (W.value) #outer optimization def vmin(v): v = v.reshape(len(predictor_variables),1) W = w_optimize(v) return ((Z1 - Z0 @ W).T @ (Z1 - Z0 @ W)).ravel() # constraint on the sum of predictor weights. def constr_f(v): return float(
np.sum(v)
numpy.sum
import numpy as np import torch import torch.nn as nn from .base_model import BaseModel from ...utils import MODEL from open3d.ml.torch.layers import SparseConv, SparseConvTranspose from open3d.ml.torch.ops import voxelize, reduce_subarrays_sum class SparseConvUnet(BaseModel): def __init__(self, name="SparseConvUnet", device="cuda", m=16, scale=20, in_channels=3, num_classes=20, **kwargs): super(SparseConvUnet, self).__init__(name=name, device=device, m=m, scale=scale, in_channels=in_channels, num_classes=num_classes, **kwargs) cfg = self.cfg self.device = device self.m = cfg.m self.inp = InputLayer() self.ssc = SubmanifoldSparseConv(in_channels=in_channels, filters=m, kernel_size=[3, 3, 3]) self.unet = UNet(1, [m, 2 * m, 3 * m, 4 * m, 5 * m, 6 * m, 7 * m], False) self.bn = nn.BatchNorm1d(m, eps=1e-4, momentum=0.01) self.relu = nn.ReLU() self.linear = nn.Linear(m, num_classes) self.out = OutputLayer() def forward(self, inputs): output = [] for inp in inputs: pos = inp['point'] feat = inp['feat'] feat, pos, rev = self.inp(feat, pos) feat = self.ssc(feat, pos, voxel_size=1.0) feat = self.unet(pos, feat) feat = self.bn(feat) feat = self.relu(feat) feat = self.linear(feat) feat = self.out(feat, rev) output.append(feat) return output def preprocess(self, data, attr): points = np.array(data['point'], dtype=np.float32) if 'label' not in data.keys() or data['label'] is None: labels = np.zeros((points.shape[0],), dtype=np.int32) else: labels =
np.array(data['label'], dtype=np.int32)
numpy.array
import numpy as np import os import pickle import scipy.sparse as sp from matrix_factorization import matrix_factorization_als, write_als_prediction def build_matrix(nnz, methods, ratings, g_mean, user_means, item_means, sgd, als, cf_item, cf_user, predict=False): """ Build the matrix for blending (shape = (number of predictions, number of models)) :param nnz: list of tuples item, user where each tuple is a prediction :param methods: list of the models to put in the matrix (should be in 'global_mean', 'user_mean', 'item_mean' 'sgd', 'als', 'cf_item', 'cf_user'). :param ratings: initial sparse matrix of shape (number of items, number of users) :param g_mean: global mean of the training set :param user_means: user means (from training set) :param item_means: item means (from training set) :param sgd: predictions coming from the sgd matrix factorization :param als: predictions coming from the als matrix factorization :param cf_item: predictions coming from the item-based collaborative filtering :param cf_user: predictions coming from the user-based collaborative filtering :param predict: Boolean, to know if currently training/testing or predicting :return: matrix for blending (shape = (number of predictions, number of models)) """ m = np.zeros(shape=(len(nnz), len(methods))) if not predict: y = [] else: y = None for i, (item, user) in enumerate(nnz): if not predict: y.append(ratings[item, user]) if 'global_mean' in methods: k = methods.index('global_mean') m[i, k] = g_mean if 'user_mean' in methods: k = methods.index('user_mean') m[i, k] = user_means[user] if 'item_mean' in methods: k = methods.index('item_mean') m[i, k] = item_means[item] if 'sgd' in methods: k = methods.index('sgd') m[i, k] = sgd[item, user] if 'als' in methods: k = methods.index('als') m[i, k] = als[item, user] if 'cf_item' in methods: k = methods.index('cf_item') m[i, k] = cf_item[item, user] if 'cf_user' in methods: k = methods.index('cf_user') m[i, k] = cf_user[item, user] return m, y def blend(methods, alpha, nnz_train, nnz_test, train, test, g_mean, user_means, item_means, sgd, als, cf_item, cf_user, predict=False): """ :param methods: list of methods to blend :param alpha: penalization parameter for the ridge regression :param nnz_train: exhaustive list of (i, j) such that train[i, j] in non zero :param nnz_test: exhaustive list of (i, j) such that test[i, j] in non zero :param train: training set (sparse matrix of shape (number of items, number of users)) :param test: test set (sparse matrix of shape (number of items, number of users)) :param g_mean: global mean of the training set :param user_means: user_means computed on the training set :param item_means: item_means computed on the training set :param sgd: sgd prediction on the training set (sparse matrix of shape (number of items, number of users)) :param als: als predictions on the training set (sparse matrix of shape (number of items, number of users)) :param cf_item: predictions on the training set (sparse matrix of shape (number of items, number of users)) :param cf_user: predictions on the training set (sparse matrix of shape (number of items, number of users)) :param predict: Boolean, if True, no ground truth vector y is return :return: matrix of shape (number of predictions, number of models), vector of length number of predictions """ m_train, y_train = build_matrix(nnz_train, methods, train, g_mean, user_means, item_means, sgd, als, cf_item, cf_user, predict=False) # Ridge Regression w = np.linalg.solve(m_train.T.dot(m_train) + alpha * np.eye(m_train.shape[1]), m_train.T.dot(y_train)) y_predict_train = m_train.dot(w) # Cut predictions that are too high and too low for i in range(len(y_predict_train)): y_predict_train[i] = min(5, y_predict_train[i]) y_predict_train[i] = max(1, y_predict_train[i]) m_test, y_test = build_matrix(nnz_test, methods, test, g_mean, user_means, item_means, sgd, als, cf_item, cf_user, predict) y_predict_test = m_test.dot(w) # Cut predictions that are too high and too low for i in range(len(y_predict_test)): y_predict_test[i] = min(5, y_predict_test[i]) y_predict_test[i] = max(1, y_predict_test[i]) if y_test is not None: return w, np.sqrt(
np.mean((y_train - y_predict_train) ** 2)
numpy.mean
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 5 12:13:33 2018 @author: <NAME> (<EMAIL> / <EMAIL>) """ # Python dependencies from __future__ import division import pandas as pd import numpy as np import mpmath as mp import matplotlib as mpl import seaborn as sns from scipy.constants import codata from pylab import * from lmfit import minimize, report_fit # from scipy.optimize import leastsq pd.options.mode.chained_assignment = None # Plotting mpl.rc("mathtext", fontset="stixsans", default="regular") mpl.rcParams.update({"axes.labelsize": 22}) mpl.rc("xtick", labelsize=16) mpl.rc("ytick", labelsize=16) mpl.rc("legend", fontsize=14) F = codata.physical_constants["Faraday constant"][0] Rg = codata.physical_constants["molar gas constant"][0] ### Importing PyEIS add-ons from .PyEIS_Data_extraction import * from .PyEIS_Lin_KK import * from .PyEIS_Advanced_tools import * ### Frequency generator ## # def freq_gen(f_start, f_stop, pts_decade=7): """ Frequency Generator with logspaced freqencies Inputs ---------- f_start = frequency start [Hz] f_stop = frequency stop [Hz] pts_decade = Points/decade, default 7 [-] Output ---------- [0] = frequency range [Hz] [1] = Angular frequency range [1/s] """ f_decades = np.log10(f_start) - np.log10(f_stop) f_range = np.logspace( np.log10(f_start), np.log10(f_stop), num=np.around(pts_decade * f_decades).astype(int), endpoint=True, ) w_range = 2 * np.pi * f_range return f_range, w_range ### Simulation Element Functions ## # def elem_L(w, L): """ Simulation Function: -L- Returns the impedance of an inductor <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] L = Inductance [ohm * s] """ return 1j * w * L def elem_C(w, C): """ Simulation Function: -C- Inputs ---------- w = Angular frequency [1/s] C = Capacitance [F] """ return 1 / (C * (w * 1j)) def elem_Q(w, Q, n): """ Simulation Function: -Q- Inputs ---------- w = Angular frequency [1/s] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] """ return 1 / (Q * (w * 1j) ** n) ### Simulation Curciuts Functions ## # def cir_RsC(w, Rs, C): """ Simulation Function: -Rs-C- Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] C = Capacitance [F] """ return Rs + 1 / (C * (w * 1j)) def cir_RsQ(w, Rs, Q, n): """ Simulation Function: -Rs-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] """ return Rs + 1 / (Q * (w * 1j) ** n) def cir_RQ(w, R="none", Q="none", n="none", fs="none"): """ Simulation Function: -RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RQ_fit() <NAME> (<EMAIL> / <EMAIL>) Inputs ---------- w = Angular frequency [1/s] R = Resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] fs = Summit frequency of RQ circuit [Hz] """ if R == "none": R = 1 / (Q * (2 * np.pi * fs) ** n) elif Q == "none": Q = 1 / (R * (2 * np.pi * fs) ** n) elif n == "none": n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) return R / (1 + R * Q * (w * 1j) ** n) def cir_RsRQ(w, Rs="none", R="none", Q="none", n="none", fs="none"): """ Simulation Function: -Rs-RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RQ_fit() <NAME> (<EMAIL> / <EMAIL>) Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] R = Resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] fs = Summit frequency of RQ circuit [Hz] """ if R == "none": R = 1 / (Q * (2 * np.pi * fs) ** n) elif Q == "none": Q = 1 / (R * (2 * np.pi * fs) ** n) elif n == "none": n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) return Rs + (R / (1 + R * Q * (w * 1j) ** n)) def cir_RC(w, C="none", R="none", fs="none"): """ Simulation Function: -RC- Returns the impedance of an RC circuit, using RQ definations where n=1. see cir_RQ() for details <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] R = Resistance [Ohm] C = Capacitance [F] fs = Summit frequency of RC circuit [Hz] """ return cir_RQ(w, R=R, Q=C, n=1, fs=fs) def cir_RsRQRQ( w, Rs, R="none", Q="none", n="none", fs="none", R2="none", Q2="none", n2="none", fs2="none", ): """ Simulation Function: -Rs-RQ-RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RQ_fit() <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [Ohm] R = Resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase element exponent [-] fs = Summit frequency of RQ circuit [Hz] R2 = Resistance [Ohm] Q2 = Constant phase element [s^n/ohm] n2 = Constant phase element exponent [-] fs2 = Summit frequency of RQ circuit [Hz] """ if R == "none": R = 1 / (Q * (2 * np.pi * fs) ** n) elif Q == "none": Q = 1 / (R * (2 * np.pi * fs) ** n) elif n == "none": n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if R2 == "none": R2 = 1 / (Q2 * (2 * np.pi * fs2) ** n2) elif Q2 == "none": Q2 = 1 / (R2 * (2 * np.pi * fs2) ** n2) elif n2 == "none": n2 = np.log(Q2 * R2) / np.log(1 / (2 * np.pi * fs2)) return ( Rs + (R / (1 + R * Q * (w * 1j) ** n)) + (R2 / (1 + R2 * Q2 * (w * 1j) ** n2)) ) def cir_RsRQQ(w, Rs, Q, n, R1="none", Q1="none", n1="none", fs1="none"): """ Simulation Function: -Rs-RQ-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] Q1 = Constant phase element in (RQ) circuit [s^n/ohm] n1 = Constant phase elelment exponent in (RQ) circuit [-] fs1 = Summit frequency of RQ circuit [Hz] Q = Constant phase element of series Q [s^n/ohm] n = Constant phase elelment exponent of series Q [-] """ return Rs + cir_RQ(w, R=R1, Q=Q1, n=n1, fs=fs1) + elem_Q(w, Q, n) def cir_RsRQC(w, Rs, C, R1="none", Q1="none", n1="none", fs1="none"): """ Simulation Function: -Rs-RQ-C- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] Q1 = Constant phase element in (RQ) circuit [s^n/ohm] n1 = Constant phase elelment exponent in (RQ) circuit [-] fs1 = summit frequency of RQ circuit [Hz] C = Constant phase element of series Q [s^n/ohm] """ return Rs + cir_RQ(w, R=R1, Q=Q1, n=n1, fs=fs1) + elem_C(w, C=C) def cir_RsRCC(w, Rs, R1, C1, C): """ Simulation Function: -Rs-RC-C- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] C1 = Constant phase element in (RQ) circuit [s^n/ohm] C = Capacitance of series C [s^n/ohm] """ return Rs + cir_RC(w, C=C1, R=R1, fs="none") + elem_C(w, C=C) def cir_RsRCQ(w, Rs, R1, C1, Q, n): """ Simulation Function: -Rs-RC-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] C1 = Constant phase element in (RQ) circuit [s^n/ohm] Q = Constant phase element of series Q [s^n/ohm] n = Constant phase elelment exponent of series Q [-] """ return Rs + cir_RC(w, C=C1, R=R1, fs="none") + elem_Q(w, Q, n) def Randles_coeff( w, n_electron, A, E="none", E0="none", D_red="none", D_ox="none", C_red="none", C_ox="none", Rg=Rg, F=F, T=298.15, ): """ Returns the Randles coefficient sigma [ohm/s^1/2]. Two cases: a) ox and red are both present in solution here both Cred and Dred are defined, b) In the particular case where initially only Ox species are present in the solution with bulk concentration C*_ox, the surface concentrations may be calculated as function of the electrode potential following Nernst equation. Here C_red and D_red == 'none' Ref.: - Lasia, A.L., ISBN: 978-1-4614-8932-0, "Electrochemical Impedance Spectroscopy and its Applications" - <NAME>., ISBN: 0-471-04372-9, <NAME>. (2001) "Electrochemical methods: Fundamentals and applications". New York: Wiley. <NAME> (<EMAIL> // <EMAIL>) Inputs ---------- n_electron = number of e- [-] A = geometrical surface area [cm2] D_ox = Diffusion coefficent of oxidized specie [cm2/s] D_red = Diffusion coefficent of reduced specie [cm2/s] C_ox = Bulk concetration of oxidized specie [mol/cm3] C_red = Bulk concetration of reduced specie [mol/cm3] T = Temperature [K] Rg = Gas constant [J/molK] F = Faradays consntat [C/mol] E = Potential [V] if reduced specie is absent == 'none' E0 = formal potential [V] if reduced specie is absent == 'none' Returns ---------- Randles coefficient [ohm/s^1/2] """ if C_red != "none" and D_red != "none": sigma = ((Rg * T) / ((n_electron ** 2) * A * (F ** 2) * (2 ** (1 / 2)))) * ( (1 / (D_ox ** (1 / 2) * C_ox)) + (1 / (D_red ** (1 / 2) * C_red)) ) elif C_red == "none" and D_red == "none" and E != "none" and E0 != "none": f = F / (Rg * T) x = (n_electron * f * (E - E0)) / 2 func_cosh2 = (np.cosh(2 * x) + 1) / 2 sigma = ( (4 * Rg * T) / ((n_electron ** 2) * A * (F ** 2) * C_ox * ((2 * D_ox) ** (1 / 2))) ) * func_cosh2 else: print("define E and E0") Z_Aw = sigma * (w ** (-0.5)) - 1j * sigma * (w ** (-0.5)) return Z_Aw def cir_Randles( w, n_electron, D_red, D_ox, C_red, C_ox, Rs, Rct, n, E, A, Q="none", fs="none", E0=0, F=F, Rg=Rg, T=298.15, ): """ Simulation Function: Randles -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit with full complity of the warbug constant NOTE: This Randles circuit is only meant for semi-infinate linear diffusion <NAME> (<EMAIL> / <EMAIL>) Inputs ---------- n_electron = number of e- [-] A = geometrical surface area [cm2] D_ox = Diffusion coefficent of oxidized specie [cm2/s] D_red = Diffusion coefficent of reduced specie [cm2/s] C_ox = Concetration of oxidized specie [mol/cm3] C_red = Concetration of reduced specie [mol/cm3] T = Temperature [K] Rg = Gas constant [J/molK] F = Faradays consntat [C/mol] E = Potential [V] if reduced specie is absent == 'none' E0 = Formal potential [V] if reduced specie is absent == 'none' Rs = Series resistance [ohm] Rct = charge-transfer resistance [ohm] Q = Constant phase element used to model the double-layer capacitance [F] n = expononent of the CPE [-] Returns ---------- The real and imaginary impedance of a Randles circuit [ohm] """ Z_Rct = Rct Z_Q = elem_Q(w, Q, n) Z_w = Randles_coeff( w, n_electron=n_electron, E=E, E0=E0, D_red=D_red, D_ox=D_ox, C_red=C_red, C_ox=C_ox, A=A, T=T, Rg=Rg, F=F, ) return Rs + 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) def cir_Randles_simplified(w, Rs, R, n, sigma, Q="none", fs="none"): """ Simulation Function: Randles -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit with a simplified NOTE: This Randles circuit is only meant for semi-infinate linear diffusion <NAME> (<EMAIL> / <EMAIL>) """ if R == "none": R = 1 / (Q * (2 * np.pi * fs) ** n) elif Q == "none": Q = 1 / (R * (2 * np.pi * fs) ** n) elif n == "none": n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) Z_Q = 1 / (Q * (w * 1j) ** n) Z_R = R Z_w = sigma * (w ** (-0.5)) - 1j * sigma * (w ** (-0.5)) return Rs + 1 / (1 / Z_Q + 1 / (Z_R + Z_w)) # Polymer electrolytes def cir_C_RC_C(w, Ce, Cb="none", Rb="none", fsb="none"): """ Simulation Function: -C-(RC)-C- This circuit is often used for modeling blocking electrodes with a polymeric electrolyte, which exhibts a immobile ionic species in bulk that gives a capacitance contribution to the otherwise resistive electrolyte Ref: - <NAME>., and <NAME>. "Polymer Electrolyte Reviews - 1" Elsevier Applied Science Publishers LTD, London, Bruce, P. "Electrical Measurements on Polymer Electrolytes" <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] Ce = Interfacial capacitance [F] Rb = Bulk/series resistance [Ohm] Cb = Bulk capacitance [F] fsb = summit frequency of bulk (RC) circuit [Hz] """ Z_C = elem_C(w, C=Ce) Z_RC = cir_RC(w, C=Cb, R=Rb, fs=fsb) return Z_C + Z_RC def cir_Q_RQ_Q(w, Qe, ne, Qb="none", Rb="none", fsb="none", nb="none"): """ Simulation Function: -Q-(RQ)-Q- Modified cir_C_RC_C() circuits that can be used if electrodes and bulk are not behaving like ideal capacitors <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] Qe = Interfacial capacitance modeled with a CPE [F] ne = Interfacial constant phase element exponent [-] Rb = Bulk/series resistance [Ohm] Qb = Bulk capacitance modeled with a CPE [s^n/ohm] nb = Bulk constant phase element exponent [-] fsb = summit frequency of bulk (RQ) circuit [Hz] """ Z_Q = elem_Q(w, Q=Qe, n=ne) Z_RQ = cir_RQ(w, Q=Qb, R=Rb, fs=fsb, n=nb) return Z_Q + Z_RQ def tanh(x): """ As numpy gives errors when tanh becomes very large, above 10^250, this functions is used for np.tanh """ return (1 - np.exp(-2 * x)) / (1 + np.exp(-2 * x)) def cir_RCRCZD( w, L, D_s, u1, u2, Cb="none", Rb="none", fsb="none", Ce="none", Re="none", fse="none", ): """ Simulation Function: -RC_b-RC_e-Z_D This circuit has been used to study non-blocking electrodes with an ioniocally conducting electrolyte with a mobile and immobile ionic specie in bulk, this is mixed with a ionically conducting salt. This behavior yields in a impedance response, that consists of the interfacial impendaces -(RC_e)-, the ionically conducitng polymer -(RC_e)-, and the diffusional impedance from the dissolved salt. Refs.: - <NAME>. and <NAME>., Electrochimica Acta, 27, 1671-1675, 1982, "Conductivity, Charge Transfer and Transport number - An AC-Investigation of the Polymer Electrolyte LiSCN-Poly(ethyleneoxide)" - <NAME>., and <NAME>. "Polymer Electrolyte Reviews - 1" Elsevier Applied Science Publishers LTD, London Bruce, P. "Electrical Measurements on Polymer Electrolytes" <NAME> (<EMAIL> || <EMAIL>) Inputs ---------- w = Angular frequency [1/s] L = Thickness of electrode [cm] D_s = Diffusion coefficient of dissolved salt [cm2/s] u1 = Mobility of the ion reacting at the electrode interface u2 = Mobility of other ion Re = Interfacial resistance [Ohm] Ce = Interfacial capacitance [F] fse = Summit frequency of the interfacial (RC) circuit [Hz] Rb = Bulk/series resistance [Ohm] Cb = Bulk capacitance [F] fsb = Summit frequency of the bulk (RC) circuit [Hz] """ Z_RCb = cir_RC(w, C=Cb, R=Rb, fs=fsb) Z_RCe = cir_RC(w, C=Ce, R=Re, fs=fse) alpha = ((w * 1j * L ** 2) / D_s) ** (1 / 2) Z_D = Rb * (u2 / u1) * (tanh(x=alpha) / alpha) return Z_RCb + Z_RCe + Z_D # Transmission lines def cir_RsTLsQ(w, Rs, L, Ri, Q="none", n="none"): """ Simulation Function: -Rs-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> / <EMAIL>) Inputs ----------- Rs = Series resistance [ohm] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] Q = Interfacial capacitance of non-faradaic interface [F/cm] n = exponent for the interfacial capacitance [-] """ Phi = 1 / (Q * (w * 1j) ** n) X1 = Ri # ohm/cm Lam = (Phi / X1) ** (1 / 2) # np.sqrt(Phi/X1) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLsQ = Lam * X1 * coth_mp return Rs + Z_TLsQ def cir_RsRQTLsQ(w, Rs, R1, fs1, n1, L, Ri, Q, n, Q1="none"): """ Simulation Function: -Rs-RQ-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance(Q) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> / <EMAIL>) Inputs ----------- Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = Exponent for RQ circuit [-] Q1 = Constant phase element of RQ circuit [s^n/ohm] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] Q = Interfacial capacitance of non-faradaic interface [F/cm] n = Exponent for the interfacial capacitance [-] Output ----------- Impdance of Rs-(RQ)1-TLsQ """ Z_RQ = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) Phi = 1 / (Q * (w * 1j) ** n) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append(float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j) Z_TLsQ = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLsQ def cir_RsTLs(w, Rs, L, Ri, R="none", Q="none", n="none", fs="none"): """ Simulation Function: -Rs-TLs- TLs = Simplified Transmission Line, with a faradaic interfacial impedance (RQ) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> / <EMAIL>) Inputs ----------- Rs = Series resistance [ohm] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] R = Interfacial Charge transfer resistance [ohm*cm] fs = Summit frequency of interfacial RQ circuit [Hz] n = Exponent for interfacial RQ circuit [-] Q = Constant phase element of interfacial capacitance [s^n/Ohm] Output ----------- Impedance of Rs-TLs(RQ) """ Phi = cir_RQ(w, R, Q, n, fs) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_TLs def cir_RsRQTLs(w, Rs, L, Ri, R1, n1, fs1, R2, n2, fs2, Q1="none", Q2="none"): """ Simulation Function: -Rs-RQ-TLs- TLs = Simplified Transmission Line, with a faradaic interfacial impedance (RQ) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - B<NAME>. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> / <EMAIL>) Inputs ----------- Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = Exponent for RQ circuit [-] Q1 = Constant phase element of RQ circuit [s^n/(ohm * cm)] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] R2 = Interfacial Charge transfer resistance [ohm*cm] fs2 = Summit frequency of interfacial RQ circuit [Hz] n2 = Exponent for interfacial RQ circuit [-] Q2 = Constant phase element of interfacial capacitance [s^n/Ohm] Output ----------- Impedance of Rs-(RQ)1-TLs(RQ)2 """ Z_RQ = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) Phi = cir_RQ(w=w, R=R2, Q=Q2, n=n2, fs=fs2) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLs ### Support function def sinh(x): """ As numpy gives errors when sinh becomes very large, above 10^250, this functions is used instead of np/mp.sinh() """ return (1 - np.exp(-2 * x)) / (2 * np.exp(-x)) def coth(x): """ As numpy gives errors when coth becomes very large, above 10^250, this functions is used instead of np/mp.coth() """ return (1 + np.exp(-2 * x)) / (1 - np.exp(-2 * x)) ### def cir_RsTLQ(w, L, Rs, Q, n, Rel, Ri): """ Simulation Function: -R-TLQ- (interfacial non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] Q = Constant phase element for the interfacial capacitance [s^n/ohm] n = exponenet for interfacial RQ element [-] Rel = electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTLQ(w, L, Rs, Q, n, Rel, Ri, R1, n1, fs1, Q1="none"): """ Simulation Function: -R-RQ-TLQ- (interfacial non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = exponent for RQ circuit [-] Q1 = constant phase element of RQ circuit [s^n/(ohm * cm)] Q = Constant phase element for the interfacial capacitance [s^n/ohm] n = exponenet for interfacial RQ element [-] Rel = electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ # The impedance of the series resistance Z_Rs = Rs # The (RQ) circuit in series with the transmission line Z_RQ1 = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL(w, L, Rs, R, fs, n, Rel, Ri, Q="none"): """ Simulation Function: -R-TL- (interfacial reacting, i.e. non-blocking) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R = Interfacial charge transfer resistance [ohm * cm] fs = Summit frequency for the interfacial RQ element [Hz] n = Exponenet for interfacial RQ element [-] Q = Constant phase element for the interfacial capacitance [s^n/ohm] Rel = Electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = Thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Phi = cir_RQ(w, R=R, Q=Q, n=n, fs=fs) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL(w, L, Rs, R1, fs1, n1, R2, fs2, n2, Rel, Ri, Q1="none", Q2="none"): """ Simulation Function: -R-RQ-TL- (interfacial reacting, i.e. non-blocking) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = exponent for RQ circuit [-] Q1 = constant phase element of RQ circuit [s^n/(ohm * cm)] R2 = interfacial charge transfer resistance [ohm * cm] fs2 = Summit frequency for the interfacial RQ element [Hz] n2 = exponenet for interfacial RQ element [-] Q2 = Constant phase element for the interfacial capacitance [s^n/ohm] Rel = electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ # The impedance of the series resistance Z_Rs = Rs # The (RQ) circuit in series with the transmission line Z_RQ1 = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) # The Interfacial impedance is given by an -(RQ)- circuit Phi = cir_RQ(w, R=R2, Q=Q2, n=n2, fs=fs2) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL # Transmission lines with solid-state transport def cir_RsTL_1Dsolid(w, L, D, radius, Rs, R, Q, n, R_w, n_w, Rel, Ri): """ Simulation Function: -R-TL(Q(RW))- Transmission line w/ full complexity, which both includes Ri and Rel Warburg element is specific for 1D solid-state diffusion Refs: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - <NAME>. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Illig, J., Physically based Impedance Modelling of Lithium-ion Cells, KIT Scientific Publishing (2014) - Scipioni, et al., ECS Transactions, 69 (18) 71-80 (2015) <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R = particle charge transfer resistance [ohm*cm^2] Q = Summit frequency peak of RQ element in the modified randles element of a particle [Hz] n = exponenet for internal RQ element in the modified randles element of a particle [-] Rel = electronic resistance of electrode [ohm/cm] Ri = ionic resistance of solution in flooded pores of electrode [ohm/cm] R_w = polarization resistance of finite diffusion Warburg element [ohm] n_w = exponent for Warburg element [-] L = thickness of porous electrode [cm] D = solid-state diffusion coefficient [cm^2/s] radius = average particle radius [cm] Output -------------- Impedance of Rs-TL(Q(RW)) """ # The impedance of the series resistance Z_Rs = Rs # The impedance of a 1D Warburg Element time_const = (radius ** 2) / D x = (time_const * w * 1j) ** n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) Z_w = R_w * np.array(warburg_coth_mp) / x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R Z_Q = elem_Q(w, Q=Q, n=n) Z_Randles = 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) # Ohm # The Impedance of the Transmission Line lamb = (Z_Randles / (Rel + Ri)) ** (1 / 2) x = L / lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * lamb) / sinh(x))) + lamb * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL_1Dsolid( w, L, D, radius, Rs, R1, fs1, n1, R2, Q2, n2, R_w, n_w, Rel, Ri, Q1="none" ): """ Simulation Function: -R-RQ-TL(Q(RW))- Transmission line w/ full complexity, which both includes Ri and Rel Warburg element is specific for 1D solid-state diffusion Refs: - <NAME>., and <NAME>., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - <NAME>. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" - <NAME>., Physically based Impedance Modelling of Lithium-ion Cells, KIT Scientific Publishing (2014) - Scipioni, et al., ECS Transactions, 69 (18) 71-80 (2015) <NAME> (<EMAIL>) <NAME> (<EMAIL> || <EMAIL>) Inputs ------------------ Rs = Series resistance [ohm] R1 = charge transfer resistance of the interfacial RQ element [ohm*cm^2] fs1 = max frequency peak of the interfacial RQ element[Hz] n1 = exponenet for interfacial RQ element R2 = particle charge transfer resistance [ohm*cm^2] Q2 = Summit frequency peak of RQ element in the modified randles element of a particle [Hz] n2 = exponenet for internal RQ element in the modified randles element of a particle [-] Rel = electronic resistance of electrode [ohm/cm] Ri = ionic resistance of solution in flooded pores of electrode [ohm/cm] R_w = polarization resistance of finite diffusion Warburg element [ohm] n_w = exponent for Warburg element [-] L = thickness of porous electrode [cm] D = solid-state diffusion coefficient [cm^2/s] radius = average particle radius [cm] Output ------------------ Impedance of R-RQ-TL(Q(RW)) """ # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Z_RQ = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) # The impedance of a 1D Warburg Element time_const = (radius ** 2) / D x = (time_const * w * 1j) ** n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) Z_w = R_w * np.array(warburg_coth_mp) / x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R2 Z_Q = elem_Q(w, Q=Q2, n=n2) Z_Randles = 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) # Ohm # The Impedance of the Transmission Line lamb = (Z_Randles / (Rel + Ri)) ** (1 / 2) x = L / lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * lamb) / sinh(x))) + lamb * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ + Z_TL ### Fitting Circuit Functions ## # def elem_C_fit(params, w): """ Fit Function: -C- """ C = params["C"] return 1 / (C * (w * 1j)) def elem_Q_fit(params, w): """ Fit Function: -Q- Constant Phase Element for Fitting """ Q = params["Q"] n = params["n"] return 1 / (Q * (w * 1j) ** n) def cir_RsC_fit(params, w): """ Fit Function: -Rs-C- """ Rs = params["Rs"] C = params["C"] return Rs + 1 / (C * (w * 1j)) def cir_RsQ_fit(params, w): """ Fit Function: -Rs-Q- """ Rs = params["Rs"] Q = params["Q"] n = params["n"] return Rs + 1 / (Q * (w * 1j) ** n) def cir_RC_fit(params, w): """ Fit Function: -RC- Returns the impedance of an RC circuit, using RQ definations where n=1 """ if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["C"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("C") == -1: # elif Q == 'none': R = params["R"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["C"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] Q = params["C"] return cir_RQ(w, R=R, Q=C, n=1, fs=fs) def cir_RQ_fit(params, w): """ Fit Function: -RQ- Return the impedance of an RQ circuit: Z(w) = R / (1+ R*Q * (2w)^n) See Explanation of equations under cir_RQ() The params.keys()[10:] finds the names of the user defined parameters that should be interated over if X == -1, if the paramter is not given, it becomes equal to 'none' <NAME> (<EMAIL> / <EMAIL>) """ if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("Q") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] n = params["n"] Q = params["Q"] return R / (1 + R * Q * (w * 1j) ** n) def cir_RsRQ_fit(params, w): """ Fit Function: -Rs-RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RsRQ_fit() <NAME> (<EMAIL> / <EMAIL>) """ if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("Q") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] Q = params["Q"] n = params["n"] Rs = params["Rs"] return Rs + (R / (1 + R * Q * (w * 1j) ** n)) def cir_RsRQRQ_fit(params, w): """ Fit Function: -Rs-RQ-RQ- Return the impedance of an Rs-RQ circuit. See details under cir_RsRQRQ() <NAME> (<EMAIL> / <EMAIL>) """ if str(params.keys())[10:].find("'R'") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("'Q'") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("'n'") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("'fs'") == -1: # elif fs == 'none': R = params["R"] Q = params["Q"] n = params["n"] if str(params.keys())[10:].find("'R2'") == -1: # if R == 'none': Q2 = params["Q2"] n2 = params["n2"] fs2 = params["fs2"] R2 = 1 / (Q2 * (2 * np.pi * fs2) ** n2) if str(params.keys())[10:].find("'Q2'") == -1: # elif Q == 'none': R2 = params["R2"] n2 = params["n2"] fs2 = params["fs2"] Q2 = 1 / (R2 * (2 * np.pi * fs2) ** n2) if str(params.keys())[10:].find("'n2'") == -1: # elif n == 'none': R2 = params["R2"] Q2 = params["Q2"] fs2 = params["fs2"] n2 = np.log(Q2 * R2) / np.log(1 / (2 * np.pi * fs2)) if str(params.keys())[10:].find("'fs2'") == -1: # elif fs == 'none': R2 = params["R2"] Q2 = params["Q2"] n2 = params["n2"] Rs = params["Rs"] return ( Rs + (R / (1 + R * Q * (w * 1j) ** n)) + (R2 / (1 + R2 * Q2 * (w * 1j) ** n2)) ) def cir_Randles_simplified_Fit(params, w): """ Fit Function: Randles simplified -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit. See more under cir_Randles_simplified() NOTE: This Randles circuit is only meant for semi-infinate linear diffusion <NAME> (<EMAIL> || <EMAIL>) """ if str(params.keys())[10:].find("'R'") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("'Q'") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("'n'") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("'fs'") == -1: # elif fs == 'none': R = params["R"] Q = params["Q"] n = params["n"] Rs = params["Rs"] sigma = params["sigma"] Z_Q = 1 / (Q * (w * 1j) ** n) Z_R = R Z_w = sigma * (w ** (-0.5)) - 1j * sigma * (w ** (-0.5)) return Rs + 1 / (1 / Z_Q + 1 / (Z_R + Z_w)) def cir_RsRQQ_fit(params, w): """ Fit Function: -Rs-RQ-Q- See cir_RsRQQ() for details """ Rs = params["Rs"] Q = params["Q"] n = params["n"] Z_Q = 1 / (Q * (w * 1j) ** n) if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) return Rs + Z_RQ + Z_Q def cir_RsRQC_fit(params, w): """ Fit Function: -Rs-RQ-C- See cir_RsRQC() for details """ Rs = params["Rs"] C = params["C"] Z_C = 1 / (C * (w * 1j)) if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) return Rs + Z_RQ + Z_C def cir_RsRCC_fit(params, w): """ Fit Function: -Rs-RC-C- See cir_RsRCC() for details """ Rs = params["Rs"] R1 = params["R1"] C1 = params["C1"] C = params["C"] return Rs + cir_RC(w, C=C1, R=R1, fs="none") + elem_C(w, C=C) def cir_RsRCQ_fit(params, w): """ Fit Function: -Rs-RC-Q- See cir_RsRCQ() for details """ Rs = params["Rs"] R1 = params["R1"] C1 = params["C1"] Q = params["Q"] n = params["n"] return Rs + cir_RC(w, C=C1, R=R1, fs="none") + elem_Q(w, Q, n) # Polymer electrolytes def cir_C_RC_C_fit(params, w): """ Fit Function: -C-(RC)-C- See cir_C_RC_C() for details <NAME> (<EMAIL> || <EMAIL>) """ # Interfacial impedance Ce = params["Ce"] Z_C = 1 / (Ce * (w * 1j)) # Bulk impendance if str(params.keys())[10:].find("Rb") == -1: # if R == 'none': Cb = params["Cb"] fsb = params["fsb"] Rb = 1 / (Cb * (2 * np.pi * fsb)) if str(params.keys())[10:].find("Cb") == -1: # elif Q == 'none': Rb = params["Rb"] fsb = params["fsb"] Cb = 1 / (Rb * (2 * np.pi * fsb)) if str(params.keys())[10:].find("fsb") == -1: # elif fs == 'none': Rb = params["Rb"] Cb = params["Cb"] Z_RC = Rb / (1 + Rb * Cb * (w * 1j)) return Z_C + Z_RC def cir_Q_RQ_Q_Fit(params, w): """ Fit Function: -Q-(RQ)-Q- See cir_Q_RQ_Q() for details <NAME> (<EMAIL> || <EMAIL>) """ # Interfacial impedance Qe = params["Qe"] ne = params["ne"] Z_Q = 1 / (Qe * (w * 1j) ** ne) # Bulk impedance if str(params.keys())[10:].find("Rb") == -1: # if R == 'none': Qb = params["Qb"] nb = params["nb"] fsb = params["fsb"] Rb = 1 / (Qb * (2 * np.pi * fsb) ** nb) if str(params.keys())[10:].find("Qb") == -1: # elif Q == 'none': Rb = params["Rb"] nb = params["nb"] fsb = params["fsb"] Qb = 1 / (Rb * (2 * np.pi * fsb) ** nb) if str(params.keys())[10:].find("nb") == -1: # elif n == 'none': Rb = params["Rb"] Qb = params["Qb"] fsb = params["fsb"] nb = np.log(Qb * Rb) / np.log(1 / (2 * np.pi * fsb)) if str(params.keys())[10:].find("fsb") == -1: # elif fs == 'none': Rb = params["Rb"] nb = params["nb"] Qb = params["Qb"] Z_RQ = Rb / (1 + Rb * Qb * (w * 1j) ** nb) return Z_Q + Z_RQ def cir_RCRCZD_fit(params, w): """ Fit Function: -RC_b-RC_e-Z_D See cir_RCRCZD() for details <NAME> (<EMAIL> || <EMAIL>) """ # Interfacial impendace if str(params.keys())[10:].find("Re") == -1: # if R == 'none': Ce = params["Ce"] fse = params["fse"] Re = 1 / (Ce * (2 * np.pi * fse)) if str(params.keys())[10:].find("Ce") == -1: # elif Q == 'none': Re = params["Rb"] fse = params["fsb"] Ce = 1 / (Re * (2 * np.pi * fse)) if str(params.keys())[10:].find("fse") == -1: # elif fs == 'none': Re = params["Re"] Ce = params["Ce"] Z_RCe = Re / (1 + Re * Ce * (w * 1j)) # Bulk impendance if str(params.keys())[10:].find("Rb") == -1: # if R == 'none': Cb = params["Cb"] fsb = params["fsb"] Rb = 1 / (Cb * (2 * np.pi * fsb)) if str(params.keys())[10:].find("Cb") == -1: # elif Q == 'none': Rb = params["Rb"] fsb = params["fsb"] Cb = 1 / (Rb * (2 * np.pi * fsb)) if str(params.keys())[10:].find("fsb") == -1: # elif fs == 'none': Rb = params["Rb"] Cb = params["Cb"] Z_RCb = Rb / (1 + Rb * Cb * (w * 1j)) # Mass transport impendance L = params["L"] D_s = params["D_s"] u1 = params["u1"] u2 = params["u2"] alpha = ((w * 1j * L ** 2) / D_s) ** (1 / 2) Z_D = Rb * (u2 / u1) * (tanh(alpha) / alpha) return Z_RCb + Z_RCe + Z_D # Transmission lines def cir_RsTLsQ_fit(params, w): """ Fit Function: -Rs-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) See more under cir_RsTLsQ() <NAME> (<EMAIL> / <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Q = params["Q"] n = params["n"] Phi = 1 / (Q * (w * 1j) ** n) X1 = Ri # ohm/cm Lam = (Phi / X1) ** (1 / 2) # np.sqrt(Phi/X1) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # # Z_TLsQ = Lam * X1 * coth_mp Z_TLsQ = Lam * X1 * coth(x) return Rs + Z_TLsQ def cir_RsRQTLsQ_Fit(params, w): """ Fit Function: -Rs-RQ-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) See more under cir_RsRQTLsQ <NAME> (<EMAIL> / <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Q = params["Q"] n = params["n"] if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) Phi = 1 / (Q * (w * 1j) ** n) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLsQ = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLsQ def cir_RsTLs_Fit(params, w): """ Fit Function: -Rs-RQ-TLs- TLs = Simplified Transmission Line, with a faradaic interfacial impedance (RQ) See mor under cir_RsTLs() <NAME> (<EMAIL> / <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("Q") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] n = params["n"] Q = params["Q"] Phi = R / (1 + R * Q * (w * 1j) ** n) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_TLs def cir_RsRQTLs_Fit(params, w): """ Fit Function: -Rs-RQ-TLs- TLs = Simplified Transmission Line with a faradaic interfacial impedance (RQ) See more under cir_RsRQTLs() <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) if str(params.keys())[10:].find("R2") == -1: # if R == 'none': Q2 = params["Q2"] n2 = params["n2"] fs2 = params["fs2"] R2 = 1 / (Q2 * (2 * np.pi * fs2) ** n2) if str(params.keys())[10:].find("Q2") == -1: # elif Q == 'none': R2 = params["R2"] n2 = params["n2"] fs2 = params["fs2"] Q2 = 1 / (R2 * (2 * np.pi * fs2) ** n1) if str(params.keys())[10:].find("n2") == -1: # elif n == 'none': R2 = params["R2"] Q2 = params["Q2"] fs2 = params["fs2"] n2 = np.log(Q2 * R2) / np.log(1 / (2 * np.pi * fs2)) if str(params.keys())[10:].find("fs2") == -1: # elif fs == 'none': R2 = params["R2"] n2 = params["n2"] Q2 = params["Q2"] Phi = R2 / (1 + R2 * Q2 * (w * 1j) ** n2) X1 = Ri Lam = (Phi / X1) ** (1 / 2) x = L / Lam x_mp = mp.matrix(x) # x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) # Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLs def cir_RsTLQ_fit(params, w): """ Fit Function: -R-TLQ- (interface non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Rel = params["Rel"] Q = params["Q"] n = params["n"] # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTLQ_fit(params, w): """ Fit Function: -R-RQ-TLQ- (interface non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Rel = params["Rel"] Q = params["Q"] n = params["n"] # The impedance of the series resistance Z_Rs = Rs # The (RQ) circuit in series with the transmission line if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) if str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) if str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ1 = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL_Fit(params, w): """ Fit Function: -R-TLQ- (interface reacting, i.e. non-blocking) Transmission line w/ full complexity, which both includes Ri and Rel See cir_RsTL() for details <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Rel = params["Rel"] # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R") == -1: # if R == 'none': Q = params["Q"] n = params["n"] fs = params["fs"] R = 1 / (Q * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("Q") == -1: # elif Q == 'none': R = params["R"] n = params["n"] fs = params["fs"] Q = 1 / (R * (2 * np.pi * fs) ** n) if str(params.keys())[10:].find("n") == -1: # elif n == 'none': R = params["R"] Q = params["Q"] fs = params["fs"] n = np.log(Q * R) / np.log(1 / (2 * np.pi * fs)) if str(params.keys())[10:].find("fs") == -1: # elif fs == 'none': R = params["R"] n = params["n"] Q = params["Q"] Phi = R / (1 + R * Q * (w * 1j) ** n) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL_fit(params, w): """ Fit Function: -R-RQ-TL- (interface reacting, i.e. non-blocking) Transmission line w/ full complexity including both includes Ri and Rel <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] Rel = params["Rel"] # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) elif str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) elif str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) elif str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ1 = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) # # # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R2") == -1: # if R == 'none': Q2 = params["Q2"] n2 = params["n2"] fs2 = params["fs2"] R2 = 1 / (Q2 * (2 * np.pi * fs2) ** n2) elif str(params.keys())[10:].find("Q2") == -1: # elif Q == 'none': R2 = params["R2"] n2 = params["n2"] fs2 = params["fs2"] Q2 = 1 / (R2 * (2 * np.pi * fs2) ** n1) elif str(params.keys())[10:].find("n2") == -1: # elif n == 'none': R2 = params["R2"] Q2 = params["Q2"] fs2 = params["fs2"] n2 = np.log(Q2 * R2) / np.log(1 / (2 * np.pi * fs2)) elif str(params.keys())[10:].find("fs2") == -1: # elif fs == 'none': R2 = params["R2"] n2 = params["n2"] Q2 = params["Q2"] Phi = R2 / (1 + R2 * Q2 * (w * 1j) ** n2) X1 = Ri X2 = Rel Lam = (Phi / (X1 + X2)) ** (1 / 2) x = L / Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float((mp.coth(x_mp[i]).imag))*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(((1-mp.exp(-2*x_mp[i]))/(2*mp.exp(-x_mp[i]))).real) + float(((1-mp.exp(-2*x_mp[i]))/(2*mp.exp(-x_mp[i]))).real)*1j) # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float((mp.sinh(x_mp[i]).imag))*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * Lam) / sinh(x))) + Lam * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL_1Dsolid_fit(params, w): """ Fit Function: -R-TL(Q(RW))- Transmission line w/ full complexity See cir_RsTL_1Dsolid() for details <NAME> (<EMAIL>) <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] radius = params["radius"] D = params["D"] R = params["R"] Q = params["Q"] n = params["n"] R_w = params["R_w"] n_w = params["n_w"] Rel = params["Rel"] Ri = params["Ri"] # The impedance of the series resistance Z_Rs = Rs # The impedance of a 1D Warburg Element time_const = (radius ** 2) / D x = (time_const * w * 1j) ** n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) Z_w = R_w * np.array(warburg_coth_mp) / x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R Z_Q = elem_Q(w=w, Q=Q, n=n) Z_Randles = 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) # Ohm # The Impedance of the Transmission Line lamb = (Z_Randles / (Rel + Ri)) ** (1 / 2) x = L / lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * lamb) / sinh(x))) + lamb * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL_1Dsolid_fit(params, w): """ Fit Function: -R-RQ-TL(Q(RW))- Transmission line w/ full complexity, which both includes Ri and Rel. The Warburg element is specific for 1D solid-state diffusion See cir_RsRQTL_1Dsolid() for details <NAME> (<EMAIL>) <NAME> (<EMAIL> || <EMAIL>) """ Rs = params["Rs"] L = params["L"] Ri = params["Ri"] radius = params["radius"] D = params["D"] R2 = params["R2"] Q2 = params["Q2"] n2 = params["n2"] R_w = params["R_w"] n_w = params["n_w"] Rel = params["Rel"] Ri = params["Ri"] # The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R1") == -1: # if R == 'none': Q1 = params["Q1"] n1 = params["n1"] fs1 = params["fs1"] R1 = 1 / (Q1 * (2 * np.pi * fs1) ** n1) elif str(params.keys())[10:].find("Q1") == -1: # elif Q == 'none': R1 = params["R1"] n1 = params["n1"] fs1 = params["fs1"] Q1 = 1 / (R1 * (2 * np.pi * fs1) ** n1) elif str(params.keys())[10:].find("n1") == -1: # elif n == 'none': R1 = params["R1"] Q1 = params["Q1"] fs1 = params["fs1"] n1 = np.log(Q1 * R1) / np.log(1 / (2 * np.pi * fs1)) elif str(params.keys())[10:].find("fs1") == -1: # elif fs == 'none': R1 = params["R1"] n1 = params["n1"] Q1 = params["Q1"] Z_RQ1 = R1 / (1 + R1 * Q1 * (w * 1j) ** n1) # The impedance of a 1D Warburg Element time_const = (radius ** 2) / D x = (time_const * w * 1j) ** n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append( float(mp.coth(x_mp[i]).real) + float(mp.coth(x_mp[i]).imag) * 1j ) Z_w = R_w * np.array(warburg_coth_mp) / x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R2 Z_Q = elem_Q(w, Q=Q2, n=n2) Z_Randles = 1 / (1 / Z_Q + 1 / (Z_Rct + Z_w)) # Ohm # The Impedance of the Transmission Line lamb = (Z_Randles / (Rel + Ri)) ** (1 / 2) x = L / lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel * Ri) / (Rel + Ri)) * (L + ((2 * lamb) / sinh(x))) + lamb * ( (Rel ** 2 + Ri ** 2) / (Rel + Ri) ) * coth(x) return Z_Rs + Z_RQ1 + Z_TL ### Least-Squares error function def leastsq_errorfunc(params, w, re, im, circuit, weight_func): """ Sum of squares error function for the complex non-linear least-squares fitting procedure (CNLS). The fitting function (lmfit) will use this function to iterate over until the total sum of errors is minimized. During the minimization the fit is weighed, and currently three different weigh options are avaliable: - modulus - unity - proportional Modulus is generially recommended as random errors and a bias can exist in the experimental data. <NAME> (<EMAIL> || <EMAIL>) Inputs ------------ - params: parameters needed for CNLS - re: real impedance - im: Imaginary impedance - circuit: The avaliable circuits are shown below, and this this parameter needs it as a string. - C - Q - R-C - R-Q - RC - RQ - R-RQ - R-RQ-RQ - R-RQ-Q - R-(Q(RW)) - R-(Q(RM)) - R-RC-C - R-RC-Q - R-RQ-Q - R-RQ-C - RC-RC-ZD - R-TLsQ - R-RQ-TLsQ - R-TLs - R-RQ-TLs - R-TLQ - R-RQ-TLQ - R-TL - R-RQ-TL - R-TL1Dsolid (reactive interface with 1D solid-state diffusion) - R-RQ-TL1Dsolid - weight_func Weight function - modulus - unity - proportional """ if circuit == "C": re_fit = elem_C_fit(params, w).real im_fit = -elem_C_fit(params, w).imag elif circuit == "Q": re_fit = elem_Q_fit(params, w).real im_fit = -elem_Q_fit(params, w).imag elif circuit == "R-C": re_fit = cir_RsC_fit(params, w).real im_fit = -cir_RsC_fit(params, w).imag elif circuit == "R-Q": re_fit = cir_RsQ_fit(params, w).real im_fit = -cir_RsQ_fit(params, w).imag elif circuit == "RC": re_fit = cir_RC_fit(params, w).real im_fit = -cir_RC_fit(params, w).imag elif circuit == "RQ": re_fit = cir_RQ_fit(params, w).real im_fit = -cir_RQ_fit(params, w).imag elif circuit == "R-RQ": re_fit = cir_RsRQ_fit(params, w).real im_fit = -cir_RsRQ_fit(params, w).imag elif circuit == "R-RQ-RQ": re_fit = cir_RsRQRQ_fit(params, w).real im_fit = -cir_RsRQRQ_fit(params, w).imag elif circuit == "R-RC-C": re_fit = cir_RsRCC_fit(params, w).real im_fit = -cir_RsRCC_fit(params, w).imag elif circuit == "R-RC-Q": re_fit = cir_RsRCQ_fit(params, w).real im_fit = -cir_RsRCQ_fit(params, w).imag elif circuit == "R-RQ-Q": re_fit = cir_RsRQQ_fit(params, w).real im_fit = -cir_RsRQQ_fit(params, w).imag elif circuit == "R-RQ-C": re_fit = cir_RsRQC_fit(params, w).real im_fit = -cir_RsRQC_fit(params, w).imag elif circuit == "R-(Q(RW))": re_fit = cir_Randles_simplified_Fit(params, w).real im_fit = -cir_Randles_simplified_Fit(params, w).imag elif circuit == "R-(Q(RM))": re_fit = cir_Randles_uelectrode_fit(params, w).real im_fit = -cir_Randles_uelectrode_fit(params, w).imag elif circuit == "C-RC-C": re_fit = cir_C_RC_C_fit(params, w).real im_fit = -cir_C_RC_C_fit(params, w).imag elif circuit == "Q-RQ-Q": re_fit = cir_Q_RQ_Q_Fit(params, w).real im_fit = -cir_Q_RQ_Q_Fit(params, w).imag elif circuit == "RC-RC-ZD": re_fit = cir_RCRCZD_fit(params, w).real im_fit = -cir_RCRCZD_fit(params, w).imag elif circuit == "R-TLsQ": re_fit = cir_RsTLsQ_fit(params, w).real im_fit = -cir_RsTLsQ_fit(params, w).imag elif circuit == "R-RQ-TLsQ": re_fit = cir_RsRQTLsQ_Fit(params, w).real im_fit = -cir_RsRQTLsQ_Fit(params, w).imag elif circuit == "R-TLs": re_fit = cir_RsTLs_Fit(params, w).real im_fit = -cir_RsTLs_Fit(params, w).imag elif circuit == "R-RQ-TLs": re_fit = cir_RsRQTLs_Fit(params, w).real im_fit = -cir_RsRQTLs_Fit(params, w).imag elif circuit == "R-TLQ": re_fit = cir_RsTLQ_fit(params, w).real im_fit = -cir_RsTLQ_fit(params, w).imag elif circuit == "R-RQ-TLQ": re_fit = cir_RsRQTLQ_fit(params, w).real im_fit = -cir_RsRQTLQ_fit(params, w).imag elif circuit == "R-TL": re_fit = cir_RsTL_Fit(params, w).real im_fit = -cir_RsTL_Fit(params, w).imag elif circuit == "R-RQ-TL": re_fit = cir_RsRQTL_fit(params, w).real im_fit = -cir_RsRQTL_fit(params, w).imag elif circuit == "R-TL1Dsolid": re_fit = cir_RsTL_1Dsolid_fit(params, w).real im_fit = -cir_RsTL_1Dsolid_fit(params, w).imag elif circuit == "R-RQ-TL1Dsolid": re_fit = cir_RsRQTL_1Dsolid_fit(params, w).real im_fit = -cir_RsRQTL_1Dsolid_fit(params, w).imag else: print("Circuit is not defined in leastsq_errorfunc()") error = [(re - re_fit) ** 2, (im - im_fit) ** 2] # sum of squares # Different Weighing options, see Lasia if weight_func == "modulus": weight = [ 1 / ((re_fit ** 2 + im_fit ** 2) ** (1 / 2)), 1 / ((re_fit ** 2 + im_fit ** 2) ** (1 / 2)), ] elif weight_func == "proportional": weight = [1 / (re_fit ** 2), 1 / (im_fit ** 2)] elif weight_func == "unity": unity_1s = [] for k in range(len(re)): unity_1s.append( 1 ) # makes an array of [1]'s, so that the weighing is == 1 * sum of squres. weight = [unity_1s, unity_1s] else: print("weight not defined in leastsq_errorfunc()") S = np.array(weight) * error # weighted sum of squares return S ### Fitting Class class EIS_exp: """ This class is used to plot and/or analyze experimental impedance data. The class has three major functions: - EIS_plot() - Lin_KK() - EIS_fit() - EIS_plot() is used to plot experimental data with or without fit - Lin_KK() performs a linear Kramers-Kronig analysis of the experimental data set. - EIS_fit() performs complex non-linear least-squares fitting of the experimental data to an equivalent circuit <NAME> (<EMAIL> || <EMAIL>) Inputs ----------- - path: path of datafile(s) as a string - data: datafile(s) including extension, e.g. ['EIS_data1', 'EIS_data2'] - cycle: Specific cycle numbers can be extracted using the cycle function. Default is 'none', which includes all cycle numbers. Specific cycles can be extracted using this parameter, insert cycle numbers in brackets, e.g. cycle number 1,4, and 6 are wanted. cycle=[1,4,6] - mask: ['high frequency' , 'low frequency'], if only a high- or low-frequency is desired use 'none' for the other, e.g. maks=[10**4,'none'] """ def __init__(self, path, data, cycle="off", mask=["none", "none"]): self.df_raw0 = [] self.cycleno = [] for j, f in enumerate(data, start=0): if f.endswith("mpt"): # file is a .mpt file self.df_raw0.append( extract_mpt(path=path, EIS_name=f) ) # reads all datafiles elif f.endswith("DTA"): # file is a .dta file self.df_raw0.append( extract_dta(path=path, EIS_name=f) ) # reads all datafiles elif f.endswith("z"): # file is a .z file self.df_raw0.append( extract_solar(path=path, EIS_name=f) ) # reads all datafiles elif f.endswith("txt"): self.df_raw0.append(extract_csv(path=path, EIS_name=f)) else: print("Data file(s) could not be identified") self.cycleno.append(self.df_raw0[j].cycle_number) if np.min(self.cycleno[j]) <= np.max(self.cycleno[j - 1]): if j > 0: # corrects cycle_number except for the first data file self.df_raw0[j].update( {"cycle_number": self.cycleno[j] + np.max(self.cycleno[j - 1])} ) # corrects cycle number # currently need to append a cycle_number coloumn to gamry files # adds individual dataframes into one if len(self.df_raw0) == 1: self.df_raw = self.df_raw0[0] elif len(self.df_raw0) == 2: self.df_raw = pd.concat([self.df_raw0[0], self.df_raw0[1]], axis=0) elif len(self.df_raw0) == 3: self.df_raw = pd.concat( [self.df_raw0[0], self.df_raw0[1], self.df_raw0[2]], axis=0 ) elif len(self.df_raw0) == 4: self.df_raw = pd.concat( [self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3]], axis=0, ) elif len(self.df_raw0) == 5: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], ], axis=0, ) elif len(self.df_raw0) == 6: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], ], axis=0, ) elif len(self.df_raw0) == 7: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], ], axis=0, ) elif len(self.df_raw0) == 8: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], ], axis=0, ) elif len(self.df_raw0) == 9: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], ], axis=0, ) elif len(self.df_raw0) == 10: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], ], axis=0, ) elif len(self.df_raw0) == 11: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], ], axis=0, ) elif len(self.df_raw0) == 12: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], self.df_raw0[11], ], axis=0, ) elif len(self.df_raw0) == 13: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], self.df_raw0[11], self.df_raw0[12], ], axis=0, ) elif len(self.df_raw0) == 14: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], self.df_raw0[11], ], self.df_raw0[12], self.df_raw0[13], axis=0, ) elif len(self.df_raw0) == 15: self.df_raw = pd.concat( [ self.df_raw0[0], self.df_raw0[1], self.df_raw0[2], self.df_raw0[3], self.df_raw0[4], self.df_raw0[5], self.df_raw0[6], self.df_raw0[7], self.df_raw0[8], self.df_raw0[9], self.df_raw0[10], self.df_raw0[11], ], self.df_raw0[12], self.df_raw0[13], self.df_raw0[14], axis=0, ) else: print("Too many data files || 15 allowed") self.df_raw = self.df_raw.assign( w=2 * np.pi * self.df_raw.f ) # creats a new coloumn with the angular frequency # Masking data to each cycle self.df_pre = [] self.df_limited = [] self.df_limited2 = [] self.df = [] if mask == ["none", "none"] and cycle == "off": for i in range(len(self.df_raw.cycle_number.unique())): # includes all data self.df.append( self.df_raw[ self.df_raw.cycle_number == self.df_raw.cycle_number.unique()[i] ] ) elif mask == ["none", "none"] and cycle != "off": for i in range(len(cycle)): self.df.append( self.df_raw[self.df_raw.cycle_number == cycle[i]] ) # extracting dataframe for each cycle elif mask[0] != "none" and mask[1] == "none" and cycle == "off": self.df_pre = self.df_raw.mask(self.df_raw.f > mask[0]) self.df_pre.dropna(how="all", inplace=True) for i in range( len(self.df_pre.cycle_number.unique()) ): # Appending data based on cycle number self.df.append( self.df_pre[ self.df_pre.cycle_number == self.df_pre.cycle_number.unique()[i] ] ) elif ( mask[0] != "none" and mask[1] == "none" and cycle != "off" ): # or [i for i, e in enumerate(mask) if e == 'none'] == [0] self.df_limited = self.df_raw.mask(self.df_raw.f > mask[0]) for i in range(len(cycle)): self.df.append( self.df_limited[self.df_limited.cycle_number == cycle[i]] ) elif mask[0] == "none" and mask[1] != "none" and cycle == "off": self.df_pre = self.df_raw.mask(self.df_raw.f < mask[1]) self.df_pre.dropna(how="all", inplace=True) for i in range(len(self.df_raw.cycle_number.unique())): # includes all data self.df.append( self.df_pre[ self.df_pre.cycle_number == self.df_pre.cycle_number.unique()[i] ] ) elif mask[0] == "none" and mask[1] != "none" and cycle != "off": self.df_limited = self.df_raw.mask(self.df_raw.f < mask[1]) for i in range(len(cycle)): self.df.append( self.df_limited[self.df_limited.cycle_number == cycle[i]] ) elif mask[0] != "none" and mask[1] != "none" and cycle != "off": self.df_limited = self.df_raw.mask(self.df_raw.f < mask[1]) self.df_limited2 = self.df_limited.mask(self.df_raw.f > mask[0]) for i in range(len(cycle)): self.df.append( self.df_limited[self.df_limited2.cycle_number == cycle[i]] ) elif mask[0] != "none" and mask[1] != "none" and cycle == "off": self.df_limited = self.df_raw.mask(self.df_raw.f < mask[1]) self.df_limited2 = self.df_limited.mask(self.df_raw.f > mask[0]) for i in range(len(self.df_raw.cycle_number.unique())): self.df.append( self.df_limited[ self.df_limited2.cycle_number == self.df_raw.cycle_number.unique()[i] ] ) else: print("__init__ error (#2)") def Lin_KK( self, num_RC="auto", legend="on", plot="residuals", bode="off", nyq_xlim="none", nyq_ylim="none", weight_func="Boukamp", savefig="none", ): """ Plots the Linear Kramers-Kronig (KK) Validity Test The script is based on Boukamp and Schōnleber et al.'s papers for fitting the resistances of multiple -(RC)- circuits to the data. A data quality analysis can hereby be made on the basis of the relative residuals Ref.: - Schōnleber, M. et al. Electrochimica Acta 131 (2014) 20-27 - Boukamp, B.A. J. Electrochem. Soc., 142, 6, 1885-1894 The function performs the KK analysis and as default the relative residuals in each subplot Note, that weigh_func should be equal to 'Boukamp'. <NAME> (<EMAIL> || <EMAIL>) Optional Inputs ----------------- - num_RC: - 'auto' applies an automatic algorithm developed by Schōnleber, M. et al. Electrochimica Acta 131 (2014) 20-27 that ensures no under- or over-fitting occurs - can be hardwired by inserting any number (RC-elements/decade) - plot: - 'residuals' = plots the relative residuals in subplots correspoding to the cycle numbers picked - 'w_data' = plots the relative residuals with the experimental data, in Nyquist and bode plot if desired, see 'bode =' in description - nyq_xlim/nyq_xlim: Change the x/y-axis limits on nyquist plot, if not equal to 'none' state [min,max] value - legend: - 'on' = displays cycle number - 'potential' = displays average potential which the spectra was measured at - 'off' = off bode = Plots Bode Plot - options: 'on' = re, im vs. log(freq) 'log' = log(re, im) vs. log(freq) 're' = re vs. log(freq) 'log_re' = log(re) vs. log(freq) 'im' = im vs. log(freq) 'log_im' = log(im) vs. log(freq) """ if num_RC == "auto": print("cycle || No. RC-elements || u") self.decade = [] self.Rparam = [] self.t_const = [] self.Lin_KK_Fit = [] self.R_names = [] self.KK_R0 = [] self.KK_R = [] self.number_RC = [] self.number_RC_sort = [] self.KK_u = [] self.KK_Rgreater = [] self.KK_Rminor = [] M = 2 for i in range(len(self.df)): self.decade.append( np.log10(np.max(self.df[i].f)) - np.log10(np.min(self.df[i].f)) ) # determine the number of RC circuits based on the number of decades measured and num_RC self.number_RC.append(M) self.number_RC_sort.append(M) # needed for self.KK_R self.Rparam.append( KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC[i]), )[0] ) # Creates intial guesses for R's self.t_const.append( KK_timeconst(w=self.df[i].w, num_RC=int(self.number_RC[i])) ) # Creates time constants values for self.number_RC -(RC)- circuits self.Lin_KK_Fit.append( minimize( KK_errorfunc, self.Rparam[i], method="leastsq", args=( self.df[i].w.values, self.df[i].re.values, self.df[i].im.values, self.number_RC[i], weight_func, self.t_const[i], ), ) ) # maxfev=99 self.R_names.append( KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC[i]), )[1] ) # creates R names for j in range(len(self.R_names[i])): self.KK_R0.append( self.Lin_KK_Fit[i].params.get(self.R_names[i][j]).value ) self.number_RC_sort.insert(0, 0) # needed for self.KK_R for i in range(len(self.df)): self.KK_R.append( self.KK_R0[ int(np.cumsum(self.number_RC_sort)[i]) : int( np.cumsum(self.number_RC_sort)[i + 1] ) ] ) # assigns resistances from each spectra to their respective df self.KK_Rgreater.append( np.where(np.array(self.KK_R)[i] >= 0, np.array(self.KK_R)[i], 0) ) self.KK_Rminor.append( np.where(np.array(self.KK_R)[i] < 0, np.array(self.KK_R)[i], 0) ) self.KK_u.append( 1 - ( np.abs(np.sum(self.KK_Rminor[i])) / np.abs(np.sum(self.KK_Rgreater[i])) ) ) for i in range(len(self.df)): while self.KK_u[i] <= 0.75 or self.KK_u[i] >= 0.88: self.number_RC_sort0 = [] self.KK_R_lim = [] self.number_RC[i] = self.number_RC[i] + 1 self.number_RC_sort0.append(self.number_RC) self.number_RC_sort = np.insert(self.number_RC_sort0, 0, 0) self.Rparam[i] = KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC[i]), )[ 0 ] # Creates intial guesses for R's self.t_const[i] = KK_timeconst( w=self.df[i].w, num_RC=int(self.number_RC[i]) ) # Creates time constants values for self.number_RC -(RC)- circuits self.Lin_KK_Fit[i] = minimize( KK_errorfunc, self.Rparam[i], method="leastsq", args=( self.df[i].w.values, self.df[i].re.values, self.df[i].im.values, self.number_RC[i], weight_func, self.t_const[i], ), ) # maxfev=99 self.R_names[i] = KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC[i]), )[ 1 ] # creates R names self.KK_R0 = np.delete( np.array(self.KK_R0), np.s_[0 : len(self.KK_R0)] ) self.KK_R0 = [] for q in range(len(self.df)): for j in range(len(self.R_names[q])): self.KK_R0.append( self.Lin_KK_Fit[q].params.get(self.R_names[q][j]).value ) self.KK_R_lim = np.cumsum(self.number_RC_sort) # used for KK_R[i] self.KK_R[i] = self.KK_R0[ self.KK_R_lim[i] : self.KK_R_lim[i + 1] ] # assigns resistances from each spectra to their respective df self.KK_Rgreater[i] = np.where( np.array(self.KK_R[i]) >= 0, np.array(self.KK_R[i]), 0 ) self.KK_Rminor[i] = np.where( np.array(self.KK_R[i]) < 0, np.array(self.KK_R[i]), 0 ) self.KK_u[i] = 1 - ( np.abs(np.sum(self.KK_Rminor[i])) / np.abs(np.sum(self.KK_Rgreater[i])) ) else: print( "[" + str(i + 1) + "]" + " " + str(self.number_RC[i]), " " + str(np.round(self.KK_u[i], 2)), ) elif num_RC != "auto": # hardwired number of RC-elements/decade print("cycle || u") self.decade = [] self.number_RC0 = [] self.number_RC = [] self.Rparam = [] self.t_const = [] self.Lin_KK_Fit = [] self.R_names = [] self.KK_R0 = [] self.KK_R = [] for i in range(len(self.df)): self.decade.append( np.log10(np.max(self.df[i].f)) - np.log10(np.min(self.df[i].f)) ) # determine the number of RC circuits based on the number of decades measured and num_RC self.number_RC0.append(np.round(num_RC * self.decade[i])) self.number_RC.append( np.round(num_RC * self.decade[i]) ) # Creats the the number of -(RC)- circuits self.Rparam.append( KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC0[i]), )[0] ) # Creates intial guesses for R's self.t_const.append( KK_timeconst(w=self.df[i].w, num_RC=int(self.number_RC0[i])) ) # Creates time constants values for self.number_RC -(RC)- circuits self.Lin_KK_Fit.append( minimize( KK_errorfunc, self.Rparam[i], method="leastsq", args=( self.df[i].w.values, self.df[i].re.values, self.df[i].im.values, self.number_RC0[i], weight_func, self.t_const[i], ), ) ) # maxfev=99 self.R_names.append( KK_Rnam_val( re=self.df[i].re, re_start=self.df[i].re.idxmin(), num_RC=int(self.number_RC0[i]), )[1] ) # creates R names for j in range(len(self.R_names[i])): self.KK_R0.append( self.Lin_KK_Fit[i].params.get(self.R_names[i][j]).value ) self.number_RC0.insert(0, 0) # print(report_fit(self.Lin_KK_Fit[i])) # prints fitting report self.KK_circuit_fit = [] self.KK_rr_re = [] self.KK_rr_im = [] self.KK_Rgreater = [] self.KK_Rminor = [] self.KK_u = [] for i in range(len(self.df)): self.KK_R.append( self.KK_R0[ int(np.cumsum(self.number_RC0)[i]) : int( np.cumsum(self.number_RC0)[i + 1] ) ] ) # assigns resistances from each spectra to their respective df self.KK_Rx = np.array(self.KK_R) self.KK_Rgreater.append(np.where(self.KK_Rx[i] >= 0, self.KK_Rx[i], 0)) self.KK_Rminor.append(np.where(self.KK_Rx[i] < 0, self.KK_Rx[i], 0)) self.KK_u.append( 1 - ( np.abs(np.sum(self.KK_Rminor[i])) / np.abs(np.sum(self.KK_Rgreater[i])) ) ) # currently gives incorrect values print( "[" + str(i + 1) + "]" + " " + str(np.round(self.KK_u[i], 2)) ) else: print("num_RC incorrectly defined") self.KK_circuit_fit = [] self.KK_rr_re = [] self.KK_rr_im = [] for i in range(len(self.df)): if int(self.number_RC[i]) == 2: self.KK_circuit_fit.append( KK_RC2( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 3: self.KK_circuit_fit.append( KK_RC3( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 4: self.KK_circuit_fit.append( KK_RC4( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 5: self.KK_circuit_fit.append( KK_RC5( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 6: self.KK_circuit_fit.append( KK_RC6( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 7: self.KK_circuit_fit.append( KK_RC7( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 8: self.KK_circuit_fit.append( KK_RC8( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 9: self.KK_circuit_fit.append( KK_RC9( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 10: self.KK_circuit_fit.append( KK_RC10( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 11: self.KK_circuit_fit.append( KK_RC11( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 12: self.KK_circuit_fit.append( KK_RC12( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 13: self.KK_circuit_fit.append( KK_RC13( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 14: self.KK_circuit_fit.append( KK_RC14( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 15: self.KK_circuit_fit.append( KK_RC15( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 16: self.KK_circuit_fit.append( KK_RC16( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 17: self.KK_circuit_fit.append( KK_RC17( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 18: self.KK_circuit_fit.append( KK_RC18( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 19: self.KK_circuit_fit.append( KK_RC19( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 20: self.KK_circuit_fit.append( KK_RC20( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 21: self.KK_circuit_fit.append( KK_RC21( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 22: self.KK_circuit_fit.append( KK_RC22( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 23: self.KK_circuit_fit.append( KK_RC23( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 24: self.KK_circuit_fit.append( KK_RC24( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 25: self.KK_circuit_fit.append( KK_RC25( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 26: self.KK_circuit_fit.append( KK_RC26( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 27: self.KK_circuit_fit.append( KK_RC27( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 28: self.KK_circuit_fit.append( KK_RC28( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 29: self.KK_circuit_fit.append( KK_RC29( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 30: self.KK_circuit_fit.append( KK_RC30( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 31: self.KK_circuit_fit.append( KK_RC31( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 32: self.KK_circuit_fit.append( KK_RC32( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 33: self.KK_circuit_fit.append( KK_RC33( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 34: self.KK_circuit_fit.append( KK_RC34( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 35: self.KK_circuit_fit.append( KK_RC35( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 36: self.KK_circuit_fit.append( KK_RC36( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 37: self.KK_circuit_fit.append( KK_RC37( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 38: self.KK_circuit_fit.append( KK_RC38( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 39: self.KK_circuit_fit.append( KK_RC39( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 40: self.KK_circuit_fit.append( KK_RC40( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 41: self.KK_circuit_fit.append( KK_RC41( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 42: self.KK_circuit_fit.append( KK_RC42( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 43: self.KK_circuit_fit.append( KK_RC43( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 44: self.KK_circuit_fit.append( KK_RC44( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 45: self.KK_circuit_fit.append( KK_RC45( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 46: self.KK_circuit_fit.append( KK_RC46( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 47: self.KK_circuit_fit.append( KK_RC47( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 48: self.KK_circuit_fit.append( KK_RC48( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 49: self.KK_circuit_fit.append( KK_RC49( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 50: self.KK_circuit_fit.append( KK_RC50( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 51: self.KK_circuit_fit.append( KK_RC51( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 52: self.KK_circuit_fit.append( KK_RC52( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 53: self.KK_circuit_fit.append( KK_RC53( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 54: self.KK_circuit_fit.append( KK_RC54( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 55: self.KK_circuit_fit.append( KK_RC55( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 56: self.KK_circuit_fit.append( KK_RC56( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 57: self.KK_circuit_fit.append( KK_RC57( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 58: self.KK_circuit_fit.append( KK_RC58( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 59: self.KK_circuit_fit.append( KK_RC59( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 60: self.KK_circuit_fit.append( KK_RC60( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 61: self.KK_circuit_fit.append( KK_RC61( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 62: self.KK_circuit_fit.append( KK_RC62( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 63: self.KK_circuit_fit.append( KK_RC63( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 64: self.KK_circuit_fit.append( KK_RC64( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 65: self.KK_circuit_fit.append( KK_RC65( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 66: self.KK_circuit_fit.append( KK_RC66( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 67: self.KK_circuit_fit.append( KK_RC67( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 68: self.KK_circuit_fit.append( KK_RC68( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 69: self.KK_circuit_fit.append( KK_RC69( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 70: self.KK_circuit_fit.append( KK_RC70( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 71: self.KK_circuit_fit.append( KK_RC71( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 72: self.KK_circuit_fit.append( KK_RC72( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 73: self.KK_circuit_fit.append( KK_RC73( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 74: self.KK_circuit_fit.append( KK_RC74( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 75: self.KK_circuit_fit.append( KK_RC75( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 76: self.KK_circuit_fit.append( KK_RC76( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 77: self.KK_circuit_fit.append( KK_RC77( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 78: self.KK_circuit_fit.append( KK_RC78( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 79: self.KK_circuit_fit.append( KK_RC79( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) elif int(self.number_RC[i]) == 80: self.KK_circuit_fit.append( KK_RC80( w=self.df[i].w, Rs=self.Lin_KK_Fit[i].params.get("Rs").value, R_values=self.KK_R[i], t_values=self.t_const[i], ) ) else: print("RC simulation circuit not defined") print(" Number of RC = ", self.number_RC) self.KK_rr_re.append( residual_real( re=self.df[i].re, fit_re=self.KK_circuit_fit[i].real, fit_im=-self.KK_circuit_fit[i].imag, ) ) # relative residuals for the real part self.KK_rr_im.append( residual_imag( im=self.df[i].im, fit_re=self.KK_circuit_fit[i].real, fit_im=-self.KK_circuit_fit[i].imag, ) ) # relative residuals for the imag part ### Plotting Linear_kk results ## # ### Label functions self.label_re_1 = [] self.label_im_1 = [] self.label_cycleno = [] if legend == "on": for i in range(len(self.df)): self.label_re_1.append("Z' (#" + str(i + 1) + ")") self.label_im_1.append("Z'' (#" + str(i + 1) + ")") self.label_cycleno.append("#" + str(i + 1)) elif legend == "potential": for i in range(len(self.df)): self.label_re_1.append( "Z' (" + str(np.round(np.average(self.df[i].E_avg), 2)) + " V)" ) self.label_im_1.append( "Z'' (" + str(np.round(np.average(self.df[i].E_avg), 2)) + " V)" ) self.label_cycleno.append( str(np.round(np.average(self.df[i].E_avg), 2)) + " V" ) if plot == "w_data": fig = figure(figsize=(6, 8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust(left=0.1, right=0.95, hspace=0.5, bottom=0.1, top=0.95) ax = fig.add_subplot(311, aspect="equal") ax1 = fig.add_subplot(312) ax2 = fig.add_subplot(313) colors = sns.color_palette("colorblind", n_colors=len(self.df)) colors_real = sns.color_palette("Blues", n_colors=len(self.df) + 2) colors_imag = sns.color_palette("Oranges", n_colors=len(self.df) + 2) ### Nyquist Plot for i in range(len(self.df)): ax.plot( self.df[i].re, self.df[i].im, marker="o", ms=4, lw=2, color=colors[i], ls="-", alpha=0.7, label=self.label_cycleno[i], ) ### Bode Plot if bode == "on": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), self.df[i].re, color=colors_real[i + 1], marker="D", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_re_1[i], ) ax1.plot( np.log10(self.df[i].f), self.df[i].im, color=colors_imag[i + 1], marker="s", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_im_1[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("Z', -Z'' [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "re": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), self.df[i].re, color=colors_real[i + 1], marker="D", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_cycleno[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("Z' [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "log_re": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), np.log10(self.df[i].re), color=colors_real[i + 1], marker="D", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_cycleno[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("log(Z') [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "im": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), self.df[i].im, color=colors_imag[i + 1], marker="s", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_cycleno[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("-Z'' [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "log_im": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), np.log10(self.df[i].im), color=colors_imag[i + 1], marker="s", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_cycleno[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("log(-Z'') [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) elif bode == "log": for i in range(len(self.df)): ax1.plot( np.log10(self.df[i].f), np.log10(self.df[i].re), color=colors_real[i + 1], marker="D", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_re_1[i], ) ax1.plot( np.log10(self.df[i].f), np.log10(self.df[i].im), color=colors_imag[i + 1], marker="s", ms=3, lw=2.25, ls="-", alpha=0.7, label=self.label_im_1[i], ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("log(Z', -Z'') [$\Omega$]") if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ### Kramers-Kronig Relative Residuals for i in range(len(self.df)): ax2.plot( np.log10(self.df[i].f), self.KK_rr_re[i] * 100, color=colors_real[i + 1], marker="D", ls="--", ms=6, alpha=0.7, label=self.label_re_1[i], ) ax2.plot( np.log10(self.df[i].f), self.KK_rr_im[i] * 100, color=colors_imag[i + 1], marker="s", ls="--", ms=6, alpha=0.7, label=self.label_im_1[i], ) ax2.set_xlabel("log(f) [Hz]") ax2.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]") if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and write 'KK-Test' on RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if np.min(self.KK_rr_im_min) > np.min(self.KK_rr_re_min): ax2.set_ylim( np.min(self.KK_rr_re_min) * 100 * 1.5, np.max(np.abs(self.KK_rr_re_min)) * 100 * 1.5, ) ax2.annotate( "Lin-KK", xy=[ np.min(np.log10(self.df[0].f)), np.max(self.KK_rr_re_max) * 100 * 0.9, ], color="k", fontweight="bold", ) elif np.min(self.KK_rr_im_min) < np.min(self.KK_rr_re_min): ax2.set_ylim( np.min(self.KK_rr_im_min) * 100 * 1.5, np.max(self.KK_rr_im_max) * 100 * 1.5, ) ax2.annotate( "Lin-KK", xy=[ np.min(np.log10(self.df[0].f)), np.max(self.KK_rr_im_max) * 100 * 0.9, ], color="k", fontweight="bold", ) ### Figure specifics if legend == "on" or legend == "potential": ax.legend(loc="best", fontsize=10, frameon=False) ax.set_xlabel("Z' [$\Omega$]") ax.set_ylabel("-Z'' [$\Omega$]") if nyq_xlim != "none": ax.set_xlim(nyq_xlim[0], nyq_xlim[1]) if nyq_ylim != "none": ax.set_ylim(nyq_ylim[0], nyq_ylim[1]) # Save Figure if savefig != "none": fig.savefig(savefig) ### Illustrating residuals only elif plot == "residuals": colors = sns.color_palette("colorblind", n_colors=9) colors_real = sns.color_palette("Blues", n_colors=9) colors_imag = sns.color_palette("Oranges", n_colors=9) ### 1 Cycle if len(self.df) == 1: fig = figure(figsize=(12, 3.8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax = fig.add_subplot(231) ax.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax.set_xlabel("log(f) [Hz]") ax.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]") if legend == "on" or legend == "potential": ax.legend(loc="best", fontsize=10, frameon=False) ax.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and write 'KK-Test' on RR subplot self.KK_rr_im_min = np.min(self.KK_rr_im) self.KK_rr_im_max = np.max(self.KK_rr_im) self.KK_rr_re_min = np.min(self.KK_rr_re) self.KK_rr_re_max = np.max(self.KK_rr_re) if self.KK_rr_re_max > self.KK_rr_im_max: self.KK_ymax = self.KK_rr_re_max else: self.KK_ymax = self.KK_rr_im_max if self.KK_rr_re_min < self.KK_rr_im_min: self.KK_ymin = self.KK_rr_re_min else: self.KK_ymin = self.KK_rr_im_min if np.abs(self.KK_ymin) > self.KK_ymax: ax.set_ylim( self.KK_ymin * 100 * 1.5, np.abs(self.KK_ymin) * 100 * 1.5 ) if legend == "on": ax.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin) < self.KK_ymax: ax.set_ylim( np.negative(self.KK_ymax) * 100 * 1.5, np.abs(self.KK_ymax) * 100 * 1.5, ) if legend == "on": ax.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax * 100 * 1.3, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 2 Cycles elif len(self.df) == 2: fig = figure(figsize=(12, 5), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax2.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.3, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.3, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 3 Cycles elif len(self.df) == 3: fig = figure(figsize=(12, 5), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_xlabel("log(f) [Hz]") ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax2.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax3.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.3, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.3, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[2]) > self.KK_ymax[2]: ax3.set_ylim( self.KK_ymin[2] * 100 * 1.5, np.abs(self.KK_ymin[2]) * 100 * 1.5 ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[2]) < self.KK_ymax[2]: ax3.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[2]) * 100 * 1.5, ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymax[2]) * 100 * 1.3, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), self.KK_ymax[2] * 100 * 1.3, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 4 Cycles elif len(self.df) == 4: fig = figure(figsize=(12, 3.8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax2.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax3.set_xlabel("log(f) [Hz]") ax3.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 4 ax4.plot( np.log10(self.df[3].f), self.KK_rr_re[3] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax4.plot( np.log10(self.df[3].f), self.KK_rr_im[3] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax4.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax4.legend(loc="best", fontsize=10, frameon=False) ax4.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[2]) > self.KK_ymax[2]: ax3.set_ylim( self.KK_ymin[2] * 100 * 1.5, np.abs(self.KK_ymin[2]) * 100 * 1.5 ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[2]) < self.KK_ymax[2]: ax3.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[2]) * 100 * 1.5, ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymax[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), self.KK_ymax[2] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[3]) > self.KK_ymax[3]: ax4.set_ylim( self.KK_ymin[3] * 100 * 1.5, np.abs(self.KK_ymin[3]) * 100 * 1.5 ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[3]) < self.KK_ymax[3]: ax4.set_ylim( np.negative(self.KK_ymax[3]) * 100 * 1.5, np.abs(self.KK_ymax[3]) * 100 * 1.5, ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymax[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), self.KK_ymax[3] * 100 * 1.2, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 5 Cycles elif len(self.df) == 5: fig = figure(figsize=(12, 3.8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax3.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 4 ax4.plot( np.log10(self.df[3].f), self.KK_rr_re[3] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax4.plot( np.log10(self.df[3].f), self.KK_rr_im[3] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax4.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=18) ax4.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax4.legend(loc="best", fontsize=10, frameon=False) ax4.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 5 ax5.plot( np.log10(self.df[4].f), self.KK_rr_re[4] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax5.plot( np.log10(self.df[4].f), self.KK_rr_im[4] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax5.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax5.legend(loc="best", fontsize=10, frameon=False) ax5.axhline(0, ls="--", c="k", alpha=0.5) ### Setting ylims and labeling plot with 'KK-Test' in RR subplot self.KK_rr_im_min = [] self.KK_rr_im_max = [] self.KK_rr_re_min = [] self.KK_rr_re_max = [] self.KK_ymin = [] self.KK_ymax = [] for i in range(len(self.df)): self.KK_rr_im_min.append(np.min(self.KK_rr_im[i])) self.KK_rr_im_max.append(np.max(self.KK_rr_im[i])) self.KK_rr_re_min.append(np.min(self.KK_rr_re[i])) self.KK_rr_re_max.append(np.max(self.KK_rr_re[i])) if self.KK_rr_re_max[i] > self.KK_rr_im_max[i]: self.KK_ymax.append(self.KK_rr_re_max[i]) else: self.KK_ymax.append(self.KK_rr_im_max[i]) if self.KK_rr_re_min[i] < self.KK_rr_im_min[i]: self.KK_ymin.append(self.KK_rr_re_min[i]) else: self.KK_ymin.append(self.KK_rr_im_min[i]) if np.abs(self.KK_ymin[0]) > self.KK_ymax[0]: ax1.set_ylim( self.KK_ymin[0] * 100 * 1.5, np.abs(self.KK_ymin[0]) * 100 * 1.5 ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymin[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax1.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[0]) * 100 * 1.5, ) if legend == "on": ax1.annotate( "Lin-KK, #1", xy=[ np.min(np.log10(self.df[0].f)), np.abs(self.KK_ymax[0]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax1.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[0].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[0].f)), self.KK_ymax[0] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[1]) > self.KK_ymax[1]: ax2.set_ylim( self.KK_ymin[1] * 100 * 1.5, np.abs(self.KK_ymin[1]) * 100 * 1.5 ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), np.max(np.abs(self.KK_ymin[1])) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[0]) < self.KK_ymax[0]: ax2.set_ylim( np.negative(self.KK_ymax[1]) * 100 * 1.5, np.abs(self.KK_ymax[1]) * 100 * 1.5, ) if legend == "on": ax2.annotate( "Lin-KK, #2", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax2.annotate( "Lin-KK (" + str(np.round(np.average(self.df[1].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[1].f)), self.KK_ymax[1] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[2]) > self.KK_ymax[2]: ax3.set_ylim( self.KK_ymin[2] * 100 * 1.5, np.abs(self.KK_ymin[2]) * 100 * 1.5 ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymin[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[2]) < self.KK_ymax[2]: ax3.set_ylim( np.negative(self.KK_ymax[0]) * 100 * 1.5, np.abs(self.KK_ymax[2]) * 100 * 1.5, ) if legend == "on": ax3.annotate( "Lin-KK, #3", xy=[ np.min(np.log10(self.df[2].f)), np.abs(self.KK_ymax[2]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax3.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[2].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[2].f)), self.KK_ymax[2] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[3]) > self.KK_ymax[3]: ax4.set_ylim( self.KK_ymin[3] * 100 * 1.5, np.abs(self.KK_ymin[3]) * 100 * 1.5 ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymin[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[3]) < self.KK_ymax[3]: ax4.set_ylim( np.negative(self.KK_ymax[3]) * 100 * 1.5, np.abs(self.KK_ymax[3]) * 100 * 1.5, ) if legend == "on": ax4.annotate( "Lin-KK, #4", xy=[ np.min(np.log10(self.df[3].f)), np.abs(self.KK_ymax[3]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax4.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[3].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[3].f)), self.KK_ymax[3] * 100 * 1.2, ], color="k", fontweight="bold", ) if np.abs(self.KK_ymin[4]) > self.KK_ymax[4]: ax5.set_ylim( self.KK_ymin[4] * 100 * 1.5, np.abs(self.KK_ymin[4]) * 100 * 1.5 ) if legend == "on": ax5.annotate( "Lin-KK, #5", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymin[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax5.annotate( "Lin-KK (" + str(np.round(np.average(self.df[4].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymin[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif np.abs(self.KK_ymin[4]) < self.KK_ymax[4]: ax5.set_ylim( np.negative(self.KK_ymax[4]) * 100 * 1.5, np.abs(self.KK_ymax[4]) * 100 * 1.5, ) if legend == "on": ax5.annotate( "Lin-KK, #5", xy=[ np.min(np.log10(self.df[4].f)), np.abs(self.KK_ymax[4]) * 100 * 1.2, ], color="k", fontweight="bold", ) elif legend == "potential": ax5.annotate( "Lin-KK, (" + str(np.round(np.average(self.df[4].E_avg), 2)) + " V)", xy=[ np.min(np.log10(self.df[4].f)), self.KK_ymax[4] * 100 * 1.2, ], color="k", fontweight="bold", ) # Save Figure if savefig != "none": fig.savefig(savefig) ### 6 Cycles elif len(self.df) == 6: fig = figure(figsize=(12, 3.8), dpi=120, facecolor="w", edgecolor="k") fig.subplots_adjust( left=0.1, right=0.95, hspace=0.25, wspace=0.25, bottom=0.1, top=0.95 ) ax1 = fig.add_subplot(231) ax2 = fig.add_subplot(232) ax3 = fig.add_subplot(233) ax4 = fig.add_subplot(234) ax5 = fig.add_subplot(235) ax6 = fig.add_subplot(236) # cycle 1 ax1.plot( np.log10(self.df[0].f), self.KK_rr_re[0] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax1.plot( np.log10(self.df[0].f), self.KK_rr_im[0] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax1.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=15) if legend == "on" or legend == "potential": ax1.legend(loc="best", fontsize=10, frameon=False) ax1.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 2 ax2.plot( np.log10(self.df[1].f), self.KK_rr_re[1] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax2.plot( np.log10(self.df[1].f), self.KK_rr_im[1] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax2.legend(loc="best", fontsize=10, frameon=False) ax2.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 3 ax3.plot( np.log10(self.df[2].f), self.KK_rr_re[2] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax3.plot( np.log10(self.df[2].f), self.KK_rr_im[2] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) if legend == "on" or legend == "potential": ax3.legend(loc="best", fontsize=10, frameon=False) ax3.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 4 ax4.plot( np.log10(self.df[3].f), self.KK_rr_re[3] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax4.plot( np.log10(self.df[3].f), self.KK_rr_im[3] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax4.set_xlabel("log(f) [Hz]") ax4.set_ylabel("$\Delta$Z', $\Delta$-Z'' [%]", fontsize=15) if legend == "on" or legend == "potential": ax4.legend(loc="best", fontsize=10, frameon=False) ax4.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 5 ax5.plot( np.log10(self.df[4].f), self.KK_rr_re[4] * 100, color=colors_real[3], marker="D", ls="--", ms=6, alpha=0.7, label="$\Delta$Z'", ) ax5.plot( np.log10(self.df[4].f), self.KK_rr_im[4] * 100, color=colors_imag[3], marker="s", ls="--", ms=6, alpha=0.7, label="$\Delta$-Z''", ) ax5.set_xlabel("log(f) [Hz]") if legend == "on" or legend == "potential": ax5.legend(loc="best", fontsize=10, frameon=False) ax5.axhline(0, ls="--", c="k", alpha=0.5) # Cycle 6 ax6.plot(
np.log10(self.df[5].f)
numpy.log10
import copy import numpy as np import os import collections import time import random import tfg.alphaZeroConfig as config from tfg.strategies import Strategy, MonteCarloTree from tfg.alphaZeroNN import NeuralNetworkAZ from tfg.util import play, get_games_per_worker from tfg.games import BLACK, WHITE from functools import reduce from joblib import delayed, Parallel from threading import Barrier, Thread class AlphaZero(Strategy): """Game strategy implementing AlphaZero algorithm.""" def __init__(self, env, adapter, c_puct=config.C_PUCT, exploration_noise=config.EXPLORATION_NOISE, mcts_iter=config.MCTS_ITER, mcts_max_time=config.MCTS_MAX_TIME, nn_config=None, gpu=True): """All default values are taken from tfg.alphaZeroConfig Args: env (tfg.games.GameEnv): Game this strategy is for. adapter (tfg.alphaZeroAdapters.NeuralNetworkAdapter): Adapter for the game given as env. c_puct (float): C constant used in the selection policy PUCT algorithm. exploration_noise ((float, float)): Values used to add Dirichlet noise to the first node of MCTS. First number is the noise fraction (between 0 and 1), which means how much noise will be added. The second number is the alpha of the Dirichlet distribution. mcts_iter (int): Max iterations of the MCTS algorithm. mcts_max_time (float): Max time for the MCTS algorithm. nn_config (tfg.alphaZeroConfig.AlphaZeroConfig or dict): Wrapper with arguments that will be directly passed to tfg.alphaZeroNN.AlphaZeroNN. If output_dim is None, env.action_space.n will be used instead. gpu (bool): Whether to allow gpu usage for the internal neural network or not. Note that Tensorflow should not have been imported before creating the actor. Defaults to True. """ if nn_config is None: nn_config = config.AlphaZeroConfig() elif isinstance(nn_config, dict): nn_config = config.AlphaZeroConfig(**nn_config) if not gpu: os.environ['CUDA_VISIBLE_DEVICES'] = '-1' self._env = env self.c_puct = c_puct self.noise_fraction = exploration_noise[0] self.noise_alpha = exploration_noise[1] self.temperature = 0 self._nn_input = None self._nn_barrier = None self._nn_predictions = None self._nn_predict = None self._thr_num_active = None self._thr_actions = None self._thr_sync = None self._mcts = MonteCarloTree( self._env, max_iter=mcts_iter, max_time=mcts_max_time, selection_policy=self._selection_policy, value_function=self._value_function, best_node_policy=self._best_node_policy, reset_tree=True ) self.neural_network = NeuralNetworkAZ( input_dim=adapter.input_shape, output_dim=adapter.output_features, **nn_config.__dict__ ) self._adapter = adapter self.training = True @property def env(self): """tfg.games.GameEnv: Game this strategy is for.""" return self._env def train(self, self_play_times=config.SELF_PLAY_TIMES, max_train_time=config.MAX_TRAIN_TIME, min_train_error=config.MIN_TRAIN_ERROR, max_games_counter=config.MAX_GAMES_COUNTER, epochs=config.EPOCHS, buffer_size=config.BUFFER_SIZE, batch_size=config.BATCH_SIZE, temperature=config.TEMPERATURE, callbacks=None): """Trains the internal neural network via self-play to learn how to play the game. All parameters default to the values given in tfg.alphaZeroConfig. Args: self_play_times (int): Number of games played before retraining the net. max_train_time (float): Maximum time the training can last. min_train_error (float): Minimum error below which the training will stop. max_games_counter (int): Maximum total number of games that can be played before stopping training. epochs (int): Number of epochs each batch will be trained with. buffer_size (int): Max number of states that can be stored before training. If this maximum is reached, oldest states will be removed when adding new ones. batch_size (int): Size of the batch to be sampled of all moves to train the network after self_play_times games have been played. temperature (int): During first moves of each game actions are taken randomly. This parameters sets how many times this will be done. callbacks (list[tfg.alphaZeroCallbacks.Callback]): Functions that will be called after every game and after every set of games to join the results. """ def is_done(): """Training ends if any of the following conditions is met: - Training time is over (current_time > max_train_time). - Error is lower than threshold (current_error < min_train_error). - Max number of played games reached (games_counter > max_games_counter). """ done = False if max_train_time is not None: done |= (current_time - start_time) > max_train_time if min_train_error is not None: done |= current_error < min_train_error if max_games_counter is not None: done |= games_counter >= max_games_counter return done self.training = True self._mcts.reset_tree = True # Initialize finishing parameters start_time = time.time() current_time = start_time current_error = float('inf') games_counter = 0 buffer = collections.deque(maxlen=buffer_size) while not is_done(): # Add to buffer the latest played games moves, callback_results = self._self_play( self_play_times, temperature, callbacks ) buffer.extend(moves) # Join callbacks if callbacks is not None: for callback, results in zip(callbacks, callback_results): callback.join(results) # Extract a mini-batch from buffer size = min(len(buffer), batch_size) mini_batch = random.sample(buffer, size) # Separate data from batch boards, turns, pies, rewards = zip(*mini_batch) train_boards = np.array([ self._adapter.to_input(board, turn) for board, turn in zip(boards, turns) ]) train_pi = np.array(list(pies)) train_reward = np.array(list(rewards)) # Train neural network with the data from the mini-batch history = self.neural_network.fit(x=train_boards, y=[train_reward, train_pi], batch_size=32, epochs=epochs, verbose=2, validation_split=0) # Update finishing parameters current_error = history.history['loss'][-1] current_time = time.time() games_counter += self_play_times print(f"Games played: {games_counter}") info = { 'error': current_error, 'time': current_time - start_time, 'games': games_counter } if callbacks is not None: for callback in callbacks: callback.on_update_end(self, info) def _self_play(self, num, temperature, callbacks): def make_policy(nodes): """Returns the pi vector according to temperature parameter.""" # Obtain visit vector from children visit_vector = np.zeros(self._adapter.output_features) for action, node in nodes.items(): indices = self._adapter.to_indices(action) visit_vector[indices] = node.visit_count if self.temperature > 0: # t = 1 | Exploration return visit_vector / visit_vector.sum() else: # t -> 0 | Exploitation # Vector with all 0s and a 1 in the most visited child index = np.unravel_index(np.argmax(visit_vector), visit_vector.shape) pi = np.zeros_like(visit_vector) pi[index] = 1 return pi def vale_function(i): return lambda node: self._value_function(node, i) def thread_run(index, mcts, obs, done): def f(): if not done: action = mcts.move(obs) self._thr_actions[index] = action while not self._thr_sync: self._nn_barrier.wait() return f def multi_predict(): if self._nn_predict: self._nn_predictions = self.neural_network.predict( self._nn_input ) self._nn_predict = False else: self._thr_sync = True callback_results = ([list() for _ in callbacks] if callbacks is not None else []) self._nn_input = np.zeros((num, *self._adapter.input_shape)) self._thr_actions = [None] * num self._thr_num_active = num self._nn_barrier = Barrier(num, action=multi_predict) envs = [copy.deepcopy(self._env) for _ in range(num)] mctss = [MonteCarloTree( env, max_iter=self._mcts.max_iter, max_time=self._mcts.max_time, selection_policy=self._selection_policy, value_function=vale_function(i), best_node_policy=self._best_node_policy, reset_tree=False ) for i, env in enumerate(envs)] # Initialize game observations = [env.reset() for env in envs] dones = [False] * num game_data = [list() for _ in range(num)] self.temperature = temperature s = time.time() # Loop until all games end while self._thr_num_active > 0: self._nn_predict = False self._thr_sync = False # Launch threads to choose moves from MCTS threads = [Thread(target=thread_run(i, mcts, o, d)) for i, (mcts, o, d) in enumerate(zip(mctss, observations, dones))] for thread in threads: thread.start() for thread in threads: thread.join() # Threads have been synchronized actions = self._thr_actions # Update temperature parameter self.temperature = max(0, self.temperature - 1) # Make all moves for i in range(num): if dones[i]: continue # Calculate Pi vector pi = make_policy(mctss[i].stats['actions']) # Store move data: (board, turn, pi) game_data[i].append((observations[i], envs[i].to_play, pi)) # Perform move observation, _, done, _ = envs[i].step(actions[i]) observations[i] = observation dones[i] = done # Update MCTS (used to recycle tree for next move) mctss[i].update(actions[i]) if done: self._thr_num_active -= 1 n = self._adapter.output_features pi =
np.full(n, 1 / n)
numpy.full
import os import numpy as np import torch import shutil def dice(vol1, vol2, labels=None, nargout=1): ''' Dice [1] volume overlap metric The default is to *not* return a measure for the background layer (label = 0) [1] Dice, <NAME>. "Measures of the amount of ecologic association between species." Ecology 26.3 (1945): 297-302. Parameters ---------- vol1 : nd array. The first volume (e.g. predicted volume) vol2 : nd array. The second volume (e.g. "true" volume) labels : optional vector of labels on which to compute Dice. If this is not provided, Dice is computed on all non-background (non-0) labels nargout : optional control of output arguments. if 1, output Dice measure(s). if 2, output tuple of (Dice, labels) Output ------ if nargout == 1 : dice : vector of dice measures for each labels if nargout == 2 : (dice, labels) : where labels is a vector of the labels on which dice was computed ''' if labels is None: labels = np.unique(
np.concatenate((vol1, vol2))
numpy.concatenate
#!/usr/bin/env python # # See top-level LICENSE file for Copyright information # # -*- coding: utf-8 -*- """ This script enables the viewing of a processed FITS file with extras. Run above the Science/ folder. """ import argparse import os import numpy as np from IPython import embed from astropy.io import fits from astropy.stats import sigma_clipped_stats from pypeit import msgs from pypeit import ginga from pypeit import slittrace from pypeit import specobjs from pypeit.core.parse import get_dnum from pypeit.images.imagebitmask import ImageBitMask from pypeit import masterframe from pypeit import spec2dobj def parser(options=None): parser = argparse.ArgumentParser(description='Display sky subtracted, spec2d image in a ' 'Ginga viewer. Run above the Science/ folder', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file', type = str, default = None, help = 'PYPIT spec2d file') parser.add_argument('--list', default=False, help='List the extensions only?', action='store_true') parser.add_argument('--det', default=1, type=int, help='Detector number') parser.add_argument('--showmask', default=False, help='Overplot masked pixels', action='store_true') parser.add_argument('--removetrace', default=False, help="Do not overplot traces in the skysub, " "sky_resid and resid channels", action = "store_true") parser.add_argument('--embed', default=False, help='Upon completion embed in ipython shell', action='store_true') parser.add_argument('--ignore_extract_mask', default=False, help='Ignore the extraction mask', action='store_true') return parser.parse_args() if options is None else parser.parse_args(options) def show_trace(specobjs, det, viewer, ch): if specobjs is None: return in_det = np.where(specobjs.DET == det)[0] for kk in in_det: trace = specobjs[kk]['TRACE_SPAT'] obj_id = specobjs[kk].NAME ginga.show_trace(viewer, ch, trace, obj_id, color='orange') #hdu.name) def main(args): # List only? if args.list: hdu = fits.open(args.file) hdu.info() return # Load it up spec2DObj = spec2dobj.Spec2DObj.from_file(args.file, args.det) # Setup for PYPIT imports msgs.reset(verbosity=2) # Init # TODO: get_dnum needs to be deprecated... sdet = get_dnum(args.det, prefix=False) # if not os.path.exists(mdir): # mdir_base = os.path.join(os.getcwd(), os.path.basename(mdir)) # msgs.warn('Master file dir: {0} does not exist. Using {1}'.format(mdir, mdir_base)) # mdir=mdir_base # Slits # slits_key = '{0}_{1:02d}'.format(spec2DObj.head0['TRACMKEY'], args.det) # slit_file = os.path.join(mdir, masterframe.construct_file_name(slittrace.SlitTraceSet, slits_key)) # slits = slittrace.SlitTraceSet.from_file(slit_file) # Grab the slit edges slits = spec2DObj.slits if spec2DObj.sci_spat_flexure is not None: msgs.info("Offseting slits by {}".format(spec2DObj.sci_spat_flexure)) all_left, all_right, mask = slits.select_edges(flexure=spec2DObj.sci_spat_flexure) # TODO -- This may be too restrictive, i.e. ignore BADFLTCALIB?? gpm = mask == 0 left = all_left[:, gpm] right = all_right[:, gpm] slid_IDs = spec2DObj.slits.slitord_id[gpm] bitMask = ImageBitMask() # Object traces from spec1d file spec1d_file = args.file.replace('spec2d', 'spec1d') if os.path.isfile(spec1d_file): sobjs = specobjs.SpecObjs.from_fitsfile(spec1d_file) else: sobjs = None msgs.warn('Could not find spec1d file: {:s}'.format(spec1d_file) + msgs.newline() + ' No objects were extracted.') ginga.connect_to_ginga(raise_err=True, allow_new=True) # Now show each image to a separate channel # Show the bitmask? mask_in = None if args.showmask: viewer, ch = ginga.show_image(spec2DObj.bpmmask, chname="BPM", waveimg=spec2DObj.waveimg, clear=True) #bpm, crmask, satmask, minmask, offslitmask, nanmask, ivar0mask, ivarnanmask, extractmask \ # SCIIMG image = spec2DObj.sciimg # Processed science image mean, med, sigma = sigma_clipped_stats(image[spec2DObj.bpmmask == 0], sigma_lower=5.0, sigma_upper=5.0) cut_min = mean - 1.0 * sigma cut_max = mean + 4.0 * sigma chname_skysub='sciimg-det{:s}'.format(sdet) # Clear all channels at the beginning viewer, ch = ginga.show_image(image, chname=chname_skysub, waveimg=spec2DObj.waveimg, clear=True) if sobjs is not None: show_trace(sobjs, args.det, viewer, ch) ginga.show_slits(viewer, ch, left, right, slit_ids=slid_IDs) # SKYSUB if args.ignore_extract_mask: # TODO -- Is there a cleaner way to do this? gpm = (spec2DObj.bpmmask == 0) | (spec2DObj.bpmmask == 2**bitMask.bits['EXTRACT']) else: gpm = spec2DObj.bpmmask == 0 image = (spec2DObj.sciimg - spec2DObj.skymodel) * gpm #(spec2DObj.mask == 0) # sky subtracted image mean, med, sigma = sigma_clipped_stats(image[spec2DObj.bpmmask == 0], sigma_lower=5.0, sigma_upper=5.0) cut_min = mean - 1.0 * sigma cut_max = mean + 4.0 * sigma chname_skysub='skysub-det{:s}'.format(sdet) # Clear all channels at the beginning # TODO: JFH For some reason Ginga crashes when I try to put cuts in here. viewer, ch = ginga.show_image(image, chname=chname_skysub, waveimg=spec2DObj.waveimg, bitmask=bitMask, mask=mask_in) #, cuts=(cut_min, cut_max),wcs_match=True) if not args.removetrace and sobjs is not None: show_trace(sobjs, args.det, viewer, ch) ginga.show_slits(viewer, ch, left, right, slit_ids=slid_IDs) # SKRESIDS chname_skyresids = 'sky_resid-det{:s}'.format(sdet) image = (spec2DObj.sciimg - spec2DObj.skymodel) * np.sqrt(spec2DObj.ivarmodel) * (spec2DObj.bpmmask == 0) # sky residual map viewer, ch = ginga.show_image(image, chname_skyresids, waveimg=spec2DObj.waveimg, cuts=(-5.0, 5.0), bitmask=bitMask, mask=mask_in) if not args.removetrace and sobjs is not None: show_trace(sobjs, args.det, viewer, ch) ginga.show_slits(viewer, ch, left, right, slit_ids=slid_IDs) # RESIDS chname_resids = 'resid-det{:s}'.format(sdet) # full model residual map image = (spec2DObj.sciimg - spec2DObj.skymodel - spec2DObj.objmodel) *
np.sqrt(spec2DObj.ivarmodel)
numpy.sqrt
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl import app import os import numpy as np import tensorflow as tf import cPickle as pkl from sklearn.model_selection import train_test_split from gensim.matutils import unitvec from gensim.models import Word2Vec, FastText from gensim.parsing.preprocessing import STOPWORDS from joblib import Parallel, delayed from scipy.special import expit from data.common import MODEL_DIR from data.wiki9 import split_wiki9_articles, WIKI9Articles from utils.word_utils import load_tf_embedding, load_glove_model from utils.sent_utils import iterate_minibatches_indices from membership.utils import compute_adversarial_advantage from membership.models import LinearMetricModel from collections import Counter, defaultdict from multiprocessing import Process, Pipe flags.DEFINE_float('noise_multiplier', 0., 'Ratio of the standard deviation to the clipping norm') flags.DEFINE_float('l2_norm_clip', 0., 'Clipping norm') flags.DEFINE_float('train_size', 0.2, 'Ratio of data for training the ' 'membership inference attack model') flags.DEFINE_integer('epoch', 4, 'Load model trained this epoch') flags.DEFINE_integer('microbatches', 128, 'microbatches') flags.DEFINE_integer('exp_id', 0, 'Experiment trial number') flags.DEFINE_integer('n_jobs', 16, 'number of CPU cores for parallel ' 'collecting metrics') flags.DEFINE_integer('window', 3, 'window size for a context of words') flags.DEFINE_integer('freq_min', 80, 'use word frequency rank above this percentile, ' 'e.g. 80=the most infrequent 20 percent words') flags.DEFINE_integer('freq_max', 100, 'maximum frequency rank') flags.DEFINE_string('metric', 'cosine', 'Metric to use for cosine similarity') flags.DEFINE_string('model', 'w2v', 'Word embedding model') flags.DEFINE_string('save_dir', os.path.join(MODEL_DIR, 'w2v'), 'Model directory for embedding model') flags.DEFINE_boolean('idf', False, 'Weight score by inverse document frequency') flags.DEFINE_boolean('ctx_level', False, 'Context level or article level inference') flags.DEFINE_boolean('learning', False, 'Whether to learning a metric model') FLAGS = flags.FLAGS tf.logging.set_verbosity(tf.logging.FATAL) def threshold_check(rank, thresh): if isinstance(thresh, tuple): return thresh[0] <= rank < thresh[1] else: assert isinstance(thresh, int) return thresh <= rank def get_all_contexts(docs, model, thresh, window=3): vocab = model.wv.vocab all_words = sorted(vocab.keys()) all_counts = 0. for word in all_words: all_counts += vocab[word].count all_docs_ctx = [] for text in WIKI9Articles(docs, verbose=1): doc_ctx = [] for i, word in enumerate(text): if word in vocab and threshold_check(vocab[word].index, thresh): s = max(0, i - window) e = min(len(text), i + window + 1) context = [neighbor for neighbor in text[s: i] + text[i + 1: e] if neighbor not in STOPWORDS and neighbor in vocab and neighbor != word] if len(context) == 0: continue context_pair = [(vocab[word].index, vocab[neighbor].index) for neighbor in context] doc_ctx.append(np.asarray(context_pair, dtype=np.int64)) # all_docs_ctx.append(np.asarray(context_pair, dtype=np.int64)) if len(doc_ctx) > 0: all_docs_ctx.append(doc_ctx) return all_docs_ctx def split_docs(docs, n_jobs): n_docs = len(docs) n_docs_per_job = n_docs // n_jobs + 1 splits = [] for i in range(n_jobs): splits.append(docs[i * n_docs_per_job: (i + 1) * n_docs_per_job]) return splits def trained_metric(exp_id=0, n_jobs=1, freqs=(80, 100), window=3, emb_model='ft'): train_docs, test_docs = split_wiki9_articles(exp_id) save_dir = FLAGS.save_dir model_name = 'wiki9_{}_{}.model'.format(emb_model, FLAGS.exp_id) model_path = os.path.join(save_dir, model_name) if emb_model == 'ft': model = FastText.load(model_path) elif emb_model == 'w2v': model = Word2Vec.load(model_path) elif emb_model == 'glove': model = load_glove_model(model_path) elif emb_model == 'tfw2v': model = load_tf_embedding(FLAGS.exp_id, save_dir=save_dir, epoch=FLAGS.epoch, noise_multiplier=FLAGS.noise_multiplier, l2_norm_clip=FLAGS.l2_norm_clip, microbatches=FLAGS.microbatches) else: raise ValueError('No such embedding model: {}'.format(emb_model)) word_vectors = model.wv.vectors word_emb = tf.convert_to_tensor(word_vectors) metric_model = LinearMetricModel(word_vectors.shape[1]) optimizer = tf.train.AdamOptimizer(5e-4) inputs_a = tf.placeholder(tf.int64, (None,), name="inputs_a") inputs_b = tf.placeholder(tf.int64, (None,), name="inputs_b") labels = tf.placeholder(tf.float32, (None,), name="labels") embs_a = tf.nn.embedding_lookup(word_emb, inputs_a) embs_b = tf.nn.embedding_lookup(word_emb, inputs_b) logits = metric_model.forward(embs_a, embs_b) if FLAGS.metric == 'cosine': embs_a = tf.nn.l2_normalize(embs_a, axis=1) embs_b = tf.nn.l2_normalize(embs_b, axis=1) dot = tf.reduce_sum(tf.multiply(embs_a, embs_b), axis=1) # loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=labels, logits=logits) loss = tf.keras.losses.hinge(labels, logits) loss = tf.reduce_mean(loss) t_vars = tf.trainable_variables() grads_and_vars = optimizer.compute_gradients(loss, t_vars) train_ops = optimizer.apply_gradients( grads_and_vars, global_step=tf.train.get_or_create_global_step()) vocab_size = len(model.wv.vocab) thresh = (int(vocab_size * freqs[0] / 100), int(vocab_size * freqs[1] / 100)) print("Loading contexts for membership inference") if n_jobs > 1: member_job_ctxs = Parallel(n_jobs)(delayed(get_all_contexts)( ds, model, thresh, window) for ds in split_docs(train_docs, n_jobs)) nonmember_job_ctxs = Parallel(n_jobs)(delayed(get_all_contexts)( ds, model, thresh, window) for ds in split_docs(test_docs, n_jobs)) member_ctxs = [ctxs for job_ctxs in member_job_ctxs for ctxs in job_ctxs] nonmember_ctxs = [ctxs for job_ctxs in nonmember_job_ctxs for ctxs in job_ctxs] else: member_ctxs = get_all_contexts(train_docs, model, thresh, window) nonmember_ctxs = get_all_contexts(test_docs, model, thresh, window) print("Loaded {} member and {} nonmember".format( len(member_ctxs), len(nonmember_ctxs))) membership_labels = np.concatenate( [np.ones(len(member_ctxs)), np.zeros(len(nonmember_ctxs))]) train_ctxs, test_ctxs, train_labels, test_labels = train_test_split( member_ctxs + nonmember_ctxs, membership_labels, random_state=12345, train_size=FLAGS.train_size, stratify=membership_labels) def flatten_ctxs(ctxs, labels): flat_ctxs, flat_labels = [], [] for doc_ctx, doc_label in zip(ctxs, labels): flat_ctxs += doc_ctx flat_labels.append(np.ones(len(doc_ctx)) * doc_label) return flat_ctxs, np.concatenate(flat_labels) train_ctxs, train_labels = flatten_ctxs(train_ctxs, train_labels) test_ctxs, test_labels = flatten_ctxs(test_ctxs, test_labels) train_y = [] for ctxs, label in zip(train_ctxs, train_labels): train_y.append(np.ones(len(ctxs)) * label) train_y = np.concatenate(train_y).astype(np.float32) train_x = np.vstack(train_ctxs) def collect_scores(ctxs, labels, sess, baseline=False): stacked_ctxs = np.vstack(ctxs) stacked_scores = [] for batch_idx in iterate_minibatches_indices( len(stacked_ctxs), batch_size=1024, shuffle=False): feed = {inputs_a: stacked_ctxs[batch_idx][:, 0], inputs_b: stacked_ctxs[batch_idx][:, 1]} scores = sess.run(dot if baseline else logits, feed_dict=feed) stacked_scores.append(scores) stacked_scores = np.concatenate(stacked_scores) member_metrics, nonmember_metrics = [], [] start_idx = 0 for ctx, label in zip(ctxs, labels): scores = stacked_scores[start_idx: start_idx + len(ctx)] start_idx += len(ctx) if label == 1: member_metrics.append(scores) else: nonmember_metrics.append(scores) return member_metrics, nonmember_metrics with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: sess.run(tf.global_variables_initializer()) test_member_metrics, test_nonmember_metrics = collect_scores( test_ctxs, test_labels, sess, True) compute_adversarial_advantage( [
np.mean(m)
numpy.mean
import os import sys import shutil import traceback import logging import numpy as np import pandas as pd import contextlib import base64 # import matplotlib # matplotlib.use("Agg") from yattag import Doc from yattag import indent import cv2 import matplotlib.pyplot as plt from matplotlib import cm from sklearn.metrics import roc_curve, roc_auc_score logger = logging.getLogger(__name__) ################################################## class Plotter(object): ''' class Plotter 将训练过程中的数值化输出保存成html以及csv文件进行记录 用法: 1. 初始化: plotter = Plotter() 2. 记录: plotter.scalar('loss1', step=10, value=0.1) 3. 输出到html文件: plotter.to_html_report('./experiment/plt') 4. 输出所有数据分别到单独的csv文件中: plotter.to_csv('./experiment/plt') ''' def __init__(self, args=None): self._scalar_data_frame_dict = {} self._dist_data_frame_dict = {} self._out_svg_list = [] self._upper_bound = {} self._lower_bound = {} self.args = args def _check_dir(self, path): p = os.path.dirname(path) if not os.path.exists(p): os.mkdir(p) return p def set_min_max(self, name, min_val=None, max_val=None): if min_val is not None: self._lower_bound[name] = min_val if max_val is not None: self._upper_bound[name] = max_val @property def scalar_names(self): return list(self._scalar_data_frame_dict.keys()) def get(self, name): if name in self._scalar_data_frame_dict: return self._scalar_data_frame_dict[name] elif name in self._dist_data_frame_dict: return self._dist_data_frame_dict[name] else: return None def has(self, name): return name in self._scalar_data_frame_dict or name in self._dist_data_frame_dict def keys(self): return list(self._scalar_data_frame_dict.keys()) + list(self._dist_data_frame_dict.keys()) def roc_auc(self, name, step, y_score, y_true): auc_score = roc_auc_score(y_true, y_score) self.scalar(name, step, auc_score) def add_roc_curve(self, name, y_score, y_true, output_dir): try: output_svg_filepath = os.path.join(output_dir, name + '.svg') plt.figure() plt.clf() fpr, tpr, thres = roc_curve(y_true, y_score) plt.plot(fpr, tpr) plt.grid(axis='y') plt.grid(axis='x', which='major') plt.grid(axis='x', which='minor', color=[0.9, 0.9, 0.9]) plt.tight_layout() plt.savefig(output_svg_filepath) plt.close() self._out_svg_list.append([name, output_svg_filepath]) except Exception as e: logger.info('draw %s failed : '%name) traceback.print_exc() def add_prob_distribution_hist(self, name, y_probs, y_labels, output_dir): label_list = np.unique(y_labels) sorted(label_list) alpha_list = np.linspace(0.0, 0.9, len(label_list)+2)[2:] color_list = ["#0000FF", "#00FF00", "#FF0000", "#FFFF00", "#FF00FF"] assert np.max(y_probs) <= 1.0 assert np.min(y_probs) >= 0.0 try: output_svg_filepath = os.path.join(output_dir, name + '.svg') bins = np.linspace(0.0, 1.0, 100) plt.figure() plt.clf() for ind, l in enumerate(label_list): plt.hist(y_probs[np.where(y_labels == l)[0]], bins, density=True, color=color_list[ind%len(color_list)], alpha=alpha_list[ind]) plt.tight_layout() plt.savefig(output_svg_filepath) plt.close() self._out_svg_list.append([name, output_svg_filepath]) except Exception as e: logger.info('draw %s failed : '%name) traceback.print_exc() def scalar(self, name, step, value, epoch=None): if isinstance(value, dict): data = value.copy() data.update({ 'step' : step }) else: data = { 'step' : step, name : value, } if epoch is not None: data['epoch'] = epoch df = pd.DataFrame(data, index=[0]) if name not in self._scalar_data_frame_dict: self._scalar_data_frame_dict[name] = df else: self._scalar_data_frame_dict[name] = self._scalar_data_frame_dict[name].append(df, ignore_index=True) def scalar_probs(self, name, step, value_array, epoch=None): data_dict = {} for i in range(1, 10): thres = float(i) / 10.0 data_dict[str(thres)] = float((value_array < thres).sum()) / float(len(value_array)) self.scalar(name, step, data_dict, epoch=epoch) self.set_min_max(name, 0.0, 1.0) # def dist(self, name, step, mean, var, epoch=None): # if epoch is not None: # df = pd.DataFrame({'epoch' : epoch, 'step' : step, name+'_mean' : mean, name+'_var' : var }, index=[0]) # else: # df = pd.DataFrame({'step' : step, name+'_mean' : mean, name+'_var' : var, }, index=[0]) # if name not in self._dist_data_frame_dict: # self._dist_data_frame_dict[name] = df # else: # self._dist_data_frame_dict[name] = self._dist_data_frame_dict[name].append(df, ignore_index=True) # def dist2(self, name, step, value_list, epoch=None): # mean = np.mean(value_list) # var = np.var(value_list) # self.dist(name, step, mean, var, epoch=epoch) def to_csv(self, output_dir): " 将记录保存到多个csv文件里面,csv文件放在output_dir下面。" if not os.path.exists(output_dir): os.mkdir(output_dir) for name, data_frame in self._scalar_data_frame_dict.items(): csv_filepath = os.path.join(output_dir, 'scalar_'+name+'.csv') data_frame.to_csv(csv_filepath, index=False) for name, data_frame in self._dist_data_frame_dict.items(): csv_filepath = os.path.join(output_dir, 'dist_'+name+'.csv') data_frame.to_csv(csv_filepath, index=False) def from_csv(self, output_dir): " 从output_dir下面的csv文件里面读取并恢复记录 " csv_name_list = [fn.split('.')[0] for fn in os.listdir(output_dir) if fn.endswith('csv')] for name in csv_name_list: if name.startswith('scalar_'): in_csv = pd.read_csv(os.path.join(output_dir, name+'.csv')) self._scalar_data_frame_dict[name[len('scalar_'):]] = in_csv elif name.startswith('dist_'): self._dist_data_frame_dict[name[len('dist_'):]] = pd.read_csv(os.path.join(output_dir, name+'.csv')) def write_svg_all(self, output_dir): " 将所有记录绘制成svg图片 " for ind, (name, data_frame) in enumerate(self._scalar_data_frame_dict.items()): try: min_val = self._lower_bound.get(name, None) max_val = self._upper_bound.get(name, None) output_svg_filepath = os.path.join(output_dir, name+'.svg') plt.figure() plt.clf() headers = [hd for hd in data_frame.columns if hd not in ['step', 'epoch']] if len(headers) == 1: plt.plot(data_frame['step'], data_frame[name]) else: for hd in headers: plt.plot(data_frame['step'], data_frame[hd]) plt.legend(headers) if min_val is not None: plt.ylim(bottom=min_val) if max_val is not None: plt.ylim(top=max_val) plt.grid(axis='y') plt.grid(axis='x', which='major') plt.grid(axis='x', which='minor', color=[0.9, 0.9, 0.9]) plt.tight_layout() plt.savefig(output_svg_filepath) plt.close() except Exception as e: logger.info('draw %s failed : '%name) logger.info(data_frame) traceback.print_exc() for ind, (name, data_frame) in enumerate(self._dist_data_frame_dict.items()): output_svg_filepath = os.path.join(output_dir, name+'.svg') plt.figure() plt.clf() plt.errorbar(data_frame['step'], data_frame[name+'_mean'], yerr=data_frame[name+'_var']) plt.tight_layout() plt.savefig(output_svg_filepath) plt.close() def to_html_report(self, output_filepath): " 将所有记录整理成一个html报告 " self.write_svg_all(self._check_dir(output_filepath)) doc, tag, text = Doc().tagtext() with open(output_filepath, 'w') as outfile: with tag('html'): with tag('body'): title_idx = 1 if self.args is not None: with tag('h3'): text('{}. args'.format(title_idx)) title_idx += 1 key_list = list(self.args.keys()) sorted(key_list) with tag('div', style='display:inline-block;width:850px;padding:5px;margin-left:20px'): for key in key_list: with tag('div', style='display:inline-block;width:400px;'): text('{} : {}\n'.format(key, self.args[key])) with tag('h3'): text('{}. scalars'.format(title_idx)) title_idx += 1 data_frame_name_list = [n for n, d in self._scalar_data_frame_dict.items()] sorted(data_frame_name_list) for ind, name in enumerate(data_frame_name_list): with tag('div', style='display:inline-block'): with tag('h4', style='margin-left:20px'): text('(%d). '%(ind+1)+name) doc.stag("embed", style="width:800px;padding:5px;margin-left:20px", src=name+'.svg', type="image/svg+xml") with tag('h3'): text('{}. others'.format(title_idx)) title_idx += 1 for ind, (name, svg_path) in enumerate(self._out_svg_list): with tag('div', style='display:inline-block'): with tag('h4', style='margin-left:20px'): text('(%d). '%(ind+1)+name) doc.stag("embed", style="width:800px;padding:5px;margin-left:20px", src=name+'.svg', type="image/svg+xml") # with tag('h3'): # text('2. distributions') # for ind, (name, data_frame) in enumerate(self._dist_data_frame_dict.items()): # with tag('div', style='display:inline-block'): # with tag('h4', style='margin-left:20px'): # text('(%d). '%(ind+1)+name) # doc.stag("embed", style="width:800px;padding:5px;margin-left:20px", src=name+'.svg', type="image/svg+xml") result = indent(doc.getvalue()) outfile.write(result) class RecordInterface(object): def start_draw(self): raise NotImplementedError() def draw_image(self, image, title=''): raise NotImplementedError() # def draw_svg(self, image, title=''): # raise NotImplementedError(); def _check_dir(self, path): if not os.path.exists(path): os.mkdir(path) return path class RecordData(object): def draw(self, draw_interface): raise NotImplementedError() def cv2_imread(filepath): filein = np.fromfile(filepath, dtype=np.uint8) cv_img = cv2.imdecode(filein, cv2.IMREAD_COLOR) return cv_img def img_vertical_concat(images, pad=0, pad_value=255, pad_right=False): nb_images = len(images) h_list = [i.shape[0] for i in images] w_list = [w.shape[1] for w in images] if pad_right: max_w = np.max(w_list) images = [i if i.shape[1] == max_w else np.hstack([i, np.ones([i.shape[0], max_w-i.shape[1]]+list(i.shape[2:]), dtype=i.dtype)*pad_value]) for i in images] else: assert np.all(np.equal(w_list, w_list[0])) if pad != 0: images = [np.vstack([i, np.ones([pad,]+list(i.shape[1:]), dtype=i.dtype)*pad_value]) for i in images[:-1]] + [images[-1],] if not isinstance(images, list): images = [i for i in images] return np.vstack(images) def img_horizontal_concat(images, pad=0, pad_value=255, pad_bottom=False): nb_images = len(images) h_list = [i.shape[0] for i in images] w_list = [w.shape[1] for w in images] if pad_bottom: max_h =
np.max(h_list)
numpy.max
"""Implementations of QMIX for Checkers. Same as alg_qmix.py, except that Checkers global state has more components. """ import numpy as np import tensorflow as tf import sys import networks class Alg(object): def __init__(self, experiment, dimensions, stage=1, n_agents=1, tau=0.01, lr_Q=0.001, gamma=0.99, nn={}): """ Same as alg_qmix. Checkers state has more components Inputs: experiment - string dimensions - dictionary containing tensor dimensions (h,w,c) for tensor l for 1D vector stage - curriculum stage (always 2 for IAC and COMA) tau - target variable update rate lr_Q - learning rates for optimizer gamma - discount factor """ self.experiment = experiment if self.experiment == "checkers": # Global state self.rows_state = dimensions['rows_state'] self.columns_state = dimensions['columns_state'] self.channels_state = dimensions['channels_state'] self.l_state = n_agents * dimensions['l_state_one'] self.l_state_one_agent = dimensions['l_state_one'] self.l_state_other_agents = (n_agents-1) * dimensions['l_state_one'] # Agent observations self.l_obs_others = dimensions['l_obs_others'] self.l_obs_self = dimensions['l_obs_self'] # Dimensions for image input self.rows_obs = dimensions['rows_obs'] self.columns_obs = dimensions['columns_obs'] self.channels_obs = dimensions['channels_obs'] self.l_action = dimensions['l_action'] self.l_goal = dimensions['l_goal'] self.n_agents = n_agents self.tau = tau self.lr_Q = lr_Q self.gamma = gamma self.nn = nn self.agent_labels = np.eye(self.n_agents) self.actions = np.eye(self.l_action) # Initialize computational graph self.create_networks(stage) self.list_initialize_target_ops, self.list_update_target_ops = self.get_assign_target_ops(tf.trainable_variables()) self.create_train_op() def create_networks(self, stage): # Placeholders self.state_env = tf.placeholder(tf.float32, [None, self.rows_state, self.columns_state, self.channels_state], 'state_env') self.v_state = tf.placeholder(tf.float32, [None, self.l_state], 'v_state') self.v_goal_all = tf.placeholder(tf.float32, [None, self.n_agents*self.l_goal], 'v_goal_all') self.v_state_one_agent = tf.placeholder(tf.float32, [None, self.l_state_one_agent], 'v_state_one_agent') self.v_state_other_agents = tf.placeholder(tf.float32, [None, self.l_state_other_agents], 'v_state_other_agents') self.v_goal = tf.placeholder(tf.float32, [None, self.l_goal], 'v_goal') self.v_goal_others = tf.placeholder(tf.float32, [None, (self.n_agents-1)*self.l_goal], 'v_goal_others') self.v_labels = tf.placeholder(tf.float32, [None, self.n_agents]) self.action_others = tf.placeholder(tf.float32, [None, self.n_agents-1, self.l_action], 'action_others') if self.experiment == "checkers": self.obs_self_t = tf.placeholder(tf.float32, [None, self.rows_obs, self.columns_obs, self.channels_obs], 'obs_self_t') self.obs_self_v = tf.placeholder(tf.float32, [None, self.l_obs_self], 'obs_self_v') self.obs_others = tf.placeholder(tf.float32, [None, self.l_obs_others], 'obs_others') self.actions_prev = tf.placeholder(tf.float32, [None, self.l_action], 'action_prev') # Individual agent networks # output dimension is [time * n_agents, q-values] with tf.variable_scope("Agent_main"): if self.experiment == 'checkers': self.agent_qs = networks.Qmix_single_checkers(self.actions_prev, self.obs_self_t, self.obs_self_v, self.obs_others, self.v_goal, f1=self.nn['A_conv_f'], k1=self.nn['A_conv_k'], n_h1=self.nn['A_n_h1'], n_h2=self.nn['A_n_h2'], n_actions=self.l_action) with tf.variable_scope("Agent_target"): if self.experiment == 'checkers': self.agent_qs_target = networks.Qmix_single_checkers(self.actions_prev, self.obs_self_t, self.obs_self_v, self.obs_others, self.v_goal, f1=self.nn['A_conv_f'], k1=self.nn['A_conv_k'], n_h1=self.nn['A_n_h1'], n_h2=self.nn['A_n_h2'], n_actions=self.l_action) self.argmax_Q = tf.argmax(self.agent_qs, axis=1) self.argmax_Q_target = tf.argmax(self.agent_qs_target, axis=1) # To extract Q-value from agent_qs and agent_qs_target; [batch*n_agents, l_action] self.actions_1hot = tf.placeholder(tf.float32, [None, self.l_action], 'actions_1hot') self.q_selected = tf.reduce_sum(tf.multiply(self.agent_qs, self.actions_1hot), axis=1) self.mixer_q_input = tf.reshape( self.q_selected, [-1, self.n_agents] ) # [batch, n_agents] self.q_target_selected = tf.reduce_sum(tf.multiply(self.agent_qs_target, self.actions_1hot), axis=1) self.mixer_target_q_input = tf.reshape( self.q_target_selected, [-1, self.n_agents] ) # Mixing network with tf.variable_scope("Mixer_main"): self.mixer = networks.Qmix_mixer_checkers(self.mixer_q_input, self.state_env, self.v_state, self.v_goal_all, self.l_state, self.l_goal, self.n_agents, f1=self.nn['Q_conv_f'], k1=self.nn['Q_conv_k']) with tf.variable_scope("Mixer_target"): self.mixer_target = networks.Qmix_mixer_checkers(self.mixer_q_input, self.state_env, self.v_state, self.v_goal_all, self.l_state, self.l_goal, self.n_agents, f1=self.nn['Q_conv_f'], k1=self.nn['Q_conv_k']) def get_assign_target_ops(self, list_vars): # ops for equating main and target list_initial_ops = [] # ops for slow update of target toward main list_update_ops = [] list_Agent_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Agent_main') map_name_Agent_main = {v.name.split('main')[1] : v for v in list_Agent_main} list_Agent_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Agent_target') map_name_Agent_target = {v.name.split('target')[1] : v for v in list_Agent_target} if len(list_Agent_main) != len(list_Agent_target): raise ValueError("get_initialize_target_ops : lengths of Agent_main and Agent_target do not match") for name, var in map_name_Agent_main.items(): # create op that assigns value of main variable to # target variable of the same name list_initial_ops.append( map_name_Agent_target[name].assign(var) ) for name, var in map_name_Agent_main.items(): # incremental update of target towards main list_update_ops.append( map_name_Agent_target[name].assign( self.tau*var + (1-self.tau)*map_name_Agent_target[name] ) ) list_Mixer_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Mixer_main') map_name_Mixer_main = {v.name.split('main')[1] : v for v in list_Mixer_main} list_Mixer_target = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Mixer_target') map_name_Mixer_target = {v.name.split('target')[1] : v for v in list_Mixer_target} if len(list_Mixer_main) != len(list_Mixer_target): raise ValueError("get_initialize_target_ops : lengths of Mixer_main and Mixer_target do not match") # ops for equating main and target for name, var in map_name_Mixer_main.items(): # create op that assigns value of main variable to # target variable of the same name list_initial_ops.append( map_name_Mixer_target[name].assign(var) ) # ops for slow update of target toward main for name, var in map_name_Mixer_main.items(): # incremental update of target towards main list_update_ops.append( map_name_Mixer_target[name].assign( self.tau*var + (1-self.tau)*map_name_Mixer_target[name] ) ) return list_initial_ops, list_update_ops def run_actor(self, actions_prev, obs_others, obs_self_t, obs_self_v, goals, epsilon, sess): """ Get actions for all agents as a batch actions_prev - list of integers obs_others - list of vector or tensor describing other agents obs_self - list of observation grid centered on self goals - [n_agents, n_lanes] """ # convert to batch obs_others = np.array(obs_others) obs_self_t = np.array(obs_self_t) obs_self_v = np.array(obs_self_v) actions_prev_1hot = np.zeros([self.n_agents, self.l_action]) actions_prev_1hot[np.arange(self.n_agents), actions_prev] = 1 feed = {self.obs_others:obs_others, self.obs_self_t:obs_self_t, self.obs_self_v:obs_self_v, self.v_goal:goals, self.actions_prev: actions_prev_1hot} actions_argmax = sess.run(self.argmax_Q, feed_dict=feed) actions = np.zeros(self.n_agents, dtype=int) for idx in range(self.n_agents): if np.random.rand(1) < epsilon: actions[idx] = np.random.randint(0, self.l_action) else: actions[idx] = actions_argmax[idx] return actions def create_train_op(self): # TD target calculated in train_step() using Mixer_target self.td_target = tf.placeholder(tf.float32, [None], 'td_target') self.loss_mixer = tf.reduce_mean(tf.square(self.td_target - tf.squeeze(self.mixer))) self.mixer_opt = tf.train.AdamOptimizer(self.lr_Q) self.mixer_op = self.mixer_opt.minimize(self.loss_mixer) def create_summary(self): summaries_mixer = [tf.summary.scalar('loss_mixer', self.loss_mixer)] mixer_main_variables = [v for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Mixer_main')] for v in mixer_main_variables: summaries_Q.append(tf.summary.histogram(v.op.name, v)) grads = self.Q_opt.compute_gradients(self.loss_mixer, mixer_main_variables) for grad, var in grads: if grad is not None: summaries_Q.append( tf.summary.histogram(var.op.name+'/gradient', grad) ) self.summary_op_Q = tf.summary.merge(summaries_mixer) def process_actions(self, n_steps, actions): """ actions must have shape [time, agents], and values are action indices """ # Each row of actions is one time step, # row contains action indices for all agents # Convert to [time, agents, l_action] # so each agent gets its own 1-hot row vector actions_1hot = np.zeros([n_steps, self.n_agents, self.l_action], dtype=int) grid = np.indices((n_steps, self.n_agents)) actions_1hot[grid[0], grid[1], actions] = 1 # Convert to format [time*agents, agents-1, l_action] # so that the set of <n_agent> actions at each time step # is duplicated <n_agent> times, and each duplicate # now contains all <n_agent>-1 actions representing # the OTHER agents actions list_to_interleave = [] for n in range(self.n_agents): # extract all actions except agent n's action list_to_interleave.append( actions_1hot[:, np.arange(self.n_agents)!=n, :] ) # interleave actions_others_1hot = np.zeros([self.n_agents*n_steps, self.n_agents-1, self.l_action]) for n in range(self.n_agents): actions_others_1hot[n::self.n_agents, :, :] = list_to_interleave[n] # In-place reshape of actions to [time*n_agents, l_action] actions_1hot.shape = (n_steps*self.n_agents, self.l_action) return actions_1hot, actions_others_1hot def process_batch(self, batch): """ Extract quantities of the same type from batch. Format batch so that each agent at each time step is one batch entry. Duplicate global quantities <n_agents> times to be compatible with this scheme. """ # shapes are [time, ...original dims...] state_env = np.stack(batch[:,0]) # [time, grid] state_agents = np.stack(batch[:,1]) # [time, agents, l_state_one_agent] # note that *_local objects have shape # [time, agents, ...original dim...] obs_others = np.stack(batch[:,2]) # [time,agents,h,w,c] or [time, agents, obs_others] obs_self_t = np.stack(batch[:,3]) # [time,agents,row,column,channel] obs_self_v = np.stack(batch[:,4]) # [time,agents,l_obs_self] actions_prev = np.stack(batch[:,5]) actions = np.stack(batch[:,6]) # [time,agents] reward = np.stack(batch[:,7]) # [time] reward_local = np.stack(batch[:,8]) # [time,agents] state_env_next = np.stack(batch[:,9]) # [time, grid] state_agents_next = np.stack(batch[:,10]) # [time, agents, l_state_one_agent] obs_others_next = np.stack(batch[:,11]) # [time,agents,h,w,c] obs_self_t_next = np.stack(batch[:,12]) # [time,agents,row,column,channel] obs_self_v_next = np.stack(batch[:,13]) # [time,agents,l_obs_self] done = np.stack(batch[:,14]) # [time] goals = np.stack(batch[:,15]) # [time, agents, l_goal] batch = None n_steps = state_agents.shape[0] # For all global quantities, for each time step, # duplicate values <n_agents> times for # batch processing of all agents reward = np.repeat(reward, self.n_agents, axis=0) # In-place reshape for *_local quantities, # so that one time step for one agent is considered # one batch entry if self.experiment == 'checkers': obs_others.shape = (n_steps*self.n_agents, self.l_obs_others) obs_others_next.shape = (n_steps*self.n_agents, self.l_obs_others) obs_self_t.shape = (n_steps*self.n_agents, self.rows_obs, self.columns_obs, self.channels_obs) obs_self_t_next.shape = (n_steps*self.n_agents, self.rows_obs, self.columns_obs, self.channels_obs) obs_self_v.shape = (n_steps*self.n_agents, self.l_obs_self) obs_self_v_next.shape = (n_steps*self.n_agents, self.l_obs_self) reward_local.shape = (n_steps*self.n_agents) actions_1hot, actions_others_1hot = self.process_actions(n_steps, actions) actions_prev_1hot = np.zeros([n_steps, self.n_agents, self.l_action], dtype=int) grid = np.indices((n_steps, self.n_agents)) actions_prev_1hot[grid[0], grid[1], actions_prev] = 1 actions_prev_1hot.shape = (n_steps*self.n_agents, self.l_action) return n_steps, state_env, state_agents, obs_others, obs_self_t, obs_self_v, actions_prev_1hot, actions_1hot, actions_others_1hot, reward, reward_local, state_env_next, state_agents_next, obs_others_next, obs_self_t_next, obs_self_v_next, done, goals def process_goals(self, goals, n_steps): """ goals has shape [batch, n_agents, l_goal] convert to two streams: 1. [n_agents * n_steps, l_goal] : each row is goal for one agent, block of <n_agents> rows belong to one sampled transition from batch 2. [n_agents * n_steps, (n_agents-1)*l_goal] : each row is the goals of all OTHER agents, as a single row vector. Block of <n_agents> rows belong to one sampled transition from batch """ # Reshape so that one time step for one agent is one batch entry goals_self = np.reshape(goals, (n_steps*self.n_agents, self.l_goal)) goals_others = np.zeros((n_steps*self.n_agents, self.n_agents-1, self.l_goal)) for n in range(self.n_agents): goals_others[n::self.n_agents, :, :] = goals[:, np.arange(self.n_agents)!=n, :] # Reshape to be [n_agents * n_steps, (n_agents-1)*l_goal] goals_others.shape = (n_steps*self.n_agents, (self.n_agents-1)*self.l_goal) return goals_self, goals_others def process_global_state(self, v_global, n_steps): """ v_global has shape [n_steps, n_agents, l_state] Convert to three streams: 1. [n_agents * n_steps, l_state_one_agent] : each row is state of one agent, and a block of <n_agents> rows belong to one sampled transition from batch 2. [n_agents * n_steps, l_state_other_agents] : each row is the state of all OTHER agents, as a single row vector. A block of <n_agents> rows belong to one sampled transition from batch 3. [n_steps*n_agents, n_agents*l_state] : each row is concatenation of state of all agents For each time step, the row is duplicated <n_agents> times, since the same state s is used in <n_agents> different evaluations of Q(s,a^{-n},a^n) """ # Reshape into 2D, each block of <n_agents> rows correspond to one time step v_global_one_agent = np.reshape(v_global, (n_steps*self.n_agents, self.l_state_one_agent)) v_global_others = np.zeros((n_steps*self.n_agents, self.n_agents-1, self.l_state_one_agent)) for n in range(self.n_agents): v_global_others[n::self.n_agents, :, :] = v_global[:, np.arange(self.n_agents)!=n, :] # Reshape into 2D, each row is state of all other agents, each block of # <n_agents> rows correspond to one time step v_global_others.shape = (n_steps*self.n_agents, (self.n_agents-1)*self.l_state_one_agent) v_global_concated = np.reshape(v_global, (n_steps, self.l_state)) state = np.repeat(v_global_concated, self.n_agents, axis=0) return v_global_one_agent, v_global_others, state def train_step(self, sess, batch, epsilon, idx_train, summarize=False, writer=None): # Each agent for each time step is now a batch entry n_steps, state_env, state_agents, obs_others, obs_self_t, obs_self_v, actions_prev_1hot, actions_1hot, actions_others_1hot, reward, reward_local, state_env_next, state_agents_next, obs_others_next, obs_self_t_next, obs_self_v_next, done, goals = self.process_batch(batch) goals_all = np.reshape(goals, (n_steps, self.n_agents*self.l_goal)) goals_self, goals_others = self.process_goals(goals, n_steps) state_agents_next =
np.reshape(state_agents_next, (n_steps, self.l_state))
numpy.reshape
#!/usr/bin/env python3 import numpy as np import scipy.signal import sys def rand_matrix(N, M, seed): return np.arange(seed, seed+N*M, dtype=np.float64).reshape(N, M) * 3.141 def emit(name, array, alignment='3'): print(".global %s" % name) print(".align " + alignment) print("%s:" % name) bs = array.tobytes() for i in range(0, len(bs), 4): s = "" for n in range(4): s += "%02x" % bs[i+3-n] print(" .word 0x%s" % s) # Define the filter size if len(sys.argv) > 1: filter_size = int(sys.argv[1]) # Filter size must be odd assert(filter_size % 2 == 1), "The filter size must be an odd integer number" else: filter_size = 3 # Input image M = 64 N = 64 padding = int(filter_size/2) M_pad = M + 2*padding N_pad = N + 2*padding assert(M % 4 == 0), "Output image dimension must be divisible by 4, pad the input image accordingly" assert(N % 4 == 0), "Output image dimension must be divisible by 4, pad the input image accordingly" # Generate a random int64 input padded image image = np.around(rand_matrix(M_pad, N_pad, 1)).astype(np.int64) np.random.shuffle(image.flat) # Generate a random int64 filter gen_filter = np.around(rand_matrix(filter_size, filter_size, 0)).astype(np.int64) np.random.shuffle(gen_filter.flat) # Create the empty o matrix empty_o = np.zeros((M, N)).astype(np.int64) # Calculate the output matrix result = np.around(scipy.signal.convolve2d(np.flip(gen_filter), image, 'valid')).astype(np.int64) # https://stackoverflow.com/questions/41613155/what-does-scipy-signal-convolve2d-calculate # Calculate a checksum checksum = np.sum(result, dtype=np.int64) # Print information on display #print("Image:\n") #print(image) #print("Filter:\n") #print(gen_filter) #print("Results:\n") #print(result) #print("\n") #print(checksum) # Print information on file print(".section .data,\"aw\",@progbits") emit("M", np.array(M, dtype=np.uint64)) emit("N",
np.array(N, dtype=np.uint64)
numpy.array
# -*- coding: utf-8 -*- """ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and not-for-profit purposes, without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643- 7201, <EMAIL>, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. """ """ Classes to encapsulate parallel-jaw grasps in image space Author: <NAME> """ import numpy as np from autolab_core import Point from autolab_core import RigidTransform from perception import CameraIntrinsics class Grasp2D(object): """ Parallel-jaw grasp in image space. Attributes ---------- center : :obj:`autolab_core.Point` point in image space angle : float grasp axis angle with the camera x-axis depth : float depth of the grasp center in 3D space width : float distance between the jaws in meters camera_intr : :obj:`perception.CameraIntrinsics` frame of reference for camera that the grasp corresponds to contact_points : list of :obj:`numpy.ndarray` pair of contact points in image space contact_normals : list of :obj:`numpy.ndarray` pair of contact normals in image space """ def __init__(self, center, angle=0.0, depth=1.0, width=0.0, camera_intr=None, contact_points=None, contact_normals=None): self.center = center self.angle = angle self.depth = depth self.width = width # if camera_intr is none use default primesense camera intrinsics if not camera_intr: self.camera_intr = CameraIntrinsics('primesense_overhead', fx=525, fy=525, cx=319.5, cy=239.5, width=640, height=480) else: self.camera_intr = camera_intr self.contact_points = contact_points self.contact_normals = contact_normals frame = 'image' if camera_intr is not None: frame = camera_intr.frame if isinstance(center, np.ndarray): self.center = Point(center, frame=frame) @property def axis(self): """ Returns the grasp axis. """ return np.array([np.cos(self.angle), np.sin(self.angle)]) @property def approach_axis(self): return np.array([0,0,1]) @property def approach_angle(self): """ The angle between the grasp approach axis and camera optical axis. """ return 0.0 @property def frame(self): """ The name of the frame of reference for the grasp. """ if self.camera_intr is None: raise ValueError('Must specify camera intrinsics') return self.camera_intr.frame @property def width_px(self): """ Returns the width in pixels. """ if self.camera_intr is None: raise ValueError('Must specify camera intrinsics to compute gripper width in 3D space') # form the jaw locations in 3D space at the given depth p1 = Point(np.array([0, 0, self.depth]), frame=self.frame) p2 = Point(np.array([self.width, 0, self.depth]), frame=self.frame) # project into pixel space u1 = self.camera_intr.project(p1) u2 = self.camera_intr.project(p2) return np.linalg.norm(u1.data - u2.data) @property def endpoints(self): """ Returns the grasp endpoints """ p1 = self.center.data - (float(self.width_px) / 2) * self.axis p2 = self.center.data + (float(self.width_px) / 2) * self.axis return p1, p2 @property def feature_vec(self): """ Returns the feature vector for the grasp. v = [p1, p2, depth] where p1 and p2 are the jaw locations in image space """ p1, p2 = self.endpoints return np.r_[p1, p2, self.depth] @staticmethod def from_feature_vec(v, width=0.0, camera_intr=None): """ Creates a Grasp2D obj from a feature vector and additional parameters. Parameters ---------- v : :obj:`numpy.ndarray` feature vector, see Grasp2D.feature_vec width : float grasp opening width, in meters camera_intr : :obj:`perception.CameraIntrinsics` frame of reference for camera that the grasp corresponds to """ # read feature vec p1 = v[:2] p2 = v[2:4] depth = v[4] # compute center and angle center_px = (p1 + p2) / 2 center = Point(center_px, camera_intr.frame) axis = p2 - p1 if np.linalg.norm(axis) > 0: axis = axis / np.linalg.norm(axis) if axis[1] > 0: angle = np.arccos(axis[0]) else: angle = -np.arccos(axis[0]) return Grasp2D(center, angle, depth, width=width, camera_intr=camera_intr) def pose(self, grasp_approach_dir=None): """ Computes the 3D pose of the grasp relative to the camera. If an approach direction is not specified then the camera optical axis is used. Parameters ---------- grasp_approach_dir : :obj:`numpy.ndarray` approach direction for the grasp in camera basis (e.g. opposite to table normal) Returns ------- :obj:`autolab_core.RigidTransform` the transformation from the grasp to the camera frame of reference """ # check intrinsics if self.camera_intr is None: raise ValueError('Must specify camera intrinsics to compute 3D grasp pose') # compute 3D grasp center in camera basis grasp_center_im = self.center.data center_px_im = Point(grasp_center_im, frame=self.camera_intr.frame) grasp_center_camera = self.camera_intr.deproject_pixel(self.depth, center_px_im) grasp_center_camera = grasp_center_camera.data # compute 3D grasp axis in camera basis grasp_axis_im = self.axis grasp_axis_im = grasp_axis_im / np.linalg.norm(grasp_axis_im) grasp_axis_camera = np.array([grasp_axis_im[0], grasp_axis_im[1], 0]) grasp_axis_camera = grasp_axis_camera / np.linalg.norm(grasp_axis_camera) # convert to 3D pose grasp_rot_camera, _, _ = np.linalg.svd(grasp_axis_camera.reshape(3,1)) grasp_x_camera = grasp_approach_dir if grasp_approach_dir is None: grasp_x_camera = np.array([0,0,1]) # aligned with camera Z axis grasp_y_camera = grasp_axis_camera grasp_z_camera = np.cross(grasp_x_camera, grasp_y_camera) grasp_z_camera = grasp_z_camera / np.linalg.norm(grasp_z_camera) grasp_y_camera = np.cross(grasp_z_camera, grasp_x_camera) grasp_rot_camera = np.array([grasp_x_camera, grasp_y_camera, grasp_z_camera]).T if np.linalg.det(grasp_rot_camera) < 0: # fix possible reflections due to SVD grasp_rot_camera[:,0] = -grasp_rot_camera[:,0] T_grasp_camera = RigidTransform(rotation=grasp_rot_camera, translation=grasp_center_camera, from_frame='grasp', to_frame=self.camera_intr.frame) return T_grasp_camera @staticmethod def image_dist(g1, g2, alpha=1.0): """ Computes the distance between grasps in image space. Euclidean distance with alpha weighting of angles Parameters ---------- g1 : :obj:`Grasp2D` first grasp g2 : :obj:`Grasp2D` second grasp alpha : float weight of angle distance (rad to meters) Returns ------- float distance between grasps """ # point to point distances point_dist = np.linalg.norm(g1.center.data - g2.center.data) # axis distances dot = max(min(np.abs(g1.axis.dot(g2.axis)), 1.0), -1.0) axis_dist = np.arccos(dot) return point_dist + alpha * axis_dist class SuctionPoint2D(object): """ Suction grasp in image space. Attributes ---------- center : :obj:`autolab_core.Point` point in image space axis : :obj:`numpy.ndarray` normalized 3-vector representing the direction of the suction tip depth : float depth of the suction point in 3D space camera_intr : :obj:`perception.CameraIntrinsics` frame of reference for camera that the suction point corresponds to """ def __init__(self, center, axis=None, depth=1.0, camera_intr=None): if axis is None: axis = np.array([0,0,1]) self.center = center self.axis = axis frame = 'image' if camera_intr is not None: frame = camera_intr.frame if isinstance(center, np.ndarray): self.center = Point(center, frame=frame) if isinstance(axis, list): self.axis = np.array(axis) if np.abs(np.linalg.norm(self.axis) - 1.0) > 1e-3: raise ValueError('Illegal axis. Must be norm 1.') self.depth = depth # if camera_intr is none use default primesense camera intrinsics if not camera_intr: self.camera_intr = CameraIntrinsics('primesense_overhead', fx=525, fy=525, cx=319.5, cy=239.5, width=640, height=480) else: self.camera_intr = camera_intr @property def frame(self): """ The name of the frame of reference for the grasp. """ if self.camera_intr is None: raise ValueError('Must specify camera intrinsics') return self.camera_intr.frame @property def angle(self): """ The angle that the grasp pivot axis makes in image space. """ rotation_axis = np.cross(self.axis, np.array([0,0,1])) rotation_axis_image = np.array([rotation_axis[0], rotation_axis[1]]) angle = 0 if np.linalg.norm(rotation_axis) > 0: rotation_axis_image = rotation_axis_image / np.linalg.norm(rotation_axis_image) angle = np.arccos(rotation_axis_image[0]) if rotation_axis[1] < 0: angle = -angle return angle @property def approach_angle(self): """ The angle between the grasp approach axis and camera optical axis. """ dot = max(min(self.axis.dot(np.array([0,0,1])), 1.0), -1.0) return np.arccos(dot) @property def approach_axis(self): return self.axis @property def feature_vec(self): """ Returns the feature vector for the suction point. v = [center, axis, depth] """ return self.center.data @staticmethod def from_feature_vec(v, camera_intr=None, depth=None, axis=None): """ Creates a SuctionPoint2D obj from a feature vector and additional parameters. Parameters ---------- v : :obj:`numpy.ndarray` feature vector, see Grasp2D.feature_vec camera_intr : :obj:`perception.CameraIntrinsics` frame of reference for camera that the grasp corresponds to depth : float hard-set the depth for the suction grasp axis : :obj:`numpy.ndarray` normalized 3-vector specifying the approach direction """ # read feature vec center_px = v[:2] grasp_axis = np.array([0,0,-1]) if len(v.shape) > 2 and axis is None: grasp_axis = v[2:5] grasp_axis = grasp_axis / np.linalg.norm(grasp_axis) elif axis is not None: grasp_axis = axis grasp_depth = 0.5 if v.shape[0] > 5 and depth is None: grasp_depth = v[5] elif depth is not None: grasp_depth = depth # compute center and angle center = Point(center_px, camera_intr.frame) return SuctionPoint2D(center, grasp_axis, grasp_depth, camera_intr=camera_intr) def pose(self): """ Computes the 3D pose of the grasp relative to the camera. Returns ------- :obj:`autolab_core.RigidTransform` the transformation from the grasp to the camera frame of reference """ # check intrinsics if self.camera_intr is None: raise ValueError('Must specify camera intrinsics to compute 3D grasp pose') # compute 3D grasp center in camera basis suction_center_im = self.center.data center_px_im = Point(suction_center_im, frame=self.camera_intr.frame) suction_center_camera = self.camera_intr.deproject_pixel(self.depth, center_px_im) suction_center_camera = suction_center_camera.data # compute 3D grasp axis in camera basis suction_axis_camera = self.axis # convert to 3D pose suction_x_camera = suction_axis_camera suction_z_camera =
np.array([-suction_x_camera[1], suction_x_camera[0], 0])
numpy.array
import random import math import numpy as np; import matplotlib.pyplot as plt; # Flame Shaped Dataset def generator1(): rad = 2 num = 300 t = np.random.uniform(0.0, 2.0*np.pi, num) r = rad * np.sqrt(np.random.uniform(0.0, 1.0, num)) x1 = r * np.cos(t)+ np.random.uniform(0.0,0.6,300) y1 = r * np.sin(t)+ np.random.uniform(0.0,0.6,300) size = 4; dom = 0.125*3.14 + np.random.uniform(0.0,0.6,300)*1.25*3.14; x2= size*np.sin(dom) + np.random.uniform(0,2,300)*0.4; y2= size*np.cos(dom.T) + np.random.uniform(0,2,300)*0.4; cluster1 =[[0.0 for i in range(0,300)]for j in range(0,2)]; cluster1[0] = x1; cluster1[1] = y1; cluster2 =[[0.0 for i in range(0,300)]for j in range(0,2)]; cluster2[0] = x2; cluster2[1] = y2; cluster1 = np.array(cluster1); cluster2 = np.array(cluster2); cluster1 = cluster1.T; cluster2 = cluster2.T; input_array = np.concatenate((cluster1,cluster2),axis=0); return input_array; def gen_res_1(input_array,result1,result2): cluster1 = [[0 for i in range(0,2)]for j in range(0,300)]; cluster2 = [[0 for i in range(0,2)]for j in range(0,300)]; result1 = np.array(result1); result2 = np.array(result2); result1 = result1.T; result2 = result2.T; f1= plt.figure(1); for i in range(0,300): cluster1[i] = input_array[i]; j=0; for i in range(300,600): cluster2[j] = input_array[i]; j=j+1; print (input_array.shape); plt.title("Result 1"); plt.scatter(result1[0],result1[1],marker='^'); plt.scatter(result2[0],result2[1],marker='+'); cluster1 = np.array(cluster1); cluster2=
np.array(cluster2)
numpy.array
import pydart2 as pydart from SkateUtils.NonHolonomicWorld import NHWorldV3 import numpy as np import gym import gym.spaces import copy from skate_cma.BSpline import BSpline from skate_cma.PenaltyType import PenaltyType from PyCommon.modules.Math import mmMath as mm class SkateDartEnv(gym.Env): def __init__(self, env_name='speed_skating'): self.world = NHWorldV3(1./1200., '../data/skel/skater_3dof_with_ground.skel') self.world.control_skel = self.world.skeletons[1] self.skel = self.world.skeletons[1] # self.Kp, self.Kd = 400., 40. # self.Kp, self.Kd = 1000., 60. self.Kp, self.Kd = 600., 49. self.torque_max = 1000. self.total_time = 1. self.env_name = env_name self.ref_motion = None # type: ym.Motion self.ref_world = NHWorldV3(1./1200., '../data/skel/skater_3dof_with_ground.skel') self.ref_skel = self.ref_world.skeletons[1] # revise_pose(self.world.skeletons[1], self.ref_root_state) self.bs = BSpline() self.bs_ori = BSpline() self.step_per_frame = 40 self.w_cv = 1. self.exp_cv = 2. self.body_num = self.skel.num_bodynodes() self.phase_frame = 0 self.penalty_type_on = [None] * len(PenaltyType) self.penalty_type_weight = [1.] * len(PenaltyType) self.com_init = np.zeros(3) self.state_duration = 0 self.recent_torque_sum = 0. self.recent_ori_q = np.zeros_like(self.skel.q) def set_penalty(self, penalty_option, penalty_weight): self.penalty_type_on = copy.deepcopy(penalty_option) self.penalty_type_weight = copy.deepcopy(penalty_weight) def save_com_init(self): self.com_init = self.skel.com() def calc_angular_momentum(self, pos): am = np.zeros(3) for body in self.skel.bodynodes: am += body.mass() * mm.cross(body.com() - pos, body.com_linear_velocity()) am += np.dot(body.inertia(), body.world_angular_velocity()) return am def penalty_instant(self): E = 0. E += self.penalty_type_weight[PenaltyType.TORQUE] * self.recent_torque_sum # E += 1e-4 * np.sum(np.square(self.skel.position_differences(self.skel.q, self.recent_ori_q)[6:])) if self.penalty_type_on[PenaltyType.COM_HEIGHT] is not None: E += self.penalty_type_weight[PenaltyType.COM_HEIGHT] \ * np.square(self.penalty_type_on[PenaltyType.COM_HEIGHT] - self.skel.com()[1]) if self.penalty_type_on[PenaltyType.LEFT_FOOT_CONTACT] is not None: E += self.penalty_type_weight[PenaltyType.LEFT_FOOT_CONTACT] \ * np.square(self.skel.body('h_blade_left').to_world([0., -0.0486, 0.])[1]) if self.penalty_type_on[PenaltyType.RIGHT_FOOT_CONTACT] is not None: E += self.penalty_type_weight[PenaltyType.RIGHT_FOOT_CONTACT] \ * np.square(self.skel.body('h_blade_right').to_world([0., -0.0486, 0.])[1]) if self.penalty_type_on[PenaltyType.LEFT_FOOT_TOE_CONTACT] is not None: E += self.penalty_type_weight[PenaltyType.LEFT_FOOT_TOE_CONTACT] \ * np.square(self.skel.body('h_blade_left').to_world([0.1256, -0.0486, 0.])[1]) if self.penalty_type_on[PenaltyType.RIGHT_FOOT_TOE_CONTACT] is not None: E += self.penalty_type_weight[PenaltyType.RIGHT_FOOT_TOE_CONTACT] \ * np.square(self.skel.body('h_blade_right').to_world([0.1256, -0.0486, 0.])[1]) if self.penalty_type_on[PenaltyType.COM_IN_LEFT_RIGHT_CENTER] is not None: com_projected = self.skel.com() com_projected[1] = 0. centroid = .5 * (self.skel.body('h_blade_left').to_world([0.0216, -0.0486, 0.]) + self.skel.body('h_blade_right').to_world([0.0216, -0.0486, 0.])) centroid[1] = 0. E += self.penalty_type_weight[PenaltyType.COM_IN_LEFT_RIGHT_CENTER] \ * np.sum(np.square(com_projected - centroid)) if self.penalty_type_on[PenaltyType.COM_IN_LEFT_FOOT] is not None: com_projected = self.skel.com() com_projected[1] = 0. centroid = self.skel.body('h_blade_left').to_world([0.0216, -0.0486, 0.]) centroid[1] = 0. E += self.penalty_type_weight[PenaltyType.COM_IN_LEFT_FOOT] \ * np.sum(np.square(com_projected - centroid)) if self.penalty_type_on[PenaltyType.COM_IN_RIGHT_FOOT] is not None: com_projected = self.skel.com() com_projected[1] = 0. centroid = self.skel.body('h_blade_right').to_world([0.0216, -0.0486, 0.]) centroid[1] = 0. E += self.penalty_type_weight[PenaltyType.COM_IN_RIGHT_FOOT] \ * np.sum(np.square(com_projected - centroid)) if self.penalty_type_on[PenaltyType.COM_IN_RIGHT_FOOT_TOE] is not None: com_projected = self.skel.com() com_projected[1] = 0. centroid = self.skel.body('h_blade_right').to_world([0.1256, -0.0486, 0.]) centroid[1] = 0. E += self.penalty_type_weight[PenaltyType.COM_IN_RIGHT_FOOT_TOE] \ * np.sum(np.square(com_projected - centroid)) if self.penalty_type_on[PenaltyType.COM_IN_LEFT_FOOT_TOE] is not None: com_projected = self.skel.com() com_projected[1] = 0. centroid = self.skel.body('h_blade_left').to_world([0.1256, -0.0486, 0.]) centroid[1] = 0. E += self.penalty_type_weight[PenaltyType.COM_IN_LEFT_FOOT_TOE] \ * np.sum(np.square(com_projected - centroid)) if self.penalty_type_on[PenaltyType.COM_IN_HEAD] is not None: com_projected = self.skel.com() com_projected[1] = 0. centroid = self.skel.body('h_head').to_world([0., 0.07825, 0.]) centroid[1] = 0. E += self.penalty_type_weight[PenaltyType.COM_IN_HEAD] \ * np.sum(np.square(com_projected - centroid)) if self.penalty_type_on[PenaltyType.MAX_Y_ANGULAR_MOMENTUM] is not None: E -= self.penalty_type_weight[PenaltyType.MAX_Y_ANGULAR_MOMENTUM] \ * np.square(self.calc_angular_momentum(self.skel.com())[1]) / (self.skel.mass() * self.skel.mass()) if self.penalty_type_on[PenaltyType.COM_VEL] is not None: E += self.penalty_type_weight[PenaltyType.COM_VEL] \ * np.sum(np.square(self.skel.com_velocity() - self.penalty_type_on[PenaltyType.COM_VEL])) if self.penalty_type_on[PenaltyType.PELVIS_HEADING] is not None: heading_des = mm.normalize2(self.penalty_type_on[PenaltyType.PELVIS_HEADING]) heading_cur = np.dot(self.skel.body('h_pelvis').world_transform()[:3, :3], mm.unitX()) E += self.penalty_type_weight[PenaltyType.PELVIS_HEADING] \ * np.sum(np.square(heading_cur - heading_des)) if self.penalty_type_on[PenaltyType.COM_VEL_DIR_WITH_PELVIS_LOCAL] is not None: R_pelvis = self.skel.body('h_pelvis').world_transform()[:3, :3] com_vel_dir_des =
np.asarray(self.penalty_type_on[PenaltyType.COM_VEL_DIR_WITH_PELVIS_LOCAL])
numpy.asarray
# coding=utf-8 import PIL.Image import matplotlib.image as mpimg import scipy.ndimage import cv2 # For Sobel etc import glob import numpy as np import matplotlib.pyplot as plt import os import tensorflow as tf import time import sys import skvideo.io np.set_printoptions(suppress=True, linewidth=200) # Better printing of arrays # Set up model featureA = tf.feature_column.numeric_column("x", shape=[11,11], dtype=tf.uint8) estimator = tf.estimator.DNNClassifier( feature_columns=[featureA], hidden_units=[256, 32], n_classes=2, dropout=0.1, model_dir='./xcorner_model_6k', ) # Saddle def getSaddle(gray_img): img = gray_img.astype(np.float64) gx = cv2.Sobel(img,cv2.CV_64F,1,0) gy = cv2.Sobel(img,cv2.CV_64F,0,1) gxx = cv2.Sobel(gx,cv2.CV_64F,1,0) gyy = cv2.Sobel(gy,cv2.CV_64F,0,1) gxy = cv2.Sobel(gx,cv2.CV_64F,0,1) S = gxx*gyy - gxy**2 return S # void nonmaxSupress(Mat &img) { # int dilation_size = 5; # Mat img_dilate; # Mat peaks; # Mat notPeaks; # Mat nonzeroImg; # Mat element = getStructuringElement(MORPH_RECT, # Size( 2*dilation_size + 1, 2*dilation_size+1 ), # Point( dilation_size, dilation_size ) ); # // Dilate max value by window size # dilate(img, img_dilate, element); # // Compare and find where values of dilated vs original image are NOT the same. # compare(img, img_dilate, peaks, CMP_EQ); # // compare(img, img_dilate, notPeaks, CMP_NE); # compare(img, 0, nonzeroImg, CMP_NE); # bitwise_and(nonzeroImg, peaks, peaks); // Only keep peaks that are non-zero # // Remove peaks that are zero # // Also set max to 255 # // compare(img, 0.8, nonzeroImg, CMP_GT); # // bitwise_and(nonzeroImg, peaks, peaks); // Only keep peaks that are non-zero # // bitwise_not(peaks, notPeaks); # // Set all values where not the same to zero. Non-max suppress. # bitwise_not(peaks, notPeaks); # img.setTo(0, notPeaks); # // img.setTo(255, peaks); # } def fast_nonmax_sup(img, win=21): element = np.ones([win, win], np.uint8) img_dilate = cv2.dilate(img, element) peaks = cv2.compare(img, img_dilate, cv2.CMP_EQ) # nonzeroImg = cv2.compare(img, 0, cv2.CMP_NE) # peaks = cv2.bitwise_and(peaks, nonzeroImg) peaks[img == 0] = 0 # notPeaks = cv2.bitwise_not(peaks) img[peaks == 0] = 0 return img def nonmax_sup(img, win=10): w, h = img.shape # img = cv2.blur(img, ksize=(5,5)) img_sup = np.zeros_like(img, dtype=np.float64) for i,j in np.argwhere(img): # Get neigborhood ta=max(0,i-win) tb=min(w,i+win+1) tc=max(0,j-win) td=min(h,j+win+1) cell = img[ta:tb,tc:td] val = img[i,j] # if np.sum(cell.max() == cell) > 1: # print(cell.argmax()) if cell.max() == val: img_sup[i,j] = val return img_sup def pruneSaddle(s): thresh = 128 score = (s>0).sum() while (score > 10000): thresh = thresh*2 s[s<thresh] = 0 score = (s>0).sum() def loadImage(filepath): img_orig = PIL.Image.open(filepath) img_width, img_height = img_orig.size # Resize aspect_ratio = min(500.0/img_width, 500.0/img_height) new_width, new_height = ((np.array(img_orig.size) * aspect_ratio)).astype(int) img = img_orig.resize((new_width,new_height), resample=PIL.Image.BILINEAR) gray_img = img.convert('L') # grayscale img = np.array(img) gray_img =
np.array(gray_img)
numpy.array
import numpy as np import math def disorient_symm_props(mis_quat_fz, lat_pt_grp, x_tol=1e-04): """ Returns the point group and the principle axes for fundamental zone of underlying bicrystal symmetry. This method takes only one value for lat_pt_grp == 'O_h', i.e. the function is written for bcc and fcc crystals only. Based on the location of the mis_quat_fz in the quaternion hypersphere (4-D), the point group symmetry of the bicrystal is determined. Parameters ----------- mis_quat_fz: numpy.array A quaternion array with size (5 x 1) The quaternion is created from the misorientation of the sigma value for the grain boundary. The misorientation is defined in the orthogonal reference frame of lower crystal 1 (po1). lat_pt_grp: The point group symmetry of the crystal. string with allowed value 'Oh' x_tol: float Tolerance value to check various conditions in the function, default value==1e-04 Returns -------- bp_symm_grp: str The point group symmetry of bicrystal. python string with allowed values 'Cs', 'C2h', 'D3d', 'D2h', 'D4h', 'D6h', 'D8h' and 'Oh' x_g: int First principle axes for the fundamental zone of the bicrystal. y_g: int Second principle axes for the fundamental zone of the bicrystal. z_g: int Third principle axes for the fundamental zone of the bicrystal. """ q0 = mis_quat_fz[0][0] q1 = mis_quat_fz[1][0] q2 = mis_quat_fz[2][0] q3 = mis_quat_fz[3][0] if lat_pt_grp == 'Oh': k = math.sqrt(2) - 1 k1 = 1.0 / math.sqrt(1 + 2*k*k) cond_0 = abs(q0 - 1) <= x_tol pt_o = cond_0 if pt_o: z_g = np.array([0, 0, 1]) x_g = np.array([1, 0, 0]) z_g = z_g/np.linalg.norm(z_g) x_g = x_g/np.linalg.norm(x_g) y_g = np.cross(z_g, x_g) bp_symm_grp = 'Oh' return x_g, y_g, z_g, bp_symm_grp cond_0 = abs(q0 - math.cos(np.pi/8)) <= x_tol cond_1 = abs(q1) <= x_tol cond_2 = abs(q2) <= x_tol cond_3 = abs(q3 - math.sin(np.pi/8)) <= x_tol pt_a = cond_0 and cond_1 and cond_2 and cond_3 if pt_a: z_g = np.array([1, 0, 0]) x_g = np.array([0, -q3, q0]) z_g = z_g/np.linalg.norm(z_g) x_g = x_g/np.linalg.norm(x_g) y_g = np.cross(z_g, x_g) bp_symm_grp = 'D8h' return x_g, y_g, z_g, bp_symm_grp cond_0 = abs(q0 - math.sqrt(3)/2) <= x_tol cond_1 = abs(q1 - 1/(2*math.sqrt(3))) <= x_tol cond_2 = abs(q2 - 1/(2*math.sqrt(3))) <= x_tol cond_3 = abs(q3 - 1/(2*math.sqrt(3))) <= x_tol pt_e = cond_0 and cond_1 and cond_2 and cond_3 if pt_e: z_g = np.array([1/math.sqrt(3), 1/math.sqrt(3), 1/math.sqrt(3)]) x_g = np.array([2/math.sqrt(3), -1/math.sqrt(3), -1/math.sqrt(3)])/math.sqrt(2) z_g = z_g/np.linalg.norm(z_g) x_g = x_g/np.linalg.norm(x_g) y_g = np.cross(z_g, x_g) bp_symm_grp = 'D6h' return x_g, y_g, z_g, bp_symm_grp cond_0 = abs(q0 - 1/(k*2*math.sqrt(2))) <= x_tol cond_1 = abs(q1 - 1/(2*math.sqrt(2))) <= x_tol cond_2 = abs(q2 - 1/(2*math.sqrt(2))) <= x_tol cond_3 = abs(q3 - k/(2*math.sqrt(2))) <= x_tol pt_c = cond_0 and cond_1 and cond_2 and cond_3 if pt_c: z_g = np.array([0, -1/math.sqrt(2), 1/math.sqrt(2)]) x_g = np.array([1, 0, 0]) z_g = z_g/np.linalg.norm(z_g) x_g = x_g/np.linalg.norm(x_g) y_g =
np.cross(z_g, x_g)
numpy.cross
import mimetypes import uuid import _init_paths import sys from fast_rcnn.config import cfg from fast_rcnn.test import im_detect from utils.cython_nms import nms from utils.timer import Timer import numpy as np import caffe, os, cv2 import argparse import dlib import falcon from time import time import estimate_cost CLASSES = ('__background__', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') def _generate_id(): return str(uuid.uuid4()) def read_synset(storage_path): synset = () synset_path = os.path.join(storage_path, 'fastrcnn_synset') with open(synset_path, "r") as f: for line in f.readlines(): synset = synset + (line.rstrip(),) return synset def vis_detections(im, class_name, dets, thresh=0.8): """Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0 or str(class_name).startswith('__background__'): return for i in inds: bbox = dets[i, :4] score = dets[i, -1] cv2.rectangle(im, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (255, 0, 0), 2) cv2.putText(im, '{:s} {:.3f}'.format(class_name, score), (bbox[0], int(bbox[1] - 5)), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), 2, cv2.LINE_AA) return im class Detect(object): def __init__(self, storage_path): self.storage_path = storage_path def on_get(self, req, resp, name): t1 = time() names = name.split("&") prototxt = os.path.join(cfg.ROOT_DIR, 'models/CaffeNet/test.prototxt') caffemodel = os.path.join(cfg.ROOT_DIR, 'data/fast_rcnn_models/' 'caffenet_fast_rcnn_iter_40000.caffemodel') if not os.path.isfile(caffemodel): raise falcon.HTTPPreconditionFailed("Error", "Caffe model not found") caffe.set_mode_cpu() net = caffe.Net(prototxt, caffemodel, caffe.TEST) classes = read_synset(self.storage_path) ext = os.path.splitext(names[0])[1][1:] image_path = os.path.join(self.storage_path, names[0]) im = cv2.imread(image_path) rects = [] dlib.find_candidate_object_locations(im, rects, min_size=np.size(im, 1)) obj_proposals = np.empty((len(rects), 4), dtype=int) for k, d in enumerate(rects): obj_proposals[k] = [d.left(), d.top(), d.right(), d.bottom()] scores, boxes = im_detect(net, im, obj_proposals) CONF_THRESH = 0.9 NMS_THRESH = 0.3 for cls in classes: if str(cls).startswith('__background__'): continue cls_ind = CLASSES.index(cls) cls_boxes = boxes[:, 4 * cls_ind:4 * (cls_ind + 1)] cls_scores = scores[:, cls_ind] keep =
np.where(cls_scores >= CONF_THRESH)
numpy.where
import sys # only needed for command line argument to validate MATLAB port to Python import numpy as np import math f1 = open('C:\\Users\\gtg498u\\Documents\\MATLAB\\trover\\thelat.txt', 'r') thelat = f1.read() f1.close() f2 = open('C:\\Users\\gtg498u\\Documents\\MATLAB\\trover\\thelon.txt', 'r') thelon = f2.read() f2.close() thelat = thelat.split(","); thelon = thelon.split(","); #print(len(thelat)) #print(len(thelon)) thelatt = [float(i) for i in thelat]; thelonn = [float(i) for i in thelon]; #print(thelatt[0]+100) #print(thelonn[0]+100) n1=len(thelatt); n2=len(thelonn); if (n1!=n2): print('Lat and Lon vectors should have the same length'); def deg2utm(Lat,Lon): # Memory pre-allocation x=[] y=[] utmzone = []; # Main Loop # la=Lat; lo=Lon; sa = 6378137.000000 sb = 6356752.314245 #e = ( ( ( sa ** 2 ) - ( sb ** 2 ) ) ** 0.5 ) / sa; e2 = ( ( ( sa ** 2 ) - ( sb ** 2 ) ) ** 0.5 ) / sb; e2cuadrada = e2 ** 2; c = ( sa ** 2 ) / sb; #alpha = ( sa - sb ) / sa; #f #ablandamiento = 1 / alpha; # 1/f lat = la * ( math.pi / 180 ); lon = lo * ( math.pi / 180 ); Huso = np.fix( ( lo / 6 ) + 31); S = ( ( Huso * 6 ) - 183 ); deltaS = lon - ( S * ( math.pi / 180 ) ); Letra = '' if (la<-72): Letra='C'; elif (la<-64): Letra='D'; elif (la<-56): Letra='E'; elif (la<-48): Letra='F'; elif (la<-40): Letra='G'; elif (la<-32): Letra='H'; elif (la<-24): Letra='J'; elif (la<-16): Letra='K'; elif (la<-8): Letra='L'; elif (la<0): Letra='M'; elif (la<8): Letra='N'; elif (la<16): Letra='P'; elif (la<24): Letra='Q'; elif (la<32): Letra='R'; elif (la<40): Letra='S'; elif (la<48): Letra='T'; elif (la<56): Letra='U'; elif (la<64): Letra='V'; elif (la<72): Letra='W'; else: Letra='X'; a = math.cos(lat) * math.sin(deltaS); epsilon = 0.5 * math.log( ( 1 + a) / ( 1 - a ) ); nu = math.atan( math.tan(lat) / math.cos(deltaS) ) - lat; v = ( c / ( ( 1 + ( e2cuadrada * ( math.cos(lat) ) ** 2 ) ) ) ** 0.5 ) * 0.9996; ta = ( e2cuadrada / 2 ) * epsilon ** 2 * ( math.cos(lat) ) ** 2; a1 = math.sin( 2 * lat ); a2 = a1 * ( math.cos(lat) ) ** 2; j2 = lat + ( a1 / 2 ); j4 = ( ( 3 * j2 ) + a2 ) / 4; j6 = ( ( 5 * j4 ) + ( a2 * ( math.cos(lat) ) ** 2) ) / 3; alfa = ( 3 / 4 ) * e2cuadrada; beta = ( 5 / 3 ) * alfa ** 2; gama = ( 35 / 27 ) * alfa ** 3; Bm = 0.9996 * c * ( lat - alfa * j2 + beta * j4 - gama * j6 ); xx = epsilon * v * ( 1 + ( ta / 3 ) ) + 500000; yy = nu * v * ( 1 + ta ) + Bm; if yy<0: yy=9999999+yy; x=xx; y=yy; utmzone = "%02d %c" % (Huso,Letra) return x,y,utmzone def mySmoothPoints(la,lo,spacing,utmz): wla = []; wlo = []; u=[]; for i in range(len(la)-1): w1 = np.array([[la[i+1]],[lo[i+1]]]) wi =
np.array([[la[i]],[lo[i]]])
numpy.array
#!/usr/bin/env python """Implementation of the Generalized Mallow Model. It's used for modeling temporal relations within video collection of one complex activity. """ __author__ = '<NAME>' __date__ = 'August 2018' import numpy as np class Mallow(object): """The Generalized Mallows Model""" def __init__(self, K, rho_0=1.0, nu_0=0.1): """ Args: K: number of subactions in current complex activity """ self._canon_ordering = None # number of subactions self._K = K self.k = 0 self.rho = [1e-8] * (K - 1) self.rho_0 = rho_0 self._nu_0 = nu_0 self._dispersion =
np.zeros((self._K, 1))
numpy.zeros
# -*- coding: utf-8 -*- import numpy as np import pytest from numpy.random import RandomState from numpy import nan from datetime import datetime from itertools import permutations from pandas import (Series, Categorical, CategoricalIndex, Timestamp, DatetimeIndex, Index, IntervalIndex) import pandas as pd from pandas import compat from pandas._libs import (groupby as libgroupby, algos as libalgos, hashtable as ht) from pandas._libs.hashtable import unique_label_indices from pandas.compat import lrange, range import pandas.core.algorithms as algos import pandas.core.common as com import pandas.util.testing as tm import pandas.util._test_decorators as td from pandas.core.dtypes.dtypes import CategoricalDtype as CDT from pandas.compat.numpy import np_array_datetime64_compat from pandas.util.testing import assert_almost_equal class TestMatch(object): def test_ints(self): values = np.array([0, 2, 1]) to_match = np.array([0, 1, 2, 2, 0, 1, 3, 0]) result = algos.match(to_match, values) expected = np.array([0, 2, 1, 1, 0, 2, -1, 0], dtype=np.int64) tm.assert_numpy_array_equal(result, expected) result = Series(algos.match(to_match, values, np.nan)) expected = Series(np.array([0, 2, 1, 1, 0, 2, np.nan, 0])) tm.assert_series_equal(result, expected) s = Series(np.arange(5), dtype=np.float32) result = algos.match(s, [2, 4]) expected = np.array([-1, -1, 0, -1, 1], dtype=np.int64) tm.assert_numpy_array_equal(result, expected) result = Series(algos.match(s, [2, 4], np.nan)) expected = Series(np.array([np.nan, np.nan, 0, np.nan, 1])) tm.assert_series_equal(result, expected) def test_strings(self): values = ['foo', 'bar', 'baz'] to_match = ['bar', 'foo', 'qux', 'foo', 'bar', 'baz', 'qux'] result = algos.match(to_match, values) expected = np.array([1, 0, -1, 0, 1, 2, -1], dtype=np.int64) tm.assert_numpy_array_equal(result, expected) result = Series(algos.match(to_match, values, np.nan)) expected = Series(np.array([1, 0, np.nan, 0, 1, 2, np.nan])) tm.assert_series_equal(result, expected) class TestFactorize(object): def test_basic(self): labels, uniques = algos.factorize(['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']) tm.assert_numpy_array_equal( uniques, np.array(['a', 'b', 'c'], dtype=object)) labels, uniques = algos.factorize(['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c'], sort=True) exp = np.array([0, 1, 1, 0, 0, 2, 2, 2], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) exp = np.array(['a', 'b', 'c'], dtype=object) tm.assert_numpy_array_equal(uniques, exp) labels, uniques = algos.factorize(list(reversed(range(5)))) exp = np.array([0, 1, 2, 3, 4], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) exp = np.array([4, 3, 2, 1, 0], dtype=np.int64) tm.assert_numpy_array_equal(uniques, exp) labels, uniques = algos.factorize(list(reversed(range(5))), sort=True) exp = np.array([4, 3, 2, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) exp = np.array([0, 1, 2, 3, 4], dtype=np.int64) tm.assert_numpy_array_equal(uniques, exp) labels, uniques = algos.factorize(list(reversed(np.arange(5.)))) exp = np.array([0, 1, 2, 3, 4], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) exp = np.array([4., 3., 2., 1., 0.], dtype=np.float64) tm.assert_numpy_array_equal(uniques, exp) labels, uniques = algos.factorize(list(reversed(np.arange(5.))), sort=True) exp = np.array([4, 3, 2, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) exp = np.array([0., 1., 2., 3., 4.], dtype=np.float64) tm.assert_numpy_array_equal(uniques, exp) def test_mixed(self): # doc example reshaping.rst x = Series(['A', 'A', np.nan, 'B', 3.14, np.inf]) labels, uniques = algos.factorize(x) exp = np.array([0, 0, -1, 1, 2, 3], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) exp = Index(['A', 'B', 3.14, np.inf]) tm.assert_index_equal(uniques, exp) labels, uniques = algos.factorize(x, sort=True) exp = np.array([2, 2, -1, 3, 0, 1], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) exp = Index([3.14, np.inf, 'A', 'B']) tm.assert_index_equal(uniques, exp) def test_datelike(self): # M8 v1 = Timestamp('20130101 09:00:00.00004') v2 = Timestamp('20130101') x = Series([v1, v1, v1, v2, v2, v1]) labels, uniques = algos.factorize(x) exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) exp = DatetimeIndex([v1, v2]) tm.assert_index_equal(uniques, exp) labels, uniques = algos.factorize(x, sort=True) exp = np.array([1, 1, 1, 0, 0, 1], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) exp = DatetimeIndex([v2, v1]) tm.assert_index_equal(uniques, exp) # period v1 = pd.Period('201302', freq='M') v2 = pd.Period('201303', freq='M') x = Series([v1, v1, v1, v2, v2, v1]) # periods are not 'sorted' as they are converted back into an index labels, uniques = algos.factorize(x) exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) tm.assert_index_equal(uniques, pd.PeriodIndex([v1, v2])) labels, uniques = algos.factorize(x, sort=True) exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) tm.assert_index_equal(uniques, pd.PeriodIndex([v1, v2])) # GH 5986 v1 = pd.to_timedelta('1 day 1 min') v2 = pd.to_timedelta('1 day') x = Series([v1, v2, v1, v1, v2, v2, v1]) labels, uniques = algos.factorize(x) exp = np.array([0, 1, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) tm.assert_index_equal(uniques, pd.to_timedelta([v1, v2])) labels, uniques = algos.factorize(x, sort=True) exp = np.array([1, 0, 1, 1, 0, 0, 1], dtype=np.intp) tm.assert_numpy_array_equal(labels, exp) tm.assert_index_equal(uniques, pd.to_timedelta([v2, v1])) def test_factorize_nan(self): # nan should map to na_sentinel, not reverse_indexer[na_sentinel] # rizer.factorize should not raise an exception if na_sentinel indexes # outside of reverse_indexer key = np.array([1, 2, 1, np.nan], dtype='O') rizer = ht.Factorizer(len(key)) for na_sentinel in (-1, 20): ids = rizer.factorize(key, sort=True, na_sentinel=na_sentinel) expected = np.array([0, 1, 0, na_sentinel], dtype='int32') assert len(set(key)) == len(set(expected)) tm.assert_numpy_array_equal(pd.isna(key), expected == na_sentinel) # nan still maps to na_sentinel when sort=False key = np.array([0, np.nan, 1], dtype='O') na_sentinel = -1 # TODO(wesm): unused? ids = rizer.factorize(key, sort=False, na_sentinel=na_sentinel) # noqa expected = np.array([2, -1, 0], dtype='int32') assert len(set(key)) == len(set(expected)) tm.assert_numpy_array_equal(pd.isna(key), expected == na_sentinel) @pytest.mark.parametrize("data,expected_label,expected_level", [ ( [(1, 1), (1, 2), (0, 0), (1, 2), 'nonsense'], [0, 1, 2, 1, 3], [(1, 1), (1, 2), (0, 0), 'nonsense'] ), ( [(1, 1), (1, 2), (0, 0), (1, 2), (1, 2, 3)], [0, 1, 2, 1, 3], [(1, 1), (1, 2), (0, 0), (1, 2, 3)] ), ( [(1, 1), (1, 2), (0, 0), (1, 2)], [0, 1, 2, 1], [(1, 1), (1, 2), (0, 0)] ) ]) def test_factorize_tuple_list(self, data, expected_label, expected_level): # GH9454 result = pd.factorize(data) tm.assert_numpy_array_equal(result[0], np.array(expected_label, dtype=np.intp)) expected_level_array = com._asarray_tuplesafe(expected_level, dtype=object) tm.assert_numpy_array_equal(result[1], expected_level_array) def test_complex_sorting(self): # gh 12666 - check no segfault # Test not valid numpy versions older than 1.11 if pd._np_version_under1p11: pytest.skip("Test valid only for numpy 1.11+") x17 = np.array([complex(i) for i in range(17)], dtype=object) pytest.raises(TypeError, algos.factorize, x17[::-1], sort=True) def test_uint64_factorize(self): data = np.array([2**63, 1, 2**63], dtype=np.uint64) exp_labels = np.array([0, 1, 0], dtype=np.intp) exp_uniques = np.array([2**63, 1], dtype=np.uint64) labels, uniques = algos.factorize(data) tm.assert_numpy_array_equal(labels, exp_labels) tm.assert_numpy_array_equal(uniques, exp_uniques) data = np.array([2**63, -1, 2**63], dtype=object) exp_labels = np.array([0, 1, 0], dtype=np.intp) exp_uniques = np.array([2**63, -1], dtype=object) labels, uniques = algos.factorize(data) tm.assert_numpy_array_equal(labels, exp_labels) tm.assert_numpy_array_equal(uniques, exp_uniques) def test_deprecate_order(self): # gh 19727 - check warning is raised for deprecated keyword, order. # Test not valid once order keyword is removed. data = np.array([2**63, 1, 2**63], dtype=np.uint64) with tm.assert_produces_warning(expected_warning=FutureWarning): algos.factorize(data, order=True) with tm.assert_produces_warning(False): algos.factorize(data) @pytest.mark.parametrize('data', [ np.array([0, 1, 0], dtype='u8'), np.array([-2**63, 1, -2**63], dtype='i8'), np.array(['__nan__', 'foo', '__nan__'], dtype='object'), ]) def test_parametrized_factorize_na_value_default(self, data): # arrays that include the NA default for that type, but isn't used. l, u = algos.factorize(data) expected_uniques = data[[0, 1]] expected_labels = np.array([0, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(l, expected_labels) tm.assert_numpy_array_equal(u, expected_uniques) @pytest.mark.parametrize('data, na_value', [ (np.array([0, 1, 0, 2], dtype='u8'), 0), (np.array([1, 0, 1, 2], dtype='u8'), 1), (np.array([-2**63, 1, -2**63, 0], dtype='i8'), -2**63), (np.array([1, -2**63, 1, 0], dtype='i8'), 1), (np.array(['a', '', 'a', 'b'], dtype=object), 'a'), (np.array([(), ('a', 1), (), ('a', 2)], dtype=object), ()), (np.array([('a', 1), (), ('a', 1), ('a', 2)], dtype=object), ('a', 1)), ]) def test_parametrized_factorize_na_value(self, data, na_value): l, u = algos._factorize_array(data, na_value=na_value) expected_uniques = data[[1, 3]] expected_labels = np.array([-1, 0, -1, 1], dtype=np.intp) tm.assert_numpy_array_equal(l, expected_labels) tm.assert_numpy_array_equal(u, expected_uniques) class TestUnique(object): def test_ints(self): arr = np.random.randint(0, 100, size=50) result = algos.unique(arr) assert isinstance(result, np.ndarray) def test_objects(self): arr = np.random.randint(0, 100, size=50).astype('O') result = algos.unique(arr) assert isinstance(result, np.ndarray) def test_object_refcount_bug(self): lst = ['A', 'B', 'C', 'D', 'E'] for i in range(1000): len(algos.unique(lst)) def test_on_index_object(self): mindex = pd.MultiIndex.from_arrays([np.arange(5).repeat(5), np.tile( np.arange(5), 5)]) expected = mindex.values expected.sort() mindex = mindex.repeat(2) result = pd.unique(mindex) result.sort() tm.assert_almost_equal(result, expected) def test_datetime64_dtype_array_returned(self): # GH 9431 expected = np_array_datetime64_compat( ['2015-01-03T00:00:00.000000000+0000', '2015-01-01T00:00:00.000000000+0000'], dtype='M8[ns]') dt_index = pd.to_datetime(['2015-01-03T00:00:00.000000000+0000', '2015-01-01T00:00:00.000000000+0000', '2015-01-01T00:00:00.000000000+0000']) result = algos.unique(dt_index) tm.assert_numpy_array_equal(result, expected) assert result.dtype == expected.dtype s = Series(dt_index) result = algos.unique(s) tm.assert_numpy_array_equal(result, expected) assert result.dtype == expected.dtype arr = s.values result = algos.unique(arr) tm.assert_numpy_array_equal(result, expected) assert result.dtype == expected.dtype def test_timedelta64_dtype_array_returned(self): # GH 9431 expected = np.array([31200, 45678, 10000], dtype='m8[ns]') td_index = pd.to_timedelta([31200, 45678, 31200, 10000, 45678]) result = algos.unique(td_index) tm.assert_numpy_array_equal(result, expected) assert result.dtype == expected.dtype s = Series(td_index) result = algos.unique(s) tm.assert_numpy_array_equal(result, expected) assert result.dtype == expected.dtype arr = s.values result = algos.unique(arr) tm.assert_numpy_array_equal(result, expected) assert result.dtype == expected.dtype def test_uint64_overflow(self): s = Series([1, 2, 2**63, 2**63], dtype=np.uint64) exp = np.array([1, 2, 2**63], dtype=np.uint64) tm.assert_numpy_array_equal(algos.unique(s), exp) def test_nan_in_object_array(self): l = ['a', np.nan, 'c', 'c'] result = pd.unique(l) expected = np.array(['a', np.nan, 'c'], dtype=object) tm.assert_numpy_array_equal(result, expected) def test_categorical(self): # we are expecting to return in the order # of appearance expected = Categorical(list('bac'), categories=list('bac')) # we are expecting to return in the order # of the categories expected_o = Categorical( list('bac'), categories=list('abc'), ordered=True) # GH 15939 c = Categorical(list('baabc')) result = c.unique() tm.assert_categorical_equal(result, expected) result = algos.unique(c) tm.assert_categorical_equal(result, expected) c = Categorical(list('baabc'), ordered=True) result = c.unique() tm.assert_categorical_equal(result, expected_o) result = algos.unique(c) tm.assert_categorical_equal(result, expected_o) # Series of categorical dtype s = Series(Categorical(list('baabc')), name='foo') result = s.unique() tm.assert_categorical_equal(result, expected) result = pd.unique(s) tm.assert_categorical_equal(result, expected) # CI -> return CI ci = CategoricalIndex(Categorical(list('baabc'), categories=list('bac'))) expected = CategoricalIndex(expected) result = ci.unique() tm.assert_index_equal(result, expected) result = pd.unique(ci) tm.assert_index_equal(result, expected) def test_datetime64tz_aware(self): # GH 15939 result = Series( Index([Timestamp('20160101', tz='US/Eastern'), Timestamp('20160101', tz='US/Eastern')])).unique() expected = np.array([Timestamp('2016-01-01 00:00:00-0500', tz='US/Eastern')], dtype=object) tm.assert_numpy_array_equal(result, expected) result = Index([Timestamp('20160101', tz='US/Eastern'), Timestamp('20160101', tz='US/Eastern')]).unique() expected = DatetimeIndex(['2016-01-01 00:00:00'], dtype='datetime64[ns, US/Eastern]', freq=None) tm.assert_index_equal(result, expected) result = pd.unique( Series(Index([Timestamp('20160101', tz='US/Eastern'), Timestamp('20160101', tz='US/Eastern')]))) expected = np.array([Timestamp('2016-01-01 00:00:00-0500', tz='US/Eastern')], dtype=object) tm.assert_numpy_array_equal(result, expected) result = pd.unique(Index([Timestamp('20160101', tz='US/Eastern'), Timestamp('20160101', tz='US/Eastern')])) expected = DatetimeIndex(['2016-01-01 00:00:00'], dtype='datetime64[ns, US/Eastern]', freq=None) tm.assert_index_equal(result, expected) def test_order_of_appearance(self): # 9346 # light testing of guarantee of order of appearance # these also are the doc-examples result = pd.unique(Series([2, 1, 3, 3])) tm.assert_numpy_array_equal(result, np.array([2, 1, 3], dtype='int64')) result = pd.unique(Series([2] + [1] * 5)) tm.assert_numpy_array_equal(result, np.array([2, 1], dtype='int64')) result = pd.unique(Series([Timestamp('20160101'), Timestamp('20160101')])) expected = np.array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]') tm.assert_numpy_array_equal(result, expected) result = pd.unique(Index( [Timestamp('20160101', tz='US/Eastern'), Timestamp('20160101', tz='US/Eastern')])) expected = DatetimeIndex(['2016-01-01 00:00:00'], dtype='datetime64[ns, US/Eastern]', freq=None) tm.assert_index_equal(result, expected) result = pd.unique(list('aabc')) expected = np.array(['a', 'b', 'c'], dtype=object) tm.assert_numpy_array_equal(result, expected) result = pd.unique(Series(Categorical(list('aabc')))) expected = Categorical(list('abc')) tm.assert_categorical_equal(result, expected) @pytest.mark.parametrize("arg ,expected", [ (('1', '1', '2'), np.array(['1', '2'], dtype=object)), (('foo',), np.array(['foo'], dtype=object)) ]) def test_tuple_with_strings(self, arg, expected): # see GH 17108 result = pd.unique(arg) tm.assert_numpy_array_equal(result, expected) class TestIsin(object): def test_invalid(self): pytest.raises(TypeError, lambda: algos.isin(1, 1)) pytest.raises(TypeError, lambda: algos.isin(1, [1])) pytest.raises(TypeError, lambda: algos.isin([1], 1)) def test_basic(self): result = algos.isin([1, 2], [1]) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(np.array([1, 2]), [1]) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(Series([1, 2]), [1]) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(Series([1, 2]), Series([1])) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(Series([1, 2]), set([1])) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(['a', 'b'], ['a']) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(Series(['a', 'b']), Series(['a'])) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(Series(['a', 'b']), set(['a'])) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(['a', 'b'], [1]) expected = np.array([False, False]) tm.assert_numpy_array_equal(result, expected) def test_i8(self): arr = pd.date_range('20130101', periods=3).values result = algos.isin(arr, [arr[0]]) expected = np.array([True, False, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(arr, arr[0:2]) expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(arr, set(arr[0:2])) expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected) arr = pd.timedelta_range('1 day', periods=3).values result = algos.isin(arr, [arr[0]]) expected = np.array([True, False, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(arr, arr[0:2]) expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected) result = algos.isin(arr, set(arr[0:2])) expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected) def test_large(self): s = pd.date_range('20000101', periods=2000000, freq='s').values result = algos.isin(s, s[0:2]) expected = np.zeros(len(s), dtype=bool) expected[0] = True expected[1] = True tm.assert_numpy_array_equal(result, expected) def test_categorical_from_codes(self): # GH 16639 vals = np.array([0, 1, 2, 0]) cats = ['a', 'b', 'c'] Sd = Series(Categorical(1).from_codes(vals, cats)) St = Series(Categorical(1).from_codes(np.array([0, 1]), cats)) expected = np.array([True, True, False, True]) result = algos.isin(Sd, St) tm.assert_numpy_array_equal(expected, result) @pytest.mark.parametrize("empty", [[], Series(), np.array([])]) def test_empty(self, empty): # see gh-16991 vals = Index(["a", "b"]) expected = np.array([False, False]) result = algos.isin(vals, empty) tm.assert_numpy_array_equal(expected, result) class TestValueCounts(object): def test_value_counts(self): np.random.seed(1234) from pandas.core.reshape.tile import cut arr = np.random.randn(4) factor = cut(arr, 4) # assert isinstance(factor, n) result = algos.value_counts(factor) breaks = [-1.194, -0.535, 0.121, 0.777, 1.433] index = IntervalIndex.from_breaks(breaks).astype(CDT(ordered=True)) expected = Series([1, 1, 1, 1], index=index) tm.assert_series_equal(result.sort_index(), expected.sort_index()) def test_value_counts_bins(self): s = [1, 2, 3, 4] result = algos.value_counts(s, bins=1) expected = Series([4], index=IntervalIndex.from_tuples([(0.996, 4.0)])) tm.assert_series_equal(result, expected) result = algos.value_counts(s, bins=2, sort=False) expected = Series([2, 2], index=IntervalIndex.from_tuples([(0.996, 2.5), (2.5, 4.0)])) tm.assert_series_equal(result, expected) def test_value_counts_dtypes(self): result = algos.value_counts([1, 1.]) assert len(result) == 1 result = algos.value_counts([1, 1.], bins=1) assert len(result) == 1 result = algos.value_counts(Series([1, 1., '1'])) # object assert len(result) == 2 pytest.raises(TypeError, lambda s: algos.value_counts(s, bins=1), ['1', 1]) def test_value_counts_nat(self): td = Series([np.timedelta64(10000), pd.NaT], dtype='timedelta64[ns]') dt = pd.to_datetime(['NaT', '2014-01-01']) for s in [td, dt]: vc = algos.value_counts(s) vc_with_na = algos.value_counts(s, dropna=False) assert len(vc) == 1 assert len(vc_with_na) == 2 exp_dt = Series({Timestamp('2014-01-01 00:00:00'): 1}) tm.assert_series_equal(algos.value_counts(dt), exp_dt) # TODO same for (timedelta) def test_value_counts_datetime_outofbounds(self): # GH 13663 s = Series([datetime(3000, 1, 1), datetime(5000, 1, 1), datetime(5000, 1, 1), datetime(6000, 1, 1), datetime(3000, 1, 1), datetime(3000, 1, 1)]) res = s.value_counts() exp_index = Index([datetime(3000, 1, 1), datetime(5000, 1, 1), datetime(6000, 1, 1)], dtype=object) exp = Series([3, 2, 1], index=exp_index) tm.assert_series_equal(res, exp) # GH 12424 res = pd.to_datetime(Series(['2362-01-01', np.nan]), errors='ignore') exp = Series(['2362-01-01', np.nan], dtype=object) tm.assert_series_equal(res, exp) def test_categorical(self): s = Series(Categorical(list('aaabbc'))) result = s.value_counts() expected = Series([3, 2, 1], index=CategoricalIndex(['a', 'b', 'c'])) tm.assert_series_equal(result, expected, check_index_type=True) # preserve order? s = s.cat.as_ordered() result = s.value_counts() expected.index = expected.index.as_ordered() tm.assert_series_equal(result, expected, check_index_type=True) def test_categorical_nans(self): s = Series(Categorical(list('aaaaabbbcc'))) # 4,3,2,1 (nan) s.iloc[1] = np.nan result = s.value_counts() expected = Series([4, 3, 2], index=CategoricalIndex( ['a', 'b', 'c'], categories=['a', 'b', 'c'])) tm.assert_series_equal(result, expected, check_index_type=True) result = s.value_counts(dropna=False) expected = Series([ 4, 3, 2, 1 ], index=CategoricalIndex(['a', 'b', 'c', np.nan])) tm.assert_series_equal(result, expected, check_index_type=True) # out of order s = Series(Categorical( list('aaaaabbbcc'), ordered=True, categories=['b', 'a', 'c'])) s.iloc[1] = np.nan result = s.value_counts() expected = Series([4, 3, 2], index=CategoricalIndex( ['a', 'b', 'c'], categories=['b', 'a', 'c'], ordered=True)) tm.assert_series_equal(result, expected, check_index_type=True) result = s.value_counts(dropna=False) expected = Series([4, 3, 2, 1], index=CategoricalIndex( ['a', 'b', 'c', np.nan], categories=['b', 'a', 'c'], ordered=True)) tm.assert_series_equal(result, expected, check_index_type=True) def test_categorical_zeroes(self): # keep the `d` category with 0 s = Series(Categorical( list('bbbaac'), categories=list('abcd'), ordered=True)) result = s.value_counts() expected = Series([3, 2, 1, 0], index=Categorical( ['b', 'a', 'c', 'd'], categories=list('abcd'), ordered=True)) tm.assert_series_equal(result, expected, check_index_type=True) def test_dropna(self): # https://github.com/pandas-dev/pandas/issues/9443#issuecomment-73719328 tm.assert_series_equal( Series([True, True, False]).value_counts(dropna=True), Series([2, 1], index=[True, False])) tm.assert_series_equal( Series([True, True, False]).value_counts(dropna=False), Series([2, 1], index=[True, False])) tm.assert_series_equal( Series([True, True, False, None]).value_counts(dropna=True), Series([2, 1], index=[True, False])) tm.assert_series_equal( Series([True, True, False, None]).value_counts(dropna=False), Series([2, 1, 1], index=[True, False, np.nan])) tm.assert_series_equal( Series([10.3, 5., 5.]).value_counts(dropna=True), Series([2, 1], index=[5., 10.3])) tm.assert_series_equal( Series([10.3, 5., 5.]).value_counts(dropna=False), Series([2, 1], index=[5., 10.3])) tm.assert_series_equal( Series([10.3, 5., 5., None]).value_counts(dropna=True), Series([2, 1], index=[5., 10.3])) # 32-bit linux has a different ordering if not compat.is_platform_32bit(): result = Series([10.3, 5., 5., None]).value_counts(dropna=False) expected = Series([2, 1, 1], index=[5., 10.3, np.nan]) tm.assert_series_equal(result, expected) def test_value_counts_normalized(self): # GH12558 s = Series([1, 2, np.nan, np.nan, np.nan]) dtypes = (np.float64, np.object, 'M8[ns]') for t in dtypes: s_typed = s.astype(t) result = s_typed.value_counts(normalize=True, dropna=False) expected = Series([0.6, 0.2, 0.2], index=Series([np.nan, 2.0, 1.0], dtype=t)) tm.assert_series_equal(result, expected) result = s_typed.value_counts(normalize=True, dropna=True) expected = Series([0.5, 0.5], index=Series([2.0, 1.0], dtype=t)) tm.assert_series_equal(result, expected) def test_value_counts_uint64(self): arr = np.array([2**63], dtype=np.uint64) expected = Series([1], index=[2**63]) result = algos.value_counts(arr) tm.assert_series_equal(result, expected) arr = np.array([-1, 2**63], dtype=object) expected = Series([1, 1], index=[-1, 2**63]) result = algos.value_counts(arr) # 32-bit linux has a different ordering if not compat.is_platform_32bit(): tm.assert_series_equal(result, expected) class TestDuplicated(object): def test_duplicated_with_nas(self): keys = np.array([0, 1, np.nan, 0, 2, np.nan], dtype=object) result = algos.duplicated(keys) expected = np.array([False, False, False, True, False, True]) tm.assert_numpy_array_equal(result, expected) result = algos.duplicated(keys, keep='first') expected = np.array([False, False, False, True, False, True]) tm.assert_numpy_array_equal(result, expected) result = algos.duplicated(keys, keep='last') expected = np.array([True, False, True, False, False, False]) tm.assert_numpy_array_equal(result, expected) result = algos.duplicated(keys, keep=False) expected = np.array([True, False, True, True, False, True]) tm.assert_numpy_array_equal(result, expected) keys = np.empty(8, dtype=object) for i, t in enumerate(zip([0, 0, np.nan, np.nan] * 2, [0, np.nan, 0, np.nan] * 2)): keys[i] = t result = algos.duplicated(keys) falses = [False] * 4 trues = [True] * 4 expected = np.array(falses + trues) tm.assert_numpy_array_equal(result, expected) result = algos.duplicated(keys, keep='last') expected = np.array(trues + falses) tm.assert_numpy_array_equal(result, expected) result = algos.duplicated(keys, keep=False) expected = np.array(trues + trues) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize('case', [ np.array([1, 2, 1, 5, 3, 2, 4, 1, 5, 6]), np.array([1.1, 2.2, 1.1, np.nan, 3.3, 2.2, 4.4, 1.1, np.nan, 6.6]), pytest.param(np.array([1 + 1j, 2 + 2j, 1 + 1j, 5 + 5j, 3 + 3j, 2 + 2j, 4 + 4j, 1 + 1j, 5 + 5j, 6 + 6j]), marks=pytest.mark.xfail(reason="Complex bug. GH 16399") ), np.array(['a', 'b', 'a', 'e', 'c', 'b', 'd', 'a', 'e', 'f'], dtype=object), np.array([1, 2**63, 1, 3**5, 10, 2**63, 39, 1, 3**5, 7], dtype=np.uint64), ]) def test_numeric_object_likes(self, case): exp_first = np.array([False, False, True, False, False, True, False, True, True, False]) exp_last = np.array([True, True, True, True, False, False, False, False, False, False]) exp_false = exp_first | exp_last res_first = algos.duplicated(case, keep='first') tm.assert_numpy_array_equal(res_first, exp_first) res_last = algos.duplicated(case, keep='last') tm.assert_numpy_array_equal(res_last, exp_last) res_false = algos.duplicated(case, keep=False) tm.assert_numpy_array_equal(res_false, exp_false) # index for idx in [Index(case), Index(case, dtype='category')]: res_first = idx.duplicated(keep='first') tm.assert_numpy_array_equal(res_first, exp_first) res_last = idx.duplicated(keep='last') tm.assert_numpy_array_equal(res_last, exp_last) res_false = idx.duplicated(keep=False) tm.assert_numpy_array_equal(res_false, exp_false) # series for s in [Series(case), Series(case, dtype='category')]: res_first = s.duplicated(keep='first') tm.assert_series_equal(res_first, Series(exp_first)) res_last = s.duplicated(keep='last') tm.assert_series_equal(res_last, Series(exp_last)) res_false = s.duplicated(keep=False) tm.assert_series_equal(res_false, Series(exp_false)) def test_datetime_likes(self): dt = ['2011-01-01', '2011-01-02', '2011-01-01', 'NaT', '2011-01-03', '2011-01-02', '2011-01-04', '2011-01-01', 'NaT', '2011-01-06'] td = ['1 days', '2 days', '1 days', 'NaT', '3 days', '2 days', '4 days', '1 days', 'NaT', '6 days'] cases = [np.array([Timestamp(d) for d in dt]), np.array([Timestamp(d, tz='US/Eastern') for d in dt]), np.array([pd.Period(d, freq='D') for d in dt]), np.array([np.datetime64(d) for d in dt]), np.array([pd.Timedelta(d) for d in td])] exp_first = np.array([False, False, True, False, False, True, False, True, True, False]) exp_last = np.array([True, True, True, True, False, False, False, False, False, False]) exp_false = exp_first | exp_last for case in cases: res_first = algos.duplicated(case, keep='first') tm.assert_numpy_array_equal(res_first, exp_first) res_last = algos.duplicated(case, keep='last') tm.assert_numpy_array_equal(res_last, exp_last) res_false = algos.duplicated(case, keep=False) tm.assert_numpy_array_equal(res_false, exp_false) # index for idx in [Index(case), Index(case, dtype='category'), Index(case, dtype=object)]: res_first = idx.duplicated(keep='first') tm.assert_numpy_array_equal(res_first, exp_first) res_last = idx.duplicated(keep='last') tm.assert_numpy_array_equal(res_last, exp_last) res_false = idx.duplicated(keep=False) tm.assert_numpy_array_equal(res_false, exp_false) # series for s in [Series(case), Series(case, dtype='category'), Series(case, dtype=object)]: res_first = s.duplicated(keep='first') tm.assert_series_equal(res_first, Series(exp_first)) res_last = s.duplicated(keep='last') tm.assert_series_equal(res_last, Series(exp_last)) res_false = s.duplicated(keep=False) tm.assert_series_equal(res_false, Series(exp_false)) def test_unique_index(self): cases = [Index([1, 2, 3]), pd.RangeIndex(0, 3)] for case in cases: assert case.is_unique tm.assert_numpy_array_equal(case.duplicated(), np.array([False, False, False])) @pytest.mark.parametrize('arr, unique', [ ([(0, 0), (0, 1), (1, 0), (1, 1), (0, 0), (0, 1), (1, 0), (1, 1)], [(0, 0), (0, 1), (1, 0), (1, 1)]), ([('b', 'c'), ('a', 'b'), ('a', 'b'), ('b', 'c')], [('b', 'c'), ('a', 'b')]), ([('a', 1), ('b', 2), ('a', 3), ('a', 1)], [('a', 1), ('b', 2), ('a', 3)]), ]) def test_unique_tuples(self, arr, unique): # https://github.com/pandas-dev/pandas/issues/16519 expected = np.empty(len(unique), dtype=object) expected[:] = unique result = pd.unique(arr) tm.assert_numpy_array_equal(result, expected) class GroupVarTestMixin(object): def test_group_var_generic_1d(self): prng = RandomState(1234) out = (np.nan * np.ones((5, 1))).astype(self.dtype) counts = np.zeros(5, dtype='int64') values = 10 * prng.rand(15, 1).astype(self.dtype) labels = np.tile(np.arange(5), (3, )).astype('int64') expected_out = (np.squeeze(values) .reshape((5, 3), order='F') .std(axis=1, ddof=1) ** 2)[:, np.newaxis] expected_counts = counts + 3 self.algo(out, counts, values, labels) assert np.allclose(out, expected_out, self.rtol) tm.assert_numpy_array_equal(counts, expected_counts) def test_group_var_generic_1d_flat_labels(self): prng = RandomState(1234) out = (np.nan * np.ones((1, 1))).astype(self.dtype) counts = np.zeros(1, dtype='int64') values = 10 * prng.rand(5, 1).astype(self.dtype) labels = np.zeros(5, dtype='int64') expected_out = np.array([[values.std(ddof=1) ** 2]]) expected_counts = counts + 5 self.algo(out, counts, values, labels) assert np.allclose(out, expected_out, self.rtol) tm.assert_numpy_array_equal(counts, expected_counts) def test_group_var_generic_2d_all_finite(self): prng = RandomState(1234) out = (np.nan * np.ones((5, 2))).astype(self.dtype) counts = np.zeros(5, dtype='int64') values = 10 * prng.rand(10, 2).astype(self.dtype) labels = np.tile(np.arange(5), (2, )).astype('int64') expected_out = np.std(values.reshape(2, 5, 2), ddof=1, axis=0) ** 2 expected_counts = counts + 2 self.algo(out, counts, values, labels) assert np.allclose(out, expected_out, self.rtol) tm.assert_numpy_array_equal(counts, expected_counts) def test_group_var_generic_2d_some_nan(self): prng = RandomState(1234) out = (np.nan * np.ones((5, 2))).astype(self.dtype) counts = np.zeros(5, dtype='int64') values = 10 * prng.rand(10, 2).astype(self.dtype) values[:, 1] = np.nan labels = np.tile(np.arange(5), (2, )).astype('int64') expected_out = np.vstack([values[:, 0] .reshape(5, 2, order='F') .std(ddof=1, axis=1) ** 2, np.nan * np.ones(5)]).T.astype(self.dtype) expected_counts = counts + 2 self.algo(out, counts, values, labels) tm.assert_almost_equal(out, expected_out, check_less_precise=6) tm.assert_numpy_array_equal(counts, expected_counts) def test_group_var_constant(self): # Regression test from GH 10448. out = np.array([[np.nan]], dtype=self.dtype) counts = np.array([0], dtype='int64') values = 0.832845131556193 * np.ones((3, 1), dtype=self.dtype) labels = np.zeros(3, dtype='int64') self.algo(out, counts, values, labels) assert counts[0] == 3 assert out[0, 0] >= 0 tm.assert_almost_equal(out[0, 0], 0.0) class TestGroupVarFloat64(GroupVarTestMixin): __test__ = True algo = libgroupby.group_var_float64 dtype = np.float64 rtol = 1e-5 def test_group_var_large_inputs(self): prng = RandomState(1234) out = np.array([[np.nan]], dtype=self.dtype) counts = np.array([0], dtype='int64') values = (prng.rand(10 ** 6) + 10 ** 12).astype(self.dtype) values.shape = (10 ** 6, 1) labels = np.zeros(10 ** 6, dtype='int64') self.algo(out, counts, values, labels) assert counts[0] == 10 ** 6 tm.assert_almost_equal(out[0, 0], 1.0 / 12, check_less_precise=True) class TestGroupVarFloat32(GroupVarTestMixin): __test__ = True algo = libgroupby.group_var_float32 dtype = np.float32 rtol = 1e-2 class TestHashTable(object): def test_lookup_nan(self): xs = np.array([2.718, 3.14, np.nan, -7, 5, 2, 3]) m = ht.Float64HashTable() m.map_locations(xs) tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.int64)) def test_lookup_overflow(self): xs = np.array([1, 2, 2**63], dtype=np.uint64) m = ht.UInt64HashTable() m.map_locations(xs) tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.int64)) def test_get_unique(self): s = Series([1, 2, 2**63, 2**63], dtype=np.uint64) exp =
np.array([1, 2, 2**63], dtype=np.uint64)
numpy.array
import os.path as osp import random import pickle import logging import numpy as np import cv2 import lmdb import torch import torch.utils.data as data import data.util as util logger = logging.getLogger('base') class RealVSRDataset(data.Dataset): """ Reading the training REDS dataset key example: 000_00000 GT: Ground-Truth; LQ: Low-Quality, e.g., low-resolution/blurry/noisy/compressed frames support reading N LQ frames, N = 1, 3, 5, 7 """ def __init__(self, opt): super(RealVSRDataset, self).__init__() self.opt = opt # temporal augmentation self.interval_list = opt['interval_list'] self.random_reverse = opt['random_reverse'] logger.info( 'Temporal augmentation interval list: [{}], with random reverse is {}.'. format(','.join(str(x) for x in opt['interval_list']), self.random_reverse) ) self.half_N_frames = opt['N_frames'] // 2 self.GT_root, self.LQ_root = opt['dataroot_GT'], opt['dataroot_LQ'] self.data_type = self.opt['data_type'] self.LR_input = False if opt['GT_size'] == opt['LQ_size'] else True # low resolution inputs #### directly load image keys if self.data_type == 'lmdb': self.paths_GT, _ = util.get_image_paths(self.data_type, opt['dataroot_GT']) logger.info('Using lmdb meta info for cache keys.') elif opt['cache_keys']: logger.info('Using cache keys: {}'.format(opt['cache_keys'])) self.paths_GT = pickle.load(open(opt['cache_keys'], 'rb'))['keys'] else: raise ValueError('Need to create cache keys (meta_info.pkl) by running [create_lmdb.py]') # remove some sequences for testing self.paths_GT = [ v for v in self.paths_GT if v.split('_')[0] not in ['008', '026', '029', '031', '042', '055', '058', '077', '105', '113', '132', '135', '146', '155', '161', '167', '173', '175', '180', '181', '189', '194', '195', '226', '232', '237', '241', '242', '247', '256', '268', '275', '293', '309', '358', '371', '372', '379', '383', '401', '409', '413', '426', '438', '448', '471', '478', '484', '490', '498'] ] assert self.paths_GT, 'Error: GT path is empty.' if self.data_type == 'lmdb': self.GT_env, self.LQ_env = None, None elif self.data_type == 'img': pass else: raise ValueError('Wrong data type: {}'.format(self.data_type)) def _init_lmdb(self): self.GT_env = lmdb.open(self.opt['dataroot_GT'], readonly=True, lock=False, readahead=False, meminit=False) self.LQ_env = lmdb.open(self.opt['dataroot_LQ'], readonly=True, lock=False, readahead=False, meminit=False) def __getitem__(self, index): if self.data_type == 'lmdb' and (self.GT_env is None or self.LQ_env is None): self._init_lmdb() scale = self.opt['scale'] GT_size = self.opt['GT_size'] key = self.paths_GT[index] name_a, name_b = key.split('_') center_frame_idx = int(name_b) #### determine the neighbor frames interval = random.choice(self.interval_list) if self.opt['border_mode']: direction = 1 # 1: forward; 0: backward N_frames = self.opt['N_frames'] if self.random_reverse and random.random() < 0.5: direction = random.choice([0, 1]) if center_frame_idx + interval * (N_frames - 1) > 49: direction = 0 elif center_frame_idx - interval * (N_frames - 1) < 0: direction = 1 # get the neighbor list if direction == 1: neighbor_list = list( range(center_frame_idx, center_frame_idx + interval * N_frames, interval) ) else: neighbor_list = list( range(center_frame_idx, center_frame_idx - interval * N_frames, -interval) ) name_b = '{:05d}'.format(neighbor_list[0]) else: # ensure not exceeding the borders while (center_frame_idx + self.half_N_frames * interval > 49) or \ (center_frame_idx - self.half_N_frames * interval < 0): center_frame_idx = random.randint(0, 49) # get the neighbor list neighbor_list = list( range(center_frame_idx - self.half_N_frames * interval, center_frame_idx + self.half_N_frames * interval + 1, interval) ) if self.random_reverse and random.random() < 0.5: neighbor_list.reverse() name_b = '{:05d}'.format(neighbor_list[self.half_N_frames]) assert len(neighbor_list) == self.opt['N_frames'], \ 'Wrong length of neighbor list: {}'.format(len(neighbor_list)) #### get the GT image (as the center frame) GT_size_tuple = (3, 1024, 512) if self.data_type == 'lmdb': img_GT = util.read_img(self.GT_env, key, GT_size_tuple) else: img_GT = util.read_img(None, osp.join(self.GT_root, name_a, name_b + '.png')) if self.opt['color']: # change color space if necessary img_GT = util.channel_convert(img_GT.shape[2], self.opt['color'], [img_GT])[0] #### get LQ images LQ_size_tuple = (3, 1024, 512) img_LQ_l = [] for v in neighbor_list: img_LQ_path = osp.join(self.LQ_root, name_a, '{:05d}.png'.format(v)) if self.data_type == 'lmdb': img_LQ = util.read_img(self.LQ_env, '{}_{:05d}'.format(name_a, v), LQ_size_tuple) else: img_LQ = util.read_img(None, img_LQ_path) if self.opt['color']: # change color space if necessary img_LQ = util.channel_convert(img_LQ.shape[2], self.opt['color'], [img_LQ])[0] img_LQ_l.append(img_LQ) if self.opt['phase'] == 'train': C, H, W = LQ_size_tuple # LQ size # randomly crop if self.LR_input: LQ_size = GT_size // scale rnd_h = random.randint(0, max(0, H - LQ_size)) rnd_w = random.randint(0, max(0, W - LQ_size)) img_LQ_l = [v[rnd_h:rnd_h + LQ_size, rnd_w:rnd_w + LQ_size, :] for v in img_LQ_l] rnd_h_HR = int(rnd_h * scale) rnd_w_HR = int(rnd_w * scale) img_GT = img_GT[rnd_h_HR:rnd_h_HR + GT_size, rnd_w_HR:rnd_w_HR + GT_size, :] else: rnd_h = random.randint(0, max(0, H - GT_size)) rnd_w = random.randint(0, max(0, W - GT_size)) img_LQ_l = [v[rnd_h:rnd_h + GT_size, rnd_w:rnd_w + GT_size, :] for v in img_LQ_l] img_GT = img_GT[rnd_h:rnd_h + GT_size, rnd_w:rnd_w + GT_size, :] # augmentation - flip, rotate img_LQ_l.append(img_GT) rlt = util.augment(img_LQ_l, self.opt['use_flip'], self.opt['use_rot']) img_LQ_l = rlt[0:-1] img_GT = rlt[-1] # stack LQ images to NHWC, N is the frame number img_LQs =
np.stack(img_LQ_l, axis=0)
numpy.stack
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyMVPA package for the # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """Unit tests for Stelzer et al. cluster thresholding algorithm""" from mvpa2.base import externals from mvpa2.testing.tools import skip_if_no_external # TODO a tiny bit also needs statsmodels skip_if_no_external('statsmodels') skip_if_no_external('scipy') from collections import Counter import numpy as np import random from mvpa2.testing import assert_array_equal, assert_raises, assert_equal, \ assert_array_almost_equal, assert_almost_equal, assert_true, assert_false import mvpa2.algorithms.group_clusterthr as gct from mvpa2.datasets import Dataset, dataset_wizard from nose.tools import assert_greater_equal, assert_greater from mvpa2.testing.sweep import sweepargs from scipy.ndimage import measurements from scipy.stats import norm def test_pval(): def not_inplace_shuffle(x): x = list(x) random.shuffle(x) return x x = range(100000) * 20 x = np.array(x) x = x.reshape(20, 100000) x = x.T x = np.apply_along_axis(not_inplace_shuffle, axis=0, arr=x) expected_result = [100000 - 100000 * 0.001] * 20 thresholds = gct.get_thresholding_map(x, p=0.001) assert_array_equal(thresholds, expected_result) # works with datasets too dsthresholds = gct.get_thresholding_map(Dataset(x), p=0.001) assert_almost_equal(thresholds, dsthresholds) assert_raises(ValueError, gct.get_thresholding_map, x, p=0.00000001) x = range(0, 100, 5) null_dist = np.repeat(1, 100).astype(float)[None] pvals = gct._transform_to_pvals(x, null_dist) desired_output = np.array([1, 0.95, 0.9, 0.85, 0.8, 0.75, 0.7, 0.65, 0.6, 0.55, 0.5, 0.45, 0.4, 0.35, 0.3, 0.25, 0.2, 0.15, 0.1, 0.05]) assert_array_almost_equal(desired_output, pvals) def test_cluster_count(): skip_if_no_external('scipy', min_version='0.10') # we get a ZERO cluster count of one if there are no clusters at all # this is needed to keept track of the number of bootstrap samples that yield # no cluster at all (high treshold) in order to compute p-values when there is no # actual cluster size histogram assert_equal(gct._get_map_cluster_sizes([0, 0, 0, 0]), [0]) # if there is at least one cluster: no ZERO count assert_equal(gct._get_map_cluster_sizes([0, 0, 1, 0]), [1]) for i in range(2): # rerun tests for bool type of test_M test_M = np.array([[1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0]]) expected_result = [5, 4, 3, 3, 2, 0, 2] # 5 clusters of size 1, # 4 clusters of size 2 ... test_ds = Dataset([test_M]) if i == 1: test_M = test_M.astype(bool) test_M_3d = np.hstack((test_M.flatten(), test_M.flatten())).reshape(2, 9, 16) test_ds_3d = Dataset([test_M_3d]) # expected_result^2 expected_result_3d = np.array([0, 5, 0, 4, 0, 3, 0, 3, 0, 2, 0, 0, 0, 2]) size = 10000 # how many times bigger than test_M_3d test_M_3d_big = np.hstack((test_M_3d.flatten(), np.zeros(144))) test_M_3d_big = np.hstack((test_M_3d_big for i in range(size)) ).reshape(3 * size, 9, 16) test_ds_3d_big = Dataset([test_M_3d_big]) expected_result_3d_big = expected_result_3d * size # check basic cluster size determination for plain arrays and datasets # with a single sample for t, e in ((test_M, expected_result), (test_ds, expected_result), (test_M_3d, expected_result_3d), (test_ds_3d, expected_result_3d), (test_M_3d_big, expected_result_3d_big), (test_ds_3d_big, expected_result_3d_big)): assert_array_equal(np.bincount(gct._get_map_cluster_sizes(t))[1:], e) # old M = np.vstack([test_M_3d.flatten()] * 10) # new ds = dataset_wizard([test_M_3d] * 10) assert_array_equal(M, ds) expected_result = Counter(np.hstack([gct._get_map_cluster_sizes(test_M_3d)] * 10)) assert_array_equal(expected_result, gct.get_cluster_sizes(ds)) # test the same with some arbitrary per-feature threshold thr = 4 labels, num = measurements.label(test_M_3d) area = measurements.sum(test_M_3d, labels, index=np.arange(labels.max() + 1)) cluster_sizes_map = area[labels] # .astype(int) thresholded_cluster_sizes_map = cluster_sizes_map > thr # old M = np.vstack([cluster_sizes_map.flatten()] * 10) # new ds = dataset_wizard([cluster_sizes_map] * 10) assert_array_equal(M, ds) expected_result = Counter(np.hstack( [gct._get_map_cluster_sizes(thresholded_cluster_sizes_map)] * 10)) th_map = np.ones(cluster_sizes_map.flatten().shape) * thr # threshold dataset by hand ds.samples = ds.samples > th_map assert_array_equal(expected_result, gct.get_cluster_sizes(ds)) # run same test with parallel and serial execution @sweepargs(n_proc=[1, 2]) def test_group_clusterthreshold_simple(n_proc): if n_proc > 1: skip_if_no_external('joblib') feature_thresh_prob = 0.005 nsubj = 10 # make a nice 1D blob and a speck blob = np.array([0, 0, .5, 3, 5, 3, 3, 0, 2, 0]) blob = Dataset([blob]) # and some nice random permutations nperms = 100 * nsubj perm_samples =
np.random.randn(nperms, blob.nfeatures)
numpy.random.randn
import numpy as np import cv2 import torch import time from smplx.lbs import batch_rigid_transform_diff, batch_rodrigues_np, \ lbs_diff, prepare_J, lbs_diff_fast, rel_to_direct, lbs_diff_nopd from smplx.body_models import SMPLX, SMPL, SMPLH import trimesh def fun1(batch_size, n_j, pose_body, J, parents): #batch rodrigues rot_mats, rot_mat_jacs = batch_rodrigues_np(pose_body) # 4. Get the global joint location transform_jac_chain = np.zeros((batch_size, n_j, n_j, 3, 4, 4)) return batch_rigid_transform_diff(rot_mats, rot_mat_jacs, transform_jac_chain, J, parents) def test_batch_rigid_transform_diff(data_path): batch_size = 1 bm_path = data_path + '/body_models/smplx/SMPLX_MALE.npz' smpl_dict = np.load(bm_path, encoding='latin1', allow_pickle=True) p2n = smpl_dict['part2num'] w = smpl_dict['weights'] num_betas = 10 # number of body parameters num_dmpls = 8 # number of DMPL parameters njoints = smpl_dict['posedirs'].shape[2] // 3 model_type = {69: 'smpl', 153: 'smplh', 162: 'smplx', 45: 'mano'}[njoints] v_template = np.repeat(smpl_dict['v_template'][np.newaxis], batch_size, axis=0) num_total_betas = smpl_dict['shapedirs'].shape[-1] if num_betas < 1: num_betas = num_total_betas shapedirs = smpl_dict['shapedirs'][:, :, :] # Pose blend shape basis: 6890 x 3 x 207, reshaped to 6890*30 x 207 posedirs = smpl_dict['posedirs'] posedirs = posedirs.reshape([posedirs.shape[0] * 3, -1]).T # indices of parents for each joints kintree_table = smpl_dict['kintree_table'].astype(np.int32) parents = kintree_table[0] # LBS weights # weights = np.repeat(smpl_dict['weights'][np.newaxis], batch_size, axis=0) weights = smpl_dict['weights'] J_regressor = smpl_dict['J_regressor'] trans = np.zeros((batch_size, 3)) # root_orient # if self.model_type in ['smpl', 'smplh']: root_orient = np.zeros((batch_size, 3)) # pose_body pose_body = np.zeros((batch_size, 63)) n_j_b = 21 # pose_hand pose_hand = np.zeros((batch_size, 1 * 3 * 2)) betas = np.zeros((batch_size, num_betas)) expression = np.zeros((batch_size, num_betas)) shape_components = np.concatenate([betas, expression], axis=1) # Add shape contribution v_shaped = v_template # Get the joints # NxJx3 array n_j = SMPLX.NUM_JOINTS + 1 J = np.zeros((batch_size, n_j, 3)) # J = vertices2joints(J_regressor, v_shaped) J[0] = J_regressor @ v_shaped # 3. Add pose blend shapes # N x J x 3 x 3 pose = np.zeros((batch_size, n_j * 3)) pose[0, 0:3] = np.asarray([-2.98, 0.07, -0.08]) # test tensor vs ndarray betas_t = torch.tensor(betas, dtype=torch.float) global_orient = torch.tensor(pose[:, :3], dtype=torch.float) body_pose = torch.tensor(pose[:, 3:3 * (SMPLX.NUM_BODY_JOINTS + 1)], dtype=torch.float) lh_pose = torch.tensor( pose[:, 3 * (SMPLX.NUM_BODY_JOINTS + 1): 3 * (SMPLX.NUM_BODY_JOINTS + SMPLX.NUM_HAND_JOINTS + 1)], dtype=torch.float) rh_pose = torch.tensor( pose[:, 3 * (SMPLX.NUM_BODY_JOINTS + SMPLX.NUM_HAND_JOINTS + 1): 3 * ( SMPLX.NUM_BODY_JOINTS + 2 * SMPLX.NUM_HAND_JOINTS + 1)], dtype=torch.float) smpl = SMPLX(model_path=bm_path, ext='npz', betas=betas_t, use_pca=False, flat_hand_mean=True, use_face_contour=True) bm = smpl(global_orient=global_orient, body_pose=body_pose, left_hand_pose=lh_pose, right_hand_pose=rh_pose) verts = bm.vertices[0].detach().cpu().numpy() faces = smpl.faces v_t = bm.vertices.detach().cpu().numpy() j_t = bm.joints.detach().cpu().numpy() v_inds = np.arange(0, 100) n_v = len(v_inds) J, v_shaped, homogen_coord, transform_jac_chain = prepare_J(shape_components, v_template, shapedirs, J_regressor, n_v) # 3. Add pose blend shapes # N x J x 3 x 3 pose = np.zeros((batch_size, n_j*3)) J_transformed, J_transformec_jac, A, A_jac = fun1(batch_size, n_j, pose, J, parents) delta = 1e-8 thr_acc = 1e-5 for rot_id in range(0, n_j): for i in range(0, 3): pose_p = pose.copy() pose_p[0][rot_id * 3 + i] += delta J_transformed_p, J_transformec_jac_p, A_p, A_jac_p = fun1(batch_size, n_j, pose_p, J, parents) dJ = 1.0/delta * (J_transformed_p - J_transformed) dJ_pred = J_transformec_jac[:, rot_id, i] dA = 1.0/delta * (A_p - A) dA_pred = A_jac[:, rot_id, i] j_err = np.linalg.norm(dJ - dJ_pred) a_err = np.linalg.norm(dA - dA_pred) assert (a_err < thr_acc) assert(j_err < thr_acc) print('test finished') def test_lbs_diff(data_path): batch_size = 1 bm_path = data_path + '/body_models/smplx/SMPLX_MALE.npz' smpl_dict = np.load(bm_path, encoding='latin1', allow_pickle=True) p2n = smpl_dict['part2num'] w = smpl_dict['weights'] num_betas = 10 # number of body parameters num_dmpls = 8 # number of DMPL parameters njoints = smpl_dict['posedirs'].shape[2] // 3 model_type = {69: 'smpl', 153: 'smplh', 162: 'smplx', 45: 'mano'}[njoints] v_template = np.repeat(smpl_dict['v_template'][np.newaxis], batch_size, axis=0) num_total_betas = smpl_dict['shapedirs'].shape[-1] if num_betas < 1: num_betas = num_total_betas shapedirs = smpl_dict['shapedirs'][:, :, :] # Pose blend shape basis: 6890 x 3 x 207, reshaped to 6890*30 x 207 posedirs = smpl_dict['posedirs'] posedirs = posedirs.reshape([posedirs.shape[0] * 3, -1]).T # indices of parents for each joints kintree_table = smpl_dict['kintree_table'].astype(np.int32) parents = kintree_table[0] # LBS weights # weights = np.repeat(smpl_dict['weights'][np.newaxis], batch_size, axis=0) weights = smpl_dict['weights'] J_regressor = smpl_dict['J_regressor'] trans = np.zeros((batch_size, 3)) # root_orient # if self.model_type in ['smpl', 'smplh']: root_orient = np.zeros((batch_size, 3)) # pose_body pose_body = np.zeros((batch_size, 63)) n_j_b = 21 # pose_hand pose_hand = np.zeros((batch_size, 1 * 3 * 2)) betas = np.zeros((batch_size, num_betas)) expression = np.zeros((batch_size, num_betas)) shape_components = np.concatenate([betas, expression], axis=1) # Add shape contribution v_shaped = v_template # Get the joints # NxJx3 array n_j = SMPLX.NUM_JOINTS + 1 J = np.zeros((batch_size, n_j, 3)) #J = vertices2joints(J_regressor, v_shaped) J[0] = J_regressor @ v_shaped # 3. Add pose blend shapes # N x J x 3 x 3 pose = np.zeros((batch_size, n_j*3)) pose[0, 0:3] = np.asarray([-2.98, 0.07, -0.08]) #test tensor vs ndarray betas_t = torch.tensor(betas, dtype=torch.float) global_orient = torch.tensor(pose[:, :3], dtype=torch.float) body_pose = torch.tensor(pose[:, 3:3*(SMPLX.NUM_BODY_JOINTS+1)], dtype=torch.float) lh_pose = torch.tensor(pose[:, 3*(SMPLX.NUM_BODY_JOINTS+1) : 3*(SMPLX.NUM_BODY_JOINTS+SMPLX.NUM_HAND_JOINTS+1)], dtype=torch.float) rh_pose = torch.tensor( pose[:, 3 * (SMPLX.NUM_BODY_JOINTS + SMPLX.NUM_HAND_JOINTS + 1) : 3 * (SMPLX.NUM_BODY_JOINTS + 2*SMPLX.NUM_HAND_JOINTS + 1)], dtype=torch.float) smpl = SMPLX(model_path=bm_path, ext='npz', betas=betas_t, use_pca=False, flat_hand_mean=True, use_face_contour=True) bm = smpl(global_orient=global_orient, body_pose=body_pose, left_hand_pose=lh_pose, right_hand_pose=rh_pose) verts = bm.vertices[0].detach().cpu().numpy() faces = smpl.faces curr_mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False) obj_txt = trimesh.exchange.obj.export_obj(curr_mesh) with open('smplx.obj', 'w') as f_out: f_out.write(obj_txt) v_t = bm.vertices.detach().cpu().numpy() j_t = bm.joints.detach().cpu().numpy() v_inds = np.arange(0, 100) n_v = len(v_inds) J, v_shaped, homogen_coord, transform_jac_chain = prepare_J(shape_components, v_template, shapedirs, J_regressor, n_v) verts, verts_jac, J_transformed, J_transformed_jac, A, A_jac, J = lbs_diff(pose, posedirs, parents, J, v_shaped, weights, homogen_coord, transform_jac_chain, v_inds) j_err = np.linalg.norm(j_t[:, 0:n_j] - J_transformed) v_err = np.linalg.norm(v_t[:, v_inds] - verts) print('nd-t errors joint {} vert {}'.format(j_err, v_err)) # if j_err > 1e-5: # for i in range(0, n_j): # print(i) # print(j_t[0][i]) # print(J_transformed[0][i]) v_id = 99 delta = 1e-8 thr_acc = 1e-5 for rot_id in range(0, n_j): for i in range(0, 3): pose_p = pose.copy() pose_p[0][rot_id * 3 + i] += delta # J_transformed_p, J_transformec_jac_p, A_p, A_jac_p = fun1(batch_size, n_j, pose_p, J, parents) t_0 = time.time() verts_p, verts_jac_p, J_transformed_p, J_transformed_jac_p, A_p, A_jac_p, J_p = \ lbs_diff(pose_p, posedirs, parents, J, v_shaped, weights, homogen_coord, transform_jac_chain, v_inds) t_1 = time.time() # print('whole time {} s '.format(t_1-t_0)) dJ = 1.0/delta * (J_transformed_p - J_transformed) dJ_pred = J_transformed_jac[:, rot_id, i] dA = 1.0/delta * (A_p - A) dA_pred = A_jac[:, rot_id, i] dV = 1.0/delta * (verts_p - verts) dV_pred = verts_jac[:, rot_id, i] v_err = np.linalg.norm(dV_pred[0, v_id] - dV[0, v_id]) # print(v_err) assert (v_err < thr_acc) # if v_err > thr_acc: # print(dV_pred[0, v_id]) # print(dV[0, v_id]) # print('-') jac_err = np.linalg.norm(dJ - dJ_pred) print('{} {} : {} {}'.format(rot_id, i, jac_err, v_err)) assert (jac_err < thr_acc) # if jac_err > thr_acc: # print('---') # for ii in range(0, 55): # print(dJ[0,ii]) # print(dJ_pred[0,ii]) # print('-') # # print('-') a_err = np.linalg.norm(dA - dA_pred) assert (a_err < thr_acc) # if a_err > thr_acc: # for ii in range(0, 55): # print(dJ[0,ii]) # print(dJ_pred[0,ii]) # print('-') print('test finished') def test_lbs_diff_nopd(): batch_size = 1 data_path = '/home/alexander/projects/pykinect_prev/data/' # data_path = '/storage/projects/pykinect/data/' bm_path = data_path + '/body_models/smplx/SMPLX_MALE.npz' smpl_dict = np.load(bm_path, encoding='latin1', allow_pickle=True) p2n = smpl_dict['part2num'] w = smpl_dict['weights'] num_betas = 10 # number of body parameters num_dmpls = 8 # number of DMPL parameters njoints = smpl_dict['posedirs'].shape[2] // 3 model_type = {69: 'smpl', 153: 'smplh', 162: 'smplx', 45: 'mano'}[njoints] v_template = np.repeat(smpl_dict['v_template'][np.newaxis], batch_size, axis=0) num_total_betas = smpl_dict['shapedirs'].shape[-1] if num_betas < 1: num_betas = num_total_betas shapedirs = smpl_dict['shapedirs'][:, :, :] # Pose blend shape basis: 6890 x 3 x 207, reshaped to 6890*30 x 207 posedirs = smpl_dict['posedirs'] posedirs = posedirs.reshape([posedirs.shape[0] * 3, -1]).T # indices of parents for each joints kintree_table = smpl_dict['kintree_table'].astype(np.int32) parents = kintree_table[0] # LBS weights # weights = np.repeat(smpl_dict['weights'][np.newaxis], batch_size, axis=0) weights = smpl_dict['weights'] J_regressor = smpl_dict['J_regressor'] trans = np.zeros((batch_size, 3)) # root_orient # if self.model_type in ['smpl', 'smplh']: root_orient = np.zeros((batch_size, 3)) # pose_body pose_body = np.zeros((batch_size, 63)) n_j_b = 21 # pose_hand pose_hand = np.zeros((batch_size, 1 * 3 * 2)) betas = np.zeros((batch_size, num_betas)) expression = np.zeros((batch_size, num_betas)) shape_components = np.concatenate([betas, expression], axis=1) # Add shape contribution v_shaped = v_template # Get the joints # NxJx3 array n_j = SMPLX.NUM_JOINTS + 1 J = np.zeros((batch_size, n_j, 3)) #J = vertices2joints(J_regressor, v_shaped) J[0] = J_regressor @ v_shaped # 3. Add pose blend shapes # N x J x 3 x 3 pose = np.zeros((batch_size, n_j*3)) pose[0, 0:3] = np.asarray([-2.98, 0.07, -0.08]) #test tensor vs ndarray betas_t = torch.tensor(betas, dtype=torch.float) global_orient = torch.tensor(pose[:, :3], dtype=torch.float) body_pose = torch.tensor(pose[:, 3:3*(SMPLX.NUM_BODY_JOINTS+1)], dtype=torch.float) lh_pose = torch.tensor(pose[:, 3*(SMPLX.NUM_BODY_JOINTS+1) : 3*(SMPLX.NUM_BODY_JOINTS+SMPLX.NUM_HAND_JOINTS+1)], dtype=torch.float) rh_pose = torch.tensor( pose[:, 3 * (SMPLX.NUM_BODY_JOINTS + SMPLX.NUM_HAND_JOINTS + 1) : 3 * (SMPLX.NUM_BODY_JOINTS + 2*SMPLX.NUM_HAND_JOINTS + 1)], dtype=torch.float) smpl = SMPLX(model_path=bm_path, ext='npz', betas=betas_t, use_pca=False, flat_hand_mean=True, use_face_contour=True) bm = smpl(global_orient=global_orient, body_pose=body_pose, left_hand_pose=lh_pose, right_hand_pose=rh_pose) verts = bm.vertices[0].detach().cpu().numpy() faces = smpl.faces curr_mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False) obj_txt = trimesh.exchange.obj.export_obj(curr_mesh) with open('smplx.obj', 'w') as f_out: f_out.write(obj_txt) v_t = bm.vertices.detach().cpu().numpy() j_t = bm.joints.detach().cpu().numpy() v_inds = np.arange(0, 100) n_v = len(v_inds) J, v_shaped, homogen_coord, transform_jac_chain = prepare_J(shape_components, v_template, shapedirs, J_regressor, n_v) verts, verts_jac, J_transformed, J_transformed_jac, A, A_jac, J, bpm = lbs_diff_nopd(pose, posedirs, parents, J, v_shaped, weights, homogen_coord, transform_jac_chain, v_inds) j_err = np.linalg.norm(j_t[:, 0:n_j] - J_transformed) v_err = np.linalg.norm(v_t[:, v_inds] - verts) print('nd-t errors joint {} vert {}'.format(j_err, v_err)) if j_err > 1e-5: for i in range(0, n_j): print(i) print(j_t[0][i]) print(J_transformed[0][i]) v_id = 99 delta = 1e-6 for rot_id in range(1, n_j): for i in range(0, 3): pose_p = pose.copy() pose_p[0][rot_id * 3 + i] += delta # J_transformed_p, J_transformec_jac_p, A_p, A_jac_p = fun1(batch_size, n_j, pose_p, J, parents) t_0 = time.time() verts_p, verts_jac_p, J_transformed_p, J_transformed_jac_p, A_p, A_jac_p, J_p, bpm = \ lbs_diff_nopd(pose_p, posedirs, parents, J, v_shaped, weights, homogen_coord, transform_jac_chain, v_inds, bpm=bpm) t_1 = time.time() # print('whole time {} s '.format(t_1-t_0)) dJ = 1.0/delta * (J_transformed_p - J_transformed) dJ_pred = J_transformed_jac[:, rot_id, i] dA = 1.0/delta * (A_p - A) dA_pred = A_jac[:, rot_id, i] dV = 1.0/delta * (verts_p - verts) dV_pred = verts_jac[:, rot_id, i] v_err = np.linalg.norm(dV_pred[0, v_id] - dV[0, v_id]) # print(v_err) # if v_err > 1e-5: # print(dV_pred[0, v_id]) # print(dV[0, v_id]) # dT = 1.0/delta * (T_p - T) # dT_pred = T_jac[:, rot_id, i] # print(np.linalg.norm(dT - dT_pred)) jac_err = np.linalg.norm(dJ - dJ_pred) print('{} {} : {} {}'.format(rot_id, i, jac_err, v_err)) # if jac_err > 0.1: # print('---') # for ii in range(0, 55): # print(dJ[0,ii]) # print(dJ_pred[0,ii]) # print('-') print('-') # print(np.linalg.norm(dA - dA_pred)) def test_lbs_diff_nopd(data_path): batch_size = 1 bm_path = data_path + '/body_models/smplx/SMPLX_MALE.npz' smpl_dict = np.load(bm_path, encoding='latin1', allow_pickle=True) p2n = smpl_dict['part2num'] w = smpl_dict['weights'] num_betas = 10 # number of body parameters num_dmpls = 8 # number of DMPL parameters njoints = smpl_dict['posedirs'].shape[2] // 3 v_template = np.repeat(smpl_dict['v_template'][np.newaxis], batch_size, axis=0) num_total_betas = smpl_dict['shapedirs'].shape[-1] if num_betas < 1: num_betas = num_total_betas shapedirs = smpl_dict['shapedirs'][:, :, :] shapedirs_face = shapedirs[:, :, -10:] # Pose blend shape basis: 6890 x 3 x 207, reshaped to 6890*30 x 207 posedirs = smpl_dict['posedirs'] posedirs = posedirs.reshape([posedirs.shape[0] * 3, -1]).T # indices of parents for each joints kintree_table = smpl_dict['kintree_table'].astype(np.int32) parents = kintree_table[0] # LBS weights # weights = np.repeat(smpl_dict['weights'][np.newaxis], batch_size, axis=0) weights = smpl_dict['weights'] J_regressor = smpl_dict['J_regressor'] trans = np.zeros((batch_size, 3)) # root_orient # if self.model_type in ['smpl', 'smplh']: root_orient = np.zeros((batch_size, 3)) # pose_body pose_body = np.zeros((batch_size, 63)) n_j_b = 21 # pose_hand pose_hand = np.zeros((batch_size, 1 * 3 * 2)) betas = np.zeros((batch_size, num_betas)) expression = np.zeros((batch_size, num_betas)) shape_components = np.concatenate([betas, expression], axis=1) # Add shape contribution v_shaped = v_template # Get the joints # NxJx3 array n_j = SMPLX.NUM_JOINTS + 1 J = np.zeros((batch_size, n_j, 3)) #J = vertices2joints(J_regressor, v_shaped) J[0] = J_regressor @ v_shaped # 3. Add pose blend shapes # N x J x 3 x 3 pose = np.zeros((batch_size, n_j*3)) pose[0, 0:3] = np.asarray([-2.98, 0.07, -0.08]) #test tensor vs ndarray betas_t = torch.tensor(betas, dtype=torch.float) global_orient = torch.tensor(pose[:, :3], dtype=torch.float) body_pose = torch.tensor(pose[:, 3:3*(SMPLX.NUM_BODY_JOINTS+1)], dtype=torch.float) lh_pose = torch.tensor(pose[:, 3*(SMPLX.NUM_BODY_JOINTS+1) : 3*(SMPLX.NUM_BODY_JOINTS+SMPLX.NUM_HAND_JOINTS+1)], dtype=torch.float) rh_pose = torch.tensor( pose[:, 3 * (SMPLX.NUM_BODY_JOINTS + SMPLX.NUM_HAND_JOINTS + 1) : 3 * (SMPLX.NUM_BODY_JOINTS + 2*SMPLX.NUM_HAND_JOINTS + 1)], dtype=torch.float) smpl = SMPLX(model_path=bm_path, ext='npz', betas=betas_t, use_pca=False, flat_hand_mean=True, use_face_contour=True) bm = smpl(global_orient=global_orient, body_pose=body_pose, left_hand_pose=lh_pose, right_hand_pose=rh_pose) verts = bm.vertices[0].detach().cpu().numpy() faces = smpl.faces # curr_mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False) # obj_txt = trimesh.exchange.obj.export_obj(curr_mesh) # with open('smplx.obj', 'w') as f_out: # f_out.write(obj_txt) v_t = bm.vertices.detach().cpu().numpy() j_t = bm.joints.detach().cpu().numpy() v_inds = np.arange(0, 100) n_v = len(v_inds) shape_components[0, 0:10] = np.random.randn(10) J, v_shaped, homogen_coord, transform_jac_chain = prepare_J(shape_components, v_template, shapedirs, J_regressor, n_v) face_expr_0 = np.random.rand(10) verts, verts_jac, J_transformed, J_transformed_jac, A, A_jac, J, bpm = lbs_diff_nopd(pose, shapedirs_face, parents, J, v_shaped, weights, homogen_coord, transform_jac_chain, v_inds, face_expression=face_expr_0) verts_jac = verts_jac[:-10].reshape(1, n_j, 3, len(v_inds), 3) # verts_jac.fill(0) # verts_jac = verts_jac[-10:] j_err = np.linalg.norm(j_t[:, 0:n_j] - J_transformed) v_err = np.linalg.norm(v_t[:, v_inds] - verts) print('nd-t errors joint {} vert {}'.format(j_err, v_err)) # if j_err > 1e-5: # for i in range(0, n_j): # print(i) # print(j_t[0][i]) # print(J_transformed[0][i]) v_id = 99 delta = 1e-8 thr_acc = 1e-5 for rot_id in range(0, n_j): for i in range(0, 3): pose_p = pose.copy() pose_p[0][rot_id * 3 + i] += delta # J_transformed_p, J_transformec_jac_p, A_p, A_jac_p = fun1(batch_size, n_j, pose_p, J, parents) t_0 = time.time() verts_p, verts_jac_p, J_transformed_p, J_transformed_jac_p, A_p, A_jac_p, J_p, bpm = \ lbs_diff_nopd(pose_p, shapedirs_face, parents, J, v_shaped, weights, homogen_coord, transform_jac_chain, v_inds, bpm=bpm, face_expression=face_expr_0) t_1 = time.time() dJ = 1.0/delta * (J_transformed_p - J_transformed) dJ_pred = J_transformed_jac[:, rot_id, i] dA = 1.0/delta * (A_p - A) dA_pred = A_jac[:, rot_id, i] dV = 1.0/delta * (verts_p - verts) dV_pred = verts_jac[:, rot_id, i] v_err = np.linalg.norm(dV_pred[0, v_id] - dV[0, v_id]) # print(v_err) # assert (v_err < thr_acc) # if v_err > thr_acc: # print(dV_pred[0, v_id]) # print(dV[0, v_id]) # print('-') jac_err = np.linalg.norm(dJ - dJ_pred) print('{} {} : {} {}'.format(rot_id, i, jac_err, v_err)) # assert (jac_err < thr_acc) if jac_err > thr_acc: print('---') for ii in range(0, 55): print(dJ[0,ii]) print(dJ_pred[0,ii]) print('-') # print('-') a_err =
np.linalg.norm(dA - dA_pred)
numpy.linalg.norm
"""Module containing functions for temporal RSA""" from itertools import islice import mne import numpy as np from joblib.parallel import Parallel, delayed from mne import EpochsArray from mne.cov import compute_whitener from numpy.testing import assert_array_equal from sklearn.model_selection import StratifiedShuffleSplit from sklearn.preprocessing.label import LabelEncoder from .metrics import CDIST_METRICS from .utils import _npairs, _get_unique_targets from .log import log log.name = __name__ def mean_group(array, targets): """ Average rows of array according to the unique values of targets Arguments --------- array : ndarray (n_samples, n_features, n_times) array containing the epoch data targets : ndarray (n_samples, ) array containing targets for the samples Returns ------- avg_array : ndarray (n_unique_targets, n_features, n_times) array containing the average within each group unique_targets : ndarray (n_unique_targets, ) array containing the unique targets, corresponding to the order in avg_array """ targets_ = np.array(targets) unique_targets = np.unique(targets_) n_unique_targets = len(unique_targets) avg_array = np.zeros((n_unique_targets, array.shape[1], array.shape[2])) for i, t in enumerate(unique_targets): mask = targets_ == t avg_array[i, ...] = array[mask, ...].mean(axis=0) return avg_array, unique_targets def _get_mask_binary_trials(target1, target2, targets_train, targets_test): unique_targets = _get_unique_targets(targets_train, targets_test) target1 = unique_targets[target1] target2 = unique_targets[target2] mask_train = (targets_train == target1) | \ (targets_train == target2) mask_test = (targets_test == target1) | \ (targets_test == target2) return mask_train, mask_test def _get_combinations_triu(unique_targets): n_unique_targets = len(unique_targets) for p1 in range(n_unique_targets): for p2 in range(p1, n_unique_targets): yield unique_targets[p1], unique_targets[p2] def _run_metric(metric_fx, epoch_train, targets_train, epoch_test, targets_test, time_diag_only=False): # check if metric is symmetric try: symmetric = metric_fx.is_symmetric except AttributeError: symmetric = False # get some vars n_times = epoch_train.shape[-1] unique_targets = _get_unique_targets(targets_train, targets_test) n_unique_targets = len(unique_targets) n_pairwise_targets = _npairs(n_unique_targets) if time_diag_only: n_pairwise_times = n_times else: n_pairwise_times = _npairs(n_times) if symmetric \ else n_times * n_times # check if we have one of our metrics try: vectorized = metric_fx.is_vectorized except AttributeError: vectorized = False # preallocate output with ones; for classification we assume that # if target1 == target2, then acc = 1 rdms = np.ones((n_pairwise_targets, n_pairwise_times)) if vectorized: # we don't need to loop explicitly through pairwise targets itime = 0 # now we can loop through time for t1 in range(n_times): # log.info("Training on time {0:.3f}".format(t1)) start_t2 = t1 if symmetric or time_diag_only else 0 end_t2 = t1 + 1 if time_diag_only else n_times # fit only once metric_fx.fit(epoch_train[..., t1], targets_train) for t2 in range(start_t2, end_t2): rdms[:, itime] = metric_fx.score(epoch_test[..., t2], targets_test) itime += 1 else: for ipair, (p1, p2) in enumerate( _get_combinations_triu(unique_targets)): log.info("Running for pair number {0} ({1}, {2})".format(ipair, p1, p2)) if p1 != p2: mask_train, mask_test = _get_mask_binary_trials(p1, p2, targets_train, targets_test) data_train = epoch_train[mask_train] data_test = epoch_test[mask_test] targets_train_ = targets_train[mask_train] targets_test_ = targets_test[mask_test] itime = 0 # now we can loop through time for t1 in range(n_times): start_t2 = t1 if symmetric or time_diag_only else 0 end_t2 = t1 + 1 if time_diag_only else n_times # fit only once metric_fx.fit(data_train[..., t1], targets_train_) for t2 in range(start_t2, end_t2): rdms[ipair, itime] = \ metric_fx.score(data_test[..., t2], targets_test_) itime += 1 return rdms def _multiv_normalize(epoch_train, epoch_test, cv_normalize_noise=None): if cv_normalize_noise not in ('epoch', 'baseline', None): raise ValueError( "cv_normalize_noise must be one of {0}".format( ('epoch', 'baseline', None))) if cv_normalize_noise: log.info("Applying multivariate noise normalization " "with method '{0}'".format(cv_normalize_noise)) tmax = 0. if cv_normalize_noise == 'baseline' else None cov_train = mne.compute_covariance(epoch_train, tmax=tmax, method='shrunk') W_train, ch_names = compute_whitener(cov_train, epoch_train.info) # whiten both training and testing set epoch_train = np.array([np.dot(W_train, e) for e in epoch_train.get_data()]) epoch_test = np.array([np.dot(W_train, e) for e in epoch_test.get_data()]) else: epoch_train = epoch_train.get_data() epoch_test = epoch_test.get_data() return epoch_train, epoch_test def _compute_fold(metric_fx, targets, train, test, epoch, cv_normalize_noise=None, mean_groups=False, time_diag_only=False): """ Computes pairwise metric across time for one fold Arguments --------- metric_fx : either an allowed string (e.g., 'correlation') or an object with attributes 'fit' and 'score' (similar to scikit-learn estimators) targets : array (n_trials,) target (condition) for each trials; they must be integers train : array-like of int indices of the training data test : array-like of int indices of the testing data epoch : instance of mne.Epoch cv_normalize_noise : str | None (default None) Multivariately normalize the trials before applying the metric (distance or classification). Normalization is performed with cross-validation, that is the covariance matrix is estimated in the training set, and then applied to the test set. Normalization is always performed on single trials, thus before averaging within each class if `mean_groups` is set to True. Valid values for `cv_normalize_noise` are 'epoch' | 'baseline' | None: - 'epoch' computes the covariance matrix on the entire epoch; - 'baseline' uses only the baseline condition; it requires `epoch` to have a valid baseline (i.e., to have performed baseline correction) mean_groups : bool (default False) Whether the trials belonging to each target should be averaged prior to running the metric. This is useful if the metric is a distance metric. Should be set to False for classification. time_diag_only : bool (default False) Whether to run only for the diagonal in time, e.g. for train_time == test_time Returns ------- rdms: array (n_pairwise_targets, n_pairwise_times) the cross-validated RDM over time targets_pairs : list of len n_pairwise_targets the labels corresponding to each element in rdms """ targets = np.asarray(targets) if targets.dtype != np.dtype('int64'): raise ValueError("targets must be integers, " "not {0}".format(targets.dtype)) # impose conditions in epoch as targets, so that covariance # matrix is computed within each target events_ = epoch.events.copy() events_[:, 2] = targets epoch_ = EpochsArray(epoch.get_data(), info=epoch.info, events=events_, tmin=epoch.times[0]) epoch_.baseline = epoch.baseline # get training and testing data epoch_train = epoch_.copy()[train] targets_train = targets[train] assert(len(epoch_train) == len(targets_train)) epoch_test = epoch_.copy()[test] targets_test = targets[test] assert(len(epoch_test) == len(targets_test)) # perform multi variate noise normalization epoch_train, epoch_test = _multiv_normalize(epoch_train, epoch_test, cv_normalize_noise) if mean_groups: # average within train and test for each target epoch_train, targets_train = mean_group(epoch_train, targets_train) epoch_test, targets_test = mean_group(epoch_test, targets_test) # the targets should be the same in both training and testing # set or else we are correlating weird things together assert_array_equal(targets_train, targets_test) rdms = _run_metric(metric_fx, epoch_train, targets_train, epoch_test, targets_test, time_diag_only=time_diag_only) # return also the pairs labels. since we are taking triu, we loop first # across rows unique_targets = _get_unique_targets(targets_train, targets_test) targets_pairs = [] for tr_lbl, te_lbl in _get_combinations_triu(unique_targets): targets_pairs.append('+'.join(map(str, [tr_lbl, te_lbl]))) return rdms, targets_pairs def compute_temporal_rdm(epoch, targets, metric='correlation', cv=StratifiedShuffleSplit(n_splits=10, test_size=0.5), cv_normalize_noise=None, mean_groups=False, time_diag_only=False, n_jobs=1, batch_size=200): """ Computes pairwise metric across time Arguments --------- epoch : instance of mne.Epoch targets : array (n_trials,) target (condition) for each trials metric: str | BaseMetric | sklearn estimator type of metric to use, one of 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'sqeuclidean' for distances. Alternatively, any object with attributes fit/score, similar to sklearn estimators. cv : instance of sklearn cross-validator Cross-validator used to split the data into training/test datasets (default StratifiedShuffleSplit(n_splits=10, test_size=0.5) cv_normalize_noise : str | None (default None) Multivariately normalize the trials before applying the metric (distance or classification). Normalization is performed with cross-validation, that is the covariance matrix is estimated in the training set, and then applied to the test set. Normalization is always performed on single trials, thus before averaging within each class if `mean_groups` is set to True. Valid values for `cv_normalize_noise` are 'epoch' | 'baseline' | None: - 'epoch' computes the covariance matrix on the entire epoch; - 'baseline' uses only the baseline condition; it requires `epoch` to have a valid baseline (i.e., to have performed baseline correction) mean_groups : bool (default False) Whether the trials belonging to each target should be averaged prior to running the metric. This is useful if the metric is a distance metric. Should be set to False for classification. time_diag_only : bool (default False) Whether to run only for the diagonal in time, e.g. for train_time == test_time n_jobs : int (default 1) batch_size : int (default 200) size of the batches for cross-validation. To be used if the number of splits are very large in order to reduce the memory load Returns ------- rdm: ndarray (n_pairwise_targets, n_pairwise_times) or (n_pairwise_targets, n_times * n_times) the cross-validated RDM over time; if the metric is symmetric, then for efficiency purposes only the upper triangular matrix over time is returned, and the full matrix can be reconstructed with `np.triu_indices_from`. Otherwise, the entire flattened matrix over time is returned, and the full matrix can be reconstructed with `np.reshape((n_times, n_times))`. The order is row first, then columns. targets_pairs : list-like (n_pairwise_targets,) the labels for each row of rdm """ # set up metric if metric in CDIST_METRICS: metric_fx = CDIST_METRICS[metric] elif hasattr(metric, 'fit') and hasattr(metric, 'score'): metric_fx = metric else: raise ValueError( "I don't know how to deal with metric {0}. It's not one of {1} " "and it doesn't have fit/score attributes".format( metric, sorted(CDIST_METRICS.keys()))) # fix targets targets_, le = _conform_targets(targets) splits = cv.split(targets_, targets_) n_splits = cv.get_n_splits(targets_) # need to batch it for memory if more than 200 splits # trick from https://stackoverflow.com/questions/14822184/ # is-there-a-ceiling-equivalent-of-operator-in-python/17511341#17511341 n_batches = -(-n_splits // batch_size) log.info("Using n_batches {0}".format(n_batches)) rdm = None for i_batch in range(n_batches): log.info("Running batch {0}/{1}".format(i_batch+1, n_batches)) rdm_cv = Parallel(n_jobs=n_jobs)( delayed(_compute_fold)(metric_fx, targets_, train, test, epoch, mean_groups=mean_groups, cv_normalize_noise=cv_normalize_noise, time_diag_only=time_diag_only) for train, test in islice(splits, batch_size)) rdm_cv, targets_pairs = zip(*rdm_cv) if rdm is None: rdm = np.sum(rdm_cv, axis=0) else: rdm += np.sum(rdm_cv, axis=0) # remove to free up some memory del rdm_cv rdm /= n_splits return rdm, _invert_targets_pairs(targets_pairs[0], le) def _invert_targets_pairs(targets_pairs, label_encoder): """ Given a list of targets pairs of the form 'target1+target2', revert back to the original labeling by using `label_encoder.inverse_transform` Parameters ---------- targets_pairs : list or array-like of str label_encoder : fitted LabelEncoder Returns ------- targets_pairs : list of str the inversed targets_pairs """ t1t2 = [l.split('+') for l in targets_pairs] t1, t2 = zip(*t1t2) t1 = label_encoder.inverse_transform([int(t) for t in t1]) t2 = label_encoder.inverse_transform([int(t) for t in t2]) return ['+'.join([str(tt1), str(tt2)]) for tt1, tt2 in zip(t1, t2)] def _make_pseudotrials_array(array, targets, navg=4, rng=None): """ Create pseudotrials by averaging within each group defined in `targets` a number `navg` of trials. The trials are randomly divided into groups of size `navg` for each target. If the number of trials in a group is not divisible by `navg`, one pseudotrials will be created by averaging the remainder trials. Parameters ---------- array : (n_epochs, n_channels, n_times) targets : (n_epochs,) navg : int number of trials to average rng : random number generator Returns ------- avg_trials : (ceil(n_epochs/navg), n_channels, n_times) array containing the averaged trials avg_targets : (ceil(n_epochs/navg),) unique targets corresponding to the avg_trials """ if rng is None: rng = np.random.RandomState() unique_targets, count_targets = np.unique(targets, return_counts=True) # count how many new trials we're getting for each condition n_splits_targets = -(-count_targets//navg) n_avg_trials = n_splits_targets.sum() # store the indices of the targets among which we'll be averaging idx_avg = dict() for i, t in enumerate(unique_targets): idx_target = np.where(targets == t)[0] # shuffle so we randomly pick them rng.shuffle(idx_target) idx_avg[t] = np.array_split(idx_target, n_splits_targets[i]) # now average avg_trials =
np.zeros((n_avg_trials, array.shape[1], array.shape[2]))
numpy.zeros
# Copyright 2018 The RLgraph authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import unittest from contrib.bitflip_env.rlgraph.environments import OpenAIGymEnv class TestOpenAIAtariEnv(unittest.TestCase): """ Tests creation, resetting and stepping through an openAI Atari Env. """ def test_openai_atari_env(self): env = OpenAIGymEnv("Pong-v0") # Simple test runs with fixed actions. s = env.reset() # Assert we have pixels. self.assertGreaterEqual(
np.mean(s)
numpy.mean
# pylint: disable=too-many-lines """Fields are the basis of Viscid's data abstration Fields belong in grids, or by themselves as a result of a calculation. They can belong to a :class:`Grid` as the result of a file load, or by themselves as the result of a calculation. This module has some convenience functions for creating fields similar to `Numpy`. """ from __future__ import print_function from itertools import count, islice from inspect import isclass import numpy as np import viscid from viscid import logger from viscid.compat import string_types, izip_longest from viscid import coordinate from viscid.cython import interp_trilin from viscid.sliceutil import to_slice from viscid import tree from viscid.vutil import subclass_spider LAYOUT_DEFAULT = "none" # do not translate LAYOUT_INTERLACED = "interlaced" LAYOUT_FLAT = "flat" LAYOUT_SCALAR = "scalar" LAYOUT_OTHER = "other" __all__ = ['arrays2field', 'dat2field', 'full', 'empty', 'zeros', 'ones', 'full_like', 'empty_like', 'zeros_like', 'ones_like', 'scalar_fields_to_vector', 'wrap_field'] def arrays2field(crd_arrs, dat_arr, name="NoName", center=None, crd_type=None, crd_names="xyzuvw"): """Turn arrays into fields so they can be used in viscid.plot, etc. This is a convenience function that takes care of making coordnates and the like. If the default behavior doesn't work for you, you'll need to make your own coordnates and call :py:func:`viscid.field.wrap_field`. Args: crd_arrs (list of ndarrays): xyz list of ndarrays that describe the node centered coordnates of the field dat_arr (ndarray): data with len(crd_arrs) or len(crd_arrs) + 1 dimensions name (str): some name center (str, None): If not None, translate field to this centering (node or cell) """ crds = coordinate.arrays2crds(crd_arrs, crd_type=crd_type, crd_names=crd_names) # discover what kind of data was given crds_shape_nc = list(crds.shape_nc) crds_shape_cc = list(crds.shape_cc) dat_arr_shape = list(dat_arr.shape) if len(dat_arr.shape) == len(crds.shape_nc): discovered_type = "scalar" discovered_layout = LAYOUT_FLAT if crds_shape_nc == dat_arr_shape: discovered_center = "node" elif crds_shape_cc == dat_arr_shape: discovered_center = "cell" else: raise ValueError("Can't detect centering for scalar dat_arr") elif len(dat_arr.shape) == len(crds.shape_nc) + 1: discovered_type = "vector" if crds_shape_nc == dat_arr_shape[:-1]: discovered_layout = LAYOUT_INTERLACED discovered_center = "node" elif crds_shape_cc == dat_arr_shape[:-1]: discovered_layout = LAYOUT_INTERLACED discovered_center = "cell" elif crds_shape_nc == dat_arr_shape[1:]: discovered_layout = LAYOUT_FLAT discovered_center = "node" elif crds_shape_cc == dat_arr_shape[1:]: discovered_layout = LAYOUT_FLAT discovered_center = "cell" else: raise ValueError("Can't detect centering for vector dat_arr") else: raise ValueError("crds and data have incompatable dimensions: {0} {1}" "".format(dat_arr.shape, crds.shape_nc)) fld = wrap_field(dat_arr, crds, name=name, fldtype=discovered_type, center=discovered_center, layout=discovered_layout) fld = fld.as_centered(center) return fld def dat2field(dat_arr, name="NoName", fldtype="scalar", center=None, layout=LAYOUT_FLAT): """Makes np.arange coordnate arrays and calls arrays2field Args: dat_arr (ndarray): data name (str): name of field fldtype (str, optional): 'scalar' / 'vector' center (str, None): If not None, translate field to this centering (node or cell) layout (TYPE, optional): Description """ sshape = [] if fldtype.lower() == "scalar": sshape = dat_arr.shape elif fldtype.lower() == "vector": if layout == LAYOUT_FLAT: sshape = dat_arr.shape[1:] elif layout == LAYOUT_INTERLACED: sshape = dat_arr.shape[:-1] else: raise ValueError("Unknown layout: {0}".format(layout)) else: raise ValueError("Unknown type: {0}".format(fldtype)) crd_arrs = [np.arange(s).astype(dat_arr.dtype) for s in sshape] return arrays2field(crd_arrs, dat_arr, name=name, center=center) def full(crds, fill_value, dtype="f8", name="NoName", center="cell", layout=LAYOUT_FLAT, nr_comps=0, crd_type=None, crd_names="xyzuvw", **kwargs): """Analogous to `numpy.full` Parameters: crds (Coordinates, list, or tuple): Can be a coordinates object. Can also be a list of ndarrays describing coordinate arrays. Or, if it's just a list or tuple of integers, those integers are taken to be the nz,ny,nx shape and the coordinates will be fill with :py:func:`np.arange`. fill_value (number, None): Initial value of array. None indicates uninitialized (i.e., `numpy.empty`) dtype (optional): some way to describe numpy dtype of data name (str): a way to refer to the field programatically center (str, optional): cell or node, there really isn't support for edge / face yet layout (str, optional): how data is stored, is in "flat" or "interlaced" (interlaced == AOS) nr_comps (int, optional): for vector fields, nr of components **kwargs: passed through to Field constructor """ if not isinstance(crds, coordinate.Coordinates): # if crds is a list/tuple of integers, then make coordinate # arrays using arange if not isinstance(crds, (list, tuple, np.ndarray)): try: crds = list(crds) except TypeError: crds = [crds] if all([isinstance(c, int) for c in crds]): crds = [np.arange(c).astype(dtype) for c in crds] # now assume that crds is a list of coordinate arrays that arrays2crds # can understand crds = coordinate.arrays2crds(crds, crd_type=crd_type, crd_names=crd_names) if center.lower() == "cell": sshape = crds.shape_cc elif center.lower() == "node": sshape = crds.shape_nc else: sshape = crds.shape_nc if nr_comps == 0: fldtype = "scalar" shape = sshape else: fldtype = "vector" if layout.lower() == LAYOUT_INTERLACED: shape = list(sshape) + [nr_comps] else: shape = [nr_comps] + list(sshape) if fill_value is None: dat = np.empty(shape, dtype=dtype) else: if hasattr(np, "full"): dat =
np.full(shape, fill_value, dtype=dtype)
numpy.full
import collections import multiprocessing import logging from multiprocessing.pool import ThreadPool import numpy as np import pandas as pd from datetime import datetime from scipy import stats from .bmr.base import BMRBase from .models.base import DoseResponseModel from .models.dichotomous import Dichotomous from . import exports class Session(object): """ Modeling session. Composed of a dataset, modeling inputs, some model specifications, and BMRs. """ ZEROISH = 1e-8 TIME_FORMAT = '%b %d %Y, %I:%M %p' def __init__(self, mcmc_iterations=20000, mcmc_num_chains=2, mcmc_warmup_fraction=0.5, seed=12345, **kwargs): self.mcmc_iterations = mcmc_iterations self.mcmc_num_chains = mcmc_num_chains self.mcmc_warmup_fraction = mcmc_warmup_fraction self.seed = seed self._unset_dataset() self.models = [] self.bmrs = [] self.name = kwargs.get('name', self._get_default_name()) self.created = self._get_timestamp().isoformat() def add_models(self, *args): for model in args: if not isinstance(model, DoseResponseModel): raise ValueError('Not a DoseResponseModel') model._set_session(self) self.models.append(model) def _unset_dataset(self): self.dataset_type = None self.dataset = None def _get_default_name(self): return 'New run {}'.format(self._get_timestamp().strftime(self.TIME_FORMAT)) def _get_timestamp(self): return datetime.now() DICHOTOMOUS_SUMMARY = 'D' DICHOTOMOUS_INDIVIDUAL = 'E' CONTINUOUS_SUMMARY = 'C' CONTINUOUS_INDIVIDUAL = 'I' DICHOTOMOUS_TYPES = ['D', 'E'] CONTINUOUS_TYPES = ['C', 'I'] def add_dichotomous_data(self, dose, n, incidence): if not isinstance(dose, collections.Iterable) or \ not isinstance(n, collections.Iterable) or \ not isinstance(incidence, collections.Iterable): raise ValueError('Must be iterables') if any([len(dose) != len(n), len(n) != len(incidence)]): raise ValueError('All arrays must be same length') if (len(dose) < 2): raise ValueError('Must have at least 2 values') incidence = np.array(incidence, dtype=np.int64) n =
np.array(n, dtype=np.int64)
numpy.array
import numpy as np from kinematics.dhparameters import DHParameters class Kinematics: def __init__(self): self.joint1_dh = DHParameters(0, 0.1625, 0) self.joint2_dh = DHParameters(0, 0, np.pi / 2) self.joint3_dh = DHParameters(-0.425, 0, 0) self.joint4_dh = DHParameters(-0.39225, 0.1333, 0) self.joint5_dh = DHParameters(0, 0.0997, np.pi / 2) self.joint6_dh = DHParameters(0, 0.0996, -np.pi / 2) def compute_transformation_matrix(self, theta, dh_params): c = np.cos(theta) s =
np.sin(theta)
numpy.sin
import math import os import time #import multiprocessing as mp from joblib import Parallel, delayed from joblib import dump, load import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.mplot3d.art3d import Poly3DCollection import torch from scipy.sparse import csr_matrix from scipy.sparse.csgraph import floyd_warshall # gudhi is needed to construct a simplex tree and to plot the persistence diagram. try: import gudhi from gudhi.clustering.tomato import Tomato except: print('Failed to import gudhi') from sklearn.metrics import pairwise_distances # hard-coded #MAX_DIST_INIT = 100000 MAX_N_PLOT = 5000 NUMBER_OF_FRAMES = 6 class WitnessComplex(): __slots__ = [ 'landmarks', 'witnesses', 'distances', 'distances_isomap', 'landmarks_idxs', 'isomap_eps', 'landmarks_dist', 'simplex_tree', 'simplex_tree_computed', 'metric_computed' ] def __init__(self, landmarks, witnesses, landmarks_idxs, n_jobs = 1, isomap_eps = 0): #todo: implement other metrices self.landmarks = landmarks self.witnesses = witnesses self.metric_computed = False self.simplex_tree_computed = False self.landmarks_idxs = landmarks_idxs self.isomap_eps = isomap_eps self.distances = pairwise_distances(witnesses, landmarks, n_jobs = n_jobs) if isomap_eps > 0: #distances = pairwise_distances(witnesses, n_jobs = -1) # todo: optimize def _create_large_matrix(): matrix = np.zeros((self.distances.shape[0], self.distances.shape[0])) for i in range(self.distances.shape[0]): for j in range(self.distances.shape[1]): if self.distances[i][j] < self.isomap_eps: matrix[i][landmarks_idxs[j]] = self.distances[i][j] return matrix def _create_small_matrix(matrix): for i in range(self.distances.shape[0]): for j in range(self.distances.shape[1]): self.distances[i][j] = matrix[i][landmarks_idxs[j]] matrix = _create_large_matrix() matrix = csr_matrix(matrix) matrix = floyd_warshall(csgraph = matrix, directed = False) self.distances_isomap = matrix _create_small_matrix(matrix) def compute_simplicial_complex(self, d_max, create_metric=False, r_max=None, create_simplex_tree=False, n_jobs = 1): if n_jobs == 1: self.compute_simplicial_complex_single(d_max=d_max, r_max=r_max) else: self.compute_simplicial_complex_parallel(d_max=d_max, r_max=r_max, n_jobs=n_jobs) def _compute_metric_for_one_witness(self, row): sorted_row = sorted([*enumerate(row)], key=lambda x: x[1]) landmark_dist_w = torch.ones(len(self.landmarks), len(self.landmarks))*math.inf for element in sorted_row: landmark_dist_w[element[0], :] = torch.ones(len(self.landmarks))*element[1] landmark_dist_w[:, element[0]] = torch.ones(len(self.landmarks))*element[1] return landmark_dist_w def compute_metric_optimized(self, n_jobs=1): ''' Computes matrix containing the filtration values for the appearance of 1-simplicies. landmark_dist: n_l x n_l ''' assert isinstance(n_jobs, int) global _compute_metric_multiprocessing def _compute_metric_multiprocessing(distances): landmark_dist_process = torch.ones(len(self.landmarks), len(self.landmarks))*math.inf for row_i in range(distances.shape[0]): row = distances[row_i, :] sorted_row = sorted([*enumerate(row)], key=lambda x: x[1]) landmark_dist_w = torch.ones(len(self.landmarks), len(self.landmarks))*math.inf for element in sorted_row: landmark_dist_w[element[0], :] = torch.ones(len(self.landmarks))*element[1] landmark_dist_w[:, element[0]] = torch.ones(len(self.landmarks))*element[1] landmark_dist_process = \ torch.min(torch.stack((landmark_dist_w, landmark_dist_process)), dim=0)[0] return landmark_dist_process if n_jobs == 1: landmark_dist = torch.ones(len(self.landmarks), len(self.landmarks))*math.inf for row_i in range(self.distances.shape[0]): row = self.distances[row_i, :] landmark_dist_w = self._compute_metric_for_one_witness(row) landmark_dist = \ torch.min(torch.stack((landmark_dist, landmark_dist_w)), dim=0)[0] self.landmarks_dist = landmark_dist self.metric_computed = True else: if n_jobs == -1: n_jobs = os.cpu_count() mp.set_start_method('fork') pool = mp.Pool(processes=n_jobs) distances_chunk = np.array_split(self.distances, n_jobs) results = pool.map(_compute_metric_multiprocessing, distances_chunk) pool.close() pool.join() self.landmarks_dist = torch.min(torch.stack((results)), dim=0)[0] self.metric_computed = True def compute_1d_simplex_tree(self, r_max = None): assert self.metric_computed simplex_tree = gudhi.SimplexTree() for i in range(0, len(self.landmarks)): for j in range(i, len(self.landmarks)): if r_max is None or float(self.landmarks_dist[i][j]) < r_max: simplex_tree.insert([i, j], float(self.landmarks_dist[i][j])) self.simplex_tree = simplex_tree self.simplex_tree_computed = True ######################################################################################### def _update_register_simplex(self, simplicial_complex_temp, i_add, i_dist): simplex_add = [] for e in simplicial_complex_temp: element = e[0] if (element[0] != i_add and len(element) == 1) or (1 < len(element) < 2): element_copy = element.copy() element_copy.append(i_add) simplex_add.append([element_copy, i_dist]) else: pass return simplex_add def compute_simplicial_complex_single(self, d_max, r_max=None): ''' Computes simplex tree and a matrix containing the filtration values for the appearance of 1-simplicies. d_max: max dimension of simplicies in the simplex tree r_max: max filtration value ''' simplicial_complex = [] try: simplex_tree = gudhi.SimplexTree() except: print('Cannot create simplex tree') for row_i in range(self.distances.shape[0]): row = self.distances[row_i, :] # sort row by landmarks witnessed sorted_row = sorted([*enumerate(row)], key=lambda x: x[1]) if r_max != None: sorted_row_new_temp = [] for element in sorted_row: if element[1] < r_max: sorted_row_new_temp.append(element) sorted_row = sorted_row_new_temp simplices_temp = [] for i in range(len(sorted_row)): simplices_temp.append([[sorted_row[i][0]], sorted_row[i][1]]) simplex_add = self._update_register_simplex(simplices_temp.copy(), sorted_row[i][0], sorted_row[i][1]) simplices_temp += simplex_add simplicial_complex += simplices_temp #self.simplicial_complex = simplicial_complex #print(simplicial_complex) sorted_simplicial_compex = sorted(simplicial_complex, key=lambda x: x[1]) for simplex in sorted_simplicial_compex: simplex_tree.insert(simplex[0], filtration=simplex[1]) self.simplex_tree = simplex_tree #t = time.time() self.simplex_tree.expansion(d_max) #t = time.time() - t #print(t) self.simplex_tree_computed = True def compute_simplicial_complex_parallel(self, d_max=math.inf, r_max=math.inf, n_jobs=-1): #global process_wc #@delayed #@wrap_non_picklable_objects def process_wc(distances, ind, r_max=r_max, d_max=d_max): simplicial_complex = [] def update_register_simplex(simplicial_complex, i_add, i_dist): simplex_add = [] for e in simplicial_complex: element = e[0] if (element[0] != i_add and len(element) == 1) or ( 1 < len(element) < 2): element_copy = element.copy() element_copy.append(i_add) simplex_add.append([element_copy, i_dist]) else: pass return simplex_add for row_i in range(distances[ind].shape[0]): row = distances[ind][row_i, :] sorted_row = sorted([*enumerate(row)], key=lambda x: x[1]) if r_max != None: sorted_row_new_temp = [] for element in sorted_row: if element[1] < r_max: sorted_row_new_temp.append(element) sorted_row = sorted_row_new_temp simplices_temp = [] for i in range(len(sorted_row)): simplices_temp.append([[sorted_row[i][0]], sorted_row[i][1]]) simplex_add = update_register_simplex(simplices_temp.copy(), sorted_row[i][0], sorted_row[i][1]) simplices_temp += simplex_add simplicial_complex += simplices_temp return simplicial_complex def combine_results(results): simplicial_complex = [] for result in results: simplicial_complex += result return simplicial_complex try: simplex_tree = gudhi.SimplexTree() except: print('Cannot create simplex tree') if n_jobs == -1: n_jobs = mp.cpu_count() #mp.set_start_method('fork') #pool = mp.Pool(processes=n_jobs) distances_chunk =
np.array_split(self.distances, n_jobs)
numpy.array_split
import torch from torch.utils.data import Dataset, DataLoader import torchvision from pytorch_pretrained_bert import BertTokenizer #import stanfordnlp import os from glob import glob import random import pickle import json import numpy as np #import scipy.io from PIL import Image, ImageDraw from tqdm import tqdm from nltk.tokenize import word_tokenize # -- local import ---------------- #from utils import get_iou, get_include base_dir = 'dataset/LSMDC/' gender_dir = base_dir + 'supplementary/csv_ids' im_dir = base_dir + 'features_mvad/image/' hb_dir = base_dir + 'features_mvad/human_bbox/' hb_agg_dir = base_dir + 'features_mvad/human_pose_agg/' i3d_dir = base_dir + 'features_mvad/i3d_rgb_map/' i3d_agg_dir = base_dir + 'features_mvad/human_i3d/' face_dir = base_dir + 'features_mvad/human_head/' hb_name_idr = base_dir + 'features_mvad/human_id/' mvad_pkl = {'train':base_dir + 'features_mvad/MVAD_train_agg.pkl', 'val':base_dir + 'features_mvad/MVAD_val_agg.pkl', 'test':base_dir + 'features_mvad/MVAD_test_agg.pkl'} class MVADDataset(Dataset): def __init__(self, mode='train', bert_model='bert-base-uncased', max_sent_len=40, hN=8, feats=['i3d_rgb','face']): ''' params: mode: train, val max_sent_len: int iou_threshold: float neg_sample_num: int ''' self.bert_range = 'whole' self.mode = mode self.feats = feats self.hN = hN # sample image number per clip # --- Load MPII data -------------------------- with open(mvad_pkl[mode], 'rb') as f: mvad_data = pickle.load(f) # --- Load Bert --------------------------------- self.tokenizer = BertTokenizer.from_pretrained(bert_model) self.bert_cls_id = self.tokenizer.convert_tokens_to_ids(["[CLS]"])[0] self.bert_sep_id = self.tokenizer.convert_tokens_to_ids(["[SEP]"])[0] self.bert_msk_id = self.tokenizer.convert_tokens_to_ids(["[MASK]"])[0] for agg5 in tqdm(mvad_data, ncols=60): for clip_data in agg5: clip_id = clip_data['clip_id'] word_list = clip_data['word_list'] # --- Tokenize sentence ----------------------- sent_emb = [] word2tok = [] for si, word in enumerate(word_list): if len(word) > 0: word2tok.append(len(sent_emb)) sent_emb += self.tokenize(word) clip_data['bert'] = sent_emb # Change word index into tok index for someone_info in clip_data['someone_info']: someone_info['bert_loc'] = word2tok[someone_info['loc']] try: someone_info['bert_dep'] = word2tok[someone_info['dep']] except: someone_info['bert_dep'] = word2tok[-2] self.datas = mvad_data print("\# of total_data: ", len(self.datas)) def tokenize(self, text, max_len=512): tokenized_text = self.tokenizer.tokenize(text)[:max_len] indexed_tokens = self.tokenizer.convert_tokens_to_ids(tokenized_text) return indexed_tokens def __getitem__(self, idx): ''' idx: 5 x [clip_id, someone_locs, sent_emb] return sent_emb : sN x [L] sent_tok : sN x [L] sent_msk : sN x [L] some_msk : sN x [L] clip_msk : sN x [5] im : [5 x hN x 3 x 224 x 224] im_msk : [5 x hN] pos_5 : [5 x hN x 17 x 2] pos_msk_5: [5 x hN x 17] meta : sN x {'clip_id', 's_idx', 'sent'} ''' # Build Bert agg5 = self.datas[idx] L = sum([len(cd['bert']) for cd in agg5]) + 6 sN = sum([len(cd['someone_info']) for cd in agg5]) sent_emb_t = np.zeros((1, L), dtype=np.int64) sent_tok_t = np.zeros((1, L), dtype=np.int64) sent_msk_t = np.ones((1, L), dtype=np.int64) some_msk_t = np.zeros((sN, L)) dep_root_msk_t = np.zeros((sN, L)) clip_msk_t = np.zeros((sN, 5)) gt_position_t = np.zeros((sN, self.hN)) gt_mat_t = np.zeros((sN, sN)) gt_gender_t = np.zeros((sN, 2)) # 0: logit, 1: mask meta_t, clip_info, s_pids= [], [], [] s_id, cur_len = 0, 1 sent_emb_t[0,0] = self.bert_cls_id for c_idx, cd in enumerate(agg5): # ----- sent processing -------------------------- sent_emb_t[0, cur_len:cur_len + len(cd['bert'])] = cd['bert'] sent_emb_t[0, cur_len + len(cd['bert'])] = self.bert_sep_id pos_trjs, pos_trjs_names, trjs = [], [], {} for s_idx, sd in enumerate(cd['someone_info']): some_msk_t[s_id, sd['bert_loc'] + cur_len] = 1 dep_root_msk_t[s_id, sd['bert_dep'] + cur_len] = 1 clip_msk_t[s_id, c_idx] = 1. trj_id = str(sd['hb_id']) if trj_id not in trjs: trjs[trj_id] = s_idx pos_trjs.append(trj_id) gt_position_t[s_id, trjs[trj_id]] = 1. # gender if sd['gender'] != 2: gt_gender_t[s_id][0] = sd['gender'] gt_gender_t[s_id][1] = 1 s_pids.append(sd['name']) pos_trjs_names.append(sd['name']) meta_t.append({'clip_id': cd['clip_id'], 'c_idx': c_idx, 's_idx': s_idx, 't_gt_idx': trjs[str(trj_id)], 'sent': cd['sent']}) s_id += 1 cur_len += len(cd['bert']) + 1 clip_info.append((cd['clip_id'], pos_trjs, pos_trjs_names)) # Text re-id GT for i in range(sN): for j in range(sN): if s_pids[i] == s_pids[j]: gt_mat_t[i][j] = 1. # Build Visual hN = self.hN im_5, im_msk_5, bbox_meta_5 = [], np.zeros((5,hN)), np.zeros((5,hN,4)) pos_5, pos_msk_5 = np.zeros((5,hN,17,2)), np.zeros((5,hN,17)) i3d_rgb_5, i3d_flow_5 = np.zeros((5,hN,1024)), np.zeros((5, hN, 1024)) face_5, face_msk_5 = np.zeros((5,hN,512)), np.zeros((5,hN)) gt_vmat, gt_vmat_msk =
np.zeros((5*hN, 5*hN))
numpy.zeros
#!/usr/bin/env python # coding: utf-8 # # Project: Azimuthal integration # https://github.com/silx-kit/pyFAI # # Copyright (C) 2015-2018 European Synchrotron Radiation Facility, Grenoble, France # # Principal author: <NAME> (<EMAIL>) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import division, print_function, absolute_import """Test suite for math utilities library""" __author__ = "<NAME>" __contact__ = "<EMAIL>" __license__ = "MIT" __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" __date__ = "17/05/2019" import unittest import numpy from pyFAI.utils import ellipse as ellipse_mdl def modulo(value, div=numpy.pi): """hack to calculate the value%div but returns the smallest absolute value, possibly negative""" q = value / div i = round(q) return (i - q) * div class TestEllipse(unittest.TestCase): def test_ellipse(self): angles = numpy.arange(0, numpy.pi * 2, 0.2) pty = numpy.sin(angles) * 20 + 50 ptx = numpy.cos(angles) * 10 + 100 ellipse = ellipse_mdl.fit_ellipse(pty, ptx) self.assertAlmostEqual(ellipse.center_1, 50) self.assertAlmostEqual(ellipse.center_2, 100) self.assertAlmostEqual(ellipse.half_long_axis, 20) self.assertAlmostEqual(ellipse.half_short_axis, 10) self.assertAlmostEqual(modulo(ellipse.angle), 0) def test_ellipse2(self): angles = numpy.arange(0, numpy.pi * 2, 0.2) pty = numpy.sin(angles) * 10 + 50 ptx = numpy.cos(angles) * 20 + 100 ellipse = ellipse_mdl.fit_ellipse(pty, ptx) self.assertAlmostEqual(ellipse.center_1, 50) self.assertAlmostEqual(ellipse.center_2, 100) self.assertAlmostEqual(ellipse.half_long_axis, 20) self.assertAlmostEqual(ellipse.half_short_axis, 10) self.assertAlmostEqual(modulo(ellipse.angle), 0) def test_half_circle(self): angles = numpy.linspace(0, numpy.pi, 10) pty = numpy.sin(angles) * 20 + 10 ptx = numpy.cos(angles) * 20 + 10 ellipse = ellipse_mdl.fit_ellipse(pty, ptx) self.assertAlmostEqual(ellipse.center_1, 10) self.assertAlmostEqual(ellipse.center_2, 10) self.assertAlmostEqual(ellipse.half_long_axis, 20) self.assertAlmostEqual(ellipse.half_short_axis, 20) def test_quarter_circle(self): angles = numpy.linspace(0, numpy.pi / 2, 10) pty = numpy.sin(angles) * 20 + 10 ptx = numpy.cos(angles) * 20 + 10 ellipse = ellipse_mdl.fit_ellipse(pty, ptx) self.assertAlmostEqual(ellipse.center_1, 10) self.assertAlmostEqual(ellipse.center_2, 10) self.assertAlmostEqual(ellipse.half_long_axis, 20) self.assertAlmostEqual(ellipse.half_short_axis, 20) def test_halfquater_circle_5ptx(self): angles = numpy.linspace(0, numpy.pi / 4, 5) pty = numpy.sin(angles) * 20 + 10 ptx = numpy.cos(angles) * 20 + 10 ellipse = ellipse_mdl.fit_ellipse(pty, ptx) self.assertAlmostEqual(ellipse.center_1, 10, places=5) self.assertAlmostEqual(ellipse.center_2, 10, places=5) self.assertAlmostEqual(ellipse.half_long_axis, 20, places=5) self.assertAlmostEqual(ellipse.half_short_axis, 20, places=5) def test_centered_to_zero(self): angles = numpy.linspace(0, numpy.pi, 10) pty = numpy.sin(angles) * 20 ptx = numpy.cos(angles) * 20 ellipse = ellipse_mdl.fit_ellipse(pty, ptx) self.assertAlmostEqual(ellipse.center_1, 0, places=5) self.assertAlmostEqual(ellipse.center_2, 0, places=5) self.assertAlmostEqual(ellipse.half_long_axis, 20, places=5) self.assertAlmostEqual(ellipse.half_short_axis, 20, places=5) def test_line(self): pty =
numpy.arange(10)
numpy.arange
import copy import numpy as np from .grid import Grid, CachedData def array_at_verts_basic2d(a): """ Computes values at cell vertices on 2d array using neighbor averaging. Parameters ---------- a : ndarray Array values at cell centers, could be a slice in any orientation. Returns ------- averts : ndarray Array values at cell vertices, shape (a.shape[0]+1, a.shape[1]+1). """ assert a.ndim == 2 shape_verts2d = (a.shape[0]+1, a.shape[1]+1) # create a 3D array of size (nrow+1, ncol+1, 4) averts3d = np.full(shape_verts2d + (4,), np.nan) averts3d[:-1, :-1, 0] = a averts3d[:-1, 1:, 1] = a averts3d[1:, :-1, 2] = a averts3d[1:, 1:, 3] = a # calculate the mean over the last axis, ignoring NaNs averts = np.nanmean(averts3d, axis=2) return averts class StructuredGrid(Grid): """ class for a structured model grid Parameters ---------- delc delc array delr delr array Properties ---------- nlay returns the number of model layers nrow returns the number of model rows ncol returns the number of model columns delc returns the delc array delr returns the delr array xyedges returns x-location points for the edges of the model grid and y-location points for the edges of the model grid Methods ---------- get_cell_vertices(i, j) returns vertices for a single cell at row, column i, j. """ def __init__(self, delc=None, delr=None, top=None, botm=None, idomain=None, lenuni=None, epsg=None, proj4=None, prj=None, xoff=0.0, yoff=0.0, angrot=0.0, nlay=None, nrow=None, ncol=None, laycbd=None): super(StructuredGrid, self).__init__('structured', top, botm, idomain, lenuni, epsg, proj4, prj, xoff, yoff, angrot) if delc is not None: self.__nrow = len(delc) self.__delc = delc.astype(float) else: self.__nrow = nrow self.__delc = delc if delr is not None: self.__ncol = len(delr) self.__delr = delr.astype(float) else: self.__ncol = ncol self.__delr = delr if top is not None: assert self.__nrow * self.__ncol == len(np.ravel(top)) if botm is not None: assert self.__nrow * self.__ncol == len(np.ravel(botm[0])) if nlay is not None: self.__nlay = nlay else: if laycbd is not None: self.__nlay = len(botm) - np.sum(laycbd>0) else: self.__nlay = len(botm) else: self.__nlay = nlay if laycbd is not None: self.__laycbd = laycbd else: self.__laycbd = np.zeros(self.__nlay, dtype=int) #################### # Properties #################### @property def is_valid(self): if self.__delc is not None and self.__delr is not None: return True return False @property def is_complete(self): if self.__delc is not None and self.__delr is not None and \ super(StructuredGrid, self).is_complete: return True return False @property def nlay(self): return self.__nlay @property def nrow(self): return self.__nrow @property def ncol(self): return self.__ncol @property def nnodes(self): return self.__nlay * self.__nrow * self.__ncol @property def shape(self): return self.__nlay, self.__nrow, self.__ncol @property def extent(self): self._copy_cache = False xyzgrid = self.xyzvertices self._copy_cache = True return (np.min(xyzgrid[0]), np.max(xyzgrid[0]), np.min(xyzgrid[1]), np.max(xyzgrid[1])) @property def delc(self): return copy.deepcopy(self.__delc) @property def delr(self): return copy.deepcopy(self.__delr) @property def delz(self): cache_index = 'delz' if cache_index not in self._cache_dict or \ self._cache_dict[cache_index].out_of_date: delz = self.top_botm[:-1, :, :] - self.top_botm[1:, :, :] self._cache_dict[cache_index] = CachedData(delz) if self._copy_cache: return self._cache_dict[cache_index].data else: return self._cache_dict[cache_index].data_nocopy @property def top_botm_withnan(self): """ Same as top_botm array but with NaN where idomain==0 both above and below a cell. """ cache_index = 'top_botm_withnan' if cache_index not in self._cache_dict or \ self._cache_dict[cache_index].out_of_date: is_inactive_above = np.full(self.top_botm.shape, True) is_inactive_above[:-1, :, :] = self._idomain==0 is_inactive_below = np.full(self.top_botm.shape, True) is_inactive_below[1:, :, :] = self._idomain==0 where_to_nan = np.logical_and(is_inactive_above, is_inactive_below) top_botm_withnan = np.where(where_to_nan, np.nan, self.top_botm) self._cache_dict[cache_index] = CachedData(top_botm_withnan) if self._copy_cache: return self._cache_dict[cache_index].data else: return self._cache_dict[cache_index].data_nocopy @property def xyzvertices(self): """ Method to get all grid vertices in a layer Returns: [] 2D array """ cache_index = 'xyzgrid' if cache_index not in self._cache_dict or \ self._cache_dict[cache_index].out_of_date: xedge = np.concatenate(([0.], np.add.accumulate(self.__delr))) length_y = np.add.reduce(self.__delc) yedge = np.concatenate(([length_y], length_y - np.add.accumulate(self.delc))) xgrid, ygrid = np.meshgrid(xedge, yedge) zgrid, zcenter = self._zcoords() if self._has_ref_coordinates: # transform x and y pass xgrid, ygrid = self.get_coords(xgrid, ygrid) if zgrid is not None: self._cache_dict[cache_index] = \ CachedData([xgrid, ygrid, zgrid]) else: self._cache_dict[cache_index] = \ CachedData([xgrid, ygrid]) if self._copy_cache: return self._cache_dict[cache_index].data else: return self._cache_dict[cache_index].data_nocopy @property def xyedges(self): """ Return a list of two 1D numpy arrays: one with the cell edge x coordinate (size = ncol+1) and the other with the cell edge y coordinate (size = nrow+1) in model space - not offset or rotated. """ cache_index = 'xyedges' if cache_index not in self._cache_dict or \ self._cache_dict[cache_index].out_of_date: xedge = np.concatenate(([0.], np.add.accumulate(self.__delr))) length_y = np.add.reduce(self.__delc) yedge = np.concatenate(([length_y], length_y - np.add.accumulate(self.delc))) self._cache_dict[cache_index] = \ CachedData([xedge, yedge]) if self._copy_cache: return self._cache_dict[cache_index].data else: return self._cache_dict[cache_index].data_nocopy @property def zedges(self): """ Return zedges for (column, row)==(0, 0). """ cache_index = 'zedges' if cache_index not in self._cache_dict or \ self._cache_dict[cache_index].out_of_date: zedge = np.concatenate((np.array([self.top[0, 0]]), self.botm[:, 0, 0])) self._cache_dict[cache_index] = \ CachedData(zedge) if self._copy_cache: return self._cache_dict[cache_index].data else: return self._cache_dict[cache_index].data_nocopy @property def zverts_smooth(self): """ Get a unique z of cell vertices for smooth (instead of stepwise) layer elevations using bilinear interpolation. Returns ------- zverts : ndarray, shape (nlay+1, nrow+1, ncol+1) z of cell vertices. NaN values are assigned in accordance with inactive cells defined by idomain. """ cache_index = 'zverts_smooth' if cache_index not in self._cache_dict or \ self._cache_dict[cache_index].out_of_date: zverts_smooth = self._zverts_smooth() self._cache_dict[cache_index] = CachedData(zverts_smooth) if self._copy_cache: return self._cache_dict[cache_index].data else: return self._cache_dict[cache_index].data_nocopy def _zverts_smooth(self): """ For internal use only. The user should call zverts_smooth. """ # initialize the result array shape_verts = (self.nlay+1, self.nrow+1, self.ncol+1) zverts_basic = np.empty(shape_verts, dtype='float64') # assign NaN to top_botm where idomain==0 both above and below if self._idomain is not None: _top_botm = self.top_botm_withnan # perform basic interpolation (this will be useful in all cases) # loop through layers for k in range(self.nlay+1): zvertsk = array_at_verts_basic2d(_top_botm[k, : , :]) zverts_basic[k, : , :] = zvertsk if self.is_regular(): # if the grid is regular, basic interpolation is the correct one zverts = zverts_basic else: # cell centers xcenters, ycenters = self.get_local_coords(self.xcellcenters, self.ycellcenters) # flip y direction because RegularGridInterpolator requires # increasing input coordinates ycenters = np.flip(ycenters, axis=0) _top_botm = np.flip(_top_botm, axis=1) xycenters = (ycenters[:, 0], xcenters[0, :]) # vertices xverts, yverts = self.get_local_coords(self.xvertices, self.yvertices) xyverts = np.ndarray((xverts.size, 2)) xyverts[:, 0] = yverts.ravel() xyverts[:, 1] = xverts.ravel() # interpolate import scipy.interpolate as interp shape_verts2d = (self.nrow+1, self.ncol+1) zverts = np.empty(shape_verts, dtype='float64') # loop through layers for k in range(self.nlay+1): # interpolate layer elevation zcenters_k = _top_botm[k, : , :] interp_func = interp.RegularGridInterpolator(xycenters, zcenters_k, bounds_error=False, fill_value=np.nan) zverts_k = interp_func(xyverts) zverts_k = zverts_k.reshape(shape_verts2d) zverts[k, : , :] = zverts_k # use basic interpolation for remaining NaNs at boundaries where_nan = np.isnan(zverts) zverts[where_nan] = zverts_basic[where_nan] return zverts @property def xyzcellcenters(self): """ Return a list of two numpy one-dimensional float array one with the cell center x coordinate and the other with the cell center y coordinate for every row in the grid in model space - not offset of rotated, with the cell center y coordinate. """ cache_index = 'cellcenters' if cache_index not in self._cache_dict or \ self._cache_dict[cache_index].out_of_date: # get x centers x = np.add.accumulate(self.__delr) - 0.5 * self.delr # get y centers Ly = np.add.reduce(self.__delc) y = Ly - (np.add.accumulate(self.__delc) - 0.5 * self.__delc) x_mesh, y_mesh = np.meshgrid(x, y) if self.__nlay is not None: # get z centers z = np.empty((self.__nlay, self.__nrow, self.__ncol)) z[0, :, :] = (self._top[:, :] + self._botm[0, :, :]) / 2. ibs = np.arange(self.__nlay) quasi3d = [cbd !=0 for cbd in self.__laycbd] if np.any(quasi3d): ibs[1:] = ibs[1:] + np.cumsum(quasi3d)[:self.__nlay - 1] for l, ib in enumerate(ibs[1:], 1): z[l, :, :] = (self._botm[ib - 1, :, :] + self._botm[ib, :, :]) / 2. else: z = None if self._has_ref_coordinates: # transform x and y x_mesh, y_mesh = self.get_coords(x_mesh, y_mesh) # store in cache self._cache_dict[cache_index] = CachedData([x_mesh, y_mesh, z]) if self._copy_cache: return self._cache_dict[cache_index].data else: return self._cache_dict[cache_index].data_nocopy @property def grid_lines(self): """ Get the grid lines as a list """ # get edges initially in model coordinates use_ref_coords = self.use_ref_coords self.use_ref_coords = False xyedges = self.xyedges self.use_ref_coords = use_ref_coords xmin = xyedges[0][0] xmax = xyedges[0][-1] ymin = xyedges[1][-1] ymax = xyedges[1][0] lines = [] # Vertical lines for j in range(self.ncol + 1): x0 = xyedges[0][j] x1 = x0 y0 = ymin y1 = ymax lines.append([(x0, y0), (x1, y1)]) # horizontal lines for i in range(self.nrow + 1): x0 = xmin x1 = xmax y0 = xyedges[1][i] y1 = y0 lines.append([(x0, y0), (x1, y1)]) if self._has_ref_coordinates: lines_trans = [] for ln in lines: lines_trans.append([self.get_coords(*ln[0]), self.get_coords(*ln[1])]) return lines_trans return lines ############### ### Methods ### ############### def intersect(self, x, y, local=False, forgive=False): """ Get the row and column of a point with coordinates x and y When the point is on the edge of two cells, the cell with the lowest row or column is returned. Parameters ---------- x : float The x-coordinate of the requested point y : float The y-coordinate of the requested point local: bool (optional) If True, x and y are in local coordinates (defaults to False) forgive: bool (optional) Forgive x,y arguments that fall outside the model grid and return NaNs instead (defaults to False - will throw exception) Returns ------- row : int The row number col : int The column number """ # transform x and y to local coordinates x, y = super(StructuredGrid, self).intersect(x, y, local, forgive) # get the cell edges in local coordinates xe, ye = self.xyedges xcomp = x > xe if np.all(xcomp) or not np.any(xcomp): if forgive: col = np.nan else: raise Exception( 'x, y point given is outside of the model area') else: col = np.where(xcomp)[0][-1] ycomp = y < ye if np.all(ycomp) or not np.any(ycomp): if forgive: row = np.nan else: raise Exception( 'x, y point given is outside of the model area') else: row = np.where(ycomp)[0][-1] if np.any(np.isnan([row, col])): row = col = np.nan return row, col def _cell_vert_list(self, i, j): """Get vertices for a single cell or sequence of i, j locations.""" self._copy_cache = False pts = [] xgrid, ygrid = self.xvertices, self.yvertices pts.append([xgrid[i, j], ygrid[i, j]]) pts.append([xgrid[i + 1, j], ygrid[i + 1, j]]) pts.append([xgrid[i + 1, j + 1], ygrid[i + 1, j + 1]]) pts.append([xgrid[i, j + 1], ygrid[i, j + 1]]) pts.append([xgrid[i, j], ygrid[i, j]]) self._copy_cache = True if np.isscalar(i): return pts else: vrts = np.array(pts).transpose([2, 0, 1]) return [v.tolist() for v in vrts] def get_cell_vertices(self, i, j): """ Method to get a set of cell vertices for a single cell used in the Shapefile export utilities :param i: (int) cell row number :param j: (int) cell column number :return: list of x,y cell vertices """ self._copy_cache = False cell_verts = [(self.xvertices[i, j], self.yvertices[i, j]), (self.xvertices[i, j+1], self.yvertices[i, j+1]), (self.xvertices[i+1, j+1], self.yvertices[i+1, j+1]), (self.xvertices[i+1, j], self.yvertices[i+1, j]),] self._copy_cache = True return cell_verts def plot(self, **kwargs): """ Plot the grid lines. Parameters ---------- kwargs : ax, colors. The remaining kwargs are passed into the the LineCollection constructor. Returns ------- lc : matplotlib.collections.LineCollection """ from ..plot import PlotMapView mm = PlotMapView(modelgrid=self) return mm.plot_grid(**kwargs) # Importing @classmethod def from_gridspec(cls, gridspec_file, lenuni=0): f = open(gridspec_file, 'r') raw = f.readline().strip().split() nrow = int(raw[0]) ncol = int(raw[1]) raw = f.readline().strip().split() xul, yul, rot = float(raw[0]), float(raw[1]), float(raw[2]) delr = [] j = 0 while j < ncol: raw = f.readline().strip().split() for r in raw: if '*' in r: rraw = r.split('*') for n in range(int(rraw[0])): delr.append(float(rraw[1])) j += 1 else: delr.append(float(r)) j += 1 delc = [] i = 0 while i < nrow: raw = f.readline().strip().split() for r in raw: if '*' in r: rraw = r.split('*') for n in range(int(rraw[0])): delc.append(float(rraw[1])) i += 1 else: delc.append(float(r)) i += 1 f.close() grd = cls(np.array(delc), np.array(delr), lenuni=lenuni) xll = grd._xul_to_xll(xul) yll = grd._yul_to_yll(yul) cls.set_coord_info(xoff=xll, yoff=yll, angrot=rot) return cls # Exporting def write_shapefile(self, filename='grid.shp', epsg=None, prj=None): """ Write a shapefile of the grid with just the row and column attributes. """ from ..export.shapefile_utils import write_grid_shapefile if epsg is None and prj is None: epsg = self.epsg write_grid_shapefile(filename, self, array_dict={}, nan_val=-1.0e9, epsg=epsg, prj=prj) def is_regular(self): """ Test whether the grid spacing is regular or not (including in the vertical direction). """ # Relative tolerance to use in test rel_tol = 1.e-5 # Regularity test in x direction rel_diff_x = (self.delr - self.delr[0]) / self.delr[0] is_regular_x =
np.count_nonzero(rel_diff_x > rel_tol)
numpy.count_nonzero
""" Single Neuron Linear Regression with data normalization N = #Samples i = [0, ... ,N] M = Dimension of samples +1(offset b) Output a_i a_i = w.transpose()*x_i Cost C C = sum(0.5*(a_i-y_i)**2) """ import numpy as np from dataset1_linreg import DataSet def get_norm_params(x_arr): mean_x =
np.sum(x_arr, axis=1)
numpy.sum
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import cv2 import json import time import numpy as np import tensorflow as tf from queue import Queue from threading import Thread from merceedge.tests.detect_object.utils.app_utils import FPS, WebcamVideoStream, draw_boxes_and_labels from merceedge.tests.detect_object.object_detection.utils import label_map_util from merceedge.core import WireLoad CWD_PATH = os.path.dirname(os.path.realpath(__file__)) # CWD_PATH = os.getcwd() # Path to frozen detection graph. This is the actual model that is used for the object detection. MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017' PATH_TO_CKPT = os.path.join(CWD_PATH, '..', 'detect_object', 'object_detection', MODEL_NAME, 'frozen_inference_graph.pb') # List of the strings that is used to add correct label for each box. PATH_TO_LABELS = os.path.join(CWD_PATH, '..', 'detect_object', 'object_detection', 'data', 'mscoco_label_map.pbtxt') NUM_CLASSES = 90 # Loading label map label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) def detect_objects(image_np, sess, detection_graph, min_score_thresh=0.5): # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the objects. # Score is shown on the result image, together with the class label. scores = detection_graph.get_tensor_by_name('detection_scores:0') classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection. rect_points, class_names, class_colors = draw_boxes_and_labels( boxes=
np.squeeze(boxes)
numpy.squeeze
import os import time import numpy as np base_dir = "/data/datasets/fake_512x512" output_dir = os.path.join(base_dir, 'preprocessed') number_of_files = 200 # Validate inputs os.makedirs(output_dir, exist_ok=True) def generate(i): output_file = os.path.join(output_dir, 'np_stack_{}.npz'.format(i)) start = time.time() img = np.random.rand(2, 512, 512) label = np.zeros((2, 512, 512)) stack =
np.stack((img, label))
numpy.stack
from src.generator.Generator import Generator from src.dataset.Dataset import Dataset from src.environment.EnvironmentManager import EnvironmentManager as EM from typing import List from os import path from src.util.Interpolation import slerp import numpy as np STYLESWIN_NAME = "styleswin" class StyleSwinGenerator(Generator): _DIM_Z = 512 _PATH_TO_IMAGES = "environment/styleswin/out/" _IMAGE_EXT = ".png" def __init__(self, dataset: Dataset): """ Constructs a new StyleSwin generator. Args: dataset (Dataset): The dataset to associate the generator with. """ super().__init__(STYLESWIN_NAME, dataset) def latent_space_std(self) -> np.ndarray: return
np.ones(self._DIM_Z)
numpy.ones
import mdtraj as md import networkx as nx import numpy as np import matplotlib.pyplot as plt from collections import defaultdict import scipy.optimize import unyt as u class BondCalculator: def __init__(self, traj, T): self.traj = traj graph = traj.top.to_bondgraph() bonds = self.identify_bonds(graph) angles = self.identify_angles(graph) bond_params = dict() angle_params = dict() for bond_type, pairs in bonds.items(): bond_lengths, bond_prob = self.calc_lengths(pairs, range=[0, 1.0]) params = self.calc_parameters(bond_lengths, bond_prob) k = 2 * u.kb * (T*u.K) / (params[0] * u.nm)**2 * u.Na l0 = params[1] * u.nm bond_params[bond_type]= {"k": k, "x0": l0} for angle_type, triplets in angles.items(): bond_angles, angle_prob = self.calc_angles(triplets, range=[0, 2*np.pi]) params = self.calc_parameters(bond_angles, angle_prob) k = 2 * u.kb * (T*u.K) / (params[0] * u.rad)**2 * u.Na t0 = params[1] * u.rad angle_params[angle_type]= {"k": k, "x0": t0} self.bond_params = bond_params self.angle_params = angle_params def identify_bonds(self, graph): all_bonds = [edge for edge in graph.edges] bonds = defaultdict(list) for bond in all_bonds: index = tuple(sorted([bond[0].name, bond[1].name])) pair = tuple([particle.index for particle in bond]) bonds[index].append(pair) return bonds def identify_angles(self, graph): angle_subgraph = nx.Graph() angle_subgraph.add_edge(0, 1) angle_subgraph.add_edge(1, 2) matcher = nx.algorithms.isomorphism.GraphMatcher(graph, angle_subgraph) all_angles = [] for m in matcher.subgraph_isomorphisms_iter(): all_angles.append(tuple(k for k in m.keys())) angles = defaultdict(list) for angle in all_angles: index = tuple(particle.name for particle in angle) if angle[0].name < angle[2].name: index = tuple(reversed(index)) triplet = tuple(particle.index for particle in angle) angles[index].append(triplet) return angles def calc_lengths(self, pairs, range=None): quantity = md.compute_distances(self.traj, pairs) hist, edges = np.histogram(quantity, density=True, range=range, bins=200) bins = (edges[1:]+edges[:-1]) * 0.5 return bins, hist def calc_angles(self, triplets, range=None): quantity = md.compute_angles(self.traj, triplets) hist, edges = np.histogram(quantity, density=True, range=range, bins=200) bins = (edges[1:]+edges[:-1]) * 0.5 hist /= np.sin(bins) hist /= np.sum(hist)*(bins[1]-bins[0]) return bins, hist def cost_function(self, args, x, y): w, x0 = args return np.sum((self.gaussian(w, x0, x) - y)**2) def gaussian(self, w, x0, x): return ((w *
np.sqrt(np.pi / 2)
numpy.sqrt
import numpy as np from classy import Class from linear_theory import f_of_a from velocileptors.LPT.lpt_rsd_fftw import LPT_RSD # k vector to use: kvec = np.concatenate( ([0.0005,],\ np.logspace(np.log10(0.0015),np.log10(0.025),10, endpoint=True),\ np.arange(0.03,0.51,0.01)) ) # Reference Cosmology: z = 0.61 Omega_M = 0.31 fb = 0.1571 h = 0.6766 ns = 0.9665 speed_of_light = 2.99792458e5 pkparams = { 'output': 'mPk', 'P_k_max_h/Mpc': 20., 'z_pk': '0.0,10', 'A_s': np.exp(3.040)*1e-10, 'n_s': 0.9665, 'h': h, 'N_ur': 3.046, 'N_ncdm': 0,#1, #'m_ncdm': 0, 'tau_reio': 0.0568, 'omega_b': h**2 * fb * Omega_M, 'omega_cdm': h**2 * (1-fb) * Omega_M} import time t1 = time.time() pkclass = Class() pkclass.set(pkparams) pkclass.compute() Hz_fid = pkclass.Hubble(z) * speed_of_light / h # this H(z) in units km/s/(Mpc/h) = 100 * E(z) chiz_fid = pkclass.angular_distance(z) * (1.+z) * h # this is the comoving radius in units of Mpc/h print(Hz_fid, chiz_fid) def compute_pell_tables(pars, z=0.61, fid_dists= (Hz_fid,chiz_fid) ): OmegaM, h, sigma8 = pars Hzfid, chizfid = fid_dists omega_b = 0.02242 lnAs = 3.047 ns = 0.9665 nnu = 1 nur = 2.033 mnu = 0.06 omega_nu = 0.0106 * mnu omega_c = (OmegaM - omega_b/h**2 - omega_nu/h**2) * h**2 pkparams = { 'output': 'mPk', 'P_k_max_h/Mpc': 20., 'z_pk': '0.0,10', 'A_s': np.exp(lnAs)*1e-10, 'n_s': ns, 'h': h, 'N_ur': nur, 'N_ncdm': nnu, 'm_ncdm': mnu, 'tau_reio': 0.0568, 'omega_b': omega_b, 'omega_cdm': omega_c} pkclass = Class() pkclass.set(pkparams) pkclass.compute() # Caluclate AP parameters Hz = pkclass.Hubble(z) * speed_of_light / h # this H(z) in units km/s/(Mpc/h) = 100 * E(z) chiz = pkclass.angular_distance(z) * (1.+z) * h # this is the comoving radius in units of Mpc/h apar, aperp = Hzfid / Hz, chiz / chizfid # Calculate growth rate fnu = pkclass.Omega_nu / pkclass.Omega_m() f = f_of_a(1/(1.+z), OmegaM=OmegaM) * (1 - 0.6 * fnu) # Calculate and renormalize power spectrum ki =
np.logspace(-3.0,1.0,200)
numpy.logspace
import numpy from scipy import optimize import algopy ## This is y-data: y_data = numpy.array([0.2867, 0.1171, -0.0087, 0.1326, 0.2415, 0.2878, 0.3133, 0.3701, 0.3996, 0.3728, 0.3551, 0.3587, 0.1408, 0.0416, 0.0708, 0.1142, 0, 0, 0]) ## This is x-data: t =
numpy.array([67., 88, 104, 127, 138, 160, 169, 188, 196, 215, 240, 247, 271, 278, 303, 305, 321, 337, 353])
numpy.array
#!/usr/bin/env python # coding: utf-8 # <NAME> used car sales service is developing an app to attract new customers. In that app, you can quickly find out the market value of your car. You have access to historical data: technical specifications, trim versions, and prices. You need to build the model to determine the value. # # <NAME> is interested in: # # - the quality of the prediction; # - the speed of the prediction; # - the time required for training # # --- # Features # # - DateCrawled — date profile was downloaded from the database # - VehicleType — vehicle body type # - RegistrationYear — vehicle registration year # - Gearbox — gearbox type # - Power — power (hp) # - Model — vehicle model # - Mileage — mileage (measured in km due to dataset's regional specifics) # - RegistrationMonth — vehicle registration month # - FuelType — fuel type # - Brand — vehicle brand # - NotRepaired — vehicle repaired or not # - DateCreated — date of profile creation # - NumberOfPictures — number of vehicle pictures # - PostalCode — postal code of profile owner (user) # - LastSeen — date of the last activity of the user # # Target # - Price — price (Euro) # # Analysis done January 2022 # ## Data preparation # In[1]: # import libraries import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import math import time import lightgbm as lgb from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.ensemble import RandomForestRegressor from sklearn.tree import DecisionTreeRegressor from catboost import CatBoostRegressor from sklearn.model_selection import cross_val_score from sklearn.metrics import make_scorer from sklearn.model_selection import RandomizedSearchCV import random random_state=42 random.seed(random_state) np.random.seed(random_state) # import sys and insert code to ignore warnings import sys if not sys.warnoptions: import warnings warnings.simplefilter("ignore") # __Helper functions__ # In[2]: # function for timing execution of cell [refrence](https://stackoverflow.com/questions/52738709/how-to-store-time-values-in-a-variable-in-jupyter) # couldn't get it to work though... def exec_time(start, end): diff_time = end - start m, s = divmod(diff_time, 60) h, m = divmod(m, 60) s,m,h = int(round(s, 0)), int(round(m, 0)), int(round(h, 0)) print("time: " + "{0:02d}:{1:02d}:{2:02d}".format(h, m, s)) # function for displaying outlier statistics for column def outlier_stats(data): data_mean, data_std = np.mean(data),
np.std(data)
numpy.std
import numpy as np import pandas as pd from tensorflow import keras class KerasAgent: def __init__(self, num_bandits, filename, margin=0.99): self.total_reward = 0 self.filename = filename self.margin = margin self.model = keras.models.load_model(self.filename) self.machine_states = pd.DataFrame( index=range(num_bandits), columns=['step', 'n_pulls', 'n_success', 'n_opp_pulls', 'streak', 'win_streak', 'opp_streak'] ).fillna(0) def description(self): return f"Keras - {self.filename}, margin:{self.margin:.2f}" def step(self, observation, configuration): if observation.step == 0: return np.random.randint(configuration.banditCount) reward = observation.reward - self.total_reward self.total_reward = observation.reward last_action = observation.lastActions[observation.agentIndex] opp_action = observation.lastActions[1 - observation.agentIndex] self.machine_states['step'] = observation.step self.machine_states.at[last_action, 'n_pulls'] += 1 self.machine_states.at[last_action, 'n_success'] += reward self.machine_states.at[opp_action, 'n_opp_pulls'] += 1 self.machine_states.at[last_action, 'streak'] += 1 self.machine_states.loc[self.machine_states.index != last_action, 'streak'] = 0 self.machine_states.at[opp_action, 'opp_streak'] += 1 self.machine_states.loc[self.machine_states.index != opp_action, 'opp_streak'] = 0 if reward: self.machine_states.at[last_action, 'win_streak'] += 1 else: self.machine_states.at[last_action, 'win_streak'] = 0 probs = self.model(self.machine_states.to_numpy()) max_return =
np.max(probs)
numpy.max
import pandas as pd import numpy as np from plantcv.plantcv import params def constellaqc(denovo_groups, annotated_groups): """ Compare de novo annotations of Constella to known standards in order to estimate error rates Inputs: denovo_groups = A pandas array representing homology groups predicted by Constella for plms annotated_groups = A pandas array representing the true biological identities of plms :param denovo_groups: pandas.core.frame.DataFrame :param annotated_groups: pandas.core.frame.DataFrame """ known_feat = np.unique(annotated_groups.loc[:, 'group']) pred_group = np.unique(denovo_groups.loc[:, 'group']) scores = [] for anno in known_feat: # anno_bool_index = annotated_groups.loc[:, 'group'] == anno anno_group_calls = denovo_groups.loc[annotated_groups.loc[:, 'group'] == anno, 'group'].values # print(anno, 'count: ', np.sum(anno_bool_index)) score_row = [] for denovo in pred_group: score_row.append(np.sum(anno_group_calls == denovo)) scores.append(score_row) scores = pd.DataFrame(scores, index=known_feat, columns=pred_group) if params.debug is not None: print('Known Feature-Predicted Group Scoring Matrix:\n') print(scores) anno_sum = [] anno_no = [] anno_error = [] ni = [] for anno in known_feat: anno_sum.append(np.sum(scores.loc[anno, :].values)) anno_no.append(np.sum(scores.loc[anno, :].values != 0)) anno_error.append(np.sum(scores.loc[anno, :].values != 0) - 1) ni.append(1) pred_sum = [] pred_no = [] pred_error = [] nj = [] for denovo in pred_group: pred_sum.append(np.sum(scores.loc[:, denovo].values)) pred_no.append(np.sum(scores.loc[:, denovo].values != 0)) pred_error.append(
np.sum(scores.loc[:, denovo].values != 0)
numpy.sum
#!/usr/bin/env python # encoding: utf-8 """ UtilizationSupplement.py Copyright (c) NREL. All rights reserved. """ from math import atan2 import numpy as np from wisdem.commonse.constants import eps from wisdem.commonse.utilities import CubicSplineSegment, cubic_spline_eval, smooth_max, smooth_min, nodal2sectional, sectional2nodal from openmdao.api import ExplicitComponent from scipy.optimize import brentq, minimize_scalar #------------------------------------------------------------------------------- # Name: UtilizationSupplement.py # Purpose: It contains functions to calculate utilizations for cylindric members, # for instance tower sections and monopile # # Author: ANing/RRD/GBarter # # Created: 07/14/2015 - It is based on towerSupplement.py by ANing, 2012. # Copyright: (c) rdamiani 2015 # Licence: <Apache 2015> #------------------------------------------------------------------------------- class GeometricConstraints(ExplicitComponent): """docstring for OtherConstraints""" def initialize(self): self.options.declare('nPoints') self.options.declare('diamFlag', default=True) def setup(self): nPoints = self.options['nPoints'] self.add_input('d', np.zeros(nPoints), units='m') self.add_input('t', np.zeros(nPoints-1), units='m') self.add_input('min_d_to_t', 120.0) self.add_input('max_taper', 0.4) self.add_output('weldability', np.zeros(nPoints-1)) self.add_output('manufacturability', np.zeros(nPoints-1)) # Derivatives self.declare_partials('*', '*', method='fd', form='central', step=1e-6) def compute(self, inputs, outputs): diamFlag = self.options['diamFlag'] d,_ = nodal2sectional(inputs['d']) t = inputs['t'] # Check if the input was radii instead of diameters and convert if necessary if not diamFlag: d *= 2.0 min_d_to_t = inputs['min_d_to_t'] max_taper = inputs['max_taper'] outputs['weldability'] = 1.0 - (d/t)/min_d_to_t d_ratio = d[1:]/d[:-1] manufacturability = np.minimum(d_ratio, 1.0/d_ratio) - max_taper outputs['manufacturability'] = np.r_[manufacturability, manufacturability[-1]] # def compute_partials(self, inputs, J): # dw_dd = np.diag(-1.0/self.t/self.min_d_to_t) # dw_dt = np.diag(self.d/self.t**2/self.min_d_to_t) # dw = np.hstack([dw_dd, dw_dt]) # dm_dd = np.zeros_like(self.d) # dm_dd[0] = self.d[-1]/self.d[0]**2 # dm_dd[-1] = -1.0/self.d[0] # dm = np.hstack([dm_dd, np.zeros(len(self.t))]) def fatigue(M_DEL, N_DEL, d, t, m=4, DC=80.0, eta=1.265, stress_factor=1.0, weld_factor=True): """estimate fatigue damage for tower station Parmeters --------- M_DEL : array_like(float) (N*m) damage equivalent moment at tower section N_DEL : array_like(int) corresponding number of cycles in lifetime d : array_like(float) (m) tower diameter at section t : array_like(float) (m) tower shell thickness at section m : int slope of S/N curve DC : float (N/mm**2) some max stress from a standard eta : float safety factor stress_factor : float load_factor * stress_concentration_factor weld_factor : bool if True include an empirical weld factor Returns ------- damage : float damage from Miner's rule for this tower section """ # convert to mm dvec = np.array(d)*1e3 tvec = np.array(t)*1e3 t = sectional2nodal(t) nvec = len(d) damage = np.zeros(nvec) # initialize weld factor (added cubic spline around corner) if weld_factor: x1 = 24.0 x2 = 26.0 spline = CubicSplineSegment(x1, x2, 1.0, (25.0/x2)**0.25, 0.0, 25.0**0.25*-0.25*x2**-1.25) for i in range(nvec): d = dvec[i] t = tvec[i] # weld factor if not weld_factor or t <= x1: weld = 1.0 elif t >= x2: weld = (25.0/t)**0.25 else: weld = spline.eval(t) # stress r = d/2.0 I = np.pi*r**3*t c = r sigma = M_DEL[i]*c/I * stress_factor * 1e3 # convert to N/mm^2 # maximum allowed stress Smax = DC * weld / eta # number of cycles to failure Nf = (Smax/sigma)**m # number of cycles for this load N1 = 2e6 # TODO: where does this come from? N = N_DEL[i]/N1 # damage damage[i] = N/Nf return damage def vonMisesStressUtilization(axial_stress, hoop_stress, shear_stress, gamma, sigma_y): """combine stress for von Mises""" # von mises stress a = ((axial_stress + hoop_stress)/2.0)**2 b = ((axial_stress - hoop_stress)/2.0)**2 c = shear_stress**2 von_mises = np.sqrt(a + 3.0*(b+c)) # stress margin stress_utilization = gamma * von_mises / sigma_y return stress_utilization # This must be <1 to pass def hoopStress(d, t, q_dyn): r = d/2.0-t/2.0 # radius of cylinder middle surface return (-q_dyn * r / t) def hoopStressEurocode(z, d, t, L_reinforced, q_dyn): """default method for computing hoop stress using Eurocode method GB 06/21/2018: Ansys comparisons for submerged case suggests this over-compensates for stiffener I'm not even sure the Eurocode is implemented correctly here. Suggest using the standard hoop stress expression above or API's handling of ring stiffeners below. """ r = d/2.0-t/2.0 # radius of cylinder middle surface omega = L_reinforced/np.sqrt(r*t) C_theta = 1.5 # clamped-clamped k_w = 0.46*(1.0 + 0.1*np.sqrt(C_theta/omega*r/t)) kw = smooth_max(k_w, 0.65) kw = smooth_min(k_w, 1.0) Peq = k_w*q_dyn return hoopStress(d, t, Peq) def bucklingGL(d, t, Fz, Myy, tower_height, E, sigma_y, gamma_f=1.2, gamma_b=1.1, gamma_g=1.1): # other factors alpha = 0.21 # buckling imperfection factor beta = 1.0 # bending coefficient sk_factor = 2.0 # fixed-free tower_height = tower_height * sk_factor # geometry A = np.pi * d * t I = np.pi * (d/2.0)**3 * t Wp = I / (d/2.0) # applied loads Nd = -Fz * gamma_g Md = Myy * gamma_f # plastic resistance Np = A * sigma_y / gamma_b Mp = Wp * sigma_y / gamma_b # factors Ne = np.pi**2 * (E * I) / (1.1 * tower_height**2) lambda_bar = np.sqrt(Np * gamma_b / Ne) phi = 0.5 * (1 + alpha*(lambda_bar - 0.2) + lambda_bar**2) kappa = np.ones_like(d) idx = lambda_bar > 0.2 kappa[idx] = 1.0 / (phi[idx] + np.sqrt(phi[idx]**2 - lambda_bar[idx]**2)) delta_n = 0.25*kappa*lambda_bar**2 delta_n = np.minimum(delta_n, 0.1) GL_utilization = Nd/(kappa*Np) + beta*Md/Mp + delta_n #this is utilization must be <1 return GL_utilization def shellBucklingEurocode(d, t, sigma_z, sigma_t, tau_zt, L_reinforced, E, sigma_y, gamma_f=1.2, gamma_b=1.1): """ Estimate shell buckling utilization along tower. Arguments: npt - number of locations at each node at which stress is evaluated. sigma_z - axial stress at npt*node locations. must be in order [(node1_pts1-npt), (node2_pts1-npt), ...] sigma_t - azimuthal stress given at npt*node locations tau_zt - shear stress (z, theta) at npt*node locations E - modulus of elasticity sigma_y - yield stress L_reinforced - reinforcement length - structure is re-discretized with this spacing gamma_f - safety factor for stresses gamma_b - safety factor for buckling Returns: z EU_utilization: - array of shell buckling utilizations evaluted at (z[0] at npt locations, \n z[0]+L_reinforced at npt locations, ...). \n Each utilization must be < 1 to avoid failure. """ n = len(d) EU_utilization = np.zeros(n) sigma_z_sh = np.zeros(n) sigma_t_sh = np.zeros(n) tau_zt_sh = np.zeros(n) for i in range(n): h = L_reinforced[i] r1 = d[i]/2.0 - t[i]/2.0 r2 = d[i]/2.0 - t[i]/2.0 sigma_z_shell = sigma_z[i] sigma_t_shell = sigma_t[i] tau_zt_shell = tau_zt[i] # TODO: the following is non-smooth, although in general its probably OK # change to magnitudes and add safety factor sigma_z_shell = gamma_f*abs(sigma_z_shell) sigma_t_shell = gamma_f*abs(sigma_t_shell) tau_zt_shell = gamma_f*abs(tau_zt_shell) EU_utilization[i] = _shellBucklingOneSection(h, r1, r2, t[i], gamma_b, sigma_z_shell, sigma_t_shell, tau_zt_shell, E[i], sigma_y[i]) #make them into vectors sigma_z_sh[i]=sigma_z_shell sigma_t_sh[i]=sigma_t_shell tau_zt_sh[i]=tau_zt_shell return EU_utilization # this is utilization must be <1 def _cxsmooth(omega, rovert): Cxb = 6.0 # clamped-clamped constant = 1 + 1.83/1.7 - 2.07/1.7**2 ptL1 = 1.7-0.25 ptR1 = 1.7+0.25 ptL2 = 0.5*rovert - 1.0 ptR2 = 0.5*rovert + 1.0 ptL3 = (0.5+Cxb)*rovert - 1.0 ptR3 = (0.5+Cxb)*rovert + 1.0 if omega < ptL1: Cx = constant - 1.83/omega + 2.07/omega**2 elif omega >= ptL1 and omega <= ptR1: fL = constant - 1.83/ptL1 + 2.07/ptL1**2 fR = 1.0 gL = 1.83/ptL1**2 - 4.14/ptL1**3 gR = 0.0 Cx = cubic_spline_eval(ptL1, ptR1, fL, fR, gL, gR, omega) elif omega > ptR1 and omega < ptL2: Cx = 1.0 elif omega >= ptL2 and omega <= ptR2: fL = 1.0 fR = 1 + 0.2/Cxb*(1-2.0*ptR2/rovert) gL = 0.0 gR = -0.4/Cxb/rovert Cx = cubic_spline_eval(ptL2, ptR2, fL, fR, gL, gR, omega) elif omega > ptR2 and omega < ptL3: Cx = 1 + 0.2/Cxb*(1-2.0*omega/rovert) elif omega >= ptL3 and omega <= ptR3: fL = 1 + 0.2/Cxb*(1-2.0*ptL3/rovert) fR = 0.6 gL = -0.4/Cxb/rovert gR = 0.0 Cx = cubic_spline_eval(ptL3, ptR3, fL, fR, gL, gR, omega) else: Cx = 0.6 return Cx def _sigmasmooth(omega, E, rovert): Ctheta = 1.5 # clamped-clamped ptL = 1.63*rovert*Ctheta - 1 ptR = 1.63*rovert*Ctheta + 1 if omega < 20.0*Ctheta: offset = (10.0/(20*Ctheta)**2 - 5/(20*Ctheta)**3) Cthetas = 1.5 + 10.0/omega**2 - 5/omega**3 - offset sigma = 0.92*E*Cthetas/omega/rovert elif omega >= 20.0*Ctheta and omega < ptL: sigma = 0.92*E*Ctheta/omega/rovert elif omega >= ptL and omega <= ptR: alpha1 = 0.92/1.63 - 2.03/1.63**4 fL = 0.92*E*Ctheta/ptL/rovert fR = E*(1.0/rovert)**2*(alpha1 + 2.03*(Ctheta/ptR*rovert)**4) gL = -0.92*E*Ctheta/rovert/ptL**2 gR = -E*(1.0/rovert)*2.03*4*(Ctheta/ptR*rovert)**3*Ctheta/ptR**2 sigma = cubic_spline_eval(ptL, ptR, fL, fR, gL, gR, omega) else: alpha1 = 0.92/1.63 - 2.03/1.63**4 sigma = E*(1.0/rovert)**2*(alpha1 + 2.03*(Ctheta/omega*rovert)**4) return sigma def _tausmooth(omega, rovert): ptL1 = 9 ptR1 = 11 ptL2 = 8.7*rovert - 1 ptR2 = 8.7*rovert + 1 if omega < ptL1: C_tau = np.sqrt(1.0 + 42.0/omega**3 - 42.0/10**3) elif omega >= ptL1 and omega <= ptR1: fL = np.sqrt(1.0 + 42.0/ptL1**3 - 42.0/10**3) fR = 1.0 gL = -63.0/ptL1**4/fL gR = 0.0 C_tau = cubic_spline_eval(ptL1, ptR1, fL, fR, gL, gR, omega) elif omega > ptR1 and omega < ptL2: C_tau = 1.0 elif omega >= ptL2 and omega <= ptR2: fL = 1.0 fR = 1.0/3.0*np.sqrt(ptR2/rovert) + 1 - np.sqrt(8.7)/3 gL = 0.0 gR = 1.0/6/np.sqrt(ptR2*rovert) C_tau = cubic_spline_eval(ptL2, ptR2, fL, fR, gL, gR, omega) else: C_tau = 1.0/3.0*np.sqrt(omega/rovert) + 1 - np.sqrt(8.7)/3 return C_tau def _shellBucklingOneSection(h, r1, r2, t, gamma_b, sigma_z, sigma_t, tau_zt, E, sigma_y): """ Estimate shell buckling for one tapered cylindrical shell section. Arguments: h - height of conical section r1 - radius at bottom r2 - radius at top t - shell thickness E - modulus of elasticity sigma_y - yield stress gamma_b - buckling reduction safety factor sigma_z - axial stress component sigma_t - azimuthal stress component tau_zt - shear stress component (z, theta) Returns: EU_utilization, shell buckling utilization which must be < 1 to avoid failure """ #NOTE: definition of r1, r2 switched from Eurocode document to be consistent with FEM. # ----- geometric parameters -------- beta = atan2(r1-r2, h) L = h/np.cos(beta) # ------------- axial stress ------------- # length parameter le = L re = 0.5*(r1+r2)/np.cos(beta) omega = le/np.sqrt(re*t) rovert = re/t # compute Cx Cx = _cxsmooth(omega, rovert) # if omega <= 1.7: # Cx = 1.36 - 1.83/omega + 2.07/omega/omega # elif omega > 0.5*rovert: # Cxb = 6.0 # clamped-clamped # Cx = max(0.6, 1 + 0.2/Cxb*(1-2.0*omega/rovert)) # else: # Cx = 1.0 # critical axial buckling stress sigma_z_Rcr = 0.605*E*Cx/rovert # compute buckling reduction factors lambda_z0 = 0.2 beta_z = 0.6 eta_z = 1.0 Q = 25.0 # quality parameter - high lambda_z = np.sqrt(sigma_y/sigma_z_Rcr) delta_wk = 1.0/Q*np.sqrt(rovert)*t alpha_z = 0.62/(1 + 1.91*(delta_wk/t)**1.44) chi_z = _buckling_reduction_factor(alpha_z, beta_z, eta_z, lambda_z0, lambda_z) # design buckling stress sigma_z_Rk = chi_z*sigma_y sigma_z_Rd = sigma_z_Rk/gamma_b # ---------------- hoop stress ------------------ # length parameter le = L re = 0.5*(r1+r2)/(np.cos(beta)) omega = le/np.sqrt(re*t) rovert = re/t # Ctheta = 1.5 # clamped-clamped # CthetaS = 1.5 + 10.0/omega**2 - 5.0/omega**3 # # critical hoop buckling stress # if (omega/Ctheta < 20.0): # sigma_t_Rcr = 0.92*E*CthetaS/omega/rovert # elif (omega/Ctheta > 1.63*rovert): # sigma_t_Rcr = E*(1.0/rovert)**2*(0.275 + 2.03*(Ctheta/omega*rovert)**4) # else: # sigma_t_Rcr = 0.92*E*Ctheta/omega/rovert sigma_t_Rcr = np.maximum(eps, _sigmasmooth(omega, E, rovert)) # buckling reduction factor alpha_t = 0.65 # high fabrication quality lambda_t0 = 0.4 beta_t = 0.6 eta_t = 1.0 lambda_t = np.sqrt(sigma_y/sigma_t_Rcr) chi_theta = _buckling_reduction_factor(alpha_t, beta_t, eta_t, lambda_t0, lambda_t) sigma_t_Rk = chi_theta*sigma_y sigma_t_Rd = sigma_t_Rk/gamma_b # ----------------- shear stress ---------------------- # length parameter le = h rho = np.sqrt((r1+r2)/(2.0*r2)) re = (1.0 + rho - 1.0/rho)*r2*np.cos(beta) omega = le/np.sqrt(re*t) rovert = re/t # if (omega < 10): # C_tau = np.sqrt(1.0 + 42.0/omega**3) # elif (omega > 8.7*rovert): # C_tau = 1.0/3.0*np.sqrt(omega/rovert) # else: # C_tau = 1.0 C_tau = _tausmooth(omega, rovert) tau_zt_Rcr = 0.75*E*C_tau*
np.sqrt(1.0/omega)
numpy.sqrt
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.utils import shuffle class TLMLP(BaseEstimator, ClassifierMixin): """ Multi Layer Perceptron (Single hidden layer) """ def __init__(self, hid_num=10, epochs=1000, r=0.5): self.hid_num = hid_num self.epochs = epochs self.r = r def __sigmoid(self, x, a=1): return 1 / (1 + np.exp(- a * x)) def __dsigmoid(self, x, a=1): return a * x * (1.0 - x) def __add_bias(self, X): return np.c_[X, np.ones(X.shape[0])] def __ltov(self, n, label): return [0 if i != label else 1 for i in range(1, n + 1)] def __calc_out(self, w, x): return self.__sigmoid(np.dot(w, x)) def __out_error(self, z, y): return (z - y) * self.__dsigmoid(z) def __hid_error(self, z, eo): return np.dot(self.wo.T, eo) * self.__dsigmoid(z) def __w_update(self, w, e, z): e = np.atleast_2d(e) z =
np.atleast_2d(z)
numpy.atleast_2d
import numpy as np from scipy import optimize class InterParams: def __init__(self, xE): self.method = "NPS" self.n = xE.shape[0] self.m = xE.shape[1] self.xi = np.copy(xE) self.w = None self.v = None self.y = None self.sigma = None def interpolateparameterization(self, yE): self.w = np.zeros((self.m, 1)) self.v =
np.zeros((self.n + 1, 1))
numpy.zeros
# -*- coding: utf-8 -*- """ This script allows for conversion of actigraphy data from GENEActiv devices into inactograms, to better visualize patterns of inactivity accross days. It is designed to work with binary files extracted with the GENEActiv software. It can also work with pre-analysed CSV files form the GENEActiv software, but these files do not contain enough information to calculate sleep bouts, and thus only activity can be plotted. <NAME>, The Storch Lab, McGill University, 2020 MIT License Copyright (c) 2020 <NAME>, The Storch Lab, McGill University 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. """ import os import pickle import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Polygon def extract_bin(filepath): """Extract data from a GENEActiv binary file.""" # Import the whole file as text with open(filepath, 'r') as f: data = f.readlines() # Only works with GENEActiv devices (at least for now) if not data[2].strip().split(':')[-1] == 'GENEActiv': raise Exception('Not a GENEActiv device') return # Create a calibration dictionnary from the header calibration = {} for i in range(47,55): tmp = data[i].strip().split(':') calibration[tmp[0]]=int(tmp[1]) # Find number of pages of recording, frequency, and length in lines of a page n_pages = int(data[57].strip().split(':')[-1]) fs = float(data[19].strip().split(':')[-1].split(' Hz')[0]) block_length = (len(data)-59)//n_pages # Initialize numpy arrays for storing raw values x = np.empty(n_pages*300) y = np.empty(n_pages*300) z = np.empty(n_pages*300) light = np.empty(n_pages*300) # button = np.empty(n_pages*300) # temperature = np.empty(n_pages) for p in range(n_pages): ''' A hexstring is 300 values encoded as following: 12 bits for x (signed) 12 bits for y (signed) 12 bits for z (signed) 10 bits for light 1 bit for button 1 bit for reserved 0 resulting in a 48-bit or 6-byte block encoded in 12 hexadecimal values, so we slice the string every 12 character. ''' hexstring = data[68 + (block_length*p)].strip() # temperature[p] = float(data[64 + (block_length*p)].strip().split(':')[-1]) for i in range(300): ''' For signed values, remove 4096 if the first bit is 1. x is in the 12 first bits, we just need to bitshift 36 times. y, z, and light are in the middle so retain the last bits using bitwise logic after bit-shifting ''' d = int(hexstring[i*12:(i+1)*12],16) x[300*p + i] = -4096 * (d >> 47) + (d >> 36) y[300*p + i] = -4096 * (d >> 35 & 1) + (d >> 24 & 0xFFF) z[300*p + i] = -4096 * (d >> 23 & 1) + (d >> 12 & 0xFFF) light[300*p + i] = d >> 2 & 0x3FF # button.append(d >> 1 & 1) # temperature = temperature.repeat(300) start_date = pd.to_datetime(data[62].strip().split('Time:')[1], format='%Y-%m-%d %H:%M:%S:%f') timestamps = pd.date_range(start=start_date, periods=n_pages*300, freq=f'{1/fs}S') # data_df = pd.DataFrame({'x':x, 'y':y, 'z':z, 'light':light, 'button':button, 'temperature':temperature}, # index=timestamps) data_df = pd.DataFrame({'x':x, 'y':y, 'z':z, 'light':light}, index=timestamps) data_df['x'] = (data_df['x'] * 100 - calibration['x offset']) / calibration['x gain'] data_df['y'] = (data_df['y'] * 100 - calibration['y offset']) / calibration['y gain'] data_df['z'] = (data_df['z'] * 100 - calibration['z offset']) / calibration['z gain'] data_df['light'] = data_df['light'] * calibration['Lux'] / calibration['Volts'] data_smooth = data_df.rolling('5S').median() data_smooth['svmg'] = np.abs(np.sqrt(data_df['x']**2 + data_df['y']**2 + data_df['z']**2) - 1) return data_smooth def extract_csv(filepath): data = pd.read_csv(filepath, header=100, index_col=0, parse_dates=True, names=['x', 'y', 'z', 'light', 'button', 'temperature', 'svmg', 'x_dev', 'y_dev', 'z_dev', 'peak_lux']) data.index = pd.to_datetime(data.index, format='%Y-%m-%d %H:%M:%S:000', infer_datetime_format=True) return data def calc_angle(data, method='max', win_size=5): """"Extract data from a CSV file.""" data['angle'] = np.arctan(data['z'] / np.sqrt(data['x'] ** 2 + data['y'] ** 2)) * 180 / np.pi angle_change = data['angle'].resample(f'5S').mean().diff().abs().rename('angle_change') win_size *= 12 if method == 'median': roll = angle_change.rolling(win_size + 1, center=True).median().rename('rolling') elif method == 'max': roll = angle_change.rolling(win_size + 1, center=True).max().rename('rolling') return data, angle_change, roll def calc_sleep(roll, thresh_method='fixed', thresh_value=5): if thresh_method == 'perc': thresh = np.nanpercentile(roll, 10)*15 elif thresh_method == 'fixed': thresh = thresh_value sleep = (roll < thresh) * 1 return sleep.rename('sleep') def plot_actogram(data, tz_off=-5, binsize=5, doubleplot=1, scale=5, title=1, first=0, last=0): """"Prepare data and plot an inactogram""" if not type(data) == pd.core.series.Series: print('Wrong data type, please input a pandas Series') return daylength = 1440 // binsize # Extract and resample data = data.resample(f'{binsize}T').sum() start = data.index[0].timetuple() end = data.index[-1].timetuple() frontpad = np.zeros((start[3]*60 + start[4]) // binsize) backpad = np.zeros(daylength - (end[3]*60 + end[4]) // binsize - 1) counts = np.concatenate([frontpad, data.values, backpad]) # Keep wanted days only if last: counts = counts[:last*daylength] if not first: counts = counts[first*daylength:] ndays = counts.shape[0] // daylength # Digitize edges = np.histogram_bin_edges(counts, bins=scale) perc = (
np.digitize(counts, edges)
numpy.digitize
import os import time from pathlib import Path import tensorflow as tf from dotenv import load_dotenv, find_dotenv from keras.callbacks import TensorBoard from mdn import sample_from_output from sklearn.model_selection import train_test_split from sklearn.preprocessing import normalize from keras.layers import Dense, Input, Concatenate, BatchNormalization from keras.models import Model import numpy as np from sklearn import preprocessing import keras.backend as K import mdn import matplotlib.pyplot as plt np.random.seed(42) def build_base_network(input_shape): inputs = Input(shape=input_shape) hidden = BatchNormalization()(inputs) # oups, forgot activation here... should have been: # Dense(16, activation='relu') hidden = Dense(16)(hidden) hidden = BatchNormalization()(hidden) model = Model(inputs=inputs, outputs=hidden) return model def create_mdn_estimator(X, y, X_val, y_val, batch_size=32, nb_epochs=1000, nb_mixtures=1): input_shape = X.shape[1:] base_network = build_base_network(input_shape) input_a = Input(shape=input_shape) x = base_network(input_a) mixture_layer = mdn.MDN(1, nb_mixtures)(x) mdn_model = Model([input_a], [mixture_layer]) loss = mdn.get_mixture_loss_func(1, nb_mixtures) mdn_model.compile(loss=loss, optimizer='adam') tb_cb = TensorBoard(log_dir='./mdn_logs/{}'.format(time.time()), histogram_freq=0, batch_size=32, write_graph=True, write_grads=True, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None, embeddings_data=None, update_freq='epoch') mdn_model.fit( X, y, batch_size=batch_size, epochs=nb_epochs, validation_data=(X_val, y_val), verbose=1, callbacks=[tb_cb]) return mdn_model def make_mdn_prediction(mdn_model, X_test, return_sample=False, nb_mixture=1, scaling=1.): assert nb_mixture == 1, "Only 1 mixture is supported" y_pred = mdn_model.predict(X_test) y_mu = y_pred[:, 0] * scaling y_std = np.sqrt(y_pred[:, 1] * scaling ** 2) if return_sample: y_sample = np.apply_along_axis(sample_from_output, 1, y_pred, 1, nb_mixture, temp=1.0) return y_mu, y_std, y_sample else: return y_mu, y_std def main(): load_dotenv(find_dotenv()) input_data_file = Path(os.environ["project_dir"]) / "data/external/pcm_main_rotor_embeded.npz" # input_data_file = Path(os.environ["project_dir"]) / "data/external/pcm_main_rotor.npz" data = np.load(input_data_file) X, y = data["X"], data["y"] nb_epochs = 1000 batch_size = 32 nb_mixtures = 1 X = normalize(X, axis=0, norm="max") X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) max_y_train = np.max(y_train) y_train /= max_y_train X_val = X_test y_val = y_test / max_y_train model = create_mdn_estimator(X_train, y_train, X_val, y_val, batch_size=batch_size, nb_epochs=nb_epochs, nb_mixtures=nb_mixtures) y_mu_test, y_std_test = make_mdn_prediction(model, X_test, scaling=max_y_train) y_true = y_test n_to_show = 50 plt.scatter(np.arange(y_true.shape[0])[:n_to_show],
np.squeeze(y_true)
numpy.squeeze
""" Modules for numpy.where to make it more IDL-like. """ from __future__ import print_function import numpy as np def andwhere(data, val1, test1, val2=None, test2=None, return_indices=False): """ Performs an 'and' where search, i.e., where(input > 3 and input < 4). Using the parameter names, where(data test1 val1 and data test2 val2). Can also do a single test, i.e., where(input > 3). Example ------- To check data > 1.1 and data < 2.5, > out = where(data=[1,2,3], val1=1.1, test1='>', val2='2.5', test2='<') > print(out) [1] # index > print(data[out]) [2] # value at index 1 Parameters ---------- data : list or array val1 : int, float, or str First value you wish to check 'data' against. test1 : str Either '<', '>', '<=', '>=', or '=='. val2 : Second value you wish to check 'data' against. test2 : str Either '<', '>', '<=', '>=', or '=='. return_indices : {True, False} If True, returns only the indices of valid 'data' entries. If False, returns only the values of 'data' corresponding to those entries. Returns ------- If 'return_indices' is False, data_cut<1/2> : array The 'data' array cut down by the testing parameters. If 'return_indices' is True: The index array of 'data' corresponding to items cut down by the testing parameters. """ # Transform the list to numpy array. data = np.array(data) # Transform the first equality tests. if test1 == '<': indices1 = np.where(data < val1)[0] elif test1 == '>': indices1 = np.where(data > val1)[0] elif test1 == '<=': indices1 = np.where(data <= val1)[0] elif test1 == '>=': indices1 = np.where(data >= val1)[0] elif test1 == '==': indices1 = np.where(data >= val1)[0] else: print("Invalid equality check, {}".format(test1)) data_cut1 = data[indices1] # If only one equality check entered, finish. if val2 == None and test2 == None: if return_indices: return indices1 else: return data_cut1 # If a second check was entered, continue # Transform the second equality tests. if test2 == '<': indices2 = np.where(data_cut1 < val2)[0] elif test2 == '>': indices2 = np.where(data_cut1 > val2)[0] elif test2 == '<=': indices2 = np.where(data_cut1 <= val2)[0] elif test2 == '>=': indices2 = np.where(data_cut1 >= val2)[0] elif test2 == '==': indices2 =
np.where(data_cut1 >= val2)
numpy.where
import tools as tls import camera import numpy as np import cv2 import matplotlib.pyplot as plt def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. `vertices` should be a numpy array of integer points. """ #defining a blank mask to start with mask = np.zeros_like(img) #defining a 3 channel or 1 channel color to fill the mask with depending on the input image if len(img.shape) > 2: channel_count = img.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255,) * channel_count else: ignore_mask_color = 255 #filling pixels inside the polygon defined by "vertices" with the fill color cv2.fillPoly(mask, vertices, ignore_mask_color) #returning the image only where mask pixels are nonzero masked_image = cv2.bitwise_and(img, mask) return masked_image def sobel_absolute_scaled(gray): # allow images with color depth = one if len(gray.shape) != 2: raise TypeError sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0) abs_sobelx = np.absolute(sobelx) scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx)) return scaled_sobel def sobel_magnitude(gray, sobel_kernel=3): # allow images with color depth = one if len(gray.shape) != 2: raise TypeError # Take the gradient in x and y separately sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel) sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) # Calculate the magnitude gradmag = np.sqrt(sobelx**2 + sobely**2) # Rescale to 8 bit scale_factor = np.max(gradmag)/255 gradmag = (gradmag/scale_factor).astype(np.uint8) return gradmag def sobel_direction(gray, sobel_kernel=3): #, thresh=(0, np.pi/2)): # allow images with color depth = one if len(gray.shape) != 2: raise TypeError # Take the gradient in x and y separately sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, sobel_kernel) sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, sobel_kernel) # Take the absolute value of the x and y gradients abs_sobel_x = np.absolute(sobel_x) abs_sobel_y = np.absolute(sobel_y) # calculate the direction of the gradient absgraddir = np.arctan2(abs_sobel_y, abs_sobel_x) return absgraddir def channel_threshold(channel, thresh=(170,255)): # Threshold color channel binary = np.zeros_like(channel) binary[(channel >= thresh[0]) & (channel <= thresh[1])] = 1 return binary def find_lane_pixels(binary_warped, leftx_base, rightx_base): # Create an output image to draw on and visualize the result out_img = np.dstack((binary_warped, binary_warped, binary_warped)) # Choose the number of sliding windows nwindows = 9 # Set the width of the windows +/- margin margin = 150 # Set minimum number of pixels found to recenter window minpix = 4 # Set height of windows - based on nwindows above and image shape window_height = np.int(binary_warped.shape[0]//nwindows) # Identify the x and y positions of all nonzero pixels in the image nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated later for each window in nwindows leftx_current = leftx_base rightx_current = rightx_base # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] # Step through the windows one by one for window in range(nwindows): # Identify window boundaries in x and y (and right and left) win_y_low = binary_warped.shape[0] - (window+1)*window_height win_y_high = binary_warped.shape[0] - window*window_height ### TO-DO: Find the four below boundaries of the window ### win_xleft_low = leftx_current - margin win_xleft_high = leftx_current + margin win_xright_low = rightx_current - margin win_xright_high = rightx_current + margin # Draw the windows on the visualization image cv2.rectangle(out_img, (win_xleft_low, win_y_low), (win_xleft_high, win_y_high), (0,255,0), 2) cv2.rectangle(out_img, (win_xright_low, win_y_low), (win_xright_high, win_y_high), (0,255,0), 2) # Identify the nonzero pixels in x and y within the window # good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0] good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0] # Append these indices to the lists left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) # If you found > minpix pixels, recenter next window on their mean position if len(good_left_inds) > minpix: leftx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rightx_current = np.int(np.mean(nonzerox[good_right_inds])) # Concatenate the arrays of indices (previously was a list of lists of pixels) left_lane_inds = np.concatenate(left_lane_inds) right_lane_inds = np.concatenate(right_lane_inds) # Extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] return leftx, lefty, rightx, righty, out_img class lane_detector: def __init__(self, filname): data = camera.load(filname) self.mtx = data["mtx"] self.dist = data["dist"] self.r_thresh=(145, 200) self.g_thresh=(200, 255) self.b_thresh=(225,255) self.font = cv2.FONT_HERSHEY_PLAIN self.color = (255,255,255) self.offset = 100 self.left = [] self.right = [] self.prev_left = 0 self.prev_right = 0 self.out = 'output_images' self.base = 'frame' self.ext = '.jpg' self.debug_binary = False self.debug_lines = False self.debug_histogram = False self.debug_warped = False self.debug_detect = False def threshold_blue(self, thresh): self.b_thresh = tuple(thresh) def undistort(self, image): return cv2.undistort(image, self.mtx, self.dist, None, self.mtx) def warp(self, binary, src, dst): # only width and height, discard depth if provided #w,h = binary.shape[1::-1] # get M, the transform matrix M = cv2.getPerspectiveTransform(src, dst) w,h = np.amax(dst,axis=0) # returned the warped image return cv2.warpPerspective(binary, M, (w,h), flags=cv2.INTER_LINEAR) def unwarp(self, binary, src, dst, w, h): # get Minv, the transform matrix Minv = cv2.getPerspectiveTransform(dst, src) # returned the warped image return cv2.warpPerspective(binary, Minv, (w,h), flags=cv2.INTER_LINEAR) def gaussian_blur(self, img, kernel_size): return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def gradients(self, undist): # separate components of hls color space (_, _, rgb_r) = tls.channels(undist) (_, _, lab_b) = tls.channels(tls.bgr2lab(undist)) (luv_l, _, _) = tls.channels(tls.bgr2luv(undist)) # color space threshold on lab_b r_channel = sobel_magnitude(lab_b) r_binary = channel_threshold(r_channel, self.r_thresh) # color space threshold on luv_l g_binary = channel_threshold(luv_l, self.g_thresh) # color space threshold of rgb_r channel b_binary = channel_threshold(rgb_r, self.b_thresh) # RGB or BGR return np.dstack((b_binary, g_binary, r_binary)) def process(self, image): # undistorte the image undist = self.undistort(image) # get width and height, w,h = image.shape[1::-1] # apply gradients and threshold color = self.gradients(undist) if self.debug_binary: tls.save_image_as(color*255, '{}_binary{}'.format(self.base, self.ext), tls.path_join(self.out, 'binary')) # combine all channels with bitwise or binary = cv2.bitwise_or(color[:,:,0], cv2.bitwise_or(color[:,:,1], color[:,:,2])) # calculate src and dst points src = np.array([[570, h//2 + self.offset], # top left point [710, h//2 + self.offset], # top right point [w,h], # bottom right point [50,h]], dtype = np.float32) # bottom left point (tl,tr,br,bl) = src widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) maxWidth = max(int(widthA), int(widthB)) heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) maxHeight = max(int(heightA), int(heightB)) # calculate the destination points dst = np.array([[0,0], [maxWidth-1, 0], [maxWidth-1, maxHeight-1], [0, maxHeight-1]], dtype = np.float32) if self.debug_lines: lines = np.copy(undist) cv2.line(lines, tuple(src[0]), tuple(src[1]), (255,0,0), 5) cv2.line(lines, tuple(src[1]), tuple(src[2]), (255,0,0), 5) cv2.line(lines, tuple(src[2]), tuple(src[3]), (255,0,0), 5) cv2.line(lines, tuple(src[3]), tuple(src[0]), (255,0,0), 5) cv2.line(lines, tuple(dst[0]), tuple(dst[1]), (0,255,0), 5) cv2.line(lines, tuple(dst[1]), tuple(dst[2]), (0,255,0), 5) cv2.line(lines, tuple(dst[2]), tuple(dst[3]), (0,255,0), 5) cv2.line(lines, tuple(dst[3]), tuple(dst[0]), (0,255,0), 5) tls.save_image_as(lines, '{}_lines{}'.format(self.base,self.ext), tls.path_join(self.out, 'lines')) # create color warped image for debugging if self.debug_warped: colorWarped = self.warp(color, src, dst) tls.save_image_as(colorWarped*255, '{}_warped{}'.format(self.base,self.ext), tls.path_join(self.out, 'color')) # warp the binary image warped = self.warp(binary, src, dst) if self.debug_warped: tls.save_image_as(warped*255, '{}_warped{}'.format(self.base,self.ext), tls.path_join(self.out, 'warped')) # Take a histogram of the bottom half of the image histogram = np.sum((warped[warped.shape[0]//2:,:]), axis=0) # calculate the midpoint in the histogram midpoint =
np.int(histogram.shape[0]//2)
numpy.int
""" $Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/pulsar/edf.py,v 1.1 2011/04/27 18:32:03 kerrm Exp $ a module for implementing EDF (empirical distribution function) TOA determination; heavily beta Authors: <NAME> <<EMAIL>> """ import numpy as np import pylab as pl #from lcfitters import get_gauss2,get_gauss1 from scipy.interpolate import interp1d from scipy.optimize import fmin #lct = get_gauss2(pulse_frac=0.1) #lct = get_gauss1(pulse_frac=0.1,width1=0.02) #lct = get_gauss2(x1=0.25,x2=0.75,pulse_frac=0.1,width1=0.02,width2=0.02,ratio=1) #lct = get_gauss2(x1=0.3,x2=0.7,pulse_frac=0.3,width1=0.15,width2=0.08,ratio=1) #ph1 = lct.random(1000) #ph2 = lct.random(1000) def comp_edfs2(edf1,edf2): """ Calculate a Kuiper test statistic for two edfs.""" idx1 = np.arange(1,edf1.n+1,dtype=float)/edf1.n idx2 = np.arange(1,edf2.n+1,dtype=float)/edf2.n s = np.argsort(np.append(edf1.ph,edf2.ph)) idx = np.append(idx1,idx2) mask = np.append([True]*edf1.n,[False]*edf2.n) idx = idx[s] mask = mask[s] e1 = 0; e2 = 0 all_e1s = np.empty_like(idx) all_e2s = np.empty_like(idx) for i in xrange(len(s)): if mask[i]: e1 = idx[i] else: e2 = idx[i] all_e1s[i] = e1 all_e2s[i] = e2 return np.max(all_e1s-all_e2s) + np.max(all_e2s-all_e1s) def timeit(e1,e2,n=10): for i in xrange(n): comp_edfs2(e1,e2) class EDF(object): def __init__(self,ph,comp_n=100000): self.ph = np.sort(ph) self.n = len(self.ph) #self.comp_vals = self(np.linspace(0,1,comp_n)) def __call__(self,phi): if not hasattr(phi,'__len__'): phi = [phi] return np.searchsorted(self.ph,phi).astype(float)/self.n def comp(self,e): # Kuiper test return comp_edfs2(self,e) #return np.max(self.comp_vals-e.comp_vals) + \ # np.max(e.comp_vals-self.comp_vals) def random(self,n): # NB -- this needs to be checked/optimized rvals = np.random.rand(n) y = np.linspace(0,1,self.n+1) #idx = np.searchsorted(y,rvals) idx = (rvals*self.n+1).astype(int) ph = np.append(self.ph,1+self.ph[0]) rvals = self.n*((y[idx]-rvals)*ph[idx-1] + (rvals-y[idx-1])*ph[idx]) return
np.mod(rvals,1)
numpy.mod
import numpy as np from paddle import fluid from interaction.transformer import TransformerDecoder from interaction.trigger import TriggerController from perception.common.backbone import MobileNetV2 class AttentionController(object): def __init__(self, inputs_type='visual_token', num_actions=1000, act_tr_dim=778, act_emb_ndarray=None, num_frames=10, tokens_per_frame=20, inst_crop_shape=[3, 128, 128], inst_crop_flatten_dim=512, inst_fm_shape=[512, 5, 5], inst_fm_conv_reduce_dim=128, inst_fm_flatten_dim=512, inst_cls_dim=80, inst_pos_dim=50, visual_token_dim=562, model_dim=512, num_decoder_blocks=6, num_heads=8, ffn_dim=2048, dropout=0.0, normalize_before=False, frame_emb_trainable=True, frame_sin_emb_temp=10000, trigger_loss_coef=5.0, obj_loss_coef=1.0, act_loss_coef=1.0, use_last_act_loss=False, attn_mask_as_input=False, attn_weights_as_output=False, mode='train'): assert inputs_type in ['visual_token', 'instance', 'without_inst_fm', 'without_inst_cls', 'without_inst_pos', 'inst_crop', 'inst_crop_wo_crop', 'inst_crop_wo_cls', 'inst_crop_wo_pos'] self.num_actions = num_actions self.act_tr_dim = act_tr_dim self.act_emb_ndarray = act_emb_ndarray self.num_frames = num_frames self.tokens_per_frame = tokens_per_frame self.inst_crop_shape = inst_crop_shape self.inst_crop_flatten_dim = inst_crop_flatten_dim self.inst_fm_shape = inst_fm_shape self.inst_fm_conv_reduce_dim = inst_fm_conv_reduce_dim self.inst_fm_flatten_dim = inst_fm_flatten_dim self.inst_cls_dim = inst_cls_dim self.inst_pos_dim = inst_pos_dim self.visual_token_dim = visual_token_dim self.model_dim = model_dim self.num_decoder_blocks = num_decoder_blocks self.num_heads = num_heads self.ffn_dim = ffn_dim self.dropout = dropout self.normalize_before = normalize_before self.frame_emb_trainable = frame_emb_trainable self.frame_sin_emb_temp = frame_sin_emb_temp self.trigger_loss_coef = trigger_loss_coef self.obj_loss_coef = obj_loss_coef self.act_loss_coef = act_loss_coef self.use_last_act_loss = use_last_act_loss self.attn_mask_as_input = attn_mask_as_input self.attn_weights_as_output = attn_weights_as_output self.mode = mode self._build_input_layer(inputs_type) self._create_embeddings() self._build_model() def _build_input_layer(self, inputs_type): if self.mode in ['train', 'test']: bs = -1 tgt_seq_len = self.num_frames * self.tokens_per_frame else: bs = 1 tgt_seq_len = self.tokens_per_frame past_seq_len = -1 # For ablation study inputs = [] if inputs_type == 'visual_token': inputs.append('visual_token') elif inputs_type == 'instance': inputs.extend(['inst_fm', 'inst_cls', 'inst_pos_emb']) elif inputs_type == 'without_inst_fm': inputs.extend(['inst_cls', 'inst_pos_emb']) elif inputs_type == 'without_inst_cls': inputs.extend(['inst_fm', 'inst_pos_emb']) elif inputs_type == 'without_inst_pos': inputs.extend(['inst_fm', 'inst_cls']) elif inputs_type == 'inst_crop': inputs.extend(['inst_crop', 'inst_cls', 'inst_pos_emb']) elif inputs_type == 'inst_crop_wo_crop': inputs.extend(['inst_cls', 'inst_pos_emb']) elif inputs_type == 'inst_crop_wo_cls': inputs.extend(['inst_crop', 'inst_pos_emb']) elif inputs_type == 'inst_crop_wo_pos': inputs.extend(['inst_crop', 'inst_cls']) self.feed_list = [] for i in inputs: if i == 'visual_token': # `visual_tokens`: are from GAP of RoIAligned feature map # and pos embedding of instances self.visual_tokens = fluid.data( 'visual_tokens', [bs, tgt_seq_len, self.visual_token_dim], dtype='float32') self.feed_list.append(self.visual_tokens) elif i == 'inst_fm': self.inst_fm = fluid.data( 'inst_fm', [bs, tgt_seq_len] + self.inst_fm_shape, dtype='float32') self.feed_list.append(self.inst_fm) elif i == 'inst_cls': self.inst_cls = fluid.data( 'inst_cls', [bs, tgt_seq_len, self.inst_cls_dim], dtype='float32') self.feed_list.append(self.inst_cls) elif i == 'inst_pos_emb': self.inst_pos_emb = fluid.data( 'inst_pos_emb', [bs, tgt_seq_len, self.inst_pos_dim], dtype='float32') self.feed_list.append(self.inst_pos_emb) elif i == 'inst_crop': self.inst_crop = fluid.data( 'inst_crop', [bs, tgt_seq_len] + self.inst_crop_shape, dtype='float32') self.feed_list.append(self.inst_crop) self.frame_ids = fluid.data( 'frame_ids', [bs, tgt_seq_len], dtype='int64') self.padding_mask = fluid.data( 'padding_mask', [bs, tgt_seq_len], dtype='float32') self.feed_list.extend([self.frame_ids, self.padding_mask]) if self.mode == 'train': self.past_kv_arr = None self.past_padding_mask = None nframes = tgt_seq_len // self.tokens_per_frame self.act_ids = fluid.data( 'act_ids', [bs, nframes], dtype='int64') self.has_act = fluid.data( 'has_act', [bs, nframes], dtype='float32') self.is_obj = fluid.data( 'is_obj', [bs, tgt_seq_len], dtype='float32') self.feed_list.extend([self.act_ids, self.has_act, self.is_obj]) elif self.mode == 'test': self.past_kv_arr = None self.past_padding_mask = None # temperature hyperparameter for softmax self.softmax_temp = fluid.data( 'softmax_temp', [1], dtype='float32') self.top_k = fluid.data('top_k', [1], dtype='int64') self.feed_list.append(self.softmax_temp) if self.attn_mask_as_input: # NOTE: for jetson, as the converting from frame_ids # to attn_mask reequires py_func, which wouldn't # work for paddle inference. self.attn_mask = fluid.data( 'attn_mask', [bs, tgt_seq_len, tgt_seq_len], dtype='float32') self.feed_list.append(self.attn_mask) elif self.mode == 'inference': # TODO: check whether this step by step inference works self.past_kv_arr = fluid.data( 'past_kv_arr', [bs, self.num_decoder_blocks, 2, self.num_heads, past_seq_len, self.model_dim // self.num_heads], dtype='float32') self.past_padding_mask = fluid.data( 'past_padding_mask', [bs, past_seq_len], dtype='float32') self.feed_list.extend([self.past_kv_arr, self.past_padding_mask]) def _create_embeddings(self): if self.frame_emb_trainable: emb_data = np.random.random((self.num_frames + 1, self.model_dim)) else: raise NotImplementedError emb_data = None self.wfe = fluid.ParamAttr( name='wfe', learning_rate=0.0001 if self.frame_emb_trainable else 0.0, initializer=fluid.initializer.NumpyArrayInitializer(emb_data), trainable=self.frame_emb_trainable) # For inference, use emb after projection act_dim = self.act_tr_dim if self.mode in ['train', 'test'] \ else self.model_dim if self.act_emb_ndarray is None: act_emb_ndarray = np.random.random( (self.num_actions + 1, act_dim)) else: # Add zero pad act_emb_ndarray = np.concatenate( [self.act_emb_ndarray, np.zeros((1, act_dim), dtype=np.float32)]) self.wae = fluid.ParamAttr( name='wae', learning_rate=0.0001 if self.mode == 'train' else 0.0, initializer=fluid.initializer.NumpyArrayInitializer( act_emb_ndarray), trainable=self.mode == 'train') def _convert_frame_ids2attnmask(self, frame_ids): # NOTE: make sure the frame_ids is non-decreasing # e.g. [1, 1, 2, 2, 1, 3] is not allowed def _idlst2mask(ids): # e.g. convert to [1, 1, 2, 2] # [[1, 1, 0, 0], # [1, 1, 0, 0], # [1, 1, 1, 1], # [1, 1, 1, 1]] n = len(ids) repeat, r, c = [0], 0, ids[0] for i in ids: if i == c: r += 1 else: repeat.append(r) r, c = 1, i repeat.append(r) cum = np.cumsum(repeat) mask =
np.zeros((n, n), dtype=np.float32)
numpy.zeros
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from skimage.measure import compare_ssim import torch from torch.autograd import Variable from modules import dist_model class PerceptualLoss(torch.nn.Module): def __init__(self, model='net-lin', net='alex', colorspace='rgb', spatial=False, use_gpu=True, gpu_ids=[0]): # VGG using our perceptually-learned weights (LPIPS metric) # def __init__(self, model='net', net='vgg', use_gpu=True): # "default" way of using VGG as a perceptual loss super(PerceptualLoss, self).__init__() print('Setting up Perceptual loss...') self.use_gpu = use_gpu self.spatial = spatial self.gpu_ids = gpu_ids self.model = dist_model.DistModel() self.model.initialize(model=model, net=net, use_gpu=use_gpu, colorspace=colorspace, spatial=self.spatial, gpu_ids=gpu_ids) print('...[%s] initialized'%self.model.name()) print('...Done') def forward(self, pred, target, normalize=False): """ Pred and target are Variables. If normalize is True, assumes the images are between [0,1] and then scales them between [-1,+1] If normalize is False, assumes the images are already between [-1,+1] Inputs pred and target are Nx3xHxW Output pytorch Variable N long """ if normalize: target = 2 * target - 1 pred = 2 * pred - 1 return self.model.forward(target, pred) def normalize_tensor(in_feat,eps=1e-10): norm_factor = torch.sqrt(torch.sum(in_feat**2,dim=1,keepdim=True)) return in_feat/(norm_factor+eps) def l2(p0, p1, range=255.): return .5*np.mean((p0 / range - p1 / range)**2) def psnr(p0, p1, peak=255.): return 10*np.log10(peak**2/np.mean((1.*p0-1.*p1)**2)) def dssim(p0, p1, range=255.): return (1 - compare_ssim(p0, p1, data_range=range, multichannel=True)) / 2. def rgb2lab(in_img,mean_cent=False): from skimage import color img_lab = color.rgb2lab(in_img) if(mean_cent): img_lab[:,:,0] = img_lab[:,:,0]-50 return img_lab def tensor2np(tensor_obj): # change dimension of a tensor object into a numpy array return tensor_obj[0].cpu().float().numpy().transpose((1,2,0)) def np2tensor(np_obj): # change dimenion of np array into tensor array return torch.Tensor(np_obj[:, :, :, np.newaxis].transpose((3, 2, 0, 1))) def tensor2tensorlab(image_tensor,to_norm=True,mc_only=False): # image tensor to lab tensor from skimage import color img = tensor2im(image_tensor) img_lab = color.rgb2lab(img) if(mc_only): img_lab[:,:,0] = img_lab[:,:,0]-50 if(to_norm and not mc_only): img_lab[:,:,0] = img_lab[:,:,0]-50 img_lab = img_lab/100. return np2tensor(img_lab) def tensorlab2tensor(lab_tensor,return_inbnd=False): from skimage import color import warnings warnings.filterwarnings("ignore") lab = tensor2np(lab_tensor)*100. lab[:,:,0] = lab[:,:,0]+50 rgb_back = 255.*np.clip(color.lab2rgb(lab.astype('float')),0,1) if(return_inbnd): # convert back to lab, see if we match lab_back = color.rgb2lab(rgb_back.astype('uint8')) mask = 1.*
np.isclose(lab_back,lab,atol=2.)
numpy.isclose
from keras.utils import to_categorical, Sequence from rdkit import Chem from rdkit.Chem import rdmolops, AllChem import numpy as np import pandas as pd import pickle import random import math import os def one_hot(x, allowable_set): # If x is not in allowed set, use last index if x not in allowable_set: x = allowable_set[-1] return list(map(lambda s: x == s, allowable_set)) def find_distance(a1, num_atoms, bond_adj_list, max_distance=7): """Computes distances from provided atom. Parameters ---------- a1: RDKit atom The source atom to compute distances from. num_atoms: int The total number of atoms. bond_adj_list: list of lists `bond_adj_list[i]` is a list of the atom indices that atom `i` shares a bond with. This list is symmetrical so if `j in bond_adj_list[i]` then `i in bond_adj_list[j]`. max_distance: int, optional (default 7) The max distance to search. Returns ------- distances: np.ndarray Of shape `(num_atoms, max_distance)`. Provides a one-hot encoding of the distances. That is, `distances[i]` is a one-hot encoding of the distance from `a1` to atom `i`. """ distance = np.zeros((num_atoms, max_distance)) radial = 0 # atoms `radial` bonds away from `a1` adj_list = set(bond_adj_list[a1]) # atoms less than `radial` bonds away all_list = set([a1]) while radial < max_distance: distance[list(adj_list), radial] = 1 all_list.update(adj_list) # find atoms `radial`+1 bonds away next_adj = set() for adj in adj_list: next_adj.update(bond_adj_list[adj]) adj_list = next_adj - all_list radial = radial + 1 return np.array(distance) def graph_distance(num_atoms, adj, max_distance=7): # Get canonical adjacency list bond_adj_list = [[] for mol_id in range(num_atoms)] for i in range(num_atoms): for j in range(num_atoms): if adj[i, j] == 1: bond_adj_list[i].append(j) bond_adj_list[j].append(i) distance_matrix = np.zeros([num_atoms, num_atoms, max_distance]) for a1 in range(num_atoms): # distance is a matrix of 1-hot encoded distances for all atoms distance = find_distance(a1, num_atoms, bond_adj_list, max_distance=max_distance) distance_matrix[a1, :, :] = distance return distance_matrix def degree_rotation_matrix(axis, degree): theta = degree / 180 * np.pi if axis == "x": r = np.array([1, 0, 0, 0, np.cos(theta), -np.sin(theta), 0, np.sin(theta), np.cos(theta)]).reshape([3, 3]) elif axis == "y": r = np.array([np.cos(theta), 0, np.sin(theta), 0, 1, 0, -np.sin(theta), 0, np.cos(theta)]).reshape([3, 3]) elif axis == "z": r = np.array([np.cos(theta), -np.sin(theta), 0, np.sin(theta), np.cos(theta), 0, 0, 0, 1]).reshape([3, 3]) else: raise ValueError("Unsupported axis for rotation: {}".format(axis)) return r def optimize_conformer(m, algo="MMFF"): # print("Calculating {}: {} ...".format(Chem.MolToSmiles(m))) mol = Chem.AddHs(m) mol2 = Chem.Mol(mol) if algo == "ETKDG": # Landrum et al. DOI: 10.1021/acs.jcim.5b00654 k = AllChem.EmbedMolecule(mol, AllChem.ETKDG()) if k != 0: return None, None elif algo == "UFF": # Universal Force Field AllChem.EmbedMultipleConfs(mol, 50, pruneRmsThresh=0.5) try: arr = AllChem.UFFOptimizeMoleculeConfs(mol, maxIters=2000) except ValueError: return None, None if not arr: return None, None else: arr = AllChem.UFFOptimizeMoleculeConfs(mol, maxIters=20000) idx = np.argmin(arr, axis=0)[1] conf = mol.GetConformers()[idx] mol.RemoveAllConformers() mol.AddConformer(conf) elif algo == "MMFF": # Merck Molecular Force Field AllChem.EmbedMultipleConfs(mol, 50, pruneRmsThresh=0.5) try: arr = AllChem.MMFFOptimizeMoleculeConfs(mol, maxIters=2000) except ValueError: return None, None if not arr: return None, None else: arr = AllChem.MMFFOptimizeMoleculeConfs(mol, maxIters=20000) idx = np.argmin(arr, axis=0)[1] conf = mol.GetConformer(id=int(idx)) # conf = mol.GetConformers()[idx] # mol.RemoveAllConformers() # mol.AddConformer(conf) mol2.AddConformer(conf) return Chem.RemoveHs(mol2) mol = Chem.RemoveHs(mol) return mol class Dataset(object): def __init__(self, dataset, fold, iter, split, adj_cutoff=None, batch=128, add_bf=False, model_type="3dgcn"): self.dataset = dataset self.path = "./dataset/{}.sdf".format(dataset) self.task = None # "binary" self.target_name = None # "active" self.max_atoms = 0 self.split = split self.fold = fold self.iter = iter self.adj_cutoff = adj_cutoff self.add_bf = add_bf self.model_type = model_type self.batch = batch self.outputs = 1 self.mols = [] self.coords = [] self.target = [] self.x, self.c, self.y = {}, {}, {} self.use_overlap_area = False self.use_full_ec = False self.use_atom_symbol = True self.use_degree = True self.use_hybridization = True self.use_implicit_valence = True self.use_partial_charge = False self.use_formal_charge = True self.use_ring_size = True self.use_hydrogen_bonding = True self.use_acid_base = True self.use_aromaticity = True self.use_chirality = True self.use_num_hydrogen = True # Load data self.load_dataset(iter) # Calculate number of features if self.add_bf: print("Add bond features") mp = MPGenerator_bond([], [], [], 1, model_type=self.model_type, use_overlap_area=self.use_overlap_area, use_full_ec=self.use_full_ec, use_atom_symbol=self.use_atom_symbol, use_degree=self.use_degree, use_hybridization=self.use_hybridization, use_implicit_valence=self.use_implicit_valence, use_partial_charge=self.use_partial_charge, use_formal_charge=self.use_formal_charge, use_ring_size=self.use_ring_size, use_hydrogen_bonding=self.use_hydrogen_bonding, use_acid_base=self.use_acid_base, use_aromaticity=self.use_aromaticity, use_chirality=self.use_chirality, use_num_hydrogen=self.use_num_hydrogen) else: mp = MPGenerator([], [], [], 1, use_full_ec=self.use_full_ec, use_atom_symbol=self.use_atom_symbol, use_degree=self.use_degree, use_hybridization=self.use_hybridization, use_implicit_valence=self.use_implicit_valence, use_partial_charge=self.use_partial_charge, use_formal_charge=self.use_formal_charge, use_ring_size=self.use_ring_size, use_hydrogen_bonding=self.use_hydrogen_bonding, use_acid_base=self.use_acid_base, use_aromaticity=self.use_aromaticity, use_chirality=self.use_chirality, use_num_hydrogen=self.use_num_hydrogen) self.num_features = mp.get_num_features() # Normalize if self.task == "regression": self.mean = np.mean(self.y["train"]) self.std = np.std(self.y["train"]) self.y["train"] = (self.y["train"] - self.mean) / self.std self.y["test"] = (self.y["test"] - self.mean) / self.std try: self.y["valid"] = (self.y["valid"] - self.mean) / self.std except: print("Cannot normalize") else: self.mean = 0 self.std = 1 def load_dataset(self, iter): # Dataset parameters if self.dataset == "bace_reg" or self.dataset == "delaney" or self.dataset == "freesolv": self.task = "regression" self.target_name = "target" self.loss = "mse" elif self.dataset == "bace_cla" or self.dataset == "hiv": self.task = "binary" self.target_name = "active" self.loss = "binary_crossentropy" elif self.dataset == "tox21": self.target_name = "NR-ER" # elif self.dataset == "tox21": # Multitask tox21 # self.target_name = ["NR-Aromatase", "NR-AR", "NR-AR-LBD", "NR-ER", "NR-ER-LBD", "NR-PPAR-gamma", "NR-AhR", # "SR-ARE", "SR-ATAD5", "SR-HSE", "SR-MMP", "SR-p53"] else: pass # Load file x, c, y = [], [], [] try: mols = Chem.SDMolSupplier(self.path) except: mols = Chem.SDMolSupplier("../dataset/{}.sdf".format(self.dataset)) for mol in mols: if mol is not None: if mol.GetNumAtoms() > 200: continue # Multitask if type(self.target_name) is list: y.append([float(mol.GetProp(t)) if t in mol.GetPropNames() else -1 for t in self.target_name]) self.outputs = len(self.target_name) # Single task elif self.target_name in mol.GetPropNames(): _y = float(mol.GetProp(self.target_name)) if _y == -1: continue else: y.append(_y) else: continue x.append(mol) c.append(mol.GetConformer().GetPositions()) assert len(x) == len(y) # Filter and update maximum number of atoms new_x, new_c, new_y = [], [], [] if self.max_atoms > 0: for mol, coo, tar in zip(x, c, y): if mol.GetNumAtoms() <= self.max_atoms: new_x.append(mol) new_c.append(coo) new_y.append(tar) x = new_x c = new_c y = new_y else: for mol, tar in zip(x, y): self.max_atoms = max(self.max_atoms, mol.GetNumAtoms()) if self.task != "regression": self.mols, self.coords, self.target = np.array(x), np.array(c), np.array(y, dtype=int) else: self.mols, self.coords, self.target = np.array(x), np.array(c), np.array(y) # Shuffle data np.random.seed(25) # np.random.seed(100) -> before 1012 idx = np.random.permutation(len(self.mols)) self.mols, self.coords, self.target = self.mols[idx], self.coords[idx], self.target[idx] # Split data if self.split == "random" or self.fold == 1: print('random split') # Split data spl1 = int(len(self.mols) * 0.2) spl2 = int(len(self.mols) * 0.1) self.x = {"train": self.mols[spl1:], "valid": self.mols[spl2:spl1], "test": self.mols[:spl2]} self.c = {"train": self.coords[spl1:], "valid": self.coords[spl2:spl1], "test": self.coords[:spl2]} self.y = {"train": self.target[spl1:], "valid": self.target[spl2:spl1], "test": self.target[:spl2]} elif self.split == "": print('cross-validation split') # Split data len_test = int(len(self.mols) / self.fold) if iter == (self.fold - 1): self.x = {"train": self.mols[:len_test * iter], "test": self.mols[len_test * iter:]} self.c = {"train": self.coords[:len_test * iter], "test": self.coords[len_test * iter:]} self.y = {"train": self.target[:len_test * iter], "test": self.target[len_test * iter:]} else: self.x = {"train": np.concatenate((self.mols[:len_test * iter], self.mols[len_test * (iter + 1):])), "test": self.mols[len_test * iter:len_test * (iter + 1)]} self.c = {"train": np.concatenate((self.coords[:len_test * iter], self.coords[len_test * (iter + 1):])), "test": self.coords[len_test * iter:len_test * (iter + 1)]} self.y = {"train": np.concatenate((self.target[:len_test * iter], self.target[len_test * (iter + 1):])), "test": self.target[len_test * iter:len_test * (iter + 1)]} elif self.split == "stratified": # Dataset parameters if self.dataset == "bace_cla" or self.dataset == "hiv": # Shuffle data idx_inactive = np.squeeze(
np.argwhere(self.target == 0)
numpy.argwhere
# Double pendulum formula translated from the C code at # http://www.physics.usyd.edu.au/~wheat/dpend_html/solve_dpend.c from numpy import sin, cos import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate import matplotlib.animation as animation plt.style.use("animation_support") G = 9.8 # acceleration due to gravity, in m/s^2 L1 = 1.0 # length of pendulum 1 in m L2 = 1.0 # length of pendulum 2 in m M1 = 1.0 # mass of pendulum 1 in kg M2 = 1.0 # mass of pendulum 2 in kg def derivs(state, t): dydx = np.zeros_like(state) dydx[0] = state[1] del_ = state[2] - state[0] den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_) dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_) + M2*G*sin(state[2])*cos(del_) + M2*L2*state[3]*state[3]*sin(del_) - (M1 + M2)*G*sin(state[0]))/den1 dydx[2] = state[3] den2 = (L2/L1)*den1 dydx[3] = (-M2*L2*state[3]*state[3]*sin(del_)*
cos(del_)
numpy.cos
#!/usr/bin/env python3 # # Tests the Rosenbrock toy problems. # # This file is part of PINTS. # Copyright (c) 2017-2018, University of Oxford. # For licensing information, see the LICENSE file distributed with the PINTS # software package. # import pints import pints.toy import unittest import numpy as np class TestRosenbrock(unittest.TestCase): """ Tests the Rosenbrock toy problems. """ def test_error(self): f = pints.toy.RosenbrockError() self.assertEqual(f.n_parameters(), 2) fx = f([10, 10]) self.assertTrue(np.isscalar(fx)) self.assertEqual(fx, 810081) xopt = f.optimum() fopt = f(xopt) self.assertEqual(fopt, 0) np.random.seed(1) for x in np.random.uniform(-5, 5, size=(10, 2)): self.assertTrue(f(x) > fopt) def test_log_pdf(self): f = pints.toy.RosenbrockLogPDF() self.assertEqual(f.n_parameters(), 2) fx = f([0.5, 6.0]) self.assertTrue(np.isscalar(fx)) self.assertAlmostEqual(fx, np.log(1.0 / 3307.5)) xopt = f.optimum() fopt = f(xopt) self.assertEqual(fopt, 0) # sensitivity test l, dl = f.evaluateS1([3, 4]) self.assertEqual(l, -np.log(2505)) self.assertEqual(len(dl), 2) self.assertEqual(dl[0], float(-6004.0 / 2505.0)) self.assertEqual(dl[1], float(200.0 / 501.0)) # suggested bounds and distance measure bounds = f.suggested_bounds() bounds = [[-2, 4], [-1, 12]] bounds = np.transpose(bounds).tolist() self.assertTrue(np.array_equal(bounds, f.suggested_bounds())) x = np.ones((100, 3)) self.assertRaises(ValueError, f.distance, x) x = np.ones((100, 3, 2)) self.assertRaises(ValueError, f.distance, x) # there is no simple way to generate samples from Rosenbrock nsamples = 10000 g = pints.toy.GaussianLogPDF([1, 1], [1, 1]) samples = g.sample(nsamples) self.assertTrue(f.distance(samples) > 0) x =
np.ones((100, 3))
numpy.ones
from __future__ import division import ctypes, os, shutil import numpy as np # constants c = 299792458 eps0 = 8.854187817e-12 e = 1.602176565e-19 m_e = 9.10938291e-31 hbar = 1.054571726e-34 h = 2*np.pi*hbar a0 = 4*np.pi*eps0*hbar**2/m_e/e**2 Ry = h*c * m_e*e**4/8/eps0**2/h**3/c # find and import shared object / DLL rootdir = os.path.dirname(os.path.realpath(__file__)) if os.name=="posix": lewenstein_so = ctypes.CDLL(os.path.join(rootdir,'lewenstein.so')) elif os.name=="nt": bits = ctypes.sizeof(ctypes.c_voidp)*8 archdirectory = os.path.join(rootdir,'dll' + str(bits)) cwd = os.getcwd() os.chdir(archdirectory) # necessary to load dependencies correctly lewenstein_so = ctypes.CDLL('lewenstein.dll') os.chdir(cwd) # Note: explicitly setting lewenstein_so.*.argtypes/restype is necessary to prevent segfault on 64 bit: # http://stackoverflow.com/questions/17240621/wrapping-simple-c-example-with-ctypes-segmentation-fault # base class for dipole elements class dipole_elements(object): dims = None pointer = None def __del__(self): raise NotImplementedError('override in subclasses') # wrap H dipole elements lewenstein_so.dipole_elements_H_double.argtypes = [ctypes.c_int, ctypes.c_double] lewenstein_so.dipole_elements_H_double.restype = ctypes.c_void_p lewenstein_so.dipole_elements_H_double_destroy.argtypes = [ctypes.c_int, ctypes.c_void_p] lewenstein_so.dipole_elements_H_double_destroy.restype = None class dipole_elements_H(dipole_elements): def __init__(self, dims, ip, wavelength=None): if wavelength: ip = sau_convert(ip, 'U', 'SAU', wavelength) alpha = 2*ip self.dims = dims self.pointer = lewenstein_so.dipole_elements_H_double(dims, alpha) def __del__(self): lewenstein_so.dipole_elements_H_double_destroy(self.dims, self.pointer) # wrap symmetric interpolated dipole elements lewenstein_so.dipole_elements_symmetric_interpolate_double.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_double, ctypes.c_void_p, ctypes.c_void_p] lewenstein_so.dipole_elements_symmetric_interpolate_double.restype = ctypes.c_void_p lewenstein_so.dipole_elements_symmetric_interpolate_double_destroy.argtypes = [ctypes.c_int, ctypes.c_void_p] lewenstein_so.dipole_elements_symmetric_interpolate_double_destroy.restype = None class dipole_elements_symmetric_interpolate(dipole_elements): _dr = None _di = None def __init__(self, dims, p, d, wavelength=None): if wavelength is not None: p = sau_convert(p, 'p', 'SAU', wavelength) d = sau_convert(d, 'd', 'SAU', wavelength) self.dims = dims N = p.size assert d.size==N dp = np.min(np.diff(p)) assert np.isclose(dp, np.max(np.diff(p)), atol=0) # dr and di must not be garbage collected until destructor is called, so make it a property of this class self._dr = np.require(np.copy(d.real), np.double, ['C', 'A']) self._di = np.require(np.copy(d.imag), np.double, ['C', 'A']) self.pointer = lewenstein_so.dipole_elements_symmetric_interpolate_double(dims, N, dp, self._dr.ctypes.data, self._di.ctypes.data) def __del__(self): lewenstein_so.dipole_elements_symmetric_interpolate_double_destroy(self.dims, self.pointer) # helper functions to generate weights def piecewise_cossqr(t, ts, ys): ts, ys = np.array(ts), np.array(ys) y = np.zeros_like(t, ys.dtype) for tstart, tend, ystart, yend in zip(ts[:-1], ts[1:], ys[:-1], ys[1:]): piece = (tstart<=t) & (t<=tend) tscaled = t[piece]/(tend-tstart) - tstart/(tend-tstart) y[piece] = (ystart-yend) * np.cos(tscaled*np.pi/2)**2 + yend return y def weights_short_trajectory(tau,T=2*np.pi,periods_soft=0.01): tau = tau - tau[0] tau_truncated = tau[tau/T<=0.65] return piecewise_cossqr(tau_truncated/T, [0, 0.65-periods_soft, 0.65], [1., 1., 0.]) def weights_long_trajectory(tau,T=2*np.pi,periods_soft=0.01): tau = tau - tau[0] tau_truncated = tau[tau/T<=1] return piecewise_cossqr(tau_truncated/T, [0, 0.65, 0.65+periods_soft, 1-periods_soft, 1], [0., 0., 1., 1., 0.]) def get_weights(tau,T=2*np.pi,periods_one=1,periods_soft=.5): tau = tau - tau[0] tau_truncated = tau[tau/T<=periods_one+periods_soft] return piecewise_cossqr(tau_truncated/T, [0, periods_one, periods_one+periods_soft], [1., 1., 0.]) # helper function for unit conversion def sau_convert(value, quantity, target, wavelength): # scaled atomic unit quantities expressed in SI units unit = {} unit['t'] = wavelength / c / (2*np.pi) unit['omega'] = 1/unit['t'] unit['U'] = hbar * unit['omega'] # hbar*omega unit['q'] = e unit['s'] = a0 * np.sqrt(2*Ry/unit['U']) # [concluded from (23) in Lewenstein paper] unit['E'] = unit['U'] / unit['q'] / unit['s'] # [concluded from (2) in Lewenstein paper] unit['d'] = unit['q'] * unit['s'] # dipole element unit['m'] = m_e unit['p'] = unit['m'] * unit['s']/unit['t'] # momentum if target=="SI": return value * unit[quantity] elif target=="SAU": return value / unit[quantity] else: raise ValueError('target must be SI or SAU') # wrap lewenstein function lewenstein_so.lewenstein_double.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_double, ctypes.c_double, ctypes.c_void_p, ctypes.c_void_p] lewenstein_so.lewenstein_double.restype = None def lewenstein(t,Et,ip,wavelength=None,weights=None,at=None,dipole_elements=None,epsilon_t=1e-4): # default value for weights if weights is None and wavelength is None: weights = get_weights(t) elif weights is None and wavelength is not None: weights = get_weights(t, wavelength/c) # unit conversion if wavelength is not None: t = sau_convert(t, 't', 'SAU', wavelength) Et = sau_convert(Et, 'E', 'SAU', wavelength) ip = sau_convert(ip, 'U', 'SAU', wavelength) # default value for ground state amplitude if at is None: at = np.ones_like(t) # allocate memory for output output = np.empty_like(Et) # make sure t axis starts at zero t = t - t[0] # make sure we have appropriate memory layout before passing to C code t = np.require(t, np.double, ['C', 'A']) Et = np.require(Et, np.double, ['C', 'A']) weights = np.require(weights, np.double, ['C', 'A']) at = np.require(at, np.double, ['C', 'A']) output = np.require(output, np.double, ['C', 'A', 'W']) # get dimensions N = t.size dims = Et.shape[1] if len(Et.shape)>1 else 1 weights_length = weights.size # check dimensions assert at.size==N assert Et.shape[0]==N assert dims in [1,2,3] assert Et.size==N*dims # default value for dipole elements if dipole_elements is None: dipole_elements = dipole_elements_H(dims, ip=ip) # call C function assert dipole_elements.dims==dims lewenstein_so.lewenstein_double(dims, N, t.ctypes.data, Et.ctypes.data, weights_length, weights.ctypes.data, at.ctypes.data, ip, epsilon_t, dipole_elements.pointer, output.ctypes.data) # unit conversion if wavelength is not None: output = sau_convert(output, 'd', 'SI', wavelength) return output # wrap yakovlev function lewenstein_so.yakovlev_double.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_double, ctypes.c_void_p] lewenstein_so.yakovlev_double.restype = None def yakovlev(t,Et,ip,at,wavelength=None,weights=None,dtfraction=None): # default value for weights if weights is None and wavelength is None: weights = get_weights(t) elif weights is None and wavelength is not None: weights = get_weights(t, wavelength/c) # unit conversion if wavelength is not None: t = sau_convert(t, 't', 'SAU', wavelength) Et = sau_convert(Et, 'E', 'SAU', wavelength) ip = sau_convert(ip, 'U', 'SAU', wavelength) # allocate memory for output output = np.empty_like(Et) # make sure t axis starts at zero t = t - t[0] # compute dtfraction if not given if dtfraction is None: dt = t[1] atsqr = at**2 dtfraction = np.empty_like(at) dtfraction[0] = 0 dtfraction[1:] = -np.diff(at**2)/dt # make sure we have appropriate memory layout before passing to C code t = np.require(t, np.double, ['C', 'A']) Et = np.require(Et, np.double, ['C', 'A']) weights = np.require(weights, np.double, ['C', 'A']) dtfraction = np.require(dtfraction, np.double, ['C', 'A']) at = np.require(at, np.double, ['C', 'A']) output =
np.require(output, np.double, ['C', 'A', 'W'])
numpy.require
import numpy as np import json from random import choice, seed from datetime import datetime, timedelta class OccupancyGenerator: """ This class use the queueing system to generate the occupancy schedule TODO: Add occupancy actions """ def __init__(self, model, num_occupant=10, random_seed=None, transition_matrics=None): """ This class contains multiple editable attributes to generate the occupancy schedule. Default setting includes: Work shift: 9:00 ~ 17:00, where people start arriving/leaving 30 minutes earily. Group meeting: 16:00, once per day, last average 15 minutes. Lunch time: 12:00 ~ 13:00. Call for absence probability: 1%. Chat with colleague: average 30 minutes each. Customer service time: average 30 minutes each. Average number of guests per day: 3. :parameter model: The ``COBS.Model`` class object as the target building model. :parameter num_occupant: The number of long-term occupants belongs to the model. :parameter random_seed: The seed for numpy and random module. None means no seed specified. :parameter transition_matrics: A list/tuple of numpy.ndarray, or a single numpy.ndarray, or None. Each numpy.ndarray must be in the shape of (len(self.possible_locations), len(self.possible_locations)). The first len(self.possible_locations) - 1 row and column represents the transition rate between zones that are in the order of self.possible_locations. The last row and column represents the transition rate of the office to other zones (will overwrite previous transition rate). Transition rate in the unit of seconds. None means the occupant always stay in the office. """ if random_seed is not None: seed(random_seed) np.random.seed(random_seed) self.work_start_time = 9 * 60 * 60 # Work start from 9:00. unit: second self.work_end_time = 17 * 60 * 60 # Work end at 17:00. unit: second self.meeting_time = 16 * 60 * 60 # Daily progress report at 16:00, in meeting room self.meeting_length_avg = 15 * 60 # Daily progress report average length 15 min self.meeting_length_std = 1 * 60 # Daily progress report std.dev 1 min self.max_earliness = 30 * 60 # Tend to come 8:30, average arrive at 9:00. Leave is similar. Exponential distribution self.call_for_absence_prob = 0.01 # Possibility of not come to the office self.lunch_break_start = 12 * 60 * 60 # Lunch serve start time 12:00. unit: second self.lunch_break_end = 13 * 60 * 60 # Lunch serve end time 13:00. unit: second self.eat_time_a = 10 # average time for each person to eat lunch. Beta distribution self.eat_time_b = self.lunch_break_end - self.lunch_break_start # average time for each person to eat lunch. Beta distribution self.cut_off_time = 14 * 60 * 60 # After this time, the person won't come to work self.day_cut_off = 24 * 60 * 60 self.start_synthetic_data = datetime(2020, 3, 25) # start date self.end_synthetic_data = datetime(2020, 3, 27) # end date self.report_interval = timedelta(seconds=60) # Time interval between two consecutive package self.guest_lambda = 3 # Poisson arrival for unknown customers. unit: person per day self.visit_colleague_lambda = 3 # How many times a worker goes to a colleague's office self.average_stay_in_colleague_office = 30 * 60 self.std_stay_in_colleague_office = 4 * 60 self.average_stay_customer = 30 * 60 self.std_stay_customer = 5 * 60 # TODO: Add zone trespass time self.model = model self.possible_locations = self.model.get_available_names_under_group("Zone") self.work_zones = self.possible_locations[:] self.zone_link = model.get_link_zones() self.meeting_room = choice(self.possible_locations) self.lunch_room = choice(self.possible_locations) self.entry_zone = choice(list(self.zone_link["Outdoor"])) self.possible_locations.insert(0, "Outdoor") self.possible_locations.append("busy") self.weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] self.work_zones.remove(self.lunch_room) if self.meeting_room != self.lunch_room: self.work_zones.remove(self.meeting_room) if isinstance(transition_matrics, (tuple, list)): if len(transition_matrics) != num_occupant: raise ValueError(f"Length of the transition_matrics must be num_occupant {num_occupant}.") self.worker_assign = [Person(self, office=choice(self.work_zones), transition_rate_matrix=transition_matrics[i]) for i in range(num_occupant)] elif isinstance(transition_matrics, np.ndarray): self.worker_assign = [Person(self, office=choice(self.work_zones), transition_rate_matrix=transition_matrics.copy()) for _ in range(num_occupant)] elif transition_matrics is None: self.worker_assign = [Person(self, office=choice(self.work_zones)) for _ in range(num_occupant)] else: raise ValueError("transition_matrics must be a list/tuple of numpy.ndarray, single numpy.ndarray, or None.") # value = (np.random.beta(eat_time_a, eat_time_b, 10000) + 0.1) * 100 def set_transition_matrics(self, transition_matrics): """ Set the transition matrics to each corresponding person. :param transition_matrics: A list of matrics or one matrix """ if isinstance(transition_matrics, (tuple, list)): if len(transition_matrics) != len(self.worker_assign): raise ValueError(f"Length of the transition_matrics must be num_occupant {len(self.worker_assign)}.") for i, q in enumerate(transition_matrics): self.worker_assign[i].set_transition_matrix(q) elif isinstance(transition_matrics, np.ndarray): if transition_matrics.ndim == 3: if transition_matrics.shape[0] != len(self.worker_assign): raise ValueError(f"For concatenated numpy array, the shape of the transition_matrics must be" f" ({len(self.worker_assign)}, " f"{len(self.possible_locations)}, {len(self.possible_locations)}).") for i in range(transition_matrics.shape[0]): self.worker_assign[i].set_transition_matrix(transition_matrics[i, :, :]) else: for worker in self.worker_assign: worker.set_transition_matrix(transition_matrics.copy()) def get_path(self, start, end): """ Use BFS to find the shortest path between two zones. :parameter start: The entry of the start zone. :parameter end: The entry of the target zone. :return: A list of zone names that the occupant need to cross. """ queue = [(start, [start])] visited = set() while queue: vertex, path = queue.pop(0) visited.add(vertex) for node in self.zone_link[vertex]: if node == end: return path + [end] else: if node not in visited: visited.add(node) queue.append((node, path + [node])) return [start] def generate_all_people_daily_movement(self, use_scheduled_events=True): """ Generate a list of ``Person`` objects and simulate the movement for each person. :return: list of ``Person`` objects. """ available_worker = list() for i, worker in enumerate(self.worker_assign): if worker.decide_come(): available_worker.append(i) # print(available_worker) guests = np.random.poisson(self.guest_lambda) if use_scheduled_events else 0 guest_assign = np.random.choice(available_worker, size=guests) all_people = list() guest_counter = 0 for i in available_worker: worker = self.worker_assign[i] all_people.append(worker) guest_list = np.random.randint(1, 4, size=np.sum(guest_assign == i)) appointments = worker.generate_daily_route(guest_list, use_scheduled_events) for j, appointment in enumerate(appointments): for _ in range(guest_list[j]): new_guest = Person(self) guest_counter += 1 new_guest.customer_come(*appointment) all_people.append(new_guest) return all_people def generate_daily_schedule(self, add_to_model=True, overwrite_dict=None, use_scheduled_events=True): """ Generate a numpy matrix contains the locations of all occupants in the day and add tp the model. :parameter add_to_model: Default is True. If False, then only generate the schedule in numpy and IDF format but not save to the model automatically. :parameter overwrite_dict: Default is None. If set to a dict with {zone_name: old_people_object_name}, it will overwrite existing People instead of creating a new one :parameter use_scheduled_events: Default is True. Determines if the lunch and group meeting event will be simulated :return: Three objects, (IDF format schedule, numpy format schedule, list of all accessble locations in the building). """ all_zones = self.model.get_available_names_under_group("Zone") valid_zones = list() for zone in all_zones: if zone in self.possible_locations: valid_zones.append(zone) all_people = self.generate_all_people_daily_movement(use_scheduled_events) locations = list() for person in all_people: locations.append(person.position.copy()) if person.office is not None: locations[-1][locations[-1] == self.possible_locations.index('busy')] = \ self.possible_locations.index(person.office) location_matrix = np.vstack(locations) all_commands = list() if add_to_model: act, work, cloth, air = self.occupancy_prep() self.model.add_configuration("Output:Variable", values={"Variable Name": "Zone People Occupant Count", "Reporting_Frequency": "timestep"}) self.model.add_configuration("Output:Variable", values={"Variable Name": "Zone Thermal Comfort Fanger Model PMV", "Reporting_Frequency": "timestep"}) zone_occupancy = np.zeros((len(self.possible_locations), 24 * 60)) for zone in valid_zones: i = self.possible_locations.index(zone) occupancy = np.sum(location_matrix == i, axis=0) result_command = {"Name": f"Generated_Schedule_Zone_{zone}", "Schedule Type Limits Name": "Any Number", "Field 1": "Through: 12/31", "Field 2": "For: Weekdays"} counter = 3 for t in range(1, 24 * 60 + 1): zone_occupancy[i, t - 1] = occupancy[t * 60 - 1] if t != 24 * 60 and occupancy[(t + 1) * 60 - 1] == occupancy[t * 60 - 1]: continue hour = t // 60 min = t % 60 result_command[f"Field {counter}"] = f"Until {hour:02d}:{min:02d}" result_command[f"Field {counter + 1}"] = f"{occupancy[t * 60 - 1]}" counter += 2 all_commands.append(result_command) if add_to_model: self.model.add_configuration("Schedule:Compact", values=result_command) if overwrite_dict is not None and zone in overwrite_dict: self.model.edit_configuration("People", {"Name": overwrite_dict[zone]}, {"Number of People": 1, "Number of People Schedule Name": f"Generated_Schedule_Zone_{zone}"}) else: people_values = {"Name": f"Test_Zone_{zone}", "Zone or ZoneList Name": zone, "Number of People Schedule Name": f"Generated_Schedule_Zone_{zone}", "Number of People": 1, "Activity Level Schedule Name": act, "Work Efficiency Schedule Name": work, "Clothing Insulation Schedule Name": cloth, "Air Velocity Schedule Name": air, "Thermal Comfort Model 1 Type": "Fanger"} self.model.add_configuration("People", values=people_values) return all_commands, location_matrix, zone_occupancy, self.possible_locations def one_day_numpy_to_schedule(self, array, name): result_command = {"Name": f"{name}", "Schedule Type Limits Name": "Any Number"} counter = 1 for t in range(1, 24 * 60 + 1): if t < 24 * 60 and array[t] == array[t - 1]: continue hour = t // 60 minute = t % 60 result_command[f"Time {counter}"] = f"Until {hour:02d}:{minute:02d}" result_command[f"Value Until Time {counter}"] = f"{int(array[t - 1])}" counter += 1 return self.model.add_configuration("Schedule:Day:Interval", values=result_command) def daily_to_week(self, daily_name_list, name, start_day): result_command = {"Name": f"{name}"} for i, daily_name in enumerate(daily_name_list): result_command[f"{self.weekdays[(start_day + i) % len(self.weekdays)]} Schedule:Day Name"] = daily_name result_command["Holiday Schedule:Day Name"] = result_command["Sunday Schedule:Day Name"] result_command["SummerDesignDay Schedule:Day Name"] = result_command["Sunday Schedule:Day Name"] result_command["WinterDesignDay Schedule:Day Name"] = result_command["Sunday Schedule:Day Name"] result_command["CustomDay1 Schedule:Day Name"] = result_command["Sunday Schedule:Day Name"] result_command["CustomDay2 Schedule:Day Name"] = result_command["Sunday Schedule:Day Name"] return self.model.add_configuration("Schedule:Week:Daily", values=result_command) def weeks_to_year(self, week_name_list, name): result_command = {"Name": f"{name}", "Schedule Type Limits Name": "Any Number"} start = datetime(1995 + self.model.leap_weather, 1, 1) start_next = datetime(1995 + self.model.leap_weather, 1, 1) counter = 1 for t in range(1, 54): start_next = start_next + timedelta(days=7) if t < 53 and week_name_list[t - 1] == week_name_list[t]: continue end = start_next - timedelta(days=1) result_command[f"Schedule:Week Name {counter}"] = week_name_list[t - 1] result_command[f"Start Month {counter}"] = start.month result_command[f"Start Day {counter}"] = start.day result_command[f"End Month {counter}"] = end.month result_command[f"End Day {counter}"] = end.day start = start_next counter += 1 result_command[f"End Month {counter - 1}"] = 12 result_command[f"End Day {counter - 1}"] = 31 return self.model.add_configuration("Schedule:Year", values=result_command) def occupancy_prep(self): activity_values = {"Name": "Test_Activity_Schedule", "Schedule Type Limits Name": "Any Number", "Field 1": "Through:12/31", "Field 2": "For: Alldays", "Field 3": "Until 24:00", "Field 4": "200"} work_efficiency = {"Name": "Test_Work_Schedule", "Schedule Type Limits Name": "Fraction", "Field 1": "Through:12/31", "Field 2": "For: Alldays", "Field 3": "Until 24:00", "Field 4": "0.1"} cloth_schedule = {"Name": "Test_Cloth_Schedule", "Schedule Type Limits Name": "Fraction", "Field 1": "Through:12/31", "Field 2": "For: Alldays", "Field 3": "Until 24:00", "Field 4": "0.9"} air_velocity = {"Name": "Test_Air_Velocity", "Schedule Type Limits Name": "Fraction", "Field 1": "Through:12/31", "Field 2": "For: Alldays", "Field 3": "Until 24:00", "Field 4": "0.25"} returns = [activity_values["Name"], work_efficiency["Name"], cloth_schedule["Name"], air_velocity["Name"]] if len(self.model.get_configuration("People")) == 0: self.model.add_configuration("Schedule:Compact", values=activity_values) self.model.add_configuration("Schedule:Compact", values=work_efficiency) self.model.add_configuration("Schedule:Compact", values=cloth_schedule) self.model.add_configuration("Schedule:Compact", values=air_velocity) else: prev = self.model.get_configuration("People")[0] for i, name, var in ((0, "Activity Level Schedule Name", activity_values), (1, "Work Efficiency Schedule Name", work_efficiency), (2, "Clothing Insulation Schedule Name", cloth_schedule), (3, "Air Velocity Schedule Name", air_velocity)): if name not in prev: self.model.add_configuration("Schedule:Compact", values=var) else: returns[i] = prev[name] return returns def generate_schedule_using_numpy(self, occupancy, room_name=None, start_day=0, overwrite_dict=None): """ Generate the occupancy pattern based on a given numpy ndarray, and add it to the model. :parameter occupancy: The numpy array with shape of (365, number_of_room, 24 * 60), where the first dimension indicates the 365 days on a year, the second dimension indicates the occupancy for each room, and the third dimension indicates the minute in a day. The value of this ndarray should be the number of occupants in the room at a specific time on a specific day. If the second dimension < actual number of rooms, the rest rooms are considered unoccupied all the time. :parameter room_name: an iterable object contains the name of rooms in the order they stored in the occupancy ndarray's second dimension. If room_name is not provided, then the default order will be used. :parameter start_day: Specify the start day of the week. 0 means Sunday, and 6 means Saturday. :parameter overwrite_dict: Default is None. If set to a dict with {zone_name: old_people_object_name}, it will overwrite existing People instead of creating a new one """ if not isinstance(occupancy, np.ndarray) or \ occupancy.ndim != 3 or \ occupancy.shape[0] != 365 + self.model.leap_weather or \ occupancy.shape[2] != 24 * 60: raise ValueError(f"Wrong format of the occupancy numpy array. " f"The shape must be ({365 + self.model.leap_weather}, n, 24 * 60)") if room_name is None: room_name = self.model.get_available_names_under_group("Zone") occupancy = occupancy.astype(int) days, rooms, _ = occupancy.shape name = self.model.get_configuration("RunPeriod")[0].Name self.model.edit_configuration("RunPeriod", {"Name": name}, {"Day of Week for Start Day": self.weekdays[start_day]}) occupancy, corres_id = np.unique(occupancy.reshape(-1, 24 * 60), axis=0, return_inverse=True) for i, row in enumerate(occupancy): self.one_day_numpy_to_schedule(row, name=f"Day Type {i}") occupancy, corres_id = np.unique(np.concatenate((corres_id.reshape(days, -1), np.zeros((7 - days % 7, rooms))), axis=0).T.reshape(-1, 7), axis=0, return_inverse=True) for i, row in enumerate(occupancy.astype(int)): self.daily_to_week(map(lambda x: f"Day Type {x}", row), name=f"Week Type {i}", start_day=start_day) for i, row in enumerate(corres_id.reshape(rooms, -1).astype(int)): if i == len(room_name): break self.weeks_to_year(list(map(lambda x: f"Week Type {x}", row)), name=f"Year For {room_name[i]}") if overwrite_dict is not None and room_name[i] in overwrite_dict: self.model.edit_configuration("People", {"Name": overwrite_dict[room_name[i]]}, {"Number of People": 1, "Number of People Schedule Name": f"Year For {room_name[i]}"}) else: act, work, cloth, air = self.occupancy_prep() people_values = {"Name": f"Test_Zone_{room_name[i]}", "Zone or ZoneList Name": room_name[i], "Number of People Schedule Name": f"Year For {room_name[i]}", "Number of People": 1, "Activity Level Schedule Name": act, "Work Efficiency Schedule Name": work, "Clothing Insulation Schedule Name": cloth, "Air Velocity Schedule Name": air, "Thermal Comfort Model 1 Type": "Fanger"} self.model.add_configuration("People", values=people_values) def save_light_config(self, output_name=None): if self.light_config is None: self.initialize_light_config() if output_name is None: output_name = "light_config.json" with open(output_name, 'w') as output_file: json.dump(self.light_config, output_file) def initialize_light_config(self): zone_lights = self.model.get_lights() self.light_config = dict() print(self.model.get_windows()) for zone in zone_lights: self.light_config[zone] = list() for light in zone_lights[zone]: self.light_config[zone].append({"name": light, "probability": 1, "condition": {zone_name: {"occupancy > 0": 1, "occupancy == 0": 1} for zone_name in self.possible_locations}}) def generate_light(self, input_name=None): pass class Person: """ This class contains the detail location of a single occupant. """ def __init__(self, generator, office=None, transition_rate_matrix=None): """ Each long-term occupant will have an office, and he tend to stay in office more than other places. :parameter generator: The OccupancyGenerator which provides the settings. :parameter office: The designated office for long-term occupants. :parameter transition_rate_matrix: The transition rate matrix for the current occupants (if None, assume the occupant tends to stay in the office). """ self.office = office self.position = np.zeros(generator.day_cut_off) self.source = generator self.start_time = 0 self.end_time = 0 self.transition_matrix = None if transition_rate_matrix is not None: self.set_transition_matrix(transition_rate_matrix) def set_transition_matrix(self, transition_rate_matrix): """ Define the transition matrix for the current person :param transition_rate_matrix: The transition matrix - a numpy array with shape (num_possible_zone + 2, num_possible_zone + 2). The order is [Outdoor, each zone, office] """ if not isinstance(transition_rate_matrix, np.ndarray): raise ValueError(f"The provided transition matrix be a numpy.ndarray") if len(self.source.possible_locations) != transition_rate_matrix.shape[0] or \ len(self.source.possible_locations) != transition_rate_matrix.shape[1]: raise ValueError(f"The provided transition matrix must in shape " f"({len(self.source.possible_locations)}, {len(self.source.possible_locations)})") office_idx = self.source.possible_locations.index(self.office) self.transition_matrix = transition_rate_matrix[:-1, :-1] if np.sum(transition_rate_matrix[-1, :]) +
np.sum(transition_rate_matrix[-1, :])
numpy.sum
# encoding: utf-8 """ Defines a common implementation of the PyNN API. Simulator modules are not required to use any of the code herein, provided they provide the correct interface, but it is suggested that they use as much as is consistent with good performance (optimisations may require overriding some of the default definitions given here). Utility functions and classes: is_conductance() check_weight() check_delay() Accessing individual neurons: IDMixin Common API implementation/base classes: 1. Simulation set-up and control: setup() end() run() reset() get_time_step() get_current_time() get_min_delay() get_max_delay() rank() num_processes() 2. Creating, connecting and recording from individual neurons: create() connect() set() initialize() build_record() 3. Creating, connecting and recording from populations of neurons: Population PopulationView Assembly Projection :copyright: Copyright 2006-2013 by the PyNN team, see AUTHORS. :license: CeCILL, see LICENSE for details. $Id: common.py 1258 2013-01-31 15:01:25Z apdavison $ """ import numpy, os import logging from warnings import warn import operator import tempfile from pyNN import random, recording, errors, models, standardmodels, core, space, descriptions from pyNN.recording import files from itertools import chain if not 'simulator' in locals(): simulator = None # should be set by simulator-specific modules DEFAULT_WEIGHT = 0.0 DEFAULT_BUFFER_SIZE = 10000 DEFAULT_MAX_DELAY = 10.0 DEFAULT_TIMESTEP = 0.1 DEFAULT_MIN_DELAY = DEFAULT_TIMESTEP logger = logging.getLogger("PyNN") # ============================================================================= # Utility functions and classes # ============================================================================= def is_conductance(target_cell): """ Returns True if the target cell uses conductance-based synapses, False if it uses current-based synapses, and None if the synapse-basis cannot be determined. """ if hasattr(target_cell, 'local') and target_cell.local and hasattr(target_cell, 'celltype'): is_conductance = target_cell.celltype.conductance_based else: is_conductance = None return is_conductance def check_weight(weight, synapse_type, is_conductance): if weight is None: weight = DEFAULT_WEIGHT if core.is_listlike(weight): weight = numpy.array(weight) nan_filter = (1 - numpy.isnan(weight)).astype(bool) # weight arrays may contain NaN, which should be ignored filtered_weight = weight[nan_filter] all_negative = (filtered_weight <= 0).all() all_positive = (filtered_weight >= 0).all() if not (all_negative or all_positive): raise errors.InvalidWeightError("Weights must be either all positive or all negative") elif numpy.isreal(weight): all_positive = weight >= 0 all_negative = weight < 0 else: raise errors.InvalidWeightError("Weight must be a number or a list/array of numbers.") if is_conductance or synapse_type == 'excitatory': if not all_positive: raise errors.InvalidWeightError("Weights must be positive for conductance-based and/or excitatory synapses") elif is_conductance == False and synapse_type == 'inhibitory': if not all_negative: raise errors.InvalidWeightError("Weights must be negative for current-based, inhibitory synapses") else: # is_conductance is None. This happens if the cell does not exist on the current node. logger.debug("Can't check weight, conductance status unknown.") return weight def check_delay(delay): if delay is None: delay = get_min_delay() # If the delay is too small , we have to throw an error if delay < get_min_delay() or delay > get_max_delay(): raise errors.ConnectionError("delay (%s) is out of range [%s,%s]" % \ (delay, get_min_delay(), get_max_delay())) return delay # ============================================================================= # Accessing individual neurons # ============================================================================= class IDMixin(object): """ Instead of storing ids as integers, we store them as ID objects, which allows a syntax like: p[3,4].tau_m = 20.0 where p is a Population object. """ # Simulator ID classes should inherit both from the base type of the ID # (e.g., int or long) and from IDMixin. def __getattr__(self, name): try: val = self.__getattribute__(name) except AttributeError: if name == "parent": raise Exception("parent is not set") try: val = self.get_parameters()[name] except KeyError: raise errors.NonExistentParameterError(name, self.celltype.__class__.__name__, self.celltype.get_parameter_names()) return val def __setattr__(self, name, value): if name == "parent": object.__setattr__(self, name, value) elif self.celltype.has_parameter(name): self.set_parameters(**{name: value}) else: object.__setattr__(self, name, value) def set_parameters(self, **parameters): """ Set cell parameters, given as a sequence of parameter=value arguments. """ # if some of the parameters are computed from the values of other # parameters, need to get and translate all parameters if self.local: if self.is_standard_cell: computed_parameters = self.celltype.computed_parameters() have_computed_parameters = numpy.any([p_name in computed_parameters for p_name in parameters]) if have_computed_parameters: all_parameters = self.get_parameters() all_parameters.update(parameters) parameters = all_parameters parameters = self.celltype.translate(parameters) self.set_native_parameters(parameters) else: raise errors.NotLocalError("Cannot set parameters for a cell that does not exist on this node.") def get_parameters(self): """Return a dict of all cell parameters.""" if self.local: parameters = self.get_native_parameters() if self.is_standard_cell: parameters = self.celltype.reverse_translate(parameters) return parameters else: raise errors.NotLocalError("Cannot obtain parameters for a cell that does not exist on this node.") @property def celltype(self): return self.parent.celltype @property def is_standard_cell(self): return issubclass(self.celltype.__class__, standardmodels.StandardCellType) def _set_position(self, pos): """ Set the cell position in 3D space. Cell positions are stored in an array in the parent Population. """ assert isinstance(pos, (tuple, numpy.ndarray)) assert len(pos) == 3 self.parent._set_cell_position(self, pos) def _get_position(self): """ Return the cell position in 3D space. Cell positions are stored in an array in the parent Population, if any, or within the ID object otherwise. Positions are generated the first time they are requested and then cached. """ return self.parent._get_cell_position(self) position = property(_get_position, _set_position) @property def local(self): return self.parent.is_local(self) def inject(self, current_source): """Inject current from a current source object into the cell.""" current_source.inject_into([self]) def get_initial_value(self, variable): """Get the initial value of a state variable of the cell.""" return self.parent._get_cell_initial_value(self, variable) def set_initial_value(self, variable, value): """Set the initial value of a state variable of the cell.""" self.parent._set_cell_initial_value(self, variable, value) def as_view(self): """Return a PopulationView containing just this cell.""" index = self.parent.id_to_index(self) return self.parent[index:index+1] # ============================================================================= # Functions for simulation set-up and control # ============================================================================= def setup(timestep=DEFAULT_TIMESTEP, min_delay=DEFAULT_MIN_DELAY, max_delay=DEFAULT_MAX_DELAY, **extra_params): """ Initialises/reinitialises the simulator. Any existing network structure is destroyed. extra_params contains any keyword arguments that are required by a given simulator but not by others. """ invalid_extra_params = ('mindelay', 'maxdelay', 'dt') for param in invalid_extra_params: if param in extra_params: raise Exception("%s is not a valid argument for setup()" % param) if min_delay > max_delay: raise Exception("min_delay has to be less than or equal to max_delay.") if min_delay < timestep: raise Exception("min_delay (%g) must be greater than timestep (%g)" % (min_delay, timestep)) def end(compatible_output=True): """Do any necessary cleaning up before exiting.""" raise NotImplementedError def run(simtime): """Run the simulation for simtime ms.""" raise NotImplementedError def reset(): """ Reset the time to zero, neuron membrane potentials and synaptic weights to their initial values, and delete any recorded data. The network structure is not changed, nor is the specification of which neurons to record from. """ simulator.reset() def initialize(cells, variable, value): assert isinstance(cells, (BasePopulation, Assembly)), type(cells) cells.initialize(variable, value) def get_current_time(): """Return the current time in the simulation.""" return simulator.state.t def get_time_step(): """Return the integration time step.""" return simulator.state.dt def get_min_delay(): """Return the minimum allowed synaptic delay.""" return simulator.state.min_delay def get_max_delay(): """Return the maximum allowed synaptic delay.""" return simulator.state.max_delay def num_processes(): """Return the number of MPI processes.""" return simulator.state.num_processes def rank(): """Return the MPI rank of the current node.""" return simulator.state.mpi_rank # ============================================================================= # Low-level API for creating, connecting and recording from individual neurons # ============================================================================= def build_create(population_class): def create(cellclass, cellparams=None, n=1): """ Create n cells all of the same type. If n > 1, return a list of cell ids/references. If n==1, return just the single id. """ return population_class(n, cellclass, cellparams) # return the Population or Population.all_cells? return create def build_connect(projection_class, connector_class): def connect(source, target, weight=0.0, delay=None, synapse_type=None, p=1, rng=None): """ Connect a source of spikes to a synaptic target. source and target can both be individual cells or lists of cells, in which case all possible connections are made with probability p, using either the random number generator supplied, or the default rng otherwise. Weights should be in nA or µS. """ if isinstance(source, IDMixin): source = source.as_view() if isinstance(target, IDMixin): target = target.as_view() connector = connector_class(p_connect=p, weights=weight, delays=delay) return projection_class(source, target, connector, target=synapse_type, rng=rng) return connect def set(cells, param, val=None): """ Set one or more parameters of an individual cell or list of cells. param can be a dict, in which case val should not be supplied, or a string giving the parameter name, in which case val is the parameter value. """ assert isinstance(cells, (BasePopulation, Assembly)) cells.set(param, val) def build_record(variable, simulator): def record(source, filename): """ Record spikes to a file. source can be an individual cell, a Population, PopulationView or Assembly. """ # would actually like to be able to record to an array and choose later # whether to write to a file. if not isinstance(source, (BasePopulation, Assembly)): source = source.parent source._record(variable, to_file=filename) # recorder_list is used by end() if isinstance(source, BasePopulation): simulator.recorder_list.append(source.recorders[variable]) # this is a bit hackish - better to add to Population.__del__? if isinstance(source, Assembly): for population in source.populations: simulator.recorder_list.append(population.recorders[variable]) if variable == 'v': record.__name__ = "record_v" record.__doc__ = """ Record membrane potential to a file. source can be an individual cell, a Population, PopulationView or Assembly.""" elif variable == 'gsyn': record.__name__ = "record_gsyn" record.__doc__ = """ Record synaptic conductances to a file. source can be an individual cell, a Population, PopulationView or Assembly.""" return record # ============================================================================= # High-level API for creating, connecting and recording from populations of # neurons. # ============================================================================= class BasePopulation(object): record_filter = None def __getitem__(self, index): """ Return either a single cell (ID object) from the Population, if index is an integer, or a subset of the cells (PopulationView object), if index is a slice or array. Note that __getitem__ is called when using [] access, e.g. p = Population(...) p[2] is equivalent to p.__getitem__(2). p[3:6] is equivalent to p.__getitem__(slice(3, 6)) """ if isinstance(index, int): return self.all_cells[index] elif isinstance(index, (slice, list, numpy.ndarray)): return PopulationView(self, index) elif isinstance(index, tuple): return PopulationView(self, list(index)) else: raise TypeError("indices must be integers, slices, lists, arrays or tuples, not %s" % type(index).__name__) def __len__(self): """Return the total number of cells in the population (all nodes).""" return self.size @property def local_size(self): return len(self.local_cells) # would self._mask_local.sum() be faster? def __iter__(self): """Iterator over cell ids on the local node.""" return iter(self.local_cells) @property def conductance_based(self): return self.celltype.conductance_based def is_local(self, id): """ Determine whether the cell with the given ID exists on the local MPI node. """ assert id.parent is self index = self.id_to_index(id) return self._mask_local[index] def all(self): """Iterator over cell ids on all nodes.""" return iter(self.all_cells) def __add__(self, other): """ A Population/PopulationView can be added to another Population, PopulationView or Assembly, returning an Assembly. """ assert isinstance(other, BasePopulation) return Assembly(self, other) def _get_cell_position(self, id): index = self.id_to_index(id) return self.positions[:, index] def _set_cell_position(self, id, pos): index = self.id_to_index(id) self.positions[:, index] = pos def _get_cell_initial_value(self, id, variable): assert isinstance(self.initial_values[variable], core.LazyArray) index = self.id_to_local_index(id) return self.initial_values[variable][index] def _set_cell_initial_value(self, id, variable, value): assert isinstance(self.initial_values[variable], core.LazyArray) index = self.id_to_local_index(id) self.initial_values[variable][index] = value def nearest(self, position): """Return the neuron closest to the specified position.""" # doesn't always work correctly if a position is equidistant between # two neurons, i.e. 0.5 should be rounded up, but it isn't always. # also doesn't take account of periodic boundary conditions pos = numpy.array([position] * self.positions.shape[1]).transpose() dist_arr = (self.positions - pos)**2 distances = dist_arr.sum(axis=0) nearest = distances.argmin() return self[nearest] def sample(self, n, rng=None): """ Randomly sample n cells from the Population, and return a PopulationView object. """ assert isinstance(n, int) if not rng: rng = random.NumpyRNG() indices = rng.permutation(numpy.arange(len(self)))[0:n] logger.debug("The %d cells recorded have indices %s" % (n, indices)) logger.debug("%s.sample(%s)", self.label, n) return PopulationView(self, indices) def get(self, parameter_name, gather=False): """ Get the values of a parameter for every local cell in the population. """ # if all the cells have the same value for this parameter, should # we return just the number, rather than an array? if hasattr(self, "_get_array"): values = self._get_array(parameter_name).tolist() else: values = [getattr(cell, parameter_name) for cell in self] # list or array? if gather == True and num_processes() > 1: all_values = { rank(): values } all_indices = { rank(): self.local_cells.tolist()} all_values = recording.gather_dict(all_values) all_indices = recording.gather_dict(all_indices) if rank() == 0: values = reduce(operator.add, all_values.values()) indices = reduce(operator.add, all_indices.values()) idx = numpy.argsort(indices) values = numpy.array(values)[idx] return values def set(self, param, val=None): """ Set one or more parameters for every cell in the population. param can be a dict, in which case val should not be supplied, or a string giving the parameter name, in which case val is the parameter value. val can be a numeric value, or list of such (e.g. for setting spike times). e.g. p.set("tau_m",20.0). p.set({'tau_m':20,'v_rest':-65}) """ #""" # -- Proposed change to arguments -- #Set one or more parameters for every cell in the population. # #Each value may be a single number or a list/array of numbers of the same #size as the population. If the parameter itself takes lists/arrays as #values (e.g. spike times), then the value provided may be either a #single lists/1D array, a list of lists/1D arrays, or a 2D array. # #e.g. p.set(tau_m=20.0). # p.set(tau_m=20, v_rest=[-65.0, -65.3, ... , -67.2]) #""" if isinstance(param, str): param_dict = {param: val} elif isinstance(param, dict): param_dict = param else: raise errors.InvalidParameterValueError param_dict = self.celltype.checkParameters(param_dict, with_defaults=False) logger.debug("%s.set(%s)", self.label, param_dict) if hasattr(self, "_set_array"): self._set_array(**param_dict) else: for cell in self: cell.set_parameters(**param_dict) def tset(self, parametername, value_array): """ 'Topographic' set. Set the value of parametername to the values in value_array, which must have the same dimensions as the Population. """ #""" # -- Proposed change to arguments -- #'Topographic' set. Each value in parameters should be a function that #accepts arguments x,y,z and returns a single value. #""" if parametername not in self.celltype.get_parameter_names(): raise errors.NonExistentParameterError(parametername, self.celltype, self.celltype.get_parameter_names()) if (self.size,) == value_array.shape: # the values are numbers or non-array objects local_values = value_array[self._mask_local] assert local_values.size == self.local_cells.size, "%d != %d" % (local_values.size, self.local_cells.size) elif len(value_array.shape) == 2: # the values are themselves 1D arrays if value_array.shape[0] != self.size: raise errors.InvalidDimensionsError("Population: %d, value_array first dimension: %s" % (self.size, value_array.shape[0])) local_values = value_array[self._mask_local] # not sure this works else: raise errors.InvalidDimensionsError("Population: %d, value_array: %s" % (self.size, str(value_array.shape))) assert local_values.shape[0] == self.local_cells.size, "%d != %d" % (local_values.size, self.local_cells.size) try: logger.debug("%s.tset('%s', array(shape=%s, min=%s, max=%s))", self.label, parametername, value_array.shape, value_array.min(), value_array.max()) except TypeError: # min() and max() won't work for non-numeric values logger.debug("%s.tset('%s', non_numeric_array(shape=%s))", self.label, parametername, value_array.shape) # Set the values for each cell if hasattr(self, "_set_array"): self._set_array(**{parametername: local_values}) else: for cell, val in zip(self, local_values): setattr(cell, parametername, val) def rset(self, parametername, rand_distr): """ 'Random' set. Set the value of parametername to a value taken from rand_distr, which should be a RandomDistribution object. """ # Note that we generate enough random numbers for all cells on all nodes # but use only those relevant to this node. This ensures that the # sequence of random numbers does not depend on the number of nodes, # provided that the same rng with the same seed is used on each node. logger.debug("%s.rset('%s', %s)", self.label, parametername, rand_distr) if isinstance(rand_distr.rng, random.NativeRNG): self._native_rset(parametername, rand_distr) else: rarr = rand_distr.next(n=self.all_cells.size, mask_local=False) rarr = numpy.array(rarr) # isn't rarr already an array? assert rarr.size == self.size, "%s != %s" % (rarr.size, self.size) self.tset(parametername, rarr) def _call(self, methodname, arguments): """ Call the method methodname(arguments) for every cell in the population. e.g. p.call("set_background","0.1") if the cell class has a method set_background(). """ raise NotImplementedError() def _tcall(self, methodname, objarr): """ `Topographic' call. Call the method methodname() for every cell in the population. The argument to the method depends on the coordinates of the cell. objarr is an array with the same dimensions as the Population. e.g. p.tcall("memb_init", vinitArray) calls p.cell[i][j].memb_init(vInitArray[i][j]) for all i,j. """ raise NotImplementedError() def randomInit(self, rand_distr): """ Set initial membrane potentials for all the cells in the population to random values. """ warn("The randomInit() method is deprecated, and will be removed in a future release. Use initialize('v', rand_distr) instead.") self.initialize('v', rand_distr) def initialize(self, variable, value): """ Set initial values of state variables, e.g. the membrane potential. `value` may either be a numeric value (all neurons set to the same value) or a `RandomDistribution` object (each neuron gets a different value) """ logger.debug("In Population '%s', initialising %s to %s" % (self.label, variable, value)) if isinstance(value, random.RandomDistribution): initial_value = value.next(n=self.all_cells.size, mask_local=self._mask_local) if self.local_size > 1: assert len(initial_value) == self.local_size, "%d != %d" % (len(initial_value), self.local_size) else: initial_value = value self.initial_values[variable] = core.LazyArray(initial_value, shape=(self.local_size,)) if hasattr(self, "_set_initial_value_array"): self._set_initial_value_array(variable, initial_value) else: if isinstance(value, random.RandomDistribution): for cell, val in zip(self, initial_value): cell.set_initial_value(variable, val) else: for cell in self: # only on local node cell.set_initial_value(variable, initial_value) def can_record(self, variable): """Determine whether `variable` can be recorded from this population.""" return (variable in self.celltype.recordable) def _add_recorder(self, variable): """Create a new Recorder for the supplied variable.""" assert variable not in self.recorders if hasattr(self, "parent"): population = self.grandparent else: population = self logger.debug("Adding recorder for %s to %s" % (variable, self.label)) population.recorders[variable] = population.recorder_class(variable, population=population) def _record(self, variable, to_file=True): """ Private method called by record() and record_v(). """ if variable is None: # reset the list of things to record # note that if _record(None) is called on a view of a population # recording will be reset for the entire population, not just the view for recorder in self.recorders.values(): recorder.reset() self.recorders = {} else: if not self.can_record(variable): raise errors.RecordingError(variable, self.celltype) logger.debug("%s.record('%s')", self.label, variable) if variable not in self.recorders: self._add_recorder(variable) if self.record_filter is not None: self.recorders[variable].record(self.record_filter) else: self.recorders[variable].record(self.all_cells) if isinstance(to_file, basestring): self.recorders[variable].file = to_file def record(self, to_file=True): """ Record spikes from all cells in the Population. """ self._record('spikes', to_file) def record_v(self, to_file=True): """ Record the membrane potential for all cells in the Population. """ self._record('v', to_file) def record_gsyn(self, to_file=True): """ Record synaptic conductances for all cells in the Population. """ self._record('gsyn', to_file) def printSpikes(self, file, gather=True, compatible_output=True): """ Write spike times to file. file should be either a filename or a PyNN File object. If compatible_output is True, the format is "spiketime cell_id", where cell_id is the index of the cell counting along rows and down columns (and the extension of that for 3-D). This allows easy plotting of a `raster' plot of spiketimes, with one line for each cell. The timestep, first id, last id, and number of data points per cell are written in a header, indicated by a '#' at the beginning of the line. If compatible_output is False, the raw format produced by the simulator is used. This may be faster, since it avoids any post-processing of the spike files. For parallel simulators, if gather is True, all data will be gathered to the master node and a single output file created there. Otherwise, a file will be written on each node, containing only the cells simulated on that node. """ self.recorders['spikes'].write(file, gather, compatible_output, self.record_filter) def getSpikes(self, gather=True, compatible_output=True): """ Return a 2-column numpy array containing cell ids and spike times for recorded cells. Useful for small populations, for example for single neuron Monte-Carlo. """ return self.recorders['spikes'].get(gather, compatible_output, self.record_filter) # if we haven't called record(), this will give a KeyError. A more # informative error message would be nice. def print_v(self, file, gather=True, compatible_output=True): """ Write membrane potential traces to file. file should be either a filename or a PyNN File object. If compatible_output is True, the format is "v cell_id", where cell_id is the index of the cell counting along rows and down columns (and the extension of that for 3-D). The timestep, first id, last id, and number of data points per cell are written in a header, indicated by a '#' at the beginning of the line. If compatible_output is False, the raw format produced by the simulator is used. This may be faster, since it avoids any post-processing of the voltage files. For parallel simulators, if gather is True, all data will be gathered to the master node and a single output file created there. Otherwise, a file will be written on each node, containing only the cells simulated on that node. """ self.recorders['v'].write(file, gather, compatible_output, self.record_filter) def get_v(self, gather=True, compatible_output=True): """ Return a 2-column numpy array containing cell ids and Vm for recorded cells. """ return self.recorders['v'].get(gather, compatible_output, self.record_filter) def print_gsyn(self, file, gather=True, compatible_output=True): """ Write synaptic conductance traces to file. file should be either a filename or a PyNN File object. If compatible_output is True, the format is "t g cell_id", where cell_id is the index of the cell counting along rows and down columns (and the extension of that for 3-D). The timestep, first id, last id, and number of data points per cell are written in a header, indicated by a '#' at the beginning of the line. If compatible_output is False, the raw format produced by the simulator is used. This may be faster, since it avoids any post-processing of the voltage files. """ self.recorders['gsyn'].write(file, gather, compatible_output, self.record_filter) def get_gsyn(self, gather=True, compatible_output=True): """ Return a 3-column numpy array containing cell ids and synaptic conductances for recorded cells. """ return self.recorders['gsyn'].get(gather, compatible_output, self.record_filter) def get_spike_counts(self, gather=True): """ Returns the number of spikes for each neuron. """ return self.recorders['spikes'].count(gather, self.record_filter) def meanSpikeCount(self, gather=True): """ Returns the mean number of spikes per neuron. """ spike_counts = self.recorders['spikes'].count(gather, self.record_filter) total_spikes = sum(spike_counts.values()) if rank() == 0 or not gather: # should maybe use allgather, and get the numbers on all nodes if len(spike_counts) > 0: return float(total_spikes)/len(spike_counts) else: return 0 else: return numpy.nan def inject(self, current_source): """ Connect a current source to all cells in the Population. """ if not self.celltype.injectable: raise TypeError("Can't inject current into a spike source.") current_source.inject_into(self) def save_positions(self, file): """ Save positions to file. The output format is id x y z """ # first column should probably be indices, not ids. This would make it # simulator independent. if isinstance(file, basestring): file = files.StandardTextFile(file, mode='w') cells = self.all_cells result = numpy.empty((len(cells), 4)) result[:,0] = cells result[:,1:4] = self.positions.T if rank() == 0: file.write(result, {'population' : self.label}) file.close() class Population(BasePopulation): """ A group of neurons all of the same type. """ nPop = 0 def __init__(self, size, cellclass, cellparams=None, structure=None, label=None): """ Create a population of neurons all of the same type. size - number of cells in the Population. For backwards-compatibility, n may also be a tuple giving the dimensions of a grid, e.g. n=(10,10) is equivalent to n=100 with structure=Grid2D() cellclass should either be a standardized cell class (a class inheriting from common.standardmodels.StandardCellType) or a string giving the name of the simulator-specific model that makes up the population. cellparams should be a dict which is passed to the neuron model constructor structure should be a Structure instance. label is an optional name for the population. """ if not isinstance(size, int): # also allow a single integer, for a 1D population assert isinstance(size, tuple), "`size` must be an integer or a tuple of ints. You have supplied a %s" % type(size) # check the things inside are ints for e in size: assert isinstance(e, int), "`size` must be an integer or a tuple of ints. Element '%s' is not an int" % str(e) assert structure is None, "If you specify `size` as a tuple you may not specify structure." if len(size) == 1: structure = space.Line() elif len(size) == 2: nx, ny = size structure = space.Grid2D(nx/float(ny)) elif len(size) == 3: nx, ny, nz = size structure = space.Grid3D(nx/float(ny), nx/float(nz)) else: raise Exception("A maximum of 3 dimensions is allowed. What do you think this is, string theory?") size = reduce(operator.mul, size) self.size = size self.label = label or 'population%d' % Population.nPop self.celltype = cellclass(cellparams) self._structure = structure or space.Line() self._positions = None self._is_sorted = True # Build the arrays of cell ids # Cells on the local node are represented as ID objects, other cells by integers # All are stored in a single numpy array for easy lookup by address # The local cells are also stored in a list, for easy iteration self._create_cells(cellclass, cellparams, size) self.initial_values = {} for variable, value in self.celltype.default_initial_values.items(): self.initialize(variable, value) self.recorders = {} Population.nPop += 1 @property def local_cells(self): return self.all_cells[self._mask_local] @property def cell(self): warn("The `Population.cell` attribute is not an official part of the \ API, and its use is deprecated. It will be removed in a future \ release. All uses of `cell` may be replaced by `all_cells`") return self.all_cells def id_to_index(self, id): """ Given the ID(s) of cell(s) in the Population, return its (their) index (order in the Population). >>> assert p.id_to_index(p[5]) == 5 >>> assert p.id_to_index(p.index([1,2,3])) == [1,2,3] """ if not numpy.iterable(id): if not self.first_id <= id <= self.last_id: raise ValueError("id should be in the range [%d,%d], actually %d" % (self.first_id, self.last_id, id)) return int(id - self.first_id) # this assumes ids are consecutive else: if isinstance(id, PopulationView): id = id.all_cells id = numpy.array(id) if (self.first_id > id.min()) or (self.last_id < id.max()): raise ValueError("ids should be in the range [%d,%d], actually [%d, %d]" % (self.first_id, self.last_id, id.min(), id.max())) return (id - self.first_id).astype(int) # this assumes ids are consecutive def id_to_local_index(self, id): """ Given the ID(s) of cell(s) in the Population, return its (their) index (order in the Population), counting only cells on the local MPI node. """ if num_processes() > 1: return self.local_cells.tolist().index(id) # probably very slow #return numpy.nonzero(self.local_cells == id)[0][0] # possibly faster? # another idea - get global index, use idx-sum(mask_local[:idx])? else: return self.id_to_index(id) def _get_structure(self): return self._structure def _set_structure(self, structure): assert isinstance(structure, space.BaseStructure) if structure != self._structure: self._positions = None # setting a new structure invalidates previously calculated positions self._structure = structure structure = property(fget=_get_structure, fset=_set_structure) # arguably structure should be read-only, i.e. it is not possible to change it after Population creation @property def position_generator(self): def gen(i): return self.positions[:,i] return gen def _get_positions(self): """ Try to return self._positions. If it does not exist, create it and then return it. """ if self._positions is None: self._positions = self.structure.generate_positions(self.size) assert self._positions.shape == (3, self.size) return self._positions def _set_positions(self, pos_array): assert isinstance(pos_array, numpy.ndarray) assert pos_array.shape == (3, self.size), "%s != %s" % (pos_array.shape, (3, self.size)) self._positions = pos_array.copy() # take a copy in case pos_array is changed later self._structure = None # explicitly setting positions destroys any previous structure positions = property(_get_positions, _set_positions, """A 3xN array (where N is the number of neurons in the Population) giving the x,y,z coordinates of all the neurons (soma, in the case of non-point models).""") def describe(self, template='population_default.txt', engine='default'): """ Returns a human-readable description of the population. The output may be customized by specifying a different template togther with an associated template engine (see ``pyNN.descriptions``). If template is None, then a dictionary containing the template context will be returned. """ context = { "label": self.label, "celltype": self.celltype.describe(template=None), "structure": None, "size": self.size, "size_local": len(self.local_cells), "first_id": self.first_id, "last_id": self.last_id, } if len(self.local_cells) > 0: first_id = self.local_cells[0] context.update({ "local_first_id": first_id, "cell_parameters": first_id.get_parameters(), }) if self.structure: context["structure"] = self.structure.describe(template=None) return descriptions.render(engine, template, context) class PopulationView(BasePopulation): """ A view of a subset of neurons within a Population. In most ways, Populations and PopulationViews have the same behaviour, i.e. they can be recorded, connected with Projections, etc. It should be noted that any changes to neurons in a PopulationView will be reflected in the parent Population and vice versa. It is possible to have views of views. """ def __init__(self, parent, selector, label=None): """ Create a view of a subset of neurons within a parent Population or PopulationView. selector - a slice or numpy mask array. The mask array should either be a boolean array of the same size as the parent, or an integer array containing cell indices, i.e. if p.size == 5, PopulationView(p, array([False, False, True, False, True])) PopulationView(p, array([2,4])) PopulationView(p, slice(2,5,2)) will all create the same view. """ self.parent = parent self.mask = selector # later we can have fancier selectors, for now we just have numpy masks self.label = label or "view of %s with mask %s" % (parent.label, self.mask) # maybe just redefine __getattr__ instead of the following... self.celltype = self.parent.celltype # If the mask is a slice, IDs will be consecutives without duplication. # If not, then we need to remove duplicated IDs if not isinstance(self.mask, slice): if isinstance(self.mask, list): self.mask = numpy.array(self.mask) if self.mask.dtype is numpy.dtype('bool'): if len(self.mask) != len(self.parent): raise Exception("Boolean masks should have the size of Parent Population") self.mask = numpy.arange(len(self.parent))[self.mask] if len(numpy.unique(self.mask)) != len(self.mask): logging.warning("PopulationView can contain only once each ID, duplicated IDs are remove") self.mask = numpy.unique(self.mask) self.all_cells = self.parent.all_cells[self.mask] # do we need to ensure this is ordered? idx = numpy.argsort(self.all_cells) self._is_sorted = numpy.all(idx == numpy.arange(len(self.all_cells))) self.size = len(self.all_cells) self._mask_local = self.parent._mask_local[self.mask] self.local_cells = self.all_cells[self._mask_local] self.first_id = numpy.min(self.all_cells) # only works if we assume all_cells is sorted, otherwise could use min() self.last_id = numpy.max(self.all_cells) self.recorders = self.parent.recorders self.record_filter= self.all_cells @property def initial_values(self): # this is going to be complex - if we keep initial_values as a dict, # need to return a dict-like object that takes account of self.mask raise NotImplementedError @property def structure(self): return self.parent.structure # should we allow setting structure for a PopulationView? Maybe if the # parent has some kind of CompositeStructure? @property def positions(self): return self.parent.positions.T[self.mask].T # make positions N,3 instead of 3,N to avoid all this transposing? def id_to_index(self, id): """ Given the ID(s) of cell(s) in the PopulationView, return its/their index/indices (order in the PopulationView). >>> assert id_to_index(p.index(5)) == 5 >>> assert id_to_index(p.index([1,2,3])) == [1,2,3] """ if not numpy.iterable(id): if self._is_sorted: if id not in self.all_cells: raise IndexError("ID %s not present in the View" %id) return numpy.searchsorted(self.all_cells, id) else: result = numpy.where(self.all_cells == id)[0] if len(result) == 0: raise IndexError("ID %s not present in the View" %id) else: return result else: if self._is_sorted: return numpy.searchsorted(self.all_cells, id) else: result = numpy.array([]) for item in id: data = numpy.where(self.all_cells == item)[0] if len(data) == 0: raise IndexError("ID %s not present in the View" %item) elif len(data) > 1: raise Exception("ID %s is duplicated in the View" %item) else: result = numpy.append(result, data) return result @property def grandparent(self): """ Returns the parent Population at the root of the tree (since the immediate parent may itself be a PopulationView). The name "grandparent" is of course a little misleading, as it could be just the parent, or the great, great, great, ..., grandparent. """ if hasattr(self.parent, "parent"): return self.parent.grandparent else: return self.parent def describe(self, template='populationview_default.txt', engine='default'): """ Returns a human-readable description of the population view. The output may be customized by specifying a different template togther with an associated template engine (see ``pyNN.descriptions``). If template is None, then a dictionary containing the template context will be returned. """ context = {"label": self.label, "parent": self.parent.label, "mask": self.mask, "size": self.size} return descriptions.render(engine, template, context) # ============================================================================= class Assembly(object): """ A group of neurons, may be heterogeneous, in contrast to a Population where all the neurons are of the same type. """ count = 0 def __init__(self, *populations, **kwargs): """ Create an Assembly of Populations and/or PopulationViews. kwargs may contain a keyword argument 'label'. """ if kwargs: assert kwargs.keys() == ['label'] self.populations = [] for p in populations: self._insert(p) self.label = kwargs.get('label', 'assembly%d' % Assembly.count) assert isinstance(self.label, basestring), "label must be a string or unicode" Assembly.count += 1 def _insert(self, element): if not isinstance(element, BasePopulation): raise TypeError("argument is a %s, not a Population." % type(element).__name__) if isinstance(element, PopulationView): if not element.parent in self.populations: double = False for p in self.populations: data = numpy.concatenate((p.all_cells, element.all_cells)) if len(
numpy.unique(data)
numpy.unique