code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import numpy as np import dp_penalty params = dp_penalty.PenaltyParams( tau = 0.2, prop_sigma = np.repeat(0.008 * 5, 2), r_clip_bound = 3.5, ocu = True, grw = True )
[ "numpy.repeat" ]
[((105, 128), 'numpy.repeat', 'np.repeat', (['(0.008 * 5)', '(2)'], {}), '(0.008 * 5, 2)\n', (114, 128), True, 'import numpy as np\n')]
import numpy as np from cleanlab.pruning import get_noise_indices class ProbaReason: """ Assign doubt based on low proba-confidence values from a scikit-learn model. Arguments: model: scikit-learn classifier max_proba: maximum probability threshold for doubt assignment Usage: ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import ProbaReason X, y = load_iris(return_X_y=True) model = LogisticRegression(max_iter=1_000) model.fit(X, y) doubt = DoubtEnsemble(reason = ProbaReason(model, max_proba=0.55)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model, max_proba=0.55): self.model = model self.max_proba = max_proba def __call__(self, X, y=None): result = self.model.predict_proba(X).max(axis=1) <= self.max_proba return result.astype(np.float16) class RandomReason: """ Assign doubt based on a random value. Arguments: probability: probability of assigning a doubt random_seed: seed for random number generator Usage: ```python from sklearn.datasets import load_iris from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import RandomReason X, y = load_iris(return_X_y=True) doubt = DoubtEnsemble(reason = RandomReason(probability=0.05, random_seed=42)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, probability=0.01, random_seed=42): self.probability = probability self.random_seed = random_seed def __call__(self, X, y=None): np.random.seed(self.random_seed) rvals = np.random.random(size=len(X)) return np.where(rvals < self.probability, rvals, 0) class WrongPredictionReason: """ Assign doubt when the model prediction doesn't match the label. Arguments: model: scikit-learn classifier Usage: ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import WrongPredictionReason X, y = load_iris(return_X_y=True) model = LogisticRegression(max_iter=1_000) model.fit(X, y) doubt = DoubtEnsemble(reason = WrongPredictionReason(model=model)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model): self.model = model def __call__(self, X, y): return (self.model.predict(X) != y).astype(np.float16) class LongConfidenceReason: """ Assign doubt when a wrong class gains too much confidence. Arguments: model: scikit-learn classifier threshold: confidence threshold for doubt assignment Usage: ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import LongConfidenceReason X, y = load_iris(return_X_y=True) model = LogisticRegression(max_iter=1_000) model.fit(X, y) doubt = DoubtEnsemble(reason = LongConfidenceReason(model=model)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model, threshold=0.2): self.model = model self.threshold = threshold def _max_bad_class_confidence(self, X, y): probas = self.model.predict_proba(X) values = [] for i, proba in enumerate(probas): proba_dict = { self.model.classes_[j]: v for j, v in enumerate(proba) if j != y[i] } values.append(max(proba_dict.values())) return np.array(values) def __call__(self, X, y): confidences = self._max_bad_class_confidence(X, y) return np.where(confidences > self.threshold, confidences, 0) class MarginConfidenceReason: """ Assign doubt when a the difference between the top two most confident classes is too large. Throws an error when there are only two classes. Arguments: model: scikit-learn classifier threshold: confidence threshold for doubt assignment Usage: ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import MarginConfidenceReason X, y = load_iris(return_X_y=True) model = LogisticRegression(max_iter=1_000) model.fit(X, y) doubt = DoubtEnsemble(reason = MarginConfidenceReason(model=model)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model, threshold=0.2): self.model = model self.threshold = threshold def _calc_margin(self, probas): sorted = np.sort(probas, axis=1) return sorted[:, -1] - sorted[:, -2] def __call__(self, X, y): probas = self.model.predict_proba(X) margin = self._calc_margin(probas) return np.where(margin > self.threshold, margin, 0) class ShortConfidenceReason: """ Assign doubt when the correct class gains too little confidence. Arguments: model: scikit-learn classifier threshold: confidence threshold for doubt assignment Usage: ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import ShortConfidenceReason X, y = load_iris(return_X_y=True) model = LogisticRegression(max_iter=1_000) model.fit(X, y) doubt = DoubtEnsemble(reason = ShortConfidenceReason(model=model)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model, threshold=0.2): self.model = model self.threshold = threshold def _correct_class_confidence(self, X, y): """ Gives the predicted confidence (or proba) associated with the correct label `y` from a given model. """ probas = self.model.predict_proba(X) values = [] for i, proba in enumerate(probas): proba_dict = {self.model.classes_[j]: v for j, v in enumerate(proba)} values.append(proba_dict[y[i]]) return np.array(values) def __call__(self, X, y): confidences = self._correct_class_confidence(X, y) return np.where(confidences < self.threshold, 1 - confidences, 0) class DisagreeReason: """ Assign doubt when two scikit-learn models disagree on a prediction. Arguments: model1: scikit-learn classifier model2: a different scikit-learn classifier Usage: ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import DisagreeReason X, y = load_iris(return_X_y=True) model1 = LogisticRegression(max_iter=1_000) model2 = KNeighborsClassifier() model1.fit(X, y) model2.fit(X, y) doubt = DoubtEnsemble(reason = DisagreeReason(model1, model2)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model1, model2): self.model1 = model1 self.model2 = model2 def __call__(self, X, y): result = self.model1.predict(X) != self.model2.predict(X) return result.astype(np.float16) class OutlierReason: """ Assign doubt when a scikit-learn outlier model detects an outlier. Arguments: model: scikit-learn outlier model Usage: ```python from sklearn.datasets import load_iris from sklearn.ensemble import IsolationForest from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import OutlierReason X, y = load_iris(return_X_y=True) model = IsolationForest() model.fit(X) doubt = DoubtEnsemble(reason = OutlierReason(model)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model): self.model = model def __call__(self, X, y): return (self.model.predict(X) == -1).astype(np.float16) class AbsoluteDifferenceReason: """ Assign doubt when the absolute difference between label and regression is too large. Arguments: model: scikit-learn outlier model threshold: cutoff for doubt assignment Usage: ```python from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import AbsoluteDifferenceReason X, y = load_diabetes(return_X_y=True) model = LinearRegression() model.fit(X, y) doubt = DoubtEnsemble(reason = AbsoluteDifferenceReason(model, threshold=100)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model, threshold): self.model = model self.threshold = threshold def __call__(self, X, y): difference = np.abs(self.model.predict(X) - y) return (difference >= self.threshold).astype(np.float16) class RelativeDifferenceReason: """ Assign doubt when the relative difference between label and regression is too large. Arguments: model: scikit-learn outlier model threshold: cutoff for doubt assignment Usage: ```python from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import RelativeDifferenceReason X, y = load_diabetes(return_X_y=True) model = LinearRegression() model.fit(X, y) doubt = DoubtEnsemble(reason = RelativeDifferenceReason(model, threshold=0.5)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model, threshold): self.model = model self.threshold = threshold def __call__(self, X, y): difference = np.abs(self.model.predict(X) - y) / y return (difference >= self.threshold).astype(np.float16) class CleanlabReason: """ Assign doubt when using the cleanlab heuristic. Arguments: model: scikit-learn outlier model sorted_index_method: method used by cleanlab for sorting indices min_doubt: the minimum doubt output value used for sorting by the ensemble Usage: ```python from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from doubtlab.ensemble import DoubtEnsemble from doubtlab.reason import CleanlabReason X, y = load_iris(return_X_y=True) model = LogisticRegression() model.fit(X, y) doubt = DoubtEnsemble(reason = CleanlabReason(model)) indices = doubt.get_indices(X, y) ``` """ def __init__(self, model, sorted_index_method="normalized_margin", min_doubt=0.5): self.model = model self.sorted_index_method = sorted_index_method self.min_doubt = min_doubt def __call__(self, X, y): probas = self.model.predict_proba(X) ordered_label_errors = get_noise_indices(y, probas, self.sorted_index_method) result = np.zeros_like(y) conf_arr = np.linspace(1, self.min_doubt, result.shape[0]) for idx, conf in zip(ordered_label_errors, conf_arr): result[idx] = conf return result
[ "numpy.where", "numpy.sort", "numpy.array", "numpy.linspace", "numpy.random.seed", "cleanlab.pruning.get_noise_indices", "numpy.zeros_like" ]
[((1734, 1766), 'numpy.random.seed', 'np.random.seed', (['self.random_seed'], {}), '(self.random_seed)\n', (1748, 1766), True, 'import numpy as np\n'), ((1828, 1872), 'numpy.where', 'np.where', (['(rvals < self.probability)', 'rvals', '(0)'], {}), '(rvals < self.probability, rvals, 0)\n', (1836, 1872), True, 'import numpy as np\n'), ((3784, 3800), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (3792, 3800), True, 'import numpy as np\n'), ((3906, 3960), 'numpy.where', 'np.where', (['(confidences > self.threshold)', 'confidences', '(0)'], {}), '(confidences > self.threshold, confidences, 0)\n', (3914, 3960), True, 'import numpy as np\n'), ((4894, 4917), 'numpy.sort', 'np.sort', (['probas'], {'axis': '(1)'}), '(probas, axis=1)\n', (4901, 4917), True, 'import numpy as np\n'), ((5097, 5141), 'numpy.where', 'np.where', (['(margin > self.threshold)', 'margin', '(0)'], {}), '(margin > self.threshold, margin, 0)\n', (5105, 5141), True, 'import numpy as np\n'), ((6374, 6390), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (6382, 6390), True, 'import numpy as np\n'), ((6496, 6554), 'numpy.where', 'np.where', (['(confidences < self.threshold)', '(1 - confidences)', '(0)'], {}), '(confidences < self.threshold, 1 - confidences, 0)\n', (6504, 6554), True, 'import numpy as np\n'), ((11311, 11365), 'cleanlab.pruning.get_noise_indices', 'get_noise_indices', (['y', 'probas', 'self.sorted_index_method'], {}), '(y, probas, self.sorted_index_method)\n', (11328, 11365), False, 'from cleanlab.pruning import get_noise_indices\n'), ((11383, 11399), 'numpy.zeros_like', 'np.zeros_like', (['y'], {}), '(y)\n', (11396, 11399), True, 'import numpy as np\n'), ((11419, 11466), 'numpy.linspace', 'np.linspace', (['(1)', 'self.min_doubt', 'result.shape[0]'], {}), '(1, self.min_doubt, result.shape[0])\n', (11430, 11466), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf class spectral_conv_layer(object): def __init__(self, input_x, in_channel, out_channel, kernel_size, random_seed, data_format='NHWC', index=0): """ A convolutional layer with spectrally-parameterized weights. :param input_x: Should be a 4D array like: (batch_num, channel_num, img_len, img_len) :param in_channel: The number of channels :param out_channel: number of filters required :param kernel_size: kernel size :param random_seed: random seed :param data_format: image should be with CHANNEL LAST: NHWC :param index: The layer index used for naming """ assert len(input_x.shape) == 4 if data_format == 'NHWC': assert input_x.shape[1] == input_x.shape[2] assert input_x.shape[3] == in_channel elif data_format == 'NCHW': assert input_x.shape[1] == in_channel assert input_x.shape[2] == input_x.shape[3] def _glorot_sample(kernel_size, n_in, n_out): limit = np.sqrt(6 / (n_in + n_out)) return np.random.uniform( low=-limit, high=limit, size=(n_in, n_out, kernel_size, kernel_size) ) with tf.variable_scope('spec_conv_layer_{0}'.format(index)): with tf.name_scope('spec_conv_kernel'): samp = _glorot_sample(kernel_size, in_channel, out_channel) """ tf.fft2d: Computes the 2-dimensional discrete Fourier transform over the inner-most 2 dimensions of input. """ # shape channel_in, channel_out, kernel_size, kernel_size spectral_weight_init = tf.fft2d(samp) real_init = tf.get_variable( name='real_{0}'.format(index), initializer=tf.real(spectral_weight_init)) imag_init = tf.get_variable( name='imag_{0}'.format(index), initializer=tf.imag(spectral_weight_init)) spectral_weight = tf.complex( real_init, imag_init, name='spectral_weight_{0}'.format(index) ) self.spectral_weight = spectral_weight with tf.variable_scope('conv_bias'): b_shape = [out_channel] bias = tf.get_variable( name='conv_bias_{0}'.format(index), shape=b_shape, initializer=tf.glorot_uniform_initializer( seed=random_seed )) self.bias = bias """ ifft2d: Computes the inverse 2-dimensional discrete Fourier transform over the inner-most 2 dimensions of input. """ complex_spatial_weight = tf.ifft2d(spectral_weight) spatial_weight = tf.real( complex_spatial_weight, name='spatial_weight_{0}'.format(index) ) # we need kernel tensor of shape [filter_height, filter_width, # in_channels, out_channels] self.weight = tf.transpose(spatial_weight, [2, 3, 0, 1]) conv_out = tf.nn.conv2d(input_x, spatial_weight, strides=[1, 1, 1, 1], padding="SAME", data_format=data_format) self.cell_out = tf.nn.relu( tf.nn.bias_add(conv_out, bias, data_format=data_format)) def output(self): return self.cell_out
[ "tensorflow.nn.conv2d", "tensorflow.glorot_uniform_initializer", "numpy.sqrt", "tensorflow.variable_scope", "tensorflow.transpose", "tensorflow.imag", "tensorflow.ifft2d", "tensorflow.real", "tensorflow.name_scope", "tensorflow.fft2d", "numpy.random.uniform", "tensorflow.nn.bias_add" ]
[((1129, 1156), 'numpy.sqrt', 'np.sqrt', (['(6 / (n_in + n_out))'], {}), '(6 / (n_in + n_out))\n', (1136, 1156), True, 'import numpy as np\n'), ((1176, 1267), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-limit)', 'high': 'limit', 'size': '(n_in, n_out, kernel_size, kernel_size)'}), '(low=-limit, high=limit, size=(n_in, n_out, kernel_size,\n kernel_size))\n', (1193, 1267), True, 'import numpy as np\n'), ((2984, 3010), 'tensorflow.ifft2d', 'tf.ifft2d', (['spectral_weight'], {}), '(spectral_weight)\n', (2993, 3010), True, 'import tensorflow as tf\n'), ((3302, 3344), 'tensorflow.transpose', 'tf.transpose', (['spatial_weight', '[2, 3, 0, 1]'], {}), '(spatial_weight, [2, 3, 0, 1])\n', (3314, 3344), True, 'import tensorflow as tf\n'), ((3369, 3473), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['input_x', 'spatial_weight'], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""', 'data_format': 'data_format'}), "(input_x, spatial_weight, strides=[1, 1, 1, 1], padding='SAME',\n data_format=data_format)\n", (3381, 3473), True, 'import tensorflow as tf\n'), ((1413, 1446), 'tensorflow.name_scope', 'tf.name_scope', (['"""spec_conv_kernel"""'], {}), "('spec_conv_kernel')\n", (1426, 1446), True, 'import tensorflow as tf\n'), ((1817, 1831), 'tensorflow.fft2d', 'tf.fft2d', (['samp'], {}), '(samp)\n', (1825, 1831), True, 'import tensorflow as tf\n'), ((2413, 2443), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv_bias"""'], {}), "('conv_bias')\n", (2430, 2443), True, 'import tensorflow as tf\n'), ((3634, 3689), 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['conv_out', 'bias'], {'data_format': 'data_format'}), '(conv_out, bias, data_format=data_format)\n', (3648, 3689), True, 'import tensorflow as tf\n'), ((1961, 1990), 'tensorflow.real', 'tf.real', (['spectral_weight_init'], {}), '(spectral_weight_init)\n', (1968, 1990), True, 'import tensorflow as tf\n'), ((2121, 2150), 'tensorflow.imag', 'tf.imag', (['spectral_weight_init'], {}), '(spectral_weight_init)\n', (2128, 2150), True, 'import tensorflow as tf\n'), ((2648, 2695), 'tensorflow.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {'seed': 'random_seed'}), '(seed=random_seed)\n', (2677, 2695), True, 'import tensorflow as tf\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' GOAL Save Arctic ocean temperature - Pacific side (thetao) PROGRAMMER <NAME> LAST UPDATE 29/04/2020 ''' # Standard libraries import numpy as np from netCDF4 import Dataset # Options exp = 'D013' save_var = True start_year = 2130 end_year = 2179 # Time parameters start_folder = int(start_year - 2130 + 281) nyears = int(end_year-start_year+1) nmy = int(12) # number of months in a year # Working directory dir_input = '/nobackup/rossby24/proj/rossby/joint_exp/oseaice/run/'+str(exp)+'/output/nemo/' dir_mask = '/nobackup/rossby24/proj/rossby/joint_exp/oseaice/run/D000/' dir_output = '/nobackup/rossby24/proj/rossby/joint_exp/oseaice/post-proc/'+str(exp)+'/' # Load dimensions filename = dir_input + '281/' + str(exp)+'_1m_21300101_21301231_grid_T.nc' fh = Dataset(filename, mode='r') test = fh.variables['thetao'][:] notused,nz,ny,nx = test.shape lat = fh.variables['nav_lat'][:] lon = fh.variables['nav_lon'][:] fh.close() # Load ocean mask for Atlantic filename = dir_mask + 'subbasins.nc' fh = Dataset(filename, mode='r') atlmsk = fh.variables['atlmsk'][:] fh.close() # Compute 2D mean Arctic ocean temperature (mean over all longitudes) averaged over 50 years thetao_2D_pac = np.zeros((nyears,nz,ny)) for year in np.arange(nyears): print(start_year+year) filename = dir_input + str(start_folder+year) + '/' + str(exp)+'_1m_'+str(start_year+year)+'0101_'+str(start_year+year)+'1231_grid_T.nc' fh = Dataset(filename, mode='r') thetao = fh.variables['thetao'][:] thetao[thetao>60.] = np.nan thetao = np.nanmean(thetao,axis=0) # annual mean fh.close() thetao_pacarc = thetao # Pacific Arctic for z in np.arange(nz): thetao_pacarc[z,:,:][atlmsk == 1] = np.nan thetao_2D_pac[year,:,:] = np.nanmean(thetao_pacarc,axis=2) # average over all longitudes of the Arctic thetao_2D_pac_mean = np.nanmean(thetao_2D_pac,axis=0) # time mean over whole period print(np.nanmean(thetao_2D_pac_mean)) # Save thetao if save_var == True: filename = dir_output + 'thetao_arc_' + str(exp) + '.npy' np.save(filename,thetao_2D_pac_mean)
[ "numpy.arange", "netCDF4.Dataset", "numpy.nanmean", "numpy.zeros", "numpy.save" ]
[((825, 852), 'netCDF4.Dataset', 'Dataset', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (832, 852), False, 'from netCDF4 import Dataset\n'), ((1067, 1094), 'netCDF4.Dataset', 'Dataset', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (1074, 1094), False, 'from netCDF4 import Dataset\n'), ((1251, 1277), 'numpy.zeros', 'np.zeros', (['(nyears, nz, ny)'], {}), '((nyears, nz, ny))\n', (1259, 1277), True, 'import numpy as np\n'), ((1288, 1305), 'numpy.arange', 'np.arange', (['nyears'], {}), '(nyears)\n', (1297, 1305), True, 'import numpy as np\n'), ((1902, 1935), 'numpy.nanmean', 'np.nanmean', (['thetao_2D_pac'], {'axis': '(0)'}), '(thetao_2D_pac, axis=0)\n', (1912, 1935), True, 'import numpy as np\n'), ((1484, 1511), 'netCDF4.Dataset', 'Dataset', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (1491, 1511), False, 'from netCDF4 import Dataset\n'), ((1596, 1622), 'numpy.nanmean', 'np.nanmean', (['thetao'], {'axis': '(0)'}), '(thetao, axis=0)\n', (1606, 1622), True, 'import numpy as np\n'), ((1708, 1721), 'numpy.arange', 'np.arange', (['nz'], {}), '(nz)\n', (1717, 1721), True, 'import numpy as np\n'), ((1804, 1837), 'numpy.nanmean', 'np.nanmean', (['thetao_pacarc'], {'axis': '(2)'}), '(thetao_pacarc, axis=2)\n', (1814, 1837), True, 'import numpy as np\n'), ((1971, 2001), 'numpy.nanmean', 'np.nanmean', (['thetao_2D_pac_mean'], {}), '(thetao_2D_pac_mean)\n', (1981, 2001), True, 'import numpy as np\n'), ((2105, 2142), 'numpy.save', 'np.save', (['filename', 'thetao_2D_pac_mean'], {}), '(filename, thetao_2D_pac_mean)\n', (2112, 2142), True, 'import numpy as np\n')]
from scipy.integrate import odeint import matplotlib.pyplot as plt import numpy as np def radial(y, r, m, k, a, l, E): """ Radial ODE with an exponential well φ = dψ/dr dφ/dr = -2φ/r - (2m(E-ke^ar) - (l(l+1)/r^2))ψ :param y: (np.ndarray) First order ODEs --------------------- all in atomic units ------------------ :param r: (float) Distance :param m: (float) Mass :param k: (float) Exponential well constant :param a: (float) Exponential well exponent :param E: (float) Energy :return: (np.ndarray): Step of the ODE """ psi, phi = y dydt = [phi, # φ = dψ/dr -2.0*phi/r - (2*m*(E - k*(np.exp(a*r) - 1.0)) - (l*(l+1)/r**2))*psi ] return dydt def radial_h_potential(y, r, m, l, E): psi, phi = y return [phi, -2.0*phi/r - (2*m*(E + 1/r) - (l*(l+1)/r**2))*psi] def h_atom(n=2): """H atom solved numerically Works for 1s, 2s, 2p """ m = 1 eigval = -1/(2 * n**2) rs = np.linspace(0.01, 10.0, num=2000) sol = odeint(radial_h_potential, y0=np.array([0.015, 1E-6]), t=rs, args=(m, 1, eigval)) plt.plot(rs, sol[:, 0]) # 2nd column is dφ/dr plt.plot(rs, np.exp(-rs), label='1s') plt.plot(rs, (2 - rs)*np.exp(-rs/2)/2, label='2s') plt.plot(rs, rs*np.exp(-rs/2), label='2p') plt.legend() plt.savefig('tmp.pdf') exit() return def old_params(): # n l respectively, indexed from 0 with """ a = 3.0 # au=1 k = 0.000054696784 # au # temp = 298.15 # K m = 48 * 1822.888486 # au """ range_00 = [0.000207029879, 0.000207030293] range_10 = [0.000477839, 0.000477870] range_20 = [0.000781328436, 0.000781359045] range_30 = [0.001115069891, 0.001115120906] range_01 = [0.000337342910, 0.000337342922] range_11 = [0.000623858533, 0.000623858545] range_21 = [0.000942477455, 0.000942477467] return if __name__ == '__main__': # h_atom() k = 0.00220873 a = 2.832 * 0.529177 m = 48 * 1822.888486 # rs = np.linspace(1.7, 0.003, num=2000) rs = np.linspace(0.001, 1.7, num=2000) range_default = (0.001537, 0.001538) # E_1 = 0.000206980766 Ha from forwards # E_1 = 0.000207029908 Ha from backwards for E in np.linspace(*range_default, num=100): sol = odeint(radial, y0=np.array([1, 0.0]), t=rs, args=(m, k, a, 1, E)) print(f'E = {E:.12f} ψ(r=0) =', sol[-1][0]) # plt.plot(rs[:-20], sol[:-20, 0]/sol[-20, 0]) plt.plot(rs, sol[:, 0]) plt.ylim(-1.1, 1.1) # plt.xlim(0, 0.1) plt.savefig('tmp.pdf')
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "numpy.exp", "numpy.array", "numpy.linspace", "matplotlib.pyplot.ylim", "matplotlib.pyplot.legend" ]
[((1002, 1035), 'numpy.linspace', 'np.linspace', (['(0.01)', '(10.0)'], {'num': '(2000)'}), '(0.01, 10.0, num=2000)\n', (1013, 1035), True, 'import numpy as np\n'), ((1184, 1207), 'matplotlib.pyplot.plot', 'plt.plot', (['rs', 'sol[:, 0]'], {}), '(rs, sol[:, 0])\n', (1192, 1207), True, 'import matplotlib.pyplot as plt\n'), ((1395, 1407), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1405, 1407), True, 'import matplotlib.pyplot as plt\n'), ((1412, 1434), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""tmp.pdf"""'], {}), "('tmp.pdf')\n", (1423, 1434), True, 'import matplotlib.pyplot as plt\n'), ((2203, 2236), 'numpy.linspace', 'np.linspace', (['(0.001)', '(1.7)'], {'num': '(2000)'}), '(0.001, 1.7, num=2000)\n', (2214, 2236), True, 'import numpy as np\n'), ((2386, 2422), 'numpy.linspace', 'np.linspace', (['*range_default'], {'num': '(100)'}), '(*range_default, num=100)\n', (2397, 2422), True, 'import numpy as np\n'), ((2715, 2734), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-1.1)', '(1.1)'], {}), '(-1.1, 1.1)\n', (2723, 2734), True, 'import matplotlib.pyplot as plt\n'), ((2762, 2784), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""tmp.pdf"""'], {}), "('tmp.pdf')\n", (2773, 2784), True, 'import matplotlib.pyplot as plt\n'), ((1263, 1274), 'numpy.exp', 'np.exp', (['(-rs)'], {}), '(-rs)\n', (1269, 1274), True, 'import numpy as np\n'), ((2686, 2709), 'matplotlib.pyplot.plot', 'plt.plot', (['rs', 'sol[:, 0]'], {}), '(rs, sol[:, 0])\n', (2694, 2709), True, 'import matplotlib.pyplot as plt\n'), ((1093, 1117), 'numpy.array', 'np.array', (['[0.015, 1e-06]'], {}), '([0.015, 1e-06])\n', (1101, 1117), True, 'import numpy as np\n'), ((1363, 1378), 'numpy.exp', 'np.exp', (['(-rs / 2)'], {}), '(-rs / 2)\n', (1369, 1378), True, 'import numpy as np\n'), ((1314, 1329), 'numpy.exp', 'np.exp', (['(-rs / 2)'], {}), '(-rs / 2)\n', (1320, 1329), True, 'import numpy as np\n'), ((2477, 2495), 'numpy.array', 'np.array', (['[1, 0.0]'], {}), '([1, 0.0])\n', (2485, 2495), True, 'import numpy as np\n'), ((669, 682), 'numpy.exp', 'np.exp', (['(a * r)'], {}), '(a * r)\n', (675, 682), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT import sys, pathlib import time sys.path.append(str(pathlib.Path(__file__).resolve().parents[1])) from m1n1.setup import * from m1n1.loadobjs import * import argparse import numpy as np argparser = argparse.ArgumentParser() argparser.add_argument("-d", "--domain", type=str, help='Look for MMIO range associated with a particular' ' power domain') argparser.add_argument("-p", "--print", action='store_true', help='Print power domain list') args = argparser.parse_args() if args.print: for dev in u.adt["/arm-io/pmgr"].devices: print(dev.name) sys.exit(0) granule = 0x4000 lp = LinkedProgram(u) lp.load_inline_c(f''' #define GRANULE {granule} ''' + ''' #include "exception.h" #include "utils.h" #include "soc.h" bool is_t6000(void) { return chip_id == T6000; } void sweep(u64 from, u64 to, u64 target) { u32 *mask = (u32 *) target; exc_guard = GUARD_MARK | GUARD_SILENT; int bitp = 0; for (u64 p = from; p < to; p += GRANULE) { sysop("dsb sy"); sysop("isb"); bool hit = read32(p) != 0xabad1dea; if (hit) *mask |= (1 << bitp); else *mask &= ~(1 << bitp); if (++bitp >= 32) { bitp = 0; mask++; } } sysop("dsb sy"); sysop("isb"); } ''') def do_sweep(maskrange): masklen = (maskrange.stop - maskrange.start) // granule // 32 * 4 + 4 mask_base = u.heap.malloc(masklen) lp.sweep(maskrange.start, maskrange.stop, mask_base) mask = iface.readmem(mask_base, masklen) u.heap.free(mask_base) return np.frombuffer(mask, dtype=np.uint8) def describe_mask(mask, maskrange): ''' Describe mask in terms of hot from-to ranges ''' ranges = [] prev_hit = False mask = np.concatenate((mask, [0])) for i in range(len(mask)*8): hit = mask[i//8] & (1<<(i%8)) != 0 if hit and not prev_hit: start = maskrange.start + i*granule if not hit and prev_hit: end = maskrange.start + i*granule ranges.append((start, end)) prev_hit = hit return ranges if lp.is_t6000(): maskrange = range(0x2_9000_0000, 0x4_0000_0000) else: maskrange = range(0x2_2000_0000, 0x3_0000_0000) pd_did_enable = set() pmgr = u.adt["/arm-io/pmgr"] ps_dev_by_id = {dev.id: dev for dev in pmgr.devices} ps_deps = dict() ps_addrs = dict() for dev in pmgr.devices: ps = pmgr.ps_regs[dev.psreg] addr = pmgr.get_reg(ps.reg)[0] + ps.offset + dev.psidx * 8 ps_addrs[dev.name] = addr ps_deps[dev.name] = [ ps_dev_by_id[idx].name for idx in dev.parents if idx in ps_dev_by_id ] def ps_pstate(name): return p.read32(ps_addrs[name]) & 0x0f def ps_enabled(name): return p.read32(ps_addrs[name]) & 0x0f == 0x0f def ps_set_pstate(name, desired): p.mask32(ps_addrs[name], 0xf, desired) time.sleep(0.001) actual = p.read32(ps_addrs[name]) if actual & 0xf0 != desired << 4: print("WARNING: %s stuck at pstate 0x%x (desired 0x%x)" \ % (name, actual >> 4, desired)) def ps_enable(name): print("Enabling %s..." % name) ps_set_pstate(name, 0xf) def ps_disable(name): p.mask32(ps_addrs[name], 0xf, 0x0) if args.domain: ps_disable(args.domain) to_enable = set([args.domain]) for dev in reversed(pmgr.devices): if dev.name not in to_enable \ or ps_enabled(dev.name): continue for dep in ps_deps[dev.name]: to_enable.add(dep) save = dict() for dev in pmgr.devices: if dev.name in to_enable: save[dev.name] = ps_pstate(dev.name) if dev.name != args.domain: ps_enable(dev.name) premask = do_sweep(maskrange) ps_enable(args.domain) postmask = do_sweep(maskrange) print("Reverting...") for dev in reversed(pmgr.devices): if dev.name in to_enable and dev.name: ps_set_pstate(dev.name, save[dev.name]) hitmask = premask ^ postmask if np.count_nonzero(hitmask & premask): print("Que? Some ranges disappeared?") else: # no --domain flag, do a plain sweep hitmask = do_sweep(maskrange) al = u.adt.build_addr_lookup() for start, stop in describe_mask(hitmask, maskrange): # bit ugly but it makes addrlookup do all the heavy lifting for us al.add(range(start, stop), "hit") print("Hits:") for zone, value in al.items(): if ((zone.start - 1) // granule + 1) * granule >= zone.stop: continue if not any([v[0] == "hit" for v in value]): continue labels = set([v[0] for v in value if v[0] != "hit"]) print(f"\t{zone.start:9x} - {zone.stop:9x} | {' '.join(labels)}")
[ "argparse.ArgumentParser", "pathlib.Path", "time.sleep", "numpy.count_nonzero", "numpy.concatenate", "sys.exit", "numpy.frombuffer" ]
[((254, 279), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (277, 279), False, 'import argparse\n'), ((634, 645), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (642, 645), False, 'import sys, pathlib\n'), ((1558, 1593), 'numpy.frombuffer', 'np.frombuffer', (['mask'], {'dtype': 'np.uint8'}), '(mask, dtype=np.uint8)\n', (1571, 1593), True, 'import numpy as np\n'), ((1726, 1753), 'numpy.concatenate', 'np.concatenate', (['(mask, [0])'], {}), '((mask, [0]))\n', (1740, 1753), True, 'import numpy as np\n'), ((2728, 2745), 'time.sleep', 'time.sleep', (['(0.001)'], {}), '(0.001)\n', (2738, 2745), False, 'import time\n'), ((3723, 3758), 'numpy.count_nonzero', 'np.count_nonzero', (['(hitmask & premask)'], {}), '(hitmask & premask)\n', (3739, 3758), True, 'import numpy as np\n'), ((106, 128), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (118, 128), False, 'import sys, pathlib\n')]
""" Demo code To run our method, you need a bounding box around the person. The person needs to be centered inside the bounding box and the bounding box should be relatively tight. You can either supply the bounding box directly or provide an [OpenPose](https://github.com/CMU-Perceptual-Computing-Lab/openpose) detection file. In the latter case we infer the bounding box from the detections. In summary, we provide 3 different ways to use our demo code and models: 1. Provide only an input image (using ```--img```), in which case it is assumed that it is already cropped with the person centered in the image. 2. Provide an input image as before, together with the OpenPose detection .json (using ```--openpose```). Our code will use the detections to compute the bounding box and crop the image. 3. Provide an image and a bounding box (using ```--bbox```). The expected format for the json file can be seen in ```examples/im1010_bbox.json```. Example with OpenPose detection .json ``` python3 demo.py --checkpoint=data/model_checkpoint.pt --img=examples/im1010.png --openpose=examples/im1010_openpose.json ``` Example with predefined Bounding Box ``` python3 demo.py --checkpoint=data/model_checkpoint.pt --img=examples/im1010.png --bbox=examples/im1010_bbox.json ``` Example with cropped and centered image ``` python3 demo.py --checkpoint=data/model_checkpoint.pt --img=examples/im1010.png ``` Running the previous command will save the results in ```examples/im1010_{shape,shape_side}.png```. The file ```im1010_shape.png``` shows the overlayed reconstruction of human shape. We also render a side view, saved in ```im1010_shape_side.png```. """ import torch from torchvision.transforms import Normalize import numpy as np import cv2 import argparse import json import os from tqdm import tqdm from models import hmr, SMPL from utils.imutils import crop from utils.renderer import Renderer import config import constants from utils.geometry import batch_rodrigues, perspective_projection, estimate_translation parser = argparse.ArgumentParser() parser.add_argument('--checkpoint', required=True, help='Path to pretrained checkpoint') # parser.add_argument('--img', type=str, required=True, help='Path to input image') parser.add_argument('--bbox', type=str, default=None, help='Path to .json file containing bounding box coordinates') parser.add_argument('--openpose', type=str, default=None, help='Path to .json containing openpose detections') parser.add_argument('--outfile', type=str, default=None, help='Filename of output images. If not set use input filename.') def draw_full_skeleton(input_image, joints, all_joints=None, draw_edges=True, vis=None, all_vis=None, radius=None): """ joints is 3 x 19. but if not will transpose it. 0: Right ankle 1: Right knee 2: Right hip 3: Left hip 4: Left knee 5: Left ankle 6: Right wrist 7: Right elbow 8: Right shoulder 9: Left shoulder 10: Left elbow 11: Left wrist 12: Neck 13: Head top 14: nose 15: left_eye 16: right_eye 17: left_ear 18: right_ear """ joints = joints + 112 print(joints) if radius is None: radius = max(4, (np.mean(input_image.shape[:2]) * 0.01).astype(int)) colors = { 'pink': np.array([197, 27, 125]), # L lower leg 'light_pink': np.array([233, 163, 201]), # L upper leg 'light_green': np.array([161, 215, 106]), # L lower arm 'green': np.array([77, 146, 33]), # L upper arm 'red': np.array([215, 48, 39]), # head 'light_red': np.array([252, 146, 114]), # head 'light_orange': np.array([252, 141, 89]), # chest 'purple': np.array([118, 42, 131]), # R lower leg 'light_purple': np.array([175, 141, 195]), # R upper 'light_blue': np.array([145, 191, 219]), # R lower arm 'blue': np.array([0, 0, 255]), # R upper arm 'gray': np.array([130, 130, 130]), # 'white': np.array([255, 255, 255]) # } image = input_image.copy() input_is_float = False if np.issubdtype(image.dtype, np.float): input_is_float = True max_val = image.max() if max_val <= 2.: # should be 1 but sometimes it's slightly above 1 image = (image * 255).astype(np.uint8) else: image = (image).astype(np.uint8) if joints.shape[0] != 2: joints = joints.T joints = np.round(joints).astype(int) if all_joints is not None: if all_joints.shape[0] != 2: all_joints = all_joints.T all_joints = np.round(all_joints).astype(int) jcolors = [ 'light_pink', 'light_pink', 'light_pink', 'pink', 'pink', 'pink', 'light_blue', 'light_blue', 'light_blue', 'blue', 'blue', 'blue', 'purple', 'purple', 'red', 'green', 'green', 'white', 'white' ] all_jcolors = [ 'light_pink', 'light_pink', 'light_pink', 'light_pink', 'pink', 'pink', 'pink', 'pink', 'light_blue', 'light_blue', 'light_blue', 'light_blue', 'blue', 'blue', 'blue', 'blue', 'purple', 'purple', 'purple', 'purple', 'red', 'green', 'green', 'green', 'white', 'white' ,'white', 'white' ] # draw all ketpoints if joints is not None: print(joints.shape[1]) for i in range(joints.shape[1]): point = joints[:, i] # If invisible skip # if all_vis is not None and all_vis[i] == 0: # continue if draw_edges: # print(radius) # print(point) # cv2.circle(image, (100, 60), 3, (0, 0, 213), -1) cv2.circle(image, (point[0], point[1]), 2, colors['blue'].tolist(), 2) # cv2.circle(image, (point[0], point[1]), radius-1, colors['blue'].tolist(), # -1) # cv2.circle(image, (point[0], point[1]), radius - 2, # colors['blue'].tolist(), -1) else: # cv2.circle(image, (point[0], point[1]), 5, colors['white'], 1) cv2.circle(image, (point[0], point[1]), radius - 1, colors['blue'].tolist(), 1) # cv2.circle(image, (point[0], point[1]), 5, colors['gray'], -1) return image def bbox_from_openpose(openpose_file, rescale=1.2, detection_thresh=0.2): """Get center and scale for bounding box from openpose detections.""" with open(openpose_file, 'r') as f: keypoints = json.load(f)['people'][0]['pose_keypoints_2d'] keypoints = np.reshape(np.array(keypoints), (-1,3)) valid = keypoints[:,-1] > detection_thresh valid_keypoints = keypoints[valid][:,:-1] center = valid_keypoints.mean(axis=0) bbox_size = (valid_keypoints.max(axis=0) - valid_keypoints.min(axis=0)).max() # adjust bounding box tightness scale = bbox_size / 200.0 scale *= rescale return center, scale def bbox_from_json(bbox_file): """Get center and scale of bounding box from bounding box annotations. The expected format is [top_left(x), top_left(y), width, height]. """ with open(bbox_file, 'r') as f: bbox = np.array(json.load(f)['bbox']).astype(np.float32) ul_corner = bbox[:2] center = ul_corner + 0.5 * bbox[2:] width = max(bbox[2], bbox[3]) scale = width / 200.0 # make sure the bounding box is rectangular return center, scale def process_image(img_file, bbox_file, openpose_file, input_res=224): """Read image, do preprocessing and possibly crop it according to the bounding box. If there are bounding box annotations, use them to crop the image. If no bounding box is specified but openpose detections are available, use them to get the bounding box. """ normalize_img = Normalize(mean=constants.IMG_NORM_MEAN, std=constants.IMG_NORM_STD) img = cv2.imread(img_file)[:,:,::-1].copy() # PyTorch does not support negative stride at the moment print(img.shape) if bbox_file is None and openpose_file is None: # Assume that the person is centerered in the image height = img.shape[0] width = img.shape[1] center = np.array([width // 2, height // 2]) scale = max(height, width) / 200 else: if bbox_file is not None: center, scale = bbox_from_json(bbox_file) elif openpose_file is not None: center, scale = bbox_from_openpose(openpose_file) img = crop(img, center, scale, (input_res, input_res)) img = img.astype(np.float32) / 255. img = torch.from_numpy(img).permute(2,0,1) norm_img = normalize_img(img.clone())[None] return img, norm_img if __name__ == '__main__': args = parser.parse_args() device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') # Load pretrained model model = hmr(config.SMPL_MEAN_PARAMS).to(device) checkpoint = torch.load(args.checkpoint) model.load_state_dict(checkpoint['model'], strict=False) # Load SMPL model smpl = SMPL(config.SMPL_MODEL_DIR, batch_size=1, create_transl=False).to(device) model.eval() # Setup renderer for visualization renderer = Renderer(focal_length=constants.FOCAL_LENGTH, img_res=constants.IMG_RES, faces=smpl.faces) # imgs_path = '/project/hpn_yyy/datasets/preprocess/min_imgs_up-3d' imgs_path = 'crop_vis' imgpath_list = [] for dirpath, dirnames, filenames in os.walk(imgs_path): for f in filenames : if os.path.splitext(f)[1] == '.png' or os.path.splitext(f)[1] == '.jpg': imgpath_list.append(os.path.join(dirpath, f)) for imgpath in tqdm(imgpath_list): # Preprocess input image and generate predictions img, norm_img = process_image(imgpath, args.bbox, args.openpose, input_res=constants.IMG_RES) with torch.no_grad(): pred_rotmat, pred_betas, pred_camera = model(norm_img.to(device)) pred_output = smpl(betas=pred_betas, body_pose=pred_rotmat[:,1:], global_orient=pred_rotmat[:,0].unsqueeze(1), pose2rot=False) pred_vertices = pred_output.vertices pred_joints = pred_output.joints # Calculate camera parameters for rendering camera_translation = torch.stack([pred_camera[:,1], pred_camera[:,2], 2*constants.FOCAL_LENGTH/(constants.IMG_RES * pred_camera[:,0] +1e-9)],dim=-1) # Convert Weak Perspective Camera [s, tx, ty] to camera translation [tx, ty, tz] in 3D given the bounding box size batch_size = 1 camera_center = torch.zeros(batch_size, 2, device=device) pred_keypoints_2d = perspective_projection(pred_joints, rotation=torch.eye(3, device=device).unsqueeze(0).expand(batch_size, -1, -1), translation=camera_translation, focal_length=constants.FOCAL_LENGTH, camera_center=camera_center) # print(pred_keypoints_2d.shape) kp_img = draw_full_skeleton(img.permute(1,2,0).cpu().numpy(), pred_keypoints_2d[0][25:,:].cpu().numpy()) # cv2.imwrite('test_kp.jpg', kp_img[:,:,::-1]) camera_translation = camera_translation[0].cpu().numpy() pred_vertices = pred_vertices[0].cpu().numpy() img = img.permute(1,2,0).cpu().numpy() # Render parametric shape img_shape = renderer(pred_vertices, camera_translation, img) # Render side views aroundy = cv2.Rodrigues(np.array([0, np.radians(90.), 0]))[0] center = pred_vertices.mean(axis=0) rot_vertices = np.dot((pred_vertices - center), aroundy) + center # Render non-parametric shape img_shape_side = renderer(rot_vertices, camera_translation, np.ones_like(img)) outfile = imgpath.split('.')[0] if args.outfile is None else args.outfile # Save reconstructions cv2.imwrite(outfile + '_kp.jpg', kp_img[:,:,::-1]) cv2.imwrite(outfile + '_shape.png', 255 * img_shape[:,:,::-1]) cv2.imwrite(outfile + '_shape_side.png', 255 * img_shape_side[:,:,::-1])
[ "utils.renderer.Renderer", "numpy.radians", "torch.from_numpy", "numpy.array", "torch.cuda.is_available", "models.hmr", "os.walk", "numpy.mean", "argparse.ArgumentParser", "torch.eye", "numpy.issubdtype", "numpy.dot", "models.SMPL", "numpy.round", "utils.imutils.crop", "os.path.splitex...
[((2034, 2059), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2057, 2059), False, 'import argparse\n'), ((4117, 4153), 'numpy.issubdtype', 'np.issubdtype', (['image.dtype', 'np.float'], {}), '(image.dtype, np.float)\n', (4130, 4153), True, 'import numpy as np\n'), ((7841, 7908), 'torchvision.transforms.Normalize', 'Normalize', ([], {'mean': 'constants.IMG_NORM_MEAN', 'std': 'constants.IMG_NORM_STD'}), '(mean=constants.IMG_NORM_MEAN, std=constants.IMG_NORM_STD)\n', (7850, 7908), False, 'from torchvision.transforms import Normalize\n'), ((8510, 8558), 'utils.imutils.crop', 'crop', (['img', 'center', 'scale', '(input_res, input_res)'], {}), '(img, center, scale, (input_res, input_res))\n', (8514, 8558), False, 'from utils.imutils import crop\n'), ((8973, 9000), 'torch.load', 'torch.load', (['args.checkpoint'], {}), '(args.checkpoint)\n', (8983, 9000), False, 'import torch\n'), ((9274, 9368), 'utils.renderer.Renderer', 'Renderer', ([], {'focal_length': 'constants.FOCAL_LENGTH', 'img_res': 'constants.IMG_RES', 'faces': 'smpl.faces'}), '(focal_length=constants.FOCAL_LENGTH, img_res=constants.IMG_RES,\n faces=smpl.faces)\n', (9282, 9368), False, 'from utils.renderer import Renderer\n'), ((9535, 9553), 'os.walk', 'os.walk', (['imgs_path'], {}), '(imgs_path)\n', (9542, 9553), False, 'import os\n'), ((9758, 9776), 'tqdm.tqdm', 'tqdm', (['imgpath_list'], {}), '(imgpath_list)\n', (9762, 9776), False, 'from tqdm import tqdm\n'), ((3289, 3313), 'numpy.array', 'np.array', (['[197, 27, 125]'], {}), '([197, 27, 125])\n', (3297, 3313), True, 'import numpy as np\n'), ((3352, 3377), 'numpy.array', 'np.array', (['[233, 163, 201]'], {}), '([233, 163, 201])\n', (3360, 3377), True, 'import numpy as np\n'), ((3417, 3442), 'numpy.array', 'np.array', (['[161, 215, 106]'], {}), '([161, 215, 106])\n', (3425, 3442), True, 'import numpy as np\n'), ((3476, 3499), 'numpy.array', 'np.array', (['[77, 146, 33]'], {}), '([77, 146, 33])\n', (3484, 3499), True, 'import numpy as np\n'), ((3531, 3554), 'numpy.array', 'np.array', (['[215, 48, 39]'], {}), '([215, 48, 39])\n', (3539, 3554), True, 'import numpy as np\n'), ((3585, 3610), 'numpy.array', 'np.array', (['[252, 146, 114]'], {}), '([252, 146, 114])\n', (3593, 3610), True, 'import numpy as np\n'), ((3644, 3668), 'numpy.array', 'np.array', (['[252, 141, 89]'], {}), '([252, 141, 89])\n', (3652, 3668), True, 'import numpy as np\n'), ((3697, 3721), 'numpy.array', 'np.array', (['[118, 42, 131]'], {}), '([118, 42, 131])\n', (3705, 3721), True, 'import numpy as np\n'), ((3762, 3787), 'numpy.array', 'np.array', (['[175, 141, 195]'], {}), '([175, 141, 195])\n', (3770, 3787), True, 'import numpy as np\n'), ((3822, 3847), 'numpy.array', 'np.array', (['[145, 191, 219]'], {}), '([145, 191, 219])\n', (3830, 3847), True, 'import numpy as np\n'), ((3880, 3901), 'numpy.array', 'np.array', (['[0, 0, 255]'], {}), '([0, 0, 255])\n', (3888, 3901), True, 'import numpy as np\n'), ((3934, 3959), 'numpy.array', 'np.array', (['[130, 130, 130]'], {}), '([130, 130, 130])\n', (3942, 3959), True, 'import numpy as np\n'), ((3981, 4006), 'numpy.array', 'np.array', (['[255, 255, 255]'], {}), '([255, 255, 255])\n', (3989, 4006), True, 'import numpy as np\n'), ((6632, 6651), 'numpy.array', 'np.array', (['keypoints'], {}), '(keypoints)\n', (6640, 6651), True, 'import numpy as np\n'), ((8223, 8258), 'numpy.array', 'np.array', (['[width // 2, height // 2]'], {}), '([width // 2, height // 2])\n', (8231, 8258), True, 'import numpy as np\n'), ((8820, 8845), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (8843, 8845), False, 'import torch\n'), ((8796, 8816), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (8808, 8816), False, 'import torch\n'), ((8851, 8870), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (8863, 8870), False, 'import torch\n'), ((10373, 10515), 'torch.stack', 'torch.stack', (['[pred_camera[:, 1], pred_camera[:, 2], 2 * constants.FOCAL_LENGTH / (\n constants.IMG_RES * pred_camera[:, 0] + 1e-09)]'], {'dim': '(-1)'}), '([pred_camera[:, 1], pred_camera[:, 2], 2 * constants.\n FOCAL_LENGTH / (constants.IMG_RES * pred_camera[:, 0] + 1e-09)], dim=-1)\n', (10384, 10515), False, 'import torch\n'), ((10671, 10712), 'torch.zeros', 'torch.zeros', (['batch_size', '(2)'], {'device': 'device'}), '(batch_size, 2, device=device)\n', (10682, 10712), False, 'import torch\n'), ((12134, 12186), 'cv2.imwrite', 'cv2.imwrite', (["(outfile + '_kp.jpg')", 'kp_img[:, :, ::-1]'], {}), "(outfile + '_kp.jpg', kp_img[:, :, ::-1])\n", (12145, 12186), False, 'import cv2\n'), ((12193, 12257), 'cv2.imwrite', 'cv2.imwrite', (["(outfile + '_shape.png')", '(255 * img_shape[:, :, ::-1])'], {}), "(outfile + '_shape.png', 255 * img_shape[:, :, ::-1])\n", (12204, 12257), False, 'import cv2\n'), ((12264, 12338), 'cv2.imwrite', 'cv2.imwrite', (["(outfile + '_shape_side.png')", '(255 * img_shape_side[:, :, ::-1])'], {}), "(outfile + '_shape_side.png', 255 * img_shape_side[:, :, ::-1])\n", (12275, 12338), False, 'import cv2\n'), ((4471, 4487), 'numpy.round', 'np.round', (['joints'], {}), '(joints)\n', (4479, 4487), True, 'import numpy as np\n'), ((8609, 8630), 'torch.from_numpy', 'torch.from_numpy', (['img'], {}), '(img)\n', (8625, 8630), False, 'import torch\n'), ((8916, 8944), 'models.hmr', 'hmr', (['config.SMPL_MEAN_PARAMS'], {}), '(config.SMPL_MEAN_PARAMS)\n', (8919, 8944), False, 'from models import hmr, SMPL\n'), ((9096, 9158), 'models.SMPL', 'SMPL', (['config.SMPL_MODEL_DIR'], {'batch_size': '(1)', 'create_transl': '(False)'}), '(config.SMPL_MODEL_DIR, batch_size=1, create_transl=False)\n', (9100, 9158), False, 'from models import hmr, SMPL\n'), ((9951, 9966), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9964, 9966), False, 'import torch\n'), ((11826, 11865), 'numpy.dot', 'np.dot', (['(pred_vertices - center)', 'aroundy'], {}), '(pred_vertices - center, aroundy)\n', (11832, 11865), True, 'import numpy as np\n'), ((11992, 12009), 'numpy.ones_like', 'np.ones_like', (['img'], {}), '(img)\n', (12004, 12009), True, 'import numpy as np\n'), ((4629, 4649), 'numpy.round', 'np.round', (['all_joints'], {}), '(all_joints)\n', (4637, 4649), True, 'import numpy as np\n'), ((7919, 7939), 'cv2.imread', 'cv2.imread', (['img_file'], {}), '(img_file)\n', (7929, 7939), False, 'import cv2\n'), ((6558, 6570), 'json.load', 'json.load', (['f'], {}), '(f)\n', (6567, 6570), False, 'import json\n'), ((9711, 9735), 'os.path.join', 'os.path.join', (['dirpath', 'f'], {}), '(dirpath, f)\n', (9723, 9735), False, 'import os\n'), ((3205, 3235), 'numpy.mean', 'np.mean', (['input_image.shape[:2]'], {}), '(input_image.shape[:2])\n', (3212, 3235), True, 'import numpy as np\n'), ((7235, 7247), 'json.load', 'json.load', (['f'], {}), '(f)\n', (7244, 7247), False, 'import json\n'), ((9603, 9622), 'os.path.splitext', 'os.path.splitext', (['f'], {}), '(f)\n', (9619, 9622), False, 'import os\n'), ((9639, 9658), 'os.path.splitext', 'os.path.splitext', (['f'], {}), '(f)\n', (9655, 9658), False, 'import os\n'), ((11734, 11750), 'numpy.radians', 'np.radians', (['(90.0)'], {}), '(90.0)\n', (11744, 11750), True, 'import numpy as np\n'), ((10838, 10865), 'torch.eye', 'torch.eye', (['(3)'], {'device': 'device'}), '(3, device=device)\n', (10847, 10865), False, 'import torch\n')]
import os import re import shutil import configparser import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder, LabelBinarizer from download_data import check_folder, remove_folder, read_config separators = {'comma': ',', ',': ',', ', ': ', ', '': r'\s+', ' ': r'\s+', ';': ';', ',|': r'\,|\|', ',[': r'\,|\['} missing = {'?': np.nan, '-': np.nan, '*': np.nan, '': np.nan, '#DIV/0!': np.nan} min_target = 5 def process_data(config_folder, processed_folder): """ :param str config_folder: :param str processed_folder: :return: """ # Lists for possible errors error_files = list() download_error = list() # Remove and create processed folder if os.path.isdir(processed_folder): shutil.rmtree(processed_folder) os.mkdir(processed_folder) # Folders from configuration folders = os.listdir(config_folder) # Classification or regression if 'classification' in config_folder: print('Processing classification') classification = True else: print('Processing regression') classification = False # Scroll through folders for directory in folders: print('Formatting', directory) config_file = None data_file = None full_dir = os.path.join(config_folder, directory) if os.path.isdir(full_dir): for f in os.listdir(full_dir): if '.ini' in f: config_file = f elif '.data' in f: data_file = f else: pass if config_file is not None and data_file is not None: try: # Read config file config = configparser.ConfigParser() with open('/'.join([full_dir, config_file]), 'r', encoding='utf-8') as f: config.read_file(f) # config.read('/'.join([full_dir, config_file])) sep = separators[config['info']['separator']] # Does it have header? header = config['info']['header'] skiprows = config.get('info', 'skiprows', fallback='') if header == '' or header == '0': header = None else: header = int(header) - 1 if skiprows == '' or header == '0': skiprows = None else: skiprows = int(skiprows) # Does it have index? index = config['info']['id_indices'] if index == '': # There is no index index_col = None else: # It could be one or several indexes index_col = [int(i) - 1 for i in index.split(',')] # if isinstance(index, int): # Just one index # index_col = index - 1 # else: # Several indexes # index_col = list() # for i in index: # index_col.append(i - 1) # Load only columns needed label_column = int(config['info']['target_index']) - 1 # In python, index begins at 0 categoric_indices = config['info']['categoric_indices'] if categoric_indices == '': categoric_indices = list() else: categoric_indices = [int(i) - 1 for i in categoric_indices.split(',')] value_indices = config['info']['value_indices'] if value_indices == '': value_indices = list() else: value_indices = [int(i) - 1 for i in value_indices.split(',')] indices = categoric_indices + value_indices + [label_column] if index_col is not None: indices += index_col indices = list(set(indices)) # Read data try: df = pd.read_csv(os.path.join(full_dir, data_file), sep=sep, index_col=index_col, usecols=indices, header=None, skiprows=skiprows, engine='python') except pd.errors.ParserError as e: # Maybe there is a easier way sk = int(re.findall(r'\d+', re.findall(r'line \d+', str(e))[0])[0]) - 1 df = pd.read_csv(os.path.join(full_dir, data_file), sep=sep, index_col=index_col, header=None, usecols=indices, skiprows=[skiprows, sk]) except UnicodeDecodeError as e: df = pd.read_csv(os.path.join(full_dir, data_file), sep=sep, index_col=index_col, header=None, skiprows=skiprows, usecols=indices, encoding='utf-16le') if header is not None: df = df.iloc[header + 1:] if index_col is not None: # Categoric columns after index reduce the numbers new_categoric_indices = list() for categoric_index in categoric_indices: for main_index in index_col: if categoric_index > main_index: categoric_index -= 1 new_categoric_indices.append(categoric_index) categoric_indices = new_categoric_indices # Value columns after index reduce the numbers new_value_indices = list() for value_index in value_indices: for main_index in index_col: if value_index > main_index: value_index -= 1 new_value_indices.append(value_index) value_indices = new_value_indices for main_index in index_col: if label_column > main_index: label_column -= 1 # Renaming columns range_columns = list(set(categoric_indices + value_indices + [label_column])) df.columns = range_columns # # Changing label to last column # final_column = df.columns[-1] # if label_column != final_column: # if label_column not in df.columns: # raise KeyError('Label index {} is not in columns {}'.format(label_column, df.columns)) # a = df[final_column].copy() # df[final_column] = df[label_column].copy() # df[label_column] = a # label_column = final_column # Now, final column is the column for the label if classification is True: unique_target, unique_count = np.unique(df[label_column], return_counts=True) if np.min(unique_count) < min_target: raise ValueError('Original data doesn\'t has poor class distribution,', np.min(unique_count)) if df[label_column].dtype != int and df[label_column].dtype != float: if 'regression' in config_folder: df[label_column] = pd.Series(df[label_column], dtype=np.float32) else: le = LabelEncoder() try: df[label_column] = le.fit_transform([str(e).replace(' ', '') for e in df[label_column]]) except TypeError as e: df[label_column] = df[label_column].factorize()[0] df[label_column] = pd.Series(df[label_column] + (1 - np.min(df[label_column].values)), dtype=np.int32) # Store label column label_series = df[label_column].copy() df = df.drop(columns=label_column) columnas = list(df.columns.copy()) if categoric_indices == list(): categoric_indices = np.array(categoric_indices) else: categoric_indices = np.array(categoric_indices, dtype=int) # Replacing missing by NaN for c in columnas: if c not in categoric_indices and (df[c].dtype != int and df[c].dtype != float): df[c] = df[c].replace(missing) # Restore label column. With this label, we assure dropna df[label_column] = label_series if pd.isnull(df).values.any() == True: # Don't work properly with "is" # Removing depending on how many data are left out n_len = len(df.index) # Length of instances m_len = len(df.columns) # Length of features # Drop NaN by rows df_dropna_0 = df.dropna(axis=0) # Drop Nan by columns df_dropna_1 = df.dropna(axis=1) if classification is True: if len(df_dropna_0) > 0: _, label_counts_0 = np.unique(df_dropna_0[label_column], return_counts=True) if classification is True: min_label_counts_0 = np.min(label_counts_0) else: min_label_counts_0 = 0 _, label_counts_1 = np.unique(df_dropna_1[label_column], return_counts=True) min_label_counts_1 = np.min(label_counts_1) if min_label_counts_0 < min_target: if min_label_counts_1 > 5: df = df_dropna_1 else: raise ValueError(directory, ' omitted. Removing NaNs delete class information') elif min_label_counts_1 < 2: df = df_dropna_0 n_len_rm_rows = len(df_dropna_0.index) # Length of instances when rows are removed m_len_rm_rows = len(df_dropna_0.columns) # Length of features when columns are removed n_len_rm_cols = len(df_dropna_1.index) # Length of instances when columns are removed m_len_rm_cols = len(df_dropna_1.columns) # Length of features when columns are removed if (n_len_rm_cols > (2 * n_len_rm_rows) and (2 * m_len_rm_cols) > m_len) or n_len_rm_rows == 0: df = df_dropna_1 else: df = df_dropna_0 # Store label column label_series = df[label_column].copy() df = df.drop(columns=label_column) columns = list(df.columns.copy()) for c in columns: series_values = df[c].values if c not in categoric_indices: # series = [float(series_values[i]) # for i in range(len(df[c]))] df[c] = pd.Series(df[c], dtype=np.float32) else: # It was a string, need to be transformed number_cat = len(np.unique(series_values)) df = df.drop(columns=c) if number_cat == 1: # It is unuseful pass elif number_cat == 2: df[c] = LabelEncoder().fit_transform(series_values) else: try: series_binarized = LabelBinarizer().fit_transform(series_values) except ValueError: raise series_binarized_t = series_binarized.transpose() for i in range(1, number_cat + 1): c_label = '_'.join([str(c), str(i)]) df[c_label] = series_binarized_t[i - 1] # Restore label column. With this label, we assure this is at the end df['Target'] = label_series # Saving the dataframe into processed folder df.to_csv(os.path.join(processed_folder, data_file), sep=' ', header=False, index=False) except ValueError as e: print(' '.join([data_file, 'gives a ValueError:', str(e)])) error_files.append(data_file) except pd.errors.ParserError as e: print(' '.join([data_file, 'gives a parser error:', str(e)])) error_files.append(data_file) except KeyError as e: print(' '.join([data_file, 'gives a KeyError:', str(e)])) error_files.append(data_file) except TypeError as e: print(' '.join([data_file, 'gives a TypeError:', str(e)])) error_files.append(data_file) except IndexError as e: print(' '.join([data_file, 'separator is not correct:', str(e)])) error_files.append(data_file) else: if config_file is None: if data_file is None: print('{} does not have .data and .ini files'.format(full_dir)) else: print('{} does not have .ini file'.format(full_dir)) else: print('{} does not have .data file'.format(full_dir)) download_error.append(full_dir) else: # This is not a directory pass if __name__ == '__main__': try: parameter_config = read_config('parameter_config.ini') except NameError: print('Not custom parameter config file found, using default') parameter_config = read_config('default_config.ini') config_folders = parameter_config.get('PROCESS', 'config_folders').split(',') processed_data_folder = parameter_config.get('PROCESS', 'processed_folder', fallback='processed_data') check_folder(processed_data_folder) remove_older = eval(parameter_config.get('PROCESS', 'remove_older', fallback='True')) for config_folder in config_folders: data_type = config_folder.split('/')[1] processed_folder = os.path.join(processed_data_folder, data_type) # Remove and create folder if remove_older is True: remove_folder(processed_folder) check_folder(processed_folder) process_data(config_folder=config_folder, processed_folder=processed_folder) print()
[ "pandas.Series", "pandas.isnull", "sklearn.preprocessing.LabelEncoder", "os.listdir", "download_data.remove_folder", "configparser.ConfigParser", "numpy.unique", "download_data.read_config", "sklearn.preprocessing.LabelBinarizer", "os.path.join", "numpy.min", "numpy.array", "os.path.isdir", ...
[((879, 910), 'os.path.isdir', 'os.path.isdir', (['processed_folder'], {}), '(processed_folder)\n', (892, 910), False, 'import os\n'), ((956, 982), 'os.mkdir', 'os.mkdir', (['processed_folder'], {}), '(processed_folder)\n', (964, 982), False, 'import os\n'), ((1031, 1056), 'os.listdir', 'os.listdir', (['config_folder'], {}), '(config_folder)\n', (1041, 1056), False, 'import os\n'), ((16287, 16322), 'download_data.check_folder', 'check_folder', (['processed_data_folder'], {}), '(processed_data_folder)\n', (16299, 16322), False, 'from download_data import check_folder, remove_folder, read_config\n'), ((920, 951), 'shutil.rmtree', 'shutil.rmtree', (['processed_folder'], {}), '(processed_folder)\n', (933, 951), False, 'import shutil\n'), ((1458, 1496), 'os.path.join', 'os.path.join', (['config_folder', 'directory'], {}), '(config_folder, directory)\n', (1470, 1496), False, 'import os\n'), ((1508, 1531), 'os.path.isdir', 'os.path.isdir', (['full_dir'], {}), '(full_dir)\n', (1521, 1531), False, 'import os\n'), ((15763, 15798), 'download_data.read_config', 'read_config', (['"""parameter_config.ini"""'], {}), "('parameter_config.ini')\n", (15774, 15798), False, 'from download_data import check_folder, remove_folder, read_config\n'), ((16621, 16667), 'os.path.join', 'os.path.join', (['processed_data_folder', 'data_type'], {}), '(processed_data_folder, data_type)\n', (16633, 16667), False, 'import os\n'), ((16788, 16818), 'download_data.check_folder', 'check_folder', (['processed_folder'], {}), '(processed_folder)\n', (16800, 16818), False, 'from download_data import check_folder, remove_folder, read_config\n'), ((1554, 1574), 'os.listdir', 'os.listdir', (['full_dir'], {}), '(full_dir)\n', (1564, 1574), False, 'import os\n'), ((15919, 15952), 'download_data.read_config', 'read_config', (['"""default_config.ini"""'], {}), "('default_config.ini')\n", (15930, 15952), False, 'from download_data import check_folder, remove_folder, read_config\n'), ((16748, 16779), 'download_data.remove_folder', 'remove_folder', (['processed_folder'], {}), '(processed_folder)\n', (16761, 16779), False, 'from download_data import check_folder, remove_folder, read_config\n'), ((1915, 1942), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (1940, 1942), False, 'import configparser\n'), ((8068, 8115), 'numpy.unique', 'np.unique', (['df[label_column]'], {'return_counts': '(True)'}), '(df[label_column], return_counts=True)\n', (8077, 8115), True, 'import numpy as np\n'), ((9581, 9608), 'numpy.array', 'np.array', (['categoric_indices'], {}), '(categoric_indices)\n', (9589, 9608), True, 'import numpy as np\n'), ((9679, 9717), 'numpy.array', 'np.array', (['categoric_indices'], {'dtype': 'int'}), '(categoric_indices, dtype=int)\n', (9687, 9717), True, 'import numpy as np\n'), ((14257, 14298), 'os.path.join', 'os.path.join', (['processed_folder', 'data_file'], {}), '(processed_folder, data_file)\n', (14269, 14298), False, 'import os\n'), ((4431, 4464), 'os.path.join', 'os.path.join', (['full_dir', 'data_file'], {}), '(full_dir, data_file)\n', (4443, 4464), False, 'import os\n'), ((8143, 8163), 'numpy.min', 'np.min', (['unique_count'], {}), '(unique_count)\n', (8149, 8163), True, 'import numpy as np\n'), ((8496, 8541), 'pandas.Series', 'pd.Series', (['df[label_column]'], {'dtype': 'np.float32'}), '(df[label_column], dtype=np.float32)\n', (8505, 8541), True, 'import pandas as pd\n'), ((8662, 8676), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (8674, 8676), False, 'from sklearn.preprocessing import LabelEncoder, LabelBinarizer\n'), ((11159, 11215), 'numpy.unique', 'np.unique', (['df_dropna_1[label_column]'], {'return_counts': '(True)'}), '(df_dropna_1[label_column], return_counts=True)\n', (11168, 11215), True, 'import numpy as np\n'), ((11323, 11345), 'numpy.min', 'np.min', (['label_counts_1'], {}), '(label_counts_1)\n', (11329, 11345), True, 'import numpy as np\n'), ((12991, 13025), 'pandas.Series', 'pd.Series', (['df[c]'], {'dtype': 'np.float32'}), '(df[c], dtype=np.float32)\n', (13000, 13025), True, 'import pandas as pd\n'), ((5054, 5087), 'os.path.join', 'os.path.join', (['full_dir', 'data_file'], {}), '(full_dir, data_file)\n', (5066, 5087), False, 'import os\n'), ((5472, 5505), 'os.path.join', 'os.path.join', (['full_dir', 'data_file'], {}), '(full_dir, data_file)\n', (5484, 5505), False, 'import os\n'), ((8278, 8298), 'numpy.min', 'np.min', (['unique_count'], {}), '(unique_count)\n', (8284, 8298), True, 'import numpy as np\n'), ((10764, 10820), 'numpy.unique', 'np.unique', (['df_dropna_0[label_column]'], {'return_counts': '(True)'}), '(df_dropna_0[label_column], return_counts=True)\n', (10773, 10820), True, 'import numpy as np\n'), ((13144, 13168), 'numpy.unique', 'np.unique', (['series_values'], {}), '(series_values)\n', (13153, 13168), True, 'import numpy as np\n'), ((10124, 10137), 'pandas.isnull', 'pd.isnull', (['df'], {}), '(df)\n', (10133, 10137), True, 'import pandas as pd\n'), ((10999, 11021), 'numpy.min', 'np.min', (['label_counts_0'], {}), '(label_counts_0)\n', (11005, 11021), True, 'import numpy as np\n'), ((9172, 9203), 'numpy.min', 'np.min', (['df[label_column].values'], {}), '(df[label_column].values)\n', (9178, 9203), True, 'import numpy as np\n'), ((13415, 13429), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (13427, 13429), False, 'from sklearn.preprocessing import LabelEncoder, LabelBinarizer\n'), ((13585, 13601), 'sklearn.preprocessing.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (13599, 13601), False, 'from sklearn.preprocessing import LabelEncoder, LabelBinarizer\n')]
""" Tests for grdtrack. """ import os import numpy as np import numpy.testing as npt import pandas as pd import pytest from pygmt import grdtrack from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import GMTTempFile, data_kind from pygmt.helpers.testing import load_static_earth_relief TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") POINTS_DATA = os.path.join(TEST_DATA_DIR, "track.txt") @pytest.fixture(scope="module", name="dataarray") def fixture_dataarray(): """ Load the grid data from the sample earth_relief file. """ return load_static_earth_relief() @pytest.fixture(scope="module", name="expected_array") def fixture_numpy_array(): """ Load a numpy array with x, y, and bathymetry data. """ array = [ [-51.613, -17.93, 796.59434514], [-48.917, -22.434, 566.49184359], [-50.444, -16.358, 571.1492788], [-50.721, -16.628, 578.76116859], [-51.394, -12.196, 274.43205501], [-50.207, -18.404, 532.11444935], [-52.56, -16.977, 670.16934401], [-51.866, -19.794, 426.77300768], [-48.001, -14.144, 741.35824074], [-54.438, -19.193, 490.02716679], ] return array @pytest.fixture(scope="module", name="dataframe") def fixture_dataframe(): """ Load a pandas DataFrame with points. """ return pd.read_csv( POINTS_DATA, sep=r"\s+", header=None, names=["longitude", "latitude"] ) def test_grdtrack_input_dataframe_and_dataarray(dataarray, dataframe, expected_array): """ Run grdtrack by passing in a pandas.DataFrame and xarray.DataArray as inputs. """ output = grdtrack(points=dataframe, grid=dataarray, newcolname="bathymetry") assert isinstance(output, pd.DataFrame) assert output.columns.to_list() == ["longitude", "latitude", "bathymetry"] npt.assert_allclose(np.array(output), expected_array) def test_grdtrack_input_csvfile_and_dataarray(dataarray, expected_array): """ Run grdtrack by passing in a csvfile and xarray.DataArray as inputs. """ with GMTTempFile() as tmpfile: output = grdtrack(points=POINTS_DATA, grid=dataarray, outfile=tmpfile.name) assert output is None # check that output is None since outfile is set assert os.path.exists(path=tmpfile.name) # check that outfile exists at path output = np.loadtxt(tmpfile.name) npt.assert_allclose(np.array(output), expected_array) def test_grdtrack_input_dataframe_and_ncfile(dataframe, expected_array): """ Run grdtrack by passing in a pandas.DataFrame and netcdf file as inputs. """ output = grdtrack( points=dataframe, grid="@static_earth_relief.nc", newcolname="bathymetry" ) assert isinstance(output, pd.DataFrame) assert output.columns.to_list() == ["longitude", "latitude", "bathymetry"] npt.assert_allclose(np.array(output), expected_array) def test_grdtrack_input_csvfile_and_ncfile_to_dataframe(expected_array): """ Run grdtrack by passing in a csv file and netcdf file as inputs with a pandas.DataFrame output. """ output = grdtrack(points=POINTS_DATA, grid="@static_earth_relief.nc") assert isinstance(output, pd.DataFrame) npt.assert_allclose(np.array(output), expected_array) def test_grdtrack_wrong_kind_of_points_input(dataarray, dataframe): """ Run grdtrack using points input that is not a pandas.DataFrame (matrix) or file. """ invalid_points = dataframe.longitude.to_xarray() assert data_kind(invalid_points) == "grid" with pytest.raises(GMTInvalidInput): grdtrack(points=invalid_points, grid=dataarray, newcolname="bathymetry") def test_grdtrack_wrong_kind_of_grid_input(dataarray, dataframe): """ Run grdtrack using grid input that is not as xarray.DataArray (grid) or file. """ invalid_grid = dataarray.to_dataset() assert data_kind(invalid_grid) == "matrix" with pytest.raises(GMTInvalidInput): grdtrack(points=dataframe, grid=invalid_grid, newcolname="bathymetry") def test_grdtrack_without_newcolname_setting(dataarray, dataframe): """ Run grdtrack by not passing in newcolname parameter setting. """ with pytest.raises(GMTInvalidInput): grdtrack(points=dataframe, grid=dataarray) def test_grdtrack_without_outfile_setting(dataarray, dataframe): """ Run grdtrack by not passing in outfile parameter setting. """ with pytest.raises(GMTInvalidInput): grdtrack(points=dataframe, grid=dataarray)
[ "os.path.exists", "pygmt.helpers.GMTTempFile", "pygmt.helpers.data_kind", "pandas.read_csv", "pygmt.grdtrack", "os.path.join", "os.path.dirname", "numpy.array", "pytest.raises", "pytest.fixture", "numpy.loadtxt", "pygmt.helpers.testing.load_static_earth_relief" ]
[((379, 419), 'os.path.join', 'os.path.join', (['TEST_DATA_DIR', '"""track.txt"""'], {}), "(TEST_DATA_DIR, 'track.txt')\n", (391, 419), False, 'import os\n'), ((423, 471), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'name': '"""dataarray"""'}), "(scope='module', name='dataarray')\n", (437, 471), False, 'import pytest\n'), ((612, 665), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'name': '"""expected_array"""'}), "(scope='module', name='expected_array')\n", (626, 665), False, 'import pytest\n'), ((1221, 1269), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'name': '"""dataframe"""'}), "(scope='module', name='dataframe')\n", (1235, 1269), False, 'import pytest\n'), ((330, 355), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (345, 355), False, 'import os\n'), ((582, 608), 'pygmt.helpers.testing.load_static_earth_relief', 'load_static_earth_relief', ([], {}), '()\n', (606, 608), False, 'from pygmt.helpers.testing import load_static_earth_relief\n'), ((1363, 1449), 'pandas.read_csv', 'pd.read_csv', (['POINTS_DATA'], {'sep': '"""\\\\s+"""', 'header': 'None', 'names': "['longitude', 'latitude']"}), "(POINTS_DATA, sep='\\\\s+', header=None, names=['longitude',\n 'latitude'])\n", (1374, 1449), True, 'import pandas as pd\n'), ((1664, 1731), 'pygmt.grdtrack', 'grdtrack', ([], {'points': 'dataframe', 'grid': 'dataarray', 'newcolname': '"""bathymetry"""'}), "(points=dataframe, grid=dataarray, newcolname='bathymetry')\n", (1672, 1731), False, 'from pygmt import grdtrack\n'), ((2648, 2736), 'pygmt.grdtrack', 'grdtrack', ([], {'points': 'dataframe', 'grid': '"""@static_earth_relief.nc"""', 'newcolname': '"""bathymetry"""'}), "(points=dataframe, grid='@static_earth_relief.nc', newcolname=\n 'bathymetry')\n", (2656, 2736), False, 'from pygmt import grdtrack\n'), ((3135, 3195), 'pygmt.grdtrack', 'grdtrack', ([], {'points': 'POINTS_DATA', 'grid': '"""@static_earth_relief.nc"""'}), "(points=POINTS_DATA, grid='@static_earth_relief.nc')\n", (3143, 3195), False, 'from pygmt import grdtrack\n'), ((1879, 1895), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (1887, 1895), True, 'import numpy as np\n'), ((2087, 2100), 'pygmt.helpers.GMTTempFile', 'GMTTempFile', ([], {}), '()\n', (2098, 2100), False, 'from pygmt.helpers import GMTTempFile, data_kind\n'), ((2130, 2196), 'pygmt.grdtrack', 'grdtrack', ([], {'points': 'POINTS_DATA', 'grid': 'dataarray', 'outfile': 'tmpfile.name'}), '(points=POINTS_DATA, grid=dataarray, outfile=tmpfile.name)\n', (2138, 2196), False, 'from pygmt import grdtrack\n'), ((2292, 2325), 'os.path.exists', 'os.path.exists', ([], {'path': 'tmpfile.name'}), '(path=tmpfile.name)\n', (2306, 2325), False, 'import os\n'), ((2380, 2404), 'numpy.loadtxt', 'np.loadtxt', (['tmpfile.name'], {}), '(tmpfile.name)\n', (2390, 2404), True, 'import numpy as np\n'), ((2893, 2909), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (2901, 2909), True, 'import numpy as np\n'), ((3264, 3280), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (3272, 3280), True, 'import numpy as np\n'), ((3538, 3563), 'pygmt.helpers.data_kind', 'data_kind', (['invalid_points'], {}), '(invalid_points)\n', (3547, 3563), False, 'from pygmt.helpers import GMTTempFile, data_kind\n'), ((3583, 3613), 'pytest.raises', 'pytest.raises', (['GMTInvalidInput'], {}), '(GMTInvalidInput)\n', (3596, 3613), False, 'import pytest\n'), ((3623, 3695), 'pygmt.grdtrack', 'grdtrack', ([], {'points': 'invalid_points', 'grid': 'dataarray', 'newcolname': '"""bathymetry"""'}), "(points=invalid_points, grid=dataarray, newcolname='bathymetry')\n", (3631, 3695), False, 'from pygmt import grdtrack\n'), ((3920, 3943), 'pygmt.helpers.data_kind', 'data_kind', (['invalid_grid'], {}), '(invalid_grid)\n', (3929, 3943), False, 'from pygmt.helpers import GMTTempFile, data_kind\n'), ((3965, 3995), 'pytest.raises', 'pytest.raises', (['GMTInvalidInput'], {}), '(GMTInvalidInput)\n', (3978, 3995), False, 'import pytest\n'), ((4005, 4075), 'pygmt.grdtrack', 'grdtrack', ([], {'points': 'dataframe', 'grid': 'invalid_grid', 'newcolname': '"""bathymetry"""'}), "(points=dataframe, grid=invalid_grid, newcolname='bathymetry')\n", (4013, 4075), False, 'from pygmt import grdtrack\n'), ((4236, 4266), 'pytest.raises', 'pytest.raises', (['GMTInvalidInput'], {}), '(GMTInvalidInput)\n', (4249, 4266), False, 'import pytest\n'), ((4276, 4318), 'pygmt.grdtrack', 'grdtrack', ([], {'points': 'dataframe', 'grid': 'dataarray'}), '(points=dataframe, grid=dataarray)\n', (4284, 4318), False, 'from pygmt import grdtrack\n'), ((4473, 4503), 'pytest.raises', 'pytest.raises', (['GMTInvalidInput'], {}), '(GMTInvalidInput)\n', (4486, 4503), False, 'import pytest\n'), ((4513, 4555), 'pygmt.grdtrack', 'grdtrack', ([], {'points': 'dataframe', 'grid': 'dataarray'}), '(points=dataframe, grid=dataarray)\n', (4521, 4555), False, 'from pygmt import grdtrack\n'), ((2433, 2449), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (2441, 2449), True, 'import numpy as np\n')]
#! /home/steve/anaconda3/bin/python3.7 import numpy as np train_images = np.load("train_images.npy") padded_train_images = [] print("padding train images") for i in train_images: entry=[] entry.append(np.zeros(32)) entry.append(np.zeros(32)) for j in i: entry.append([0,0]+list(j)+[0,0]) entry.append(np.zeros(32)) entry.append(np.zeros(32)) padded_train_images.append(entry) print("saving padded train images") np.save("padded_train_images.npy", np.array(padded_train_images)) test_images = np.load("test_images.npy") padded_test_images = [] print("padding test images") for i in test_images: entry=[] entry.append(np.zeros(32)) entry.append(np.zeros(32)) for j in i: entry.append([0,0]+list(j)+[0,0]) entry.append(np.zeros(32)) entry.append(np.zeros(32)) padded_test_images.append(entry) print("saving padded test images") np.save("padded_test_images.npy", np.array(padded_test_images))
[ "numpy.array", "numpy.zeros", "numpy.load" ]
[((74, 101), 'numpy.load', 'np.load', (['"""train_images.npy"""'], {}), "('train_images.npy')\n", (81, 101), True, 'import numpy as np\n'), ((535, 561), 'numpy.load', 'np.load', (['"""test_images.npy"""'], {}), "('test_images.npy')\n", (542, 561), True, 'import numpy as np\n'), ((486, 515), 'numpy.array', 'np.array', (['padded_train_images'], {}), '(padded_train_images)\n', (494, 515), True, 'import numpy as np\n'), ((941, 969), 'numpy.array', 'np.array', (['padded_test_images'], {}), '(padded_test_images)\n', (949, 969), True, 'import numpy as np\n'), ((212, 224), 'numpy.zeros', 'np.zeros', (['(32)'], {}), '(32)\n', (220, 224), True, 'import numpy as np\n'), ((243, 255), 'numpy.zeros', 'np.zeros', (['(32)'], {}), '(32)\n', (251, 255), True, 'import numpy as np\n'), ((332, 344), 'numpy.zeros', 'np.zeros', (['(32)'], {}), '(32)\n', (340, 344), True, 'import numpy as np\n'), ((363, 375), 'numpy.zeros', 'np.zeros', (['(32)'], {}), '(32)\n', (371, 375), True, 'import numpy as np\n'), ((669, 681), 'numpy.zeros', 'np.zeros', (['(32)'], {}), '(32)\n', (677, 681), True, 'import numpy as np\n'), ((700, 712), 'numpy.zeros', 'np.zeros', (['(32)'], {}), '(32)\n', (708, 712), True, 'import numpy as np\n'), ((789, 801), 'numpy.zeros', 'np.zeros', (['(32)'], {}), '(32)\n', (797, 801), True, 'import numpy as np\n'), ((820, 832), 'numpy.zeros', 'np.zeros', (['(32)'], {}), '(32)\n', (828, 832), True, 'import numpy as np\n')]
import numpy as np import pandas as pd from scipy.spatial import distance_matrix from sklearn.preprocessing import scale from scipy.stats import linregress from matplotlib import pyplot as plt import os def normalize(a): return np.interp(a, (a.min(), a.max()), (-1, +1)) def plot_diff(x, node, path): x_norm = normalize(x) x = list(range(1,x_norm.shape[0]+1)) y = list(x_norm) plt.figure(figsize=(12,8)) plt.plot(x,y) plt.title(node) plt.xlabel('monthly interval') plt.ylabel('norm question count') plt.tight_layout() plt.savefig(os.path.join(path, '{}.png'.format(node))) plt.clf() plt.close() def plot_pair(x1, x2, path, node): x = list(range(1,x1.shape[0]+1)) y1 = list(x1) y2 = list(x2) plt.figure(figsize=(12,8)) plt.plot(x,y1) plt.plot(x,y2) plt.title(node) plt.xlabel('monthly interval') plt.ylabel('question count') plt.tight_layout() plt.savefig(os.path.join(path, '{}.png'.format(node))) plt.clf() plt.close() def get_cluster_qn_count(cluster_data, node_data, num_clusters=200): qn_count_map = {} for cluster in range(num_clusters): nodes = list(cluster_data[cluster_data.clusters_200 == cluster]['nodes']) cl_data = node_data[nodes].T cl_data = cl_data.loc[:, (cl_data != 0).any(axis=0)] qn_count_map[cluster] = (cl_data.sum(axis=1)/cl_data.shape[1]).sum()/cl_data.shape[0] return qn_count_map root_folder = '/home/hduser/iit_data/node_clusters/tmp' cluster_data = pd.read_csv('/home/hduser/iit_data/node_clusters/master_clusters_200.csv') node_data = pd.read_csv('/home/hduser/iit_data/node_clusters/node_data_wo_index.csv') small_cluster_threshold = 1 cluster_qn_count_map = get_cluster_qn_count(cluster_data, node_data) clusters_subset = [k for k, v in cluster_qn_count_map.items() if v > small_cluster_threshold] def identify_entity_change(norm_array, threshold = 1.2): count = 0 sign_shift_count = 0 shift_len = norm_array.shape[0] if np.where(norm_array == 1)[0].shape[0] >= 1 and np.where(norm_array == -1)[0].shape[0] >= 1 : if np.where(norm_array == 1)[0][0] < np.where(norm_array == -1)[0][0]: if np.where(norm_array[:np.where(norm_array == 1)[0][0]] < 0)[0].shape[0] == 0 and np.where(norm_array[np.where(norm_array == -1)[0][0]:] > 0.5)[0].shape[0] == 0: shift_len = np.where(norm_array == -1)[0][0] - np.where(norm_array == 1)[0][0] # for first, second in zip(norm_array, norm_array[1:]): # if (first - second) >= threshold: # count = count + 1 if shift_len < 10: print(shift_len) return True else: return False possible_entity_change = [] for cluster in clusters_subset: nodes = list(cluster_data[cluster_data.clusters_200 == cluster]['nodes']) entity_cluster = node_data[nodes] #os.makedirs(os.path.join(root_folder, str(cluster))) #os.makedirs(os.path.join(root_folder, str(cluster), 'pair_plots')) #os.makedirs(os.path.join(root_folder, str(cluster), 'diff_plots')) analysis_data = {} for node1 in nodes: for node2 in nodes: if node1 != node2: analysis_data[node1 + '-' +node2] = entity_cluster[node1] - entity_cluster[node2] if max(entity_cluster[node1]) - min(entity_cluster[node1]) > 10 and max(entity_cluster[node2]) - min(entity_cluster[node2]) > 10: if identify_entity_change(normalize(entity_cluster[node1] - entity_cluster[node2])): possible_entity_change.append(node1 + '-' +node2) print('Cluster : {0}, pair : {1}'.format(cluster, node1 + '-' +node2)) #plot_diff(entity_cluster[node1] - entity_cluster[node2], node1 + '-' +node2, os.path.join(root_folder, str(cluster), 'diff_plots')) #plot_pair(entity_cluster[node1], entity_cluster[node2], os.path.join(root_folder, str(cluster), 'pair_plots'), node1 + '-' +node2) #print(possible_entity_change)
[ "pandas.read_csv", "matplotlib.pyplot.ylabel", "numpy.where", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.clf", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.title" ]
[((1418, 1492), 'pandas.read_csv', 'pd.read_csv', (['"""/home/hduser/iit_data/node_clusters/master_clusters_200.csv"""'], {}), "('/home/hduser/iit_data/node_clusters/master_clusters_200.csv')\n", (1429, 1492), True, 'import pandas as pd\n'), ((1505, 1578), 'pandas.read_csv', 'pd.read_csv', (['"""/home/hduser/iit_data/node_clusters/node_data_wo_index.csv"""'], {}), "('/home/hduser/iit_data/node_clusters/node_data_wo_index.csv')\n", (1516, 1578), True, 'import pandas as pd\n'), ((384, 411), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (394, 411), True, 'from matplotlib import pyplot as plt\n'), ((412, 426), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (420, 426), True, 'from matplotlib import pyplot as plt\n'), ((427, 442), 'matplotlib.pyplot.title', 'plt.title', (['node'], {}), '(node)\n', (436, 442), True, 'from matplotlib import pyplot as plt\n'), ((444, 474), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""monthly interval"""'], {}), "('monthly interval')\n", (454, 474), True, 'from matplotlib import pyplot as plt\n'), ((476, 509), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""norm question count"""'], {}), "('norm question count')\n", (486, 509), True, 'from matplotlib import pyplot as plt\n'), ((511, 529), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (527, 529), True, 'from matplotlib import pyplot as plt\n'), ((587, 596), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (594, 596), True, 'from matplotlib import pyplot as plt\n'), ((598, 609), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (607, 609), True, 'from matplotlib import pyplot as plt\n'), ((711, 738), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 8)'}), '(figsize=(12, 8))\n', (721, 738), True, 'from matplotlib import pyplot as plt\n'), ((739, 754), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y1'], {}), '(x, y1)\n', (747, 754), True, 'from matplotlib import pyplot as plt\n'), ((755, 770), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y2'], {}), '(x, y2)\n', (763, 770), True, 'from matplotlib import pyplot as plt\n'), ((771, 786), 'matplotlib.pyplot.title', 'plt.title', (['node'], {}), '(node)\n', (780, 786), True, 'from matplotlib import pyplot as plt\n'), ((788, 818), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""monthly interval"""'], {}), "('monthly interval')\n", (798, 818), True, 'from matplotlib import pyplot as plt\n'), ((820, 848), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""question count"""'], {}), "('question count')\n", (830, 848), True, 'from matplotlib import pyplot as plt\n'), ((850, 868), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (866, 868), True, 'from matplotlib import pyplot as plt\n'), ((926, 935), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (933, 935), True, 'from matplotlib import pyplot as plt\n'), ((937, 948), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (946, 948), True, 'from matplotlib import pyplot as plt\n'), ((1998, 2023), 'numpy.where', 'np.where', (['(norm_array == 1)'], {}), '(norm_array == 1)\n', (2006, 2023), True, 'import numpy as np\n'), ((2033, 2059), 'numpy.where', 'np.where', (['(norm_array == -1)'], {}), '(norm_array == -1)\n', (2041, 2059), True, 'import numpy as np\n'), ((1900, 1925), 'numpy.where', 'np.where', (['(norm_array == 1)'], {}), '(norm_array == 1)\n', (1908, 1925), True, 'import numpy as np\n'), ((1947, 1973), 'numpy.where', 'np.where', (['(norm_array == -1)'], {}), '(norm_array == -1)\n', (1955, 1973), True, 'import numpy as np\n'), ((2249, 2275), 'numpy.where', 'np.where', (['(norm_array == -1)'], {}), '(norm_array == -1)\n', (2257, 2275), True, 'import numpy as np\n'), ((2284, 2309), 'numpy.where', 'np.where', (['(norm_array == 1)'], {}), '(norm_array == 1)\n', (2292, 2309), True, 'import numpy as np\n'), ((2094, 2119), 'numpy.where', 'np.where', (['(norm_array == 1)'], {}), '(norm_array == 1)\n', (2102, 2119), True, 'import numpy as np\n'), ((2173, 2199), 'numpy.where', 'np.where', (['(norm_array == -1)'], {}), '(norm_array == -1)\n', (2181, 2199), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np from scipy import stats from scipy.stats import spearmanr import scipy import statistics ##################################### #多読図書の誤差 gosa_t = [2.5936085940242886, 0.3649609355211716, -1.5684807178864082, 0.08092297493428235, 0.22543171481307445, -1.3691957161909167, -0.3474666004673743, 1.8252411101316153, 0.55875223949132, 0.5226005465508596, 0.3525884186972337, 0.3041152432565233, 0.8437276168620489, -0.9181574433326762, -0.7906627803715223] #一般図書の誤差 gosa_i = [0.10847348531766343, -0.5258853994325055, -1.2541770882612653, -0.5501409126883967, 0.7475673290440792, 0.11254455566384358, 0.18835643338229602, -0.12045902195570513, 1.0401978506856189, -0.3144134218532173, 0.5345536552762553, 0.6229265175369045, 0.8611454214443981, -0.48745911396300734, -0.7107419915524602, -1.6866471577013176, -1.0657173549843346] tadoku_np = np.array(gosa_t) ippan_np = np.array(gosa_i) #シャピロウィルク検定で正規性の確認 #w値とp_value shap_w_tadoku, shap_p_value_tadoku = stats.shapiro(tadoku_np) shap_w_ippan, shap_p_value_ippan = stats.shapiro(ippan_np) #F検定で等分散性の確認 fkentei_w, fkentei_p_value = scipy.stats.bartlett(tadoku_np,ippan_np) print("正規性p値", shap_p_value_tadoku, shap_p_value_ippan) print("等分散性p値", fkentei_p_value) #p_valueが0.05以上なら,帰無仮説が採択→正規性がある if (shap_p_value_tadoku >= 0.05) and (shap_p_value_ippan >= 0.05) : print("正規性があるといえる") #p_valueが0.05以上なら,帰無仮説が採択→等分散である if fkentei_p_value>= 0.05: #正規性を示し,等分散性である #スチューデントのt検定 stu_w, stu_p = stats.ttest_ind(tadoku_np, ippan_np) #スチューデント検定のpが0.05以上なら,帰無仮説は採択→2郡間には差がない→多読図書と一般図書を一緒に考えられる if stu_p >= 0.05: print("2郡間に差があるとはいえない", stu_p) else: print("2郡間に差がある", stu_p) #p_valueが0.05以下なら,帰無仮説が棄却→等分散でない else: #ウェルチのt検定 wel_w, wel_p = stats.ttest_ind(tadoku_np, ippan_np, equal_var=False) #ウェルチのt検定のpが0.05以上なら,帰無仮説は採択→2郡間には差がない→多読図書と一般図書を一緒に考えられる if wel_p >= 0.05: print("2郡間に差があるとはいえない", wel_p) #ウェルチのt検定のpが0.05以下なら,帰無仮説は棄却→2郡間には差がある→多読図書と一般図書を一緒に考えられない else: print("2郡間に差がある", wel_p) #p_valueが0.05以下なら,帰無仮説が棄却→正規性がない else: print("正規性がない") #マン・ホイットニー検定 man_w, man_p = stats.mannwhitneyu(tadoku_np, ippan_np, alternative='two-sided') #マン・ホイットニー検定のpが0.05以上なら,帰無仮説は採択→2郡間には差がない→多読図書と一般図書を一緒に考えられる if man_p >= 0.05: print("2郡間に差があるとはいえない", man_p) #マン・ホイットニー検定のpが0.05以下なら,帰無仮説は棄却→2郡間には差がある→多読図書と一般図書を一緒に考えられない else: print("2郡間に差がある", wel_p) print(statistics.mean(gosa_t)) print(statistics.mean(gosa_i)) import scipy.stats as st MU = abs(statistics.mean(gosa_t)-statistics.mean(gosa_i)) SE = MU/stu_w DF = len(gosa_t)+len(gosa_i)-2 CI = st.t.interval( alpha=0.95, loc=MU, scale=SE, df=DF ) print('対応なしt検定') print(f'p値 = {stu_p:.3f}') print(f't値 = {stu_w:.2f}') print(f'平均値の差 = {MU:.2f}') print(f'差の標準誤差 = {SE:.2f}') print(f'平均値の差の95%信頼区間CI = [{CI[0]:.2f} , {CI[1]:.2f}]')
[ "statistics.mean", "scipy.stats.bartlett", "scipy.stats.t.interval", "numpy.array", "scipy.stats.ttest_ind", "scipy.stats.mannwhitneyu", "scipy.stats.shapiro" ]
[((897, 913), 'numpy.array', 'np.array', (['gosa_t'], {}), '(gosa_t)\n', (905, 913), True, 'import numpy as np\n'), ((925, 941), 'numpy.array', 'np.array', (['gosa_i'], {}), '(gosa_i)\n', (933, 941), True, 'import numpy as np\n'), ((1015, 1039), 'scipy.stats.shapiro', 'stats.shapiro', (['tadoku_np'], {}), '(tadoku_np)\n', (1028, 1039), False, 'from scipy import stats\n'), ((1075, 1098), 'scipy.stats.shapiro', 'stats.shapiro', (['ippan_np'], {}), '(ippan_np)\n', (1088, 1098), False, 'from scipy import stats\n'), ((1143, 1184), 'scipy.stats.bartlett', 'scipy.stats.bartlett', (['tadoku_np', 'ippan_np'], {}), '(tadoku_np, ippan_np)\n', (1163, 1184), False, 'import scipy\n'), ((2817, 2867), 'scipy.stats.t.interval', 'st.t.interval', ([], {'alpha': '(0.95)', 'loc': 'MU', 'scale': 'SE', 'df': 'DF'}), '(alpha=0.95, loc=MU, scale=SE, df=DF)\n', (2830, 2867), True, 'import scipy.stats as st\n'), ((2306, 2370), 'scipy.stats.mannwhitneyu', 'stats.mannwhitneyu', (['tadoku_np', 'ippan_np'], {'alternative': '"""two-sided"""'}), "(tadoku_np, ippan_np, alternative='two-sided')\n", (2324, 2370), False, 'from scipy import stats\n'), ((2625, 2648), 'statistics.mean', 'statistics.mean', (['gosa_t'], {}), '(gosa_t)\n', (2640, 2648), False, 'import statistics\n'), ((2656, 2679), 'statistics.mean', 'statistics.mean', (['gosa_i'], {}), '(gosa_i)\n', (2671, 2679), False, 'import statistics\n'), ((1539, 1575), 'scipy.stats.ttest_ind', 'stats.ttest_ind', (['tadoku_np', 'ippan_np'], {}), '(tadoku_np, ippan_np)\n', (1554, 1575), False, 'from scipy import stats\n'), ((1889, 1942), 'scipy.stats.ttest_ind', 'stats.ttest_ind', (['tadoku_np', 'ippan_np'], {'equal_var': '(False)'}), '(tadoku_np, ippan_np, equal_var=False)\n', (1904, 1942), False, 'from scipy import stats\n'), ((2717, 2740), 'statistics.mean', 'statistics.mean', (['gosa_t'], {}), '(gosa_t)\n', (2732, 2740), False, 'import statistics\n'), ((2741, 2764), 'statistics.mean', 'statistics.mean', (['gosa_i'], {}), '(gosa_i)\n', (2756, 2764), False, 'import statistics\n')]
import pickle import json import argparse import cv2 import os import numpy as np import torch import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.patches as patches import matplotlib.lines as lines from tqdm import tqdm import _init_paths from core.config import cfg from datasets_rel.pytorch_misc import intersect_2d, argsort_desc from functools import reduce #from utils.boxes import bbox_overlaps #from utils_rel.boxes_rel import boxes_union from graphviz import Digraph, Graph import seaborn as sns #sns.set_theme() parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument( '--output_dir', help='output directory to save the testing results. If not provided, ' 'defaults to [args.load_ckpt|args.load_detectron]/../test.') parser.add_argument( '--filename', help='Visualization file', default='rel_detection_range_12_15', type=str) args = parser.parse_args() strfname = args.filename.split('_') st,ed = strfname[-2], strfname[-1] st,ed = int(st), int(ed) def visualize_feature_map(feat_map, save_path, fname='feat_map'): fig = plt.figure() plt.imshow(feat_map) plt.axis('off') plt.savefig(os.path.join(save_path, fname+'.png')) plt.close(fig) def vis_box(img, box, save_path, fname='obj_box'): fig = plt.figure() ax = plt.gca() ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) plt.imshow(img) plt.axis('off') for i in range(len(box)): x, y, x1, y1 = box[i, 1:].astype(np.int) srect = plt.Rectangle((x,y),x1-x,y1-y, fill=False, edgecolor='b', linewidth=1) ax.add_patch(srect) #ax.text(x, y, # color='white', # bbox=dict(facecolor='orange', alpha=0.5, pad=0, edgecolor='none')) plt.savefig(os.path.join(save_path, fname+'.png')) plt.close(fig) with open(os.path.join(args.output_dir, args.filename+'.pkl'), 'rb') as f: ret = pickle.load(f) f.close() for ii, return_dict2 in enumerate(ret): if return_dict2 is None: continue blob_conv = return_dict2['blob_conv'] feat_map = return_dict2['feat_map'] temporal_blob_conv_prd = return_dict2['temporal_blob_conv_prd'] batch_A = return_dict2['batch_A'] batch_non_leaf_bbox = return_dict2['batch_non_leaf_bbox'] spatio_feat1 = return_dict2['spatio_feat1'] spatio_feat2 = return_dict2['spatio_feat2'] if batch_non_leaf_bbox is not None: batch_non_leaf_bbox = batch_non_leaf_bbox.data.cpu().numpy() if return_dict2['roi'] is not None: roi = return_dict2['roi'].data.cpu().numpy() else: roi = None im = return_dict2['im'] save_dir = os.path.join(args.output_dir, str(ii+st)) if not os.path.exists(os.path.join(args.output_dir, str(ii+st))): os.mkdir(save_dir) else: continue all_frames = return_dict2['all_frames'] if isinstance(blob_conv, list): for i,v in enumerate(blob_conv): visualize_feature_map(v, save_dir, fname='obj_feat_map'+str(i)) else: visualize_feature_map(blob_conv, save_dir, fname='obj_feat_map') im = im[:,:,::-1] visualize_feature_map(im, save_dir, fname='origin') if all_frames is not None: all_frames = all_frames.squeeze(0) channel_swap = (0, 2, 3, 1) all_frames = all_frames.transpose(channel_swap) frame_sampled = all_frames[0] + cfg.PIXEL_MEANS frame_sampled = frame_sampled.astype(np.int) frame_sampled = frame_sampled[:,:,::-1] visualize_feature_map(frame_sampled, save_dir, fname='frame_sampled') visualize_feature_map(feat_map, save_dir) if temporal_blob_conv_prd is not None: for i in range(len(temporal_blob_conv_prd)): visualize_feature_map(temporal_blob_conv_prd[i], save_dir, fname='temporal_feat_map'+str(i)) if roi is not None: vis_box(im, roi, save_dir) if batch_A is not None: rid_f2s = set() dot = Graph(filename=('tree')) dot.body.append('size="16,16"') #dot.body.append('rankdir="LR"') son, fa = np.where(batch_A > 0) for i in range(len(batch_A)): dot.node(str(i), str(i), color='black') for i in range(len(fa)): if (son[i], fa[i]) in rid_f2s or (son[i], fa[i]) in rid_f2s: continue dot.edge(str(son[i]), str(fa[i]), color='black') rid_f2s.add((son[i], fa[i])) dot.render(os.path.join(save_dir, 'tree'), cleanup=True) for i in range(len(batch_A)): if i < len(roi): x, y, x1, y1 = roi[i, 1:].astype(np.int) else: x, y, x1, y1 = batch_non_leaf_bbox[i-len(roi), 1:].astype(np.int) subim = im[y:y1, x:x1, :] if not os.path.exists(os.path.join(save_dir, 'subim')): os.mkdir(os.path.join(save_dir, 'subim')) visualize_feature_map(subim, os.path.join(save_dir, 'subim'), str(i)) if not os.path.exists(os.path.join(save_dir, 'subject_vis_branch')): os.mkdir(os.path.join(save_dir, 'subject_vis_branch')) for i in range(len(spatio_feat1)): print(spatio_feat1[i]) print(spatio_feat2[i]) print() #visualize_feature_map(spatio_feat1[i], os.path.join(save_dir, 'subject_vis_branch'), str(i)) #if not os.path.exists(os.path.join(save_dir, 'object_vis_branch')): # os.mkdir(os.path.join(save_dir, 'object_vis_branch')) #for i in range(len(spatio_feat2)): # visualize_feature_map(spatio_feat2[i], os.path.join(save_dir, 'object_vis_branch'), str(i))
[ "matplotlib.pyplot.imshow", "argparse.ArgumentParser", "numpy.where", "matplotlib.pyplot.gca", "pickle.load", "os.path.join", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "os.mkdir", "graphviz.Graph", "matplotlib.pyplot.Rectangle", "matplotlib.pyplot.axis" ]
[((567, 631), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test a Fast R-CNN network"""'}), "(description='Test a Fast R-CNN network')\n", (590, 631), False, 'import argparse\n'), ((1142, 1154), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1152, 1154), True, 'import matplotlib.pyplot as plt\n'), ((1159, 1179), 'matplotlib.pyplot.imshow', 'plt.imshow', (['feat_map'], {}), '(feat_map)\n', (1169, 1179), True, 'import matplotlib.pyplot as plt\n'), ((1184, 1199), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1192, 1199), True, 'import matplotlib.pyplot as plt\n'), ((1259, 1273), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (1268, 1273), True, 'import matplotlib.pyplot as plt\n'), ((1336, 1348), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1346, 1348), True, 'import matplotlib.pyplot as plt\n'), ((1358, 1367), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1365, 1367), True, 'import matplotlib.pyplot as plt\n'), ((1538, 1553), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (1548, 1553), True, 'import matplotlib.pyplot as plt\n'), ((1558, 1573), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1566, 1573), True, 'import matplotlib.pyplot as plt\n'), ((1958, 1972), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (1967, 1972), True, 'import matplotlib.pyplot as plt\n'), ((2072, 2086), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2083, 2086), False, 'import pickle\n'), ((1216, 1255), 'os.path.join', 'os.path.join', (['save_path', "(fname + '.png')"], {}), "(save_path, fname + '.png')\n", (1228, 1255), False, 'import os\n'), ((1669, 1746), 'matplotlib.pyplot.Rectangle', 'plt.Rectangle', (['(x, y)', '(x1 - x)', '(y1 - y)'], {'fill': '(False)', 'edgecolor': '"""b"""', 'linewidth': '(1)'}), "((x, y), x1 - x, y1 - y, fill=False, edgecolor='b', linewidth=1)\n", (1682, 1746), True, 'import matplotlib.pyplot as plt\n'), ((1915, 1954), 'os.path.join', 'os.path.join', (['save_path', "(fname + '.png')"], {}), "(save_path, fname + '.png')\n", (1927, 1954), False, 'import os\n'), ((1997, 2050), 'os.path.join', 'os.path.join', (['args.output_dir', "(args.filename + '.pkl')"], {}), "(args.output_dir, args.filename + '.pkl')\n", (2009, 2050), False, 'import os\n'), ((2932, 2950), 'os.mkdir', 'os.mkdir', (['save_dir'], {}), '(save_dir)\n', (2940, 2950), False, 'import os\n'), ((4177, 4199), 'graphviz.Graph', 'Graph', ([], {'filename': '"""tree"""'}), "(filename='tree')\n", (4182, 4199), False, 'from graphviz import Digraph, Graph\n'), ((4301, 4322), 'numpy.where', 'np.where', (['(batch_A > 0)'], {}), '(batch_A > 0)\n', (4309, 4322), True, 'import numpy as np\n'), ((4662, 4692), 'os.path.join', 'os.path.join', (['save_dir', '"""tree"""'], {}), "(save_dir, 'tree')\n", (4674, 4692), False, 'import os\n'), ((5239, 5283), 'os.path.join', 'os.path.join', (['save_dir', '"""subject_vis_branch"""'], {}), "(save_dir, 'subject_vis_branch')\n", (5251, 5283), False, 'import os\n'), ((5303, 5347), 'os.path.join', 'os.path.join', (['save_dir', '"""subject_vis_branch"""'], {}), "(save_dir, 'subject_vis_branch')\n", (5315, 5347), False, 'import os\n'), ((5167, 5198), 'os.path.join', 'os.path.join', (['save_dir', '"""subim"""'], {}), "(save_dir, 'subim')\n", (5179, 5198), False, 'import os\n'), ((5013, 5044), 'os.path.join', 'os.path.join', (['save_dir', '"""subim"""'], {}), "(save_dir, 'subim')\n", (5025, 5044), False, 'import os\n'), ((5072, 5103), 'os.path.join', 'os.path.join', (['save_dir', '"""subim"""'], {}), "(save_dir, 'subim')\n", (5084, 5103), False, 'import os\n')]
import matplotlib.pyplot as plt import numpy as np import pandas as pd import sklearn.linear_model oecd = pd.read_csv(r'/Users/pariszhang/Desktop/Data/oecd/OECDBLI2017cleanedcsv.csv') life_satisfaction = oecd['Life satisfaction as avg score'] personal_earnings = oecd['Personal earnings in usd'] d = {'Life Satisfaction': oecd['Life satisfaction as avg score'], 'Personal Earnings': oecd['Personal earnings in usd']} stats = pd.DataFrame(data=d) x = np.array(stats['Life Satisfaction']) y = np.array(stats['Personal Earnings']) model = sklearn.linear_model.LinearRegression() model.fit(x.reshape(-1, 1), y) x_new = [[10]] print(model.predict(x_new))
[ "pandas.DataFrame", "numpy.array", "pandas.read_csv" ]
[((107, 183), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/pariszhang/Desktop/Data/oecd/OECDBLI2017cleanedcsv.csv"""'], {}), "('/Users/pariszhang/Desktop/Data/oecd/OECDBLI2017cleanedcsv.csv')\n", (118, 183), True, 'import pandas as pd\n'), ((438, 458), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd'}), '(data=d)\n', (450, 458), True, 'import pandas as pd\n'), ((464, 500), 'numpy.array', 'np.array', (["stats['Life Satisfaction']"], {}), "(stats['Life Satisfaction'])\n", (472, 500), True, 'import numpy as np\n'), ((505, 541), 'numpy.array', 'np.array', (["stats['Personal Earnings']"], {}), "(stats['Personal Earnings'])\n", (513, 541), True, 'import numpy as np\n')]
import math import numpy as np from ... import IntegerProgram, LinearProgram from unittest import TestCase, main class TestRelax(TestCase): def test_relax(self) -> None: A = np.array([ [1, 2, 3, 4], [3, 5, 7, 9] ]) b = np.array([-9, 7]) c = np.array([1, 7, 1, 5]) z = 25 ip = IntegerProgram(A, b, c, z, "min", ["<=", ">="], [2], [1]) lp = ip.relax() self.assertIsInstance(lp, LinearProgram, "Should be a linear program.") self.assertTrue(np.allclose(lp.A, A), "Should have the same constraint matrix.") self.assertTrue(np.allclose(lp.b, b), "Should have the same constraint vector.") self.assertTrue(np.allclose(lp.c, c), "Should have the same coefficient vector.") self.assertTrue(math.isclose(lp.z, z), "Should have the same constant.") self.assertEqual(lp.inequalities, ip.inequalities, "Should have the same inequalities.") self.assertEqual(lp.objective, ip.objective, "Should have the same objective.") self.assertEqual(lp.negative_variables, ip.negative_variables, "Should have the same negative variables.") self.assertEqual(lp.free_variables, ip.free_variables, "Should have the same free variables.") if __name__ == "__main__": main()
[ "unittest.main", "numpy.array", "numpy.allclose", "math.isclose" ]
[((1302, 1308), 'unittest.main', 'main', ([], {}), '()\n', (1306, 1308), False, 'from unittest import TestCase, main\n'), ((188, 226), 'numpy.array', 'np.array', (['[[1, 2, 3, 4], [3, 5, 7, 9]]'], {}), '([[1, 2, 3, 4], [3, 5, 7, 9]])\n', (196, 226), True, 'import numpy as np\n'), ((273, 290), 'numpy.array', 'np.array', (['[-9, 7]'], {}), '([-9, 7])\n', (281, 290), True, 'import numpy as np\n'), ((303, 325), 'numpy.array', 'np.array', (['[1, 7, 1, 5]'], {}), '([1, 7, 1, 5])\n', (311, 325), True, 'import numpy as np\n'), ((542, 562), 'numpy.allclose', 'np.allclose', (['lp.A', 'A'], {}), '(lp.A, A)\n', (553, 562), True, 'import numpy as np\n'), ((631, 651), 'numpy.allclose', 'np.allclose', (['lp.b', 'b'], {}), '(lp.b, b)\n', (642, 651), True, 'import numpy as np\n'), ((720, 740), 'numpy.allclose', 'np.allclose', (['lp.c', 'c'], {}), '(lp.c, c)\n', (731, 740), True, 'import numpy as np\n'), ((810, 831), 'math.isclose', 'math.isclose', (['lp.z', 'z'], {}), '(lp.z, z)\n', (822, 831), False, 'import math\n')]
#!/usr/bin/env python """ The Monty Hall problem simulator parameterizable with soops. https://en.wikipedia.org/wiki/Monty_Hall_problem Examples -------- - Direct runs:: python examples/monty_hall.py -h python examples/monty_hall.py output python examples/monty_hall.py --switch output python examples/monty_hall.py --num=10000 output - A parametric study:: soops-run -r 1 -n 3 -c='--switch + --seed' -o output "python='python3', output_dir='output/study/%s', --num=[100,1000,10000], --repeat=[10,20], --switch=['@undefined', '@defined', '@undefined', '@defined'], --seed=['@undefined', '@undefined', 12345, 12345], --host=['random', 'first'], --silent=@defined, --no-show=@defined" examples/monty_hall.py soops-info examples/monty_hall.py -e output/study/00* soops-scoop examples/monty_hall.py output/study/ -s rdir -o output/study soops-scoop examples/monty_hall.py output/study/ -s rdir -o output/study -r --plugin-args=plot_win_rates={colormap_name='plasma'} soops-scoop examples/monty_hall.py output/study/ -o output/study -r --no-plugins --shell - Use --generate-pars instead of listing values of --seed and --switch:: soops-run -r 1 -n 3 -c='--switch + --seed' -o output/study2 "python='python3', output_dir='output/study2/%s', --num=[100,1000,10000], --repeat=[10,20], --switch=@generate, --seed=@generate, --host=['random', 'first'], --silent=@defined, --no-show=@defined" --generate-pars="function=generate_seed_switch, seeds=['@undefined', 12345], switches=['@undefined', '@defined']" examples/monty_hall.py soops-scoop examples/monty_hall.py output/study2/0* -s rdir -o output/study2 - Explore the studies parameters:: soops-find output/study soops-find output/study -q "num==1000 & repeat==20 & seed==12345" """ from argparse import ArgumentParser, RawDescriptionHelpFormatter import os from functools import partial from itertools import product import numpy as np import matplotlib.pyplot as plt import soops as so import soops.scoop_outputs as sc from soops import output def get_run_info(): # script_dir is added by soops-run, it is the normalized path to # this script. run_cmd = """ {python} {script_dir}/monty_hall.py {output_dir} """ run_cmd = ' '.join(run_cmd.split()) # Arguments allowed to be missing in soops-run calls. opt_args = { '--num' : '--num={--num}', '--repeat' : '--repeat={--repeat}', '--switch' : '--switch', '--host' : '--host={--host}', '--seed' : '--seed={--seed}', '--plot-opts' : '--plot-opts={--plot-opts}', '--no-show' : '--no-show', '--silent' : '--silent', } output_dir_key = 'output_dir' is_finished_basename = 'wins.png' return run_cmd, opt_args, output_dir_key, is_finished_basename def generate_seed_switch(args, gkeys, dconf, options): """ Parameters ---------- args : Struct The arguments passed from the command line. gkeys : list The list of option keys to generate. dconf : dict The parsed parameters of the parametric study. options : Namespace The soops-run command line options. """ seeds, switches = zip(*product(args.seeds, args.switches)) gconf = {'--seed' : list(seeds), '--switch' : list(switches)} return gconf def get_scoop_info(): info = [ ('options.txt', partial( sc.load_split_options, split_keys=None, ), True), ('output_log.txt', scrape_output), ] return info def scrape_output(filename, rdata=None): out = {} with open(filename, 'r') as fd: repeat = rdata['repeat'] for ii in range(4): next(fd) elapsed = [] win_rate = [] for ii in range(repeat): line = next(fd).split() elapsed.append(float(line[-1])) line = next(fd).split() win_rate.append(float(line[-1])) out['elapsed'] = np.array(elapsed) out['win_rate'] = np.array(win_rate) return out def get_plugin_info(): from soops.plugins import show_figures info = [plot_win_rates, show_figures] return info def plot_win_rates(df, data=None, colormap_name='viridis'): import soops.plot_selected as sps df = df.copy() df['seed'] = df['seed'].where(df['seed'].notnull(), -1) uniques = sc.get_uniques(df, [key for key in data.multi_par_keys if key not in ['output_dir']]) output('parameterization:') for key, val in uniques.items(): output(key, val) selected = sps.normalize_selected(uniques) styles = {key : {} for key in selected.keys()} styles['seed'] = {'alpha' : [0.9, 0.1]} styles['num'] = {'color' : colormap_name} styles['repeat'] = {'lw' : np.linspace(3, 2, len(selected.get('repeat', [1])))} styles['host'] = {'ls' : ['-', ':']} styles['switch'] = {'marker' : ['x', 'o'], 'mfc' : 'None', 'ms' : 10} styles = sps.setup_plot_styles(selected, styles) fig, ax = plt.subplots(figsize=(8, 8)) sps.plot_selected(ax, df, 'win_rate', selected, {}, styles) ax.set_xlabel('simulation number') ax.set_ylabel('win rate') fig.tight_layout() fig.savefig(os.path.join(data.output_dir, 'win_rates.png')) return data helps = { 'output_dir' : 'output directory', 'switch' : ('if given, the contestant always switches the door, otherwise never' ' switches'), 'host' : 'the host strategy for opening doors', 'num' : 'the number of rounds in a single simulation [default: %(default)s]', 'repeat' : 'the number of simulations [default: %(default)s]', 'seed' : 'if given, the random seed is fixed to the given value', 'plot_opts' : 'matplotlib plot() options [default: "{}"]', 'no_show' : 'do not call matplotlib show()', 'silent' : 'do not print messages to screen', } def main(): default_plot_opts = ("linewidth=3,alpha=0.5") helps['plot_opts'] = helps['plot_opts'].format(default_plot_opts) parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--switch', action='store_true', dest='switch', default=False, help=helps['switch']) parser.add_argument('--host', action='store', dest='host', choices=['random', 'first'], default='random', help=helps['host']) parser.add_argument('--num', metavar='int', type=int, action='store', dest='num', default=100, help=helps['num']) parser.add_argument('--repeat', metavar='int', type=int, action='store', dest='repeat', default=5, help=helps['repeat']) parser.add_argument('--seed', metavar='int', type=int, action='store', dest='seed', default=None, help=helps['seed']) parser.add_argument('--plot-opts', metavar='dict-like', action='store', dest='plot_opts', default=default_plot_opts, help=helps['plot_opts']) parser.add_argument('-n', '--no-show', action='store_false', dest='show', default=True, help=helps['no_show']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) options = parser.parse_args() output_dir = options.output_dir output.prefix = 'monty_hall:' filename = os.path.join(output_dir, 'output_log.txt') so.ensure_path(filename) output.set_output(filename=filename, combined=options.silent == False) options.plot_opts = so.parse_as_dict(options.plot_opts) filename = os.path.join(output_dir, 'options.txt') so.save_options(filename, [('options', vars(options))], quote_command_line=True) output('num:', options.num) output('repeat:', options.repeat) output('switch:', options.switch) output('host strategy:', options.host) switch = options.switch host_strategy = options.host histories = [] for ir in range(options.repeat): if options.seed is not None: np.random.seed(options.seed) timer = so.Timer().start() history = [] choices = {0, 1, 2} for ii in range(options.num): doors = [False] * 3 car = np.random.randint(0, 3) doors[car] = True choice1 = np.random.randint(0, 3) can_host = sorted(choices.difference([car, choice1])) if len(can_host) == 2: # choice1 is correct. if host_strategy == 'random': host = can_host[np.random.randint(0, 2)] else: host = can_host[0] else: host = can_host[0] if switch: choice2 = choices.difference([choice1, host]).pop() else: choice2 = choice1 win = doors[choice2] history.append(win) output('elapsed:', timer.stop()) output('win rate:', sum(history) / options.num) histories.append(history) wins = np.cumsum(histories, axis=1) fig, ax = plt.subplots() colors = plt.cm.viridis(np.linspace(0, 1, options.repeat)) ax.set_prop_cycle( plt.cycler('color', colors) ) ax.plot(wins.T, **options.plot_opts) ax.set_xlabel('round') ax.set_ylabel('wins') ax.set_title('switch: {}, host strategy: {}, num: {}, repeat: {}, seed: {}' .format(options.switch, options.host, options.num, options.repeat, options.seed)) plt.tight_layout() fig.savefig(os.path.join(output_dir, 'wins.png'), bbox_inches='tight') if options.show: plt.show() if __name__ == '__main__': main()
[ "numpy.array", "soops.output", "soops.plot_selected.setup_plot_styles", "soops.parse_as_dict", "itertools.product", "numpy.linspace", "numpy.random.seed", "soops.output.set_output", "soops.ensure_path", "soops.scoop_outputs.get_uniques", "soops.Timer", "matplotlib.pyplot.show", "soops.plot_s...
[((4366, 4456), 'soops.scoop_outputs.get_uniques', 'sc.get_uniques', (['df', "[key for key in data.multi_par_keys if key not in ['output_dir']]"], {}), "(df, [key for key in data.multi_par_keys if key not in [\n 'output_dir']])\n", (4380, 4456), True, 'import soops.scoop_outputs as sc\n'), ((4490, 4517), 'soops.output', 'output', (['"""parameterization:"""'], {}), "('parameterization:')\n", (4496, 4517), False, 'from soops import output\n'), ((4596, 4627), 'soops.plot_selected.normalize_selected', 'sps.normalize_selected', (['uniques'], {}), '(uniques)\n', (4618, 4627), True, 'import soops.plot_selected as sps\n'), ((5026, 5065), 'soops.plot_selected.setup_plot_styles', 'sps.setup_plot_styles', (['selected', 'styles'], {}), '(selected, styles)\n', (5047, 5065), True, 'import soops.plot_selected as sps\n'), ((5081, 5109), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (5093, 5109), True, 'import matplotlib.pyplot as plt\n'), ((5114, 5173), 'soops.plot_selected.plot_selected', 'sps.plot_selected', (['ax', 'df', '"""win_rate"""', 'selected', '{}', 'styles'], {}), "(ax, df, 'win_rate', selected, {}, styles)\n", (5131, 5173), True, 'import soops.plot_selected as sps\n'), ((7782, 7824), 'os.path.join', 'os.path.join', (['output_dir', '"""output_log.txt"""'], {}), "(output_dir, 'output_log.txt')\n", (7794, 7824), False, 'import os\n'), ((7829, 7853), 'soops.ensure_path', 'so.ensure_path', (['filename'], {}), '(filename)\n', (7843, 7853), True, 'import soops as so\n'), ((7858, 7928), 'soops.output.set_output', 'output.set_output', ([], {'filename': 'filename', 'combined': '(options.silent == False)'}), '(filename=filename, combined=options.silent == False)\n', (7875, 7928), False, 'from soops import output\n'), ((7954, 7989), 'soops.parse_as_dict', 'so.parse_as_dict', (['options.plot_opts'], {}), '(options.plot_opts)\n', (7970, 7989), True, 'import soops as so\n'), ((8005, 8044), 'os.path.join', 'os.path.join', (['output_dir', '"""options.txt"""'], {}), "(output_dir, 'options.txt')\n", (8017, 8044), False, 'import os\n'), ((8152, 8179), 'soops.output', 'output', (['"""num:"""', 'options.num'], {}), "('num:', options.num)\n", (8158, 8179), False, 'from soops import output\n'), ((8184, 8217), 'soops.output', 'output', (['"""repeat:"""', 'options.repeat'], {}), "('repeat:', options.repeat)\n", (8190, 8217), False, 'from soops import output\n'), ((8222, 8255), 'soops.output', 'output', (['"""switch:"""', 'options.switch'], {}), "('switch:', options.switch)\n", (8228, 8255), False, 'from soops import output\n'), ((8260, 8298), 'soops.output', 'output', (['"""host strategy:"""', 'options.host'], {}), "('host strategy:', options.host)\n", (8266, 8298), False, 'from soops import output\n'), ((9470, 9498), 'numpy.cumsum', 'np.cumsum', (['histories'], {'axis': '(1)'}), '(histories, axis=1)\n', (9479, 9498), True, 'import numpy as np\n'), ((9514, 9528), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9526, 9528), True, 'import matplotlib.pyplot as plt\n'), ((9960, 9978), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9976, 9978), True, 'import matplotlib.pyplot as plt\n'), ((3966, 3983), 'numpy.array', 'np.array', (['elapsed'], {}), '(elapsed)\n', (3974, 3983), True, 'import numpy as np\n'), ((4010, 4028), 'numpy.array', 'np.array', (['win_rate'], {}), '(win_rate)\n', (4018, 4028), True, 'import numpy as np\n'), ((4563, 4579), 'soops.output', 'output', (['key', 'val'], {}), '(key, val)\n', (4569, 4579), False, 'from soops import output\n'), ((5282, 5328), 'os.path.join', 'os.path.join', (['data.output_dir', '"""win_rates.png"""'], {}), "(data.output_dir, 'win_rates.png')\n", (5294, 5328), False, 'import os\n'), ((9557, 9590), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'options.repeat'], {}), '(0, 1, options.repeat)\n', (9568, 9590), True, 'import numpy as np\n'), ((9623, 9650), 'matplotlib.pyplot.cycler', 'plt.cycler', (['"""color"""', 'colors'], {}), "('color', colors)\n", (9633, 9650), True, 'import matplotlib.pyplot as plt\n'), ((9995, 10031), 'os.path.join', 'os.path.join', (['output_dir', '"""wins.png"""'], {}), "(output_dir, 'wins.png')\n", (10007, 10031), False, 'import os\n'), ((10084, 10094), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10092, 10094), True, 'import matplotlib.pyplot as plt\n'), ((3193, 3227), 'itertools.product', 'product', (['args.seeds', 'args.switches'], {}), '(args.seeds, args.switches)\n', (3200, 3227), False, 'from itertools import product\n'), ((3372, 3419), 'functools.partial', 'partial', (['sc.load_split_options'], {'split_keys': 'None'}), '(sc.load_split_options, split_keys=None)\n', (3379, 3419), False, 'from functools import partial\n'), ((8466, 8494), 'numpy.random.seed', 'np.random.seed', (['options.seed'], {}), '(options.seed)\n', (8480, 8494), True, 'import numpy as np\n'), ((8668, 8691), 'numpy.random.randint', 'np.random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (8685, 8691), True, 'import numpy as np\n'), ((8744, 8767), 'numpy.random.randint', 'np.random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (8761, 8767), True, 'import numpy as np\n'), ((8512, 8522), 'soops.Timer', 'so.Timer', ([], {}), '()\n', (8520, 8522), True, 'import soops as so\n'), ((8973, 8996), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {}), '(0, 2)\n', (8990, 8996), True, 'import numpy as np\n')]
""" Created on 08 Okt. 2021 @author: <NAME> This example shows how you can use MiP-EGO in order to perform hyper-parameter optimization for machine learning tasks. """ #import packages from sklearn.datasets import load_iris from sklearn.svm import SVC from sklearn.model_selection import cross_val_score, KFold import numpy as np #import our package, the surrogate model and the search space classes from mipego import ParallelBO from mipego.Surrogate import RandomForest from mipego.SearchSpace import ContinuousSpace, NominalSpace, OrdinalSpace # Load the dataset iris = load_iris() X_iris = iris.data y_iris = iris.target # First we need to define the Search Space # the search space consists of one continues variable # one ordinal (integer) variable # and two categorical (nominal) variables. Cvar = ContinuousSpace([1.0, 20.0],'C') # one integer variable with label C degree = OrdinalSpace([2,6], 'degree') gamma = NominalSpace(['scale', 'auto'], 'gamma') kernel = NominalSpace(['linear', 'poly', 'rbf', 'sigmoid'], 'kernel') #the complete search space is just the sum of the parameter spaces search_space = Cvar + gamma + degree + kernel #now we define the objective function (the model optimization) def train_model(c): #define the model # We will use a Support Vector Classifier svm = SVC(kernel=c['kernel'], gamma=c['gamma'], C=c['C'], degree=c['degree']) cv = KFold(n_splits=4, shuffle=True, random_state=42) # Nested CV with parameter optimization cv_score = cross_val_score(svm, X=X_iris, y=y_iris, cv=cv) #by default mip-ego minimises, so we reverse the accuracy return -1 * np.mean(cv_score) model = RandomForest(levels=search_space.levels) opt = ParallelBO( search_space=search_space, obj_fun=train_model, model=model, max_FEs=6, DoE_size=5, # the initial DoE size eval_type='dict', acquisition_fun='MGFI', acquisition_par={'t' : 2}, n_job=3, # number of processes n_point=3, # number of the candidate solution proposed in each iteration verbose=True # turn this off, if you prefer no output ) xopt, fopt, stop_dict = opt.run() print('xopt: {}'.format(xopt)) print('fopt: {}'.format(fopt)) print('stop criteria: {}'.format(stop_dict))
[ "sklearn.datasets.load_iris", "mipego.ParallelBO", "sklearn.svm.SVC", "numpy.mean", "mipego.SearchSpace.NominalSpace", "sklearn.model_selection.cross_val_score", "mipego.SearchSpace.ContinuousSpace", "sklearn.model_selection.KFold", "mipego.Surrogate.RandomForest", "mipego.SearchSpace.OrdinalSpace...
[((578, 589), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (587, 589), False, 'from sklearn.datasets import load_iris\n'), ((811, 844), 'mipego.SearchSpace.ContinuousSpace', 'ContinuousSpace', (['[1.0, 20.0]', '"""C"""'], {}), "([1.0, 20.0], 'C')\n", (826, 844), False, 'from mipego.SearchSpace import ContinuousSpace, NominalSpace, OrdinalSpace\n'), ((889, 919), 'mipego.SearchSpace.OrdinalSpace', 'OrdinalSpace', (['[2, 6]', '"""degree"""'], {}), "([2, 6], 'degree')\n", (901, 919), False, 'from mipego.SearchSpace import ContinuousSpace, NominalSpace, OrdinalSpace\n'), ((928, 968), 'mipego.SearchSpace.NominalSpace', 'NominalSpace', (["['scale', 'auto']", '"""gamma"""'], {}), "(['scale', 'auto'], 'gamma')\n", (940, 968), False, 'from mipego.SearchSpace import ContinuousSpace, NominalSpace, OrdinalSpace\n'), ((979, 1039), 'mipego.SearchSpace.NominalSpace', 'NominalSpace', (["['linear', 'poly', 'rbf', 'sigmoid']", '"""kernel"""'], {}), "(['linear', 'poly', 'rbf', 'sigmoid'], 'kernel')\n", (991, 1039), False, 'from mipego.SearchSpace import ContinuousSpace, NominalSpace, OrdinalSpace\n'), ((1662, 1702), 'mipego.Surrogate.RandomForest', 'RandomForest', ([], {'levels': 'search_space.levels'}), '(levels=search_space.levels)\n', (1674, 1702), False, 'from mipego.Surrogate import RandomForest\n'), ((1709, 1913), 'mipego.ParallelBO', 'ParallelBO', ([], {'search_space': 'search_space', 'obj_fun': 'train_model', 'model': 'model', 'max_FEs': '(6)', 'DoE_size': '(5)', 'eval_type': '"""dict"""', 'acquisition_fun': '"""MGFI"""', 'acquisition_par': "{'t': 2}", 'n_job': '(3)', 'n_point': '(3)', 'verbose': '(True)'}), "(search_space=search_space, obj_fun=train_model, model=model,\n max_FEs=6, DoE_size=5, eval_type='dict', acquisition_fun='MGFI',\n acquisition_par={'t': 2}, n_job=3, n_point=3, verbose=True)\n", (1719, 1913), False, 'from mipego import ParallelBO\n'), ((1317, 1388), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': "c['kernel']", 'gamma': "c['gamma']", 'C': "c['C']", 'degree': "c['degree']"}), "(kernel=c['kernel'], gamma=c['gamma'], C=c['C'], degree=c['degree'])\n", (1320, 1388), False, 'from sklearn.svm import SVC\n'), ((1398, 1446), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(4)', 'shuffle': '(True)', 'random_state': '(42)'}), '(n_splits=4, shuffle=True, random_state=42)\n', (1403, 1446), False, 'from sklearn.model_selection import cross_val_score, KFold\n'), ((1507, 1554), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['svm'], {'X': 'X_iris', 'y': 'y_iris', 'cv': 'cv'}), '(svm, X=X_iris, y=y_iris, cv=cv)\n', (1522, 1554), False, 'from sklearn.model_selection import cross_val_score, KFold\n'), ((1634, 1651), 'numpy.mean', 'np.mean', (['cv_score'], {}), '(cv_score)\n', (1641, 1651), True, 'import numpy as np\n')]
""" ========= Plot Mesh ========= This example shows how to load an STL mesh. This example must be run from within the main folder because it uses a hard-coded path to the STL file. """ print(__doc__) import os import numpy as np import matplotlib.pyplot as plt from pytransform3d.transformations import plot_transform from pytransform3d.plot_utils import plot_mesh BASE_DIR = "test/test_data/" data_dir = BASE_DIR search_path = "." while (not os.path.exists(data_dir) and os.path.dirname(search_path) != "pytransform3d"): search_path = os.path.join(search_path, "..") data_dir = os.path.join(search_path, BASE_DIR) ax = plot_mesh( filename=os.path.join(data_dir, "cone.stl"), s=5 * np.ones(3), alpha=0.3) plot_transform(ax=ax, A2B=np.eye(4), s=0.3, lw=3) plt.show()
[ "os.path.exists", "numpy.eye", "numpy.ones", "os.path.join", "os.path.dirname", "matplotlib.pyplot.show" ]
[((785, 795), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (793, 795), True, 'import matplotlib.pyplot as plt\n'), ((553, 584), 'os.path.join', 'os.path.join', (['search_path', '""".."""'], {}), "(search_path, '..')\n", (565, 584), False, 'import os\n'), ((600, 635), 'os.path.join', 'os.path.join', (['search_path', 'BASE_DIR'], {}), '(search_path, BASE_DIR)\n', (612, 635), False, 'import os\n'), ((449, 473), 'os.path.exists', 'os.path.exists', (['data_dir'], {}), '(data_dir)\n', (463, 473), False, 'import os\n'), ((485, 513), 'os.path.dirname', 'os.path.dirname', (['search_path'], {}), '(search_path)\n', (500, 513), False, 'import os\n'), ((666, 700), 'os.path.join', 'os.path.join', (['data_dir', '"""cone.stl"""'], {}), "(data_dir, 'cone.stl')\n", (678, 700), False, 'import os\n'), ((761, 770), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (767, 770), True, 'import numpy as np\n'), ((712, 722), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (719, 722), True, 'import numpy as np\n')]
""" Code based on random_transform in keras.processing.image from 2016. (https://github.com/fchollet/keras) Keras copyright: All contributions by <NAME>: Copyright (c) 2015, <NAME>. All contributions by Google: Copyright (c) 2015, Google, Inc. All contributions by Microsoft: Copyright (c) 2017, Microsoft, Inc. All other contributions: Copyright (c) 2015-2017, the respective contributors. (All rights reserved by copyright holders of all contributions.) Modified: Copyright 2017, <NAME> Copyright 2016, <NAME> Copyright 2016, <NAME> """ import os import numpy as np import scipy.ndimage as ndi import SimpleITK as sitk """ Apply data augmentation to all images in an N-dimensional stack. Assumes the final two axes are spatial axes (not considering the channel axis). Arguments are as defined for image_random_transform. """ def image_stack_random_transform(x, *args, y=None, channel_axis=1, **kwargs): # Make sure these are numpy arrays. x_arr = np.array(x) if y is not None: y_arr = np.array(y) x_shape = list(x_arr.shape) y_shape = list(y_arr.shape) x_shape[channel_axis] = None y_shape[channel_axis] = None if x_shape!=y_shape: raise ValueError("Error: inputs x and y to " "image_stack_random_transform must have the same " "shape. Shapes are {} and {} for x, y." "".format(x_arr.shape, y_arr.shape)) # Move channel axis to just before spatial axes. std_channel_axis = x_arr.ndim-1-2 if channel_axis!=std_channel_axis: x_arr = np.moveaxis(x_arr, source=channel_axis, destination=std_channel_axis) if y is not None: x_arr = np.moveaxis(y_arr, source=channel_axis, destination=std_channel_axis) # Compute indices to iterate over (everything except channel and spatial). x_indices = np.ndindex(x_arr.shape[:-3]) if y is not None: y_indices = np.ndindex(y_arr.shape[:-3]) # Random transform on each value. x_out, y_out = None, None if y is not None: for idx_x, idx_y in zip(np.ndindex(x_arr.shape[:-3]), np.ndindex(y_arr.shape[:-3])): xt, yt = image_random_transform(x_arr[idx_x], y_arr[idx_y], *args, channel_axis=0, **kwargs) out_shape_x = x_arr.shape[:-2]+xt.shape[-2:] out_shape_y = y_arr.shape[:-2]+xt.shape[-2:] if x_out is None: x_out = np.zeros(out_shape_x, dtype=np.float32) if y_out is None: y_out = np.zeros(out_shape_y, dtype=np.float32) x_out[idx_x], y_out[idx_y] = xt, yt else: for idx_x in np.ndindex(x_arr.shape[:-3]): xt = image_random_transform(x_arr[idx_x], *args, channel_axis=0, **kwargs) out_shape = x_arr.shape[:-2]+xt.shape[-2:] if x_out is None: x_out = np.zeros(out_shape, dtype=np.float32) x_out[idx_x] = xt # Move channel axis back to where it was. if channel_axis!=std_channel_axis: x_out = np.moveaxis(x_out, source=std_channel_axis, destination=channel_axis) if y is not None: y_out = np.moveaxis(y_out, source=std_channel_axis, destination=channel_axis) if y is not None: return x_out, y_out return x_out """ Data augmentation for 2D images using random image transformations. This code handles on input images alone or jointly on input images and their corresponding output images (eg. input images and corresponding segmentation masks). x : A single 2D input image (ndim=3, channel and 2 spatial dims). y : A single output image or mask. rotation_range : Positive degree value, specifying the maximum amount to rotate the image in any direction about its center. width_shift_range : Float specifying the maximum distance by which to shift the image horizontally, as a fraction of the image's width. height_shift_range : Float specifying the maximum distance by which to shift the image vertically, as a fraction of the image's height. shear_range : Positive degree value, specifying the maximum horizontal sheer of the image. zoom_range : The maximum absolute deviation of the image scale from one. (I.e. zoom_range of 0.2 allows zooming the image to scales within the range [0.8, 1.2]). intensity_shift_range : The maximum absolute value by which to shift image intensities up or down. fill_mode : Once an image is spatially transformed, fill any empty space with the 'nearest', 'reflect', or 'constant' strategy. Mode 'nearest' fills the space with the values of the nearest pixels; mode 'reflect' fills the space with a mirror image of the image along its nearest border or corner; 'constant' fills it with the constant value defined in `cval`. cval : The constant value with which to fill any empty space in a transformed input image when using `fill_mode='constant'`. cvalMask : The constant value with which to fill any empty space in a transformed target image when using `fill_mode='constant'`. horizontal_flip : Boolean, whether to randomly flip images horizontally. vertical_flip : Boolean, whether to randomly flip images vertically. spline_warp : Boolean, whether to apply a b-spline nonlineary warp. warp_sigma : Standard deviation of control point jitter in spline warp. warp_grid_size : Integer s specifying an a grid with s by s control points. crop_size : Tuple specifying the size of random crops taken of transformed images. Crops are always taken from within the transformed image, with no padding. channel_axis : The axis in the input images that corresponds to the channel. Remaining axes are the two spatial axes. rng : A numpy random number generator. """ def image_random_transform(x, y=None, rotation_range=0., width_shift_range=0., height_shift_range=0., shear_range=0., zoom_range=0., intensity_shift_range=0., fill_mode='nearest', cval_x=0., cval_y=0., horizontal_flip=False, vertical_flip=False, spline_warp=False, warp_sigma=0.1, warp_grid_size=3, crop_size=None, channel_axis=0, n_warp_threads=None, rng=None): # Set random number generator if rng is None: rng = np.random.RandomState() # x is a single image, so we don't have batch dimension assert(x.ndim == 3) if y is not None: assert(y.ndim == 3) img_row_index = 1 img_col_index = 2 img_channel_index = channel_axis # Nonlinear spline warping if spline_warp: if n_warp_threads is None: n_warp_threads = os.cpu_count() warp_field = _gen_warp_field(shape=x.shape[-2:], sigma=warp_sigma, grid_size=warp_grid_size, n_threads=n_warp_threads, rng=rng) x = _apply_warp(x, warp_field, interpolator=sitk.sitkNearestNeighbor, fill_mode=fill_mode, cval=cval_x, n_threads=n_warp_threads) if y is not None: y = np.round(_apply_warp(y, warp_field, interpolator=sitk.sitkNearestNeighbor, fill_mode=fill_mode, cval=cval_y, n_threads=n_warp_threads)) # use composition of homographies to generate final transform that needs # to be applied if np.isscalar(zoom_range): zoom_range = [1 - zoom_range, 1 + zoom_range] elif len(zoom_range) == 2: zoom_range = [zoom_range[0], zoom_range[1]] else: raise Exception('zoom_range should be a float or ' 'a tuple or list of two floats. ' 'Received arg: ', zoom_range) if zoom_range[0] == 1 and zoom_range[1] == 1: zx, zy = 1, 1 else: zx, zy = rng.uniform(zoom_range[0], zoom_range[1], 2) zoom_matrix = np.array([[zx, 0, 0], [0, zy, 0], [0, 0, 1]]) if rotation_range: theta = np.pi / 180 * rng.uniform(-rotation_range, rotation_range) else: theta = 0 rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]]) if height_shift_range: tx = rng.uniform(-height_shift_range, height_shift_range) \ * x.shape[img_row_index] else: tx = 0 if width_shift_range: ty = rng.uniform(-width_shift_range, width_shift_range) \ * x.shape[img_col_index] else: ty = 0 translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]]) if shear_range: shear = np.pi / 180 * rng.uniform(-shear_range, shear_range) else: shear = 0 shear_matrix = np.array([[1, -np.sin(shear), 0], [0, np.cos(shear), 0], [0, 0, 1]]) transform_matrix = np.dot(np.dot(np.dot(rotation_matrix, shear_matrix), translation_matrix), zoom_matrix) h, w = x.shape[img_row_index], x.shape[img_col_index] transform_matrix = _transform_matrix_offset_center(transform_matrix, h, w) x = _apply_transform_matrix(x, transform_matrix, img_channel_index, fill_mode=fill_mode, cval=cval_x) if y is not None: y = _apply_transform_matrix(y, transform_matrix, img_channel_index, fill_mode=fill_mode, cval=cval_y) if intensity_shift_range != 0: x = _random_intensity_shift(x, intensity_shift_range, img_channel_index, rng=rng) if horizontal_flip: if rng.random_sample() < 0.5: x = _flip_axis(x, img_col_index) if y is not None: y = _flip_axis(y, img_col_index) if vertical_flip: if rng.random_sample() < 0.5: x = _flip_axis(x, img_row_index) if y is not None: y = _flip_axis(y, img_row_index) # Crop crop = list(crop_size) if crop_size else None if crop: h, w = x.shape[img_row_index], x.shape[img_col_index] if crop[0] < h: top = rng.randint(h - crop[0]) else: print('Data augmentation: Crop height >= image size') top, crop[0] = 0, h if crop[1] < w: left = rng.randint(w - crop[1]) else: print('Data augmentation: Crop width >= image size') left, crop[1] = 0, w x = x[:, top:top+crop[0], left:left+crop[1]] if y is not None: y = y[:, top:top+crop[0], left:left+crop[1]] if y is None: return x else: return x, y def _transform_matrix_offset_center(matrix, x, y): o_x = float(x) / 2 + 0.5 o_y = float(y) / 2 + 0.5 offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]]) reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]]) transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix) return transform_matrix def _apply_transform_matrix(x, transform_matrix, channel_index=0, fill_mode='nearest', cval=0.): x_ = np.copy(x) x_ = np.rollaxis(x_, channel_index, 0) final_affine_matrix = transform_matrix[:2, :2] final_offset = transform_matrix[:2, 2] channel_images = [ndi.interpolation.affine_transform(\ x_channel, final_affine_matrix, final_offset, order=0, mode=fill_mode, cval=cval)\ for x_channel in x_] x_out = np.stack(channel_images, axis=0) x_out = np.rollaxis(x_out, 0, channel_index+1) return x_out def _random_intensity_shift(x, intensity, channel_index=0, rng=None): x_ = np.copy(x) x_ = np.rollaxis(x_, channel_index, 0) channel_images = [np.clip(x_channel + \ rng.uniform(-intensity, intensity), np.min(x_), np.max(x_)) for x_channel in x_] x_out = np.stack(channel_images, axis=0) x_out = np.rollaxis(x_out, 0, channel_index+1) return x_out def _flip_axis(x, axis): x_ = np.copy(x) x_ = np.asarray(x_).swapaxes(axis, 0) x_ = x_[::-1, ...] x_ = x_.swapaxes(0, axis) x_out = x_ return x_out def _gen_warp_field(shape, sigma=0.1, grid_size=3, n_threads=1, rng=None): # Initialize bspline transform args = shape+(sitk.sitkFloat32,) ref_image = sitk.Image(*args) tx = sitk.BSplineTransformInitializer(ref_image, [grid_size, grid_size]) # Initialize shift in control points: # mesh size = number of control points - spline order p = sigma * rng.randn(grid_size+3, grid_size+3, 2) # Anchor the edges of the image p[:, 0, :] = 0 p[:, -1:, :] = 0 p[0, :, :] = 0 p[-1:, :, :] = 0 # Set bspline transform parameters to the above shifts tx.SetParameters(p.flatten()) # Compute deformation field displacement_filter = sitk.TransformToDisplacementFieldFilter() displacement_filter.SetReferenceImage(ref_image) displacement_filter.SetNumberOfThreads(n_threads) displacement_field = displacement_filter.Execute(tx) return displacement_field def _pad_image(x, pad_amount, mode='reflect', cval=0.): e = pad_amount assert(len(x.shape)>=2) shape = list(x.shape) shape[:2] += 2*e if mode == 'constant': x_padded = np.ones(shape, dtype=np.float32)*cval x_padded[e:-e, e:-e] = x.copy() else: x_padded = np.zeros(shape, dtype=np.float32) x_padded[e:-e, e:-e] = x.copy() if mode == 'reflect': x_padded[:e, e:-e] = np.flipud(x[:e, :]) # left edge x_padded[-e:, e:-e] = np.flipud(x[-e:, :]) # right edge x_padded[e:-e, :e] = np.fliplr(x[:, :e]) # top edge x_padded[e:-e, -e:] = np.fliplr(x[:, -e:]) # bottom edge x_padded[:e, :e] = np.fliplr(np.flipud(x[:e, :e])) # top-left corner x_padded[-e:, :e] = np.fliplr(np.flipud(x[-e:, :e])) # top-right x_padded[:e, -e:] = np.fliplr(np.flipud(x[:e, -e:])) # bottom-left x_padded[-e:, -e:] = np.fliplr(np.flipud(x[-e:, -e:])) # bottom-right elif mode == 'zero' or mode == 'constant': pass elif mode == 'nearest': x_padded[:e, e:-e] = x[[0], :] # left edge x_padded[-e:, e:-e] = x[[-1], :] # right edge x_padded[e:-e, :e] = x[:, [0]] # top edge x_padded[e:-e, -e:] = x[:, [-1]] # bottom edge x_padded[:e, :e] = x[[0], [0]] # top-left corner x_padded[-e:, :e] = x[[-1], [0]] # top-right corner x_padded[:e, -e:] = x[[0], [-1]] # bottom-left corner x_padded[-e:, -e:] = x[[-1], [-1]] # bottom-right corner else: raise ValueError("Unsupported padding mode \"{}\"".format(mode)) return x_padded def _apply_warp(x, warp_field, fill_mode='reflect', interpolator=sitk.sitkLinear, cval=0, channel_index=0, n_threads=1): # Expand deformation field (and later the image), padding for the largest # deformation warp_field_arr = sitk.GetArrayFromImage(warp_field) max_deformation = np.max(np.abs(warp_field_arr)) pad = np.ceil(max_deformation).astype(np.int32) warp_field_padded_arr = _pad_image(warp_field_arr, pad_amount=pad, mode='nearest') warp_field_padded = sitk.GetImageFromArray(warp_field_padded_arr, isVector=True) # Warp x, one filter slice at a time x_warped = np.zeros(x.shape, dtype=np.float32) warp_filter = sitk.WarpImageFilter() warp_filter.SetInterpolator(interpolator) warp_filter.SetEdgePaddingValue(np.min(x).astype(np.double)) warp_filter.SetNumberOfThreads(n_threads) x_by_channel = np.rollaxis(x, channel_index, 0) for i, channel in enumerate(x_by_channel): image_padded = _pad_image(channel, pad_amount=pad, mode=fill_mode, cval=cval).T image_f = sitk.GetImageFromArray(image_padded) image_f_warped = warp_filter.Execute(image_f, warp_field_padded) image_warped = sitk.GetArrayFromImage(image_f_warped) x_warped[i] = image_warped[pad:-pad, pad:-pad].T x_warped = np.rollaxis(x_warped, 0, channel_index+1) return x_warped
[ "SimpleITK.BSplineTransformInitializer", "numpy.rollaxis", "numpy.array", "os.cpu_count", "numpy.moveaxis", "numpy.sin", "numpy.random.RandomState", "numpy.isscalar", "numpy.asarray", "SimpleITK.GetArrayFromImage", "numpy.max", "numpy.stack", "numpy.dot", "numpy.min", "numpy.abs", "num...
[((964, 975), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (972, 975), True, 'import numpy as np\n'), ((1970, 1998), 'numpy.ndindex', 'np.ndindex', (['x_arr.shape[:-3]'], {}), '(x_arr.shape[:-3])\n', (1980, 1998), True, 'import numpy as np\n'), ((8003, 8026), 'numpy.isscalar', 'np.isscalar', (['zoom_range'], {}), '(zoom_range)\n', (8014, 8026), True, 'import numpy as np\n'), ((8513, 8558), 'numpy.array', 'np.array', (['[[zx, 0, 0], [0, zy, 0], [0, 0, 1]]'], {}), '([[zx, 0, 0], [0, zy, 0], [0, 0, 1]])\n', (8521, 8558), True, 'import numpy as np\n'), ((9273, 9318), 'numpy.array', 'np.array', (['[[1, 0, tx], [0, 1, ty], [0, 0, 1]]'], {}), '([[1, 0, tx], [0, 1, ty], [0, 0, 1]])\n', (9281, 9318), True, 'import numpy as np\n'), ((11608, 11655), 'numpy.array', 'np.array', (['[[1, 0, o_x], [0, 1, o_y], [0, 0, 1]]'], {}), '([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]])\n', (11616, 11655), True, 'import numpy as np\n'), ((11737, 11786), 'numpy.array', 'np.array', (['[[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]]'], {}), '([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]])\n', (11745, 11786), True, 'import numpy as np\n'), ((12087, 12097), 'numpy.copy', 'np.copy', (['x'], {}), '(x)\n', (12094, 12097), True, 'import numpy as np\n'), ((12107, 12140), 'numpy.rollaxis', 'np.rollaxis', (['x_', 'channel_index', '(0)'], {}), '(x_, channel_index, 0)\n', (12118, 12140), True, 'import numpy as np\n'), ((12521, 12553), 'numpy.stack', 'np.stack', (['channel_images'], {'axis': '(0)'}), '(channel_images, axis=0)\n', (12529, 12553), True, 'import numpy as np\n'), ((12566, 12606), 'numpy.rollaxis', 'np.rollaxis', (['x_out', '(0)', '(channel_index + 1)'], {}), '(x_out, 0, channel_index + 1)\n', (12577, 12606), True, 'import numpy as np\n'), ((12703, 12713), 'numpy.copy', 'np.copy', (['x'], {}), '(x)\n', (12710, 12713), True, 'import numpy as np\n'), ((12723, 12756), 'numpy.rollaxis', 'np.rollaxis', (['x_', 'channel_index', '(0)'], {}), '(x_, channel_index, 0)\n', (12734, 12756), True, 'import numpy as np\n'), ((12959, 12991), 'numpy.stack', 'np.stack', (['channel_images'], {'axis': '(0)'}), '(channel_images, axis=0)\n', (12967, 12991), True, 'import numpy as np\n'), ((13004, 13044), 'numpy.rollaxis', 'np.rollaxis', (['x_out', '(0)', '(channel_index + 1)'], {}), '(x_out, 0, channel_index + 1)\n', (13015, 13044), True, 'import numpy as np\n'), ((13096, 13106), 'numpy.copy', 'np.copy', (['x'], {}), '(x)\n', (13103, 13106), True, 'import numpy as np\n'), ((13399, 13416), 'SimpleITK.Image', 'sitk.Image', (['*args'], {}), '(*args)\n', (13409, 13416), True, 'import SimpleITK as sitk\n'), ((13426, 13493), 'SimpleITK.BSplineTransformInitializer', 'sitk.BSplineTransformInitializer', (['ref_image', '[grid_size, grid_size]'], {}), '(ref_image, [grid_size, grid_size])\n', (13458, 13493), True, 'import SimpleITK as sitk\n'), ((13920, 13961), 'SimpleITK.TransformToDisplacementFieldFilter', 'sitk.TransformToDisplacementFieldFilter', ([], {}), '()\n', (13959, 13961), True, 'import SimpleITK as sitk\n'), ((16047, 16081), 'SimpleITK.GetArrayFromImage', 'sitk.GetArrayFromImage', (['warp_field'], {}), '(warp_field)\n', (16069, 16081), True, 'import SimpleITK as sitk\n'), ((16337, 16397), 'SimpleITK.GetImageFromArray', 'sitk.GetImageFromArray', (['warp_field_padded_arr'], {'isVector': '(True)'}), '(warp_field_padded_arr, isVector=True)\n', (16359, 16397), True, 'import SimpleITK as sitk\n'), ((16502, 16537), 'numpy.zeros', 'np.zeros', (['x.shape'], {'dtype': 'np.float32'}), '(x.shape, dtype=np.float32)\n', (16510, 16537), True, 'import numpy as np\n'), ((16556, 16578), 'SimpleITK.WarpImageFilter', 'sitk.WarpImageFilter', ([], {}), '()\n', (16576, 16578), True, 'import SimpleITK as sitk\n'), ((16755, 16787), 'numpy.rollaxis', 'np.rollaxis', (['x', 'channel_index', '(0)'], {}), '(x, channel_index, 0)\n', (16766, 16787), True, 'import numpy as np\n'), ((17219, 17262), 'numpy.rollaxis', 'np.rollaxis', (['x_warped', '(0)', '(channel_index + 1)'], {}), '(x_warped, 0, channel_index + 1)\n', (17230, 17262), True, 'import numpy as np\n'), ((1014, 1025), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1022, 1025), True, 'import numpy as np\n'), ((1624, 1693), 'numpy.moveaxis', 'np.moveaxis', (['x_arr'], {'source': 'channel_axis', 'destination': 'std_channel_axis'}), '(x_arr, source=channel_axis, destination=std_channel_axis)\n', (1635, 1693), True, 'import numpy as np\n'), ((2041, 2069), 'numpy.ndindex', 'np.ndindex', (['y_arr.shape[:-3]'], {}), '(y_arr.shape[:-3])\n', (2051, 2069), True, 'import numpy as np\n'), ((2824, 2852), 'numpy.ndindex', 'np.ndindex', (['x_arr.shape[:-3]'], {}), '(x_arr.shape[:-3])\n', (2834, 2852), True, 'import numpy as np\n'), ((3272, 3341), 'numpy.moveaxis', 'np.moveaxis', (['x_out'], {'source': 'std_channel_axis', 'destination': 'channel_axis'}), '(x_out, source=std_channel_axis, destination=channel_axis)\n', (3283, 3341), True, 'import numpy as np\n'), ((6670, 6693), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (6691, 6693), True, 'import numpy as np\n'), ((11878, 11907), 'numpy.dot', 'np.dot', (['offset_matrix', 'matrix'], {}), '(offset_matrix, matrix)\n', (11884, 11907), True, 'import numpy as np\n'), ((12257, 12377), 'scipy.ndimage.interpolation.affine_transform', 'ndi.interpolation.affine_transform', (['x_channel', 'final_affine_matrix', 'final_offset'], {'order': '(0)', 'mode': 'fill_mode', 'cval': 'cval'}), '(x_channel, final_affine_matrix,\n final_offset, order=0, mode=fill_mode, cval=cval)\n', (12291, 12377), True, 'import scipy.ndimage as ndi\n'), ((14462, 14495), 'numpy.zeros', 'np.zeros', (['shape'], {'dtype': 'np.float32'}), '(shape, dtype=np.float32)\n', (14470, 14495), True, 'import numpy as np\n'), ((14592, 14611), 'numpy.flipud', 'np.flipud', (['x[:e, :]'], {}), '(x[:e, :])\n', (14601, 14611), True, 'import numpy as np\n'), ((14655, 14675), 'numpy.flipud', 'np.flipud', (['x[-e:, :]'], {}), '(x[-e:, :])\n', (14664, 14675), True, 'import numpy as np\n'), ((14719, 14738), 'numpy.fliplr', 'np.fliplr', (['x[:, :e]'], {}), '(x[:, :e])\n', (14728, 14738), True, 'import numpy as np\n'), ((14781, 14801), 'numpy.fliplr', 'np.fliplr', (['x[:, -e:]'], {}), '(x[:, -e:])\n', (14790, 14801), True, 'import numpy as np\n'), ((16111, 16133), 'numpy.abs', 'np.abs', (['warp_field_arr'], {}), '(warp_field_arr)\n', (16117, 16133), True, 'import numpy as np\n'), ((16975, 17011), 'SimpleITK.GetImageFromArray', 'sitk.GetImageFromArray', (['image_padded'], {}), '(image_padded)\n', (16997, 17011), True, 'import SimpleITK as sitk\n'), ((17108, 17146), 'SimpleITK.GetArrayFromImage', 'sitk.GetArrayFromImage', (['image_f_warped'], {}), '(image_f_warped)\n', (17130, 17146), True, 'import SimpleITK as sitk\n'), ((1768, 1837), 'numpy.moveaxis', 'np.moveaxis', (['y_arr'], {'source': 'channel_axis', 'destination': 'std_channel_axis'}), '(y_arr, source=channel_axis, destination=std_channel_axis)\n', (1779, 1837), True, 'import numpy as np\n'), ((2201, 2229), 'numpy.ndindex', 'np.ndindex', (['x_arr.shape[:-3]'], {}), '(x_arr.shape[:-3])\n', (2211, 2229), True, 'import numpy as np\n'), ((2263, 2291), 'numpy.ndindex', 'np.ndindex', (['y_arr.shape[:-3]'], {}), '(y_arr.shape[:-3])\n', (2273, 2291), True, 'import numpy as np\n'), ((3416, 3485), 'numpy.moveaxis', 'np.moveaxis', (['y_out'], {'source': 'std_channel_axis', 'destination': 'channel_axis'}), '(y_out, source=std_channel_axis, destination=channel_axis)\n', (3427, 3485), True, 'import numpy as np\n'), ((7035, 7049), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (7047, 7049), False, 'import os\n'), ((9690, 9727), 'numpy.dot', 'np.dot', (['rotation_matrix', 'shear_matrix'], {}), '(rotation_matrix, shear_matrix)\n', (9696, 9727), True, 'import numpy as np\n'), ((12897, 12907), 'numpy.min', 'np.min', (['x_'], {}), '(x_)\n', (12903, 12907), True, 'import numpy as np\n'), ((12909, 12919), 'numpy.max', 'np.max', (['x_'], {}), '(x_)\n', (12915, 12919), True, 'import numpy as np\n'), ((13116, 13130), 'numpy.asarray', 'np.asarray', (['x_'], {}), '(x_)\n', (13126, 13130), True, 'import numpy as np\n'), ((14355, 14387), 'numpy.ones', 'np.ones', (['shape'], {'dtype': 'np.float32'}), '(shape, dtype=np.float32)\n', (14362, 14387), True, 'import numpy as np\n'), ((14854, 14874), 'numpy.flipud', 'np.flipud', (['x[:e, :e]'], {}), '(x[:e, :e])\n', (14863, 14874), True, 'import numpy as np\n'), ((14933, 14954), 'numpy.flipud', 'np.flipud', (['x[-e:, :e]'], {}), '(x[-e:, :e])\n', (14942, 14954), True, 'import numpy as np\n'), ((15007, 15028), 'numpy.flipud', 'np.flipud', (['x[:e, -e:]'], {}), '(x[:e, -e:])\n', (15016, 15028), True, 'import numpy as np\n'), ((15084, 15106), 'numpy.flipud', 'np.flipud', (['x[-e:, -e:]'], {}), '(x[-e:, -e:])\n', (15093, 15106), True, 'import numpy as np\n'), ((16145, 16169), 'numpy.ceil', 'np.ceil', (['max_deformation'], {}), '(max_deformation)\n', (16152, 16169), True, 'import numpy as np\n'), ((2611, 2650), 'numpy.zeros', 'np.zeros', (['out_shape_x'], {'dtype': 'np.float32'}), '(out_shape_x, dtype=np.float32)\n', (2619, 2650), True, 'import numpy as np\n'), ((2705, 2744), 'numpy.zeros', 'np.zeros', (['out_shape_y'], {'dtype': 'np.float32'}), '(out_shape_y, dtype=np.float32)\n', (2713, 2744), True, 'import numpy as np\n'), ((3090, 3127), 'numpy.zeros', 'np.zeros', (['out_shape'], {'dtype': 'np.float32'}), '(out_shape, dtype=np.float32)\n', (3098, 3127), True, 'import numpy as np\n'), ((8779, 8792), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (8785, 8792), True, 'import numpy as np\n'), ((8847, 8860), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (8853, 8860), True, 'import numpy as np\n'), ((8862, 8875), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (8868, 8875), True, 'import numpy as np\n'), ((9592, 9605), 'numpy.cos', 'np.cos', (['shear'], {}), '(shear)\n', (9598, 9605), True, 'import numpy as np\n'), ((16661, 16670), 'numpy.min', 'np.min', (['x'], {}), '(x)\n', (16667, 16670), True, 'import numpy as np\n'), ((8795, 8808), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (8801, 8808), True, 'import numpy as np\n'), ((9540, 9553), 'numpy.sin', 'np.sin', (['shear'], {}), '(shear)\n', (9546, 9553), True, 'import numpy as np\n')]
import wx import matplotlib.cm import numpy as np from . import properties slider_width = 30 s_off = slider_width/2 class ColorBarPanel(wx.Panel): ''' A HORIZONTAL color bar and value axis drawn on a panel. ''' def __init__(self, parent, map, local_extents=[0.,1.], global_extents=None, ticks=5, **kwargs): ''' map -- a colormap name from matplotlib.cm local_extents -- local min and max values of the measurement global_extents -- min and max values of the measurement ticks -- # of ticks to display values for on the bar 1 or 0 will draw no ticks labelformat -- a valid format string for the values displayed on the value axis ''' wx.Panel.__init__(self, parent, **kwargs) self.ticks = ticks self.labelformat = '%.3f' self.low_slider = wx.Button(self, -1, '[', pos=(0,-1), size=(slider_width,-1)) self.high_slider = wx.Button(self, -1, ']', pos=(self.Size[0],-1), size=(slider_width,-1)) self.ClearNotifyWindows() self.SetMap(map) self.interval = list(local_extents) self.local_extents = local_extents self.global_extents = list(local_extents) self.clipmode = 'rescale' self.low_slider.SetToolTip('') self.low_slider.GetToolTip().Enable(True) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.Bind(wx.EVT_MOTION, self.OnMotion) self.low_slider.Bind(wx.EVT_LEFT_DOWN, self.OnClipSliderLeftDown) self.low_slider.Bind(wx.EVT_MOTION, self.OnClipSliderMotion) self.high_slider.Bind(wx.EVT_LEFT_DOWN, self.OnClipSliderLeftDown) self.high_slider.Bind(wx.EVT_MOTION, self.OnClipSliderMotion) self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.Bind(wx.EVT_SIZE, self.OnResize) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnLeftDown(self, evt): # Get the slider closest to the click point. if abs(self.low_slider.GetPositionTuple()[0] - evt.GetX()) < abs(self.high_slider.GetPositionTuple()[0] - evt.GetX()): self.cur_slider = self.low_slider else: self.cur_slider = self.high_slider self.cur_slider.SetPosition((evt.GetX() - s_off, -1)) self.xo = 0 self.UpdateInterval() def OnMotion(self, evt): if not evt.Dragging() or not evt.LeftIsDown(): return self.cur_slider.SetPosition((evt.GetX() - s_off, -1)) self.UpdateInterval() def OnClipSliderLeftDown(self, evt): self.cur_slider = evt.EventObject self.xo = evt.GetX() def OnClipSliderMotion(self, evt): slider = evt.EventObject if not evt.Dragging() or not evt.LeftIsDown(): return slider.SetPosition((slider.GetPosition()[0] + evt.GetX() - self.xo - s_off, -1)) self.xo = 0 self.UpdateInterval() def ClearNotifyWindows(self): self.notify_windows = [] def AddNotifyWindow(self, win): self.notify_windows += [win] def ResetInterval(self): ''' Sets clip interval to the extents of the colorbar. ''' self.interval = list(self.global_extents) self.low_slider.SetPosition((0-s_off,-1)) self.high_slider.SetPosition((self.Size[0]-s_off,-1)) for win in self.notify_windows: win.SetClipInterval(self.GetLocalInterval(), self.local_extents, self.clipmode) self.Refresh() def UpdateInterval(self): ''' Calculates the interval values w.r.t. the current extents and clipping slider positions. ''' range = self.global_extents[1]-self.global_extents[0] w = float(self.Size[0]) if range > 0 and w > 0: self.interval[0] = self.global_extents[0] + ((self.low_slider.GetPosition()[0] + s_off) / w * range) self.interval[1] = self.global_extents[0] + ((self.high_slider.GetPosition()[0] + s_off) / w * range) self.low_slider.SetToolTip(str(self.global_extents[0] + ((self.low_slider.GetPosition()[0] + s_off) / w * range))) self.high_slider.SetToolTip(str(self.global_extents[0] + ((self.high_slider.GetPosition()[0] + s_off) / w * range))) else: self.interval = list(self.local_extents) self.UpdateLabelFormat() for win in self.notify_windows: win.SetClipInterval(self.GetLocalInterval(), self.local_extents, self.clipmode) self.Refresh() # TODO: To be added. Not sure how to treat intervals that are outside # the current extents, do we resize the extents? This could get # ugly and confusing. ## def SetInterval(self, interval): ## ''' ''' ## self.interval = interval ## self.low_slider.SetPosition((0-s_off,-1)) ## self.high_slider.SetPosition((self.Size[0]-s_off,-1)) ## for win in self.notify_windows: ## win.SetClipInterval(self.GetInterval(), self.clipmode) ## self.Refresh() def GetGlobalInterval(self): ''' Returns the interval clipped on the value axis. ''' return self.interval def GetLocalInterval(self): ''' Returns the interval clipped on the local color bar. If either part is outside the local_extents, the extent is returned. ''' return (max(self.interval[0], self.local_extents[0]), min(self.interval[1], self.local_extents[1])) def GetGlobalExtents(self): return self.global_extents def GetLocalExtents(self): return self.local_extents def GetClipMode(self): return self.clipmode def SetMap(self, map): ''' Sets the colormap that is displayed. map should be the string name of a colormap from matplotlib.cm''' self.cm = matplotlib.cm.get_cmap(map) self.Refresh() def SetLocalExtents(self, local_extents): #''' Sets the value axis min and max. Accepts a 2-tuple.''' self.local_extents = local_extents if self.local_extents[0] < self.global_extents[0]: self.global_extents[0] = self.local_extents[0] if self.local_extents[1] > self.global_extents[1]: self.global_extents[1] = self.local_extents[1] self.UpdateInterval() def SetGlobalExtents(self, global_extents): self.global_extents = list(global_extents) self.UpdateInterval() def SetTicks(self, ticks): ''' Sets the number of tick marks displayed by the ColorBarPanel. 1 or 0 will draw no ticks''' self.ticks = ticks self.Refresh() def UpdateLabelFormat(self): ''' Selects a number format based on the step value between ticks ''' range = self.global_extents[1] - self.global_extents[0] step = range / self.ticks if 0 < step < 0.001: self.labelformat = '%.3e' else: self.labelformat = '%.3f' def OnToggleClipMode(self, evt): if self.clipmode == 'clip': self.clipmode = 'rescale' else: self.clipmode = 'clip' for win in self.notify_windows: win.SetClipInterval(self.GetLocalInterval(), self.local_extents, self.clipmode) self.Refresh() def OnRightDown(self, evt): popupMenu = wx.Menu() popupMenu.SetTitle('Colorbar') reset = popupMenu.AppendItem(wx.MenuItem(popupMenu, -1, 'Reset sliders')) self.Bind(wx.EVT_MENU, lambda evt:self.ResetInterval(), reset) if self.clipmode == 'clip': bracket_mode = popupMenu.AppendItem(wx.MenuItem(popupMenu, -1, 'Value bracketing: RESCALE')) else: bracket_mode = popupMenu.AppendItem(wx.MenuItem(popupMenu, -1, 'Value bracketing: CLIP')) self.Bind(wx.EVT_MENU, self.OnToggleClipMode, bracket_mode) aggmethod = self.Parent.aggregationMethodsChoice.GetStringSelection().lower() src_table = self.Parent.sourceChoice.GetStringSelection() if (aggmethod in ['mean', 'median', 'min', 'max'] and self.interval != self.global_extents): popupMenu.AppendSeparator() saveitem = popupMenu.AppendItem(wx.MenuItem(popupMenu, -1, 'Create gate from interval')) self.Bind(wx.EVT_MENU, self.on_create_gate_from_interval, saveitem) self.PopupMenu(popupMenu, (evt.GetX(), evt.GetY())) def on_create_gate_from_interval(self, evt): self.create_gate_from_interval() def create_gate_from_interval(self): table = self.Parent.sourceChoice.GetStringSelection() colname = self.Parent.measurementsChoice.GetStringSelection() from .guiutils import GateDialog dlg = GateDialog(self) if dlg.ShowModal() == wx.ID_OK: from .sqltools import Gate, Gate1D p = properties.Properties() p.gates[dlg.Value] = Gate([Gate1D((table, colname), self.interval)]) dlg.Destroy() def OnResize(self, evt): range = self.global_extents[1] - self.global_extents[0] if range == 0: self.low_slider.SetPosition((0,-1)) self.high_slider.SetPosition((self.Size[1],-1)) else: self.low_slider.SetPosition((self.Size[0] * (self.interval[0] - self.global_extents[0]) / range - s_off, -1)) self.high_slider.SetPosition((self.Size[0] * (self.interval[1] - self.global_extents[0]) / range - s_off, -1)) self.UpdateLabelFormat() def OnPaint(self, evt): w_global, h = self.Size if 0 in self.Size: return low_slider_pos = self.low_slider.GetPosition()[0] + s_off high_slider_pos = self.high_slider.GetPosition()[0] + s_off global_scale = self.global_extents[1] - self.global_extents[0] # value scale of the global data if global_scale == 0: local_x0 = 0 local_x1 = w_global w_local = w_global else: local_x0 = (self.local_extents[0] - self.global_extents[0]) / global_scale * w_global # x pos (pixels) to start drawing the local color bar local_x1 = (self.local_extents[1] - self.global_extents[0]) / global_scale * w_global # x pos (pixels) to stop drawing the local color bar w_local = local_x1 - local_x0 # pixel width of the local color bar w0 = int(max(low_slider_pos, local_x0) - local_x0) w1 = int(local_x1 - min(high_slider_pos, local_x1)) # create array of values to be used for the color bar if self.clipmode=='rescale': a1 = np.array([]) if w0 > 0: a1 = np.zeros(w0) a2 = np.arange(abs(min(high_slider_pos, local_x1) - max(low_slider_pos, local_x0)), dtype=float) / (min(high_slider_pos, local_x1) - max(low_slider_pos, local_x0)) * 255 a3 = np.array([]) if w1 > 0: a3 = np.ones(w1) if len(a1) > 0 and len(a3) > 0: a = np.hstack([a1,a2,a3]) else: a = a2 elif self.clipmode=='clip': a = np.arange(w_local, dtype=float) / w_local a[:w0] = 0. if w1>=1: a[-w1:] = 1. # draw the color bar dc = wx.PaintDC(self) dc.Clear() dc.SetPen(wx.Pen((0,0,0))) dc.DrawLine(0, (h-14)/2, local_x0, (h-14)/2) for x, v in enumerate(a): v = int(v) color = np.array(self.cm(v)) * 255 dc.SetPen(wx.Pen(color)) dc.DrawLine(x+local_x0, 0, x+local_x0, h-14) dc.SetPen(wx.Pen((0,0,0))) dc.DrawLine(local_x1, (h-14)/2, w_global, (h-14)/2) # draw value axis if self.ticks <= 1: return font = dc.GetFont() font.SetPixelSize((6,12)) dc.SetFont(font) for t in range(self.ticks): xpos = t * w_global/(self.ticks-1.) val = t * (self.global_extents[1]-self.global_extents[0]) / (self.ticks-1) + self.global_extents[0] dc.DrawLine(xpos,6,xpos,h-14) textpos = xpos - xpos/w_global * dc.GetFullTextExtent(self.labelformat%(val), font)[0] dc.DrawText(self.labelformat%(val), textpos, h-13)
[ "wx.Button", "wx.PaintDC", "numpy.ones", "numpy.hstack", "numpy.array", "wx.MenuItem", "numpy.zeros", "wx.Pen", "wx.Menu", "wx.Panel.__init__", "numpy.arange" ]
[((775, 816), 'wx.Panel.__init__', 'wx.Panel.__init__', (['self', 'parent'], {}), '(self, parent, **kwargs)\n', (792, 816), False, 'import wx\n'), ((904, 966), 'wx.Button', 'wx.Button', (['self', '(-1)', '"""["""'], {'pos': '(0, -1)', 'size': '(slider_width, -1)'}), "(self, -1, '[', pos=(0, -1), size=(slider_width, -1))\n", (913, 966), False, 'import wx\n'), ((992, 1065), 'wx.Button', 'wx.Button', (['self', '(-1)', '"""]"""'], {'pos': '(self.Size[0], -1)', 'size': '(slider_width, -1)'}), "(self, -1, ']', pos=(self.Size[0], -1), size=(slider_width, -1))\n", (1001, 1065), False, 'import wx\n'), ((7507, 7516), 'wx.Menu', 'wx.Menu', ([], {}), '()\n', (7514, 7516), False, 'import wx\n'), ((11567, 11583), 'wx.PaintDC', 'wx.PaintDC', (['self'], {}), '(self)\n', (11577, 11583), False, 'import wx\n'), ((7593, 7636), 'wx.MenuItem', 'wx.MenuItem', (['popupMenu', '(-1)', '"""Reset sliders"""'], {}), "(popupMenu, -1, 'Reset sliders')\n", (7604, 7636), False, 'import wx\n'), ((10880, 10892), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (10888, 10892), True, 'import numpy as np\n'), ((11149, 11161), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (11157, 11161), True, 'import numpy as np\n'), ((11622, 11639), 'wx.Pen', 'wx.Pen', (['(0, 0, 0)'], {}), '((0, 0, 0))\n', (11628, 11639), False, 'import wx\n'), ((11918, 11935), 'wx.Pen', 'wx.Pen', (['(0, 0, 0)'], {}), '((0, 0, 0))\n', (11924, 11935), False, 'import wx\n'), ((7793, 7848), 'wx.MenuItem', 'wx.MenuItem', (['popupMenu', '(-1)', '"""Value bracketing: RESCALE"""'], {}), "(popupMenu, -1, 'Value bracketing: RESCALE')\n", (7804, 7848), False, 'import wx\n'), ((7912, 7964), 'wx.MenuItem', 'wx.MenuItem', (['popupMenu', '(-1)', '"""Value bracketing: CLIP"""'], {}), "(popupMenu, -1, 'Value bracketing: CLIP')\n", (7923, 7964), False, 'import wx\n'), ((8393, 8448), 'wx.MenuItem', 'wx.MenuItem', (['popupMenu', '(-1)', '"""Create gate from interval"""'], {}), "(popupMenu, -1, 'Create gate from interval')\n", (8404, 8448), False, 'import wx\n'), ((10937, 10949), 'numpy.zeros', 'np.zeros', (['w0'], {}), '(w0)\n', (10945, 10949), True, 'import numpy as np\n'), ((11206, 11217), 'numpy.ones', 'np.ones', (['w1'], {}), '(w1)\n', (11213, 11217), True, 'import numpy as np\n'), ((11282, 11305), 'numpy.hstack', 'np.hstack', (['[a1, a2, a3]'], {}), '([a1, a2, a3])\n', (11291, 11305), True, 'import numpy as np\n'), ((11819, 11832), 'wx.Pen', 'wx.Pen', (['color'], {}), '(color)\n', (11825, 11832), False, 'import wx\n'), ((11399, 11430), 'numpy.arange', 'np.arange', (['w_local'], {'dtype': 'float'}), '(w_local, dtype=float)\n', (11408, 11430), True, 'import numpy as np\n')]
import cv2 import numpy as np import os import glob from random import shuffle #from tqdm import tqdm import os, fnmatch import torch from torch import autograd, nn, optim import torch.nn.functional as F from time import time #input = autograd.Variable(torch.rand(batch_size, input_size))-0.5 #target = autograd.Variable((torch.rand(batch_size)*num_classes).long()) #print ('===> input : ',input) #print ('===> target : ',target#) TRAIN_DIR = 'data_c_vs_d/PetImages/' TEST_DIR = '' IMG_SIZE = 20 LR = 1e-3 batch_size = 10 input_size = IMG_SIZE*IMG_SIZE hidden_size = 6 input_size = 3 num_classes = 2 learning_rate = 0.001 MODEL_NAME = 'dogvscat-{}-{}-model'.format(LR,'2conv-basic') def find_files(directory, pattern): for root, dirs, files in os.walk(directory): for basename in files: if fnmatch.fnmatch(basename, pattern): filename = os.path.join(root, basename) yield filename def get_jpg_files(path): for filename in find_files(path, '*.jpg'): label = filename.split('/')[2] yield label,filename def create_train_data(): train_data = [] for label,path in get_jpg_files(TRAIN_DIR): original_img = cv2.imread(path,cv2.IMREAD_GRAYSCALE) # print('----->',original_img) if original_img != None: img = cv2.resize(original_img,(IMG_SIZE,IMG_SIZE)) train_data.append([np.array(img), np.array(label)]) # training_Data.append(np.array(img), np.arrat(label)) shuffle(train_data) np.save('train_data.npy',train_data) return train_data '''class Net(nn.Module): def __init__(self, input_size, hidden_size,num_classes): super(Net,self).__init__() self.conv1 = nn.Conv2d(1,6,5) self.conv2 = nn.Conv2d(6,16,5) self.h1 = nn.Linear(input_size, hidden_size) self.h2 = nn.Linear(hidden_size, num_classes) def forward(self,x): x = self.h1(x) x = F.tanh(x) x = self.h2(x) x = F.softmax(x) return x''' class Net(nn.Module): def __init__(self): super(Net,self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 2 * 2, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 2) def forward(self, x): # Max pooling over a (2, 2) window # print('0. input: ',x.shape) x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # print('1. ==>conv2-relu-pool', x.shape) # If the size is a square you can only specify a single number x = F.max_pool2d(F.relu(self.conv2(x)), 2) # print('2. ==>conv2-relu-pool', x.shape) x = x.view(-1, self.num_flat_features(x)) # print('3. ==>view???', x.shape) x = F.relu(self.fc1(x)) # print('4. ==>fc1 - relu', x.shape) x = F.relu(self.fc2(x)) # print('5. ==>fc2 + relu', x.shape) x = self.fc3(x) # print('6. ==>fc3 ', x.shape) # x = F.softmax(x,2) # print('7. ==>softmax ', x.shape) return x def num_flat_features(self, x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s return num_features def to_num(label): if label=='dog': return 1 else: return 0 def separate_train_data(train_data): train = train_data[1:500] test = train_data[501:1000] h = np.array([np.array([i[0]]) for i in train]) print('h ===>', h.shape) X = h.reshape(-1,1,IMG_SIZE,IMG_SIZE) Y = np.array([to_num(i[1]) for i in train]) test_X = np.array([np.array([i[0]]) for i in test]).reshape(-1,1,IMG_SIZE,IMG_SIZE) test_Y = np.array([to_num(i[1]) for i in test]) return X, Y, test_X, test_Y def torch_npvars(x,dtype=torch.float32): # cast fails y = torch.tensor(x,dtype=dtype) # print('y data yype:', y.dtype) z = autograd.Variable(y) # print('z.dtype==',z.dtype) return z train_data_files = [f for f in find_files('./','train_data.npy')] # data prepatetion if len(train_data_files)==0: train_data = create_train_data() else: train_data = np.load('train_data.npy') X, Y, test_X, test_Y = separate_train_data(train_data) # defining model and optimizer #model = Net(input_size = input_size, hidden_size=hidden_size, num_classes = num_classes) model = Net() opt = optim.Adam(params=model.parameters(), lr=learning_rate) #training process X = torch_npvars(X) Y = torch_npvars(Y,dtype = torch.long) # print(X.size()) # g = torch.randn(1,400) # print('g type: =====> ',g.dtype) # output = model(X) # print(output) for i in range(10): print('### Epoch ### ',i) start = time() output = model(X) _, pred = output.max(1) loss = F.nll_loss(output,Y) print('===> target : ',Y[1:10]) print('===> prediction : ',pred[1:10]) print('===> loss : ',loss.view(1,-1)) print('===> evaluation time: ',time() - start) # optiminaztion model.zero_grad() loss.backward() opt.step()
[ "cv2.imread", "random.shuffle", "torch.nn.functional.nll_loss", "os.walk", "os.path.join", "torch.nn.Conv2d", "torch.tensor", "numpy.array", "fnmatch.fnmatch", "torch.nn.Linear", "cv2.resize", "torch.autograd.Variable", "time.time", "numpy.save", "numpy.load" ]
[((760, 778), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (767, 778), False, 'import os, fnmatch\n'), ((1513, 1532), 'random.shuffle', 'shuffle', (['train_data'], {}), '(train_data)\n', (1520, 1532), False, 'from random import shuffle\n'), ((1537, 1574), 'numpy.save', 'np.save', (['"""train_data.npy"""', 'train_data'], {}), "('train_data.npy', train_data)\n", (1544, 1574), True, 'import numpy as np\n'), ((4050, 4078), 'torch.tensor', 'torch.tensor', (['x'], {'dtype': 'dtype'}), '(x, dtype=dtype)\n', (4062, 4078), False, 'import torch\n'), ((4123, 4143), 'torch.autograd.Variable', 'autograd.Variable', (['y'], {}), '(y)\n', (4140, 4143), False, 'from torch import autograd, nn, optim\n'), ((4369, 4394), 'numpy.load', 'np.load', (['"""train_data.npy"""'], {}), "('train_data.npy')\n", (4376, 4394), True, 'import numpy as np\n'), ((4903, 4909), 'time.time', 'time', ([], {}), '()\n', (4907, 4909), False, 'from time import time\n'), ((4971, 4992), 'torch.nn.functional.nll_loss', 'F.nll_loss', (['output', 'Y'], {}), '(output, Y)\n', (4981, 4992), True, 'import torch.nn.functional as F\n'), ((1208, 1246), 'cv2.imread', 'cv2.imread', (['path', 'cv2.IMREAD_GRAYSCALE'], {}), '(path, cv2.IMREAD_GRAYSCALE)\n', (1218, 1246), False, 'import cv2\n'), ((2234, 2252), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(6)', '(5)'], {}), '(1, 6, 5)\n', (2243, 2252), False, 'from torch import autograd, nn, optim\n'), ((2274, 2293), 'torch.nn.Conv2d', 'nn.Conv2d', (['(6)', '(16)', '(5)'], {}), '(6, 16, 5)\n', (2283, 2293), False, 'from torch import autograd, nn, optim\n'), ((2355, 2381), 'torch.nn.Linear', 'nn.Linear', (['(16 * 2 * 2)', '(120)'], {}), '(16 * 2 * 2, 120)\n', (2364, 2381), False, 'from torch import autograd, nn, optim\n'), ((2401, 2419), 'torch.nn.Linear', 'nn.Linear', (['(120)', '(84)'], {}), '(120, 84)\n', (2410, 2419), False, 'from torch import autograd, nn, optim\n'), ((2439, 2455), 'torch.nn.Linear', 'nn.Linear', (['(84)', '(2)'], {}), '(84, 2)\n', (2448, 2455), False, 'from torch import autograd, nn, optim\n'), ((826, 860), 'fnmatch.fnmatch', 'fnmatch.fnmatch', (['basename', 'pattern'], {}), '(basename, pattern)\n', (841, 860), False, 'import os, fnmatch\n'), ((1337, 1383), 'cv2.resize', 'cv2.resize', (['original_img', '(IMG_SIZE, IMG_SIZE)'], {}), '(original_img, (IMG_SIZE, IMG_SIZE))\n', (1347, 1383), False, 'import cv2\n'), ((3657, 3673), 'numpy.array', 'np.array', (['[i[0]]'], {}), '([i[0]])\n', (3665, 3673), True, 'import numpy as np\n'), ((5158, 5164), 'time.time', 'time', ([], {}), '()\n', (5162, 5164), False, 'from time import time\n'), ((889, 917), 'os.path.join', 'os.path.join', (['root', 'basename'], {}), '(root, basename)\n', (901, 917), False, 'import os, fnmatch\n'), ((1413, 1426), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (1421, 1426), True, 'import numpy as np\n'), ((1428, 1443), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (1436, 1443), True, 'import numpy as np\n'), ((3834, 3850), 'numpy.array', 'np.array', (['[i[0]]'], {}), '([i[0]])\n', (3842, 3850), True, 'import numpy as np\n')]
from csdl import Model import csdl import numpy as np class ExampleScalarRotX(Model): """ :param var: scalar :param var: scalar_Rot_x """ def define(self): angle_val3 = np.pi / 3 angle_scalar = self.declare_variable('scalar', val=angle_val3) # Rotation in the x-axis for scalar self.register_output('scalar_Rot_x', csdl.rotmat(angle_scalar, axis='x')) class ExampleScalarRotY(Model): """ :param var: scalar :param var: scalar_Rot_y """ def define(self): angle_val3 = np.pi / 3 angle_scalar = self.declare_variable('scalar', val=angle_val3) # Rotation in the y-axis for scalar self.register_output('scalar_Rot_y', csdl.rotmat(angle_scalar, axis='y')) class ExampleSameRadianTensorRotX(Model): """ :param var: tensor :param var: tensor_Rot_x """ def define(self): # Shape of a random tensor rotation matrix shape = (2, 3, 4) num_elements = np.prod(shape) # Tensor of angles in radians angle_val1 = np.repeat(np.pi / 3, num_elements).reshape(shape) # Adding the tensor as an input angle_tensor1 = self.declare_variable('tensor', val=angle_val1) # Rotation in the x-axis for tensor1 self.register_output('tensor_Rot_x', csdl.rotmat(angle_tensor1, axis='x')) class ExampleDiffRadianTensorRotX(Model): """ :param var: tensor :param var: tensor_Rot_x """ def define(self): # Shape of a random tensor rotation matrix shape = (2, 3, 4) num_elements = np.prod(shape) # Vector of angles in radians angle_val2 = np.repeat( np.pi / 3, num_elements) + 2 * np.pi * np.arange(num_elements) angle_val2 = angle_val2.reshape(shape) # Adding the vector as an input angle_tensor = self.declare_variable('tensor', val=angle_val2) # Rotation in the x-axis for tensor2 self.register_output('tensor_Rot_x', csdl.rotmat(angle_tensor, axis='x'))
[ "numpy.prod", "csdl.rotmat", "numpy.repeat", "numpy.arange" ]
[((1112, 1126), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (1119, 1126), True, 'import numpy as np\n'), ((1744, 1758), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (1751, 1758), True, 'import numpy as np\n'), ((371, 406), 'csdl.rotmat', 'csdl.rotmat', (['angle_scalar'], {'axis': '"""x"""'}), "(angle_scalar, axis='x')\n", (382, 406), False, 'import csdl\n'), ((782, 817), 'csdl.rotmat', 'csdl.rotmat', (['angle_scalar'], {'axis': '"""y"""'}), "(angle_scalar, axis='y')\n", (793, 817), False, 'import csdl\n'), ((1470, 1506), 'csdl.rotmat', 'csdl.rotmat', (['angle_tensor1'], {'axis': '"""x"""'}), "(angle_tensor1, axis='x')\n", (1481, 1506), False, 'import csdl\n'), ((1819, 1853), 'numpy.repeat', 'np.repeat', (['(np.pi / 3)', 'num_elements'], {}), '(np.pi / 3, num_elements)\n', (1828, 1853), True, 'import numpy as np\n'), ((2156, 2191), 'csdl.rotmat', 'csdl.rotmat', (['angle_tensor'], {'axis': '"""x"""'}), "(angle_tensor, axis='x')\n", (2167, 2191), False, 'import csdl\n'), ((1187, 1221), 'numpy.repeat', 'np.repeat', (['(np.pi / 3)', 'num_elements'], {}), '(np.pi / 3, num_elements)\n', (1196, 1221), True, 'import numpy as np\n'), ((1881, 1904), 'numpy.arange', 'np.arange', (['num_elements'], {}), '(num_elements)\n', (1890, 1904), True, 'import numpy as np\n')]
"""Sets a consistent plotting settings across the project. Example: Usage with simple plots:: from src.plot_settings import ( ps_defaults, label_subplots, get_dim, set_dim, PALETTE, STD_CLR_LIST, CAM_BLUE, BRICK_RED, OX_BLUE, ) ps_defaults(use_tex=True) # ---- example set of graphs --- import numpy as np import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) x = np.linspace(0, np.pi, num=100) axs[0, 0].plot(x, np.sin(x), color=STD_CLR_LIST[0]) axs[0, 1].plot(x, np.cos(x), color=STD_CLR_LIST[1]) axs[1, 0].plot(x, np.sinc(x), color=STD_CLR_LIST[2]) axs[1, 1].plot(x, np.abs(x), color=STD_CLR_LIST[3]) # set size set_dim(fig, fraction_of_line_width=1, ratio=(5 ** 0.5 - 1) / 2) # label subplots label_subplots(axs, start_from=0, fontsize=10) """ import numpy as np from sys import platform import itertools from distutils.spawn import find_executable from typing import Sequence, Tuple import matplotlib import seaborn as sns from src.constants import REPORT_WIDTH def ps_defaults(use_tex: bool = True, dpi: int = 600) -> None: """Apply plotting style to produce nice looking figures. Call this at the start of a script which uses `matplotlib`. Can enable `matplotlib` LaTeX backend if it is available. Args: use_tex (bool, optional): Whether or not to use latex matplotlib backend. Defaults to True. dpi (int, optional): Which dpi to set for the figures. Defaults to 600 dpi (high quality). 150 dpi probably fine for notebooks. Largest dpi needed for presentations. """ if platform == "darwin": matplotlib.use("TkAgg") # matplotlib.use('agg') this used to be required for jasmin p_general = { "font.family": "STIXGeneral", # Nice alternative font. # "font.family": "serif", # "font.serif": [], # Use 10pt font in plots, to match 10pt font in document "axes.labelsize": 10, "font.size": 10, "figure.dpi": dpi, "savefig.dpi": dpi, # Make the legend/label fonts a little smaller "legend.fontsize": 10, "xtick.labelsize": 9, "ytick.labelsize": 9, # Set the font for maths "mathtext.fontset": "cm", # "font.sans-serif": ["DejaVu Sans"], # gets rid of error messages # "font.monospace": [], "lines.linewidth": 1.0, "scatter.marker": "+", "image.cmap": "viridis", } matplotlib.rcParams.update(p_general) matplotlib.style.use("seaborn-colorblind") if use_tex and find_executable("latex"): p_setting = { "pgf.texsystem": "pdflatex", "text.usetex": True, "pgf.preamble": ( r"\usepackage[utf8x]{inputenc} \usepackage[T1]{fontenc}" + r"\usepackage[separate -uncertainty=true]{siunitx}" ), } else: p_setting = { "text.usetex": False, } matplotlib.rcParams.update(p_setting) def label_subplots( axs: Sequence[matplotlib.pyplot.axes], labels: Sequence[str] = [chr(ord("`") + z) for z in range(1, 27)], start_from: int = 0, fontsize: int = 10, x_pos: float = 0.02, y_pos: float = 0.95, ) -> None: """Adds (a), (b), (c) at the top left of each subplot panel. Labelling order achieved through ravelling the input `list` / `np.array`. Args: axs (Sequence[matplotlib.axes]): `list` or `np.array` of `matplotlib.pyplot.axes`. labels (Sequence[str]): A sequence of labels for the subplots. start_from (int, optional): skips first `start_from` labels. Defaults to 0. fontsize (int, optional): Font size for labels. Defaults to 10. x_pos (float, optional): Relative x position of labels. Defaults to 0.02. y_pos (float, optional): Relative y position of labels. Defaults to 0.95. Returns: void; alters the `matplotlib.pyplot.axes` objects Examples: Here is an example of using this function:: >>> label_subplots(axs, start_from=0, fontsize=10) """ if isinstance(axs, list): axs = np.asarray(axs) assert len(axs.ravel()) + start_from <= len(labels) subset_labels = [] for i in range(len(axs.ravel())): subset_labels.append(labels[i + start_from]) for i, label in enumerate(subset_labels): axs.ravel()[i].text( x_pos, y_pos, str("(" + label + ")"), color="black", transform=axs.ravel()[i].transAxes, fontsize=fontsize, fontweight="bold", va="top", ) def get_dim( width: float = REPORT_WIDTH, fraction_of_line_width: float = 1, ratio: float = (5 ** 0.5 - 1) / 2, ) -> Tuple[float, float]: """Return figure height, width in inches to avoid scaling in latex. Default width is `src.constants.REPORT_WIDTH`. Default ratio is golden ratio, with figure occupying full page width. Args: width (float, optional): Textwidth of the report to make fontsizes match. Defaults to `src.constants.REPORT_WIDTH`. fraction_of_line_width (float, optional): Fraction of the document width which you wish the figure to occupy. Defaults to 1. ratio (float, optional): Fraction of figure width that the figure height should be. Defaults to (5 ** 0.5 - 1)/2. Returns: fig_dim (tuple): Dimensions of figure in inches Examples: Here is an example of using this function:: >>> dim_tuple = get_dim(fraction_of_line_width=1, ratio=(5 ** 0.5 - 1) / 2) """ # Width of figure fig_width_pt = width * fraction_of_line_width # Convert from pt to inches inches_per_pt = 1 / 72.27 # Figure width in inches fig_width_in = fig_width_pt * inches_per_pt # Figure height in inches fig_height_in = fig_width_in * ratio fig_dim = (fig_width_in, fig_height_in) return fig_dim def set_dim( fig: matplotlib.pyplot.figure, width: float = REPORT_WIDTH, fraction_of_line_width: float = 1, ratio: float = (5 ** 0.5 - 1) / 2, ) -> None: """Set aesthetic figure dimensions to avoid scaling in latex. Default width is `src.constants.REPORT_WIDTH`. Default ratio is golden ratio, with figure occupying full page width. Args: fig (matplotlib.pyplot.figure): Figure object to resize. width (float): Textwidth of the report to make fontsizes match. Defaults to `src.constants.REPORT_WIDTH`. fraction_of_line_width (float, optional): Fraction of the document width which you wish the figure to occupy. Defaults to 1. ratio (float, optional): Fraction of figure width that the figure height should be. Defaults to (5 ** 0.5 - 1)/2. Returns: void; alters current figure to have the desired dimensions Examples: Here is an example of using this function:: >>> set_dim(fig, fraction_of_line_width=1, ratio=(5 ** 0.5 - 1) / 2) """ fig.set_size_inches( get_dim(width=width, fraction_of_line_width=fraction_of_line_width, ratio=ratio) ) STD_CLR_LIST = [ "#4d2923ff", "#494f1fff", "#38734bff", "#498489ff", "#8481baff", "#c286b2ff", "#d7a4a3ff", ] _paper_colors = sns.color_palette(STD_CLR_LIST) # Note: To inspect colors, call `sns.palplot(_paper_colors)` PALETTE = itertools.cycle(_paper_colors) CAM_BLUE = "#a3c1ad" OX_BLUE = "#002147" BRICK_RED = "#CB4154"
[ "itertools.cycle", "distutils.spawn.find_executable", "matplotlib.rcParams.update", "seaborn.color_palette", "matplotlib.use", "numpy.asarray", "matplotlib.style.use" ]
[((7616, 7647), 'seaborn.color_palette', 'sns.color_palette', (['STD_CLR_LIST'], {}), '(STD_CLR_LIST)\n', (7633, 7647), True, 'import seaborn as sns\n'), ((7719, 7749), 'itertools.cycle', 'itertools.cycle', (['_paper_colors'], {}), '(_paper_colors)\n', (7734, 7749), False, 'import itertools\n'), ((2677, 2714), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (['p_general'], {}), '(p_general)\n', (2703, 2714), False, 'import matplotlib\n'), ((2719, 2761), 'matplotlib.style.use', 'matplotlib.style.use', (['"""seaborn-colorblind"""'], {}), "('seaborn-colorblind')\n", (2739, 2761), False, 'import matplotlib\n'), ((3182, 3219), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (['p_setting'], {}), '(p_setting)\n', (3208, 3219), False, 'import matplotlib\n'), ((1843, 1866), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (1857, 1866), False, 'import matplotlib\n'), ((2782, 2806), 'distutils.spawn.find_executable', 'find_executable', (['"""latex"""'], {}), "('latex')\n", (2797, 2806), False, 'from distutils.spawn import find_executable\n'), ((4369, 4384), 'numpy.asarray', 'np.asarray', (['axs'], {}), '(axs)\n', (4379, 4384), True, 'import numpy as np\n')]
import numpy as np import cv2 from flask import Flask from flask import jsonify from flask import request from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker,relationship,scoped_session from flask_sqlalchemy_session import flask_scoped_session from sqlalchemy import create_engine from sqlalchemy import Column, Integer, Float, DateTime from dateutil import parser from ripeness_predictor import is_ripe app = Flask(__name__) Base = declarative_base() class TamatarData(Base): __tablename__ = 'tamatar' id = Column(Integer, primary_key=True) lat = Column(Float) lng = Column(Float) timestamp = Column(DateTime) ripe = Column(Integer) def get_sqlite3_session(path): engine = create_engine('sqlite:///' + path) Base.metadata.create_all(engine) return scoped_session(sessionmaker(bind=engine)) session = flask_scoped_session(get_sqlite3_session("db.db"), app) @app.route("/add", methods=["POST"]) def add_image(): lat = float(request.form['lat']) lng = float(request.form['lng']) dt = parser.parse(request.form["date"]) img_str = request.form['image'] nparr = np.fromstring(img_str, np.uint8) img_np = cv2.imdecode(nparr, 1) # cv2.IMREAD_COLOR in OpenCV 3.1 ripe = is_ripe(img_np) t = TamatarData(lat=lat, lng=lng, ripe=ripe) session.add(t) session.commit() return jsonify(status=True) @app.route("/get") def get_all(): query = session.query(TamatarData) if 'from' in request.form: frm = parser.parse(request.form['from']) query = query.filter(TamatarData.timestamp >= frm) if 'to' in request.form: to = parser.parse(request.form['to']) query = query.filter(TamatarData.timestamp <= to) res = list(query) return jsonify(result=res) app.run(host='0.0.0.0', threaded=True)
[ "dateutil.parser.parse", "sqlalchemy.orm.sessionmaker", "flask.Flask", "flask.jsonify", "sqlalchemy.create_engine", "cv2.imdecode", "sqlalchemy.ext.declarative.declarative_base", "numpy.fromstring", "sqlalchemy.Column", "ripeness_predictor.is_ripe" ]
[((457, 472), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (462, 472), False, 'from flask import Flask\n'), ((480, 498), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (496, 498), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((565, 598), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (571, 598), False, 'from sqlalchemy import Column, Integer, Float, DateTime\n'), ((609, 622), 'sqlalchemy.Column', 'Column', (['Float'], {}), '(Float)\n', (615, 622), False, 'from sqlalchemy import Column, Integer, Float, DateTime\n'), ((633, 646), 'sqlalchemy.Column', 'Column', (['Float'], {}), '(Float)\n', (639, 646), False, 'from sqlalchemy import Column, Integer, Float, DateTime\n'), ((663, 679), 'sqlalchemy.Column', 'Column', (['DateTime'], {}), '(DateTime)\n', (669, 679), False, 'from sqlalchemy import Column, Integer, Float, DateTime\n'), ((691, 706), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (697, 706), False, 'from sqlalchemy import Column, Integer, Float, DateTime\n'), ((752, 786), 'sqlalchemy.create_engine', 'create_engine', (["('sqlite:///' + path)"], {}), "('sqlite:///' + path)\n", (765, 786), False, 'from sqlalchemy import create_engine\n'), ((1083, 1117), 'dateutil.parser.parse', 'parser.parse', (["request.form['date']"], {}), "(request.form['date'])\n", (1095, 1117), False, 'from dateutil import parser\n'), ((1166, 1198), 'numpy.fromstring', 'np.fromstring', (['img_str', 'np.uint8'], {}), '(img_str, np.uint8)\n', (1179, 1198), True, 'import numpy as np\n'), ((1212, 1234), 'cv2.imdecode', 'cv2.imdecode', (['nparr', '(1)'], {}), '(nparr, 1)\n', (1224, 1234), False, 'import cv2\n'), ((1280, 1295), 'ripeness_predictor.is_ripe', 'is_ripe', (['img_np'], {}), '(img_np)\n', (1287, 1295), False, 'from ripeness_predictor import is_ripe\n'), ((1397, 1417), 'flask.jsonify', 'jsonify', ([], {'status': '(True)'}), '(status=True)\n', (1404, 1417), False, 'from flask import jsonify\n'), ((1799, 1818), 'flask.jsonify', 'jsonify', ([], {'result': 'res'}), '(result=res)\n', (1806, 1818), False, 'from flask import jsonify\n'), ((850, 875), 'sqlalchemy.orm.sessionmaker', 'sessionmaker', ([], {'bind': 'engine'}), '(bind=engine)\n', (862, 875), False, 'from sqlalchemy.orm import sessionmaker, relationship, scoped_session\n'), ((1538, 1572), 'dateutil.parser.parse', 'parser.parse', (["request.form['from']"], {}), "(request.form['from'])\n", (1550, 1572), False, 'from dateutil import parser\n'), ((1674, 1706), 'dateutil.parser.parse', 'parser.parse', (["request.form['to']"], {}), "(request.form['to'])\n", (1686, 1706), False, 'from dateutil import parser\n')]
import contextlib import logging import rasterio.crs import rasterio.vrt import rasterio.windows import affine import numpy as np import xarray as xr logger = logging.getLogger(__name__) CRS_WGS = rasterio.crs.CRS({'init': 'epsg:4326'}) def _datasets_are_congruent(datasets): """Determine whether datasets are congruent""" profiles = set((src.height, src.width, src.transform, src.crs.to_string()) for src in datasets) return (len(profiles) == 1), profiles def select_extract_class_points( select_path, extract_path, select_class, bounds=None, remove_empty_extracted=True, ): """Find points corresponding to class Parameters ---------- select_path : str or Path path to raster with classes to select extract_path : str or Path path to raster with data to extract at selected points select_class : int value for class to select bounds : tuple (xmin, ymin, xmax, ymax), optional bounds within file to search in lat, lon coordinates remove_empty_extracted : bool remove points where extracted data is nodata Yields ------ xr.Dataset coordinates of points in selection dataset that are equal to select_class together with extracted values from extract dataset and indices in original image (for raster reconstruction) """ with contextlib.ExitStack() as es: datasets = [ es.enter_context(rasterio.open(path)) for path in [select_path, extract_path] ] congruent, profiles = _datasets_are_congruent(datasets) if not congruent: raise ValueError( f'Datasets must be perfectly congruent. Got {profiles}.' ) # take first dataset as model src = datasets[0] if src.crs != CRS_WGS: raise ValueError(f'Expecting datasets in WGS84. Got {src.crs}.') if bounds is not None: logger.debug(f'Clipping data to bounds {bounds}') # limit dataset to bounds window = src.window(*bounds) window = window.round_offsets().round_shape() transform = src.window_transform(window) vrts = [ es.enter_context(rasterio.vrt.WarpedVRT( src, transform=transform, width=window.width, height=window.height )) for src in datasets ] else: # pass vrts = datasets sds, xds = vrts # select class points seldata = sds.read(1) selcond = seldata == select_class if not np.any(selcond): raise ValueError( f'No points found for class value {select_class} (within bounding box).' ) jj, ii = np.where(selcond) extracted = xds.read(1)[selcond] if remove_empty_extracted: # remove points where extracted is nodata good = extracted != xds.nodata logger.info(f'Dropping {np.sum(~good)} points where extracted data is nodata.') extracted = extracted[good] ii = ii[good] jj = jj[good] # convert pixel indices to lon, lat coordinates lon, lat = sds.transform * (ii, jj) # store all in Dataset variables = {'lon': lon, 'lat': lat, 'i': ii, 'j': jj, 'extracted': extracted} data_vars = { name: xr.DataArray(data, dims='point', name=name) for name, data in variables.items() } ds = xr.Dataset(data_vars, coords={'point': np.arange(len(lon))}) ds.attrs.update({name: sds.profile[name] for name in ['width', 'height']}) # properly serialize transform ds.attrs['transform'] = list(sds.profile['transform']) return ds def interpolate_to_points(da, ixds): """Interpolate data array to points Parameters ---------- da : DataArray data to interpolate ixds : Dataset dataset with lon, lat, i, j coordinates to interpolate at Returns ------- DataArray interpolated data array with points dimension and passed-through i, j indices """ ida = da.interp(coords=ixds[['lon', 'lat']], method='linear') # preserve i,j indices for name in ['j', 'i']: ida.coords[name] = ixds[name] return ida def lonlat_from_transform(transform, width, height): """Make lon, lat arrays from transform and shape""" lon, _ = transform * (np.arange(width) + 0.5, np.full(shape=width, fill_value=0.5)) _, lat = transform * (np.full(shape=height, fill_value=0.5), np.arange(height, 0, -1) - 0.5) return lon, lat def points_to_2d(ds): """Map points dataset back to 2D coordinates Parameters ---------- ds : Dataset dataset with points Returns ------- ds dataset with lon, lat """ shape = height, width = (ds.attrs['height'], ds.attrs['width']) transform = affine.Affine(*ds.attrs['transform'][:6]) lon, lat = lonlat_from_transform(transform, width=width, height=height) coords = dict(lon=lon, lat=lat) darrs = {} for name, da in ds.data_vars.items(): data = np.ma.zeros(shape=shape, dtype=da.dtype) data[:] = np.ma.masked data[ds['j'], ds['i']] = da.values darrs[name] = xr.DataArray(data, dims=('lat', 'lon'), name=name) dsout = xr.Dataset(darrs, coords=coords) dsout['time'] = ds['time'] return dsout
[ "logging.getLogger", "numpy.where", "numpy.ma.zeros", "xarray.Dataset", "numpy.any", "numpy.sum", "contextlib.ExitStack", "affine.Affine", "xarray.DataArray", "numpy.full", "numpy.arange" ]
[((161, 188), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (178, 188), False, 'import logging\n'), ((5016, 5057), 'affine.Affine', 'affine.Affine', (["*ds.attrs['transform'][:6]"], {}), "(*ds.attrs['transform'][:6])\n", (5029, 5057), False, 'import affine\n'), ((5444, 5476), 'xarray.Dataset', 'xr.Dataset', (['darrs'], {'coords': 'coords'}), '(darrs, coords=coords)\n', (5454, 5476), True, 'import xarray as xr\n'), ((1392, 1414), 'contextlib.ExitStack', 'contextlib.ExitStack', ([], {}), '()\n', (1412, 1414), False, 'import contextlib\n'), ((2809, 2826), 'numpy.where', 'np.where', (['selcond'], {}), '(selcond)\n', (2817, 2826), True, 'import numpy as np\n'), ((5243, 5283), 'numpy.ma.zeros', 'np.ma.zeros', ([], {'shape': 'shape', 'dtype': 'da.dtype'}), '(shape=shape, dtype=da.dtype)\n', (5254, 5283), True, 'import numpy as np\n'), ((5380, 5430), 'xarray.DataArray', 'xr.DataArray', (['data'], {'dims': "('lat', 'lon')", 'name': 'name'}), "(data, dims=('lat', 'lon'), name=name)\n", (5392, 5430), True, 'import xarray as xr\n'), ((2642, 2657), 'numpy.any', 'np.any', (['selcond'], {}), '(selcond)\n', (2648, 2657), True, 'import numpy as np\n'), ((3445, 3488), 'xarray.DataArray', 'xr.DataArray', (['data'], {'dims': '"""point"""', 'name': 'name'}), "(data, dims='point', name=name)\n", (3457, 3488), True, 'import xarray as xr\n'), ((4558, 4594), 'numpy.full', 'np.full', ([], {'shape': 'width', 'fill_value': '(0.5)'}), '(shape=width, fill_value=0.5)\n', (4565, 4594), True, 'import numpy as np\n'), ((4622, 4659), 'numpy.full', 'np.full', ([], {'shape': 'height', 'fill_value': '(0.5)'}), '(shape=height, fill_value=0.5)\n', (4629, 4659), True, 'import numpy as np\n'), ((4534, 4550), 'numpy.arange', 'np.arange', (['width'], {}), '(width)\n', (4543, 4550), True, 'import numpy as np\n'), ((4661, 4685), 'numpy.arange', 'np.arange', (['height', '(0)', '(-1)'], {}), '(height, 0, -1)\n', (4670, 4685), True, 'import numpy as np\n'), ((3037, 3050), 'numpy.sum', 'np.sum', (['(~good)'], {}), '(~good)\n', (3043, 3050), True, 'import numpy as np\n')]
from tpot import TPOTRegressor from tpot import TPOTClassifier from sklearn.model_selection import train_test_split import numpy as np from models.classes import prepare as prepare from models.classes import randomforest as randomforest from models.classes import randomforestc as randomforestc from sklearn.metrics.scorer import make_scorer from sklearn.metrics import r2_score import matplotlib.pyplot as plt import pandas as pd import random, os, json, datetime from timeit import default_timer as timer #random.seed(36) def tpot_c(input_file_loc): dirName = 'pickled' try: # Create target Directory os.mkdir(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists. Skipping creation.") dirName = 'predictions' try: # Create target Directory os.mkdir(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists. Skipping creation.") if input_file_loc: with open(input_file_loc, 'r') as f: datastore = json.load(f) current_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/'+datastore["folder_name"]["content"] +'/' filename = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/'+datastore["folder_name"]["content"] +'/' +datastore["dataset_name"]["content"] selected_data, IDboolean = prepare.isolate(structname= datastore["column_SMILES"]['content'], activityname = datastore["column_activity"]["content"], filelocation = filename , chemID = datastore["chemID"]["content"]) print("-----------------------------------") print("Cleaning Data") print("-----------------------------------\n") inDF = prepare.cleanSMILES(df = selected_data, elementskept = datastore["elements_kept"]["content"], smilesName = datastore["column_SMILES"]["content"]) print("-----------------------------------") print("Curating Descriptors") print("-----------------------------------\n") print(f"Number of Compounds: {inDF.shape[0]}") inDF = prepare.createdescriptors(df = inDF, colName = datastore["column_SMILES"]['content'], correlationthreshold = datastore["correlation_threshold"]['content'], STDthreshold = datastore['std_threshold']['content'], IDboolean = IDboolean) #print(inDF.head) activityValidDF, activityTrainDF, activityTestDF, IDValidDF, IDTrainDF, IDTestDF, validDF, trainDF, testDF, nameValidDF, nameTrainDF, nameTestDF, _= prepare.partition(df = inDF,validset = datastore['valid_split']['content'], testset = datastore['test_split'] ['content'], IDboolean = IDboolean) print("-----------------------------------") print("Partitioning Data") print("-----------------------------------\n") X_Valid = validDF Y_Valid = activityValidDF X_Train = trainDF Y_Train = activityTrainDF X_Test = testDF Y_Test = activityTestDF #print(X_Valid) #print(Y_Train) # Make a custom metric function def my_custom_accuracy(y_true, y_pred): return r2_score(y_true, y_pred) my_custom_scorer = make_scorer(my_custom_accuracy, greater_is_better=True) start = timer() tpot = TPOTClassifier(generations=50, population_size=50, verbosity=2, cv = 10, n_jobs = -1, use_dask = False, periodic_checkpoint_folder = '/Users/spencerhong/Documents/QSARBayesOpt/autotest/tpot_check') tpot.fit(X_Train, Y_Train) Y_Test_Pred = tpot.predict(X_Test) Y_Train_Pred = tpot.predict(X_Train) Y_Valid_Pred = tpot.predict(X_Valid) SMILESTest = [] YTestList = [] YTestPredList = [] SMILESValid = [] YValidList = [] YValidPredList = [] for i in range(0,IDTestDF.shape[0]): SMILESTest.append(IDTestDF.loc[:,].values[i]) YTestList.append(Y_Test.loc[:,].values[i]) YTestPredList.append(Y_Test_Pred[i]) for i in range(0,IDTrainDF.shape[0]): #NAMESList.append(nameTrainDF.loc[:, ].values[i]) SMILESTest.append(IDTrainDF.loc[:,].values[i]) YTestList.append(Y_Train.loc[:,].values[i]) YTestPredList.append(Y_Train_Pred[i]) res = pd.DataFrame({'SMILES':SMILESTest, 'Actual':YTestList, 'Prediction':YTestPredList}) SMILESTest = [] YTestList = [] YTestPredList = [] #NAMESList = [] for i in range(0,IDValidDF.shape[0]): #NAMESList.append(nameValidDF.loc[:, ].values[i]) SMILESTest.append(IDValidDF.loc[:,].values[i]) YTestList.append(Y_Valid.loc[:,].values[i]) YTestPredList.append(Y_Valid_Pred[i]) res_valid = pd.DataFrame({'SMILES':SMILESTest, 'Actual':YTestList, 'Prediction':YTestPredList}) res.to_csv(current_folder + 'predictions/automl_test.csv', sep=',') res_valid.to_csv(current_folder + 'predictions/automl_valid.csv', sep=',') print(r2_score(Y_Test, Y_Test_Pred)) print('---------------------------\n') print('TIME') end = timer() time_duration = end - start print(f"Time taken: {time_duration}") # Time in seconds, e.g. 5.38091952400282 tpot.export('tpot_classification.py') del(res) del(res_valid) del(X_Train) return time_duration, r2_score(Y_Train, Y_Train_Pred), r2_score(Y_Test, Y_Test_Pred), r2_score(Y_Valid, Y_Valid_Pred) def tpot_r(input_file_loc): dirName = 'pickled' try: # Create target Directory os.mkdir(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists. Skipping creation.") dirName = 'predictions' try: # Create target Directory os.mkdir(dirName) print("Directory " , dirName , " Created ") except FileExistsError: print("Directory " , dirName , " already exists. Skipping creation.") if input_file_loc: with open(input_file_loc, 'r') as f: datastore = json.load(f) current_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/'+datastore["folder_name"]["content"] +'/' filename = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/'+datastore["folder_name"]["content"] +'/' +datastore["dataset_name"]["content"] selected_data, IDboolean = prepare.isolate(structname= datastore["column_SMILES"]['content'], activityname = datastore["column_activity"]["content"], filelocation = filename , chemID = datastore["chemID"]["content"]) print("-----------------------------------") print("Cleaning Data") print("-----------------------------------\n") inDF = prepare.cleanSMILES(df = selected_data, elementskept = datastore["elements_kept"]["content"], smilesName = datastore["column_SMILES"]["content"]) print("-----------------------------------") print("Curating Descriptors") print("-----------------------------------\n") print(f"Number of Compounds: {inDF.shape[0]}") inDF = prepare.createdescriptors(df = inDF, colName = datastore["column_SMILES"]['content'], correlationthreshold = datastore["correlation_threshold"]['content'], STDthreshold = datastore['std_threshold']['content'], IDboolean = IDboolean) #print(inDF.head) activityValidDF, activityTrainDF, activityTestDF, IDValidDF, IDTrainDF, IDTestDF, validDF, trainDF, testDF, nameValidDF, nameTrainDF, nameTestDF, _ = prepare.partition(df = inDF,validset = datastore['valid_split']['content'], testset = datastore['test_split'] ['content'], IDboolean = IDboolean) print("-----------------------------------") print("Partitioning Data") print("-----------------------------------\n") X_Valid = validDF Y_Valid = activityValidDF X_Train = trainDF Y_Train = activityTrainDF X_Test = testDF Y_Test = activityTestDF #print(X_Valid) #print(Y_Train) # Make a custom metric function def my_custom_accuracy(y_true, y_pred): return r2_score(y_true, y_pred) my_custom_scorer = make_scorer(my_custom_accuracy, greater_is_better=True) start = timer() tpot = TPOTRegressor(generations=25, population_size=25, verbosity=2, cv = 10, n_jobs = -1, use_dask = False, periodic_checkpoint_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+'/'+datastore["folder_name"]["content"] +'/') tpot.fit(X_Train, Y_Train) print("-----------------------------------") print("Saving Predictions...") print("-----------------------------------\n") Y_Test_Pred = tpot.predict(X_Test) Y_Train_Pred = tpot.predict(X_Train) Y_Valid_Pred = tpot.predict(X_Valid) SMILESTest = [] YTestList = [] YTestPredList = [] SMILESValid = [] YValidList = [] YValidPredList = [] for i in range(0,IDTestDF.shape[0]): SMILESTest.append(IDTestDF.loc[:,].values[i]) YTestList.append(Y_Test.loc[:,].values[i]) YTestPredList.append(Y_Test_Pred[i]) for i in range(0,IDTrainDF.shape[0]): #NAMESList.append(nameTrainDF.loc[:, ].values[i]) SMILESTest.append(IDTrainDF.loc[:,].values[i]) YTestList.append(Y_Train.loc[:,].values[i]) YTestPredList.append(Y_Train_Pred[i]) res = pd.DataFrame({'SMILES':SMILESTest, 'Actual':YTestList, 'Prediction':YTestPredList}) SMILESTest = [] YTestList = [] YTestPredList = [] #NAMESList = [] for i in range(0,IDValidDF.shape[0]): #NAMESList.append(nameValidDF.loc[:, ].values[i]) SMILESTest.append(IDValidDF.loc[:,].values[i]) YTestList.append(Y_Valid.loc[:,].values[i]) YTestPredList.append(Y_Valid_Pred[i]) res_valid = pd.DataFrame({'SMILES':SMILESTest, 'Actual':YTestList, 'Prediction':YTestPredList}) res.to_csv(current_folder + 'predictions/automl_test.csv', sep=',') res_valid.to_csv(current_folder + 'predictions/automl_valid.csv', sep=',') print(r2_score(Y_Test, Y_Test_Pred)) end = timer() print('---------------------------\n') print('TIME') time_duration = end - start print(f"Time taken: {time_duration}")# Time in seconds, e.g. 5.38091952400282 tpot.export('tpot_regression.py') print("-----------------------------------") print("Time to do visualizations!") print("-----------------------------------\n") ## df is a dataframe containing the smiles, actual, and prediction ## returns the dataframe containing leverages def calculate_leverage(df): actualmean = df['Actual'].mean() num = df.shape[0] denom = 0 for i in range(0, num): denom += (df['Actual'][i] - actualmean) ** 2. outside=[] leverage = [] for i in range(0, num): leverage_i = ((df['Actual'][i] - actualmean)** 2.)/(denom) + (1/num) leverage.append(leverage_i) if leverage_i > 0.012: outside.append('Invalid') else: outside.append('Valid') df.insert(2, "Leverage", leverage, True) df.insert(2, "Domain", outside, True) return df def calculate_residuals(df): df.insert(2, "Residual", df['Actual']-df['Prediction'], True) return df def calculate_standard_residuals(df): df.insert(2, "Standard Residual", df['Residual']/(df['Residual'].std()), True) print(df) domain = [] for i in range(0, df.shape[0]): if ((df['Residual'][i]/(df['Residual'].std()) > 1.5 ) | (df['Residual'][i]/(df['Residual'].std()) < -1.5)) & (df['Domain'][i] == 'Valid'): domain.append('Valid') else: domain.append('Invalid') del df['Domain'] df.insert(2, 'Domain', domain, True) return df train_plot = calculate_leverage(res) train_plot = calculate_residuals(train_plot) train_plot = calculate_standard_residuals(train_plot) test_plot = calculate_leverage(res_valid) test_plot = calculate_residuals(test_plot) test_plot = calculate_standard_residuals(test_plot) fig, ax = plt.subplots() ax.scatter(train_plot['Leverage'], train_plot['Residual'], marker='o', c='blue', label = 'Train') ax.scatter(test_plot['Leverage'], test_plot['Residual'], marker='o', c='red', label = 'Test') ax.axhline(y=1.5, xmin=0, xmax=3.0, color='k') ax.set_xlabel('Leverage') ax.set_ylabel('Standardized Residuals') ax.axhline(y=-1.5, xmin=0.0, xmax=3.0, color='k') ax.axvline(x=0.012, ymin=np.min(train_plot['Residual']) - np.min(train_plot['Residual'] * 0.05), ymax=np.max(train_plot['Residual']) + np.max(train_plot['Residual'] * 0.05), color='k') #ax.set_xlim([0, np.max(train_plot['Leverage']) + np.max(train_plot['Leverage']) * 0.05]) ax.legend() try: # Create target Directory os.mkdir("visualizations") print("Visualizations Directory Created ") except FileExistsError: print("Visualizations Directory already exists. Skipping creation.") fig.savefig('visualizations/automLregression.png') del(res) del(res_valid) del(X_Train) return time_duration, r2_score(Y_Train, Y_Train_Pred), r2_score(Y_Test, Y_Test_Pred), r2_score(Y_Valid, Y_Valid_Pred)
[ "pandas.DataFrame", "models.classes.prepare.cleanSMILES", "timeit.default_timer", "models.classes.prepare.partition", "models.classes.prepare.createdescriptors", "json.load", "numpy.max", "tpot.TPOTClassifier", "os.mkdir", "numpy.min", "sklearn.metrics.scorer.make_scorer", "sklearn.metrics.r2_...
[((1386, 1576), 'models.classes.prepare.isolate', 'prepare.isolate', ([], {'structname': "datastore['column_SMILES']['content']", 'activityname': "datastore['column_activity']['content']", 'filelocation': 'filename', 'chemID': "datastore['chemID']['content']"}), "(structname=datastore['column_SMILES']['content'],\n activityname=datastore['column_activity']['content'], filelocation=\n filename, chemID=datastore['chemID']['content'])\n", (1401, 1576), True, 'from models.classes import prepare as prepare\n'), ((1703, 1852), 'models.classes.prepare.cleanSMILES', 'prepare.cleanSMILES', ([], {'df': 'selected_data', 'elementskept': "datastore['elements_kept']['content']", 'smilesName': "datastore['column_SMILES']['content']"}), "(df=selected_data, elementskept=datastore[\n 'elements_kept']['content'], smilesName=datastore['column_SMILES'][\n 'content'])\n", (1722, 1852), True, 'from models.classes import prepare as prepare\n'), ((2030, 2266), 'models.classes.prepare.createdescriptors', 'prepare.createdescriptors', ([], {'df': 'inDF', 'colName': "datastore['column_SMILES']['content']", 'correlationthreshold': "datastore['correlation_threshold']['content']", 'STDthreshold': "datastore['std_threshold']['content']", 'IDboolean': 'IDboolean'}), "(df=inDF, colName=datastore['column_SMILES'][\n 'content'], correlationthreshold=datastore['correlation_threshold'][\n 'content'], STDthreshold=datastore['std_threshold']['content'],\n IDboolean=IDboolean)\n", (2055, 2266), True, 'from models.classes import prepare as prepare\n'), ((2432, 2573), 'models.classes.prepare.partition', 'prepare.partition', ([], {'df': 'inDF', 'validset': "datastore['valid_split']['content']", 'testset': "datastore['test_split']['content']", 'IDboolean': 'IDboolean'}), "(df=inDF, validset=datastore['valid_split']['content'],\n testset=datastore['test_split']['content'], IDboolean=IDboolean)\n", (2449, 2573), True, 'from models.classes import prepare as prepare\n'), ((2998, 3053), 'sklearn.metrics.scorer.make_scorer', 'make_scorer', (['my_custom_accuracy'], {'greater_is_better': '(True)'}), '(my_custom_accuracy, greater_is_better=True)\n', (3009, 3053), False, 'from sklearn.metrics.scorer import make_scorer\n'), ((3063, 3070), 'timeit.default_timer', 'timer', ([], {}), '()\n', (3068, 3070), True, 'from timeit import default_timer as timer\n'), ((3079, 3277), 'tpot.TPOTClassifier', 'TPOTClassifier', ([], {'generations': '(50)', 'population_size': '(50)', 'verbosity': '(2)', 'cv': '(10)', 'n_jobs': '(-1)', 'use_dask': '(False)', 'periodic_checkpoint_folder': '"""/Users/spencerhong/Documents/QSARBayesOpt/autotest/tpot_check"""'}), "(generations=50, population_size=50, verbosity=2, cv=10,\n n_jobs=-1, use_dask=False, periodic_checkpoint_folder=\n '/Users/spencerhong/Documents/QSARBayesOpt/autotest/tpot_check')\n", (3093, 3277), False, 'from tpot import TPOTClassifier\n'), ((3931, 4021), 'pandas.DataFrame', 'pd.DataFrame', (["{'SMILES': SMILESTest, 'Actual': YTestList, 'Prediction': YTestPredList}"], {}), "({'SMILES': SMILESTest, 'Actual': YTestList, 'Prediction':\n YTestPredList})\n", (3943, 4021), True, 'import pandas as pd\n'), ((4328, 4418), 'pandas.DataFrame', 'pd.DataFrame', (["{'SMILES': SMILESTest, 'Actual': YTestList, 'Prediction': YTestPredList}"], {}), "({'SMILES': SMILESTest, 'Actual': YTestList, 'Prediction':\n YTestPredList})\n", (4340, 4418), True, 'import pandas as pd\n'), ((4658, 4665), 'timeit.default_timer', 'timer', ([], {}), '()\n', (4663, 4665), True, 'from timeit import default_timer as timer\n'), ((5836, 6026), 'models.classes.prepare.isolate', 'prepare.isolate', ([], {'structname': "datastore['column_SMILES']['content']", 'activityname': "datastore['column_activity']['content']", 'filelocation': 'filename', 'chemID': "datastore['chemID']['content']"}), "(structname=datastore['column_SMILES']['content'],\n activityname=datastore['column_activity']['content'], filelocation=\n filename, chemID=datastore['chemID']['content'])\n", (5851, 6026), True, 'from models.classes import prepare as prepare\n'), ((6153, 6302), 'models.classes.prepare.cleanSMILES', 'prepare.cleanSMILES', ([], {'df': 'selected_data', 'elementskept': "datastore['elements_kept']['content']", 'smilesName': "datastore['column_SMILES']['content']"}), "(df=selected_data, elementskept=datastore[\n 'elements_kept']['content'], smilesName=datastore['column_SMILES'][\n 'content'])\n", (6172, 6302), True, 'from models.classes import prepare as prepare\n'), ((6480, 6716), 'models.classes.prepare.createdescriptors', 'prepare.createdescriptors', ([], {'df': 'inDF', 'colName': "datastore['column_SMILES']['content']", 'correlationthreshold': "datastore['correlation_threshold']['content']", 'STDthreshold': "datastore['std_threshold']['content']", 'IDboolean': 'IDboolean'}), "(df=inDF, colName=datastore['column_SMILES'][\n 'content'], correlationthreshold=datastore['correlation_threshold'][\n 'content'], STDthreshold=datastore['std_threshold']['content'],\n IDboolean=IDboolean)\n", (6505, 6716), True, 'from models.classes import prepare as prepare\n'), ((6883, 7024), 'models.classes.prepare.partition', 'prepare.partition', ([], {'df': 'inDF', 'validset': "datastore['valid_split']['content']", 'testset': "datastore['test_split']['content']", 'IDboolean': 'IDboolean'}), "(df=inDF, validset=datastore['valid_split']['content'],\n testset=datastore['test_split']['content'], IDboolean=IDboolean)\n", (6900, 7024), True, 'from models.classes import prepare as prepare\n'), ((7451, 7506), 'sklearn.metrics.scorer.make_scorer', 'make_scorer', (['my_custom_accuracy'], {'greater_is_better': '(True)'}), '(my_custom_accuracy, greater_is_better=True)\n', (7462, 7506), False, 'from sklearn.metrics.scorer import make_scorer\n'), ((7516, 7523), 'timeit.default_timer', 'timer', ([], {}), '()\n', (7521, 7523), True, 'from timeit import default_timer as timer\n'), ((8549, 8639), 'pandas.DataFrame', 'pd.DataFrame', (["{'SMILES': SMILESTest, 'Actual': YTestList, 'Prediction': YTestPredList}"], {}), "({'SMILES': SMILESTest, 'Actual': YTestList, 'Prediction':\n YTestPredList})\n", (8561, 8639), True, 'import pandas as pd\n'), ((8946, 9036), 'pandas.DataFrame', 'pd.DataFrame', (["{'SMILES': SMILESTest, 'Actual': YTestList, 'Prediction': YTestPredList}"], {}), "({'SMILES': SMILESTest, 'Actual': YTestList, 'Prediction':\n YTestPredList})\n", (8958, 9036), True, 'import pandas as pd\n'), ((9221, 9228), 'timeit.default_timer', 'timer', ([], {}), '()\n', (9226, 9228), True, 'from timeit import default_timer as timer\n'), ((11055, 11069), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (11067, 11069), True, 'import matplotlib.pyplot as plt\n'), ((610, 627), 'os.mkdir', 'os.mkdir', (['dirName'], {}), '(dirName)\n', (618, 627), False, 'import random, os, json, datetime\n'), ((832, 849), 'os.mkdir', 'os.mkdir', (['dirName'], {}), '(dirName)\n', (840, 849), False, 'import random, os, json, datetime\n'), ((2953, 2977), 'sklearn.metrics.r2_score', 'r2_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (2961, 2977), False, 'from sklearn.metrics import r2_score\n'), ((4565, 4594), 'sklearn.metrics.r2_score', 'r2_score', (['Y_Test', 'Y_Test_Pred'], {}), '(Y_Test, Y_Test_Pred)\n', (4573, 4594), False, 'from sklearn.metrics import r2_score\n'), ((4879, 4910), 'sklearn.metrics.r2_score', 'r2_score', (['Y_Train', 'Y_Train_Pred'], {}), '(Y_Train, Y_Train_Pred)\n', (4887, 4910), False, 'from sklearn.metrics import r2_score\n'), ((4912, 4941), 'sklearn.metrics.r2_score', 'r2_score', (['Y_Test', 'Y_Test_Pred'], {}), '(Y_Test, Y_Test_Pred)\n', (4920, 4941), False, 'from sklearn.metrics import r2_score\n'), ((4943, 4974), 'sklearn.metrics.r2_score', 'r2_score', (['Y_Valid', 'Y_Valid_Pred'], {}), '(Y_Valid, Y_Valid_Pred)\n', (4951, 4974), False, 'from sklearn.metrics import r2_score\n'), ((5060, 5077), 'os.mkdir', 'os.mkdir', (['dirName'], {}), '(dirName)\n', (5068, 5077), False, 'import random, os, json, datetime\n'), ((5282, 5299), 'os.mkdir', 'os.mkdir', (['dirName'], {}), '(dirName)\n', (5290, 5299), False, 'import random, os, json, datetime\n'), ((7406, 7430), 'sklearn.metrics.r2_score', 'r2_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (7414, 7430), False, 'from sklearn.metrics import r2_score\n'), ((9183, 9212), 'sklearn.metrics.r2_score', 'r2_score', (['Y_Test', 'Y_Test_Pred'], {}), '(Y_Test, Y_Test_Pred)\n', (9191, 9212), False, 'from sklearn.metrics import r2_score\n'), ((11765, 11791), 'os.mkdir', 'os.mkdir', (['"""visualizations"""'], {}), "('visualizations')\n", (11773, 11791), False, 'import random, os, json, datetime\n'), ((12059, 12090), 'sklearn.metrics.r2_score', 'r2_score', (['Y_Train', 'Y_Train_Pred'], {}), '(Y_Train, Y_Train_Pred)\n', (12067, 12090), False, 'from sklearn.metrics import r2_score\n'), ((12092, 12121), 'sklearn.metrics.r2_score', 'r2_score', (['Y_Test', 'Y_Test_Pred'], {}), '(Y_Test, Y_Test_Pred)\n', (12100, 12121), False, 'from sklearn.metrics import r2_score\n'), ((12123, 12154), 'sklearn.metrics.r2_score', 'r2_score', (['Y_Valid', 'Y_Valid_Pred'], {}), '(Y_Valid, Y_Valid_Pred)\n', (12131, 12154), False, 'from sklearn.metrics import r2_score\n'), ((1067, 1079), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1076, 1079), False, 'import random, os, json, datetime\n'), ((5517, 5529), 'json.load', 'json.load', (['f'], {}), '(f)\n', (5526, 5529), False, 'import random, os, json, datetime\n'), ((11457, 11487), 'numpy.min', 'np.min', (["train_plot['Residual']"], {}), "(train_plot['Residual'])\n", (11463, 11487), True, 'import numpy as np\n'), ((11490, 11527), 'numpy.min', 'np.min', (["(train_plot['Residual'] * 0.05)"], {}), "(train_plot['Residual'] * 0.05)\n", (11496, 11527), True, 'import numpy as np\n'), ((11534, 11564), 'numpy.max', 'np.max', (["train_plot['Residual']"], {}), "(train_plot['Residual'])\n", (11540, 11564), True, 'import numpy as np\n'), ((11567, 11604), 'numpy.max', 'np.max', (["(train_plot['Residual'] * 0.05)"], {}), "(train_plot['Residual'] * 0.05)\n", (11573, 11604), True, 'import numpy as np\n'), ((1130, 1155), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (1145, 1155), False, 'import random, os, json, datetime\n'), ((5580, 5605), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (5595, 5605), False, 'import random, os, json, datetime\n'), ((1247, 1272), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (1262, 1272), False, 'import random, os, json, datetime\n'), ((5697, 5722), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (5712, 5722), False, 'import random, os, json, datetime\n'), ((7696, 7721), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (7711, 7721), False, 'import random, os, json, datetime\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt aux = { 'get_server': 'Get server delay', 'start_session': 'Start session delay', 'stop_session': 'Stop session delay', 'srv_request': 'Service request delay', } def plot_ue_service_delay(time, delay, ue_id=None, service_id=None, action=None, alpha=1): delay_ = apply_ema(delay, alpha) plt.plot(time, delay_) plt.xlabel('time [s]', fontsize=12) plt.ylabel('delay [s]', fontsize=12) title = aux.get(action, 'Delay') if ue_id is not None: title += ' perceived by UE {}'.format(ue_id) if service_id is not None: title += ' for service {}'.format(service_id) if alpha < 1: title += ' (EMA,alpha={})'.format(alpha) plt.title(title) plt.show() def plot_bw(time, ue_id, ap_id, bandwidth, rate, efficiency, link='Uplink', alpha=1): bandwidth_ = apply_ema(bandwidth, alpha) rate_ = apply_ema(rate, alpha) efficiency_ = apply_ema(efficiency, alpha) plt.plot(time, bandwidth_) plt.plot(time, rate_) plt.xlabel('time [s]', fontsize=12) plt.legend(['bandwidth [Hz]', 'bitrate [bps]'], prop={'size': 12}) title = '{} bandwidth and bit rate'.format(link) if alpha < 1: title += ' (EMA,alpha={})'.format(alpha) plt.title(title) plt.show() plt.plot(time, efficiency_) plt.xlabel('time [s]', fontsize=12) plt.ylabel('spectral efficiency [bps/Hz]', fontsize=12) title = '{} spectral efficiency'.format(link) if alpha < 1: title += ' (EMA,alpha={})'.format(alpha) plt.title(title) plt.show() def plot_edc_utilization(time, edc_id, utilization, stacked=False, alpha=1): title = 'Edge Data Centers Utilization Factor' if stacked: title = 'Stacked ' + title graph_data = { 'xlabel': 'time [s]', 'ylabel': 'EDC utilization [%]', 'title': title } if stacked: stacked_graph(time, edc_id, utilization, graph_data, alpha) else: multiple_graph(time, edc_id, utilization, graph_data, alpha) def plot_edc_power(time, edc_id, power, stacked=False, alpha=1, nature='Demand'): title = 'Edge Data Centers Power ' + nature if stacked: title = 'Stacked ' + title graph_data = { 'xlabel': 'time [s]', 'ylabel': 'power [W]', 'title': title } if stacked: stacked_graph(time, edc_id, power, graph_data, alpha) else: multiple_graph(time, edc_id, power, graph_data, alpha) def plot_edc_energy(time, edc_id, energy, alpha=1): xlabel = 'time [s]' ylabel = 'energy [W·h]' edcs = list(set(edc_id)) df = pd.DataFrame(list(zip(time, edc_id, energy)), columns=['time', 'edc_id', 'energy']) for edc_id in edcs: time = df[df['edc_id'] == edc_id].time energy = df[df['edc_id'] == edc_id].energy energy_ = apply_ema(energy, alpha) plt.plot(time, energy_) plt.xlabel(xlabel, fontsize=12) plt.ylabel(ylabel, fontsize=12) title = 'Edge Data Centers Stored Energy' if alpha < 1: title += ' (EMA,alpha={})'.format(alpha) plt.title(title) plt.legend(edcs, prop={'size': 12}) plt.show() def multiple_graph(time, classes, y_values, graph_data, alpha=1): class_labels = list(set(classes)) class_labels.sort() n_labels = len(class_labels) data_array = np.zeros((len(y_values), len(class_labels))) for i in range(n_labels): for j in range(len(time)): if classes[j] == class_labels[i]: data_array[j:, i] = y_values[j] for i in reversed(range(n_labels)): data_array[:, i] = np.asarray(apply_ema(data_array[:, i].tolist(), alpha)) plt.step(time, data_array[:, i], where='post') plt.xlabel(graph_data['xlabel'], fontsize=12) plt.ylabel(graph_data['ylabel'], fontsize=12) plt.legend(class_labels, prop={'size': 12}) if alpha < 1: graph_data['title'] += ' (EMA,alpha={})'.format(alpha) plt.title(graph_data['title']) plt.show() return plt def stacked_graph(time, classes, y_values, graph_data, alpha=1): class_labels = list(set(classes)) n_labels = len(class_labels) data_array = np.zeros((len(y_values), len(class_labels))) for i in range(n_labels): last_value = 0 for j in range(len(time)): if classes[j] == class_labels[i]: increment = y_values[j] - last_value data_array[j:, i:n_labels] += increment last_value = y_values[j] for i in reversed(range(n_labels)): data_array[:, i] = np.asarray(apply_ema(data_array[:, i].tolist(), alpha)) plt.step(time, data_array[:, i], where='post') plt.xlabel(graph_data['xlabel'], fontsize=12) plt.ylabel(graph_data['ylabel'], fontsize=12) if alpha < 1: graph_data['title'] += ' (EMA,alpha={})'.format(alpha) plt.title(graph_data['title']) plt.legend(class_labels, prop={'size': 12}) plt.show() def delay_summary(ue_file_path): data = pd.read_csv(ue_file_path, sep=";") delay = data['delay'].values mean_delay = np.mean(delay) peak_delay = np.max(delay) print("Mean delay: {} seconds".format(mean_delay)) print("Peak delay: {} seconds".format(peak_delay)) def power_summary(edc_file_path): data = pd.read_csv(edc_file_path, index_col=False, sep=";") edc_ids = data['edc_id'].unique().tolist() n_edcs = len(edc_ids) max_power = 0 t_prev = 0 power = np.zeros(n_edcs) mean_power = 0 for index, row in data.iterrows(): mean_power += np.sum(power) * (row['time'] - t_prev) t_prev = row['time'] for i in range(n_edcs): if row['edc_id'] == edc_ids[i]: power[i] = row['power_demand'] max_power = max(max_power, np.sum(power)) mean_power /= t_prev print("Mean power: {} Watts".format(mean_power)) print("Peak power: {} Watts".format(max_power)) def apply_ema(data, alpha): assert 0 < alpha <= 1 aux = np.asarray(data.copy()) if alpha < 1: for i in range(1, aux.shape[0]): aux[i] = (1 - alpha) * aux[i - 1] + alpha * aux[i] return aux.tolist()
[ "numpy.mean", "pandas.read_csv", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.max", "numpy.sum", "numpy.zeros", "matplotlib.pyplot.title", "matplotlib.pyplot.step", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((385, 407), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'delay_'], {}), '(time, delay_)\n', (393, 407), True, 'import matplotlib.pyplot as plt\n'), ((412, 447), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time [s]"""'], {'fontsize': '(12)'}), "('time [s]', fontsize=12)\n", (422, 447), True, 'import matplotlib.pyplot as plt\n'), ((452, 488), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""delay [s]"""'], {'fontsize': '(12)'}), "('delay [s]', fontsize=12)\n", (462, 488), True, 'import matplotlib.pyplot as plt\n'), ((761, 777), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (770, 777), True, 'import matplotlib.pyplot as plt\n'), ((782, 792), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (790, 792), True, 'import matplotlib.pyplot as plt\n'), ((1012, 1038), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'bandwidth_'], {}), '(time, bandwidth_)\n', (1020, 1038), True, 'import matplotlib.pyplot as plt\n'), ((1043, 1064), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'rate_'], {}), '(time, rate_)\n', (1051, 1064), True, 'import matplotlib.pyplot as plt\n'), ((1069, 1104), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time [s]"""'], {'fontsize': '(12)'}), "('time [s]', fontsize=12)\n", (1079, 1104), True, 'import matplotlib.pyplot as plt\n'), ((1109, 1175), 'matplotlib.pyplot.legend', 'plt.legend', (["['bandwidth [Hz]', 'bitrate [bps]']"], {'prop': "{'size': 12}"}), "(['bandwidth [Hz]', 'bitrate [bps]'], prop={'size': 12})\n", (1119, 1175), True, 'import matplotlib.pyplot as plt\n'), ((1300, 1316), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1309, 1316), True, 'import matplotlib.pyplot as plt\n'), ((1321, 1331), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1329, 1331), True, 'import matplotlib.pyplot as plt\n'), ((1337, 1364), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'efficiency_'], {}), '(time, efficiency_)\n', (1345, 1364), True, 'import matplotlib.pyplot as plt\n'), ((1369, 1404), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time [s]"""'], {'fontsize': '(12)'}), "('time [s]', fontsize=12)\n", (1379, 1404), True, 'import matplotlib.pyplot as plt\n'), ((1409, 1464), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""spectral efficiency [bps/Hz]"""'], {'fontsize': '(12)'}), "('spectral efficiency [bps/Hz]', fontsize=12)\n", (1419, 1464), True, 'import matplotlib.pyplot as plt\n'), ((1586, 1602), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1595, 1602), True, 'import matplotlib.pyplot as plt\n'), ((1607, 1617), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1615, 1617), True, 'import matplotlib.pyplot as plt\n'), ((2953, 2984), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {'fontsize': '(12)'}), '(xlabel, fontsize=12)\n', (2963, 2984), True, 'import matplotlib.pyplot as plt\n'), ((2989, 3020), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {'fontsize': '(12)'}), '(ylabel, fontsize=12)\n', (2999, 3020), True, 'import matplotlib.pyplot as plt\n'), ((3138, 3154), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (3147, 3154), True, 'import matplotlib.pyplot as plt\n'), ((3159, 3194), 'matplotlib.pyplot.legend', 'plt.legend', (['edcs'], {'prop': "{'size': 12}"}), "(edcs, prop={'size': 12})\n", (3169, 3194), True, 'import matplotlib.pyplot as plt\n'), ((3199, 3209), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3207, 3209), True, 'import matplotlib.pyplot as plt\n'), ((3777, 3822), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["graph_data['xlabel']"], {'fontsize': '(12)'}), "(graph_data['xlabel'], fontsize=12)\n", (3787, 3822), True, 'import matplotlib.pyplot as plt\n'), ((3827, 3872), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (["graph_data['ylabel']"], {'fontsize': '(12)'}), "(graph_data['ylabel'], fontsize=12)\n", (3837, 3872), True, 'import matplotlib.pyplot as plt\n'), ((3877, 3920), 'matplotlib.pyplot.legend', 'plt.legend', (['class_labels'], {'prop': "{'size': 12}"}), "(class_labels, prop={'size': 12})\n", (3887, 3920), True, 'import matplotlib.pyplot as plt\n'), ((4006, 4036), 'matplotlib.pyplot.title', 'plt.title', (["graph_data['title']"], {}), "(graph_data['title'])\n", (4015, 4036), True, 'import matplotlib.pyplot as plt\n'), ((4041, 4051), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4049, 4051), True, 'import matplotlib.pyplot as plt\n'), ((4735, 4780), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["graph_data['xlabel']"], {'fontsize': '(12)'}), "(graph_data['xlabel'], fontsize=12)\n", (4745, 4780), True, 'import matplotlib.pyplot as plt\n'), ((4785, 4830), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (["graph_data['ylabel']"], {'fontsize': '(12)'}), "(graph_data['ylabel'], fontsize=12)\n", (4795, 4830), True, 'import matplotlib.pyplot as plt\n'), ((4916, 4946), 'matplotlib.pyplot.title', 'plt.title', (["graph_data['title']"], {}), "(graph_data['title'])\n", (4925, 4946), True, 'import matplotlib.pyplot as plt\n'), ((4951, 4994), 'matplotlib.pyplot.legend', 'plt.legend', (['class_labels'], {'prop': "{'size': 12}"}), "(class_labels, prop={'size': 12})\n", (4961, 4994), True, 'import matplotlib.pyplot as plt\n'), ((4999, 5009), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5007, 5009), True, 'import matplotlib.pyplot as plt\n'), ((5056, 5090), 'pandas.read_csv', 'pd.read_csv', (['ue_file_path'], {'sep': '""";"""'}), "(ue_file_path, sep=';')\n", (5067, 5090), True, 'import pandas as pd\n'), ((5141, 5155), 'numpy.mean', 'np.mean', (['delay'], {}), '(delay)\n', (5148, 5155), True, 'import numpy as np\n'), ((5173, 5186), 'numpy.max', 'np.max', (['delay'], {}), '(delay)\n', (5179, 5186), True, 'import numpy as np\n'), ((5344, 5396), 'pandas.read_csv', 'pd.read_csv', (['edc_file_path'], {'index_col': '(False)', 'sep': '""";"""'}), "(edc_file_path, index_col=False, sep=';')\n", (5355, 5396), True, 'import pandas as pd\n'), ((5515, 5531), 'numpy.zeros', 'np.zeros', (['n_edcs'], {}), '(n_edcs)\n', (5523, 5531), True, 'import numpy as np\n'), ((2925, 2948), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'energy_'], {}), '(time, energy_)\n', (2933, 2948), True, 'import matplotlib.pyplot as plt\n'), ((3726, 3772), 'matplotlib.pyplot.step', 'plt.step', (['time', 'data_array[:, i]'], {'where': '"""post"""'}), "(time, data_array[:, i], where='post')\n", (3734, 3772), True, 'import matplotlib.pyplot as plt\n'), ((4684, 4730), 'matplotlib.pyplot.step', 'plt.step', (['time', 'data_array[:, i]'], {'where': '"""post"""'}), "(time, data_array[:, i], where='post')\n", (4692, 4730), True, 'import matplotlib.pyplot as plt\n'), ((5612, 5625), 'numpy.sum', 'np.sum', (['power'], {}), '(power)\n', (5618, 5625), True, 'import numpy as np\n'), ((5838, 5851), 'numpy.sum', 'np.sum', (['power'], {}), '(power)\n', (5844, 5851), True, 'import numpy as np\n')]
''' Keep track of document and topic priors. Gradient updates performed by Theano. <NAME> ''' from functools import reduce from scipy.special import digamma import theano from theano import config import theano.tensor as T import numpy as np import mlp, opt from _sample import _loglikelihood_marginalizeTopics EPS=np.array(1.e-8).astype(np.float32) def compLL(Ds, Ws, nzw, ndz, nz, nd, priorDZ, priorZW, thetaDenom, phiDenom): return _loglikelihood_marginalizeTopics(Ds, Ws, nzw.astype(np.int32), ndz.astype(np.int32), nz[:,0].astype(np.int32), nd[:,0].astype(np.int32), priorDZ, priorZW, 1./(nd[:,0]+thetaDenom[:,0]), 1./(nz[:,0]+phiDenom[:,0])) def buildSpriteParams(C, W, Z, betaMean, betaL1, betaL2, deltaMean, deltaL1, deltaL2, omegaMean, omegaL1, omegaL2, deltaBMean, deltaBL1, deltaBL2, omegaBMean, omegaBL1, omegaBL2, tieBetaAndDelta): betaInit = RegularizedWeights(np.random.normal(betaMean, 0.01, (Z, C)). astype(np.float32), betaMean, betaL1, betaL2, 'beta') if tieBetaAndDelta: deltaTInit = betaInit else: deltaTInit = RegularizedWeights(np.random.normal(deltaMean, 0.01, (Z, C)). astype(np.float32), deltaMean, deltaL1, deltaL2, 'deltaT') omegaInit = RegularizedWeights(np.random.normal(omegaMean, 0.01, (C, W)). astype(np.float32), omegaMean, omegaL1, omegaL2, 'omega') omegaBInit = RegularizedWeights(np.random.normal(omegaMean, 0.01, (1,W)). astype(np.float32), omegaBMean, omegaBL1, omegaBL2, 'omegaB') deltaBInit = RegularizedWeights(np.random.normal(deltaBMean, 0.01, (1,Z)). astype(np.float32), deltaBMean, deltaBL1, deltaBL2, 'deltaB') return SpriteParams(betaInit, deltaTInit, omegaInit, omegaBInit, deltaBInit) class RegularizedWeights: def __init__(self, initWeights, meanWeight, l1=0.0, l2=0.0, name=''): bcast = (True, False) if initWeights.shape[0]==1 else (False, False) self.wts = theano.shared(initWeights.astype(np.float32), borrow=True, broadcastable=bcast, name=name) self._mean = (meanWeight * np.ones(initWeights.shape, dtype=np.float32)).astype(np.float32) self._l1 = np.array(l1).astype(np.float32) self._l2 = np.array(l2).astype(np.float32) self.reg_cost = self._l1 * T.sum(abs(self.wts-self._mean)) + \ self._l2 * T.sum((self.wts-self._mean)**2.) self.reg_grad = T.grad(self.reg_cost, self.wts) class SpriteParams: ''' Keep track of Sprite weights and regularization terms -- excludes the neural network for alpha. ''' def __init__(self, beta, deltaT, omega, omegaB, deltaB): self.beta = beta self.deltaT = deltaT self.omega = omega self.omegaB = omegaB self.deltaB = deltaB # collect all weights together self.wts = [self.beta.wts, self.deltaT.wts, self.omega.wts, self.omegaB.wts, self.deltaB.wts] self.reg_cost = sum([self.beta.reg_cost, self.deltaT.reg_cost, self.omega.reg_cost, self.omegaB.reg_cost, self.deltaB.reg_cost]) class LdaCounts: def __init__(self, nd, nz, ndz, nzw): # borrowed because gibbs sampling step updates the counts self._nd = theano.shared(nd, borrow=True, name='Nd', broadcastable=(False, True)) self._nz = theano.shared(nz, borrow=True, name='Nz', broadcastable=(False, True)) self._ndz = theano.shared(ndz, borrow=True, name='Ndz') self._nzw = theano.shared(nzw, borrow=True, name='Nzw') class NeuralPrior: ''' Factor where document labels influence priors through a neural network. Computes document and topic priors. ''' def __init__(self, params, alphaGraph, optimizer=opt.SGDOptimizer(0.01), onlyBias=False, mbatchsize=1000000): self._params = params self.optimizer = optimizer self._alpha = alphaGraph.output self._alphaObj = alphaGraph self._nlayers = alphaGraph.nlayers self.__docLabels = alphaGraph.input self.numComponents = alphaGraph.outWidth self.inNumComponents = alphaGraph.inWidth self.__alpha_reg_cost = alphaGraph.getRegCost() self.__alpha_params = alphaGraph.getParams() self.mbatchsize = mbatchsize self._onlyBias = onlyBias # zero out weights that are not bias terms if self._onlyBias: for w in self._params.wts: if w.name not in set(['omegaB', 'deltaB']): w.set_value(np.array(0.).astype(np.float32) * w.get_value()) def setCorpus(self, alphaValues, counts): ''' alphaValues: this factor is observed, set document labels ''' # shared variables with topic/word counts self._nd = counts._nd self._nz = counts._nz self._ndz = counts._ndz self._nzw = counts._nzw self._alphaValues = alphaValues M, K, V = (alphaValues.shape[0], self._params.deltaB.wts.get_value().shape[1], self._params.omegaB.wts.get_value().shape[1]) self._batch_index = theano.shared(0) self.__thetaTilde = theano.shared(np.zeros((M, K)).astype(np.float32), borrow='True') self.__phiTilde = theano.shared(np.zeros((K, V)).astype(np.float32), borrow='True') self.__thetaNorm = theano.shared(np.zeros((M,1)).astype(np.float32), borrow='True', broadcastable=(False, True)) self.__phiNorm = theano.shared(np.zeros((K,1)).astype(np.float32), borrow='True', broadcastable=(False, True)) self._tt = self.__thetaTilde self._pt = self.__phiTilde self._tn = self.__thetaNorm self._pn = self.__phiNorm self._buildGraph() def _buildGraph(self): # Document and topic priors self.thetaTilde_next = T.exp(self._alpha.dot(self._params.deltaT.wts.T) + self._params.deltaB.wts) self.phiTilde_next = T.exp(self._params.beta.wts.dot(self._params.omega.wts) + self._params.omegaB.wts) self.thetaNorm_next = T.sum(self.thetaTilde_next, axis=1, keepdims=True) self.phiNorm_next = T.sum(self.phiTilde_next, axis=1, keepdims=True) self.__priorUpdates = [(self.__thetaTilde, T.set_subtensor(self.__thetaTilde[self._batch_index*self.mbatchsize: ((self._batch_index+1)*self.mbatchsize)], self.thetaTilde_next)), (self.__phiTilde, self.phiTilde_next), (self.__thetaNorm, T.set_subtensor(self.__thetaNorm[self._batch_index*self.mbatchsize: ((self._batch_index+1)*self.mbatchsize)], self.thetaNorm_next)), (self.__phiNorm, self.phiNorm_next)] #self._updatePriorFns = [theano.function(inputs=inputs, # outputs=[], updates=[update]) # for i, (inputs, update) # in enumerate(zip([[self.__docLabels], [], [self.__docLabels], []], # self.__priorUpdates))] self.__updatePriors = theano.function(inputs=[self.__docLabels, self._alphaObj._dummy], outputs=[], updates=self.__priorUpdates) self.__getPriors = theano.function(inputs=[self.__docLabels, self._alphaObj._dummy], outputs=[self.thetaTilde_next, self.thetaNorm_next, self.phiTilde_next, self.phiNorm_next]) # Calculate gradient w.r.t. prior self.buildExtGradFn() # Function to update model weights self.buildStepFn() # Calculate current value of priors self.__updatePriors(self._alphaValues, 0) def getPriors(self): return self.__thetaTilde.get_value(), self.__thetaNorm.get_value(), self.__phiTilde.get_value(), self.__phiNorm.get_value() def step(self): ''' Take a gradient step, updating all parameters. ''' gradTerm_phi, gradTerm_theta = self.calcExternalGrad() if self._onlyBias: self.take_step_bias(self._alphaValues, gradTerm_phi, gradTerm_theta, 0) else: self.take_step(self._alphaValues, gradTerm_phi, gradTerm_theta, 0) def stepSprite(self): ''' Take a gradient step, updating only SPRITE parameters, not alpha ''' gradTerm_phi, gradTerm_theta = self.calcExternalGrad() if self.mbatchsize <= 0: self.take_step_sprite(self._alphaValues, gradTerm_phi, gradTerm_theta, 0) else: # update prior in minibatches N = self._alphaValues.shape[0] batches = (N // self.mbatchsize) + 1 for i in range(batches): if i*self.mbatchsize >= N: continue else: self._batch_index.set_value(i) self.take_step_sprite(self._alphaValues, gradTerm_phi, gradTerm_theta, 0) def stepAlpha(self): ''' Take a gradient step, updating only alpha network weights ''' gradTerm_phi, gradTerm_theta = self.calcExternalGrad() if self.mbatchsize <= 0: self.take_step_alpha(self._alphaValues, gradTerm_phi, gradTerm_theta, 0) else: # update prior in minibatches N = self._alphaValues.shape[0] batches = (N // self.mbatchsize) + 1 for i in range(batches): if i*self.mbatchsize >= N: continue else: self._batch_index.set_value(i) self.take_step_alpha(self._alphaValues, gradTerm_phi, gradTerm_theta, 0) def buildExtGradFn(self): tn, tt, pn, pt = self.__thetaNorm, self.__thetaTilde, self.__phiNorm, self.__phiTilde dg1 = T.psi(self.__thetaNorm + EPS) dg2 = T.psi(self.__thetaNorm + T.cast(self._nd, 'float32') + EPS) dgW1 = T.psi(self.__thetaTilde + T.cast(self._ndz, 'float32') + EPS) dgW2 = T.psi(self.__thetaTilde + EPS) gradTerm_theta = dg1 - dg2 + dgW1 - dgW2 dg1 = T.psi(self.__phiNorm + EPS) dg2 = T.psi(self.__phiNorm + T.cast(self._nz, 'float32') + EPS) dgW1 = T.psi(self.__phiTilde + T.cast(self._nzw, 'float32') + EPS) dgW2 = T.psi(self.__phiTilde + EPS) gradTerm_phi = dg1 - dg2 + dgW1 - dgW2 self.calcExternalGrad_phi = theano.function(inputs=[], outputs=[gradTerm_phi]) self.calcExternalGrad_theta = theano.function(inputs=[], outputs=[gradTerm_theta]) self.calcExternalGrad = theano.function(inputs=[], outputs=[gradTerm_phi, gradTerm_theta]) def buildStepFn(self): # the gradient of likelihood w.r.t. topic and document priors gradTerm_phi = T.matrix('gradientTerm_phi') gradTerm_theta = T.matrix('gradientTerm_theta') # Total cost extGradCost_phi = - T.sum( self.phiTilde_next * gradTerm_phi ) extGradCost_theta = - T.sum( self.thetaTilde_next * gradTerm_theta ) extGradCost = extGradCost_phi + extGradCost_theta reg_extGradCost = extGradCost + self.__alpha_reg_cost + self._params.reg_cost #reg_extGradCost = - reg_extGradCost # Collect SPRITE parameters together with the MLP weights __params_bias = [w for w in self._params.wts if w.name=='deltaB' or w.name=='omegaB'] __params_sprite = self._params.wts __params_alpha = self.__alpha_params __params = __params_sprite + __params_alpha # Calculate gradient with respect to this cost function __grads_bias = [T.grad(reg_extGradCost, p) for p in __params_bias] __grads_sprite = [T.grad(reg_extGradCost, p) for p in __params_sprite] __grads_alpha = [T.grad(reg_extGradCost, p) for p in __params_alpha] __grads = [T.grad(reg_extGradCost, p) for p in __params] __updates_bias = self.optimizer.getUpdates(__params_bias, __grads_bias) __updates_sprite = self.optimizer.getUpdates(__params_sprite, __grads_sprite) __updates_alpha = self.optimizer.getUpdates(__params_alpha, __grads_alpha) __updates = self.optimizer.getUpdates(__params, __grads) # update all model weights, and recalculate doc/topic priors def buildFn(updates): if updates: # To remove duplicates when beta&delta are tied updatesWoDups = list({k:v for (k,v) in updates}.items()) return theano.function([ self.__docLabels, gradTerm_phi, gradTerm_theta, self._alphaObj._dummy], outputs=[], updates=updatesWoDups + self.__priorUpdates) else: return theano.function([ ], outputs=[]) # update weights self.take_step_bias = buildFn(__updates_bias) # only bias terms self.take_step_sprite = buildFn(__updates_sprite) # only SPRITE parameters if self._nlayers > 0: self.take_step_alpha = buildFn(__updates_alpha) # only alpha network else: self.take_step_alpha = lambda x,y,z: [] self.take_step = buildFn(__updates) # update all parameters self.__get_reg_cost = theano.function([], outputs=[self.__alpha_reg_cost + self._params.reg_cost]) self.__get_theta_cost = theano.function([self.__docLabels, gradTerm_theta, self._alphaObj._dummy], outputs=[extGradCost_theta]) self.__get_phi_cost = theano.function([gradTerm_phi], outputs=[extGradCost_phi]) self.__get_total_cost = theano.function([self.__docLabels, gradTerm_phi, gradTerm_theta, self._alphaObj._dummy], outputs=[reg_extGradCost]) self.__get_all_costs = theano.function([self.__docLabels, gradTerm_phi, gradTerm_theta, self._alphaObj._dummy], outputs=[self._params.reg_cost, extGradCost_theta, extGradCost_phi, reg_extGradCost]) def getCosts(self): gradTerm_phi, gradTerm_theta = self.calcExternalGrad() return self.__get_all_costs(self._alphaValues, gradTerm_phi, gradTerm_theta) def getSupertopics(self, itow, topn=20): omegaBTopic = [] supertopics = [] omegab = self._params.wts[3].get_value()[0] omegaBTopic = [(itow[i], weight) for i, weight in sorted(enumerate(omegab), key=lambda x:x[1], reverse=True)[:topn]] omega = self._params.wts[2].get_value() for omegaRow in omega: topicPos = [(itow[i], weight) for i, weight in sorted(enumerate(omegaRow), key=lambda x:x[1], reverse=True)[:topn]] topicNeg = [(itow[i], weight) for i, weight in sorted(enumerate(omegaRow), key=lambda x:x[1])[:topn]] supertopics.append(topicPos + topicNeg) return omegaBTopic, supertopics def printSupertopics(self, itow, topn=20): omegaBTopic, supertopics = self.getSupertopics(itow, topn) print('==== Omega Bias ====') for word, weight in omegaBTopic: print('%s: %s' % (word, weight)) print('') for topicIdx, topic in enumerate(supertopics): print('=== (Omega) Supertopic %d ===' % (topicIdx)) for word, weight in topic: print('%s: %s' % (word, weight)) print('') def test(): Cin, Cout, W, Z, D, Dn = 20, 4, 50, 2, 1000, 10 L2 = 1.0 betaMean, betaL1, betaL2 = 0.0, 0.0, L2 deltaMean, deltaL1, deltaL2 = 0.0, 0.0, L2 omegaMean, omegaL1, omegaL2 = 0.0, 0.0, L2 deltaBMean, deltaBL1, deltaBL2 = -2.0, -2.0, L2 omegaBMean, omegaBL1, omegaBL2 = -4.0, -4.0, L2 params = buildSpriteParams(Cout, W, Z, betaMean, betaL1, betaL2, deltaMean, deltaL1, deltaL2, omegaMean, omegaL1, omegaL2, deltaBMean, deltaBL1, deltaBL2, omegaBMean, omegaBL1, omegaBL2, tieBetaAndDelta=False) docLabels = np.asarray([[1.0*(j==(i%(Cin//2)) and (j < (Cin//2))) for j in range(Cin)] for i in range(D//2)] + [[1.0*((j-(Cin//2))==(i%(Cin//2)) and (j >= (Cin//2))) for j in range(Cin)] for i in range(D//2,D)], dtype=np.float32) trueWts = np.zeros((Cin, Cout)) for c in range(Cout): trueWts[(c*(Cin//Cout)):((c+1)*(Cin//Cout)),c] = 10.0 trueAlpha = docLabels.dot(trueWts).astype(np.float32) ndz = np.zeros((D, Z)).astype(np.float32) Ds = np.asarray([d for d in range(D) for dn in range(Dn)]).astype(np.int32) Ws = np.asarray([(idx % 25) for idx in range((D*Dn)//2)] + [((idx % 25) + 25) for idx in range((D*Dn)//2, D*Dn)]).astype(np.int32) for z in range(Z): ndz[(z*(D//Z)):((z+1)*(D//Z)),z] = Dn ndz = ndz.astype(np.float32) nzw = np.zeros((Z, W)) nzw[0,:(W//2)] = (D * Dn) // W nzw[1,(W//2):] = (D * Dn) // W nzw = nzw.astype(np.float32) nd = (Dn * np.ones((D, 1))).astype(np.float32) nz = ((D//Z) * Dn * np.ones((Z, 1))).astype(np.float32) optimizer = opt.AdadeltaOptimizer(-1.0) alphaGraph = mlp.MLP(12345, [Cin, Cout], None, None, optimizer, 0.0, L2, 'alphaGraph') prior = NeuralPrior(params, alphaGraph, optimizer=optimizer) prior.setCorpus(docLabels, LdaCounts(nd, nz, ndz, nzw)) thetaTilde, thetaNorm, phiTilde, phiNorm = prior.getPriors() ll = compLL(Ds, Ws, nzw, ndz, nz, nd, thetaTilde, phiTilde, thetaNorm, phiNorm) costStr = ', '.join(map(str, prior.getCosts())) print('LL: %.3f, DeltaB: %s' % (ll, prior._params.wts[4].get_value())) print('Costs: ' + costStr) for epoch in range(2000): prior.step() thetaTilde, thetaNorm, phiTilde, phiNorm = prior.getPriors() ll = compLL(Ds, Ws, nzw, ndz, nz, nd, thetaTilde, phiTilde, thetaNorm, phiNorm) if not epoch % 1: print('Finished epoch %d, LL %.3f, DeltaB: %s' % (epoch, ll, prior._params.wts[4].get_value())) costStr = ', '.join(map(str, prior.getCosts())) print('Costs: ' + costStr) if __name__ == '__main__': test()
[ "numpy.random.normal", "mlp.MLP", "theano.shared", "theano.tensor.psi", "theano.function", "numpy.ones", "theano.tensor.sum", "theano.tensor.matrix", "opt.AdadeltaOptimizer", "numpy.array", "numpy.zeros", "theano.tensor.cast", "theano.tensor.set_subtensor", "opt.SGDOptimizer", "theano.te...
[((17220, 17241), 'numpy.zeros', 'np.zeros', (['(Cin, Cout)'], {}), '((Cin, Cout))\n', (17228, 17241), True, 'import numpy as np\n'), ((17776, 17792), 'numpy.zeros', 'np.zeros', (['(Z, W)'], {}), '((Z, W))\n', (17784, 17792), True, 'import numpy as np\n'), ((18017, 18044), 'opt.AdadeltaOptimizer', 'opt.AdadeltaOptimizer', (['(-1.0)'], {}), '(-1.0)\n', (18038, 18044), False, 'import mlp, opt\n'), ((18063, 18136), 'mlp.MLP', 'mlp.MLP', (['(12345)', '[Cin, Cout]', 'None', 'None', 'optimizer', '(0.0)', 'L2', '"""alphaGraph"""'], {}), "(12345, [Cin, Cout], None, None, optimizer, 0.0, L2, 'alphaGraph')\n", (18070, 18136), False, 'import mlp, opt\n'), ((324, 339), 'numpy.array', 'np.array', (['(1e-08)'], {}), '(1e-08)\n', (332, 339), True, 'import numpy as np\n'), ((2701, 2732), 'theano.tensor.grad', 'T.grad', (['self.reg_cost', 'self.wts'], {}), '(self.reg_cost, self.wts)\n', (2707, 2732), True, 'import theano.tensor as T\n'), ((3544, 3614), 'theano.shared', 'theano.shared', (['nd'], {'borrow': '(True)', 'name': '"""Nd"""', 'broadcastable': '(False, True)'}), "(nd, borrow=True, name='Nd', broadcastable=(False, True))\n", (3557, 3614), False, 'import theano\n'), ((3632, 3702), 'theano.shared', 'theano.shared', (['nz'], {'borrow': '(True)', 'name': '"""Nz"""', 'broadcastable': '(False, True)'}), "(nz, borrow=True, name='Nz', broadcastable=(False, True))\n", (3645, 3702), False, 'import theano\n'), ((3720, 3763), 'theano.shared', 'theano.shared', (['ndz'], {'borrow': '(True)', 'name': '"""Ndz"""'}), "(ndz, borrow=True, name='Ndz')\n", (3733, 3763), False, 'import theano\n'), ((3780, 3823), 'theano.shared', 'theano.shared', (['nzw'], {'borrow': '(True)', 'name': '"""Nzw"""'}), "(nzw, borrow=True, name='Nzw')\n", (3793, 3823), False, 'import theano\n'), ((4023, 4045), 'opt.SGDOptimizer', 'opt.SGDOptimizer', (['(0.01)'], {}), '(0.01)\n', (4039, 4045), False, 'import mlp, opt\n'), ((5309, 5325), 'theano.shared', 'theano.shared', (['(0)'], {}), '(0)\n', (5322, 5325), False, 'import theano\n'), ((6413, 6463), 'theano.tensor.sum', 'T.sum', (['self.thetaTilde_next'], {'axis': '(1)', 'keepdims': '(True)'}), '(self.thetaTilde_next, axis=1, keepdims=True)\n', (6418, 6463), True, 'import theano.tensor as T\n'), ((6490, 6538), 'theano.tensor.sum', 'T.sum', (['self.phiTilde_next'], {'axis': '(1)', 'keepdims': '(True)'}), '(self.phiTilde_next, axis=1, keepdims=True)\n', (6495, 6538), True, 'import theano.tensor as T\n'), ((7690, 7801), 'theano.function', 'theano.function', ([], {'inputs': '[self.__docLabels, self._alphaObj._dummy]', 'outputs': '[]', 'updates': 'self.__priorUpdates'}), '(inputs=[self.__docLabels, self._alphaObj._dummy], outputs=[\n ], updates=self.__priorUpdates)\n', (7705, 7801), False, 'import theano\n'), ((7867, 8034), 'theano.function', 'theano.function', ([], {'inputs': '[self.__docLabels, self._alphaObj._dummy]', 'outputs': '[self.thetaTilde_next, self.thetaNorm_next, self.phiTilde_next, self.\n phiNorm_next]'}), '(inputs=[self.__docLabels, self._alphaObj._dummy], outputs=[\n self.thetaTilde_next, self.thetaNorm_next, self.phiTilde_next, self.\n phiNorm_next])\n', (7882, 8034), False, 'import theano\n'), ((10421, 10450), 'theano.tensor.psi', 'T.psi', (['(self.__thetaNorm + EPS)'], {}), '(self.__thetaNorm + EPS)\n', (10426, 10450), True, 'import theano.tensor as T\n'), ((10606, 10636), 'theano.tensor.psi', 'T.psi', (['(self.__thetaTilde + EPS)'], {}), '(self.__thetaTilde + EPS)\n', (10611, 10636), True, 'import theano.tensor as T\n'), ((10698, 10725), 'theano.tensor.psi', 'T.psi', (['(self.__phiNorm + EPS)'], {}), '(self.__phiNorm + EPS)\n', (10703, 10725), True, 'import theano.tensor as T\n'), ((10877, 10905), 'theano.tensor.psi', 'T.psi', (['(self.__phiTilde + EPS)'], {}), '(self.__phiTilde + EPS)\n', (10882, 10905), True, 'import theano.tensor as T\n'), ((10988, 11038), 'theano.function', 'theano.function', ([], {'inputs': '[]', 'outputs': '[gradTerm_phi]'}), '(inputs=[], outputs=[gradTerm_phi])\n', (11003, 11038), False, 'import theano\n'), ((11123, 11175), 'theano.function', 'theano.function', ([], {'inputs': '[]', 'outputs': '[gradTerm_theta]'}), '(inputs=[], outputs=[gradTerm_theta])\n', (11138, 11175), False, 'import theano\n'), ((11254, 11320), 'theano.function', 'theano.function', ([], {'inputs': '[]', 'outputs': '[gradTerm_phi, gradTerm_theta]'}), '(inputs=[], outputs=[gradTerm_phi, gradTerm_theta])\n', (11269, 11320), False, 'import theano\n'), ((11480, 11508), 'theano.tensor.matrix', 'T.matrix', (['"""gradientTerm_phi"""'], {}), "('gradientTerm_phi')\n", (11488, 11508), True, 'import theano.tensor as T\n'), ((11530, 11560), 'theano.tensor.matrix', 'T.matrix', (['"""gradientTerm_theta"""'], {}), "('gradientTerm_theta')\n", (11538, 11560), True, 'import theano.tensor as T\n'), ((13851, 13927), 'theano.function', 'theano.function', (['[]'], {'outputs': '[self.__alpha_reg_cost + self._params.reg_cost]'}), '([], outputs=[self.__alpha_reg_cost + self._params.reg_cost])\n', (13866, 13927), False, 'import theano\n'), ((14009, 14116), 'theano.function', 'theano.function', (['[self.__docLabels, gradTerm_theta, self._alphaObj._dummy]'], {'outputs': '[extGradCost_theta]'}), '([self.__docLabels, gradTerm_theta, self._alphaObj._dummy],\n outputs=[extGradCost_theta])\n', (14024, 14116), False, 'import theano\n'), ((14228, 14286), 'theano.function', 'theano.function', (['[gradTerm_phi]'], {'outputs': '[extGradCost_phi]'}), '([gradTerm_phi], outputs=[extGradCost_phi])\n', (14243, 14286), False, 'import theano\n'), ((14357, 14477), 'theano.function', 'theano.function', (['[self.__docLabels, gradTerm_phi, gradTerm_theta, self._alphaObj._dummy]'], {'outputs': '[reg_extGradCost]'}), '([self.__docLabels, gradTerm_phi, gradTerm_theta, self.\n _alphaObj._dummy], outputs=[reg_extGradCost])\n', (14372, 14477), False, 'import theano\n'), ((14589, 14772), 'theano.function', 'theano.function', (['[self.__docLabels, gradTerm_phi, gradTerm_theta, self._alphaObj._dummy]'], {'outputs': '[self._params.reg_cost, extGradCost_theta, extGradCost_phi, reg_extGradCost]'}), '([self.__docLabels, gradTerm_phi, gradTerm_theta, self.\n _alphaObj._dummy], outputs=[self._params.reg_cost, extGradCost_theta,\n extGradCost_phi, reg_extGradCost])\n', (14604, 14772), False, 'import theano\n'), ((11609, 11649), 'theano.tensor.sum', 'T.sum', (['(self.phiTilde_next * gradTerm_phi)'], {}), '(self.phiTilde_next * gradTerm_phi)\n', (11614, 11649), True, 'import theano.tensor as T\n'), ((11680, 11724), 'theano.tensor.sum', 'T.sum', (['(self.thetaTilde_next * gradTerm_theta)'], {}), '(self.thetaTilde_next * gradTerm_theta)\n', (11685, 11724), True, 'import theano.tensor as T\n'), ((12282, 12308), 'theano.tensor.grad', 'T.grad', (['reg_extGradCost', 'p'], {}), '(reg_extGradCost, p)\n', (12288, 12308), True, 'import theano.tensor as T\n'), ((12355, 12381), 'theano.tensor.grad', 'T.grad', (['reg_extGradCost', 'p'], {}), '(reg_extGradCost, p)\n', (12361, 12381), True, 'import theano.tensor as T\n'), ((12430, 12456), 'theano.tensor.grad', 'T.grad', (['reg_extGradCost', 'p'], {}), '(reg_extGradCost, p)\n', (12436, 12456), True, 'import theano.tensor as T\n'), ((12497, 12523), 'theano.tensor.grad', 'T.grad', (['reg_extGradCost', 'p'], {}), '(reg_extGradCost, p)\n', (12503, 12523), True, 'import theano.tensor as T\n'), ((17397, 17413), 'numpy.zeros', 'np.zeros', (['(D, Z)'], {}), '((D, Z))\n', (17405, 17413), True, 'import numpy as np\n'), ((1058, 1098), 'numpy.random.normal', 'np.random.normal', (['betaMean', '(0.01)', '(Z, C)'], {}), '(betaMean, 0.01, (Z, C))\n', (1074, 1098), True, 'import numpy as np\n'), ((1452, 1493), 'numpy.random.normal', 'np.random.normal', (['omegaMean', '(0.01)', '(C, W)'], {}), '(omegaMean, 0.01, (C, W))\n', (1468, 1493), True, 'import numpy as np\n'), ((1623, 1664), 'numpy.random.normal', 'np.random.normal', (['omegaMean', '(0.01)', '(1, W)'], {}), '(omegaMean, 0.01, (1, W))\n', (1639, 1664), True, 'import numpy as np\n'), ((1798, 1840), 'numpy.random.normal', 'np.random.normal', (['deltaBMean', '(0.01)', '(1, Z)'], {}), '(deltaBMean, 0.01, (1, Z))\n', (1814, 1840), True, 'import numpy as np\n'), ((2464, 2476), 'numpy.array', 'np.array', (['l1'], {}), '(l1)\n', (2472, 2476), True, 'import numpy as np\n'), ((2513, 2525), 'numpy.array', 'np.array', (['l2'], {}), '(l2)\n', (2521, 2525), True, 'import numpy as np\n'), ((2648, 2685), 'theano.tensor.sum', 'T.sum', (['((self.wts - self._mean) ** 2.0)'], {}), '((self.wts - self._mean) ** 2.0)\n', (2653, 2685), True, 'import theano.tensor as T\n'), ((6619, 6759), 'theano.tensor.set_subtensor', 'T.set_subtensor', (['self.__thetaTilde[self._batch_index * self.mbatchsize:(self._batch_index + \n 1) * self.mbatchsize]', 'self.thetaTilde_next'], {}), '(self.__thetaTilde[self._batch_index * self.mbatchsize:(self\n ._batch_index + 1) * self.mbatchsize], self.thetaTilde_next)\n', (6634, 6759), True, 'import theano.tensor as T\n'), ((7000, 7138), 'theano.tensor.set_subtensor', 'T.set_subtensor', (['self.__thetaNorm[self._batch_index * self.mbatchsize:(self._batch_index + 1\n ) * self.mbatchsize]', 'self.thetaNorm_next'], {}), '(self.__thetaNorm[self._batch_index * self.mbatchsize:(self.\n _batch_index + 1) * self.mbatchsize], self.thetaNorm_next)\n', (7015, 7138), True, 'import theano.tensor as T\n'), ((13108, 13258), 'theano.function', 'theano.function', (['[self.__docLabels, gradTerm_phi, gradTerm_theta, self._alphaObj._dummy]'], {'outputs': '[]', 'updates': '(updatesWoDups + self.__priorUpdates)'}), '([self.__docLabels, gradTerm_phi, gradTerm_theta, self.\n _alphaObj._dummy], outputs=[], updates=updatesWoDups + self.__priorUpdates)\n', (13123, 13258), False, 'import theano\n'), ((13377, 13408), 'theano.function', 'theano.function', (['[]'], {'outputs': '[]'}), '([], outputs=[])\n', (13392, 13408), False, 'import theano\n'), ((17906, 17921), 'numpy.ones', 'np.ones', (['(D, 1)'], {}), '((D, 1))\n', (17913, 17921), True, 'import numpy as np\n'), ((17964, 17979), 'numpy.ones', 'np.ones', (['(Z, 1)'], {}), '((Z, 1))\n', (17971, 17979), True, 'import numpy as np\n'), ((1278, 1319), 'numpy.random.normal', 'np.random.normal', (['deltaMean', '(0.01)', '(Z, C)'], {}), '(deltaMean, 0.01, (Z, C))\n', (1294, 1319), True, 'import numpy as np\n'), ((2382, 2426), 'numpy.ones', 'np.ones', (['initWeights.shape'], {'dtype': 'np.float32'}), '(initWeights.shape, dtype=np.float32)\n', (2389, 2426), True, 'import numpy as np\n'), ((5369, 5385), 'numpy.zeros', 'np.zeros', (['(M, K)'], {}), '((M, K))\n', (5377, 5385), True, 'import numpy as np\n'), ((5497, 5513), 'numpy.zeros', 'np.zeros', (['(K, V)'], {}), '((K, V))\n', (5505, 5513), True, 'import numpy as np\n'), ((5625, 5641), 'numpy.zeros', 'np.zeros', (['(M, 1)'], {}), '((M, 1))\n', (5633, 5641), True, 'import numpy as np\n'), ((5781, 5797), 'numpy.zeros', 'np.zeros', (['(K, 1)'], {}), '((K, 1))\n', (5789, 5797), True, 'import numpy as np\n'), ((10487, 10514), 'theano.tensor.cast', 'T.cast', (['self._nd', '"""float32"""'], {}), "(self._nd, 'float32')\n", (10493, 10514), True, 'import theano.tensor as T\n'), ((10559, 10587), 'theano.tensor.cast', 'T.cast', (['self._ndz', '"""float32"""'], {}), "(self._ndz, 'float32')\n", (10565, 10587), True, 'import theano.tensor as T\n'), ((10760, 10787), 'theano.tensor.cast', 'T.cast', (['self._nz', '"""float32"""'], {}), "(self._nz, 'float32')\n", (10766, 10787), True, 'import theano.tensor as T\n'), ((10830, 10858), 'theano.tensor.cast', 'T.cast', (['self._nzw', '"""float32"""'], {}), "(self._nzw, 'float32')\n", (10836, 10858), True, 'import theano.tensor as T\n'), ((4750, 4763), 'numpy.array', 'np.array', (['(0.0)'], {}), '(0.0)\n', (4758, 4763), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # IkaLog # ====== # Copyright (C) 2015 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import cv2 import numpy as np from PIL import Image def imread(filename): if not os.path.exists(filename): return None f = open(filename, 'rb') img_bytes = f.read() f.close() img = cv2.imdecode(np.fromstring(img_bytes, dtype='uint8'), 1) return img
[ "os.path.exists", "numpy.fromstring" ]
[((754, 778), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (768, 778), False, 'import os\n'), ((893, 932), 'numpy.fromstring', 'np.fromstring', (['img_bytes'], {'dtype': '"""uint8"""'}), "(img_bytes, dtype='uint8')\n", (906, 932), True, 'import numpy as np\n')]
#Imports from scipy.stats import linregress import matplotlib.pyplot as plt import numpy as np import random import sys from math import * from PrimesArray import primes na = np.array #Collatz Function def c(n): if n % 2 == 0: return n / 2 else: return 3 * n + 1 #Collatz Sequence generating function :!!! RETURNS PATH LEN def cs(s): count = 0 prev = s while True: x = c(prev) # print(x) if x == 2: #print("[COUNT] %s" % count) break else: count += 1 prev = x return count # Progress Bar: DIRECTLY from stack overflow ALL credit for this function to the author at https://stackoverflow.com/questions/3160699/python-progress-bar def update_progress(progress): barLength = 10 # Modify this to change the length of the progress bar status = "" if isinstance(progress, int): progress = float(progress) if not isinstance(progress, float): progress = 0 status = "error: progress var must be float\r\n" if progress < 0: progress = 0 status = "Halt...\r\n" if progress >= 1: progress = 1 status = "Done...\r\n" block = int(round(barLength*progress)) text = "\rPercent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status) sys.stdout.write(text) sys.stdout.flush() #Generate Points based off of a function of x baseRule= lambda a : a #identity # Generate Points up to a quantity= upperLim, based off of a function def genPoints(upperLim,collatzSequenceFunction=cs,statusFunction=update_progress,silent=False,x_rule=baseRule,y_rule=baseRule): #Note the calculation may run faster if it is silent... y = [] x = [] for i in range(2, upperLim): ## 2!! o is not in the range of cs x.append(x_rule(i)) y.append(collatzSequenceFunction(y_rule(i))) if not silent: statusFunction(round((i / (upperLim)) * 100) / 100) return [np.array(x), np.array(y)] if __name__ == "__main__": #settings Points_Quantity=1000 print("[Begin Generation]") #Maping rules for expiramentation yr = lambda y: primes[y] xr = lambda x : x/primes[x] #Generate Points points = genPoints(Points_Quantity,x_rule=xr,y_rule=yr) print("[End Generation]") #Graph Setup plt.title('Collatz of 2*n +1 numbers') plt.xlabel('x-Axis: x') plt.ylabel('y-Axis: Path Length to 2') #Plot the points print("[Plotting]") plt.scatter(points[0], points[1], c=(random.random(),random.random(),random.random()), s=np.pi * 3, alpha=0.5) plt.show() print("[Finished]")
[ "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.array", "random.random", "matplotlib.pyplot.title", "sys.stdout.flush", "sys.stdout.write" ]
[((1410, 1432), 'sys.stdout.write', 'sys.stdout.write', (['text'], {}), '(text)\n', (1426, 1432), False, 'import sys\n'), ((1438, 1456), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (1454, 1456), False, 'import sys\n'), ((2462, 2500), 'matplotlib.pyplot.title', 'plt.title', (['"""Collatz of 2*n +1 numbers"""'], {}), "('Collatz of 2*n +1 numbers')\n", (2471, 2500), True, 'import matplotlib.pyplot as plt\n'), ((2506, 2529), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x-Axis: x"""'], {}), "('x-Axis: x')\n", (2516, 2529), True, 'import matplotlib.pyplot as plt\n'), ((2535, 2573), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y-Axis: Path Length to 2"""'], {}), "('y-Axis: Path Length to 2')\n", (2545, 2573), True, 'import matplotlib.pyplot as plt\n'), ((2744, 2754), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2752, 2754), True, 'import matplotlib.pyplot as plt\n'), ((2083, 2094), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2091, 2094), True, 'import numpy as np\n'), ((2096, 2107), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (2104, 2107), True, 'import numpy as np\n'), ((2665, 2680), 'random.random', 'random.random', ([], {}), '()\n', (2678, 2680), False, 'import random\n'), ((2681, 2696), 'random.random', 'random.random', ([], {}), '()\n', (2694, 2696), False, 'import random\n'), ((2697, 2712), 'random.random', 'random.random', ([], {}), '()\n', (2710, 2712), False, 'import random\n')]
from torch.nn import Sequential, Linear, ReLU, GRU from torch_geometric.data import Dataset, Data, DataLoader # from torch_geometric.datasets import QM9 from torch_geometric.nn import NNConv, Set2Set from torch.nn import BCELoss, BCEWithLogitsLoss from torch_geometric.utils import remove_self_loops import numpy as np import os import os.path as osp import random import sys import torch import torch.nn.functional as F import torch_geometric.transforms as T import time, itertools from torch_geometric.utils import degree from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from torch.utils.tensorboard import SummaryWriter #returns the encoding and adjacency matrix given the program filename def graphToMatrices(filename): # move to global to i`mprove performance from matrixFormation import oneHotEncoder,adjacencyMatrixCreator languageType="" astOfProgram=[] if filename.split(".")[1] == "py": languageType = "python" listOfFiles = open('python-asts.txt', 'r') filenameArray = listOfFiles.readlines() listOfAsts = open('python-asts.json', 'r') astArray = listOfAsts.readlines() filename+="\n" idxOfFile = filenameArray.index(filename) astOfProgram = astArray[idxOfFile] else: languageType = "java" listOfFiles = open('java-asts.txt', 'r') filenameArray = listOfFiles.readlines() listOfAsts = open('java-asts.json', 'r') astArray = listOfAsts.readlines() filename+="\n" idxOfFile = filenameArray.index(filename) astOfProgram = astArray[idxOfFile] encodedMatrix = oneHotEncoder(astOfProgram,languageType) adjacencyMatrix,num_nodes = adjacencyMatrixCreator(astOfProgram) return adjacencyMatrix,encodedMatrix,num_nodes def getTrainingPairs(): trainingPairs = [] ## read from trainPairs.txt (Java, py) ## read from txt (Java, py) listOfClones = open('../CloneDetectionSrc/ClonePairs.txt', 'r') listOfNonClones = open('../CloneDetectionSrc/nonClonePairs.txt', 'r') trainingPairs = listOfClones.readlines() nonCloneTrainingPairs = listOfNonClones.readlines() return trainingPairs, nonCloneTrainingPairs class PairData(Data): def __inc__(self, key, value): if key == 'edge_index1': return self.x1.size(0) if key == 'edge_index2': return self.x2.size(0) else: return super(PairData, self).__inc__(key, value) def __cat_dim__(self, key, value): if 'index' in key or 'face' in key: return 1 else: return 0 # will return dataset pairs => # ------------------------------------ # data_point -> ASTAdjacencyMatrices + encodedMatrices + Label (pair or not) # ------------------------------------ ## Define n n=51917+51917 # n=4405 # n=60 class TrainLoadData(Dataset): def __init__(self, root, transform=None, pre_transform=None): super(TrainLoadData, self).__init__(root, transform, pre_transform) # self.data, self.slices = torch.load(self.processed_paths[0]) @property def raw_file_names(self): return ['../CloneDetectionSrc/NonClonePairs.txt'] @property def processed_file_names(self): return ['cloneDetectionData/data_{}.pt'.format(i) for i in range(n)] def process(self): #get all the pairs - self.raw_paths # check pair or not and then save the pair in the data clonePairs,nonClonePairs = getTrainingPairs() if(len(clonePairs)>int(n/2)): clonePairs=clonePairs[:(int(n/2))] if(len(nonClonePairs)>int(n/2)): nonClonePairs=nonClonePairs[:(int(n/2))] i = 0 for pairs in clonePairs: print(i) matrix1, encode1, num_nodes1 = graphToMatrices(pairs.split(",")[0]) matrix2, encode2, num_nodes2 = graphToMatrices(pairs.split(",")[1][:-1]) listForLabel=[1] labelTensor=torch.Tensor(listForLabel) # data = Data(x1=torch.Tensor(encode1), x2=torch.Tensor(encode2), edge_index1=torch.Tensor(matrix1), edge_index2=torch.Tensor(matrix2),num_nodes1=num_nodes1,num_nodes2=num_nodes2 y=1) data = PairData(x1=torch.Tensor(encode1), x2=torch.Tensor(encode2), edge_index1=torch.Tensor(matrix1), edge_index2=torch.Tensor(matrix2), y=labelTensor) # data1 = Data(x=torch.Tensor(encode1), edge_index=torch.LongTensor(matrix1), num_nodes=num_nodes1) # data2 = Data(x=torch.Tensor(encode2), edge_index=torch.LongTensor(matrix2), num_nodes=num_nodes2) # data = Data(data1=data1, data2=data2, y=1) torch.save(data, osp.join(self.processed_dir, 'cloneDetectionData/data_{}.pt'.format(i))) i += 1 for pairs in nonClonePairs: print(i) matrix1, encode1, num_nodes1 = graphToMatrices(pairs.split(",")[0]) matrix2, encode2, num_nodes2 = graphToMatrices(pairs.split(",")[1][:-1]) listForLabel=[0] labelTensor=torch.Tensor(listForLabel) # data = Data(x1=torch.Tensor(encode1), x2=torch.Tensor(encode2), edge_index1=torch.Tensor(matrix1), edge_index2=torch.Tensor(matrix2),num_nodes1=num_nodes1,num_nodes2=num_nodes2 y=0) data = PairData(x1=torch.Tensor(encode1), x2=torch.Tensor(encode2), edge_index1=torch.Tensor(matrix1), edge_index2=torch.Tensor(matrix2), y=labelTensor) # data1 = Data(x=torch.Tensor(encode1), edge_index=torch.LongTensor(matrix1), num_nodes=num_nodes1) # data2 = Data(x=torch.Tensor(encode2), edge_index=torch.LongTensor(matrix2), num_nodes=num_nodes2) # data = Data(data1=data1, data2=data2, y=0) torch.save(data, osp.join(self.processed_dir, 'cloneDetectionData/data_{}.pt'.format(i))) i += 1 def len(self): return len(self.processed_file_names) def get(self, idx): data = torch.load(osp.join(self.processed_dir, 'cloneDetectionData/data_{}.pt'.format(idx))) # print(data) # print(data.edge_index2.shape) return data class MyTransform(object): def __call__(self, data): # Specify target - in our case its 0 only data.y = data.y[:, target] return data class Complete(object): def __call__(self, data): device = data.edge_index.device row = torch.arange(data.num_nodes, dtype=torch.long, device=device) col = torch.arange(data.num_nodes, dtype=torch.long, device=device) row = row.view(-1, 1).repeat(1, data.num_nodes).view(-1) col = col.repeat(data.num_nodes) edge_index = torch.stack([row, col], dim=0) edge_attr = None if data.edge_attr is not None: idx = data.edge_index[0] * data.num_nodes + data.edge_index[1] size = list(data.edge_attr.size()) size[0] = data.num_nodes * data.num_nodes edge_attr = data.edge_attr.new_zeros(size) edge_attr[idx] = data.edge_attr edge_index, edge_attr = remove_self_loops(edge_index, edge_attr) data.edge_attr = edge_attr data.edge_index = edge_index return data def train(epoch, use_unsup_loss): model.train() loss_all = 0 sup_loss_all = 0 unsup_loss_all = 0 unsup_sup_loss_all = 0 if use_unsup_loss: for data, udata in zip(train_loader, unsup_train_loader): data = data.to(device) udata = udata.to(device) optimizer.zero_grad() criterion = BCEWithLogitsLoss() pred=model(data) sup_loss = criterion(pred, data.y) unsup_loss1 = model.unsup_loss1(udata,udata.x1_batch) # unsup loss for java encoder unsup_loss2 = model.unsup_loss2(udata,udata.x2_batch) # unsup loss for python encoder if separate_encoder: unsup_sup_loss1 = model.unsup_sup_loss1(udata,udata.x1_batch) unsup_sup_loss2 = model.unsup_sup_loss2(udata,udata.x2_batch) loss = sup_loss + (unsup_loss1 + unsup_loss2) + (unsup_sup_loss1 + unsup_sup_loss2)* lamda else: loss = sup_loss + (unsup_loss1 + unsup_loss2 )* lamda loss.backward() sup_loss_all += sup_loss.item()*batch_size unsup_loss_all += (unsup_loss1.item()+unsup_loss2.item())*batch_size if separate_encoder: unsup_sup_loss_all += (unsup_sup_loss1.item()+unsup_sup_loss2.item()) loss_all += loss.item() * batch_size optimizer.step() if separate_encoder: print(sup_loss_all, unsup_loss_all, unsup_sup_loss_all) return loss_all / len(train_loader.dataset),sup_loss_all, unsup_loss_all, unsup_sup_loss_all else: print(sup_loss_all/ len(train_loader.dataset), unsup_loss_all/ len(train_loader.dataset)) return loss_all / len(train_loader.dataset),sup_loss_all/ len(train_loader.dataset), unsup_loss_all/ len(train_loader.dataset) else: cnt=0 for data in train_loader: data = data.to(device) optimizer.zero_grad() criterion = BCEWithLogitsLoss() pred=model(data) sup_loss = criterion(pred, data.y) loss = sup_loss loss.backward() loss_all += loss.item() * batch_size optimizer.step() cnt+=1 print(cnt) return loss_all / len(train_loader.dataset) def test(loader): model.eval() error = 0 precision =0 recall = 0 accuracy = 0 predictions=[] grndTruth=[] ####################### fix the metrics for data in loader: data = data.to(device) # data.x=data.x.float() # error += (model(data) * std - data.y * std).abs().sum().item() # MAE y_pred=torch.round(torch.sigmoid(model(data))) predictions.append(y_pred.cpu().detach().numpy().tolist()) grndTruth.append(data.y.cpu().detach().numpy().tolist()) error += (y_pred - data.y).abs().sum().item() # MAE predictions = list(itertools.chain.from_iterable(predictions)) grndTruth = list(itertools.chain.from_iterable(grndTruth)) accuracy += accuracy_score(grndTruth,predictions) precision += precision_score(grndTruth,predictions) recall += recall_score(grndTruth,predictions) return error / len(loader.dataset),accuracy,precision,recall def seed_everything(seed=1234): random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False if __name__ == '__main__': seed_everything() from baseLineModel import Net # ============ # Hyperparameters # ============ target = 0 dim = 64 epochs = 25 batch_size = 200 lamda = 0.001 use_unsup_loss = False separate_encoder = False tb = SummaryWriter() ## If transformation is required : # transform = T.Compose([MyTransform(), Complete()]) # dataset = JavaClassificationDataset(root="./",transform=transform) dataset = TrainLoadData(root="./") dataset=dataset.shuffle() print('num_features : {}\n'.format(dataset.num_features)) dataset_num_features = max(dataset.num_features, 1) # if dataset.data.x is None: # max_degree = 0 # degs = [] # for data in dataset: # degs += [degree(data.edge_index[0], dtype=torch.long)] # max_degree = max(max_degree, degs[-1].max().item()) # if max_degree < 1000: # dataset.transform = T.OneHotDegree(max_degree) # else: # deg = torch.cat(degs, dim=0).to(torch.float) # mean, std = deg.mean().item(), deg.std().item() # dataset.transform = NormalizedDegree(mean, std) # Normalize targets to mean = 0 and std = 1. # mean = dataset.data.y[:, target].mean().item() # std = dataset.data.y[:, target].std().item() # dataset.data.y[:, target] = (dataset.data.y[:, target] - mean) / std ####### Split datasets. # trainSize=int(0.6*len(dataset)) # valSize=int(0.2*len(dataset)) # testSize=len(dataset)-trainSize-valSize # train_dataset, test_dataset , val_dataset = torch.utils.data.random_split(dataset, [trainSize,valSize,testSize]) testLimit=int(0.2*n) valLimit=int(0.4*n) test_dataset = dataset[:testLimit] val_dataset = dataset[testLimit:valLimit] train_dataset = dataset[valLimit:] test_loader = DataLoader(test_dataset, follow_batch=['x1', 'x2'],batch_size=batch_size, shuffle=True) val_loader = DataLoader(val_dataset,follow_batch=['x1', 'x2'], batch_size=batch_size, shuffle=True) train_loader = DataLoader(train_dataset,follow_batch=['x1', 'x2'], batch_size=batch_size, shuffle=True) if use_unsup_loss: unsup_train_dataset = dataset[valLimit:] unsup_train_loader = DataLoader(unsup_train_dataset,follow_batch=['x1', 'x2'], batch_size=batch_size, shuffle=True) print(len(train_dataset), len(val_dataset), len(test_dataset), len(unsup_train_dataset)) else: print(len(train_dataset), len(val_dataset), len(test_dataset)) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') dataset_num_features=142 model = Net(dataset_num_features, dim, use_unsup_loss, separate_encoder).to(device) optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.7, patience=5, min_lr=0.000001) # val_error = test(val_loader) # test_error = test(test_loader) # print('Epoch: {:03d}, Validation MAE: {:.7f}, Test MAE: {:.7f},'.format(0, val_error, test_error)) # state=torch.load("javaModels/Classifier-Infograph*_271.pth") # model.load_state_dict(state['state_dict']) # print(state['state_dict']) # test_loader2 = DataLoader(test_dataset, follow_batch=['x1', 'x2'],batch_size=1000, shuffle=True) # for data in (test_loader2): # print(data.y) best_val_error = None for epoch in range(1, epochs): start_time = time.time() lr = scheduler.optimizer.param_groups[0]['lr'] print("Training epoch %d :" % epoch) if separate_encoder: loss,sup_loss, unsup_loss, unsup_sup_loss = train(epoch, use_unsup_loss) else: if use_unsup_loss: loss,sup_loss, unsup_loss = train(epoch, use_unsup_loss) else: sup_loss = train(epoch, use_unsup_loss) print("Testing epoch %d :" % epoch) val_error,val_accuracy,val_prec,val_recall = test(val_loader) scheduler.step(val_error) if best_val_error is None or val_error <= best_val_error: test_error,test_accuracy,test_prec,test_recall = test(test_loader) best_val_error = val_error tb.add_scalar('Sup_Loss', sup_loss, epoch) if use_unsup_loss: tb.add_scalar('UnSup Loss', unsup_loss, epoch) if separate_encoder: tb.add_scalar('UnSup-Sup- Loss', unsup_sup_loss, epoch) tb.add_scalar('val_error', val_error, epoch) tb.add_scalar('val_accuracy', val_accuracy, epoch) tb.add_scalar('val_prec', val_prec, epoch) tb.add_scalar('val_recall', val_recall, epoch) tb.add_scalar('test_error', test_error, epoch) tb.add_scalar('test_accuracy', test_accuracy, epoch) tb.add_scalar('test_prec', test_prec, epoch) tb.add_scalar('test_recall', test_recall, epoch) end_time = time.time() epoch_duration = (end_time - start_time)/3600 # change this with open('cloneDetection-EpochResults-baseLine-SimpleGCn.txt', 'a+') as f: if separate_encoder: f.write('Epoch: {:03d}, LR: {:7f}, T.Loss: {:.7f}, Sup-Loss: {:.7f},unSup-Loss: {:.7f},unSup-sup-Loss: {:.7f}, Validation MAE: {:.7f},Validation Acc: {:.7f},Validation Prec: {:.7f},Validation Rec: {:.7f},Test MAE: {:.7f},Test Acc: {:.7f},Test Prec: {:.7f},Test Rec: {:.7f}, Time : {:.7f}'.format(epoch, lr, loss,sup_loss, unsup_loss, unsup_sup_loss, val_error,val_accuracy,val_prec,val_recall,test_error,test_accuracy,test_prec,test_recall,epoch_duration)) else: if use_unsup_loss: f.write('Epoch: {:03d}, LR: {:7f}, T.Loss: {:.7f}, Sup-Loss: {:.7f},unSup-Loss: {:.7f}, Validation MAE: {:.7f},Validation Acc: {:.7f},Validation Prec: {:.7f},Validation Rec: {:.7f},Test MAE: {:.7f},Test Acc: {:.7f},Test Prec: {:.7f},Test Rec: {:.7f}, Time : {:.7f}'.format(epoch, lr, loss,sup_loss, unsup_loss, val_error,val_accuracy,val_prec,val_recall,test_error,test_accuracy,test_prec,test_recall,epoch_duration)) else: f.write('Epoch: {:03d}, LR: {:7f}, Sup-Loss: {:.7f}, Validation MAE: {:.7f},Validation Acc: {:.7f},Validation Prec: {:.7f},Validation Rec: {:.7f},Test MAE: {:.7f},Test Acc: {:.7f},Test Prec: {:.7f},Test Rec: {:.7f}, Time : {:.7f}'.format(epoch, lr,sup_loss, val_error,val_accuracy,val_prec,val_recall,test_error,test_accuracy,test_prec,test_recall,epoch_duration)) f.write('\n') # change this torch.save({'state_dict': model.state_dict(),'optimizer' : optimizer.state_dict()},"cloneDetectionModels/baseline_SimpleGCN_bigDB_new_"+str(epoch)+".pth") # change this # with open('cloneDetection-EpochResults-baseLine-SimpleGCn.log', 'a+') as f: # f.write('{},{},{},{},{},{},{},{}\n'.format(target,1000,use_unsup_loss,separate_encoder,0.001,0,val_error,test_error)) # f.write('\n') # f.write("Total time taken for evaluation is: ",(end_time - start_time)/3600,"hrs.") tb.close()
[ "sklearn.metrics.precision_score", "sklearn.metrics.recall_score", "torch.cuda.is_available", "torch.arange", "matrixFormation.oneHotEncoder", "torch.utils.tensorboard.SummaryWriter", "itertools.chain.from_iterable", "torch_geometric.utils.remove_self_loops", "baseLineModel.Net", "numpy.random.see...
[((1750, 1791), 'matrixFormation.oneHotEncoder', 'oneHotEncoder', (['astOfProgram', 'languageType'], {}), '(astOfProgram, languageType)\n', (1763, 1791), False, 'from matrixFormation import oneHotEncoder, adjacencyMatrixCreator\n'), ((1823, 1859), 'matrixFormation.adjacencyMatrixCreator', 'adjacencyMatrixCreator', (['astOfProgram'], {}), '(astOfProgram)\n', (1845, 1859), False, 'from matrixFormation import oneHotEncoder, adjacencyMatrixCreator\n'), ((10434, 10472), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['grndTruth', 'predictions'], {}), '(grndTruth, predictions)\n', (10448, 10472), False, 'from sklearn.metrics import accuracy_score\n'), ((10489, 10528), 'sklearn.metrics.precision_score', 'precision_score', (['grndTruth', 'predictions'], {}), '(grndTruth, predictions)\n', (10504, 10528), False, 'from sklearn.metrics import precision_score\n'), ((10542, 10578), 'sklearn.metrics.recall_score', 'recall_score', (['grndTruth', 'predictions'], {}), '(grndTruth, predictions)\n', (10554, 10578), False, 'from sklearn.metrics import recall_score\n'), ((10685, 10702), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (10696, 10702), False, 'import random\n'), ((10707, 10730), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (10724, 10730), False, 'import torch\n'), ((10735, 10767), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (10761, 10767), False, 'import torch\n'), ((10772, 10792), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (10786, 10792), True, 'import numpy as np\n'), ((11222, 11237), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {}), '()\n', (11235, 11237), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((12827, 12919), 'torch_geometric.data.DataLoader', 'DataLoader', (['test_dataset'], {'follow_batch': "['x1', 'x2']", 'batch_size': 'batch_size', 'shuffle': '(True)'}), "(test_dataset, follow_batch=['x1', 'x2'], batch_size=batch_size,\n shuffle=True)\n", (12837, 12919), False, 'from torch_geometric.data import Dataset, Data, DataLoader\n'), ((12932, 13023), 'torch_geometric.data.DataLoader', 'DataLoader', (['val_dataset'], {'follow_batch': "['x1', 'x2']", 'batch_size': 'batch_size', 'shuffle': '(True)'}), "(val_dataset, follow_batch=['x1', 'x2'], batch_size=batch_size,\n shuffle=True)\n", (12942, 13023), False, 'from torch_geometric.data import Dataset, Data, DataLoader\n'), ((13038, 13131), 'torch_geometric.data.DataLoader', 'DataLoader', (['train_dataset'], {'follow_batch': "['x1', 'x2']", 'batch_size': 'batch_size', 'shuffle': '(True)'}), "(train_dataset, follow_batch=['x1', 'x2'], batch_size=batch_size,\n shuffle=True)\n", (13048, 13131), False, 'from torch_geometric.data import Dataset, Data, DataLoader\n'), ((13791, 13899), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'torch.optim.lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'mode': '"""min"""', 'factor': '(0.7)', 'patience': '(5)', 'min_lr': '(1e-06)'}), "(optimizer, mode='min', factor=\n 0.7, patience=5, min_lr=1e-06)\n", (13833, 13899), False, 'import torch\n'), ((6534, 6595), 'torch.arange', 'torch.arange', (['data.num_nodes'], {'dtype': 'torch.long', 'device': 'device'}), '(data.num_nodes, dtype=torch.long, device=device)\n', (6546, 6595), False, 'import torch\n'), ((6610, 6671), 'torch.arange', 'torch.arange', (['data.num_nodes'], {'dtype': 'torch.long', 'device': 'device'}), '(data.num_nodes, dtype=torch.long, device=device)\n', (6622, 6671), False, 'import torch\n'), ((6800, 6830), 'torch.stack', 'torch.stack', (['[row, col]'], {'dim': '(0)'}), '([row, col], dim=0)\n', (6811, 6830), False, 'import torch\n'), ((7204, 7244), 'torch_geometric.utils.remove_self_loops', 'remove_self_loops', (['edge_index', 'edge_attr'], {}), '(edge_index, edge_attr)\n', (7221, 7244), False, 'from torch_geometric.utils import remove_self_loops\n'), ((10311, 10353), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['predictions'], {}), '(predictions)\n', (10340, 10353), False, 'import time, itertools\n'), ((10376, 10416), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['grndTruth'], {}), '(grndTruth)\n', (10405, 10416), False, 'import time, itertools\n'), ((13230, 13330), 'torch_geometric.data.DataLoader', 'DataLoader', (['unsup_train_dataset'], {'follow_batch': "['x1', 'x2']", 'batch_size': 'batch_size', 'shuffle': '(True)'}), "(unsup_train_dataset, follow_batch=['x1', 'x2'], batch_size=\n batch_size, shuffle=True)\n", (13240, 13330), False, 'from torch_geometric.data import Dataset, Data, DataLoader\n'), ((14469, 14480), 'time.time', 'time.time', ([], {}), '()\n', (14478, 14480), False, 'import time, itertools\n'), ((15933, 15944), 'time.time', 'time.time', ([], {}), '()\n', (15942, 15944), False, 'import time, itertools\n'), ((4113, 4139), 'torch.Tensor', 'torch.Tensor', (['listForLabel'], {}), '(listForLabel)\n', (4125, 4139), False, 'import torch\n'), ((5179, 5205), 'torch.Tensor', 'torch.Tensor', (['listForLabel'], {}), '(listForLabel)\n', (5191, 5205), False, 'import torch\n'), ((7699, 7718), 'torch.nn.BCEWithLogitsLoss', 'BCEWithLogitsLoss', ([], {}), '()\n', (7716, 7718), False, 'from torch.nn import BCELoss, BCEWithLogitsLoss\n'), ((9361, 9380), 'torch.nn.BCEWithLogitsLoss', 'BCEWithLogitsLoss', ([], {}), '()\n', (9378, 9380), False, 'from torch.nn import BCELoss, BCEWithLogitsLoss\n'), ((13540, 13565), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (13563, 13565), False, 'import torch\n'), ((13620, 13684), 'baseLineModel.Net', 'Net', (['dataset_num_features', 'dim', 'use_unsup_loss', 'separate_encoder'], {}), '(dataset_num_features, dim, use_unsup_loss, separate_encoder)\n', (13623, 13684), False, 'from baseLineModel import Net\n'), ((4367, 4388), 'torch.Tensor', 'torch.Tensor', (['encode1'], {}), '(encode1)\n', (4379, 4388), False, 'import torch\n'), ((4393, 4414), 'torch.Tensor', 'torch.Tensor', (['encode2'], {}), '(encode2)\n', (4405, 4414), False, 'import torch\n'), ((4428, 4449), 'torch.Tensor', 'torch.Tensor', (['matrix1'], {}), '(matrix1)\n', (4440, 4449), False, 'import torch\n'), ((4463, 4484), 'torch.Tensor', 'torch.Tensor', (['matrix2'], {}), '(matrix2)\n', (4475, 4484), False, 'import torch\n'), ((5433, 5454), 'torch.Tensor', 'torch.Tensor', (['encode1'], {}), '(encode1)\n', (5445, 5454), False, 'import torch\n'), ((5459, 5480), 'torch.Tensor', 'torch.Tensor', (['encode2'], {}), '(encode2)\n', (5471, 5480), False, 'import torch\n'), ((5494, 5515), 'torch.Tensor', 'torch.Tensor', (['matrix1'], {}), '(matrix1)\n', (5506, 5515), False, 'import torch\n'), ((5529, 5550), 'torch.Tensor', 'torch.Tensor', (['matrix2'], {}), '(matrix2)\n', (5541, 5550), False, 'import torch\n')]
import context # Remove this import if running with pip installed version. from pypsqueak.api import qReg, qOp from pypsqueak.gates import X, Z, I, ROT_Y, CNOT from pypsqueak.noise import b_flip_map import numpy as np import sys if len(sys.argv) > 1 and int(sys.argv[1]) > 0: n_trials = int(sys.argv[1]) else: n_trials = 2000 if len(sys.argv) > 2 and float(sys.argv[2]) <= 1 and float(sys.argv[2]) >= 0: prob = float(sys.argv[2]) else: prob = 0.1 theory_success = (1 - prob)**3 + 3*prob*(1-prob)**2 theory_failure = 1 - theory_success successes = 0 failures = 0 noisy_channel = qOp(np.eye(2), kraus_ops=b_flip_map(prob)) # Check that we are getting the correct statistics out of our noisy channel. print("Initialized noisy channel with {:.1f}% chance of bit flip.".format(100*prob)) print("Probing channel with single qubit {} times...".format(n_trials)) flip_amount = 0 for i in range(n_trials): register = qReg() noisy_channel.on(register) if not np.array_equal([1, 0], register.dump_state()): flip_amount += 1 flip_percent = 100*flip_amount/n_trials print("Bit flip occured ({:.1f} +/- {:.1f})% of the time.\n".format(flip_percent, 0.5*flip_percent/np.sqrt(n_trials))) print("With bit flip probability of {:.1f}%:".format(100*prob)) print("Theoretical transmission success rate: {:.1f}%".format(100*theory_success)) print("Theoretical transmission failure rate: {:.1f}%\n".format(100*theory_failure)) # Now we send an encoded state through our noisy channel n_trials times. # Uncomment the print lines in the for loop to peek at the state of the register # after each operation. Remember, peeking is unphysical! print("Running {} trials of sending an encoded state...".format(n_trials)) for i in range(n_trials): # Initialize a state. super_position = qReg(1) ROT_Y(0.2).on(super_position) # print("Input state |psi> =", super_position.peek()) # Encode against bit flip. CNOT.on(super_position, 1, 0) CNOT.on(super_position, 2, 0) init_state = super_position.dump_state() # print("Encoded state |psi'> =", super_position.peek()) # Send state through noisy channel. for qubit in range(len(super_position)): noisy_channel.on(super_position, qubit) # print("Encoded state after noisy transmission:", super_position.peek()) # Diagnose error syndrome. Z_21 = Z.kron(Z, I) Z_10 = I.kron(Z, Z) product_21 = super_position.measure_observable(Z_21) # print("Action of Z_21:", super_position.peek()) # print("Z_21 measurement:", product_21) product_10 = super_position.measure_observable(Z_10) # print("Action of Z_10:", super_position.peek()) # print("Z_10 measurement:", product_10) if product_10 == product_21: if product_10 == 1: # No correction required (1 - p)^3 pass else: # Middle qubit flipped (1 - p)^2 * p X.on(super_position, 1) if product_10 != product_21: if product_21 == -1: # Qubit 2 flipped (1 - p)^2 * p X.on(super_position, 2) else: # Qubit 0 flipped (1 - p)^2 * p X.on(super_position, 0) # print("Recovered state:", super_position.peek()) if np.allclose(init_state, super_position.dump_state()): successes += 1 else: failures += 1 print("Successful {:.2f}% of the time".format(100*successes/n_trials)) print("Unsuccessful {:.2f}% of the time".format(100*failures/n_trials))
[ "pypsqueak.api.qReg", "pypsqueak.gates.ROT_Y", "numpy.eye", "pypsqueak.gates.CNOT.on", "numpy.sqrt", "pypsqueak.gates.I.kron", "pypsqueak.gates.X.on", "pypsqueak.noise.b_flip_map", "pypsqueak.gates.Z.kron" ]
[((603, 612), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (609, 612), True, 'import numpy as np\n'), ((934, 940), 'pypsqueak.api.qReg', 'qReg', ([], {}), '()\n', (938, 940), False, 'from pypsqueak.api import qReg, qOp\n'), ((1808, 1815), 'pypsqueak.api.qReg', 'qReg', (['(1)'], {}), '(1)\n', (1812, 1815), False, 'from pypsqueak.api import qReg, qOp\n'), ((1943, 1972), 'pypsqueak.gates.CNOT.on', 'CNOT.on', (['super_position', '(1)', '(0)'], {}), '(super_position, 1, 0)\n', (1950, 1972), False, 'from pypsqueak.gates import X, Z, I, ROT_Y, CNOT\n'), ((1977, 2006), 'pypsqueak.gates.CNOT.on', 'CNOT.on', (['super_position', '(2)', '(0)'], {}), '(super_position, 2, 0)\n', (1984, 2006), False, 'from pypsqueak.gates import X, Z, I, ROT_Y, CNOT\n'), ((2366, 2378), 'pypsqueak.gates.Z.kron', 'Z.kron', (['Z', 'I'], {}), '(Z, I)\n', (2372, 2378), False, 'from pypsqueak.gates import X, Z, I, ROT_Y, CNOT\n'), ((2390, 2402), 'pypsqueak.gates.I.kron', 'I.kron', (['Z', 'Z'], {}), '(Z, Z)\n', (2396, 2402), False, 'from pypsqueak.gates import X, Z, I, ROT_Y, CNOT\n'), ((624, 640), 'pypsqueak.noise.b_flip_map', 'b_flip_map', (['prob'], {}), '(prob)\n', (634, 640), False, 'from pypsqueak.noise import b_flip_map\n'), ((1195, 1212), 'numpy.sqrt', 'np.sqrt', (['n_trials'], {}), '(n_trials)\n', (1202, 1212), True, 'import numpy as np\n'), ((1820, 1830), 'pypsqueak.gates.ROT_Y', 'ROT_Y', (['(0.2)'], {}), '(0.2)\n', (1825, 1830), False, 'from pypsqueak.gates import X, Z, I, ROT_Y, CNOT\n'), ((2915, 2938), 'pypsqueak.gates.X.on', 'X.on', (['super_position', '(1)'], {}), '(super_position, 1)\n', (2919, 2938), False, 'from pypsqueak.gates import X, Z, I, ROT_Y, CNOT\n'), ((3057, 3080), 'pypsqueak.gates.X.on', 'X.on', (['super_position', '(2)'], {}), '(super_position, 2)\n', (3061, 3080), False, 'from pypsqueak.gates import X, Z, I, ROT_Y, CNOT\n'), ((3151, 3174), 'pypsqueak.gates.X.on', 'X.on', (['super_position', '(0)'], {}), '(super_position, 0)\n', (3155, 3174), False, 'from pypsqueak.gates import X, Z, I, ROT_Y, CNOT\n')]
# -*- coding: utf-8 -*- """ triangulate =========== Script : triangulate.py Author : <EMAIL> Modified : 2018-08-24 Purpose: triangulate poly* features Useage : References ---------- `<http://pro.arcgis.com/en/pro-app/arcpy/data-access/numpyarraytotable.htm>`_. `<http://pro.arcgis.com/en/pro-app/arcpy/data-access/tabletonumpyarray.htm>`_. `<https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/ scipy.spatial.Delaunay.html>`_. --------------------------------------------------------------------- """ import sys import numpy as np from numpy.lib.recfunctions import structured_to_unstructured as stu from scipy.spatial import Delaunay, Voronoi from arcpytools_plt import fc_info #, tweet #, frmt_rec, _col_format import arcpy ft = {'bool': lambda x: repr(x.astype(np.int32)), 'float_kind': '{: 0.3f}'.format} np.set_printoptions(edgeitems=10, linewidth=80, precision=2, suppress=True, threshold=100, formatter=ft) np.ma.masked_print_option.set_display('-') # change to a single - script = sys.argv[0] # print this should you need to locate the script arcpy.env.overwriteOutput = True # ---- # def _xyID(in_fc, to_pnts=True): """Convert featureclass geometry (in_fc) to a simple 2D structured array : with ID, X, Y values. Optionally convert to points, otherwise centroid. """ flds = ['OID@', 'SHAPE@X', 'SHAPE@Y'] args = [in_fc, flds, None, None, to_pnts, (None, None)] cur = arcpy.da.SearchCursor(*args) a = cur._as_narray() a.dtype = [('IDs', '<i4'), ('Xs', '<f8'), ('Ys', '<f8')] del cur return a def poly(pnt_groups, SR): """Short form polygon creation """ polygons = [] for pnts in pnt_groups: for pair in pnts: arr = arcpy.Array([arcpy.Point(*xy) for xy in pair]) pl = arcpy.Polygon(arr, SR) polygons.append(pl) return polygons def vor_pnts(pnts, ri_type="Voronoi", testing=False): """not used with polygons""" out = [] for ps in pnts: avg = np.mean(ps, axis=0) p = ps - avg tri = Voronoi(p) for region in tri.regions: if not -1 in region: polygon = np.array([tri.vertices[i] + avg for i in region]) out.append(polygon) if testing: print("{}".format(polygon.T)) #ts = [i for i in t if i.ndim == 2] return out def tri_pnts(pnts, testing=False): """Triangulate the points and return the triangles Parameters: ----------- pnts : np.array Points in array format. out : array an array of triangle points Notes: ------ >>> pnts = pnts.reshape((1,) + pnts.shape) # a 3D set of points (ndim=3) >>> [pnts] # or pass in as a list """ out = [] for ps in pnts: ps = np.unique(ps, axis=0) # get the unique points only avg = np.mean(ps, axis=0) p = ps - avg tri = Delaunay(p) simps = tri.simplices new_pnts = [p[s]+avg for s in simps] if testing: print("{}".format(new_pnts)) out.append(new_pnts) return out def pnt_groups(in_fc): """Simple def to convert shapes to points from a featureclass """ shp_fld, oid_fld, shp_type, SR = fc_info(in_fc) flds = ['OID@', 'SHAPE@X', 'SHAPE@Y'] args = [in_fc, flds, None, None, True, (None, None)] cur = arcpy.da.SearchCursor(*args) a = cur._as_narray() a.dtype = [('IDs', '<i4'), ('Xs', '<f8'), ('Ys', '<f8')] del cur pts = [] keys = np.unique(a['IDs']) for k in keys: w = np.where(a['IDs'] == k)[0] z = a[['Xs', 'Ys']][w[0]:w[-1] + 1] z = stu(z) #z = np.copy(z.view(np.float64).reshape(z.shape[0], 2)) pts.append(z) return pts, a, SR # ---- Do the work # if len(sys.argv) == 1: testing = True in_pth = script.split("/")[:-2] + ["Polygon_lineTools.gdb"] in_fc = "/".join(in_pth) + "/shapes_mtm9" #/Densified_4x" out_fc = "/".join(in_pth) + "/v3" # keep_flds = "*" # shp_fld, oid_fld, shp_type, SR = fc_info(in_fc) # pts, a, SR = pnt_groups(in_fc) # t = tri_pnts(pts, True) # polys = poly(t, SR) # arcpy.CopyFeatures_management(polys, "in_memory/temp") # arcpy.analysis.Clip("in_memory/temp", in_fc, out_fc, None) else: testing = False in_fc = sys.argv[1] out_fc = sys.argv[2] # finish up # #keep_flds = "*" #shp_fld, oid_fld, shp_type, SR = fc_info(in_fc) if not testing: pts, a, SR = pnt_groups(in_fc) t = tri_pnts(pts, True) polys = poly(t, SR) if arcpy.Exists(out_fc): arcpy.Delete_management(out_fc) arcpy.CopyFeatures_management(polys, "in_memory/temp") arcpy.MakeFeatureLayer_management("in_memory/temp", "temp") arcpy.management.SelectLayerByLocation("temp", "WITHIN_CLEMENTINI", in_fc, None, "NEW_SELECTION", "NOT_INVERT") arcpy.CopyFeatures_management("temp", out_fc) #arcpy.analysis.Clip("in_memory/temp", in_fc, out_fc, None) # #arcpy.analysis.Intersect(["in_memory/temp",in_fc], out_fc, # "ONLY_FID", None, "INPUT") # ---------------------------------------------------------------------- # __main__ .... code section if __name__ == "__main__": """Optionally... : - print the script source name. : - run the _demo """
[ "numpy.mean", "arcpy.CopyFeatures_management", "arcpy.management.SelectLayerByLocation", "numpy.unique", "arcpy.MakeFeatureLayer_management", "numpy.where", "arcpytools_plt.fc_info", "numpy.set_printoptions", "arcpy.Point", "arcpy.da.SearchCursor", "arcpy.Polygon", "numpy.array", "arcpy.Exis...
[((870, 978), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'edgeitems': '(10)', 'linewidth': '(80)', 'precision': '(2)', 'suppress': '(True)', 'threshold': '(100)', 'formatter': 'ft'}), '(edgeitems=10, linewidth=80, precision=2, suppress=True,\n threshold=100, formatter=ft)\n', (889, 978), True, 'import numpy as np\n'), ((997, 1039), 'numpy.ma.masked_print_option.set_display', 'np.ma.masked_print_option.set_display', (['"""-"""'], {}), "('-')\n", (1034, 1039), True, 'import numpy as np\n'), ((1503, 1531), 'arcpy.da.SearchCursor', 'arcpy.da.SearchCursor', (['*args'], {}), '(*args)\n', (1524, 1531), False, 'import arcpy\n'), ((3400, 3414), 'arcpytools_plt.fc_info', 'fc_info', (['in_fc'], {}), '(in_fc)\n', (3407, 3414), False, 'from arcpytools_plt import fc_info\n'), ((3527, 3555), 'arcpy.da.SearchCursor', 'arcpy.da.SearchCursor', (['*args'], {}), '(*args)\n', (3548, 3555), False, 'import arcpy\n'), ((3683, 3702), 'numpy.unique', 'np.unique', (["a['IDs']"], {}), "(a['IDs'])\n", (3692, 3702), True, 'import numpy as np\n'), ((4750, 4770), 'arcpy.Exists', 'arcpy.Exists', (['out_fc'], {}), '(out_fc)\n', (4762, 4770), False, 'import arcpy\n'), ((4818, 4872), 'arcpy.CopyFeatures_management', 'arcpy.CopyFeatures_management', (['polys', '"""in_memory/temp"""'], {}), "(polys, 'in_memory/temp')\n", (4847, 4872), False, 'import arcpy\n'), ((4878, 4937), 'arcpy.MakeFeatureLayer_management', 'arcpy.MakeFeatureLayer_management', (['"""in_memory/temp"""', '"""temp"""'], {}), "('in_memory/temp', 'temp')\n", (4911, 4937), False, 'import arcpy\n'), ((4943, 5058), 'arcpy.management.SelectLayerByLocation', 'arcpy.management.SelectLayerByLocation', (['"""temp"""', '"""WITHIN_CLEMENTINI"""', 'in_fc', 'None', '"""NEW_SELECTION"""', '"""NOT_INVERT"""'], {}), "('temp', 'WITHIN_CLEMENTINI', in_fc,\n None, 'NEW_SELECTION', 'NOT_INVERT')\n", (4981, 5058), False, 'import arcpy\n'), ((5192, 5237), 'arcpy.CopyFeatures_management', 'arcpy.CopyFeatures_management', (['"""temp"""', 'out_fc'], {}), "('temp', out_fc)\n", (5221, 5237), False, 'import arcpy\n'), ((2102, 2121), 'numpy.mean', 'np.mean', (['ps'], {'axis': '(0)'}), '(ps, axis=0)\n', (2109, 2121), True, 'import numpy as np\n'), ((2160, 2170), 'scipy.spatial.Voronoi', 'Voronoi', (['p'], {}), '(p)\n', (2167, 2170), False, 'from scipy.spatial import Delaunay, Voronoi\n'), ((2935, 2956), 'numpy.unique', 'np.unique', (['ps'], {'axis': '(0)'}), '(ps, axis=0)\n', (2944, 2956), True, 'import numpy as np\n'), ((3002, 3021), 'numpy.mean', 'np.mean', (['ps'], {'axis': '(0)'}), '(ps, axis=0)\n', (3009, 3021), True, 'import numpy as np\n'), ((3060, 3071), 'scipy.spatial.Delaunay', 'Delaunay', (['p'], {}), '(p)\n', (3068, 3071), False, 'from scipy.spatial import Delaunay, Voronoi\n'), ((3821, 3827), 'numpy.lib.recfunctions.structured_to_unstructured', 'stu', (['z'], {}), '(z)\n', (3824, 3827), True, 'from numpy.lib.recfunctions import structured_to_unstructured as stu\n'), ((4781, 4812), 'arcpy.Delete_management', 'arcpy.Delete_management', (['out_fc'], {}), '(out_fc)\n', (4804, 4812), False, 'import arcpy\n'), ((1882, 1904), 'arcpy.Polygon', 'arcpy.Polygon', (['arr', 'SR'], {}), '(arr, SR)\n', (1895, 1904), False, 'import arcpy\n'), ((3736, 3759), 'numpy.where', 'np.where', (["(a['IDs'] == k)"], {}), "(a['IDs'] == k)\n", (3744, 3759), True, 'import numpy as np\n'), ((2268, 2319), 'numpy.array', 'np.array', (['[(tri.vertices[i] + avg) for i in region]'], {}), '([(tri.vertices[i] + avg) for i in region])\n', (2276, 2319), True, 'import numpy as np\n'), ((1830, 1846), 'arcpy.Point', 'arcpy.Point', (['*xy'], {}), '(*xy)\n', (1841, 1846), False, 'import arcpy\n')]
import pandas as pd import numpy as np from sklearn import tree from sklearn.externals.six import StringIO from IPython.display import Image, display from sklearn.tree import export_graphviz import pydotplus import matplotlib.pyplot as plt import matplotlib.image as mpimg def remap_data(data_row,values) : row_values = [] for data in data_row: row_values.append(values.index(data)) return row_values def get_correct_ratio(test_results,values) : test_positive_count = 0 test_negative_count = 0 for i in range(len(test_results)): if test_results[i] == values[i] : test_positive_count += 1 else : test_negative_count += 1 test_total_count = test_positive_count + test_negative_count test_prediction_rate = 0.0 if test_total_count > 0 : test_prediction_rate = test_positive_count/test_total_count return test_prediction_rate titanic_data = pd.read_csv('../../input/train.csv') row = len(titanic_data.index) #split the data set in two dfs = np.split(titanic_data, [np.int64(4*row/5)], axis=0) titanic_train = dfs[0] titanic_test = dfs[1] target = "Survived" features = ["Pclass", "SibSp", "Parch"] features_names = ["Pclass", "SibSp", "Parch","SexValues","EmbarkedValues"] #change EmbarkedData embarked_values = titanic_train["Embarked"].unique().tolist() embarked_row = titanic_train["Embarked"].values embarked_row_value = remap_data(embarked_row,embarked_values) emb_em = pd.Series(embarked_row_value) #change sex data to binary sex_row = titanic_train["Sex"].values sex_values = titanic_train["Sex"].unique().tolist() sex_row_value = remap_data(sex_row,sex_values) titanic_data_features = titanic_train[features] sem = pd.Series(sex_row_value) titanic_data_features["SexValues"] = sem.values titanic_data_features["EmbarkedValues"] = emb_em.values titanic_data_features.fillna(-100, inplace=True) data = [] for index, row in titanic_data_features.iterrows(): data.append(row) survived = titanic_train[target].values titanic_tree = tree.DecisionTreeClassifier() titanic_tree.fit(data,survived) train_results = titanic_tree.predict(data) train_prediction_rate = get_correct_ratio(train_results,survived) print('{} : {}'.format("train_prediction_rate",train_prediction_rate)) ################################################ #change EmbarkedData test_embarked_row = titanic_test["Embarked"].values test_embarked_row_value = remap_data(test_embarked_row,embarked_values) test_emb_em = pd.Series(test_embarked_row_value) #change sex data to binary test_sex_row = titanic_test["Sex"].values test_sex_row_value = remap_data(test_sex_row,sex_values) titanic_test_features = titanic_test[features] test_sem = pd.Series(test_sex_row_value) titanic_test_features["SexValues"] = test_sem.values titanic_test_features["EmbarkedValues"] = test_emb_em.values titanic_test_features.fillna(-100, inplace=True) test_data = [] for index, row in titanic_test_features.iterrows(): test_data.append(row) test_survived = titanic_test[target].values test_results = titanic_tree.predict(test_data) test_prediction_rate = get_correct_ratio(test_results,test_survived) print('{} : {}'.format("test_prediction_rate",test_prediction_rate)) dot_data = StringIO() export_graphviz(titanic_tree, out_file=dot_data, filled=True, rounded=True, special_characters=True, feature_names=titanic_data_features.columns.values, class_names=["Died","Survived"]) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png('tree.png') png_str = graph.create_png(prog='dot') # treat the dot output string as an image file sio = StringIO() sio.write(png_str) sio.seek(0) img = mpimg.imread(sio) # plot the image imgplot = plt.imshow(img, aspect='equal') plt.show(block=False)
[ "pandas.Series", "matplotlib.pyplot.imshow", "numpy.int64", "pandas.read_csv", "sklearn.tree.DecisionTreeClassifier", "matplotlib.image.imread", "sklearn.tree.export_graphviz", "sklearn.externals.six.StringIO", "matplotlib.pyplot.show" ]
[((942, 978), 'pandas.read_csv', 'pd.read_csv', (['"""../../input/train.csv"""'], {}), "('../../input/train.csv')\n", (953, 978), True, 'import pandas as pd\n'), ((1484, 1513), 'pandas.Series', 'pd.Series', (['embarked_row_value'], {}), '(embarked_row_value)\n', (1493, 1513), True, 'import pandas as pd\n'), ((1736, 1760), 'pandas.Series', 'pd.Series', (['sex_row_value'], {}), '(sex_row_value)\n', (1745, 1760), True, 'import pandas as pd\n'), ((2062, 2091), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {}), '()\n', (2089, 2091), False, 'from sklearn import tree\n'), ((2520, 2554), 'pandas.Series', 'pd.Series', (['test_embarked_row_value'], {}), '(test_embarked_row_value)\n', (2529, 2554), True, 'import pandas as pd\n'), ((2744, 2773), 'pandas.Series', 'pd.Series', (['test_sex_row_value'], {}), '(test_sex_row_value)\n', (2753, 2773), True, 'import pandas as pd\n'), ((3283, 3293), 'sklearn.externals.six.StringIO', 'StringIO', ([], {}), '()\n', (3291, 3293), False, 'from sklearn.externals.six import StringIO\n'), ((3295, 3490), 'sklearn.tree.export_graphviz', 'export_graphviz', (['titanic_tree'], {'out_file': 'dot_data', 'filled': '(True)', 'rounded': '(True)', 'special_characters': '(True)', 'feature_names': 'titanic_data_features.columns.values', 'class_names': "['Died', 'Survived']"}), "(titanic_tree, out_file=dot_data, filled=True, rounded=True,\n special_characters=True, feature_names=titanic_data_features.columns.\n values, class_names=['Died', 'Survived'])\n", (3310, 3490), False, 'from sklearn.tree import export_graphviz\n'), ((3696, 3706), 'sklearn.externals.six.StringIO', 'StringIO', ([], {}), '()\n', (3704, 3706), False, 'from sklearn.externals.six import StringIO\n'), ((3744, 3761), 'matplotlib.image.imread', 'mpimg.imread', (['sio'], {}), '(sio)\n', (3756, 3761), True, 'import matplotlib.image as mpimg\n'), ((3790, 3821), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'aspect': '"""equal"""'}), "(img, aspect='equal')\n", (3800, 3821), True, 'import matplotlib.pyplot as plt\n'), ((3822, 3843), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (3830, 3843), True, 'import matplotlib.pyplot as plt\n'), ((1068, 1089), 'numpy.int64', 'np.int64', (['(4 * row / 5)'], {}), '(4 * row / 5)\n', (1076, 1089), True, 'import numpy as np\n')]
""" Random table generator module. """ from collections import OrderedDict import logging import numpy as np from ..utils.errors import ProgressiveError, ProgressiveStopIteration from ..table.module import TableModule from ..table.table import Table from ..table.constant import Constant from ..utils.psdict import PsDict from ..core.utils import integer_types logger = logging.getLogger(__name__) RAND = np.random.rand class RandomTable(TableModule): "Random table generator module" def __init__(self, columns, rows=-1, random=RAND, dtype='float64',throttle=False, **kwds): super(RandomTable, self).__init__(**kwds) self.default_step_size = 1000 if isinstance(columns, integer_types): self.columns = ["_%d"%i for i in range(1, columns+1)] elif isinstance(columns, (list, np.ndarray)): self.columns = columns else: raise ProgressiveError('Invalid type for columns') self.rows = rows self.random = random if throttle and isinstance(throttle, integer_types+(float,)): self.throttle = throttle else: self.throttle = False dshape = ", ".join([f"{col}: {dtype}" for col in self.columns]) dshape = "{" + dshape + "}" self.result = Table(self.generate_table_name('table'), dshape=dshape, create=True) self.columns = self.result.columns def is_source(self): return True def run_step(self, run_number, step_size, howlong): if step_size == 0: logger.error('Received a step_size of 0') return self._return_run_step(self.state_ready, steps_run=0) logger.info('generating %d lines', step_size) if self.throttle: step_size = np.min([self.throttle, step_size]) if self.rows >= 0 and (len(self.result)+step_size) > self.rows: step_size = self.rows - len(self.result) logger.info('truncating to %d lines', step_size) if step_size <= 0: raise ProgressiveStopIteration values = OrderedDict() for column in self.columns: s = self.random(step_size) values[column] = s self.result.append(values) if len(self.result) == self.rows: next_state = self.state_zombie elif self.throttle: next_state = self.state_blocked else: next_state = self.state_ready return self._return_run_step(next_state, steps_run=step_size) class RandomDict(Constant): def __init__(self, columns, **kwds): keys = [f'_{i}' for i in range(1, columns+1)] vals = np.random.rand(columns) super().__init__(PsDict(dict(zip(keys, vals))), **kwds)
[ "logging.getLogger", "collections.OrderedDict", "numpy.random.rand", "numpy.min" ]
[((374, 401), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (391, 401), False, 'import logging\n'), ((2141, 2154), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2152, 2154), False, 'from collections import OrderedDict\n'), ((2730, 2753), 'numpy.random.rand', 'np.random.rand', (['columns'], {}), '(columns)\n', (2744, 2753), True, 'import numpy as np\n'), ((1824, 1858), 'numpy.min', 'np.min', (['[self.throttle, step_size]'], {}), '([self.throttle, step_size])\n', (1830, 1858), True, 'import numpy as np\n')]
import contextlib import os import pickle import sys import time from collections import Counter from pathlib import Path from typing import Dict, List, Optional, Union import joblib import numpy as np import pandas as pd import rdkit.Chem as Chem import rdkit.Chem.AllChem as AllChem from joblib import Parallel, delayed from rdchiral.main import rdchiralReactants, rdchiralReaction, rdchiralRun from rdkit import DataStructs from rxnebm.proposer.RetroSim.retrosim.data.get_data import ( get_data_df, split_data_df) from rxnebm.proposer.RetroSim.retrosim.utils.generate_retro_templates import \ process_an_example from tqdm import tqdm @contextlib.contextmanager def tqdm_joblib(tqdm_object): # https://stackoverflow.com/questions/24983493/tracking-progress-of-joblib-parallel-execution """Context manager to patch joblib to report into tqdm progress bar given as argument""" class TqdmBatchCompletionCallback(joblib.parallel.BatchCompletionCallBack): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __call__(self, *args, **kwargs): tqdm_object.update(n=self.batch_size) return super().__call__(*args, **kwargs) old_batch_callback = joblib.parallel.BatchCompletionCallBack joblib.parallel.BatchCompletionCallBack = TqdmBatchCompletionCallback try: yield tqdm_object finally: joblib.parallel.BatchCompletionCallBack = old_batch_callback tqdm_object.close() # wrappers for multiprocessing def mol_from_smiles(smiles): mol = Chem.MolFromSmiles(smiles) return mol def mol_to_smiles(mol, isomericSmiles=True): smi = Chem.MolToSmiles(mol, isomericSmiles) return smi def similarity_metric(fp, list_fps): result = DataStructs.BulkTanimotoSimilarity(fp, list_fps) return result def rdchiralreactant_dist(smi): return rdchiralReactants(smi) def rdchiralreaction_dist(template): return rdchiralReaction(template) def rdchiralrun_dist(rxn, rct, combine_enantiomers): return rdchiralRun(rxn, rct, combine_enantiomers=combine_enantiomers) class Retrosim: ''' Wrapper over retrosim for preparing training corpus + fingerprints, and generating one-step precursor proposals for EBM re-ranking task Called by rxnebm.proposer.retrosim_proposer (self.build_model & self.propose methods) Parameters ---------- topk : int (Default = 200) for each product, how many of all the total proposals generated by Retrosim to be extracted the original Retrosim paper uses 50 (testlimit variable) max_prec: int (Default = 200) for each product, how many similar products Retrosim should consider in the product similarity search the original Retrosim paper uses 100 (max_prec variable) similarity_type : Optional[str] (Default = 'Tanimoto') ['Tanimoto', 'Dice', 'TverskyA', 'TverskyB'] metric to use for similarity search of product fingerprints fp_type : Optional[str] (Default = 'Morgan2Feat') ['Morgan2noFeat', 'Morgan3noFeat', 'Morgan2Feat', 'Morgan3Feat'] fingerprint type to generate for each product molecule input_data_folder : Optional[Union[str, bytes, os.PathLike]] (Default = None) path to the folder containing the train/valid/test reaction SMILES strings if None, this defaults to: path/to/rxn/ebm/data/cleaned_data/ input_data_file_prefix : Optional[str] (Default = '50k_clean_rxnsmi_noreagent_allmapped') prefix of the 3 pickle files containing the train/valid/test reaction SMILES strings output_folder : Optional[Union[str, bytes, os.PathLike]] (Default = None) path to the folder that will contain the CSV file(s) containing Retrosim's proposals if None, this defaults to the same folder as input_data_folder parallelize : Optional[bool] (Default = False) whether to parallelize the proposal generation step, using all available cores ''' def __init__(self, topk: int = 200, max_prec: int = 200, similarity_type: Optional[str] = 'Tanimoto', fp_type: Optional[str] = 'Morgan2Feat', input_data_folder: Optional[Union[str, bytes, os.PathLike]] = None, input_data_file_prefix: Optional[str] = '50k_clean_rxnsmi_noreagent_allmapped', output_folder: Optional[Union[str, bytes, os.PathLike]] = None, parallelize: Optional[bool] = True): self.topk = topk self.max_prec = max_prec if similarity_type == 'Tanimoto': self.similarity_metric = lambda x, y: DataStructs.BulkTanimotoSimilarity(x, y) elif similarity_type == 'Dice': self.similarity_metric = lambda x, y: DataStructs.BulkDiceSimilarity(x, y) elif similarity_type == 'TverskyA': # weighted towards punishing only A self.similarity_metric = lambda x, y: DataStructs.BulkTverskySimilarity(x, y, 1.5, 1.0) elif similarity_type == 'TverskyB': # weighted towards punishing only B self.similarity_metric = lambda x, y: DataStructs.BulkTverskySimilarity(x, y, 1.0, 1.5) else: raise ValueError('Unknown similarity type') if fp_type == 'Morgan2Feat': self.getfp = lambda smi: AllChem.GetMorganFingerprint(Chem.MolFromSmiles(smi), 2, useFeatures=True) elif fp_type == 'Morgan2noFeat': self.getfp = lambda smi: AllChem.GetMorganFingerprint(Chem.MolFromSmiles(smi), 2, useFeatures=False) elif fp_type == 'Morgan3Feat': self.getfp = lambda smi: AllChem.GetMorganFingerprint(Chem.MolFromSmiles(smi), 3, useFeatures=True) elif fp_type == 'Morgan3noFeat': self.getfp = lambda smi: AllChem.GetMorganFingerprint(Chem.MolFromSmiles(smi), 3, useFeatures=False) else: raise ValueError('Unknown fingerprint type') if input_data_folder is None: self.input_folder = Path(__file__).resolve().parents[1] / 'data/cleaned_data/' else: self.input_folder = Path(input_data_folder) self.input_prefix = input_data_file_prefix if output_folder is None: self.output_folder = self.input_folder else: self.output_folder = Path(output_folder) self.parallelize = parallelize self._prep_training_corpus() def _prep_training_corpus(self) -> None: ''' Sets (but only with training data): self.clean_50k (Dict[str, List[str]]), self.clean_50k_remove_atom_map (Dict[str, List[str]]), self.prod_smiles (Dict[str, List[str]]), self.rcts_smiles (Dict[str, List[str]]), self.all_prod_smiles (List[str]) ''' print('Preparing training data for Retrosim...') clean_50k, clean_50k_remove_atom_map = {}, {} prod_smiles, rcts_smiles = {}, {} phase_marker = [] # to create 'dataset' column for dataframe all_prod_smiles, all_rxn_smiles = [], [] # for dataframe self.phases = ['train'] for phase in self.phases: phase_rxn_smi_remove_atom_map, phase_prod_smis, phase_rcts_smis = [], [], [] with open(self.input_folder / f'{self.input_prefix}_{phase}.pickle', 'rb') as handle: clean_50k[phase] = pickle.load(handle) phase_marker.extend([phase] * len(clean_50k[phase])) for rxn_smi in tqdm(clean_50k[phase]): all_rxn_smiles.append(rxn_smi) prod_smi = rxn_smi.split('>>')[-1] prod_mol = Chem.MolFromSmiles(prod_smi) [atom.ClearProp('molAtomMapNumber') for atom in prod_mol.GetAtoms()] prod_smi_remove_atom_map = Chem.MolToSmiles(prod_mol, True) prod_smi_remove_atom_map = Chem.MolToSmiles(Chem.MolFromSmiles(prod_smi_remove_atom_map), True) all_prod_smiles.append(prod_smi_remove_atom_map) phase_prod_smis.append(prod_smi_remove_atom_map) rcts_smi = rxn_smi.split('>>')[0] rcts_mol = Chem.MolFromSmiles(rcts_smi) [atom.ClearProp('molAtomMapNumber') for atom in rcts_mol.GetAtoms()] rcts_smi_remove_atom_map = Chem.MolToSmiles(rcts_mol, True) # Sometimes stereochem takes another canonicalization... rcts_smi_remove_atom_map = Chem.MolToSmiles(Chem.MolFromSmiles(rcts_smi_remove_atom_map), True) phase_rcts_smis.append(rcts_smi_remove_atom_map) rxn_smi_remove_atom_map = rcts_smi_remove_atom_map + '>>' + prod_smi_remove_atom_map phase_rxn_smi_remove_atom_map.append(rxn_smi_remove_atom_map) clean_50k_remove_atom_map[phase] = phase_rxn_smi_remove_atom_map prod_smiles[phase] = phase_prod_smis rcts_smiles[phase] = phase_rcts_smis data = pd.DataFrame({ 'prod_smiles': all_prod_smiles, 'rxn_smiles': all_rxn_smiles, 'dataset': phase_marker, }) try: if prev_FP != self.getfp: raise NameError except NameError: all_fps = [] for smi in tqdm(data['prod_smiles'], desc='Generating fingerprints'): all_fps.append(self.getfp(smi)) data['prod_fp'] = all_fps prev_FP = self.getfp self.datasub = data.loc[data['dataset'] == 'train'] fps = list(self.datasub['prod_fp']) print(f'Size of training corpus: {len(fps)}') try: with open(self.input_folder / 'jx_cache.pickle', 'rb') as handle: self.jx_cache = pickle.load(handle) except: print('Did not find jx_cache.pickle, initialising new jx_cache dictionary') self.jx_cache = {} self.clean_50k = clean_50k self.clean_50k_remove_atom_map = clean_50k_remove_atom_map self.prod_smiles = prod_smiles self.rcts_smiles = rcts_smiles self.all_prod_smiles = all_prod_smiles def prep_valid_and_test_data(self, input_data_folder: Optional[Union[str, bytes, os.PathLike]] = None, input_data_file_prefix: Optional[str] = None) -> None: ''' Needs self._prep_training_corpus() to have executed first! Sets: self.clean_50k (Dict[str, List[str]]), self.clean_50k_remove_atom_map (Dict[str, List[str]]), self.prod_smiles (Dict[str, List[str]]), self.rcts_smiles (Dict[str, List[str]]), self.all_prod_smiles (List[str]) ''' # retrieve existing data prepared by self._prep_training_corpus() clean_50k, clean_50k_remove_atom_map = self.clean_50k, self.clean_50k_remove_atom_map prod_smiles, rcts_smiles = self.prod_smiles, self.rcts_smiles all_prod_smiles = self.all_prod_smiles # for self.propose_all() print('Preparing validation and testing data for Retrosim...') self.phases = ['valid', 'test'] for phase in self.phases: phase_rxn_smi_remove_atom_map, phase_prod_smis, phase_rcts_smis = [], [], [] if input_data_folder is None: input_data_folder = self.input_folder if input_data_file_prefix is None: input_data_file_prefix = self.input_prefix with open(input_data_folder / f'{input_data_file_prefix}_{phase}.pickle', 'rb') as handle: clean_50k[phase] = pickle.load(handle) for rxn_smi in tqdm(clean_50k[phase], desc=f'Processing {phase}'): prod_smi = rxn_smi.split('>>')[-1] prod_mol = Chem.MolFromSmiles(prod_smi) [atom.ClearProp('molAtomMapNumber') for atom in prod_mol.GetAtoms()] prod_smi_remove_atom_map = Chem.MolToSmiles(prod_mol, True) prod_smi_remove_atom_map = Chem.MolToSmiles(Chem.MolFromSmiles(prod_smi_remove_atom_map), True) all_prod_smiles.append(prod_smi_remove_atom_map) phase_prod_smis.append(prod_smi_remove_atom_map) rcts_smi = rxn_smi.split('>>')[0] rcts_mol = Chem.MolFromSmiles(rcts_smi) [atom.ClearProp('molAtomMapNumber') for atom in rcts_mol.GetAtoms()] rcts_smi_remove_atom_map = Chem.MolToSmiles(rcts_mol, True) # Sometimes stereochem takes another canonicalization... rcts_smi_remove_atom_map = Chem.MolToSmiles(Chem.MolFromSmiles(rcts_smi_remove_atom_map), True) phase_rcts_smis.append(rcts_smi_remove_atom_map) rxn_smi_remove_atom_map = rcts_smi_remove_atom_map + '>>' + prod_smi_remove_atom_map phase_rxn_smi_remove_atom_map.append(rxn_smi_remove_atom_map) clean_50k_remove_atom_map[phase] = phase_rxn_smi_remove_atom_map prod_smiles[phase] = phase_prod_smis rcts_smiles[phase] = phase_rcts_smis self.clean_50k = clean_50k self.clean_50k_remove_atom_map = clean_50k_remove_atom_map self.prod_smiles = prod_smiles self.rcts_smiles = rcts_smiles self.all_prod_smiles = all_prod_smiles def propose_one(self, prod_smiles: str, topk: int = 200, max_prec: int = 200) -> List[str]: ex = mol_from_smiles(prod_smiles) rct = rdchiralreactant_dist(prod_smiles) fp = self.getfp(prod_smiles) sims = self.similarity_metric(fp, [fp_ for fp_ in self.datasub['prod_fp']]) js = np.argsort(sims)[::-1] # Get probability of precursors probs = {} for j in js[:max_prec]: jx = self.datasub.index[j] if jx in self.jx_cache: (template, rcts_ref_fp) = self.jx_cache[jx] else: retro_canonical = process_an_example(self.datasub['rxn_smiles'][jx], super_general=True) if retro_canonical is None: # cannot get template, most likely due to 'could not find consistent tetrahedral centre' continue template = '(' + retro_canonical.replace('>>', ')>>') rcts_ref_fp = self.getfp(self.datasub['rxn_smiles'][jx].split('>')[0]) self.jx_cache[jx] = (template, rcts_ref_fp) rxn = rdchiralreaction_dist(template) try: outcomes = rdchiralrun_dist(rxn, rct, combine_enantiomers=False) except Exception as e: print(e) outcomes = [] for precursors in outcomes: precursors_fp = self.getfp(precursors) precursors_sim = self.similarity_metric(precursors_fp, [rcts_ref_fp])[0] if precursors in probs: probs[precursors] = max(probs[precursors], precursors_sim * sims[j]) else: probs[precursors] = precursors_sim * sims[j] mols = [] found_rank = 9999 for r, (prec, prob) in enumerate(sorted(probs.items(), key=lambda x:x[1], reverse=True)[:topk]): mols.append(mol_from_smiles(prec)) proposed_precursors_smiles = [mol_to_smiles(x, True) for x in mols] return proposed_precursors_smiles def propose_one_helper(self, prod_smiles: str, results: dict, topk: int = 200, max_prec: int = 200) -> Dict[str, List[str]]: ''' wrapper over self.propose_one() to allow parallelization within self.propose_all() ''' results[prod_smiles] = self.propose_one(prod_smiles, topk=topk, max_prec=max_prec) return results def propose_all(self) -> None: ''' iterates through all product smiles in dataset (self.all_prod_smiles) and proposes precursors for them based on self.max_prec and self.topk Sets self.all_proposed_smiles upon successful execution ''' if (self.output_folder / f'retrosim_proposed_smiles_{self.topk}maxtest_{self.max_prec}maxprec.pickle' ).exists(): # file already exists with open(self.output_folder / f'retrosim_proposed_smiles_{self.topk}maxtest_{self.max_prec}maxprec.pickle', 'rb' ) as handle: self.all_proposed_smiles = pickle.load(handle) self._compile_into_csv() else: all_proposed_smiles = {} if self.parallelize: # TODO: see if this can also be checkpointed from inside self.propose_one_helper() try: num_workers = len(os.sched_getaffinity(0)) except AttributeError: num_workers = os.cpu_count() print(f"Parallelizing over {num_workers} cores") results = {} with tqdm_joblib(tqdm(desc="Generating Retrosim's Proposals", total=len(self.all_prod_smiles))) as progress_bar: output_dicts = Parallel(n_jobs=num_workers)( delayed(self.propose_one_helper)( prod_smi, results, self.topk, self.max_prec ) for prod_smi in self.all_prod_smiles ) for output_dict in output_dicts: all_proposed_smiles.update(output_dict) else: for i, prod_smi in enumerate(tqdm(self.all_prod_smiles, desc="Generating Retrosim's Proposals...")): if prod_smi in all_proposed_smiles and len(all_proposed_smiles[prod_smi]) > 0: continue # no need to repeat calculation all_proposed_smiles[prod_smi] = self.propose_one(prod_smi, self.topk, self.max_prec) if i % 4000 == 0: # checkpoint temporary files with open(self.output_folder / f'retrosim_proposed_smiles_{self.topk}maxtest_{self.max_prec}maxprec_{i}.pickle', 'wb') as handle: pickle.dump(all_proposed_smiles, handle, protocol=pickle.HIGHEST_PROTOCOL) with open( self.output_folder / f'retrosim_proposed_smiles_{self.topk}maxtest_{self.max_prec}maxprec.pickle', 'wb' ) as handle: pickle.dump(all_proposed_smiles, handle, protocol=pickle.HIGHEST_PROTOCOL) with open(self.input_folder / 'jx_cache.pickle', 'wb') as handle: pickle.dump(jx_cache, handle, protocol=pickle.HIGHEST_PROTOCOL) self.all_proposed_smiles = all_proposed_smiles self._compile_into_csv() def _compile_into_csv(self): ''' Sets self.proposed_precursors Also runs self._calc_accs() ''' if self.all_proposed_smiles is None: with open( self.output_folder / f'retrosim_proposed_smiles_{self.topk}maxtest_{self.max_prec}maxprec.pickle', 'rb' ) as handle: self.all_proposed_smiles = pickle.load(handle) proposed_precursors = {} self.phases = ['train', 'valid', 'test'] for phase in self.phases: dup_count = 0 phase_proposed_precursors = [] for rxn_smi in self.clean_50k_remove_atom_map[phase]: prod_smi = rxn_smi.split('>>')[-1] precursors = self.all_proposed_smiles[prod_smi] # check for duplicates - but by design, retrosim shouldn't make any duplicate proposal seen = [] for prec in precursors: # no need to canonicalize bcos retrosim already canonicalized if prec not in seen: seen.append(prec) else: dup_count += 1 if len(precursors) < self.topk: precursors.extend(['9999'] * (self.topk - len(precursors))) phase_proposed_precursors.append(precursors) proposed_precursors[phase] = phase_proposed_precursors dup_count /= len(self.clean_50k_remove_atom_map[phase]) print(f'Avg # dups per product for {phase}: {dup_count}') # should be 0 self.proposed_precursors = proposed_precursors print('Compiled proposed_precursors by rxn_smi!') self.ranks, self.accs = self._calc_accs() # repeat accuracy calculation after removing ground truth predictions _, _ = self._calc_accs() combined = {} for phase in self.phases: zipped = [] for rxn_smi, prod_smi, rcts_smi, rank_of_true_precursor, proposed_rcts_smi in zip( self.clean_50k[phase], self.prod_smiles[phase], self.rcts_smiles[phase], self.ranks[phase], proposed_precursors[phase], ): result = [] result.extend([rxn_smi, prod_smi, rcts_smi, rank_of_true_precursor]) result.extend(proposed_rcts_smi) zipped.append(result) combined[phase] = zipped print('Zipped all info for each rxn_smi into a list for dataframe creation!') processed_dataframes = {} for phase in self.phases: temp_dataframe = pd.DataFrame( data={ 'zipped': combined[phase] } ) phase_dataframe = pd.DataFrame( temp_dataframe['zipped'].to_list(), index=temp_dataframe.index ) if phase == 'train': # true precursor has been removed from the proposals, so whatever is left are negatives proposed_col_names = [f'neg_precursor_{i}' for i in range(1, self.topk+1)] else: # validation/testing, we don't assume true precursor is present & we also do not remove them if present proposed_col_names = [f'cand_precursor_{i}' for i in range(1, self.topk+1)] base_col_names = ['orig_rxn_smi', 'prod_smi', 'true_precursors', 'rank_of_true_precursor'] base_col_names.extend(proposed_col_names) phase_dataframe.columns = base_col_names processed_dataframes[phase] = phase_dataframe print(f'Shape of {phase} dataframe: {phase_dataframe.shape}') phase_dataframe.to_csv( self.output_folder / f'retrosim_{self.topk}maxtest_{self.max_prec}maxprec_{phase}.csv', index=False ) print(f'Saved all proposals as 3 dataframes in {self.output_folder}!') def _calc_accs(self): ''' Returns: ranks, accs ''' ranks = {} for phase in self.phases: phase_ranks = [] if phase == 'train': for idx in tqdm(range(len(self.clean_50k[phase])), desc=phase): true_precursors = self.rcts_smiles[phase][idx] all_proposed_precursors = self.proposed_precursors[phase][idx] found = False for rank, proposal in enumerate(all_proposed_precursors): # ranks are 0-indexed if true_precursors == proposal: phase_ranks.append(rank) # remove true precursor from proposals all_proposed_precursors.pop(rank) all_proposed_precursors.append('9999') found = True break if not found: phase_ranks.append(9999) self.proposed_precursors[phase][idx] = all_proposed_precursors else: for idx in tqdm(range(len(self.clean_50k[phase])), desc=phase): true_precursors = self.rcts_smiles[phase][idx] all_proposed_precursors = self.proposed_precursors[phase][idx] found = False for rank, proposal in enumerate(all_proposed_precursors): # ranks are 0-indexed if true_precursors == proposal: phase_ranks.append(rank) # do not pop true precursor from proposals! found = True break if not found: phase_ranks.append(9999) self.proposed_precursors[phase][idx] = all_proposed_precursors ranks[phase] = phase_ranks accs = {} for phase in self.phases: phase_accs = [] for n in [1, 3, 5, 10, 20, 50]: total = float(len(ranks[phase])) phase_accs.append(sum([r+1 <= n for r in ranks[phase]]) / total) print(f'{phase} Top-{n} accuracy: {phase_accs[-1]*100:.3f}%') print('\n') accs[phase] = phase_accs return ranks, accs def analyse_proposed(self): if self.all_proposed_smiles is None: with open( self.output_folder / f'retrosim_proposed_smiles_{self.topk}maxtest_{self.max_prec}maxprec.pickle', 'rb' ) as handle: self.all_proposed_smiles = pickle.load(handle) proposed_counter = Counter() total_proposed, min_proposed, max_proposed = 0, float('+inf'), float('-inf') key_count = 0 for key, value in tqdm(self.all_proposed_smiles.items()): precursors_count = len(value) total_proposed += precursors_count if precursors_count > max_proposed: max_proposed = precursors_count prod_smi_max = key if precursors_count < min_proposed: min_proposed = precursors_count prod_smi_min = key proposed_counter[key] = precursors_count key_count += 1 print(f'Average precursors proposed per prod_smi: {total_proposed / key_count}') print(f'Min precursors: {min_proposed} for {prod_smi_min}') print(f'Max precursors: {max_proposed} for {prod_smi_max})') print(f'\nMost common 20:') for i in proposed_counter.most_common(20): print(f'{i}') print(f'\nLeast common 20:') for i in proposed_counter.most_common()[-20:]: print(f'{i}') if __name__ == '__main__': retrosim_model = Retrosim(topk=200, max_prec=200, similarity_type='Tanimoto', fp_type='Morgan2Feat') retrosim_model.prep_valid_and_test_data(input_data_file_prefix='50k_clean_rxnsmi_noreagent_allmapped') retrosim_model.propose_all() retrosim_model.analyse_proposed()
[ "numpy.argsort", "os.cpu_count", "pathlib.Path", "rdkit.Chem.MolToSmiles", "rdchiral.main.rdchiralRun", "pandas.DataFrame", "rdchiral.main.rdchiralReaction", "rdchiral.main.rdchiralReactants", "pickle.load", "rdkit.DataStructs.BulkTverskySimilarity", "rdkit.DataStructs.BulkDiceSimilarity", "rx...
[((1573, 1599), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['smiles'], {}), '(smiles)\n', (1591, 1599), True, 'import rdkit.Chem as Chem\n'), ((1671, 1708), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['mol', 'isomericSmiles'], {}), '(mol, isomericSmiles)\n', (1687, 1708), True, 'import rdkit.Chem as Chem\n'), ((1775, 1823), 'rdkit.DataStructs.BulkTanimotoSimilarity', 'DataStructs.BulkTanimotoSimilarity', (['fp', 'list_fps'], {}), '(fp, list_fps)\n', (1809, 1823), False, 'from rdkit import DataStructs\n'), ((1886, 1908), 'rdchiral.main.rdchiralReactants', 'rdchiralReactants', (['smi'], {}), '(smi)\n', (1903, 1908), False, 'from rdchiral.main import rdchiralReactants, rdchiralReaction, rdchiralRun\n'), ((1958, 1984), 'rdchiral.main.rdchiralReaction', 'rdchiralReaction', (['template'], {}), '(template)\n', (1974, 1984), False, 'from rdchiral.main import rdchiralReactants, rdchiralReaction, rdchiralRun\n'), ((2050, 2112), 'rdchiral.main.rdchiralRun', 'rdchiralRun', (['rxn', 'rct'], {'combine_enantiomers': 'combine_enantiomers'}), '(rxn, rct, combine_enantiomers=combine_enantiomers)\n', (2061, 2112), False, 'from rdchiral.main import rdchiralReactants, rdchiralReaction, rdchiralRun\n'), ((9066, 9171), 'pandas.DataFrame', 'pd.DataFrame', (["{'prod_smiles': all_prod_smiles, 'rxn_smiles': all_rxn_smiles, 'dataset':\n phase_marker}"], {}), "({'prod_smiles': all_prod_smiles, 'rxn_smiles': all_rxn_smiles,\n 'dataset': phase_marker})\n", (9078, 9171), True, 'import pandas as pd\n'), ((26066, 26075), 'collections.Counter', 'Counter', ([], {}), '()\n', (26073, 26075), False, 'from collections import Counter\n'), ((6142, 6165), 'pathlib.Path', 'Path', (['input_data_folder'], {}), '(input_data_folder)\n', (6146, 6165), False, 'from pathlib import Path\n'), ((6350, 6369), 'pathlib.Path', 'Path', (['output_folder'], {}), '(output_folder)\n', (6354, 6369), False, 'from pathlib import Path\n'), ((7524, 7546), 'tqdm.tqdm', 'tqdm', (['clean_50k[phase]'], {}), '(clean_50k[phase])\n', (7528, 7546), False, 'from tqdm import tqdm\n'), ((11748, 11798), 'tqdm.tqdm', 'tqdm', (['clean_50k[phase]'], {'desc': 'f"""Processing {phase}"""'}), "(clean_50k[phase], desc=f'Processing {phase}')\n", (11752, 11798), False, 'from tqdm import tqdm\n'), ((13909, 13925), 'numpy.argsort', 'np.argsort', (['sims'], {}), '(sims)\n', (13919, 13925), True, 'import numpy as np\n'), ((21901, 21947), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'zipped': combined[phase]}"}), "(data={'zipped': combined[phase]})\n", (21913, 21947), True, 'import pandas as pd\n'), ((4679, 4719), 'rdkit.DataStructs.BulkTanimotoSimilarity', 'DataStructs.BulkTanimotoSimilarity', (['x', 'y'], {}), '(x, y)\n', (4713, 4719), False, 'from rdkit import DataStructs\n'), ((7391, 7410), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (7402, 7410), False, 'import pickle\n'), ((7694, 7722), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['prod_smi'], {}), '(prod_smi)\n', (7712, 7722), True, 'import rdkit.Chem as Chem\n'), ((7851, 7883), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['prod_mol', '(True)'], {}), '(prod_mol, True)\n', (7867, 7883), True, 'import rdkit.Chem as Chem\n'), ((8221, 8249), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['rcts_smi'], {}), '(rcts_smi)\n', (8239, 8249), True, 'import rdkit.Chem as Chem\n'), ((8378, 8410), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['rcts_mol', '(True)'], {}), '(rcts_mol, True)\n', (8394, 8410), True, 'import rdkit.Chem as Chem\n'), ((9373, 9430), 'tqdm.tqdm', 'tqdm', (["data['prod_smiles']"], {'desc': '"""Generating fingerprints"""'}), "(data['prod_smiles'], desc='Generating fingerprints')\n", (9377, 9430), False, 'from tqdm import tqdm\n'), ((9834, 9853), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (9845, 9853), False, 'import pickle\n'), ((11699, 11718), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (11710, 11718), False, 'import pickle\n'), ((11899, 11927), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['prod_smi'], {}), '(prod_smi)\n', (11917, 11927), True, 'import rdkit.Chem as Chem\n'), ((12056, 12088), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['prod_mol', '(True)'], {}), '(prod_mol, True)\n', (12072, 12088), True, 'import rdkit.Chem as Chem\n'), ((12442, 12470), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['rcts_smi'], {}), '(rcts_smi)\n', (12460, 12470), True, 'import rdkit.Chem as Chem\n'), ((12599, 12631), 'rdkit.Chem.MolToSmiles', 'Chem.MolToSmiles', (['rcts_mol', '(True)'], {}), '(rcts_mol, True)\n', (12615, 12631), True, 'import rdkit.Chem as Chem\n'), ((14220, 14290), 'rxnebm.proposer.RetroSim.retrosim.utils.generate_retro_templates.process_an_example', 'process_an_example', (["self.datasub['rxn_smiles'][jx]"], {'super_general': '(True)'}), "(self.datasub['rxn_smiles'][jx], super_general=True)\n", (14238, 14290), False, 'from rxnebm.proposer.RetroSim.retrosim.utils.generate_retro_templates import process_an_example\n'), ((16785, 16804), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (16796, 16804), False, 'import pickle\n'), ((18820, 18894), 'pickle.dump', 'pickle.dump', (['all_proposed_smiles', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(all_proposed_smiles, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (18831, 18894), False, 'import pickle\n'), ((19006, 19069), 'pickle.dump', 'pickle.dump', (['jx_cache', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(jx_cache, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (19017, 19069), False, 'import pickle\n'), ((19587, 19606), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (19598, 19606), False, 'import pickle\n'), ((26018, 26037), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (26029, 26037), False, 'import pickle\n'), ((4810, 4846), 'rdkit.DataStructs.BulkDiceSimilarity', 'DataStructs.BulkDiceSimilarity', (['x', 'y'], {}), '(x, y)\n', (4840, 4846), False, 'from rdkit import DataStructs\n'), ((5381, 5404), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['smi'], {}), '(smi)\n', (5399, 5404), True, 'import rdkit.Chem as Chem\n'), ((7944, 7988), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['prod_smi_remove_atom_map'], {}), '(prod_smi_remove_atom_map)\n', (7962, 7988), True, 'import rdkit.Chem as Chem\n'), ((8544, 8588), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['rcts_smi_remove_atom_map'], {}), '(rcts_smi_remove_atom_map)\n', (8562, 8588), True, 'import rdkit.Chem as Chem\n'), ((12149, 12193), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['prod_smi_remove_atom_map'], {}), '(prod_smi_remove_atom_map)\n', (12167, 12193), True, 'import rdkit.Chem as Chem\n'), ((12765, 12809), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['rcts_smi_remove_atom_map'], {}), '(rcts_smi_remove_atom_map)\n', (12783, 12809), True, 'import rdkit.Chem as Chem\n'), ((17918, 17987), 'tqdm.tqdm', 'tqdm', (['self.all_prod_smiles'], {'desc': '"""Generating Retrosim\'s Proposals..."""'}), '(self.all_prod_smiles, desc="Generating Retrosim\'s Proposals...")\n', (17922, 17987), False, 'from tqdm import tqdm\n'), ((4977, 5026), 'rdkit.DataStructs.BulkTverskySimilarity', 'DataStructs.BulkTverskySimilarity', (['x', 'y', '(1.5)', '(1.0)'], {}), '(x, y, 1.5, 1.0)\n', (5010, 5026), False, 'from rdkit import DataStructs\n'), ((5534, 5557), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['smi'], {}), '(smi)\n', (5552, 5557), True, 'import rdkit.Chem as Chem\n'), ((17096, 17119), 'os.sched_getaffinity', 'os.sched_getaffinity', (['(0)'], {}), '(0)\n', (17116, 17119), False, 'import os\n'), ((17194, 17208), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (17206, 17208), False, 'import os\n'), ((17468, 17496), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'num_workers'}), '(n_jobs=num_workers)\n', (17476, 17496), False, 'from joblib import Parallel, delayed\n'), ((5157, 5206), 'rdkit.DataStructs.BulkTverskySimilarity', 'DataStructs.BulkTverskySimilarity', (['x', 'y', '(1.0)', '(1.5)'], {}), '(x, y, 1.0, 1.5)\n', (5190, 5206), False, 'from rdkit import DataStructs\n'), ((5686, 5709), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['smi'], {}), '(smi)\n', (5704, 5709), True, 'import rdkit.Chem as Chem\n'), ((18511, 18585), 'pickle.dump', 'pickle.dump', (['all_proposed_smiles', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(all_proposed_smiles, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (18522, 18585), False, 'import pickle\n'), ((5839, 5862), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['smi'], {}), '(smi)\n', (5857, 5862), True, 'import rdkit.Chem as Chem\n'), ((6036, 6050), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (6040, 6050), False, 'from pathlib import Path\n'), ((17522, 17554), 'joblib.delayed', 'delayed', (['self.propose_one_helper'], {}), '(self.propose_one_helper)\n', (17529, 17554), False, 'from joblib import Parallel, delayed\n')]
# Copyright 2018 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 # # https://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. """Detects section barlines, which are much thicker than normal barlines. Section barlines appear as connected components which span the height of the system, and are not too thick. They may have 2 repeat dots on one or both sides of each staff (at y positions -1 and 1), which affect the barline type. """ # TODO(ringw): Get repeat dots from the components and adjust the barline # type accordingly. Currently, assume all thick barlines are END_BAR. from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from moonlight.protobuf import musicscore_pb2 from moonlight.structure import barlines from moonlight.structure import components as components_module Bar = musicscore_pb2.StaffSystem.Bar # pylint: disable=invalid-name COLUMNS = components_module.ConnectedComponentsColumns class SectionBarlines(object): """Reads the connected components, and adds thick barlines to the page.""" def __init__(self, structure): self.components = structure.connected_components.components self.staff_detector = structure.staff_detector def apply(self, page): """Detects thick section barlines from the connected components. These should be tall components that start and end near the start and end of two (possibly different) staves. We use the standard barlines logic to assign components to the nearest start and end staff. We filter for candidate barlines, whose start and end are sufficiently close to the expected values. We then filter again by whether the component width is within the expected values for section barlines. For each staff system, we take the section barlines that match exactly that system's staves. Any standard barlines that are too close to a new section barline are removed, and we merge the existing standard barlines with the new section barlines. Args: page: A Page message. Returns: The same Page message, with new section barlines added. """ component_center_x = np.mean( self.components[:, [COLUMNS.X0, COLUMNS.X1]], axis=1).astype(int) # Take section barline candidates, whose start and end y values are close # enough to the staff start and end ys. component_is_candidate, candidate_start_staff, candidate_end_staff = ( barlines.assign_barlines_to_staves( barline_x=component_center_x, barline_y0=self.components[:, COLUMNS.Y0], barline_y1=self.components[:, COLUMNS.Y1], staff_detector=self.staff_detector)) candidates = self.components[component_is_candidate] candidate_center_x = component_center_x[component_is_candidate] del component_center_x # Filter again by the expected section barline width. component_width = candidates[:, COLUMNS.X1] - candidates[:, COLUMNS.X0] component_width_ok = np.logical_and( self._section_min_width() <= component_width, component_width <= self._section_max_width(candidate_start_staff)) candidates = candidates[component_width_ok] candidate_center_x = candidate_center_x[component_width_ok] candidate_start_staff = candidate_start_staff[component_width_ok] candidate_end_staff = candidate_end_staff[component_width_ok] # For each existing staff system, consider only the candidates that match # exactly the system's start and end staves. start_staff = 0 for system in page.system: staffline_distance = np.median( [staff.staffline_distance for staff in system.staff]).astype(int) candidate_covers_staff_system = np.logical_and( candidate_start_staff == start_staff, candidate_end_staff + 1 == start_staff + len(system.staff)) # Calculate the x coordinates of all section barlines to keep. section_bar_x = candidate_center_x[candidate_covers_staff_system] # Extract the existing bar x coordinates and types for merging. existing_bar_type = {bar.x: bar.type for bar in system.bar} existing_bars = np.asarray([bar.x for bar in system.bar]) # Merge the existing barlines and section barlines. if existing_bars.size and section_bar_x.size: # Filter the existing bars by whether they are far enough from a new # section barline. Section barlines override the existing standard # barlines. existing_bars_ok = np.greater( np.min( np.abs(existing_bars[:, None] - section_bar_x[None, :]), axis=1), staffline_distance * 4) existing_bars = existing_bars[existing_bars_ok] # Merge the existing barlines which we kept, and the new section barlines # (which are assumed to be type END_BAR), in sorted order. bars = sorted( [Bar(x=x, type=existing_bar_type[x]) for x in existing_bars] + [Bar(x=x, type=Bar.END_BAR) for x in section_bar_x], key=lambda bar: bar.x) # Update the staff system. system.ClearField('bar') system.bar.extend(bars) start_staff += len(system.staff) return page def _section_min_width(self): return self.staff_detector.staffline_thickness * 3 def _section_max_width(self, staff_index): return self.staff_detector.staffline_distance[staff_index] * 2 class MergeStandardAndBeginRepeatBars(object): """Detects a begin repeat at the beginning of the staff system. Typically, a begin repeat bar on a new line will be preceded by a standard barline, clef, and key signature. We can override a standard bar with a section bar if they are close together, but this distance is typically closer than the two bars are in this case. We want the two bars to be replaced by a single begin repeat bar where we actually found the first bar, because we want the clef, key signature, and notes to be a single measure. Because we don't yet detect repeat dots, and all non-STANDARD barlines are detected as END_BAR, we accept any non-STANDARD barlines for the second bar. """ def __init__(self, structure): self.staff_detector = structure.staff_detector def apply(self, page): for system in page.system: if (len(system.bar) > 1 and system.bar[0].type == Bar.STANDARD_BAR and system.bar[1].type != Bar.STANDARD_BAR): staffline_distance = np.median( [staff.staffline_distance for staff in system.staff]) if system.bar[1].x - system.bar[0].x < staffline_distance * 12: system.bar[0].type = system.bar[1].type del system.bar[1] return page
[ "numpy.mean", "numpy.abs", "numpy.median", "numpy.asarray", "moonlight.structure.barlines.assign_barlines_to_staves" ]
[((2920, 3116), 'moonlight.structure.barlines.assign_barlines_to_staves', 'barlines.assign_barlines_to_staves', ([], {'barline_x': 'component_center_x', 'barline_y0': 'self.components[:, COLUMNS.Y0]', 'barline_y1': 'self.components[:, COLUMNS.Y1]', 'staff_detector': 'self.staff_detector'}), '(barline_x=component_center_x, barline_y0\n =self.components[:, COLUMNS.Y0], barline_y1=self.components[:, COLUMNS.\n Y1], staff_detector=self.staff_detector)\n', (2954, 3116), False, 'from moonlight.structure import barlines\n'), ((4626, 4667), 'numpy.asarray', 'np.asarray', (['[bar.x for bar in system.bar]'], {}), '([bar.x for bar in system.bar])\n', (4636, 4667), True, 'import numpy as np\n'), ((2632, 2693), 'numpy.mean', 'np.mean', (['self.components[:, [COLUMNS.X0, COLUMNS.X1]]'], {'axis': '(1)'}), '(self.components[:, [COLUMNS.X0, COLUMNS.X1]], axis=1)\n', (2639, 2693), True, 'import numpy as np\n'), ((6907, 6970), 'numpy.median', 'np.median', (['[staff.staffline_distance for staff in system.staff]'], {}), '([staff.staffline_distance for staff in system.staff])\n', (6916, 6970), True, 'import numpy as np\n'), ((4068, 4131), 'numpy.median', 'np.median', (['[staff.staffline_distance for staff in system.staff]'], {}), '([staff.staffline_distance for staff in system.staff])\n', (4077, 4131), True, 'import numpy as np\n'), ((5025, 5080), 'numpy.abs', 'np.abs', (['(existing_bars[:, None] - section_bar_x[None, :])'], {}), '(existing_bars[:, None] - section_bar_x[None, :])\n', (5031, 5080), True, 'import numpy as np\n')]
from gym import spaces import numpy as np from pettingzoo.utils.env import ParallelEnv from pettingzoo.utils.agent_selector import agent_selector from gym.utils import seeding from gym import spaces from pettingzoo.utils import wrappers def make_env(raw_env): def env(**kwargs): env = raw_env(**kwargs) env = wrappers.AssertOutOfBoundsWrapper(env) backup_policy = "taking zero action (no movement, communication 0)" env = wrappers.NanNoOpWrapper(env, 4, backup_policy) env = wrappers.OrderEnforcingWrapper(env) return env return env class MatrixGameEnv(ParallelEnv): def __init__(self, num_agents, num_actions, utility_matrix, memory_length, max_frames): super(MatrixGameEnv, self).__init__() self.num_agents = num_agents self.num_actions = [num_actions] * num_agents if type(num_actions) == int else list(num_actions) self.sum_actions = sum(self.num_actions) self.utility_matrix = np.array(utility_matrix) self.memory_length = memory_length self.max_frames = max_frames assert len(utility_matrix.shape) == num_agents + 1 assert utility_matrix.shape[num_agents] == num_agents for i in range(num_agents): assert utility_matrix.shape[i] == self.num_actions[i] self.agents = list(range(self.num_agents)) self.action_spaces = list() self.observation_spaces = list() self.input_structures = list() self.action_positions = list() position = 0 for i in range(self.num_agents): self.action_spaces.append(spaces.Discrete(self.num_actions[i])) observation_space = spaces.Box(low=0., high=1., shape=(1 + self.memory_length * self.sum_actions,), dtype=np.float32) self.observation_spaces.append(observation_space) self.input_structures.append(self._get_input_structure_agent(i)) self.action_positions.append(position) position += self.num_actions[i] self.action_history = np.zeros((max_frames, self.sum_actions)) self.steps = 0 def _get_obs_agent(self, agent_id): num_padding = max(0, self.memory_length - self.steps) padding = np.zeros((num_padding, self.sum_actions)) history = self.action_history[max(0, self.steps - self.memory_length): self.steps] history = np.concatenate((padding, history), axis=0) l_p = self.action_positions[agent_id] r_p = l_p + self.num_actions[agent_id] history = np.concatenate((history[:, l_p: r_p], history[:, :l_p], history[:, r_p:]), axis=1).reshape(-1) return np.concatenate(([self.steps / self.max_frames], history)) def _get_obs_all(self): obs_all = [self._get_obs_agent(i) for i in range(self.num_agents)] # print(obs_all) return obs_all def _get_input_structure_agent(self, agent_id): structure = [("step", 1)] for i in range(self.memory_length): structure.append((f"history-{i}-self", self.num_actions[agent_id])) for j in range(self.num_agents): if j != agent_id: structure.append((f"history-{i}-agent-{j}", self.num_actions[j])) return structure def reset(self): self.action_history.fill(0.) self.steps = 0 return self._get_obs_all() def step(self, actions): list_actions = [actions[i] for i in range(self.num_agents)] utility = self.utility_matrix[tuple(list_actions)] si = 0 for i in range(self.num_agents): self.action_history[self.steps, si + actions[i]] = 1. si += self.num_actions[i] self.steps += 1 rewards = (utility * 0.1).tolist() dones = [self.steps >= self.max_frames] * self.num_agents infos = [None] * self.num_agents return self._get_obs_all(), rewards, dones, infos def render(self, mode="human"): pass def seed(self, seed=None): pass
[ "pettingzoo.utils.wrappers.NanNoOpWrapper", "pettingzoo.utils.wrappers.OrderEnforcingWrapper", "pettingzoo.utils.wrappers.AssertOutOfBoundsWrapper", "gym.spaces.Discrete", "gym.spaces.Box", "numpy.array", "numpy.zeros", "numpy.concatenate" ]
[((331, 369), 'pettingzoo.utils.wrappers.AssertOutOfBoundsWrapper', 'wrappers.AssertOutOfBoundsWrapper', (['env'], {}), '(env)\n', (364, 369), False, 'from pettingzoo.utils import wrappers\n'), ((460, 506), 'pettingzoo.utils.wrappers.NanNoOpWrapper', 'wrappers.NanNoOpWrapper', (['env', '(4)', 'backup_policy'], {}), '(env, 4, backup_policy)\n', (483, 506), False, 'from pettingzoo.utils import wrappers\n'), ((521, 556), 'pettingzoo.utils.wrappers.OrderEnforcingWrapper', 'wrappers.OrderEnforcingWrapper', (['env'], {}), '(env)\n', (551, 556), False, 'from pettingzoo.utils import wrappers\n'), ((987, 1011), 'numpy.array', 'np.array', (['utility_matrix'], {}), '(utility_matrix)\n', (995, 1011), True, 'import numpy as np\n'), ((2099, 2139), 'numpy.zeros', 'np.zeros', (['(max_frames, self.sum_actions)'], {}), '((max_frames, self.sum_actions))\n', (2107, 2139), True, 'import numpy as np\n'), ((2284, 2325), 'numpy.zeros', 'np.zeros', (['(num_padding, self.sum_actions)'], {}), '((num_padding, self.sum_actions))\n', (2292, 2325), True, 'import numpy as np\n'), ((2435, 2477), 'numpy.concatenate', 'np.concatenate', (['(padding, history)'], {'axis': '(0)'}), '((padding, history), axis=0)\n', (2449, 2477), True, 'import numpy as np\n'), ((2699, 2756), 'numpy.concatenate', 'np.concatenate', (['([self.steps / self.max_frames], history)'], {}), '(([self.steps / self.max_frames], history))\n', (2713, 2756), True, 'import numpy as np\n'), ((1693, 1797), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(0.0)', 'high': '(1.0)', 'shape': '(1 + self.memory_length * self.sum_actions,)', 'dtype': 'np.float32'}), '(low=0.0, high=1.0, shape=(1 + self.memory_length * self.\n sum_actions,), dtype=np.float32)\n', (1703, 1797), False, 'from gym import spaces\n'), ((1623, 1659), 'gym.spaces.Discrete', 'spaces.Discrete', (['self.num_actions[i]'], {}), '(self.num_actions[i])\n', (1638, 1659), False, 'from gym import spaces\n'), ((2589, 2674), 'numpy.concatenate', 'np.concatenate', (['(history[:, l_p:r_p], history[:, :l_p], history[:, r_p:])'], {'axis': '(1)'}), '((history[:, l_p:r_p], history[:, :l_p], history[:, r_p:]),\n axis=1)\n', (2603, 2674), True, 'import numpy as np\n')]
import os import julian import datetime import math import pandas as pd import numpy as np from numpy import * import pickle from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA import matplotlib.pyplot as plt import warnings from sklearn.cluster import KMeans import matplotlib.colors as mcolors import scipy.stats from scipy.linalg import qr, solve, lstsq from scipy.stats import multivariate_normal from scipy.interpolate import griddata import random as rd import julian import time from pylab import * import warnings import random nasa_julian = 98 cnes_julian = 90 from mpl_toolkits.axes_grid1 import make_axes_locatable import os os.environ['PROJ_LIB']= "C:\\Users\\vankh\\Anaconda3\\Lib\\site-packages\\mpl_toolkits\\basemap" from mpl_toolkits.basemap import Basemap warnings.filterwarnings('ignore') def region_ex(name,pres_max,fe = 0.1): """ This function extracts data of a specific region ! Parameters ---------- - name: string name of the region - fe: float (default fe = 0.1) percentage of extracted dataset - pres_max: float maximum considered pressure Returns ------- - region: dict contain all informations of the region """ region_ = {} file = 'FetchData.pkl' if name == 'GulfStream': coords = {} coords["up_lon"] = -35 coords["low_lon"] = -75 coords["up_lat"] = 50 coords["low_lat"] = 30 name = 'GulfStream.pkl' region_ = regionv2(file,coords,name,fe,pres_max) elif name == 'Kuroshio': coords = {} coords["up_lon"] = 189 coords["low_lon"] = 132 coords["up_lat"] = 45 coords["low_lat"] = 25 name = 'Kuroshio.pkl' region_ = regionv2(file,coords,name,fe,pres_max) return region_ def regionv2( file, coords, name, fe, pres_max): """ Extract the the data of specific region from the global one by referencing to it's coordinates Preprocessing the data (date type, latiude, longtitude) Parameters: ----------- - file: string a file name containing the global information of the ocean. - coords: dict coordinates of the region. - name: string pickle file name of the region - fe: float percentage of extracted dataset - pres_max: float maximum considered pressure Returns: -------- - region: dict contain all region informations """ # Get a particular region # # get the root path root = os.path.abspath(os.path.join("", '..')) # invoke the global data gl_data = pd.read_pickle(root+"\\data\\"+file) # delete rebundant informations del gl_data['n'],gl_data['profile_n'] # get index index = np.where((gl_data['lat'] > coords["low_lat"])*(gl_data['lat'] < coords["up_lat"])*(gl_data['lon']>coords["low_lon"])*(gl_data['lon']<coords["up_lon"])) # region extract region = {v: gl_data[v][index] for v in gl_data} # process days jul_days = region['juld'] alpha0_x = np.ones(jul_days.shape[0]) alpha1_x = jul_days w = 1/365.25 sin_days = np.sin(2*math.pi*w*jul_days) cos_days = np.cos(2*math.pi*w*jul_days) # process latitude lat_rad = region['lat']*(math.pi/180) lat_sin = np.sin(lat_rad) # process longtitude lon_rad = region['lon']*(math.pi/180) lon_sin = np.sin(lon_rad) lon_cos = np.cos(lon_rad) # Create a processed dataset # region['alpha0_x'] = alpha0_x; region['alpha1_x'] = alpha1_x; region['sin_days'] = sin_days; region['cos_days'] = cos_days region['lat_sin'] = lat_sin; region['lon_sin'] = lon_sin; region['lon_cos'] = lon_cos data_split(region, pres_max, fe) def data_split(region, pres_max, fe = 0.1): """ Prepare the data to feed the model Parameters: ---------- - region: dict - fe: float (default = 0.1) percentage of data to feed the model - pres_max: float maximum considered pressure Returns: -------- - X: samples - y: target """ # features = ['alpha0_x','alpha1_x','sin_days','cos_days','lat_sin','lon_sin','lon_cos','sla','beta0_p','beta1_p','beta2_p'] features = ['alpha0_x','alpha1_x','sin_days','cos_days','lat_sin','lon_sin','lon_cos','sla','pres'] targets = ['temp','psal'] # orginal features o_features = ['lat','lon','juld','profile_ids'] uniq_profile, _ = np.unique(region['profile_ids'], return_counts = True) X_train = np.empty(shape=[0, len(features)]) y_train = np.empty(shape=[0, len(targets)]) o_feature_train = np.empty(shape=[0, len(o_features)]) # Extract by profile_ids, and pressure less than 100 for i,uni in enumerate(uniq_profile): index = np.where((region['profile_ids'] == uni)&(region['pres'] < pres_max))[0] nb_eles = int(index.shape[0]*fe) np.random.shuffle(index) train = index[0:nb_eles] # test = index[nb_eles:] x_uni_train = np.squeeze(np.asarray([[region[x][train]] for x in features])).T y_uni_train = np.squeeze(np.asarray([[region[x][train]] for x in targets])).T o_fea_uni_train = np.squeeze(np.asarray([[region[x][train]] for x in o_features])).T X_train = np.concatenate((X_train,x_uni_train.reshape(train.shape[0],len(features))), axis =0) y_train = np.concatenate((y_train,y_uni_train.reshape(train.shape[0],len(targets))), axis =0) o_feature_train = np.concatenate((o_feature_train,o_fea_uni_train.reshape(train.shape[0],len(o_features))), axis = 0) sav_obj = open("x.pkl", 'wb') pickle.dump(X_train,sav_obj) sav_obj.close() sav_obj = open("y.pkl", 'wb') pickle.dump(y_train,sav_obj) sav_obj.close() sav_obj = open("feature.pkl", 'wb') pickle.dump(o_feature_train,sav_obj) sav_obj.close() def lon_lat_juld(name): """ """ coords = {} file = 'FetchData.pkl' if name == 'GulfStream': coords = {} coords["up_lon"] = -35 coords["low_lon"] = -75 coords["up_lat"] = 50 coords["low_lat"] = 30 name = 'GulfStream_Coords.pkl' # Get a particular region # # get the root path root = os.path.abspath(os.path.join("", '..')) # invoke the global data gl_data = pd.read_pickle(root+"\\data\\"+file) # delete rebundant informations del gl_data['n'],gl_data['profile_n'] # get index index = np.where((gl_data['lat'] > coords["low_lat"])*(gl_data['lat'] < coords["up_lat"])*(gl_data['lon']>coords["low_lon"])*(gl_data['lon']<coords["up_lon"])) # region extract region = {v: gl_data[v][index] for v in gl_data} coords['lon'] = region['lon'] coords['lat'] = region['lat'] coords['juld'] = region['juld'] coords['profile_ids'] = region['profile_ids'] elif name == 'Kuroshio': coords = {} coords["up_lon"] = 189 coords["low_lon"] = 132 coords["up_lat"] = 45 coords["low_lat"] = 25 name = 'Kuroshio_Coords.pkl' # Get a particular region # # get the root path root = os.path.abspath(os.path.join("", '..')) # invoke the global data gl_data = pd.read_pickle(root+"\\data\\"+file) # delete rebundant informations del gl_data['n'],gl_data['profile_n'] # get index index = np.where((gl_data['lat'] > coords["low_lat"])*(gl_data['lat'] < coords["up_lat"])*(gl_data['lon']>coords["low_lon"])*(gl_data['lon']<coords["up_lon"])) # region extract region = {v: gl_data[v][index] for v in gl_data} coords['lon'] = region['lon'] coords['lat'] = region['lat'] coords['juld'] = region['juld'] coords['profile_ids'] = region['profile_ids'] # save dataset as a .pkl extention sav_obj = open(name, 'wb') pickle.dump(coords,sav_obj) sav_obj.close() return region def DR(X, variance = 0.8, nb_max = 6, to_plot = False,): """ This function does the dimension reduction on the samples Parameters ---------- - X: numpy array (nb_samples,features) - variances: float (default = 0.8) The percentage of variances to keep - nb_max: int (default = 5) max number of components considered to plot - to_plot: boolean plot the analysis Returns ------- - X_new: the new X with reduced dimensions """ # number of observations n = X.shape[0] # instanciation acp = PCA(svd_solver='full') X_transform = acp.fit_transform(X) print("Number of acp components features= ", acp.n_components_) #variance explained eigval = acp.explained_variance_ # variance of each component variances = acp.explained_variance_ratio_ # percentage of variance explained cumsum_var_explained= np.cumsum(variances) print("cumsum variance explained= ",cumsum_var_explained[0:nb_max-1]) #get the number of components satisfying the establised variance condition nb_component_features = np.where(cumsum_var_explained>variance)[0][0] acp_features = PCA(svd_solver='full',n_components =nb_component_features+1) X_new = acp_features.fit_transform(X) if to_plot: plt.figure(figsize=(10,5)) plt.plot(np.arange(1,nb_max),variances[0:nb_max-1]) plt.scatter(np.arange(1,nb_max),variances[0:nb_max-1]) plt.title("Variance explained by each component") plt.ylabel("Variance values") plt.xlabel("Component") #scree plot plt.figure(figsize=(15,10)) plt.subplot(221) plt.plot(np.arange(1,nb_max),eigval[0:nb_max-1]) plt.scatter(np.arange(1,nb_max),eigval[0:nb_max-1]) plt.title("Scree plot") plt.ylabel("Eigen values") plt.xlabel("Factor number") plt.subplot(222) plt.plot(np.arange(1,nb_max),cumsum_var_explained[0:nb_max-1]) plt.scatter(np.arange(1,nb_max),cumsum_var_explained[0:nb_max-1]) plt.title("Total Variance explained") plt.ylabel("Variance values") plt.xlabel("Factor number") return X_new def spatial_dist(ft,Nlat,Nlon,regname, minlat, maxlat, minlon, maxlon): """ Plot spatial distribution on the maps ft: feature train regnam: region name """ # extract latitude and longtitude lon = ft[:,1] lat = ft[:,0] # create a grid of coordinates approximating the true coordinates xlat = np.linspace(min(lat),max(lat),Nlat) xlon = np.linspace(min(lon),max(lon),Nlon) # number of profiles at each approximated coordinate Freq = np.zeros((xlat.shape[0],xlon.shape[0])) N = lon.shape[0] for k in range(N): i = np.argmin(abs(xlat - lat[k])) j = np.argmin(abs(xlon - lon[k])) Freq[i,j] += 1 # and plot ! figure(num=None, figsize=(10, 10), dpi=80, facecolor='w', edgecolor='k') map = Basemap(projection='merc', llcrnrlat=minlat, urcrnrlat=maxlat, llcrnrlon=minlon, urcrnrlon=maxlon, resolution='c') ax = plt.gca() plon, plat = map(xlon, xlat) xxlon,xxlat = meshgrid(plon,plat) map.scatter(xxlon, xxlat, c = Freq, marker = 's', cmap = "Blues") map.drawcoastlines() plt.title("Number of profiles in "+regname) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(cax=cax) plt.show() def temporal_dist(ft, regname): """ Plot temporal distribution on the maps ft: feature train regname: region name """ # encoded julian days encoded_juld = [julian.from_jd(round(x), fmt='mjd') for x in ft[:,2]] months = np.asarray([x.month for x in encoded_juld]) years = np.asarray([x.year + cnes_julian for x in encoded_juld]) years_ = np.linspace(min(years),max(years),max(years) - min(years) + 1, dtype = int) months_ = np.linspace(1,12,12, dtype = int) count_months = np.zeros(months_.shape[0], dtype = int) count_years = np.zeros(years_.shape[0]*months_.shape[0], dtype = int) for m in list(months_): count = size(np.where(months == m)) count_months[m-1] = count x_labels = ['Jan','Feb','Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] plt.figure(figsize=(9, 6)) plt.bar(x_labels,count_months); plt.title("Monthly Data Distribution in "+regname); plt.ylabel("Nb of profiles"); i = 0 for y in list(years_): for m in list(months_): count = size(np.where((years == y)*(months == m))) count_years[i] = count i = i + 1 u_year = np.unique(years_) spots = np.asarray([12*i for i in range(len(u_year))]) plt.figure(figsize=(12, 6)) plt.plot(count_years); plt.grid() plt.xticks(spots,u_year); plt.title('Monthly Data Distribution in '+regname); plt.ylabel('Nb of profiles'); def train_test_split(X,y,features,test_per): """ Split data into train and test sets """ mask = [i for i in range(len(X))] random.shuffle(mask) mask_test = mask[:int(len(X)*test_per)] mask_train = mask[int(len(X)*test_per):] x_train, x_test = X[mask_train,:], X[mask_test,:] y_train, y_test = y[mask_train,:], y[mask_test,:] feature_train, feature_test = features[mask_train,:], features[mask_test,:] sav_obj = open("x_train.pkl", 'wb') pickle.dump(x_train,sav_obj) sav_obj.close() sav_obj = open("x_test.pkl", 'wb') pickle.dump(x_test,sav_obj) sav_obj.close() sav_obj = open("y_train.pkl", 'wb') pickle.dump(y_train,sav_obj) sav_obj.close() sav_obj = open("y_test.pkl", 'wb') pickle.dump(y_test,sav_obj) sav_obj.close() sav_obj = open("feature_train.pkl", 'wb') pickle.dump(feature_train,sav_obj) sav_obj.close() sav_obj = open("feature_test.pkl", 'wb') pickle.dump(feature_test,sav_obj) sav_obj.close()
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.ylabel", "numpy.sin", "numpy.arange", "pandas.read_pickle", "numpy.where", "sklearn.decomposition.PCA", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.asarray", "numpy.linspace", "mpl_toolkits.axes_grid1.make_axes_locatable", "numpy....
[((813, 846), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (836, 846), False, 'import warnings\n'), ((2614, 2654), 'pandas.read_pickle', 'pd.read_pickle', (["(root + '\\\\data\\\\' + file)"], {}), "(root + '\\\\data\\\\' + file)\n", (2628, 2654), True, 'import pandas as pd\n'), ((2757, 2927), 'numpy.where', 'np.where', (["((gl_data['lat'] > coords['low_lat']) * (gl_data['lat'] < coords['up_lat']) *\n (gl_data['lon'] > coords['low_lon']) * (gl_data['lon'] < coords['up_lon']))"], {}), "((gl_data['lat'] > coords['low_lat']) * (gl_data['lat'] < coords[\n 'up_lat']) * (gl_data['lon'] > coords['low_lon']) * (gl_data['lon'] <\n coords['up_lon']))\n", (2765, 2927), True, 'import numpy as np\n'), ((3048, 3074), 'numpy.ones', 'np.ones', (['jul_days.shape[0]'], {}), '(jul_days.shape[0])\n', (3055, 3074), True, 'import numpy as np\n'), ((3131, 3165), 'numpy.sin', 'np.sin', (['(2 * math.pi * w * jul_days)'], {}), '(2 * math.pi * w * jul_days)\n', (3137, 3165), True, 'import numpy as np\n'), ((3175, 3209), 'numpy.cos', 'np.cos', (['(2 * math.pi * w * jul_days)'], {}), '(2 * math.pi * w * jul_days)\n', (3181, 3209), True, 'import numpy as np\n'), ((3284, 3299), 'numpy.sin', 'np.sin', (['lat_rad'], {}), '(lat_rad)\n', (3290, 3299), True, 'import numpy as np\n'), ((3382, 3397), 'numpy.sin', 'np.sin', (['lon_rad'], {}), '(lon_rad)\n', (3388, 3397), True, 'import numpy as np\n'), ((3412, 3427), 'numpy.cos', 'np.cos', (['lon_rad'], {}), '(lon_rad)\n', (3418, 3427), True, 'import numpy as np\n'), ((4387, 4439), 'numpy.unique', 'np.unique', (["region['profile_ids']"], {'return_counts': '(True)'}), "(region['profile_ids'], return_counts=True)\n", (4396, 4439), True, 'import numpy as np\n'), ((5533, 5562), 'pickle.dump', 'pickle.dump', (['X_train', 'sav_obj'], {}), '(X_train, sav_obj)\n', (5544, 5562), False, 'import pickle\n'), ((5615, 5644), 'pickle.dump', 'pickle.dump', (['y_train', 'sav_obj'], {}), '(y_train, sav_obj)\n', (5626, 5644), False, 'import pickle\n'), ((5703, 5740), 'pickle.dump', 'pickle.dump', (['o_feature_train', 'sav_obj'], {}), '(o_feature_train, sav_obj)\n', (5714, 5740), False, 'import pickle\n'), ((7810, 7838), 'pickle.dump', 'pickle.dump', (['coords', 'sav_obj'], {}), '(coords, sav_obj)\n', (7821, 7838), False, 'import pickle\n'), ((8423, 8445), 'sklearn.decomposition.PCA', 'PCA', ([], {'svd_solver': '"""full"""'}), "(svd_solver='full')\n", (8426, 8445), False, 'from sklearn.decomposition import PCA\n'), ((8744, 8764), 'numpy.cumsum', 'np.cumsum', (['variances'], {}), '(variances)\n', (8753, 8764), True, 'import numpy as np\n'), ((9004, 9066), 'sklearn.decomposition.PCA', 'PCA', ([], {'svd_solver': '"""full"""', 'n_components': '(nb_component_features + 1)'}), "(svd_solver='full', n_components=nb_component_features + 1)\n", (9007, 9066), False, 'from sklearn.decomposition import PCA\n'), ((10464, 10504), 'numpy.zeros', 'np.zeros', (['(xlat.shape[0], xlon.shape[0])'], {}), '((xlat.shape[0], xlon.shape[0]))\n', (10472, 10504), True, 'import numpy as np\n'), ((10763, 10882), 'mpl_toolkits.basemap.Basemap', 'Basemap', ([], {'projection': '"""merc"""', 'llcrnrlat': 'minlat', 'urcrnrlat': 'maxlat', 'llcrnrlon': 'minlon', 'urcrnrlon': 'maxlon', 'resolution': '"""c"""'}), "(projection='merc', llcrnrlat=minlat, urcrnrlat=maxlat, llcrnrlon=\n minlon, urcrnrlon=maxlon, resolution='c')\n", (10770, 10882), False, 'from mpl_toolkits.basemap import Basemap\n'), ((10887, 10896), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (10894, 10896), True, 'import matplotlib.pyplot as plt\n'), ((11067, 11112), 'matplotlib.pyplot.title', 'plt.title', (["('Number of profiles in ' + regname)"], {}), "('Number of profiles in ' + regname)\n", (11076, 11112), True, 'import matplotlib.pyplot as plt\n'), ((11125, 11148), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (11144, 11148), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((11213, 11234), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'cax': 'cax'}), '(cax=cax)\n', (11225, 11234), True, 'import matplotlib.pyplot as plt\n'), ((11239, 11249), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11247, 11249), True, 'import matplotlib.pyplot as plt\n'), ((11508, 11551), 'numpy.asarray', 'np.asarray', (['[x.month for x in encoded_juld]'], {}), '([x.month for x in encoded_juld])\n', (11518, 11551), True, 'import numpy as np\n'), ((11564, 11622), 'numpy.asarray', 'np.asarray', (['[(x.year + cnes_julian) for x in encoded_juld]'], {}), '([(x.year + cnes_julian) for x in encoded_juld])\n', (11574, 11622), True, 'import numpy as np\n'), ((11725, 11758), 'numpy.linspace', 'np.linspace', (['(1)', '(12)', '(12)'], {'dtype': 'int'}), '(1, 12, 12, dtype=int)\n', (11736, 11758), True, 'import numpy as np\n'), ((11779, 11816), 'numpy.zeros', 'np.zeros', (['months_.shape[0]'], {'dtype': 'int'}), '(months_.shape[0], dtype=int)\n', (11787, 11816), True, 'import numpy as np\n'), ((11837, 11892), 'numpy.zeros', 'np.zeros', (['(years_.shape[0] * months_.shape[0])'], {'dtype': 'int'}), '(years_.shape[0] * months_.shape[0], dtype=int)\n', (11845, 11892), True, 'import numpy as np\n'), ((12101, 12127), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 6)'}), '(figsize=(9, 6))\n', (12111, 12127), True, 'import matplotlib.pyplot as plt\n'), ((12132, 12163), 'matplotlib.pyplot.bar', 'plt.bar', (['x_labels', 'count_months'], {}), '(x_labels, count_months)\n', (12139, 12163), True, 'import matplotlib.pyplot as plt\n'), ((12168, 12220), 'matplotlib.pyplot.title', 'plt.title', (["('Monthly Data Distribution in ' + regname)"], {}), "('Monthly Data Distribution in ' + regname)\n", (12177, 12220), True, 'import matplotlib.pyplot as plt\n'), ((12224, 12252), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Nb of profiles"""'], {}), "('Nb of profiles')\n", (12234, 12252), True, 'import matplotlib.pyplot as plt\n'), ((12458, 12475), 'numpy.unique', 'np.unique', (['years_'], {}), '(years_)\n', (12467, 12475), True, 'import numpy as np\n'), ((12540, 12567), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (12550, 12567), True, 'import matplotlib.pyplot as plt\n'), ((12572, 12593), 'matplotlib.pyplot.plot', 'plt.plot', (['count_years'], {}), '(count_years)\n', (12580, 12593), True, 'import matplotlib.pyplot as plt\n'), ((12599, 12609), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (12607, 12609), True, 'import matplotlib.pyplot as plt\n'), ((12614, 12639), 'matplotlib.pyplot.xticks', 'plt.xticks', (['spots', 'u_year'], {}), '(spots, u_year)\n', (12624, 12639), True, 'import matplotlib.pyplot as plt\n'), ((12644, 12696), 'matplotlib.pyplot.title', 'plt.title', (["('Monthly Data Distribution in ' + regname)"], {}), "('Monthly Data Distribution in ' + regname)\n", (12653, 12696), True, 'import matplotlib.pyplot as plt\n'), ((12700, 12728), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Nb of profiles"""'], {}), "('Nb of profiles')\n", (12710, 12728), True, 'import matplotlib.pyplot as plt\n'), ((12878, 12898), 'random.shuffle', 'random.shuffle', (['mask'], {}), '(mask)\n', (12892, 12898), False, 'import random\n'), ((13223, 13252), 'pickle.dump', 'pickle.dump', (['x_train', 'sav_obj'], {}), '(x_train, sav_obj)\n', (13234, 13252), False, 'import pickle\n'), ((13316, 13344), 'pickle.dump', 'pickle.dump', (['x_test', 'sav_obj'], {}), '(x_test, sav_obj)\n', (13327, 13344), False, 'import pickle\n'), ((13409, 13438), 'pickle.dump', 'pickle.dump', (['y_train', 'sav_obj'], {}), '(y_train, sav_obj)\n', (13420, 13438), False, 'import pickle\n'), ((13502, 13530), 'pickle.dump', 'pickle.dump', (['y_test', 'sav_obj'], {}), '(y_test, sav_obj)\n', (13513, 13530), False, 'import pickle\n'), ((13601, 13636), 'pickle.dump', 'pickle.dump', (['feature_train', 'sav_obj'], {}), '(feature_train, sav_obj)\n', (13612, 13636), False, 'import pickle\n'), ((13706, 13740), 'pickle.dump', 'pickle.dump', (['feature_test', 'sav_obj'], {}), '(feature_test, sav_obj)\n', (13717, 13740), False, 'import pickle\n'), ((2547, 2569), 'os.path.join', 'os.path.join', (['""""""', '""".."""'], {}), "('', '..')\n", (2559, 2569), False, 'import os\n'), ((4820, 4844), 'numpy.random.shuffle', 'np.random.shuffle', (['index'], {}), '(index)\n', (4837, 4844), True, 'import numpy as np\n'), ((6226, 6266), 'pandas.read_pickle', 'pd.read_pickle', (["(root + '\\\\data\\\\' + file)"], {}), "(root + '\\\\data\\\\' + file)\n", (6240, 6266), True, 'import pandas as pd\n'), ((6385, 6555), 'numpy.where', 'np.where', (["((gl_data['lat'] > coords['low_lat']) * (gl_data['lat'] < coords['up_lat']) *\n (gl_data['lon'] > coords['low_lon']) * (gl_data['lon'] < coords['up_lon']))"], {}), "((gl_data['lat'] > coords['low_lat']) * (gl_data['lat'] < coords[\n 'up_lat']) * (gl_data['lon'] > coords['low_lon']) * (gl_data['lon'] <\n coords['up_lon']))\n", (6393, 6555), True, 'import numpy as np\n'), ((9127, 9154), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (9137, 9154), True, 'import matplotlib.pyplot as plt\n'), ((9279, 9328), 'matplotlib.pyplot.title', 'plt.title', (['"""Variance explained by each component"""'], {}), "('Variance explained by each component')\n", (9288, 9328), True, 'import matplotlib.pyplot as plt\n'), ((9335, 9364), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Variance values"""'], {}), "('Variance values')\n", (9345, 9364), True, 'import matplotlib.pyplot as plt\n'), ((9371, 9394), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Component"""'], {}), "('Component')\n", (9381, 9394), True, 'import matplotlib.pyplot as plt\n'), ((9420, 9448), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 10)'}), '(figsize=(15, 10))\n', (9430, 9448), True, 'import matplotlib.pyplot as plt\n'), ((9455, 9471), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(221)'], {}), '(221)\n', (9466, 9471), True, 'import matplotlib.pyplot as plt\n'), ((9591, 9614), 'matplotlib.pyplot.title', 'plt.title', (['"""Scree plot"""'], {}), "('Scree plot')\n", (9600, 9614), True, 'import matplotlib.pyplot as plt\n'), ((9621, 9647), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Eigen values"""'], {}), "('Eigen values')\n", (9631, 9647), True, 'import matplotlib.pyplot as plt\n'), ((9654, 9681), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Factor number"""'], {}), "('Factor number')\n", (9664, 9681), True, 'import matplotlib.pyplot as plt\n'), ((9689, 9705), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(222)'], {}), '(222)\n', (9700, 9705), True, 'import matplotlib.pyplot as plt\n'), ((9853, 9890), 'matplotlib.pyplot.title', 'plt.title', (['"""Total Variance explained"""'], {}), "('Total Variance explained')\n", (9862, 9890), True, 'import matplotlib.pyplot as plt\n'), ((9897, 9926), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Variance values"""'], {}), "('Variance values')\n", (9907, 9926), True, 'import matplotlib.pyplot as plt\n'), ((9933, 9960), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Factor number"""'], {}), "('Factor number')\n", (9943, 9960), True, 'import matplotlib.pyplot as plt\n'), ((4703, 4773), 'numpy.where', 'np.where', (["((region['profile_ids'] == uni) & (region['pres'] < pres_max))"], {}), "((region['profile_ids'] == uni) & (region['pres'] < pres_max))\n", (4711, 4773), True, 'import numpy as np\n'), ((6151, 6173), 'os.path.join', 'os.path.join', (['""""""', '""".."""'], {}), "('', '..')\n", (6163, 6173), False, 'import os\n'), ((7171, 7211), 'pandas.read_pickle', 'pd.read_pickle', (["(root + '\\\\data\\\\' + file)"], {}), "(root + '\\\\data\\\\' + file)\n", (7185, 7211), True, 'import pandas as pd\n'), ((7330, 7500), 'numpy.where', 'np.where', (["((gl_data['lat'] > coords['low_lat']) * (gl_data['lat'] < coords['up_lat']) *\n (gl_data['lon'] > coords['low_lon']) * (gl_data['lon'] < coords['up_lon']))"], {}), "((gl_data['lat'] > coords['low_lat']) * (gl_data['lat'] < coords[\n 'up_lat']) * (gl_data['lon'] > coords['low_lon']) * (gl_data['lon'] <\n coords['up_lon']))\n", (7338, 7500), True, 'import numpy as np\n'), ((8941, 8982), 'numpy.where', 'np.where', (['(cumsum_var_explained > variance)'], {}), '(cumsum_var_explained > variance)\n', (8949, 8982), True, 'import numpy as np\n'), ((9169, 9189), 'numpy.arange', 'np.arange', (['(1)', 'nb_max'], {}), '(1, nb_max)\n', (9178, 9189), True, 'import numpy as np\n'), ((9230, 9250), 'numpy.arange', 'np.arange', (['(1)', 'nb_max'], {}), '(1, nb_max)\n', (9239, 9250), True, 'import numpy as np\n'), ((9487, 9507), 'numpy.arange', 'np.arange', (['(1)', 'nb_max'], {}), '(1, nb_max)\n', (9496, 9507), True, 'import numpy as np\n'), ((9545, 9565), 'numpy.arange', 'np.arange', (['(1)', 'nb_max'], {}), '(1, nb_max)\n', (9554, 9565), True, 'import numpy as np\n'), ((9721, 9741), 'numpy.arange', 'np.arange', (['(1)', 'nb_max'], {}), '(1, nb_max)\n', (9730, 9741), True, 'import numpy as np\n'), ((9793, 9813), 'numpy.arange', 'np.arange', (['(1)', 'nb_max'], {}), '(1, nb_max)\n', (9802, 9813), True, 'import numpy as np\n'), ((11943, 11964), 'numpy.where', 'np.where', (['(months == m)'], {}), '(months == m)\n', (11951, 11964), True, 'import numpy as np\n'), ((4940, 4990), 'numpy.asarray', 'np.asarray', (['[[region[x][train]] for x in features]'], {}), '([[region[x][train]] for x in features])\n', (4950, 4990), True, 'import numpy as np\n'), ((5025, 5074), 'numpy.asarray', 'np.asarray', (['[[region[x][train]] for x in targets]'], {}), '([[region[x][train]] for x in targets])\n', (5035, 5074), True, 'import numpy as np\n'), ((5114, 5166), 'numpy.asarray', 'np.asarray', (['[[region[x][train]] for x in o_features]'], {}), '([[region[x][train]] for x in o_features])\n', (5124, 5166), True, 'import numpy as np\n'), ((7096, 7118), 'os.path.join', 'os.path.join', (['""""""', '""".."""'], {}), "('', '..')\n", (7108, 7118), False, 'import os\n'), ((12349, 12387), 'numpy.where', 'np.where', (['((years == y) * (months == m))'], {}), '((years == y) * (months == m))\n', (12357, 12387), True, 'import numpy as np\n')]
from abc import ABC, abstractmethod import numpy as np from .activations import NoActivation from .constants import EPSILON from .initializers import Constant from .optimizers import Momentum class Layer(ABC): @abstractmethod def init_weights(self, num_input, optimizer, initializer): pass @abstractmethod def feed_forward(self, input): pass @abstractmethod def back_prop(self, last_derivative, learning_rate): pass class BatchNorm(Layer): """ I don't know why batch norm does worse than normal layer Batch norm backprop https://kratzert.github.io/2016/02/12/understanding-the-gradient-flow-through-the-batch-normalization-layer.html """ def init_weights(self, num_output, optimizer, initializer): self._batch_norm_G = initializer(1, num_output) self._batch_norm_B = initializer(1, num_output) # init optimizer self._optimizer_G = optimizer.generate_optimizer((1, num_output)) self._optimizer_B = optimizer.generate_optimizer((1, num_output)) self._optimizer_mean = Momentum().generate_optimizer((1, num_output)) #optimizer.generate_optimizer((1, num_output)) def feed_forward(self, z): mean = np.mean(z, axis=0) mean = self._optimizer_mean.get_velocity(mean) self._diff_mean = z-mean variance = np.mean(np.square(self._diff_mean), axis=0) self._one_over_stddev = 1/np.sqrt(variance + EPSILON) self._z_norm = self._diff_mean * self._one_over_stddev self._output = self._batch_norm_G * self._z_norm + self._batch_norm_B return self._output def back_prop(self, last_derivative, learning_rate): dG = np.sum(self._z_norm * last_derivative, axis=0) dB = np.sum(last_derivative, axis=0) self._batch_norm_G -= learning_rate * self._optimizer_G.get_velocity(dG) self._batch_norm_B -= learning_rate * self._optimizer_G.get_velocity(dB) dz_norm = self._batch_norm_G * last_derivative # ---- d_z_minus_u_1 ---- d_z_minus_u_1 = self._one_over_stddev * dz_norm # ----------------------- d_stddev = -np.square(self._one_over_stddev) * \ np.sum(self._diff_mean * dz_norm, axis=0) d_variance = 0.5 * self._one_over_stddev * d_stddev d_z_minus_u_square = np.full( self._output.shape, 1/self._output.shape[0]) * d_variance # ---- d_z_minus_u_2 ---- d_z_minus_u_2 = 2 * self._diff_mean * d_z_minus_u_square # ----------------------- d_z_minus_u = d_z_minus_u_1 + d_z_minus_u_2 dz_1 = 1 * d_z_minus_u du = -np.sum(d_z_minus_u, axis=0) dz_2 = np.full(self._output.shape, 1/self._output.shape[0]) * du dz = dz_1 + dz_2 return dz class Dense(Layer): def __init__(self, num_output, Activation_function=None, is_batch_norm=False): self._num_output = num_output self._activation_function = Activation_function( ) if Activation_function is not None else NoActivation() self._is_batch_norm = is_batch_norm def init_weights(self, num_input, optimizer, initializer): # init weights self._weights = initializer(num_input, self._num_output) self._bias = initializer(1, self._num_output) # init optimizer self._optimizer_w = optimizer.generate_optimizer(self._weights.shape) self._optimizer_b = optimizer.generate_optimizer(self._bias.shape) # batch_norm if self._is_batch_norm: self.batch_norm = BatchNorm() self.batch_norm.init_weights(self._num_output, optimizer, initializer) def feed_forward(self, input): z = np.dot(input, self._weights) + self._bias if self._is_batch_norm: z = self.batch_norm.feed_forward(z) # output & save output = self._activation_function.feed_forward(z) self._input = input self._output = output return output def back_prop(self, last_derivative, learning_rate): dz = last_derivative * self._activation_function.back_prop() if self._is_batch_norm: dz = self.batch_norm.back_prop(dz, learning_rate) # Update weight # Be careful, it's not mean, it's sum dw = np.dot(self._input.T, dz) db = np.sum(dz, axis=0) # np.mean(dz) # ------------------------------------------------------ current_derivative = np.dot(dz, self._weights.T) self._weights -= learning_rate * self._optimizer_w.get_velocity(dw) self._bias -= learning_rate * self._optimizer_b.get_velocity(db) return current_derivative @property def num_output(self): return self._num_output
[ "numpy.mean", "numpy.sqrt", "numpy.square", "numpy.sum", "numpy.dot", "numpy.full" ]
[((1232, 1250), 'numpy.mean', 'np.mean', (['z'], {'axis': '(0)'}), '(z, axis=0)\n', (1239, 1250), True, 'import numpy as np\n'), ((1706, 1752), 'numpy.sum', 'np.sum', (['(self._z_norm * last_derivative)'], {'axis': '(0)'}), '(self._z_norm * last_derivative, axis=0)\n', (1712, 1752), True, 'import numpy as np\n'), ((1766, 1797), 'numpy.sum', 'np.sum', (['last_derivative'], {'axis': '(0)'}), '(last_derivative, axis=0)\n', (1772, 1797), True, 'import numpy as np\n'), ((4309, 4334), 'numpy.dot', 'np.dot', (['self._input.T', 'dz'], {}), '(self._input.T, dz)\n', (4315, 4334), True, 'import numpy as np\n'), ((4348, 4366), 'numpy.sum', 'np.sum', (['dz'], {'axis': '(0)'}), '(dz, axis=0)\n', (4354, 4366), True, 'import numpy as np\n'), ((4477, 4504), 'numpy.dot', 'np.dot', (['dz', 'self._weights.T'], {}), '(dz, self._weights.T)\n', (4483, 4504), True, 'import numpy as np\n'), ((1367, 1393), 'numpy.square', 'np.square', (['self._diff_mean'], {}), '(self._diff_mean)\n', (1376, 1393), True, 'import numpy as np\n'), ((1438, 1465), 'numpy.sqrt', 'np.sqrt', (['(variance + EPSILON)'], {}), '(variance + EPSILON)\n', (1445, 1465), True, 'import numpy as np\n'), ((2210, 2251), 'numpy.sum', 'np.sum', (['(self._diff_mean * dz_norm)'], {'axis': '(0)'}), '(self._diff_mean * dz_norm, axis=0)\n', (2216, 2251), True, 'import numpy as np\n'), ((2341, 2395), 'numpy.full', 'np.full', (['self._output.shape', '(1 / self._output.shape[0])'], {}), '(self._output.shape, 1 / self._output.shape[0])\n', (2348, 2395), True, 'import numpy as np\n'), ((2651, 2678), 'numpy.sum', 'np.sum', (['d_z_minus_u'], {'axis': '(0)'}), '(d_z_minus_u, axis=0)\n', (2657, 2678), True, 'import numpy as np\n'), ((2695, 2749), 'numpy.full', 'np.full', (['self._output.shape', '(1 / self._output.shape[0])'], {}), '(self._output.shape, 1 / self._output.shape[0])\n', (2702, 2749), True, 'import numpy as np\n'), ((3716, 3744), 'numpy.dot', 'np.dot', (['input', 'self._weights'], {}), '(input, self._weights)\n', (3722, 3744), True, 'import numpy as np\n'), ((2161, 2193), 'numpy.square', 'np.square', (['self._one_over_stddev'], {}), '(self._one_over_stddev)\n', (2170, 2193), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np class MultiHeadSelfAttention(tf.keras.layers.Layer): def __init__(self, emb_dim = 768, n_head = 12, out_dim = None, relative_window_size = None, dropout_rate = 0., kernel_initializer = tf.keras.initializers.RandomNormal(mean = 0, stddev = 0.01), **kwargs): #ScaledDotProductAttention super(MultiHeadSelfAttention, self).__init__(**kwargs) self.emb_dim = emb_dim self.n_head = n_head if emb_dim % n_head != 0: raise ValueError("Shoud be embedding dimension % number of heads = 0.") if out_dim is None: out_dim = self.emb_dim self.out_dim = out_dim if relative_window_size is not None and np.ndim(relative_window_size) == 0: relative_window_size = [relative_window_size, relative_window_size] self.relative_window_size = relative_window_size self.projection_dim = emb_dim // n_head self.dropout_rate = dropout_rate self.query = tf.keras.layers.Dense(emb_dim, kernel_initializer = kernel_initializer) self.key = tf.keras.layers.Dense(emb_dim, kernel_initializer = kernel_initializer) self.value = tf.keras.layers.Dense(emb_dim, kernel_initializer = kernel_initializer) self.combine = tf.keras.layers.Dense(out_dim, kernel_initializer = kernel_initializer) def build(self, input_shape): if self.relative_window_size is not None: self.relative_position_bias_table = self.add_weight("relative_position_bias_table", shape = [((2 * self.relative_window_size[0]) - 1) * ((2 * self.relative_window_size[1]) - 1), self.n_head], trainable = self.trainable) coords_h = np.arange(self.relative_window_size[0]) coords_w = np.arange(self.relative_window_size[1]) coords = np.stack(np.meshgrid(coords_h, coords_w, indexing = "ij")) #2, Wh, Ww coords = np.reshape(coords, [2, -1]) relative_coords = np.expand_dims(coords, axis = -1) - np.expand_dims(coords, axis = -2) #2, Wh * Ww, Wh * Ww relative_coords = np.transpose(relative_coords, [1, 2, 0]) #Wh * Ww, Wh * Ww, 2 relative_coords[:, :, 0] += self.relative_window_size[0] - 1 #shift to start from 0 relative_coords[:, :, 1] += self.relative_window_size[1] - 1 relative_coords[:, :, 0] *= 2 * self.relative_window_size[1] - 1 relative_position_index = np.sum(relative_coords, -1) self.relative_position_index = tf.Variable(tf.convert_to_tensor(relative_position_index), trainable = False, name= "relative_position_index") def attention(self, query, key, value, relative_position_bias = None): score = tf.matmul(query, key, transpose_b = True) n_key = tf.cast(tf.shape(key)[-1], tf.float32) scaled_score = score / tf.math.sqrt(n_key) if relative_position_bias is not None: scaled_score = scaled_score + relative_position_bias weight = tf.nn.softmax(scaled_score, axis = -1) if 0 < self.dropout_rate: weight = tf.nn.dropout(weight, self.dropout_rate) out = tf.matmul(weight, value) return out def separate_head(self, x): out = tf.keras.layers.Reshape([-1, self.n_head, self.projection_dim])(x) out = tf.keras.layers.Permute([2, 1, 3])(out) return out def call(self, inputs): query = self.query(inputs) key = self.key(inputs) value = self.value(inputs) query = self.separate_head(query) key = self.separate_head(key) value = self.separate_head(value) relative_position_bias = None if self.relative_window_size is not None: relative_position_bias = tf.gather(self.relative_position_bias_table, tf.reshape(self.relative_position_index, [-1])) relative_position_bias = tf.reshape(relative_position_bias, [self.relative_window_size[0] * self.relative_window_size[1], self.relative_window_size[0] * self.relative_window_size[1], -1]) #Wh * Ww,Wh * Ww, nH relative_position_bias = tf.transpose(relative_position_bias, [2, 0, 1]) #nH, Wh * Ww, Wh * Ww relative_position_bias = tf.expand_dims(relative_position_bias, axis = 0) attention = self.attention(query, key, value, relative_position_bias) attention = tf.keras.layers.Permute([2, 1, 3])(attention) attention = tf.keras.layers.Reshape([-1, self.emb_dim])(attention) out = self.combine(attention) return out def get_config(self): config = super(MultiHeadSelfAttention, self).get_config() config["emb_dim"] = self.emb_dim config["n_head"] = self.n_head config["out_dim"] = self.out_dim config["relative_window_size"] = self.relative_window_size config["projection_dim"] = self.projection_dim config["dropout_rate"] = self.dropout_rate return config class TransformerBlock(tf.keras.layers.Layer): def __init__(self, emb_dim = 768, n_head = 12, n_feature = 3072, dropout_rate = 0.1, **kwargs): super(TransformerBlock, self).__init__(**kwargs) self.emb_dim = emb_dim self.n_head = n_head self.n_feature = n_feature self.dropout_rate = dropout_rate self.attention = MultiHeadSelfAttention(emb_dim, n_head) self.feed_forward = [tf.keras.layers.Dense(n_feature, activation = tf.keras.activations.gelu), tf.keras.layers.Dense(emb_dim)] self.layer_norm = [tf.keras.layers.LayerNormalization(epsilon = 1e-6), tf.keras.layers.LayerNormalization(epsilon = 1e-6)] if 0 < dropout_rate: self.dropout = tf.keras.layers.Dropout(dropout_rate) def call(self, inputs): out = self.layer_norm[0](inputs) out = self.attention(out) if 0 < self.dropout_rate: out = self.dropout(out) att_out = self.layer_norm[1](inputs + out) out = self.feed_forward[0](att_out) if 0 < self.dropout_rate: out = self.dropout(out) out = self.feed_forward[1](out) if 0 < self.dropout_rate: out = self.dropout(out) return att_out + out def get_config(self): config = super(TransformerBlock, self).get_config() config["emb_dim"] = self.emb_dim config["n_head"] = self.n_head config["n_feature"] = self.n_feature config["dropout_rate"] = self.dropout_rate return config class VisionTransformer(tf.keras.layers.Layer): def __init__(self, n_class = 1000, include_top = True, patch_size = 16, distillation = False, emb_dim = 768, n_head = 12, n_feature = 3072, n_layer = 12, dropout_rate = 0.1, ori_input_shape = None, method = "bicubic", **kwargs): super(VisionTransformer, self).__init__(**kwargs) self.n_class = n_class self.include_top = include_top self.patch_size = patch_size if not isinstance(patch_size, int) else [patch_size, patch_size] self.distillation = distillation self.emb_dim = emb_dim self.n_head = n_head self.n_feature = n_feature self.n_layer = n_layer self.dropout_rate = dropout_rate self.ori_input_shape = ori_input_shape self.method = method self.patch_projection = tf.keras.layers.Dense(emb_dim) self.encoder = [TransformerBlock(emb_dim, n_head, n_feature, dropout_rate) for _ in range(n_layer)] if include_top: self.logits = tf.keras.layers.Dense(n_class, kernel_initializer = "zeros", name = "logits") if self.distillation: self.dist_logits = tf.keras.layers.Dense(n_class, kernel_initializer = "zeros", name = "kd_logits") def build(self, input_shape): n_patches = (input_shape[-3] // self.patch_size[0]) * (input_shape[-2] // self.patch_size[1]) pos_dim = n_patches + 1 self.class_emb = self.add_weight("class_embedding", shape = (1, 1, self.emb_dim), trainable = self.trainable) if self.distillation: pos_dim += 1 self.dist_emb = self.add_weight("kd_embedding", shape = (1, 1, self.emb_dim), trainable = self.trainable) if self.ori_input_shape is not None: ori_n_patches = (self.ori_input_shape[0] // self.patch_size[0]) * (self.ori_input_shape[1] // self.patch_size[1]) ori_pos_dim = ori_n_patches + 1 if self.distillation: ori_pos_dim += 1 self.pos_emb = self.add_weight("position_embedding", shape = (1, ori_pos_dim, self.emb_dim), trainable = self.trainable) self.pos_emb = self.resize_pos_embedding(self.pos_emb, pos_dim, self.distillation, self.method) else: self.pos_emb = self.add_weight("position_embedding", shape = (1, pos_dim, self.emb_dim), trainable = self.trainable) def extract_patches(self, images, patch_size): patches = tf.image.extract_patches(images = images, sizes = [1, patch_size[0], patch_size[1], 1], strides = [1, patch_size[0], patch_size[1], 1], rates = [1, 1, 1, 1], padding = "VALID") n_patch, patch_dim = tf.keras.backend.int_shape(patches)[-2:] patches = tf.keras.layers.Reshape([n_patch ** 2, patch_dim])(patches) return patches def resize_pos_embedding(self, pos_embedding, new_pos_dim, distillation = False, method = "bicubic"): pos_emb_token = pos_embedding[:, :1] pos_emb_grid = pos_embedding[:, 1:] new_pos_dim -= 1 if distillation: pos_emb_dist_token = pos_embedding[:, -1:] pos_emb_grid = pos_embedding[:, 1:-1] new_pos_dim -= 1 pos_dim, emb_dim = tf.keras.backend.int_shape(pos_emb_grid)[1:] n_patch = np.sqrt(pos_dim).astype(int) new_n_patch = np.sqrt(new_pos_dim).astype(int) pos_emb_grid = tf.reshape(pos_emb_grid, [1, n_patch, n_patch, emb_dim]) pos_emb_grid = tf.image.resize(pos_emb_grid, [new_n_patch, new_n_patch], method = method) pos_emb_grid = tf.reshape(pos_emb_grid, [1, new_n_patch **2, emb_dim]) pos_embedding = [pos_emb_token, pos_emb_grid] if distillation: pos_embedding.append(pos_emb_dist_token) pos_embedding = tf.concat(pos_embedding, axis = 1) return pos_embedding def call(self, inputs): out = self.extract_patches(inputs, self.patch_size) out = self.patch_projection(out) batch_size = tf.shape(inputs)[0] class_emb = tf.broadcast_to(self.class_emb, [batch_size, 1, self.emb_dim]) out = [class_emb, out] if self.distillation: dist_emb = tf.broadcast_to(self.dist_emb, [batch_size, 1, self.emb_dim]) out.append(dist_emb) out = tf.concat(out, axis = 1) out = out + self.pos_emb for encoder in self.encoder: out = encoder(out) if self.include_top: pre_logits = out[:, 0] #class token logits = self.logits(pre_logits) if self.distillation: pre_dist_logits = out[:, -1] #distillation token dist_logits = self.dist_logits(pre_dist_logits) out = [logits, dist_logits] else: out = logits return out def get_config(self): config = super(VisionTransformer, self).get_config() config["patch_size"] = self.patch_size config["distillation"] = self.distillation config["emb_dim"] = self.emb_dim config["n_head"] = self.n_head config["n_feature"] = self.n_feature config["n_layer"] = self.n_layer config["emb_dim"] = self.emb_dim config["dropout_rate"] = self.dropout_rate config["n_class"] = self.n_class config["include_top"] = self.include_top config["ori_input_shape"] = self.ori_input_shape config["method"] = self.method return config def train_model(input, logits, kd_logits = None, soft = True, alpha = 0.5, tau = 1.0): y_true = tf.keras.layers.Input(shape = (None,), name = "y_true", dtype = tf.float32) kd_true = None if kd_logits is not None: kd_true = tf.keras.layers.Input(shape = (None,), name = "kd_true", dtype = tf.float32) _y_true = tf.keras.layers.Lambda(lambda args: tf.cond(tf.equal(tf.shape(args[0])[-1], 1), true_fn = lambda: tf.one_hot(tf.cast(args[0], tf.int32), tf.shape(args[1])[-1])[:, 0], false_fn = lambda: args[0]))([y_true, logits]) _y_true = tf.cast(_y_true, logits.dtype) if kd_logits is not None: _kd_true = tf.keras.layers.Lambda(lambda args: tf.cond(tf.equal(tf.shape(args[0])[-1], 1), true_fn = lambda: tf.one_hot(tf.cast(args[0], tf.int32), tf.shape(args[1])[-1])[:, 0], false_fn = lambda: args[0]))([kd_true, kd_logits]) _kd_true = tf.cast(_kd_true, kd_logits.dtype) logits = tf.where(tf.equal(logits, 0), tf.keras.backend.epsilon(), logits) kd_logits = tf.where(tf.equal(kd_logits, 0), tf.keras.backend.epsilon(), kd_logits) accuracy = tf.keras.metrics.categorical_accuracy(_y_true, logits) loss = logits_loss = tf.keras.losses.categorical_crossentropy(_y_true, logits) if kd_logits is not None: if soft: kd_loss = tf.keras.losses.kl_divergence(tf.nn.softmax(_kd_true / tau), tf.nn.softmax(kd_logits / tau)) * (tau ** 2) else: kd_loss = tf.keras.losses.categorical_crossentropy(_kd_true, kd_logits) loss = (1 - alpha) * logits_loss + alpha * kd_loss model = tf.keras.Model([l for l in [input, y_true, kd_true] if l is not None], loss) model.add_metric(accuracy, name = "accuracy", aggregation = "mean") model.add_metric(loss, name = "loss", aggregation = "mean") model.add_loss(loss) return model def vit_small(include_top = True, weights = None, input_tensor = None, input_shape = None, classes = 1000, distillation = False): if input_tensor is None: img_input = tf.keras.layers.Input(shape = input_shape) else: if not tf.keras.backend.is_keras_tensor(input_tensor): img_input = tf.keras.layers.Input(tensor = input_tensor, shape = input_shape) else: img_input = input_tensor out = VisionTransformer(classes, include_top, patch_size = 16, distillation = distillation, emb_dim = 768, n_head = 8, n_feature = 2304, n_layer = 8, dropout_rate = 0.1, ori_input_shape = None, method = "bicubic")(img_input) model = tf.keras.Model(img_input, out) if weights is not None: model.load_weights(weights) return model def vit_base(include_top = True, weights = None, input_tensor = None, input_shape = None, classes = 1000, distillation = False): if input_tensor is None: img_input = tf.keras.layers.Input(shape = input_shape) else: if not tf.keras.backend.is_keras_tensor(input_tensor): img_input = tf.keras.layers.Input(tensor = input_tensor, shape = input_shape) else: img_input = input_tensor out = VisionTransformer(classes, include_top, patch_size = 16, distillation = distillation, emb_dim = 768, n_head = 12, n_feature = 3072, n_layer = 12, dropout_rate = 0.1, ori_input_shape = None, method = "bicubic")(img_input) model = tf.keras.Model(img_input, out) if weights is not None: model.load_weights(weights) return model def vit_large(include_top = True, weights = None, input_tensor = None, input_shape = None, classes = 1000, distillation = False): if input_tensor is None: img_input = tf.keras.layers.Input(shape = input_shape) else: if not tf.keras.backend.is_keras_tensor(input_tensor): img_input = tf.keras.layers.Input(tensor = input_tensor, shape = input_shape) else: img_input = input_tensor out = VisionTransformer(classes, include_top, patch_size = 16, distillation = distillation, emb_dim = 1024, n_head = 16, n_feature = 4096, n_layer = 24, dropout_rate = 0.1, ori_input_shape = None, method = "bicubic")(img_input) model = tf.keras.Model(img_input, out) if weights is not None: model.load_weights(weights) return model def vit_huge(include_top = True, weights = None, input_tensor = None, input_shape = None, classes = 1000, distillation = False): if input_tensor is None: img_input = tf.keras.layers.Input(shape = input_shape) else: if not tf.keras.backend.is_keras_tensor(input_tensor): img_input = tf.keras.layers.Input(tensor = input_tensor, shape = input_shape) else: img_input = input_tensor out = VisionTransformer(classes, include_top, patch_size = 16, distillation = distillation, emb_dim = 1280, n_head = 16, n_feature = 5120, n_layer = 32, dropout_rate = 0.1, ori_input_shape = None, method = "bicubic")(img_input) model = tf.keras.Model(img_input, out) if weights is not None: model.load_weights(weights) return model
[ "tensorflow.equal", "tensorflow.shape", "tensorflow.keras.backend.epsilon", "tensorflow.transpose", "numpy.sqrt", "tensorflow.keras.layers.Dense", "tensorflow.nn.dropout", "tensorflow.nn.softmax", "tensorflow.cast", "numpy.arange", "tensorflow.keras.layers.Input", "numpy.reshape", "tensorflo...
[((12137, 12206), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(None,)', 'name': '"""y_true"""', 'dtype': 'tf.float32'}), "(shape=(None,), name='y_true', dtype=tf.float32)\n", (12158, 12206), True, 'import tensorflow as tf\n'), ((12600, 12630), 'tensorflow.cast', 'tf.cast', (['_y_true', 'logits.dtype'], {}), '(_y_true, logits.dtype)\n', (12607, 12630), True, 'import tensorflow as tf\n'), ((13136, 13190), 'tensorflow.keras.metrics.categorical_accuracy', 'tf.keras.metrics.categorical_accuracy', (['_y_true', 'logits'], {}), '(_y_true, logits)\n', (13173, 13190), True, 'import tensorflow as tf\n'), ((13216, 13273), 'tensorflow.keras.losses.categorical_crossentropy', 'tf.keras.losses.categorical_crossentropy', (['_y_true', 'logits'], {}), '(_y_true, logits)\n', (13256, 13273), True, 'import tensorflow as tf\n'), ((13623, 13699), 'tensorflow.keras.Model', 'tf.keras.Model', (['[l for l in [input, y_true, kd_true] if l is not None]', 'loss'], {}), '([l for l in [input, y_true, kd_true] if l is not None], loss)\n', (13637, 13699), True, 'import tensorflow as tf\n'), ((14570, 14600), 'tensorflow.keras.Model', 'tf.keras.Model', (['img_input', 'out'], {}), '(img_input, out)\n', (14584, 14600), True, 'import tensorflow as tf\n'), ((15375, 15405), 'tensorflow.keras.Model', 'tf.keras.Model', (['img_input', 'out'], {}), '(img_input, out)\n', (15389, 15405), True, 'import tensorflow as tf\n'), ((16182, 16212), 'tensorflow.keras.Model', 'tf.keras.Model', (['img_input', 'out'], {}), '(img_input, out)\n', (16196, 16212), True, 'import tensorflow as tf\n'), ((16988, 17018), 'tensorflow.keras.Model', 'tf.keras.Model', (['img_input', 'out'], {}), '(img_input, out)\n', (17002, 17018), True, 'import tensorflow as tf\n'), ((233, 288), 'tensorflow.keras.initializers.RandomNormal', 'tf.keras.initializers.RandomNormal', ([], {'mean': '(0)', 'stddev': '(0.01)'}), '(mean=0, stddev=0.01)\n', (267, 288), True, 'import tensorflow as tf\n'), ((1006, 1075), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['emb_dim'], {'kernel_initializer': 'kernel_initializer'}), '(emb_dim, kernel_initializer=kernel_initializer)\n', (1027, 1075), True, 'import tensorflow as tf\n'), ((1097, 1166), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['emb_dim'], {'kernel_initializer': 'kernel_initializer'}), '(emb_dim, kernel_initializer=kernel_initializer)\n', (1118, 1166), True, 'import tensorflow as tf\n'), ((1190, 1259), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['emb_dim'], {'kernel_initializer': 'kernel_initializer'}), '(emb_dim, kernel_initializer=kernel_initializer)\n', (1211, 1259), True, 'import tensorflow as tf\n'), ((1285, 1354), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['out_dim'], {'kernel_initializer': 'kernel_initializer'}), '(out_dim, kernel_initializer=kernel_initializer)\n', (1306, 1354), True, 'import tensorflow as tf\n'), ((2727, 2766), 'tensorflow.matmul', 'tf.matmul', (['query', 'key'], {'transpose_b': '(True)'}), '(query, key, transpose_b=True)\n', (2736, 2766), True, 'import tensorflow as tf\n'), ((3004, 3040), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['scaled_score'], {'axis': '(-1)'}), '(scaled_score, axis=-1)\n', (3017, 3040), True, 'import tensorflow as tf\n'), ((3153, 3177), 'tensorflow.matmul', 'tf.matmul', (['weight', 'value'], {}), '(weight, value)\n', (3162, 3177), True, 'import tensorflow as tf\n'), ((7379, 7409), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['emb_dim'], {}), '(emb_dim)\n', (7400, 7409), True, 'import tensorflow as tf\n'), ((9006, 9182), 'tensorflow.image.extract_patches', 'tf.image.extract_patches', ([], {'images': 'images', 'sizes': '[1, patch_size[0], patch_size[1], 1]', 'strides': '[1, patch_size[0], patch_size[1], 1]', 'rates': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(images=images, sizes=[1, patch_size[0], patch_size\n [1], 1], strides=[1, patch_size[0], patch_size[1], 1], rates=[1, 1, 1, \n 1], padding='VALID')\n", (9030, 9182), True, 'import tensorflow as tf\n'), ((9937, 9993), 'tensorflow.reshape', 'tf.reshape', (['pos_emb_grid', '[1, n_patch, n_patch, emb_dim]'], {}), '(pos_emb_grid, [1, n_patch, n_patch, emb_dim])\n', (9947, 9993), True, 'import tensorflow as tf\n'), ((10017, 10089), 'tensorflow.image.resize', 'tf.image.resize', (['pos_emb_grid', '[new_n_patch, new_n_patch]'], {'method': 'method'}), '(pos_emb_grid, [new_n_patch, new_n_patch], method=method)\n', (10032, 10089), True, 'import tensorflow as tf\n'), ((10115, 10171), 'tensorflow.reshape', 'tf.reshape', (['pos_emb_grid', '[1, new_n_patch ** 2, emb_dim]'], {}), '(pos_emb_grid, [1, new_n_patch ** 2, emb_dim])\n', (10125, 10171), True, 'import tensorflow as tf\n'), ((10328, 10360), 'tensorflow.concat', 'tf.concat', (['pos_embedding'], {'axis': '(1)'}), '(pos_embedding, axis=1)\n', (10337, 10360), True, 'import tensorflow as tf\n'), ((10592, 10654), 'tensorflow.broadcast_to', 'tf.broadcast_to', (['self.class_emb', '[batch_size, 1, self.emb_dim]'], {}), '(self.class_emb, [batch_size, 1, self.emb_dim])\n', (10607, 10654), True, 'import tensorflow as tf\n'), ((10848, 10870), 'tensorflow.concat', 'tf.concat', (['out'], {'axis': '(1)'}), '(out, axis=1)\n', (10857, 10870), True, 'import tensorflow as tf\n'), ((12280, 12350), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '(None,)', 'name': '"""kd_true"""', 'dtype': 'tf.float32'}), "(shape=(None,), name='kd_true', dtype=tf.float32)\n", (12301, 12350), True, 'import tensorflow as tf\n'), ((12917, 12951), 'tensorflow.cast', 'tf.cast', (['_kd_true', 'kd_logits.dtype'], {}), '(_kd_true, kd_logits.dtype)\n', (12924, 12951), True, 'import tensorflow as tf\n'), ((12975, 12994), 'tensorflow.equal', 'tf.equal', (['logits', '(0)'], {}), '(logits, 0)\n', (12983, 12994), True, 'import tensorflow as tf\n'), ((12996, 13022), 'tensorflow.keras.backend.epsilon', 'tf.keras.backend.epsilon', ([], {}), '()\n', (13020, 13022), True, 'import tensorflow as tf\n'), ((13057, 13079), 'tensorflow.equal', 'tf.equal', (['kd_logits', '(0)'], {}), '(kd_logits, 0)\n', (13065, 13079), True, 'import tensorflow as tf\n'), ((13081, 13107), 'tensorflow.keras.backend.epsilon', 'tf.keras.backend.epsilon', ([], {}), '()\n', (13105, 13107), True, 'import tensorflow as tf\n'), ((14067, 14107), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (14088, 14107), True, 'import tensorflow as tf\n'), ((14870, 14910), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (14891, 14910), True, 'import tensorflow as tf\n'), ((15676, 15716), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (15697, 15716), True, 'import tensorflow as tf\n'), ((16482, 16522), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (16503, 16522), True, 'import tensorflow as tf\n'), ((1705, 1744), 'numpy.arange', 'np.arange', (['self.relative_window_size[0]'], {}), '(self.relative_window_size[0])\n', (1714, 1744), True, 'import numpy as np\n'), ((1768, 1807), 'numpy.arange', 'np.arange', (['self.relative_window_size[1]'], {}), '(self.relative_window_size[1])\n', (1777, 1807), True, 'import numpy as np\n'), ((1920, 1947), 'numpy.reshape', 'np.reshape', (['coords', '[2, -1]'], {}), '(coords, [2, -1])\n', (1930, 1947), True, 'import numpy as np\n'), ((2099, 2139), 'numpy.transpose', 'np.transpose', (['relative_coords', '[1, 2, 0]'], {}), '(relative_coords, [1, 2, 0])\n', (2111, 2139), True, 'import numpy as np\n'), ((2445, 2472), 'numpy.sum', 'np.sum', (['relative_coords', '(-1)'], {}), '(relative_coords, -1)\n', (2451, 2472), True, 'import numpy as np\n'), ((2855, 2874), 'tensorflow.math.sqrt', 'tf.math.sqrt', (['n_key'], {}), '(n_key)\n', (2867, 2874), True, 'import tensorflow as tf\n'), ((3098, 3138), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['weight', 'self.dropout_rate'], {}), '(weight, self.dropout_rate)\n', (3111, 3138), True, 'import tensorflow as tf\n'), ((3248, 3311), 'tensorflow.keras.layers.Reshape', 'tf.keras.layers.Reshape', (['[-1, self.n_head, self.projection_dim]'], {}), '([-1, self.n_head, self.projection_dim])\n', (3271, 3311), True, 'import tensorflow as tf\n'), ((3329, 3363), 'tensorflow.keras.layers.Permute', 'tf.keras.layers.Permute', (['[2, 1, 3]'], {}), '([2, 1, 3])\n', (3352, 3363), True, 'import tensorflow as tf\n'), ((3917, 4089), 'tensorflow.reshape', 'tf.reshape', (['relative_position_bias', '[self.relative_window_size[0] * self.relative_window_size[1], self.\n relative_window_size[0] * self.relative_window_size[1], -1]'], {}), '(relative_position_bias, [self.relative_window_size[0] * self.\n relative_window_size[1], self.relative_window_size[0] * self.\n relative_window_size[1], -1])\n', (3927, 4089), True, 'import tensorflow as tf\n'), ((4138, 4185), 'tensorflow.transpose', 'tf.transpose', (['relative_position_bias', '[2, 0, 1]'], {}), '(relative_position_bias, [2, 0, 1])\n', (4150, 4185), True, 'import tensorflow as tf\n'), ((4245, 4291), 'tensorflow.expand_dims', 'tf.expand_dims', (['relative_position_bias'], {'axis': '(0)'}), '(relative_position_bias, axis=0)\n', (4259, 4291), True, 'import tensorflow as tf\n'), ((4392, 4426), 'tensorflow.keras.layers.Permute', 'tf.keras.layers.Permute', (['[2, 1, 3]'], {}), '([2, 1, 3])\n', (4415, 4426), True, 'import tensorflow as tf\n'), ((4458, 4501), 'tensorflow.keras.layers.Reshape', 'tf.keras.layers.Reshape', (['[-1, self.emb_dim]'], {}), '([-1, self.emb_dim])\n', (4481, 4501), True, 'import tensorflow as tf\n'), ((5444, 5514), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['n_feature'], {'activation': 'tf.keras.activations.gelu'}), '(n_feature, activation=tf.keras.activations.gelu)\n', (5465, 5514), True, 'import tensorflow as tf\n'), ((5518, 5548), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['emb_dim'], {}), '(emb_dim)\n', (5539, 5548), True, 'import tensorflow as tf\n'), ((5577, 5626), 'tensorflow.keras.layers.LayerNormalization', 'tf.keras.layers.LayerNormalization', ([], {'epsilon': '(1e-06)'}), '(epsilon=1e-06)\n', (5611, 5626), True, 'import tensorflow as tf\n'), ((5629, 5678), 'tensorflow.keras.layers.LayerNormalization', 'tf.keras.layers.LayerNormalization', ([], {'epsilon': '(1e-06)'}), '(epsilon=1e-06)\n', (5663, 5678), True, 'import tensorflow as tf\n'), ((5737, 5774), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (['dropout_rate'], {}), '(dropout_rate)\n', (5760, 5774), True, 'import tensorflow as tf\n'), ((7568, 7641), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['n_class'], {'kernel_initializer': '"""zeros"""', 'name': '"""logits"""'}), "(n_class, kernel_initializer='zeros', name='logits')\n", (7589, 7641), True, 'import tensorflow as tf\n'), ((9212, 9247), 'tensorflow.keras.backend.int_shape', 'tf.keras.backend.int_shape', (['patches'], {}), '(patches)\n', (9238, 9247), True, 'import tensorflow as tf\n'), ((9271, 9321), 'tensorflow.keras.layers.Reshape', 'tf.keras.layers.Reshape', (['[n_patch ** 2, patch_dim]'], {}), '([n_patch ** 2, patch_dim])\n', (9294, 9321), True, 'import tensorflow as tf\n'), ((9766, 9806), 'tensorflow.keras.backend.int_shape', 'tf.keras.backend.int_shape', (['pos_emb_grid'], {}), '(pos_emb_grid)\n', (9792, 9806), True, 'import tensorflow as tf\n'), ((10552, 10568), 'tensorflow.shape', 'tf.shape', (['inputs'], {}), '(inputs)\n', (10560, 10568), True, 'import tensorflow as tf\n'), ((10739, 10800), 'tensorflow.broadcast_to', 'tf.broadcast_to', (['self.dist_emb', '[batch_size, 1, self.emb_dim]'], {}), '(self.dist_emb, [batch_size, 1, self.emb_dim])\n', (10754, 10800), True, 'import tensorflow as tf\n'), ((13485, 13546), 'tensorflow.keras.losses.categorical_crossentropy', 'tf.keras.losses.categorical_crossentropy', (['_kd_true', 'kd_logits'], {}), '(_kd_true, kd_logits)\n', (13525, 13546), True, 'import tensorflow as tf\n'), ((14135, 14181), 'tensorflow.keras.backend.is_keras_tensor', 'tf.keras.backend.is_keras_tensor', (['input_tensor'], {}), '(input_tensor)\n', (14167, 14181), True, 'import tensorflow as tf\n'), ((14207, 14268), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'tensor': 'input_tensor', 'shape': 'input_shape'}), '(tensor=input_tensor, shape=input_shape)\n', (14228, 14268), True, 'import tensorflow as tf\n'), ((14938, 14984), 'tensorflow.keras.backend.is_keras_tensor', 'tf.keras.backend.is_keras_tensor', (['input_tensor'], {}), '(input_tensor)\n', (14970, 14984), True, 'import tensorflow as tf\n'), ((15010, 15071), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'tensor': 'input_tensor', 'shape': 'input_shape'}), '(tensor=input_tensor, shape=input_shape)\n', (15031, 15071), True, 'import tensorflow as tf\n'), ((15744, 15790), 'tensorflow.keras.backend.is_keras_tensor', 'tf.keras.backend.is_keras_tensor', (['input_tensor'], {}), '(input_tensor)\n', (15776, 15790), True, 'import tensorflow as tf\n'), ((15816, 15877), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'tensor': 'input_tensor', 'shape': 'input_shape'}), '(tensor=input_tensor, shape=input_shape)\n', (15837, 15877), True, 'import tensorflow as tf\n'), ((16550, 16596), 'tensorflow.keras.backend.is_keras_tensor', 'tf.keras.backend.is_keras_tensor', (['input_tensor'], {}), '(input_tensor)\n', (16582, 16596), True, 'import tensorflow as tf\n'), ((16622, 16683), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'tensor': 'input_tensor', 'shape': 'input_shape'}), '(tensor=input_tensor, shape=input_shape)\n', (16643, 16683), True, 'import tensorflow as tf\n'), ((723, 752), 'numpy.ndim', 'np.ndim', (['relative_window_size'], {}), '(relative_window_size)\n', (730, 752), True, 'import numpy as np\n'), ((1838, 1884), 'numpy.meshgrid', 'np.meshgrid', (['coords_h', 'coords_w'], {'indexing': '"""ij"""'}), "(coords_h, coords_w, indexing='ij')\n", (1849, 1884), True, 'import numpy as np\n'), ((1978, 2009), 'numpy.expand_dims', 'np.expand_dims', (['coords'], {'axis': '(-1)'}), '(coords, axis=-1)\n', (1992, 2009), True, 'import numpy as np\n'), ((2014, 2045), 'numpy.expand_dims', 'np.expand_dims', (['coords'], {'axis': '(-2)'}), '(coords, axis=-2)\n', (2028, 2045), True, 'import numpy as np\n'), ((2528, 2573), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['relative_position_index'], {}), '(relative_position_index)\n', (2548, 2573), True, 'import tensorflow as tf\n'), ((2793, 2806), 'tensorflow.shape', 'tf.shape', (['key'], {}), '(key)\n', (2801, 2806), True, 'import tensorflow as tf\n'), ((3832, 3878), 'tensorflow.reshape', 'tf.reshape', (['self.relative_position_index', '[-1]'], {}), '(self.relative_position_index, [-1])\n', (3842, 3878), True, 'import tensorflow as tf\n'), ((7715, 7791), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['n_class'], {'kernel_initializer': '"""zeros"""', 'name': '"""kd_logits"""'}), "(n_class, kernel_initializer='zeros', name='kd_logits')\n", (7736, 7791), True, 'import tensorflow as tf\n'), ((9829, 9845), 'numpy.sqrt', 'np.sqrt', (['pos_dim'], {}), '(pos_dim)\n', (9836, 9845), True, 'import numpy as np\n'), ((9880, 9900), 'numpy.sqrt', 'np.sqrt', (['new_pos_dim'], {}), '(new_pos_dim)\n', (9887, 9900), True, 'import numpy as np\n'), ((13373, 13402), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(_kd_true / tau)'], {}), '(_kd_true / tau)\n', (13386, 13402), True, 'import tensorflow as tf\n'), ((13404, 13434), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(kd_logits / tau)'], {}), '(kd_logits / tau)\n', (13417, 13434), True, 'import tensorflow as tf\n'), ((12425, 12442), 'tensorflow.shape', 'tf.shape', (['args[0]'], {}), '(args[0])\n', (12433, 12442), True, 'import tensorflow as tf\n'), ((12733, 12750), 'tensorflow.shape', 'tf.shape', (['args[0]'], {}), '(args[0])\n', (12741, 12750), True, 'import tensorflow as tf\n'), ((12481, 12507), 'tensorflow.cast', 'tf.cast', (['args[0]', 'tf.int32'], {}), '(args[0], tf.int32)\n', (12488, 12507), True, 'import tensorflow as tf\n'), ((12509, 12526), 'tensorflow.shape', 'tf.shape', (['args[1]'], {}), '(args[1])\n', (12517, 12526), True, 'import tensorflow as tf\n'), ((12789, 12815), 'tensorflow.cast', 'tf.cast', (['args[0]', 'tf.int32'], {}), '(args[0], tf.int32)\n', (12796, 12815), True, 'import tensorflow as tf\n'), ((12817, 12834), 'tensorflow.shape', 'tf.shape', (['args[1]'], {}), '(args[1])\n', (12825, 12834), True, 'import tensorflow as tf\n')]
# -*- coding: utf-8 -*- import numpy as np import taft import shelve from network import Network from calcdata import CalcData import utils # Переменная для записи сообщений о ошибках logMessage = "" def getLastError(): global logMessage return logMessage # end of def getLastError() # Загружает веса сети из файла fileName. # Возвращает объект Network в случае успеха и None в случае ошибки. def loadNetwork( fileName ): ok = True try: s = shelve.open( fileName, flag='r' ) except Exception: ok = False if ok: try: weights = s['weights'] bs = s['bs'] activationFuncs = s['activationFuncs'] except Exception: ok = True finally: s.close() if ok: numLayers = len( weights ) - 1 numFeatures = np.shape(weights[0])[0] numNodes = [] for i in range( numLayers ): numNodes.append( np.shape( weights[i] )[1] ) numLabels = np.shape( weights[numLayers] )[1] network = Network( numLayers, numNodes, numFeatures, numLabels, activationFuncs=activationFuncs, weights=weights, bs=bs ) return network return None # end of loadNetwork() # Готовит данные для обучения и тестирования сети. def prepareData( fileWithRates=None, rates=None, normalize=True, detachTest=20, calcData=None, precalcData=None, oneHot=True ): global logMessage logMessage = "" retErr = None, None if fileWithRates is not None: rates = taft.readFinam( fileWithRates ) # Читаем котировки из файла finam if rates is None: logMessage += "Failed to read rates from finam file %s.\n" % (fileWithRates) if rates is None: logMessage += "No rates.\n" return retErr op = rates['op'] hi = rates['hi'] lo = rates['lo'] cl = rates['cl'] vol = rates['vol'] dtm = rates['dtm'] length = rates['length'] # If data precalculation is required if precalcData is not None: precalcData(rates) elif isinstance( calcData, CalcData ): if callable( calcData.precalcData ): calcData.precalcData( calcData, rates ) if calcData is None: # If None using the built in function calcDataFunc = __calcData elif isinstance( calcData, CalcData ): # If calcData is an object calcDataFunc = calcData.run elif callable( calcData ): # If calcData is a function calcDataFunc = calcData else: return retErr nnInputs = [] nnObserved = [] nnProfit = [] for i in range(length-1,0,-1): # Inputs pastRates = { 'op': op[i:], 'hi':hi[i:], 'lo':lo[i:], 'cl':cl[i:], 'vol':vol[i:], 'dtm':dtm[i:] } futureRates = { 'op': op[i-1::-1], 'hi':hi[i-1::-1], 'lo':lo[i-1::-1], 'cl':cl[i-1::-1], 'vol':vol[i-1::-1], 'dtm':dtm[i-1::-1] } res = calcDataFunc( pastRates, futureRates ) if isinstance( res, tuple ): # Если функция вернула tuple (как результат корректного завершени работы) inputs, observed, profit = res if inputs is None or observed is None: # Удостоверимся, что главные переменные - не None continue else: # Функция вернула не tuple - по соглашению это может быть только None, то есть "неудача" continue nnInputs.append( inputs ) nnObserved.append( observed ) nnProfit.append( profit ) if len(nnInputs) == 0: return retErr if len(nnObserved) == 0: return retErr if isinstance( nnObserved[0], float ) and isinstance( calcData, CalcData ): # Instead of labels single observed float values has been received. Labeling is required. if calcData.lookAheadScale is None: calcData.lookAheadScale = utils.createScale( nnObserved, calcData.numLabels ) nnLabels = [] for observedIndex in range( len(nnObserved) ): label = calcData.getLabelByScale( nnObserved[observedIndex] ) if oneHot: labels = np.zeros( shape=[calcData.numLabels], dtype=np.float32 ) labels[label] = 1 nnLabels.append( labels ) else: nnLabels.append(label) else: nnLabels = nnObserved nnInputs = np.array( nnInputs, dtype='float' ) numSamples, numFeatures = np.shape( nnInputs ) nnLabels = np.array( nnLabels, dtype='float' ) if oneHot: numLabels = np.shape( nnLabels )[1] else: numLabels = int( np.max( nnLabels ) + 1 ) nnProfit = np.array( nnProfit, dtype='float' ) nnMean = np.zeros( shape=[numFeatures], dtype='float' ) nnStd = np.zeros( shape=[numFeatures], dtype='float' ) if detachTest is not None: detachStart = int( float(numSamples) * detachTest / 100.0 ) if normalize: # Если нужна нормализация normIntervalStart = 0 if detachTest is not None: normIntervalStart = detachStart for i in range(numFeatures): status, mean, std = taft.normalize( nnInputs[:,i], normInterval=[normIntervalStart,numSamples] ) if status is None: logMessage += "Can't normalize %d column\n." % (i) return None nnMean[i] = mean nnStd[i] = std else: logMessage += "Normalization skipped.\n" nnMean = None nnStd = None if detachTest is None: retval1 = { 'inputs': nnInputs, 'labels': nnLabels, 'profit': nnProfit, 'numSamples':numSamples, 'numFeatures':numFeatures, 'numLabels':numLabels, 'mean':nnMean, 'std':nnStd } retval2 = None else: retval1 = { 'inputs': nnInputs[detachStart:], 'labels': nnLabels[detachStart:], 'profit': nnProfit[detachStart:], 'numSamples':numSamples-detachStart, 'numFeatures':numFeatures, 'numLabels':numLabels, 'mean':nnMean, 'std':nnStd } retval2 = { 'inputs': nnInputs[:detachStart], 'labels': nnLabels[:detachStart], 'profit': nnProfit[:detachStart], 'numSamples':detachStart, 'numFeatures':numFeatures, 'numLabels':numLabels, 'mean':nnMean, 'std':nnStd } return( retval1, retval2 ) # end of def prepareData __lookBack = None __lookAhead = None def setLookBack( lookBack ): global __lookBack __lookBack = lookBack def setLookAhead( lookAhead ): global __lookAhead __lookAhead = lookAhead def __calcData( pastRates, futureRates ): global __lookBack global __lookAhead retErr = None, None, None # Calculating inputs / Вычисляем "инпуты" if __lookBack is not None: # Какие временные отрезки "прошлого" мы будем пересчитывать в "инпуты" сети lookBack = __lookBack else: lookBack = [ [0,0], [1,1], [2,3], [4,6], [7,10] ] # По умолчанию inputs = [] cl0 = pastRates['cl'][0] # "Сейчас" мы в точке '0', последняя известная цена - цена закрытия lenRates = len( pastRates['cl'] ) for i in range( len( lookBack ) ): startRate = lookBack[i][0] endRate = lookBack[i][1] if endRate >= lenRates: # Если нужная нам точка лежит за пределами массива, "инпуты" подсчитать не удастся return retErr high = pastRates['hi'][startRate:endRate+1] # Массив со значениями HIGH на выбранном интервале прошлого highestHigh = np.max( high ) # Ищем максимальный HIGH inputs.append( highestHigh - cl0 ) # Добавляем "инпут" low = pastRates['lo'][startRate:endRate+1] # Массив со значениями LOW на выбранном интервале прошлого lowestLow = np.min( low ) # Ищем минимальный LOW inputs.append( cl0 - lowestLow ) # Добавляем "инпут" # Calculating labels and profits / Вычисляем "аутпуты" (labels) и ддоходность if __lookAhead is None: # На сколько периодов вперед надо смотреть ahead = 0 # По умолчанию смотрим вперед на один период, а значит нас интересует цена закрытия 0-го периода else: ahead = __lookAhead if ahead >= len(futureRates['cl']): # Если требуется смотреть за пределы массивов с котировками, расчет невозможен. return retErr # Вычисляем "аутпут" - отношение (CLOSE-OPEN) / (HIGH-LOW) на указанном (переменной ahead) отрезке "ближайшего будущего". # Каждое значения "аутпута" будет отнесено к одной из трех категорий и представлено в виде one-hot вектора длиной 3. # Маленькие значения будут кодироваться [1,0,0], средние - [0,1,0], большие - [0,0,1]. bins = 3 op = futureRates['op'][0] cl = futureRates['cl'][ahead] hi = np.max( futureRates['hi'][:ahead+1] ) lo = np.min( futureRates['lo'][:ahead+1] ) clLessOp = cl - op hiLessLo = hi - lo if hiLessLo > 0: observed = clLessOp / hiLessLo else: observed = 0.0 observedBin = int( float(bins) * ( (observed + 1.0) / (2.0 + 1e-10) ) ) labels = np.zeros( shape=[bins], dtype=np.float32 ) labels[observedBin] = 1.0 profit = clLessOp # Позиция будет открыта "сейчас" (futureRates['op'][0]) и закрыть ее через ahead периодов (futureRates['cl'][ahead]). # Доходность на этом отрезке составит CLOSE-OPEN (этого временного отрезка) return inputs, labels, profit # end of def __calcData def saveData( fileName, data, normOnly=False ): global logMessage ok = True logMessage += "Saving into \"%s\"...\n" % (fileName) try: s = shelve.open( fileName ) except Exception: ok = False if ok: try: if not normOnly: s['inputs'] = data['inputs'] s['labels'] = data['labels'] s['profit'] = data['profit'] s['mean'] = data['mean'] s['std'] = data['std'] except Exception: ok = False finally: s.close() return ok # end of saveData() def loadData( fileName, normOnly=False ): global logMessage ok = True logMessage += "Reading data from \"%s\"...\n" % (fileName) try: s = shelve.open( fileName ) except Exception: ok = False logMessage += "Can't open file %s.\n" % (fileName) if ok: try: if not normOnly: data['inputs'] = s['inputs'] data['labels'] = s['labels'] data['profit'] = s['profit'] data['mean'] = s['mean'] data['std'] = s['std'] s.close() except Exception: ok = False logMessage += "Error reading the data.\n" finally: s.close() if ok: return data else: return None # end of loadData()
[ "utils.createScale", "taft.normalize", "numpy.max", "network.Network", "numpy.array", "numpy.zeros", "shelve.open", "taft.readFinam", "numpy.min", "numpy.shape" ]
[((4293, 4326), 'numpy.array', 'np.array', (['nnInputs'], {'dtype': '"""float"""'}), "(nnInputs, dtype='float')\n", (4301, 4326), True, 'import numpy as np\n'), ((4359, 4377), 'numpy.shape', 'np.shape', (['nnInputs'], {}), '(nnInputs)\n', (4367, 4377), True, 'import numpy as np\n'), ((4395, 4428), 'numpy.array', 'np.array', (['nnLabels'], {'dtype': '"""float"""'}), "(nnLabels, dtype='float')\n", (4403, 4428), True, 'import numpy as np\n'), ((4572, 4605), 'numpy.array', 'np.array', (['nnProfit'], {'dtype': '"""float"""'}), "(nnProfit, dtype='float')\n", (4580, 4605), True, 'import numpy as np\n'), ((4627, 4671), 'numpy.zeros', 'np.zeros', ([], {'shape': '[numFeatures]', 'dtype': '"""float"""'}), "(shape=[numFeatures], dtype='float')\n", (4635, 4671), True, 'import numpy as np\n'), ((4686, 4730), 'numpy.zeros', 'np.zeros', ([], {'shape': '[numFeatures]', 'dtype': '"""float"""'}), "(shape=[numFeatures], dtype='float')\n", (4694, 4730), True, 'import numpy as np\n'), ((8569, 8606), 'numpy.max', 'np.max', (["futureRates['hi'][:ahead + 1]"], {}), "(futureRates['hi'][:ahead + 1])\n", (8575, 8606), True, 'import numpy as np\n'), ((8616, 8653), 'numpy.min', 'np.min', (["futureRates['lo'][:ahead + 1]"], {}), "(futureRates['lo'][:ahead + 1])\n", (8622, 8653), True, 'import numpy as np\n'), ((8882, 8922), 'numpy.zeros', 'np.zeros', ([], {'shape': '[bins]', 'dtype': 'np.float32'}), '(shape=[bins], dtype=np.float32)\n', (8890, 8922), True, 'import numpy as np\n'), ((474, 505), 'shelve.open', 'shelve.open', (['fileName'], {'flag': '"""r"""'}), "(fileName, flag='r')\n", (485, 505), False, 'import shelve\n'), ((1058, 1172), 'network.Network', 'Network', (['numLayers', 'numNodes', 'numFeatures', 'numLabels'], {'activationFuncs': 'activationFuncs', 'weights': 'weights', 'bs': 'bs'}), '(numLayers, numNodes, numFeatures, numLabels, activationFuncs=\n activationFuncs, weights=weights, bs=bs)\n', (1065, 1172), False, 'from network import Network\n'), ((1532, 1561), 'taft.readFinam', 'taft.readFinam', (['fileWithRates'], {}), '(fileWithRates)\n', (1546, 1561), False, 'import taft\n'), ((7361, 7373), 'numpy.max', 'np.max', (['high'], {}), '(high)\n', (7367, 7373), True, 'import numpy as np\n'), ((7595, 7606), 'numpy.min', 'np.min', (['low'], {}), '(low)\n', (7601, 7606), True, 'import numpy as np\n'), ((9426, 9447), 'shelve.open', 'shelve.open', (['fileName'], {}), '(fileName)\n', (9437, 9447), False, 'import shelve\n'), ((10040, 10061), 'shelve.open', 'shelve.open', (['fileName'], {}), '(fileName)\n', (10051, 10061), False, 'import shelve\n'), ((845, 865), 'numpy.shape', 'np.shape', (['weights[0]'], {}), '(weights[0])\n', (853, 865), True, 'import numpy as np\n'), ((1006, 1034), 'numpy.shape', 'np.shape', (['weights[numLayers]'], {}), '(weights[numLayers])\n', (1014, 1034), True, 'import numpy as np\n'), ((3796, 3845), 'utils.createScale', 'utils.createScale', (['nnObserved', 'calcData.numLabels'], {}), '(nnObserved, calcData.numLabels)\n', (3813, 3845), False, 'import utils\n'), ((4466, 4484), 'numpy.shape', 'np.shape', (['nnLabels'], {}), '(nnLabels)\n', (4474, 4484), True, 'import numpy as np\n'), ((5057, 5133), 'taft.normalize', 'taft.normalize', (['nnInputs[:, i]'], {'normInterval': '[normIntervalStart, numSamples]'}), '(nnInputs[:, i], normInterval=[normIntervalStart, numSamples])\n', (5071, 5133), False, 'import taft\n'), ((4047, 4101), 'numpy.zeros', 'np.zeros', ([], {'shape': '[calcData.numLabels]', 'dtype': 'np.float32'}), '(shape=[calcData.numLabels], dtype=np.float32)\n', (4055, 4101), True, 'import numpy as np\n'), ((4525, 4541), 'numpy.max', 'np.max', (['nnLabels'], {}), '(nnLabels)\n', (4531, 4541), True, 'import numpy as np\n'), ((958, 978), 'numpy.shape', 'np.shape', (['weights[i]'], {}), '(weights[i])\n', (966, 978), True, 'import numpy as np\n')]
from typing import Protocol import numpy as np class EmissionFunction(Protocol): def __call__( self, distance_to_shell: np.ndarray, observer_position: np.ndarray, earth_position: np.ndarray, unit_vectors: np.ndarray, freq: float, ) -> np.ndarray: """Interface of the `get_emission` function of a Zodiacal Component.""" def line_of_sight_integrate( radial_distances: np.ndarray, get_emission_func: EmissionFunction, observer_position: np.ndarray, earth_position: np.ndarray, unit_vectors: np.ndarray, freq: float, ) -> np.ndarray: """Returns the integrated Zodiacal emission for a component (Trapezoidal). Parameters ---------- radial_distances Array of discrete radial distances from the observer [AU]. get_emission_func The `get_emission` function of the component. observer_position The heliocentric ecliptic cartesian position of the observer. earth_position The heliocentric ecliptic cartesian position of the Earth. unit_vectors Heliocentric ecliptic cartesian unit vectors pointing to each position in space we that we consider. freq Frequency at which to evaluate to Zodiacal Emission. Returns ------- integrated_emission The line-of-sight integrated emission of the shells around an observer for a Zodiacal Component. """ emission_previous = get_emission_func( distance_to_shell=radial_distances[0], observer_position=observer_position, earth_position=earth_position, unit_vectors=unit_vectors, freq=freq, ) dR = np.diff(radial_distances) integrated_emission = np.zeros(unit_vectors.shape[-1]) for r, dr in zip(radial_distances, dR): emission_current = get_emission_func( distance_to_shell=r, observer_position=observer_position, earth_position=earth_position, unit_vectors=unit_vectors, freq=freq, ) integrated_emission += (emission_previous + emission_current) * dr / 2 emission_previous = emission_current return integrated_emission
[ "numpy.zeros", "numpy.diff" ]
[((1698, 1723), 'numpy.diff', 'np.diff', (['radial_distances'], {}), '(radial_distances)\n', (1705, 1723), True, 'import numpy as np\n'), ((1751, 1783), 'numpy.zeros', 'np.zeros', (['unit_vectors.shape[-1]'], {}), '(unit_vectors.shape[-1])\n', (1759, 1783), True, 'import numpy as np\n')]
""" Draw Figures - Chapter 4 This script generates all of the figures that appear in Chapter 4 of the textbook. Ported from MATLAB Code <NAME> 24 March 2021 """ import utils from utils.unit_conversions import lin_to_db, db_to_lin import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import numpy as np import scipy as sp from scipy import stats from scipy import fftpack import seaborn as sns import detector def make_all_figures(close_figs=False): """ Call all the figure generators for this chapter :close_figs: Boolean flag. If true, will close all figures after generating them; for batch scripting. Default=False :return: List of figure handles """ # Initializes colorSet - Mx3 RGB vector for successive plot lines colors = plt.get_cmap("tab10") # Reset the random number generator, to ensure reproducability rng = np.random.default_rng(0) # Find the output directory prefix = utils.init_output_dir('chapter4') # Activate seaborn for prettier plots sns.set() # Generate all figures fig1a = make_figure_1a(prefix) fig1b = make_figure_1b(prefix, rng) fig2a = make_figure_2a(prefix, rng) fig2b = make_figure_2b(prefix, rng) fig3 = make_figure_3(prefix) fig5 = make_figure_5(prefix, colors) fig6 = make_figure_6(prefix, rng, colors) fig7 = make_figure_7(prefix) fig8 = make_figure_8(prefix, colors) figs = [fig1a, fig1b, fig2a, fig2b, fig3, fig5, fig6, fig7, fig8] if close_figs: for fig in figs: plt.close(fig) return None else: plt.show() return figs def make_figure_1a(prefix=None): """ Figure 1a - Alternating Sine Waves Ported from MATLAB Code <NAME> 24 March 2021 :param prefix: output directory to place generated figure :return: figure handle """ # Sine wave num_points = 1024 # Sample points y_chip = np.exp(1j*(np.pi/2+2*np.pi*np.arange(num_points)/num_points)) # String together multiple periods code = np.array([0, 1, 1, 0, 1]) symbol = np.exp(1j*np.pi*code) y_full = np.ravel(np.expand_dims(y_chip, axis=0)*np.expand_dims(symbol, axis=1)) # x axis t_vec = np.arange(np.size(y_full)) fig1a = plt.figure() plt.plot(t_vec, np.real(y_full), color='k', linewidth=0.5) plt.plot(t_vec, np.zeros_like(t_vec), color='k', linewidth=0.5) for idx, bit in enumerate(code): plt.text(num_points/2 + num_points*idx-1, 1.5, '{}'.format(bit)) plt.plot(num_points*idx*np.array([1, 1]), np.array([-1, 2]), color='k', linestyle=':') # Annotation plt.annotate(s='', xy=(2*num_points, 1.1), xytext=(3*num_points, 1.1), arrowprops=dict(arrowstyle='<->')) plt.text(2.35*num_points, 1.25, r'$T_{chip}$') # Turn off the axes ax = plt.gca() ax.axis('off') # Save figure if prefix is not None: plt.savefig(prefix + 'fig1a.svg') plt.savefig(prefix + 'fig1a.png') return fig1a def make_figure_1b(prefix=None, rng=None): """ Figure 1b - Figure 1b, Bandwidth Ported from MATLAB Code <NAME> 24 March 2021 :param prefix: output directory to place generated figure :param rng: random number generator :return: figure handle """ if rng is None: rng = np.random.default_rng() num_samples = 16 # Number of samples per cycle num_code_bits = 128 # Length of transmit code in bits y_chip = np.exp(1j*(np.pi/2+2*np.pi*np.arange(num_samples)/num_samples)) num_code_samples = num_code_bits*num_samples lo = np.exp(1j*2*np.pi*np.arange(num_code_samples)*4/num_samples) # 4 samples/cycle num_monte_carlo = 100 spectral_average = np.zeros_like(lo) for ii in range(num_monte_carlo): # Generate a random code code = rng.integers(low=0, high=2, size=(num_code_bits, 1)) # with random integers, the interval is [low, high) symbol = np.exp(1j*np.pi*code) # Random starting phase starting_phase = np.exp(1j*rng.uniform(low=0, high=2*np.pi)) # Generate full transmit signal at the intermediate frequency (IF) of y_chip signal_if = np.ravel(starting_phase*symbol*y_chip) # Mix with the local oscillator (lo) to get the radio frequency (RF) sample signal_rf = signal_if*lo # Take the fourier transform spectral_average += np.absolute(sp.fft((np.real(signal_rf)))) # Normalize, and use an fftshift to put the center frequency in the middle of the vector spectral_average = fftpack.fftshift(spectral_average)/np.max(np.absolute(spectral_average)) fig1b = plt.figure() plt.plot(np.linspace(start=-1, stop=1, num=num_code_samples), 2*lin_to_db(np.absolute(spectral_average))) # Plot top and -3 dB lines plt.plot([-1, 1], [0, 0], color='k', linestyle=':') plt.plot([-1, 1], [-3, -3], color='k', linestyle=':') plt.plot([0, 0], [-20, 0], color='k', linestyle='-') plt.ylim([-40, 3]) # Create textbox plt.text(-.4, -1.5, '3 dB') plt.text(.3, 2, r'$f_0$') # Create doublearrows f0 = 0.625 # (normalized freq is 1/16 (y_chip) + 4/16 (lo)) bw = 0.125 plt.annotate(s='', xy=(0, 1), xytext=(0.64, 1), arrowprops=dict(arrowstyle='<->', color='k')) plt.annotate(s='', xy=(-.5, 0), xytext=(-.5, -3), arrowprops=dict(arrowstyle='<->', color='k')) plt.annotate(s='', xy=(f0-bw/2, -3), xytext=(f0+bw/2, -3), arrowprops=dict(arrowstyle='<->', color='k')) plt.annotate(s=r'$B_s=1/T_{\mathrm{chip}}$', xy=(f0, -3), xytext=(.1, -6), arrowprops=dict(arrowstyle='-', color='k')) # Turn off the axes ax = plt.gca() ax.axis('off') # Save figure if prefix is not None: plt.savefig(prefix + 'fig1b.svg') plt.savefig(prefix + 'fig1b.png') return fig1b def make_figure_2a(prefix=None, rng=None): """ Figure 2a - Chip Rate Ported from MATLAB Code <NAME> 24 March 2021 :param prefix: output directory to place generated figure :param rng: random number generator :return: figure handle """ if rng is None: rng = np.random.default_rng() # Generate the digital signals rate_data = 4 # bits/sec rate_chip = 16 # bits/sec num_code_bits = int(np.fix(rate_chip/rate_data)) num_data_bits = 4 num_full_bits = num_code_bits*num_data_bits data_bits = rng.integers(low=0, high=2, size=(1, num_data_bits)) code_bits = rng.integers(low=0, high=2, size=(num_code_bits, 1)) code_bits_full, data_bits_full = np.meshgrid(code_bits, data_bits) out_bits_full = np.logical_xor(data_bits_full, code_bits_full) out_bits_full = out_bits_full.astype(int) # Convert from bits to symbols data_symbols = np.reshape(np.exp(1j*np.pi*data_bits_full), newshape=(num_full_bits, 1)) code_symbols = np.reshape(np.exp(1j*np.pi*code_bits_full), newshape=(num_full_bits, 1)) out_symbols = np.reshape(np.exp(1j*np.pi*out_bits_full), newshape=(num_full_bits, 1)) # Generate the signals osf = 16 # Samples per cycle y = np.expand_dims(np.exp(1j*(np.pi/2+2*np.pi*np.arange(osf)/osf)), axis=0) # Construct the code signals y_data = np.ravel(y*data_symbols) y_code = np.ravel(y*code_symbols) y_dsss = np.ravel(y*out_symbols) fig2a = plt.figure() # Start with the Signals at the origin plt.plot(np.arange(num_full_bits*osf), np.real(y_data)+6, label='Data Signal') plt.plot(np.arange(num_code_bits*osf), np.real(y_code[0:num_code_bits*osf])+3, label='Spreading Code') plt.plot(np.arange(num_full_bits*osf), np.real(y_dsss), label='Encoded Signal') # Add the code and vertical lines for idx, bit in enumerate(np.ravel(out_bits_full)): plt.text(osf*idx+osf/2, 1.5, '{}'.format(bit)) plt.plot(osf*idx*np.array([1, 1]), [-1, 2], color='w', linestyle='-', linewidth=.5, label=None) for idx, bit in enumerate(np.ravel(code_bits)): plt.text(osf*idx+osf/2, 4.5, '{}'.format(bit)) plt.plot(osf*idx*np.array([1, 1]), [2, 5], color='w', linestyle='-', linewidth=.5, label=None) for idx, bit in enumerate(np.ravel(data_bits)): plt.text(osf*num_code_bits*idx+osf*num_code_bits/2, 7.5, '{}'.format(bit)) plt.plot(osf*num_code_bits*idx*np.array([1, 1]), [2, 8], color='w', linestyle='-', linewidth=.5, label=None) plt.grid('off') ax = plt.gca() ax.axis('off') plt.legend(loc='right') # Save figure if prefix is not None: plt.savefig(prefix + 'fig2a.svg') plt.savefig(prefix + 'fig2a.png') return fig2a def make_figure_2b(prefix=None, rng=None): """ Figure 2b - Spectrum Ported from MATLAB Code <NAME> 24 March 2021 :param prefix: output directory to place generated figure :param rng: random number generator :return: figure handle """ if rng is None: rng = np.random.default_rng(0) num_monte_carlo = 1000 num_bits_code1 = 16 num_bits_code2 = 64 samples_per_bit = 16 num_samples_full = samples_per_bit*max(num_bits_code1, num_bits_code2) # at least 16 samples per period chip_len_code1 = int(np.fix(num_samples_full/num_bits_code1)) chip_len_code2 = int(np.fix(num_samples_full/num_bits_code2)) # Generate the chips chip1 = np.exp(1j*(np.pi/2+2*np.pi*np.arange(chip_len_code1)/chip_len_code1)) chip2 = np.exp(1j*(np.pi/2+2*np.pi*np.arange(chip_len_code2)/chip_len_code2)) spectral_average1 = np.zeros(shape=(num_samples_full, )) spectral_average2 = np.zeros(shape=(num_samples_full, )) for jj in range(num_monte_carlo): # Generate new codes code1 = rng.integers(low=0, high=2, size=(num_bits_code1, )) code2 = rng.integers(low=0, high=2, size=(num_bits_code2, )) starting_phase1 = np.exp(1j*rng.uniform(low=0, high=2*np.pi)) starting_phase2 = np.exp(1j*rng.uniform(low=0, high=2*np.pi)) # Construct the full signals signal1 = np.zeros_like(spectral_average1, dtype=complex) for idx, bit in enumerate(code1): signal1[np.arange(chip_len_code1)+chip_len_code1*idx] = chip1*np.exp(1j*np.pi*bit)*starting_phase1 signal2 = np.zeros_like(spectral_average2, dtype=complex) for idx, bit in enumerate(code2): signal2[np.arange(chip_len_code2)+chip_len_code2*idx] = chip2*np.exp(1j*np.pi*bit)*starting_phase2 # Take the fourier transform spectral_average1 += np.absolute(sp.fft(signal1)) spectral_average2 += np.absolute(sp.fft(signal2)) # Normalize the spectra and use an fftshift to move the center frequency to the middle spectral_average1 = fftpack.fftshift(spectral_average1)/np.amax(spectral_average1, axis=None) spectral_average2 = fftpack.fftshift(spectral_average2)/np.amax(spectral_average2, axis=None) # Shift to account for central frequency of chip waveform spectral_average1 = np.roll(spectral_average1, -num_bits_code1) spectral_average2 = np.roll(spectral_average2, -num_bits_code2) # Plot fig2b = plt.figure() t_vec = np.linspace(start=0, stop=1, num=num_samples_full) plt.plot(t_vec, lin_to_db(spectral_average1), label='Data Signal') plt.plot(t_vec, lin_to_db(spectral_average2), label='Encoded Signal') plt.ylim([-20, 2]) plt.xlim([.25, .75]) plt.legend(loc='upper right') # Plot top and -3 dB lines plt.plot([0, 1], [-3, -3], color='k', linestyle=':', label=None) plt.text(.3, -2.5, '-3 dB') plt.text(.55, -2.25, r'$B_s = 1/T_{chip}$') plt.text(.55, -4.5, r'$B_d = 1/T_{sym}$') # Annotation plt.annotate(s='', xy=(.5-.7/num_bits_code1, -2.5), xytext=(.5+.7/num_bits_code1, -2.5), arrowprops=dict(arrowstyle='<->', color='k')) plt.annotate(s='', xy=(.5-.7/num_bits_code2, -3.5), xytext=(.5+.7/num_bits_code2, -3.5), arrowprops=dict(arrowstyle='<->', color='k')) # Save figure if prefix is not None: plt.savefig(prefix + 'fig2b.svg') plt.savefig(prefix + 'fig2b.png') return fig2b def make_figure_3(prefix=None): """ Figure 3, Spreading of SNR Ported from MATLAB Code <NAME> 24 March 2021 :param prefix: output directory to place generated figure :return: figure handle """ snr_ref_db = 0 bw_ref = 1e6 bw = np.logspace(start=3, stop=9, num=10) loss_spreading = lin_to_db(bw / bw_ref) snr_o_db = snr_ref_db - loss_spreading fig3 = plt.figure() plt.semilogx(bw, snr_o_db) plt.xlabel(r'$B_s$ [Hz]') plt.ylabel(r'$\xi$ [dB]') # Save figure if prefix is not None: plt.savefig(prefix + 'fig3.svg') plt.savefig(prefix + 'fig3.png') return fig3 def make_figure_5(prefix=None, colors=None): """ Figures 5, Cross-Correlator SNR Ported from MATLAB Code <NAME> 24 March 2021 :param prefix: output directory to place generated figure :param colors: colormap for plotting :return: figure handle """ if colors is None: colors = plt.get_cmap('tab10') # SNR axis snr_i_db = np.arange(start=-30, stop=30.1, step=.1) snr_i_lin = np.expand_dims(db_to_lin(snr_i_db), axis=1) pulse_duration = 1e-6 bandwidth = np.logspace(start=6, stop=9, num=4) tbwp_lin = pulse_duration*bandwidth tbwp_db = lin_to_db(tbwp_lin) snr_o_lin = np.expand_dims(tbwp_lin, axis=0)*snr_i_lin**2/(1+2*snr_i_lin) snr_o_db = lin_to_db(snr_o_lin) snr_o_ideal = np.expand_dims(snr_i_db, axis=1) + np.expand_dims(tbwp_db, axis=0) fig5 = plt.figure() for idx, tbwp in enumerate(tbwp_lin): plt.plot(snr_i_db, snr_o_db[:, idx], color=colors(idx), label='TB={:.0f}'.format(tbwp)) plt.plot(snr_i_db, snr_o_ideal[:, idx], color=colors(idx), linestyle='-.', label=None) plt.legend(loc='upper left') plt.xlabel(r'$\xi_i$ [dB]') plt.ylabel(r'$\xi_o$ [dB]') # Save figure if prefix is not None: plt.savefig(prefix + 'fig5.svg') plt.savefig(prefix + 'fig5.png') return fig5 def make_figure_6(prefix=None, rng=None, colors=None): """ Figures 6, Comparison of Performance Ported from MATLAB Code <NAME> 24 March 2021 :param prefix: output directory to place generated figure :param rng: random number generator :param colors: colormap for plotting :return: figure handle """ # Vary Time-Bandwidth Product tbwp_vec_db = np.arange(start=10., stop=31., step=10., dtype=int) tbwp_vec_lin = np.expand_dims(db_to_lin(tbwp_vec_db), axis=0).astype(int) input_snr_vec_db = np.arange(start=-20, stop=10.1, step=0.1) input_snr_vec_lin = np.expand_dims(db_to_lin(input_snr_vec_db), axis=1) output_snr_vec_lin = tbwp_vec_lin*input_snr_vec_lin**2/(1+2*input_snr_vec_lin) # output_snr_vec_db = lin_to_db(output_snr_vec_lin) # Energy Detector Performance prob_fa = 1e-6 threshold_ed = stats.chi2.ppf(q=1-prob_fa, df=2*tbwp_vec_lin) prob_det_ed = stats.ncx2.sf(x=threshold_ed, df=2*tbwp_vec_lin, nc=2*tbwp_vec_lin*input_snr_vec_lin) # Cross-Correlator Performance threshold_xc = stats.chi2.ppf(q=1-prob_fa, df=2) prob_det_xc = stats.ncx2.sf(x=threshold_xc/(1+2*input_snr_vec_lin), df=2, nc=2*output_snr_vec_lin) # Monte Carlo Trials input_snr_vec_coarse_db = input_snr_vec_db[::10] input_snr_vec_coarse_lin = db_to_lin(input_snr_vec_coarse_db) num_monte_carlo = int(1e4) num_tbwp = int(tbwp_vec_lin.size) num_snr = int(input_snr_vec_coarse_lin.size) # Generate noise vectors noise_pwr = 1 # Unit Variance prob_det_ed_mc = np.zeros(shape=(num_snr, num_tbwp)) prob_det_xc_mc = np.zeros(shape=(num_snr, num_tbwp)) for idx_tbwp, tbwp in enumerate(np.ravel(tbwp_vec_lin)): # Generate the noise vectors noise1 = np.sqrt(noise_pwr/2)*(rng.standard_normal(size=(tbwp, num_monte_carlo)) + 1j*rng.standard_normal(size=(tbwp, num_monte_carlo))) noise2 = np.sqrt(noise_pwr/2)*(rng.standard_normal(size=(tbwp, num_monte_carlo)) + 1j*rng.standard_normal(size=(tbwp, num_monte_carlo))) # Generate a signal vector signal = np.sqrt(1/2)*(rng.standard_normal(size=(tbwp, num_monte_carlo)) + 1j*rng.standard_normal(size=(tbwp, num_monte_carlo))) phase_difference = np.exp(1j*rng.uniform(low=0, high=2*np.pi, size=(1, num_monte_carlo))) for idx_snr, snr in enumerate(input_snr_vec_coarse_lin): # Scale the signal power to match SNR this_signal = signal * np.sqrt(snr) y1 = this_signal+noise1 y2 = this_signal*phase_difference+noise2 det_result_ed = detector.squareLaw.det_test(z=y1, noise_var=noise_pwr/2, prob_fa=prob_fa) prob_det_ed_mc[idx_snr, idx_tbwp] = np.sum(det_result_ed, axis=None)/num_monte_carlo det_result_xc = detector.xcorr.det_test(y1=y1, y2=y2, noise_var=noise_pwr, num_samples=tbwp, prob_fa=prob_fa) prob_det_xc_mc[idx_snr, idx_tbwp] = np.sum(det_result_xc, axis=None)/num_monte_carlo fig6 = plt.figure() for idx, tbwp in enumerate(tbwp_vec_lin[0, :]): if idx == 0: ed_label = 'ED' xc_label = 'XC' ed_mc_label = 'ED (Monte Carlo)' xc_mc_label = 'XC (Monte Carlo)' else: ed_label = None xc_label = None ed_mc_label = None xc_mc_label = None plt.plot(input_snr_vec_db, prob_det_ed[:, idx], color=colors(idx), linestyle='-', label=ed_label) plt.plot(input_snr_vec_db, prob_det_xc[:, idx], color=colors(idx), linestyle='--', label=xc_label) plt.scatter(input_snr_vec_coarse_db, prob_det_ed_mc[:, idx], color=colors(idx), marker='^', label=ed_mc_label) plt.scatter(input_snr_vec_coarse_db, prob_det_xc_mc[:, idx], color=colors(idx), marker='x', label=xc_mc_label) plt.legend(loc='lower right') # Create ellipses ax = plt.gca() ell = Ellipse(xy=(2, .4), width=5, height=.05) ell.set_fill(False) ell.set_edgecolor(colors(0)) ax.add_artist(ell) plt.annotate(s='TB=10', xy=(-.5, .4), xytext=(-16, .3), arrowprops=dict(arrowstyle='-', color=colors(0))) ell = Ellipse(xy=(-3.5, .5), width=3, height=.05) ell.set_fill(False) ell.set_edgecolor(colors(1)) ax.add_artist(ell) plt.annotate(s='TB=100', xy=(-5, .5), xytext=(-16, .5), arrowprops=dict(arrowstyle='-', color=colors(1))) ell = Ellipse(xy=(-8.5, .6), width=3, height=.05) ell.set_fill(False) ell.set_edgecolor(colors(2)) ax.add_artist(ell) plt.annotate(s='TB=1,000', xy=(-10, .6), xytext=(-16, .7), arrowprops=dict(arrowstyle='-', color=colors(2))) # Save figure if prefix is not None: plt.savefig(prefix + 'fig6.svg') plt.savefig(prefix + 'fig6.png') return fig6 def make_figure_7(prefix=None): """ Figure 7, Example 4.1 Monte Carlo results Ported from MATLAB Code <NAME> 24 March 2021 :param prefix: output directory to place generated figure :return: figure handle """ from examples import chapter4 fig7 = chapter4.example1() # Save figure if prefix is not None: plt.savefig(prefix + 'fig7.svg') plt.savefig(prefix + 'fig7.png') return fig7 def make_figure_8(prefix=None, colors=None): """ Figure 8, Example 4.2 Monte Carlo results Ported from MATLAB Code <NAME> 24 March 2021 :param prefix: output directory to place generated figure :param colors: colormap for plotting :return: figure handle """ from examples import chapter4 fig8 = chapter4.example2(colors) # Save figure if prefix is not None: plt.savefig(prefix + 'fig8.svg') plt.savefig(prefix + 'fig8.png') return fig8
[ "matplotlib.pyplot.grid", "numpy.sqrt", "numpy.random.default_rng", "examples.chapter4.example2", "matplotlib.pyplot.ylabel", "numpy.array", "utils.unit_conversions.lin_to_db", "scipy.stats.chi2.ppf", "detector.xcorr.det_test", "numpy.arange", "seaborn.set", "detector.squareLaw.det_test", "s...
[((801, 822), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""tab10"""'], {}), "('tab10')\n", (813, 822), True, 'import matplotlib.pyplot as plt\n'), ((901, 925), 'numpy.random.default_rng', 'np.random.default_rng', (['(0)'], {}), '(0)\n', (922, 925), True, 'import numpy as np\n'), ((972, 1005), 'utils.init_output_dir', 'utils.init_output_dir', (['"""chapter4"""'], {}), "('chapter4')\n", (993, 1005), False, 'import utils\n'), ((1053, 1062), 'seaborn.set', 'sns.set', ([], {}), '()\n', (1060, 1062), True, 'import seaborn as sns\n'), ((2079, 2104), 'numpy.array', 'np.array', (['[0, 1, 1, 0, 1]'], {}), '([0, 1, 1, 0, 1])\n', (2087, 2104), True, 'import numpy as np\n'), ((2118, 2145), 'numpy.exp', 'np.exp', (['(1.0j * np.pi * code)'], {}), '(1.0j * np.pi * code)\n', (2124, 2145), True, 'import numpy as np\n'), ((2291, 2303), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2301, 2303), True, 'import matplotlib.pyplot as plt\n'), ((2773, 2820), 'matplotlib.pyplot.text', 'plt.text', (['(2.35 * num_points)', '(1.25)', '"""$T_{chip}$"""'], {}), "(2.35 * num_points, 1.25, '$T_{chip}$')\n", (2781, 2820), True, 'import matplotlib.pyplot as plt\n'), ((2854, 2863), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2861, 2863), True, 'import matplotlib.pyplot as plt\n'), ((3759, 3776), 'numpy.zeros_like', 'np.zeros_like', (['lo'], {}), '(lo)\n', (3772, 3776), True, 'import numpy as np\n'), ((4692, 4704), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4702, 4704), True, 'import matplotlib.pyplot as plt\n'), ((4864, 4915), 'matplotlib.pyplot.plot', 'plt.plot', (['[-1, 1]', '[0, 0]'], {'color': '"""k"""', 'linestyle': '""":"""'}), "([-1, 1], [0, 0], color='k', linestyle=':')\n", (4872, 4915), True, 'import matplotlib.pyplot as plt\n'), ((4920, 4973), 'matplotlib.pyplot.plot', 'plt.plot', (['[-1, 1]', '[-3, -3]'], {'color': '"""k"""', 'linestyle': '""":"""'}), "([-1, 1], [-3, -3], color='k', linestyle=':')\n", (4928, 4973), True, 'import matplotlib.pyplot as plt\n'), ((4978, 5030), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 0]', '[-20, 0]'], {'color': '"""k"""', 'linestyle': '"""-"""'}), "([0, 0], [-20, 0], color='k', linestyle='-')\n", (4986, 5030), True, 'import matplotlib.pyplot as plt\n'), ((5035, 5053), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-40, 3]'], {}), '([-40, 3])\n', (5043, 5053), True, 'import matplotlib.pyplot as plt\n'), ((5084, 5112), 'matplotlib.pyplot.text', 'plt.text', (['(-0.4)', '(-1.5)', '"""3 dB"""'], {}), "(-0.4, -1.5, '3 dB')\n", (5092, 5112), True, 'import matplotlib.pyplot as plt\n'), ((5116, 5141), 'matplotlib.pyplot.text', 'plt.text', (['(0.3)', '(2)', '"""$f_0$"""'], {}), "(0.3, 2, '$f_0$')\n", (5124, 5141), True, 'import matplotlib.pyplot as plt\n'), ((5812, 5821), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5819, 5821), True, 'import matplotlib.pyplot as plt\n'), ((6722, 6755), 'numpy.meshgrid', 'np.meshgrid', (['code_bits', 'data_bits'], {}), '(code_bits, data_bits)\n', (6733, 6755), True, 'import numpy as np\n'), ((6776, 6822), 'numpy.logical_xor', 'np.logical_xor', (['data_bits_full', 'code_bits_full'], {}), '(data_bits_full, code_bits_full)\n', (6790, 6822), True, 'import numpy as np\n'), ((7368, 7394), 'numpy.ravel', 'np.ravel', (['(y * data_symbols)'], {}), '(y * data_symbols)\n', (7376, 7394), True, 'import numpy as np\n'), ((7406, 7432), 'numpy.ravel', 'np.ravel', (['(y * code_symbols)'], {}), '(y * code_symbols)\n', (7414, 7432), True, 'import numpy as np\n'), ((7444, 7469), 'numpy.ravel', 'np.ravel', (['(y * out_symbols)'], {}), '(y * out_symbols)\n', (7452, 7469), True, 'import numpy as np\n'), ((7481, 7493), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (7491, 7493), True, 'import matplotlib.pyplot as plt\n'), ((8534, 8549), 'matplotlib.pyplot.grid', 'plt.grid', (['"""off"""'], {}), "('off')\n", (8542, 8549), True, 'import matplotlib.pyplot as plt\n'), ((8559, 8568), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (8566, 8568), True, 'import matplotlib.pyplot as plt\n'), ((8593, 8616), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""right"""'}), "(loc='right')\n", (8603, 8616), True, 'import matplotlib.pyplot as plt\n'), ((9658, 9693), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_samples_full,)'}), '(shape=(num_samples_full,))\n', (9666, 9693), True, 'import numpy as np\n'), ((9719, 9754), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_samples_full,)'}), '(shape=(num_samples_full,))\n', (9727, 9754), True, 'import numpy as np\n'), ((11109, 11152), 'numpy.roll', 'np.roll', (['spectral_average1', '(-num_bits_code1)'], {}), '(spectral_average1, -num_bits_code1)\n', (11116, 11152), True, 'import numpy as np\n'), ((11177, 11220), 'numpy.roll', 'np.roll', (['spectral_average2', '(-num_bits_code2)'], {}), '(spectral_average2, -num_bits_code2)\n', (11184, 11220), True, 'import numpy as np\n'), ((11245, 11257), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (11255, 11257), True, 'import matplotlib.pyplot as plt\n'), ((11270, 11320), 'numpy.linspace', 'np.linspace', ([], {'start': '(0)', 'stop': '(1)', 'num': 'num_samples_full'}), '(start=0, stop=1, num=num_samples_full)\n', (11281, 11320), True, 'import numpy as np\n'), ((11470, 11488), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-20, 2]'], {}), '([-20, 2])\n', (11478, 11488), True, 'import matplotlib.pyplot as plt\n'), ((11493, 11515), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0.25, 0.75]'], {}), '([0.25, 0.75])\n', (11501, 11515), True, 'import matplotlib.pyplot as plt\n'), ((11519, 11548), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (11529, 11548), True, 'import matplotlib.pyplot as plt\n'), ((11585, 11649), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 1]', '[-3, -3]'], {'color': '"""k"""', 'linestyle': '""":"""', 'label': 'None'}), "([0, 1], [-3, -3], color='k', linestyle=':', label=None)\n", (11593, 11649), True, 'import matplotlib.pyplot as plt\n'), ((11654, 11682), 'matplotlib.pyplot.text', 'plt.text', (['(0.3)', '(-2.5)', '"""-3 dB"""'], {}), "(0.3, -2.5, '-3 dB')\n", (11662, 11682), True, 'import matplotlib.pyplot as plt\n'), ((11686, 11729), 'matplotlib.pyplot.text', 'plt.text', (['(0.55)', '(-2.25)', '"""$B_s = 1/T_{chip}$"""'], {}), "(0.55, -2.25, '$B_s = 1/T_{chip}$')\n", (11694, 11729), True, 'import matplotlib.pyplot as plt\n'), ((11734, 11775), 'matplotlib.pyplot.text', 'plt.text', (['(0.55)', '(-4.5)', '"""$B_d = 1/T_{sym}$"""'], {}), "(0.55, -4.5, '$B_d = 1/T_{sym}$')\n", (11742, 11775), True, 'import matplotlib.pyplot as plt\n'), ((12531, 12567), 'numpy.logspace', 'np.logspace', ([], {'start': '(3)', 'stop': '(9)', 'num': '(10)'}), '(start=3, stop=9, num=10)\n', (12542, 12567), True, 'import numpy as np\n'), ((12590, 12612), 'utils.unit_conversions.lin_to_db', 'lin_to_db', (['(bw / bw_ref)'], {}), '(bw / bw_ref)\n', (12599, 12612), False, 'from utils.unit_conversions import lin_to_db, db_to_lin\n'), ((12669, 12681), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (12679, 12681), True, 'import matplotlib.pyplot as plt\n'), ((12686, 12712), 'matplotlib.pyplot.semilogx', 'plt.semilogx', (['bw', 'snr_o_db'], {}), '(bw, snr_o_db)\n', (12698, 12712), True, 'import matplotlib.pyplot as plt\n'), ((12717, 12741), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$B_s$ [Hz]"""'], {}), "('$B_s$ [Hz]')\n", (12727, 12741), True, 'import matplotlib.pyplot as plt\n'), ((12747, 12772), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\xi$ [dB]"""'], {}), "('$\\\\xi$ [dB]')\n", (12757, 12772), True, 'import matplotlib.pyplot as plt\n'), ((13301, 13342), 'numpy.arange', 'np.arange', ([], {'start': '(-30)', 'stop': '(30.1)', 'step': '(0.1)'}), '(start=-30, stop=30.1, step=0.1)\n', (13310, 13342), True, 'import numpy as np\n'), ((13445, 13480), 'numpy.logspace', 'np.logspace', ([], {'start': '(6)', 'stop': '(9)', 'num': '(4)'}), '(start=6, stop=9, num=4)\n', (13456, 13480), True, 'import numpy as np\n'), ((13535, 13554), 'utils.unit_conversions.lin_to_db', 'lin_to_db', (['tbwp_lin'], {}), '(tbwp_lin)\n', (13544, 13554), False, 'from utils.unit_conversions import lin_to_db, db_to_lin\n'), ((13648, 13668), 'utils.unit_conversions.lin_to_db', 'lin_to_db', (['snr_o_lin'], {}), '(snr_o_lin)\n', (13657, 13668), False, 'from utils.unit_conversions import lin_to_db, db_to_lin\n'), ((13767, 13779), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13777, 13779), True, 'import matplotlib.pyplot as plt\n'), ((14018, 14046), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (14028, 14046), True, 'import matplotlib.pyplot as plt\n'), ((14051, 14078), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$\\\\xi_i$ [dB]"""'], {}), "('$\\\\xi_i$ [dB]')\n", (14061, 14078), True, 'import matplotlib.pyplot as plt\n'), ((14083, 14110), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\xi_o$ [dB]"""'], {}), "('$\\\\xi_o$ [dB]')\n", (14093, 14110), True, 'import matplotlib.pyplot as plt\n'), ((14653, 14707), 'numpy.arange', 'np.arange', ([], {'start': '(10.0)', 'stop': '(31.0)', 'step': '(10.0)', 'dtype': 'int'}), '(start=10.0, stop=31.0, step=10.0, dtype=int)\n', (14662, 14707), True, 'import numpy as np\n'), ((14807, 14848), 'numpy.arange', 'np.arange', ([], {'start': '(-20)', 'stop': '(10.1)', 'step': '(0.1)'}), '(start=-20, stop=10.1, step=0.1)\n', (14816, 14848), True, 'import numpy as np\n'), ((15139, 15189), 'scipy.stats.chi2.ppf', 'stats.chi2.ppf', ([], {'q': '(1 - prob_fa)', 'df': '(2 * tbwp_vec_lin)'}), '(q=1 - prob_fa, df=2 * tbwp_vec_lin)\n', (15153, 15189), False, 'from scipy import stats\n'), ((15204, 15299), 'scipy.stats.ncx2.sf', 'stats.ncx2.sf', ([], {'x': 'threshold_ed', 'df': '(2 * tbwp_vec_lin)', 'nc': '(2 * tbwp_vec_lin * input_snr_vec_lin)'}), '(x=threshold_ed, df=2 * tbwp_vec_lin, nc=2 * tbwp_vec_lin *\n input_snr_vec_lin)\n', (15217, 15299), False, 'from scipy import stats\n'), ((15345, 15380), 'scipy.stats.chi2.ppf', 'stats.chi2.ppf', ([], {'q': '(1 - prob_fa)', 'df': '(2)'}), '(q=1 - prob_fa, df=2)\n', (15359, 15380), False, 'from scipy import stats\n'), ((15397, 15493), 'scipy.stats.ncx2.sf', 'stats.ncx2.sf', ([], {'x': '(threshold_xc / (1 + 2 * input_snr_vec_lin))', 'df': '(2)', 'nc': '(2 * output_snr_vec_lin)'}), '(x=threshold_xc / (1 + 2 * input_snr_vec_lin), df=2, nc=2 *\n output_snr_vec_lin)\n', (15410, 15493), False, 'from scipy import stats\n'), ((15596, 15630), 'utils.unit_conversions.db_to_lin', 'db_to_lin', (['input_snr_vec_coarse_db'], {}), '(input_snr_vec_coarse_db)\n', (15605, 15630), False, 'from utils.unit_conversions import lin_to_db, db_to_lin\n'), ((15837, 15872), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_snr, num_tbwp)'}), '(shape=(num_snr, num_tbwp))\n', (15845, 15872), True, 'import numpy as np\n'), ((15894, 15929), 'numpy.zeros', 'np.zeros', ([], {'shape': '(num_snr, num_tbwp)'}), '(shape=(num_snr, num_tbwp))\n', (15902, 15929), True, 'import numpy as np\n'), ((17441, 17453), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (17451, 17453), True, 'import matplotlib.pyplot as plt\n'), ((18262, 18291), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (18272, 18291), True, 'import matplotlib.pyplot as plt\n'), ((18324, 18333), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (18331, 18333), True, 'import matplotlib.pyplot as plt\n'), ((18344, 18386), 'matplotlib.patches.Ellipse', 'Ellipse', ([], {'xy': '(2, 0.4)', 'width': '(5)', 'height': '(0.05)'}), '(xy=(2, 0.4), width=5, height=0.05)\n', (18351, 18386), False, 'from matplotlib.patches import Ellipse\n'), ((18586, 18631), 'matplotlib.patches.Ellipse', 'Ellipse', ([], {'xy': '(-3.5, 0.5)', 'width': '(3)', 'height': '(0.05)'}), '(xy=(-3.5, 0.5), width=3, height=0.05)\n', (18593, 18631), False, 'from matplotlib.patches import Ellipse\n'), ((18831, 18876), 'matplotlib.patches.Ellipse', 'Ellipse', ([], {'xy': '(-8.5, 0.6)', 'width': '(3)', 'height': '(0.05)'}), '(xy=(-8.5, 0.6), width=3, height=0.05)\n', (18838, 18876), False, 'from matplotlib.patches import Ellipse\n'), ((19504, 19523), 'examples.chapter4.example1', 'chapter4.example1', ([], {}), '()\n', (19521, 19523), False, 'from examples import chapter4\n'), ((20014, 20039), 'examples.chapter4.example2', 'chapter4.example2', (['colors'], {}), '(colors)\n', (20031, 20039), False, 'from examples import chapter4\n'), ((1622, 1632), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1630, 1632), True, 'import matplotlib.pyplot as plt\n'), ((2261, 2276), 'numpy.size', 'np.size', (['y_full'], {}), '(y_full)\n', (2268, 2276), True, 'import numpy as np\n'), ((2324, 2339), 'numpy.real', 'np.real', (['y_full'], {}), '(y_full)\n', (2331, 2339), True, 'import numpy as np\n'), ((2387, 2407), 'numpy.zeros_like', 'np.zeros_like', (['t_vec'], {}), '(t_vec)\n', (2400, 2407), True, 'import numpy as np\n'), ((2937, 2970), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig1a.svg')"], {}), "(prefix + 'fig1a.svg')\n", (2948, 2970), True, 'import matplotlib.pyplot as plt\n'), ((2979, 3012), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig1a.png')"], {}), "(prefix + 'fig1a.png')\n", (2990, 3012), True, 'import matplotlib.pyplot as plt\n'), ((3353, 3376), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (3374, 3376), True, 'import numpy as np\n'), ((3986, 4013), 'numpy.exp', 'np.exp', (['(1.0j * np.pi * code)'], {}), '(1.0j * np.pi * code)\n', (3992, 4013), True, 'import numpy as np\n'), ((4216, 4258), 'numpy.ravel', 'np.ravel', (['(starting_phase * symbol * y_chip)'], {}), '(starting_phase * symbol * y_chip)\n', (4224, 4258), True, 'import numpy as np\n'), ((4602, 4636), 'scipy.fftpack.fftshift', 'fftpack.fftshift', (['spectral_average'], {}), '(spectral_average)\n', (4618, 4636), False, 'from scipy import fftpack\n'), ((4718, 4769), 'numpy.linspace', 'np.linspace', ([], {'start': '(-1)', 'stop': '(1)', 'num': 'num_code_samples'}), '(start=-1, stop=1, num=num_code_samples)\n', (4729, 4769), True, 'import numpy as np\n'), ((5895, 5928), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig1b.svg')"], {}), "(prefix + 'fig1b.svg')\n", (5906, 5928), True, 'import matplotlib.pyplot as plt\n'), ((5937, 5970), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig1b.png')"], {}), "(prefix + 'fig1b.png')\n", (5948, 5970), True, 'import matplotlib.pyplot as plt\n'), ((6300, 6323), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (6321, 6323), True, 'import numpy as np\n'), ((6446, 6475), 'numpy.fix', 'np.fix', (['(rate_chip / rate_data)'], {}), '(rate_chip / rate_data)\n', (6452, 6475), True, 'import numpy as np\n'), ((6935, 6972), 'numpy.exp', 'np.exp', (['(1.0j * np.pi * data_bits_full)'], {}), '(1.0j * np.pi * data_bits_full)\n', (6941, 6972), True, 'import numpy as np\n'), ((7027, 7064), 'numpy.exp', 'np.exp', (['(1.0j * np.pi * code_bits_full)'], {}), '(1.0j * np.pi * code_bits_full)\n', (7033, 7064), True, 'import numpy as np\n'), ((7118, 7154), 'numpy.exp', 'np.exp', (['(1.0j * np.pi * out_bits_full)'], {}), '(1.0j * np.pi * out_bits_full)\n', (7124, 7154), True, 'import numpy as np\n'), ((7550, 7580), 'numpy.arange', 'np.arange', (['(num_full_bits * osf)'], {}), '(num_full_bits * osf)\n', (7559, 7580), True, 'import numpy as np\n'), ((7633, 7663), 'numpy.arange', 'np.arange', (['(num_code_bits * osf)'], {}), '(num_code_bits * osf)\n', (7642, 7663), True, 'import numpy as np\n'), ((7740, 7770), 'numpy.arange', 'np.arange', (['(num_full_bits * osf)'], {}), '(num_full_bits * osf)\n', (7749, 7770), True, 'import numpy as np\n'), ((7770, 7785), 'numpy.real', 'np.real', (['y_dsss'], {}), '(y_dsss)\n', (7777, 7785), True, 'import numpy as np\n'), ((7880, 7903), 'numpy.ravel', 'np.ravel', (['out_bits_full'], {}), '(out_bits_full)\n', (7888, 7903), True, 'import numpy as np\n'), ((8096, 8115), 'numpy.ravel', 'np.ravel', (['code_bits'], {}), '(code_bits)\n', (8104, 8115), True, 'import numpy as np\n'), ((8307, 8326), 'numpy.ravel', 'np.ravel', (['data_bits'], {}), '(data_bits)\n', (8315, 8326), True, 'import numpy as np\n'), ((8671, 8704), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig2a.svg')"], {}), "(prefix + 'fig2a.svg')\n", (8682, 8704), True, 'import matplotlib.pyplot as plt\n'), ((8713, 8746), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig2a.png')"], {}), "(prefix + 'fig2a.png')\n", (8724, 8746), True, 'import matplotlib.pyplot as plt\n'), ((9075, 9099), 'numpy.random.default_rng', 'np.random.default_rng', (['(0)'], {}), '(0)\n', (9096, 9099), True, 'import numpy as np\n'), ((9336, 9377), 'numpy.fix', 'np.fix', (['(num_samples_full / num_bits_code1)'], {}), '(num_samples_full / num_bits_code1)\n', (9342, 9377), True, 'import numpy as np\n'), ((9402, 9443), 'numpy.fix', 'np.fix', (['(num_samples_full / num_bits_code2)'], {}), '(num_samples_full / num_bits_code2)\n', (9408, 9443), True, 'import numpy as np\n'), ((10159, 10206), 'numpy.zeros_like', 'np.zeros_like', (['spectral_average1'], {'dtype': 'complex'}), '(spectral_average1, dtype=complex)\n', (10172, 10206), True, 'import numpy as np\n'), ((10379, 10426), 'numpy.zeros_like', 'np.zeros_like', (['spectral_average2'], {'dtype': 'complex'}), '(spectral_average2, dtype=complex)\n', (10392, 10426), True, 'import numpy as np\n'), ((10850, 10885), 'scipy.fftpack.fftshift', 'fftpack.fftshift', (['spectral_average1'], {}), '(spectral_average1)\n', (10866, 10885), False, 'from scipy import fftpack\n'), ((10886, 10923), 'numpy.amax', 'np.amax', (['spectral_average1'], {'axis': 'None'}), '(spectral_average1, axis=None)\n', (10893, 10923), True, 'import numpy as np\n'), ((10948, 10983), 'scipy.fftpack.fftshift', 'fftpack.fftshift', (['spectral_average2'], {}), '(spectral_average2)\n', (10964, 10983), False, 'from scipy import fftpack\n'), ((10984, 11021), 'numpy.amax', 'np.amax', (['spectral_average2'], {'axis': 'None'}), '(spectral_average2, axis=None)\n', (10991, 11021), True, 'import numpy as np\n'), ((11341, 11369), 'utils.unit_conversions.lin_to_db', 'lin_to_db', (['spectral_average1'], {}), '(spectral_average1)\n', (11350, 11369), False, 'from utils.unit_conversions import lin_to_db, db_to_lin\n'), ((11412, 11440), 'utils.unit_conversions.lin_to_db', 'lin_to_db', (['spectral_average2'], {}), '(spectral_average2)\n', (11421, 11440), False, 'from utils.unit_conversions import lin_to_db, db_to_lin\n'), ((12160, 12193), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig2b.svg')"], {}), "(prefix + 'fig2b.svg')\n", (12171, 12193), True, 'import matplotlib.pyplot as plt\n'), ((12202, 12235), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig2b.png')"], {}), "(prefix + 'fig2b.png')\n", (12213, 12235), True, 'import matplotlib.pyplot as plt\n'), ((12827, 12859), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig3.svg')"], {}), "(prefix + 'fig3.svg')\n", (12838, 12859), True, 'import matplotlib.pyplot as plt\n'), ((12868, 12900), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig3.png')"], {}), "(prefix + 'fig3.png')\n", (12879, 12900), True, 'import matplotlib.pyplot as plt\n'), ((13248, 13269), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""tab10"""'], {}), "('tab10')\n", (13260, 13269), True, 'import matplotlib.pyplot as plt\n'), ((13373, 13392), 'utils.unit_conversions.db_to_lin', 'db_to_lin', (['snr_i_db'], {}), '(snr_i_db)\n', (13382, 13392), False, 'from utils.unit_conversions import lin_to_db, db_to_lin\n'), ((13688, 13720), 'numpy.expand_dims', 'np.expand_dims', (['snr_i_db'], {'axis': '(1)'}), '(snr_i_db, axis=1)\n', (13702, 13720), True, 'import numpy as np\n'), ((13723, 13754), 'numpy.expand_dims', 'np.expand_dims', (['tbwp_db'], {'axis': '(0)'}), '(tbwp_db, axis=0)\n', (13737, 13754), True, 'import numpy as np\n'), ((14165, 14197), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig5.svg')"], {}), "(prefix + 'fig5.svg')\n", (14176, 14197), True, 'import matplotlib.pyplot as plt\n'), ((14206, 14238), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig5.png')"], {}), "(prefix + 'fig5.png')\n", (14217, 14238), True, 'import matplotlib.pyplot as plt\n'), ((14888, 14915), 'utils.unit_conversions.db_to_lin', 'db_to_lin', (['input_snr_vec_db'], {}), '(input_snr_vec_db)\n', (14897, 14915), False, 'from utils.unit_conversions import lin_to_db, db_to_lin\n'), ((15971, 15993), 'numpy.ravel', 'np.ravel', (['tbwp_vec_lin'], {}), '(tbwp_vec_lin)\n', (15979, 15993), True, 'import numpy as np\n'), ((19122, 19154), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig6.svg')"], {}), "(prefix + 'fig6.svg')\n", (19133, 19154), True, 'import matplotlib.pyplot as plt\n'), ((19163, 19195), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig6.png')"], {}), "(prefix + 'fig6.png')\n", (19174, 19195), True, 'import matplotlib.pyplot as plt\n'), ((19578, 19610), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig7.svg')"], {}), "(prefix + 'fig7.svg')\n", (19589, 19610), True, 'import matplotlib.pyplot as plt\n'), ((19619, 19651), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig7.png')"], {}), "(prefix + 'fig7.png')\n", (19630, 19651), True, 'import matplotlib.pyplot as plt\n'), ((20094, 20126), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig8.svg')"], {}), "(prefix + 'fig8.svg')\n", (20105, 20126), True, 'import matplotlib.pyplot as plt\n'), ((20135, 20167), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(prefix + 'fig8.png')"], {}), "(prefix + 'fig8.png')\n", (20146, 20167), True, 'import matplotlib.pyplot as plt\n'), ((1568, 1582), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (1577, 1582), True, 'import matplotlib.pyplot as plt\n'), ((2162, 2192), 'numpy.expand_dims', 'np.expand_dims', (['y_chip'], {'axis': '(0)'}), '(y_chip, axis=0)\n', (2176, 2192), True, 'import numpy as np\n'), ((2193, 2223), 'numpy.expand_dims', 'np.expand_dims', (['symbol'], {'axis': '(1)'}), '(symbol, axis=1)\n', (2207, 2223), True, 'import numpy as np\n'), ((2596, 2613), 'numpy.array', 'np.array', (['[-1, 2]'], {}), '([-1, 2])\n', (2604, 2613), True, 'import numpy as np\n'), ((4644, 4673), 'numpy.absolute', 'np.absolute', (['spectral_average'], {}), '(spectral_average)\n', (4655, 4673), True, 'import numpy as np\n'), ((7580, 7595), 'numpy.real', 'np.real', (['y_data'], {}), '(y_data)\n', (7587, 7595), True, 'import numpy as np\n'), ((7663, 7701), 'numpy.real', 'np.real', (['y_code[0:num_code_bits * osf]'], {}), '(y_code[0:num_code_bits * osf])\n', (7670, 7701), True, 'import numpy as np\n'), ((10659, 10674), 'scipy.fft', 'sp.fft', (['signal1'], {}), '(signal1)\n', (10665, 10674), True, 'import scipy as sp\n'), ((10717, 10732), 'scipy.fft', 'sp.fft', (['signal2'], {}), '(signal2)\n', (10723, 10732), True, 'import scipy as sp\n'), ((13571, 13603), 'numpy.expand_dims', 'np.expand_dims', (['tbwp_lin'], {'axis': '(0)'}), '(tbwp_lin, axis=0)\n', (13585, 13603), True, 'import numpy as np\n'), ((16050, 16072), 'numpy.sqrt', 'np.sqrt', (['(noise_pwr / 2)'], {}), '(noise_pwr / 2)\n', (16057, 16072), True, 'import numpy as np\n'), ((16234, 16256), 'numpy.sqrt', 'np.sqrt', (['(noise_pwr / 2)'], {}), '(noise_pwr / 2)\n', (16241, 16256), True, 'import numpy as np\n'), ((16454, 16468), 'numpy.sqrt', 'np.sqrt', (['(1 / 2)'], {}), '(1 / 2)\n', (16461, 16468), True, 'import numpy as np\n'), ((16986, 17061), 'detector.squareLaw.det_test', 'detector.squareLaw.det_test', ([], {'z': 'y1', 'noise_var': '(noise_pwr / 2)', 'prob_fa': 'prob_fa'}), '(z=y1, noise_var=noise_pwr / 2, prob_fa=prob_fa)\n', (17013, 17061), False, 'import detector\n'), ((17186, 17283), 'detector.xcorr.det_test', 'detector.xcorr.det_test', ([], {'y1': 'y1', 'y2': 'y2', 'noise_var': 'noise_pwr', 'num_samples': 'tbwp', 'prob_fa': 'prob_fa'}), '(y1=y1, y2=y2, noise_var=noise_pwr, num_samples=tbwp,\n prob_fa=prob_fa)\n', (17209, 17283), False, 'import detector\n'), ((2578, 2594), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (2586, 2594), True, 'import numpy as np\n'), ((4463, 4481), 'numpy.real', 'np.real', (['signal_rf'], {}), '(signal_rf)\n', (4470, 4481), True, 'import numpy as np\n'), ((4796, 4825), 'numpy.absolute', 'np.absolute', (['spectral_average'], {}), '(spectral_average)\n', (4807, 4825), True, 'import numpy as np\n'), ((7986, 8002), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (7994, 8002), True, 'import numpy as np\n'), ((8198, 8214), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (8206, 8214), True, 'import numpy as np\n'), ((8451, 8467), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (8459, 8467), True, 'import numpy as np\n'), ((14739, 14761), 'utils.unit_conversions.db_to_lin', 'db_to_lin', (['tbwp_vec_db'], {}), '(tbwp_vec_db)\n', (14748, 14761), False, 'from utils.unit_conversions import lin_to_db, db_to_lin\n'), ((16854, 16866), 'numpy.sqrt', 'np.sqrt', (['snr'], {}), '(snr)\n', (16861, 16866), True, 'import numpy as np\n'), ((17108, 17140), 'numpy.sum', 'np.sum', (['det_result_ed'], {'axis': 'None'}), '(det_result_ed, axis=None)\n', (17114, 17140), True, 'import numpy as np\n'), ((17380, 17412), 'numpy.sum', 'np.sum', (['det_result_xc'], {'axis': 'None'}), '(det_result_xc, axis=None)\n', (17386, 17412), True, 'import numpy as np\n'), ((3647, 3674), 'numpy.arange', 'np.arange', (['num_code_samples'], {}), '(num_code_samples)\n', (3656, 3674), True, 'import numpy as np\n'), ((10269, 10294), 'numpy.arange', 'np.arange', (['chip_len_code1'], {}), '(chip_len_code1)\n', (10278, 10294), True, 'import numpy as np\n'), ((10323, 10349), 'numpy.exp', 'np.exp', (['(1.0j * np.pi * bit)'], {}), '(1.0j * np.pi * bit)\n', (10329, 10349), True, 'import numpy as np\n'), ((10489, 10514), 'numpy.arange', 'np.arange', (['chip_len_code2'], {}), '(chip_len_code2)\n', (10498, 10514), True, 'import numpy as np\n'), ((10543, 10569), 'numpy.exp', 'np.exp', (['(1.0j * np.pi * bit)'], {}), '(1.0j * np.pi * bit)\n', (10549, 10569), True, 'import numpy as np\n'), ((1993, 2014), 'numpy.arange', 'np.arange', (['num_points'], {}), '(num_points)\n', (2002, 2014), True, 'import numpy as np\n'), ((3529, 3551), 'numpy.arange', 'np.arange', (['num_samples'], {}), '(num_samples)\n', (3538, 3551), True, 'import numpy as np\n'), ((9508, 9533), 'numpy.arange', 'np.arange', (['chip_len_code1'], {}), '(chip_len_code1)\n', (9517, 9533), True, 'import numpy as np\n'), ((9590, 9615), 'numpy.arange', 'np.arange', (['chip_len_code2'], {}), '(chip_len_code2)\n', (9599, 9615), True, 'import numpy as np\n'), ((7291, 7305), 'numpy.arange', 'np.arange', (['osf'], {}), '(osf)\n', (7300, 7305), True, 'import numpy as np\n')]
### Code Adapted From <NAME> Kaggle Submission: https://www.kaggle.com/shayantaherian/nfl-training-fasterrcnn # Import Packages import pandas as pd import numpy as np from matplotlib import pyplot as plt from matplotlib import patches import imageio from tqdm import tqdm_notebook as tqdm from tqdm import tqdm from tqdm.notebook import tqdm as tqdm import cv2 import os import re import random import subprocess from PIL import Image from IPython.display import Video, display import albumentations as A from albumentations.pytorch.transforms import ToTensorV2 import torch import torchvision import ast from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torchvision.models.detection import FasterRCNN from torchvision.models.detection.rpn import AnchorGenerator from torch.utils.data import DataLoader, Dataset from torch.utils.data.sampler import SequentialSampler # Build Dataset of Image Frames class build_dataset(): # Below is the file path for my folder of images, but change it to fit your computer def __init__(self): self.images_df = pd.read_csv('image_labels.csv') self.images_list = os.listdir(r'/home/jupyter-rogersdv/images/images') # Classes of helmets to be tracked self.labels_dict = {'Helmet': 1, 'Helmet-Blurred': 2, 'Helmet-Difficult': 3, 'Helmet-Sideline': 4, 'Helmet-Partial': 5} # Collect initial bounding boxes of images def __getitem__(self, idx): img_path = os.path.join(r'/home/jupyter-rogersdv/images/images', self.images_list[idx]) img = np.array(Image.open(img_path)) / 255 img = np.moveaxis(img, 2, 0) # to [C, H, W] # Collect data about boxes and helmet labels from `image_labels.csv` img_data_df = self.images_df[self.images_df['image'] == self.images_list[idx]] n_bboxes = img_data_df.shape[0] bboxes = [] labels = [] for i in range(n_bboxes): img_data = img_data_df.iloc[i] x_min = img_data.left x_max = img_data.left + img_data.width y_min = img_data.top y_max = img_data.top + img_data.height bboxes.append([x_min, y_min, x_max, y_max]) label = self.labels_dict[img_data.label] labels.append(label) # Convert data to tensors img = torch.as_tensor(img, dtype=torch.float32) bboxes = torch.as_tensor(bboxes, dtype=torch.float32) labels = torch.as_tensor(labels, dtype=torch.int64) image_id = torch.tensor([idx]) target = {} target['boxes'] = bboxes target['labels'] = labels target['image_id'] = image_id return img, target def __len__(self): return len(self.images_list) # Functions to convert train/validation image information to tensors def get_train_transform(): return A.Compose([ A.Flip(0.5), ToTensorV2(p=1.0) ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']}) def get_valid_transform(): return A.Compose([ ToTensorV2(p=1.0) ], bbox_params={'format': 'pascal_voc', 'label_fields': ['labels']}) # Loading Faster R-CNN (ResNet50 Model), pretrained weights on COCO dataset model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) # replace the classifier by adjusting number of classes num_classes = 6 # get number of input features for the classifier in_features = model.roi_heads.box_predictor.cls_score.in_features # replace the pre-trained head with a new one model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) # Function to form mini-batches of tensors def collate_fn(batch): return tuple(zip(*batch)) # Building dataset and making train/validation split dataset = build_dataset() indices = torch.randperm(len(dataset)).tolist() train_set = int(0.9*len(indices)) train_dataset = torch.utils.data.Subset(dataset, indices[:train_set]) valid_dataset = torch.utils.data.Subset(dataset, indices[train_set:]) train_data_loader = torch.utils.data.DataLoader( train_dataset, batch_size = 8, shuffle = False, collate_fn = collate_fn) valid_data_loader = torch.utils.data.DataLoader( valid_dataset, batch_size = 8, shuffle = False, collate_fn = collate_fn) # Allocating model to a device, creating a model optimizer using SGD device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') torch.cuda.empty_cache() torch.cuda.memory_summary(device=None, abbreviated=False) model.to(device) params = [p for p in model.parameters() if p.requires_grad] optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005) lr_scheduler = None # Model training & optimization num_iters = 100 progress_bar = tqdm(range(num_iters)) tr_it = iter(train_data_loader) loss_log = [] iterations = [] # Looping through batches and copmuting log loss for i in progress_bar: try: data = next(tr_it) except StopIteration: tr_it = iter(train_data_loader) data = next(tr_it) model.train() torch.set_grad_enabled(True) imgs, targets = data imgs = [image.to(device) for image in imgs] targets = [{k: v.to(device) for k, v in tgt.items()} for tgt in targets] loss_dict = model(imgs, targets) losses = sum(loss for loss in loss_dict.values()) # Optimization optimizer.zero_grad() losses.backward() optimizer.step() loss_log.append(losses.item()) iterations.append(i) # Updating a live progress bar progress_bar.set_description(f'batch loss: {losses.item()}, average loss: {np.mean(loss_log)}.') # Plotting log loss performance by iteration plt.plot(iterations, loss_log) plt.xlabel("Iteration") plt.ylabel("Log Loss") plt.title("Average Log Loss per Batch") plt.show() # Function to put image bounding boxes and detection scores in string format def format_predictions(boxes, scores): pred_strings = [] for s, b in zip(scores, boxes.astype(int)): pred_strings.append(f'{s:.4f} {b[0]} {b[1]} {b[2] - b[0]} {b[3] - b[1]}') return " ".join(pred_strings) # Evaluating model and compiling successfully detected bounding boxes detection_threshold = 0.5 results = [] device = 'cuda' model.eval() for images, image_ids in valid_data_loader: images = list(image.to(device) for image in images) outputs = model(images) for i, image in enumerate(images): boxes = outputs[i]['boxes'].data.cpu().numpy() scores = outputs[i]['scores'].data.cpu().numpy() boxes = boxes[scores >= detection_threshold].astype(np.int32) scores = scores[scores >= detection_threshold] image_id = image_ids[i] result = { 'image_id': image_id, 'PredictionString': format_predictions(boxes, scores) } results.append(result) # Function to plot predicted bounding boxes def plot_detected_bboxes(test_img, predictions, n_to_plot=2, score_threshold=0.6): n = min(len(test_img), n_to_plot) fig, ax = plt.subplots(1, n, figsize=(20, 8)) for i in range(n): img = np.asarray(test_img[i].cpu().numpy() * 255, dtype=np.int64) img = np.moveaxis(img, 0, 2) img = Image.fromarray(np.uint8(img)).convert('RGB') ax[i].imshow(img) ax[i].set_axis_off() bboxes = predictions[i]['boxes'].cpu().numpy() scores = predictions[i]['scores'].cpu().numpy() scores_mask = scores > score_threshold for bbox in bboxes[scores_mask]: patch = patches.Rectangle( (bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], linewidth=2, edgecolor='r', facecolor='None', alpha=0.8) ax[i].add_patch(patch) fig.tight_layout() return # Evaluate / Plot validation set images model.eval() torch.set_grad_enabled(False) test_it = iter(valid_data_loader) valid_img, valid_gt = next(test_it) valid_img = [image.to(device) for image in valid_img] predictions = model(test_img) plot_detected_bboxes(valid_img, predictions, n_to_plot=2, score_threshold=0.6)
[ "numpy.uint8", "torch.as_tensor", "pandas.read_csv", "matplotlib.pyplot.ylabel", "torch.cuda.is_available", "numpy.moveaxis", "torch.cuda.memory_summary", "numpy.mean", "os.listdir", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "albumentations.pytorch.transforms.ToTensorV2", "torch....
[((3411, 3480), 'torchvision.models.detection.fasterrcnn_resnet50_fpn', 'torchvision.models.detection.fasterrcnn_resnet50_fpn', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (3463, 3480), False, 'import torchvision\n'), ((3750, 3793), 'torchvision.models.detection.faster_rcnn.FastRCNNPredictor', 'FastRCNNPredictor', (['in_features', 'num_classes'], {}), '(in_features, num_classes)\n', (3767, 3793), False, 'from torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n'), ((4073, 4126), 'torch.utils.data.Subset', 'torch.utils.data.Subset', (['dataset', 'indices[:train_set]'], {}), '(dataset, indices[:train_set])\n', (4096, 4126), False, 'import torch\n'), ((4143, 4196), 'torch.utils.data.Subset', 'torch.utils.data.Subset', (['dataset', 'indices[train_set:]'], {}), '(dataset, indices[train_set:])\n', (4166, 4196), False, 'import torch\n'), ((4218, 4316), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_dataset'], {'batch_size': '(8)', 'shuffle': '(False)', 'collate_fn': 'collate_fn'}), '(train_dataset, batch_size=8, shuffle=False,\n collate_fn=collate_fn)\n', (4245, 4316), False, 'import torch\n'), ((4405, 4503), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['valid_dataset'], {'batch_size': '(8)', 'shuffle': '(False)', 'collate_fn': 'collate_fn'}), '(valid_dataset, batch_size=8, shuffle=False,\n collate_fn=collate_fn)\n', (4432, 4503), False, 'import torch\n'), ((4727, 4751), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (4749, 4751), False, 'import torch\n'), ((4752, 4809), 'torch.cuda.memory_summary', 'torch.cuda.memory_summary', ([], {'device': 'None', 'abbreviated': '(False)'}), '(device=None, abbreviated=False)\n', (4777, 4809), False, 'import torch\n'), ((4900, 4968), 'torch.optim.SGD', 'torch.optim.SGD', (['params'], {'lr': '(0.005)', 'momentum': '(0.9)', 'weight_decay': '(0.0005)'}), '(params, lr=0.005, momentum=0.9, weight_decay=0.0005)\n', (4915, 4968), False, 'import torch\n'), ((5988, 6018), 'matplotlib.pyplot.plot', 'plt.plot', (['iterations', 'loss_log'], {}), '(iterations, loss_log)\n', (5996, 6018), True, 'from matplotlib import pyplot as plt\n'), ((6019, 6042), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Iteration"""'], {}), "('Iteration')\n", (6029, 6042), True, 'from matplotlib import pyplot as plt\n'), ((6043, 6065), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Log Loss"""'], {}), "('Log Loss')\n", (6053, 6065), True, 'from matplotlib import pyplot as plt\n'), ((6066, 6105), 'matplotlib.pyplot.title', 'plt.title', (['"""Average Log Loss per Batch"""'], {}), "('Average Log Loss per Batch')\n", (6075, 6105), True, 'from matplotlib import pyplot as plt\n'), ((6106, 6116), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6114, 6116), True, 'from matplotlib import pyplot as plt\n'), ((8266, 8295), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (8288, 8295), False, 'import torch\n'), ((4675, 4700), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4698, 4700), False, 'import torch\n'), ((4651, 4671), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (4663, 4671), False, 'import torch\n'), ((4706, 4725), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (4718, 4725), False, 'import torch\n'), ((5365, 5393), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (5387, 5393), False, 'import torch\n'), ((7386, 7421), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', 'n'], {'figsize': '(20, 8)'}), '(1, n, figsize=(20, 8))\n', (7398, 7421), True, 'from matplotlib import pyplot as plt\n'), ((1100, 1131), 'pandas.read_csv', 'pd.read_csv', (['"""image_labels.csv"""'], {}), "('image_labels.csv')\n", (1111, 1131), True, 'import pandas as pd\n'), ((1159, 1209), 'os.listdir', 'os.listdir', (['"""/home/jupyter-rogersdv/images/images"""'], {}), "('/home/jupyter-rogersdv/images/images')\n", (1169, 1209), False, 'import os\n'), ((1593, 1668), 'os.path.join', 'os.path.join', (['"""/home/jupyter-rogersdv/images/images"""', 'self.images_list[idx]'], {}), "('/home/jupyter-rogersdv/images/images', self.images_list[idx])\n", (1605, 1668), False, 'import os\n'), ((1735, 1757), 'numpy.moveaxis', 'np.moveaxis', (['img', '(2)', '(0)'], {}), '(img, 2, 0)\n', (1746, 1757), True, 'import numpy as np\n'), ((2477, 2518), 'torch.as_tensor', 'torch.as_tensor', (['img'], {'dtype': 'torch.float32'}), '(img, dtype=torch.float32)\n', (2492, 2518), False, 'import torch\n'), ((2540, 2584), 'torch.as_tensor', 'torch.as_tensor', (['bboxes'], {'dtype': 'torch.float32'}), '(bboxes, dtype=torch.float32)\n', (2555, 2584), False, 'import torch\n'), ((2602, 2644), 'torch.as_tensor', 'torch.as_tensor', (['labels'], {'dtype': 'torch.int64'}), '(labels, dtype=torch.int64)\n', (2617, 2644), False, 'import torch\n'), ((2664, 2683), 'torch.tensor', 'torch.tensor', (['[idx]'], {}), '([idx])\n', (2676, 2683), False, 'import torch\n'), ((7538, 7560), 'numpy.moveaxis', 'np.moveaxis', (['img', '(0)', '(2)'], {}), '(img, 0, 2)\n', (7549, 7560), True, 'import numpy as np\n'), ((3064, 3075), 'albumentations.Flip', 'A.Flip', (['(0.5)'], {}), '(0.5)\n', (3070, 3075), True, 'import albumentations as A\n'), ((3085, 3102), 'albumentations.pytorch.transforms.ToTensorV2', 'ToTensorV2', ([], {'p': '(1.0)'}), '(p=1.0)\n', (3095, 3102), False, 'from albumentations.pytorch.transforms import ToTensorV2\n'), ((3235, 3252), 'albumentations.pytorch.transforms.ToTensorV2', 'ToTensorV2', ([], {'p': '(1.0)'}), '(p=1.0)\n', (3245, 3252), False, 'from albumentations.pytorch.transforms import ToTensorV2\n'), ((7896, 8032), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(bbox[0], bbox[1])', '(bbox[2] - bbox[0])', '(bbox[3] - bbox[1])'], {'linewidth': '(2)', 'edgecolor': '"""r"""', 'facecolor': '"""None"""', 'alpha': '(0.8)'}), "((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1],\n linewidth=2, edgecolor='r', facecolor='None', alpha=0.8)\n", (7913, 8032), False, 'from matplotlib import patches\n'), ((1693, 1713), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (1703, 1713), False, 'from PIL import Image\n'), ((5911, 5928), 'numpy.mean', 'np.mean', (['loss_log'], {}), '(loss_log)\n', (5918, 5928), True, 'import numpy as np\n'), ((7591, 7604), 'numpy.uint8', 'np.uint8', (['img'], {}), '(img)\n', (7599, 7604), True, 'import numpy as np\n')]
from __future__ import annotations from collections import namedtuple from copy import deepcopy from typing import Dict, List, Optional, Tuple, Union import numpy as np from numpy.typing import ArrayLike, NDArray from simweights.powerlaw import PowerLaw from simweights.spatial import SpatialDist from .pdgcode import PDGCode SurfaceTuple = namedtuple("SurfaceTuple", ["pdgid", "nevents", "energy_dist", "spatial_dist"]) class GenerationSurface: """ This class represents a surface on which Monte Carlo simulation was generated on. The number of events thrown, the spatial distribution, and the energy distribution are stored in this class. Each particle type is stored separately. """ def __init__(self, *spectra: SurfaceTuple): """ :param spectra: a collection of GenerationProbabilities. """ self.spectra: Dict[int, List[SurfaceTuple]] = {} for spec in spectra: self._insert(spec) def _insert(self, surface: SurfaceTuple) -> None: key = int(surface.pdgid) if key not in self.spectra: self.spectra[key] = [] for i, spec in enumerate(self.spectra[key]): if surface.energy_dist == spec.energy_dist and surface.spatial_dist == spec.spatial_dist: self.spectra[key][i] = spec._replace(nevents=surface.nevents + spec.nevents) break else: self.spectra[key].append(deepcopy(surface)) def __add__(self, other: GenerationSurface) -> GenerationSurface: output = deepcopy(self) if not isinstance(other, GenerationSurface): raise TypeError(f"Cannot add {type(self)} to {type(other)}") for _, ospectra in other.spectra.items(): for ospec in ospectra: output._insert(ospec) return output def __radd__(self, other: GenerationSurface) -> GenerationSurface: return self + other def __mul__(self, factor: float) -> GenerationSurface: new_surface = deepcopy(self) for subsurf in new_surface.spectra.values(): for i, _ in enumerate(subsurf): subsurf[i] = subsurf[i]._replace(nevents=factor * subsurf[i].nevents) return new_surface def __rmul__(self, factor: float) -> GenerationSurface: return self.__mul__(factor) def get_epdf(self, pdgid: ArrayLike, energy: ArrayLike, cos_zen: ArrayLike) -> NDArray[np.floating]: """ Get the extended pdf of an event. The pdf is the probability that an event with these parameters is generated. The pdf is multiplied by the number of events. """ energy = np.asarray(energy) cos_zen = np.asarray(cos_zen) count = np.zeros_like(energy, dtype=float) for ptype in np.unique(pdgid): mask = ptype == pdgid if np.any(mask): masked_energy = energy[mask] masked_cos_zen = cos_zen[mask] count[mask] += sum( p.nevents * p.energy_dist.pdf(masked_energy) * p.spatial_dist.pdf(masked_cos_zen) for p in self.spectra[ptype] ) return count def get_pdgids(self) -> List[Union[int, PDGCode]]: """ Return a list of pdgids that this surface represents """ return sorted(self.spectra.keys()) def get_energy_range(self, pdgid: Optional[PDGCode]) -> Tuple[float, float]: """ Return the energy range for given particle type over all surfaces """ if pdgid is None: pdgids = sorted(self.spectra.keys()) else: pdgids = [pdgid] assert set(pdgids).issubset(self.spectra.keys()) emin = np.inf emax = -np.inf for pid in pdgids: for surf in self.spectra[pid]: emin = min(emin, surf.energy_dist.a) emax = max(emax, surf.energy_dist.b) assert np.isfinite(emin) assert np.isfinite(emax) return emin, emax def get_cos_zenith_range(self, pdgid: Optional[PDGCode]) -> Tuple[float, float]: """ Return the cos zenith range for given particle type over all surfaces """ if pdgid is None: pdgids = sorted(self.spectra.keys()) else: pdgids = [pdgid] assert set(pdgids).issubset(self.spectra.keys()) czmin = np.inf czmax = -np.inf for pid in pdgids: for surf in self.spectra[pid]: czmin = min(czmin, surf.spatial_dist.cos_zen_min) czmax = max(czmax, surf.spatial_dist.cos_zen_max) assert np.isfinite(czmin) assert np.isfinite(czmax) return czmin, czmax def __eq__(self, other: object) -> bool: # must handle the same set of particle types if not isinstance(other, GenerationSurface): return False if set(self.spectra.keys()) != set(other.spectra.keys()): return False for pdgid, spec1 in self.spectra.items(): spec2 = other.spectra[pdgid] # must have the same number of unique spectra if len(spec1) != len(spec2): return False # exactly one match for each energy_dist for subspec1 in spec1: if sum(subspec1 == subspec2 for subspec2 in spec2) != 1: return False return True def __repr__(self) -> str: return ( self.__class__.__name__ + "(" + ",".join(repr(y) for x in self.spectra.values() for y in x) + ")" ) def __str__(self) -> str: outstrs = [] for pdgid, specs in self.spectra.items(): try: ptype = PDGCode(pdgid).name except ValueError: ptype = str(pdgid) collections = [] for subspec in specs: collections.append(f"N={subspec.nevents} {subspec.energy_dist} {subspec.spatial_dist}") outstrs.append(f" {ptype:>11} : " + "\n ".join(collections)) return "< " + self.__class__.__name__ + "\n" + "\n".join(outstrs) + "\n>" def generation_surface(pdgid: Union[int, PDGCode], energy_dist: PowerLaw, spatial_dist: SpatialDist): """ Convenience function to generate a GenerationSurface for a single particle type """ return GenerationSurface( SurfaceTuple(pdgid=pdgid, nevents=1.0, energy_dist=energy_dist, spatial_dist=spatial_dist) ) NullSurface = GenerationSurface()
[ "collections.namedtuple", "numpy.unique", "numpy.asarray", "numpy.any", "numpy.isfinite", "copy.deepcopy", "numpy.zeros_like" ]
[((346, 425), 'collections.namedtuple', 'namedtuple', (['"""SurfaceTuple"""', "['pdgid', 'nevents', 'energy_dist', 'spatial_dist']"], {}), "('SurfaceTuple', ['pdgid', 'nevents', 'energy_dist', 'spatial_dist'])\n", (356, 425), False, 'from collections import namedtuple\n'), ((1557, 1571), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (1565, 1571), False, 'from copy import deepcopy\n'), ((2025, 2039), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (2033, 2039), False, 'from copy import deepcopy\n'), ((2677, 2695), 'numpy.asarray', 'np.asarray', (['energy'], {}), '(energy)\n', (2687, 2695), True, 'import numpy as np\n'), ((2714, 2733), 'numpy.asarray', 'np.asarray', (['cos_zen'], {}), '(cos_zen)\n', (2724, 2733), True, 'import numpy as np\n'), ((2750, 2784), 'numpy.zeros_like', 'np.zeros_like', (['energy'], {'dtype': 'float'}), '(energy, dtype=float)\n', (2763, 2784), True, 'import numpy as np\n'), ((2807, 2823), 'numpy.unique', 'np.unique', (['pdgid'], {}), '(pdgid)\n', (2816, 2823), True, 'import numpy as np\n'), ((3982, 3999), 'numpy.isfinite', 'np.isfinite', (['emin'], {}), '(emin)\n', (3993, 3999), True, 'import numpy as np\n'), ((4015, 4032), 'numpy.isfinite', 'np.isfinite', (['emax'], {}), '(emax)\n', (4026, 4032), True, 'import numpy as np\n'), ((4688, 4706), 'numpy.isfinite', 'np.isfinite', (['czmin'], {}), '(czmin)\n', (4699, 4706), True, 'import numpy as np\n'), ((4722, 4740), 'numpy.isfinite', 'np.isfinite', (['czmax'], {}), '(czmax)\n', (4733, 4740), True, 'import numpy as np\n'), ((2874, 2886), 'numpy.any', 'np.any', (['mask'], {}), '(mask)\n', (2880, 2886), True, 'import numpy as np\n'), ((1450, 1467), 'copy.deepcopy', 'deepcopy', (['surface'], {}), '(surface)\n', (1458, 1467), False, 'from copy import deepcopy\n')]
from calendar import timegm from datetime import datetime from ephem import Moon, Observer, constellation, next_full_moon, next_new_moon from numpy import rad2deg from app.business.astronomy.planets.models import Planet, PlanetType, SolarSystem class ObserverBuilder: def __init__(self, latitude: str, longitude: str, altitude: str): self.latitude = latitude self.longitude = longitude self.altitude = altitude def build(self) -> Observer: observer = Observer() observer.lat = self.latitude observer.lon = self.longitude observer.elevation = self.altitude return observer class PlanetBuilder: def __init__(self, observer: Observer) -> None: self.__observer = observer def build(self, planet_type: PlanetType) -> Planet: ephem_planet = planet_type() ephem_planet.compute(self.__observer) data = { "name": ephem_planet.name, "sun_distance": "{0:.5f}".format(ephem_planet.sun_distance), "earth_distance": "{0:.5f}".format(ephem_planet.earth_distance), "phase": int(ephem_planet.phase), "zodiac": constellation(ephem_planet)[1].lower(), "ra": ephem_planet.ra, "dec": ephem_planet.dec, "altitude": "{0:.2f}".format(rad2deg(ephem_planet.alt)), "azimut": "{0:.2f}".format(rad2deg(ephem_planet.az)), "mag": "{0:.2f}".format(ephem_planet.mag), } planet = Planet(**data) if isinstance(ephem_planet, Moon): dtime = datetime.utcnow() planet.moon_phase = int(ephem_planet.moon_phase * 100) planet.next_new_moon = timegm(next_new_moon(dtime).datetime().timetuple()) planet.next_full_moon = timegm(next_full_moon(dtime).datetime().timetuple()) return planet class SolarSystemBuilder: def __init__(self, latitude: str, longitude: str, altitude: str): self.latitude = latitude self.longitude = longitude self.altitude = altitude def build(self): observer = ObserverBuilder(self.latitude, self.longitude, self.altitude).build() planet_builder = PlanetBuilder(observer) solar_system: dict[str:Planet] = { planet_type.name.title(): planet_builder.build(planet_type.value) for planet_type in PlanetType } return SolarSystem(**solar_system)
[ "ephem.Observer", "datetime.datetime.utcnow", "app.business.astronomy.planets.models.Planet", "ephem.next_new_moon", "ephem.constellation", "ephem.next_full_moon", "numpy.rad2deg", "app.business.astronomy.planets.models.SolarSystem" ]
[((496, 506), 'ephem.Observer', 'Observer', ([], {}), '()\n', (504, 506), False, 'from ephem import Moon, Observer, constellation, next_full_moon, next_new_moon\n'), ((1502, 1516), 'app.business.astronomy.planets.models.Planet', 'Planet', ([], {}), '(**data)\n', (1508, 1516), False, 'from app.business.astronomy.planets.models import Planet, PlanetType, SolarSystem\n'), ((2410, 2437), 'app.business.astronomy.planets.models.SolarSystem', 'SolarSystem', ([], {}), '(**solar_system)\n', (2421, 2437), False, 'from app.business.astronomy.planets.models import Planet, PlanetType, SolarSystem\n'), ((1580, 1597), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (1595, 1597), False, 'from datetime import datetime\n'), ((1326, 1351), 'numpy.rad2deg', 'rad2deg', (['ephem_planet.alt'], {}), '(ephem_planet.alt)\n', (1333, 1351), False, 'from numpy import rad2deg\n'), ((1393, 1417), 'numpy.rad2deg', 'rad2deg', (['ephem_planet.az'], {}), '(ephem_planet.az)\n', (1400, 1417), False, 'from numpy import rad2deg\n'), ((1173, 1200), 'ephem.constellation', 'constellation', (['ephem_planet'], {}), '(ephem_planet)\n', (1186, 1200), False, 'from ephem import Moon, Observer, constellation, next_full_moon, next_new_moon\n'), ((1707, 1727), 'ephem.next_new_moon', 'next_new_moon', (['dtime'], {}), '(dtime)\n', (1720, 1727), False, 'from ephem import Moon, Observer, constellation, next_full_moon, next_new_moon\n'), ((1795, 1816), 'ephem.next_full_moon', 'next_full_moon', (['dtime'], {}), '(dtime)\n', (1809, 1816), False, 'from ephem import Moon, Observer, constellation, next_full_moon, next_new_moon\n')]
# Copyright 2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Labudde tests""" import math import numpy as np import thewalrus.charpoly import pytest @pytest.mark.parametrize("phi", [0.1, 0.2, 0.3]) def test_labudde_2by2(phi): """Test that the La Budde algorithm produces the correct characteristic polynomial from https://en.wikipedia.org/wiki/Characteristic_polynomial.""" sinh_phi = math.sinh(phi) cosh_phi = math.cosh(phi) mat = np.array([[cosh_phi, sinh_phi], [sinh_phi, cosh_phi]]) charpoly = thewalrus.charpoly.charpoly(mat) assert np.allclose(charpoly[0], -2 * cosh_phi) assert np.allclose(charpoly[1], 1) @pytest.mark.parametrize("n", [1, 2, 3]) def test_powtrace_2by2(n): """Consistency test between power_trace_eigen and powertrace""" phi = 0.1 * math.pi sinh_phi = math.sinh(phi) cosh_phi = math.cosh(phi) mat = np.array([[cosh_phi, sinh_phi], [sinh_phi, cosh_phi]]) pow_trace_lab = thewalrus.charpoly.powertrace(mat, n + 1) # Use wolfram alpha to verify with: # Trace[[[1.04975523, 0.31935254], [0.31935254, 1.04975523]]^1] # Trace[[[1.04975523, 0.31935254], [0.31935254, 1.04975523]]^2] # Trace[[[1.04975523, 0.31935254], [0.31935254, 1.04975523]]^3] if n == 1: assert np.allclose(pow_trace_lab[-1], 2.09951) if n == 2: assert np.allclose(pow_trace_lab[-1], 2.40794) if n == 3: assert np.allclose(pow_trace_lab[-1], 2.95599) @pytest.mark.parametrize("n", [1, 2, 4]) def test_powtrace_4by4(n): """Consistency test between power_trace_eigen and powertrace""" mat = np.array( [ [1.04975523, 0.31935254, 1, 2], [0.31935254, 1.04975523, 3, 4], [0.31635254, 2.444, 5, 6], [21.31935254, 3.14975523, 7, 8], ] ) pow_trace_lab = thewalrus.charpoly.powertrace(mat, n + 1) if n == 1: assert np.allclose(pow_trace_lab[-1], 15.0995) if n == 2: assert np.allclose(pow_trace_lab[-1], 301.18) if n == 4: assert np.allclose(pow_trace_lab[-1], 81466.1)
[ "numpy.allclose", "pytest.mark.parametrize", "numpy.array", "math.cosh", "math.sinh" ]
[((688, 735), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""phi"""', '[0.1, 0.2, 0.3]'], {}), "('phi', [0.1, 0.2, 0.3])\n", (711, 735), False, 'import pytest\n'), ((1186, 1225), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n"""', '[1, 2, 3]'], {}), "('n', [1, 2, 3])\n", (1209, 1225), False, 'import pytest\n'), ((1991, 2030), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n"""', '[1, 2, 4]'], {}), "('n', [1, 2, 4])\n", (2014, 2030), False, 'import pytest\n'), ((935, 949), 'math.sinh', 'math.sinh', (['phi'], {}), '(phi)\n', (944, 949), False, 'import math\n'), ((965, 979), 'math.cosh', 'math.cosh', (['phi'], {}), '(phi)\n', (974, 979), False, 'import math\n'), ((990, 1044), 'numpy.array', 'np.array', (['[[cosh_phi, sinh_phi], [sinh_phi, cosh_phi]]'], {}), '([[cosh_phi, sinh_phi], [sinh_phi, cosh_phi]])\n', (998, 1044), True, 'import numpy as np\n'), ((1104, 1143), 'numpy.allclose', 'np.allclose', (['charpoly[0]', '(-2 * cosh_phi)'], {}), '(charpoly[0], -2 * cosh_phi)\n', (1115, 1143), True, 'import numpy as np\n'), ((1155, 1182), 'numpy.allclose', 'np.allclose', (['charpoly[1]', '(1)'], {}), '(charpoly[1], 1)\n', (1166, 1182), True, 'import numpy as np\n'), ((1360, 1374), 'math.sinh', 'math.sinh', (['phi'], {}), '(phi)\n', (1369, 1374), False, 'import math\n'), ((1390, 1404), 'math.cosh', 'math.cosh', (['phi'], {}), '(phi)\n', (1399, 1404), False, 'import math\n'), ((1415, 1469), 'numpy.array', 'np.array', (['[[cosh_phi, sinh_phi], [sinh_phi, cosh_phi]]'], {}), '([[cosh_phi, sinh_phi], [sinh_phi, cosh_phi]])\n', (1423, 1469), True, 'import numpy as np\n'), ((2137, 2276), 'numpy.array', 'np.array', (['[[1.04975523, 0.31935254, 1, 2], [0.31935254, 1.04975523, 3, 4], [\n 0.31635254, 2.444, 5, 6], [21.31935254, 3.14975523, 7, 8]]'], {}), '([[1.04975523, 0.31935254, 1, 2], [0.31935254, 1.04975523, 3, 4], [\n 0.31635254, 2.444, 5, 6], [21.31935254, 3.14975523, 7, 8]])\n', (2145, 2276), True, 'import numpy as np\n'), ((1808, 1847), 'numpy.allclose', 'np.allclose', (['pow_trace_lab[-1]', '(2.09951)'], {}), '(pow_trace_lab[-1], 2.09951)\n', (1819, 1847), True, 'import numpy as np\n'), ((1878, 1917), 'numpy.allclose', 'np.allclose', (['pow_trace_lab[-1]', '(2.40794)'], {}), '(pow_trace_lab[-1], 2.40794)\n', (1889, 1917), True, 'import numpy as np\n'), ((1948, 1987), 'numpy.allclose', 'np.allclose', (['pow_trace_lab[-1]', '(2.95599)'], {}), '(pow_trace_lab[-1], 2.95599)\n', (1959, 1987), True, 'import numpy as np\n'), ((2437, 2476), 'numpy.allclose', 'np.allclose', (['pow_trace_lab[-1]', '(15.0995)'], {}), '(pow_trace_lab[-1], 15.0995)\n', (2448, 2476), True, 'import numpy as np\n'), ((2507, 2545), 'numpy.allclose', 'np.allclose', (['pow_trace_lab[-1]', '(301.18)'], {}), '(pow_trace_lab[-1], 301.18)\n', (2518, 2545), True, 'import numpy as np\n'), ((2576, 2615), 'numpy.allclose', 'np.allclose', (['pow_trace_lab[-1]', '(81466.1)'], {}), '(pow_trace_lab[-1], 81466.1)\n', (2587, 2615), True, 'import numpy as np\n')]
import numpy as np def computeCostMulti(X, y, theta): """ computes the cost of using theta as the parameter for linear regression to fit the data points in X and y """ m = y.size J = 0. # ====================== YOUR CODE HERE ====================== # Instructions: Compute the cost of a particular choice of theta for i in range(m): h_theta = np.dot(X[i, :], theta) J = (h_theta - y[i]) ** 2 J *= 1 / (2 * m) # ============================================================ return J[0]
[ "numpy.dot" ]
[((396, 418), 'numpy.dot', 'np.dot', (['X[i, :]', 'theta'], {}), '(X[i, :], theta)\n', (402, 418), True, 'import numpy as np\n')]
import torch import numpy as np from hparams import create_hparams as hps def mode(obj, model = False): if model and hps.is_cuda: obj = obj.cuda() elif hps.is_cuda: obj = obj.cuda(non_blocking = hps.pin_mem) return obj def to_arr(var): return var.cpu().detach().numpy().astype(np.float32) def get_mask_from_lengths(lengths, pad = False): max_len = torch.max(lengths).item() if pad and max_len%hps.n_frames_per_step != 0: max_len += hps.n_frames_per_step - max_len%hps.n_frames_per_step assert max_len%hps.n_frames_per_step == 0 ids = torch.arange(0, max_len, out = torch.LongTensor(max_len)) ids = mode(ids) mask = (ids < lengths.unsqueeze(1)) return mask import scipy import librosa import librosa.filters import numpy as np from scipy.io import wavfile from hparams import hparams as hps def load_wav(path): sr, wav = wavfile.read(path) wav = wav.astype(np.float32) wav = wav / np.max(np.abs(wav)) try: assert sr == hps.sample_rate except: print('Error:', path, 'has wrong sample rate.') return wav def save_wav(wav, path): wav *= 32767 / max(0.01, np.max(np.abs(wav))) wavfile.write(path, hps.sample_rate, wav.astype(np.int16)) def preemphasis(x): return scipy.signal.lfilter([1, -hps.preemphasis], [1], x) def inv_preemphasis(x): return scipy.signal.lfilter([1], [1, -hps.preemphasis], x) def spectrogram(y): D = _stft(preemphasis(y)) S = _amp_to_db(np.abs(D)) - hps.ref_level_db return _normalize(S) def inv_spectrogram(spectrogram): '''Converts spectrogram to waveform using librosa''' S = _db_to_amp(_denormalize(spectrogram) + hps.ref_level_db) # Convert back to linear return inv_preemphasis(_griffin_lim(S ** hps.power)) # Reconstruct phase def melspectrogram(y): D = _stft(preemphasis(y)) S = _amp_to_db(_linear_to_mel(np.abs(D))) - hps.ref_level_db return _normalize(S) def inv_melspectrogram(spectrogram): mel = _db_to_amp(_denormalize(spectrogram) + hps.ref_level_db) S = _mel_to_linear(mel) return inv_preemphasis(_griffin_lim(S ** hps.power)) def find_endpoint(wav, threshold_db=-40, min_silence_sec=0.8): window_length = int(hps.sample_rate * min_silence_sec) hop_length = int(window_length / 4) threshold = _db_to_amp(threshold_db) for x in range(hop_length, len(wav) - window_length, hop_length): if np.max(wav[x:x + window_length]) < threshold: return x + hop_length return len(wav) def _griffin_lim(S): '''librosa implementation of Griffin-Lim Based on https://github.com/librosa/librosa/issues/434 ''' angles = np.exp(2j * np.pi * np.random.rand(*S.shape)) S_complex = np.abs(S).astype(np.complex) y = _istft(S_complex * angles) for i in range(hps.gl_iters): angles = np.exp(1j * np.angle(_stft(y))) y = _istft(S_complex * angles) return y def _stft(y): n_fft, hop_length, win_length = _stft_parameters() return librosa.stft(y=y, n_fft=n_fft, hop_length=hop_length, win_length=win_length) def _istft(y): _, hop_length, win_length = _stft_parameters() return librosa.istft(y, hop_length=hop_length, win_length=win_length) def _stft_parameters(): return (hps.num_freq - 1) * 2, hps.frame_shift, hps.frame_length # Conversions: _mel_basis = None def _linear_to_mel(spectrogram): global _mel_basis if _mel_basis is None: _mel_basis = _build_mel_basis() return np.dot(_mel_basis, spectrogram) def _mel_to_linear(spectrogram): global _mel_basis if _mel_basis is None: _mel_basis = _build_mel_basis() inv_mel_basis = np.linalg.pinv(_mel_basis) inverse = np.dot(inv_mel_basis, spectrogram) inverse = np.maximum(1e-10, inverse) return inverse def _build_mel_basis(): n_fft = (hps.num_freq - 1) * 2 return librosa.filters.mel(hps.sample_rate, n_fft, n_mels=hps.num_mels, fmin=hps.fmin, fmax=hps.fmax) def _amp_to_db(x): return 20 * np.log10(np.maximum(1e-5, x)) def _db_to_amp(x): return np.power(10.0, x * 0.05) def _normalize(S): return np.clip((S - hps.min_level_db) / -hps.min_level_db, 0, 1) def _denormalize(S): return (np.clip(S, 0, 1) * -hps.min_level_db) + hps.min_level_db import glob import sys import os from pydub import AudioSegment def concat_Audio(utterances): Full_audio=AudioSegment.empty() for audio in utterances: Full_audio.extend(audio) return Full_audio
[ "librosa.istft", "numpy.clip", "numpy.abs", "pydub.AudioSegment.empty", "numpy.linalg.pinv", "numpy.random.rand", "numpy.power", "torch.LongTensor", "torch.max", "numpy.max", "numpy.dot", "scipy.signal.lfilter", "scipy.io.wavfile.read", "librosa.filters.mel", "librosa.stft", "numpy.max...
[((849, 867), 'scipy.io.wavfile.read', 'wavfile.read', (['path'], {}), '(path)\n', (861, 867), False, 'from scipy.io import wavfile\n'), ((1239, 1290), 'scipy.signal.lfilter', 'scipy.signal.lfilter', (['[1, -hps.preemphasis]', '[1]', 'x'], {}), '([1, -hps.preemphasis], [1], x)\n', (1259, 1290), False, 'import scipy\n'), ((1328, 1379), 'scipy.signal.lfilter', 'scipy.signal.lfilter', (['[1]', '[1, -hps.preemphasis]', 'x'], {}), '([1], [1, -hps.preemphasis], x)\n', (1348, 1379), False, 'import scipy\n'), ((2981, 3057), 'librosa.stft', 'librosa.stft', ([], {'y': 'y', 'n_fft': 'n_fft', 'hop_length': 'hop_length', 'win_length': 'win_length'}), '(y=y, n_fft=n_fft, hop_length=hop_length, win_length=win_length)\n', (2993, 3057), False, 'import librosa\n'), ((3137, 3199), 'librosa.istft', 'librosa.istft', (['y'], {'hop_length': 'hop_length', 'win_length': 'win_length'}), '(y, hop_length=hop_length, win_length=win_length)\n', (3150, 3199), False, 'import librosa\n'), ((3466, 3497), 'numpy.dot', 'np.dot', (['_mel_basis', 'spectrogram'], {}), '(_mel_basis, spectrogram)\n', (3472, 3497), True, 'import numpy as np\n'), ((3642, 3668), 'numpy.linalg.pinv', 'np.linalg.pinv', (['_mel_basis'], {}), '(_mel_basis)\n', (3656, 3668), True, 'import numpy as np\n'), ((3683, 3717), 'numpy.dot', 'np.dot', (['inv_mel_basis', 'spectrogram'], {}), '(inv_mel_basis, spectrogram)\n', (3689, 3717), True, 'import numpy as np\n'), ((3732, 3758), 'numpy.maximum', 'np.maximum', (['(1e-10)', 'inverse'], {}), '(1e-10, inverse)\n', (3742, 3758), True, 'import numpy as np\n'), ((3850, 3949), 'librosa.filters.mel', 'librosa.filters.mel', (['hps.sample_rate', 'n_fft'], {'n_mels': 'hps.num_mels', 'fmin': 'hps.fmin', 'fmax': 'hps.fmax'}), '(hps.sample_rate, n_fft, n_mels=hps.num_mels, fmin=hps.\n fmin, fmax=hps.fmax)\n', (3869, 3949), False, 'import librosa\n'), ((4044, 4068), 'numpy.power', 'np.power', (['(10.0)', '(x * 0.05)'], {}), '(10.0, x * 0.05)\n', (4052, 4068), True, 'import numpy as np\n'), ((4101, 4158), 'numpy.clip', 'np.clip', (['((S - hps.min_level_db) / -hps.min_level_db)', '(0)', '(1)'], {}), '((S - hps.min_level_db) / -hps.min_level_db, 0, 1)\n', (4108, 4158), True, 'import numpy as np\n'), ((4360, 4380), 'pydub.AudioSegment.empty', 'AudioSegment.empty', ([], {}), '()\n', (4378, 4380), False, 'from pydub import AudioSegment\n'), ((360, 378), 'torch.max', 'torch.max', (['lengths'], {}), '(lengths)\n', (369, 378), False, 'import torch\n'), ((583, 608), 'torch.LongTensor', 'torch.LongTensor', (['max_len'], {}), '(max_len)\n', (599, 608), False, 'import torch\n'), ((924, 935), 'numpy.abs', 'np.abs', (['wav'], {}), '(wav)\n', (930, 935), True, 'import numpy as np\n'), ((1451, 1460), 'numpy.abs', 'np.abs', (['D'], {}), '(D)\n', (1457, 1460), True, 'import numpy as np\n'), ((2390, 2422), 'numpy.max', 'np.max', (['wav[x:x + window_length]'], {}), '(wav[x:x + window_length])\n', (2396, 2422), True, 'import numpy as np\n'), ((2658, 2682), 'numpy.random.rand', 'np.random.rand', (['*S.shape'], {}), '(*S.shape)\n', (2672, 2682), True, 'import numpy as np\n'), ((2700, 2709), 'numpy.abs', 'np.abs', (['S'], {}), '(S)\n', (2706, 2709), True, 'import numpy as np\n'), ((3991, 4011), 'numpy.maximum', 'np.maximum', (['(1e-05)', 'x'], {}), '(1e-05, x)\n', (4001, 4011), True, 'import numpy as np\n'), ((4194, 4210), 'numpy.clip', 'np.clip', (['S', '(0)', '(1)'], {}), '(S, 0, 1)\n', (4201, 4210), True, 'import numpy as np\n'), ((1129, 1140), 'numpy.abs', 'np.abs', (['wav'], {}), '(wav)\n', (1135, 1140), True, 'import numpy as np\n'), ((1857, 1866), 'numpy.abs', 'np.abs', (['D'], {}), '(D)\n', (1863, 1866), True, 'import numpy as np\n')]
import numpy as np import torch as torch import numpy as np import torch as torch from scipy.interpolate import griddata import torch.nn.functional as F import torch.nn as nn # import audtorch import piq def calculate_CC_metrics(pred, gt): """ Calculate CC Metrics :param pred: :param gt: :return: """ if isinstance(pred, np.ndarray) and isinstance(gt, np.ndarray): pccs = 0 for i in range(pred.shape[0]): if len(pred.shape) == 3: pred_i = pred[i, :, :].reshape(-1) gt_i = gt[i, :, :].reshape(-1) else: pred_i = pred[i, :, :, :].reshape(-1) gt_i = gt[i, :, :, :].reshape(-1) cc = np.corrcoef(pred_i, gt_i)[0, 1] pccs += cc result = pccs / pred.shape[0] else: pred = pred.detach().cpu().numpy() gt = gt.detach().cpu().numpy() pccs = 0 for i in range(pred.shape[0]): if len(pred.shape) == 3: pred_i = pred[i, :, :].reshape(-1) gt_i = gt[i, :, :].reshape(-1) else: pred_i = pred[i, :, :, :].reshape(-1) gt_i = gt[i, :, :, :].reshape(-1) cc = np.corrcoef(pred_i, gt_i)[0, 1] pccs += cc result = pccs / pred.shape[0] return result def uv2bmap(uv, background): uv = uv.detach().cpu().numpy() background = background.detach().cpu().numpy() img_bgr = (uv + 1) / 2 # [c h w] img_rgb = img_bgr[::-1, :, :] img_rgb[1, :, :] = 1 - img_rgb[1, :, :] s_x = (img_rgb[0, :, :] * 256) s_y = (img_rgb[1, :, :] * 256) mask = background[0, :, :] > 0 s_x = s_x[mask] s_y = s_y[mask] index = np.argwhere(mask) t_y = index[:, 0] t_x = index[:, 1] x = np.arange(256) y = np.arange(256) xi, yi = np.meshgrid(x, y) # zz = np.zeros((256, 256)) zx = griddata((s_x, s_y), t_x, (xi, yi), method='linear') zy = griddata((s_x, s_y), t_y, (xi, yi), method='linear') # backward_img = np.stack([zy, zx, zz], axis=2) backward_img = np.stack([zy, zx], axis=2) backward_img[np.isnan(backward_img)] = 0 backward_img = (backward_img / 256) * 2 - 1 # np.save('C:/tmp/'+uv_path.split('/')[-1].split('.')[0]+'_backward',backward_img) # cv2.imwrite('C:/tmp/'+uv_path.split('/')[-1].split('.')[0]+'_backward.png',backward_img*255) return backward_img def uv2bmap4d(uv, background): """input: [batch, channel, h ,w]""" """output: numpy""" batch = uv.size()[0] uv = uv.detach().cpu().numpy() background = background.detach().cpu().numpy() output = np.zeros(shape=(0, 256, 256, 2),dtype=np.float32) for c in range(batch): img_bgr = (uv[c, :, :, :] + 1.) / 2. # [c h w] img_rgb = img_bgr[::-1, :, :] img_rgb[1, :, :] = 1 - img_rgb[1, :, :] s_x = (img_rgb[0, :, :] * 256) s_y = (img_rgb[1, :, :] * 256) mask = background[c, 0, :, :] > 0.1 # 0.6 s_x = s_x[mask] s_y = s_y[mask] index = np.argwhere(mask) t_y = index[:, 0] t_x = index[:, 1] x = np.arange(256) y = np.arange(256) xi, yi = np.meshgrid(x, y) zx = griddata((s_x, s_y), t_x, (xi, yi), method='linear',fill_value=0) zy = griddata((s_x, s_y), t_y, (xi, yi), method='linear',fill_value=0) backward_img = np.stack([zy, zx], axis=2) backward_img = (backward_img / 256.) * 2. - 1. # [h, w, 2] backward_img = np.expand_dims(backward_img, axis=0) output = np.concatenate((output, backward_img), 0) return output def bw_mapping(bw_map, image, device): image = torch.unsqueeze(image, 0) # [1, 3, 256, 256] image_t = image.transpose(2, 3) # b c h w # bw # from [h, w, 2] # to 4D tensor [-1, 1] [b, h, w, 2] bw_map = torch.from_numpy(bw_map).type(torch.float32).to(device) # numpy to tensor bw_map = torch.unsqueeze(bw_map, 0) # bw_map = bw_map.transpose(1, 2).transpose(2, 3) output = F.grid_sample(input=image, grid=bw_map, align_corners=True) output_t = F.grid_sample(input=image_t, grid=bw_map, align_corners=True) # tensor output = output.transpose(1, 2).transpose(2, 3) output = output.squeeze() output_t = output_t.transpose(1, 2).transpose(2, 3) output_t = output_t.squeeze() return output_t # transpose(1,2).transpose(0,1) # ensure output [c, h, w] def bw_mapping4d(bw_map, image, device): """image""" # [batch, 3, 256, 256] image_t = image.transpose(2, 3) # b c h w # bw # from [h, w, 2] # to 4D tensor [-1, 1] [b, h, w, 2] bw_map = torch.from_numpy(bw_map).type(torch.float32).to(device) # bw_map = torch.unsqueeze(bw_map, 0) # bw_map = bw_map.transpose(1, 2).transpose(2, 3) output = F.grid_sample(input=image, grid=bw_map, align_corners=True) output_t = F.grid_sample(input=image_t, grid=bw_map, align_corners=True) output = output.transpose(1, 2).transpose(2, 3) output = output.squeeze() output_t = output_t.transpose(1, 2).transpose(2, 3) output_t = output_t.squeeze() return output_t # transpose(1,2).transpose(0,1) # ensure output [c, h, w] class film_metrics(nn.Module): def __init__(self, l1_norm=True, mse=True, pearsonr=True, cc=True, psnr=True, ssim=True, mssim=True): super(film_metrics, self).__init__() self.l1_norm = l1_norm self.mse = mse self.pearsonr = pearsonr self.cc = cc self.psnr = psnr self.ssim =ssim self.mssim = mssim def forward(self, predict, target): if self.l1_norm: l1_norm_metric = nn.functional.l1_loss(predict, target) if self.mse: mse_norm_metric = nn.functional.mse_loss(predict, target) if self.pearsonr: pearsonr_metric = audtorch.metrics.functional.pearsonr(predict, target).mean() if self.cc: cc_metric = audtorch.metrics.functional.concordance_cc(predict, target).mean() if self.psnr: psnr_metric = piq.psnr(predict, target, data_range=1., reduction='none').mean() if self.ssim: ssim_metric = piq.ssim(predict, target, data_range=1.) if self.mssim: mssim_metric = piq.multi_scale_ssim(predict, target, data_range=1.) metric_summary = {'l1_norm': l1_norm_metric, 'mse': mse_norm_metric, 'pearsonr_metric': pearsonr_metric, 'cc': cc_metric, 'psnr': psnr_metric, 'ssim': ssim_metric, 'mssim': mssim_metric } return metric_summary
[ "torch.nn.functional.grid_sample", "torch.nn.functional.l1_loss", "torch.nn.functional.mse_loss", "numpy.corrcoef", "torch.unsqueeze", "scipy.interpolate.griddata", "piq.multi_scale_ssim", "torch.from_numpy", "numpy.stack", "numpy.zeros", "numpy.argwhere", "numpy.isnan", "numpy.expand_dims",...
[((1740, 1757), 'numpy.argwhere', 'np.argwhere', (['mask'], {}), '(mask)\n', (1751, 1757), True, 'import numpy as np\n'), ((1810, 1824), 'numpy.arange', 'np.arange', (['(256)'], {}), '(256)\n', (1819, 1824), True, 'import numpy as np\n'), ((1833, 1847), 'numpy.arange', 'np.arange', (['(256)'], {}), '(256)\n', (1842, 1847), True, 'import numpy as np\n'), ((1861, 1878), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (1872, 1878), True, 'import numpy as np\n'), ((1920, 1972), 'scipy.interpolate.griddata', 'griddata', (['(s_x, s_y)', 't_x', '(xi, yi)'], {'method': '"""linear"""'}), "((s_x, s_y), t_x, (xi, yi), method='linear')\n", (1928, 1972), False, 'from scipy.interpolate import griddata\n'), ((1982, 2034), 'scipy.interpolate.griddata', 'griddata', (['(s_x, s_y)', 't_y', '(xi, yi)'], {'method': '"""linear"""'}), "((s_x, s_y), t_y, (xi, yi), method='linear')\n", (1990, 2034), False, 'from scipy.interpolate import griddata\n'), ((2106, 2132), 'numpy.stack', 'np.stack', (['[zy, zx]'], {'axis': '(2)'}), '([zy, zx], axis=2)\n', (2114, 2132), True, 'import numpy as np\n'), ((2663, 2713), 'numpy.zeros', 'np.zeros', ([], {'shape': '(0, 256, 256, 2)', 'dtype': 'np.float32'}), '(shape=(0, 256, 256, 2), dtype=np.float32)\n', (2671, 2713), True, 'import numpy as np\n'), ((3701, 3726), 'torch.unsqueeze', 'torch.unsqueeze', (['image', '(0)'], {}), '(image, 0)\n', (3716, 3726), True, 'import torch as torch\n'), ((3966, 3992), 'torch.unsqueeze', 'torch.unsqueeze', (['bw_map', '(0)'], {}), '(bw_map, 0)\n', (3981, 3992), True, 'import torch as torch\n'), ((4060, 4119), 'torch.nn.functional.grid_sample', 'F.grid_sample', ([], {'input': 'image', 'grid': 'bw_map', 'align_corners': '(True)'}), '(input=image, grid=bw_map, align_corners=True)\n', (4073, 4119), True, 'import torch.nn.functional as F\n'), ((4135, 4196), 'torch.nn.functional.grid_sample', 'F.grid_sample', ([], {'input': 'image_t', 'grid': 'bw_map', 'align_corners': '(True)'}), '(input=image_t, grid=bw_map, align_corners=True)\n', (4148, 4196), True, 'import torch.nn.functional as F\n'), ((4841, 4900), 'torch.nn.functional.grid_sample', 'F.grid_sample', ([], {'input': 'image', 'grid': 'bw_map', 'align_corners': '(True)'}), '(input=image, grid=bw_map, align_corners=True)\n', (4854, 4900), True, 'import torch.nn.functional as F\n'), ((4916, 4977), 'torch.nn.functional.grid_sample', 'F.grid_sample', ([], {'input': 'image_t', 'grid': 'bw_map', 'align_corners': '(True)'}), '(input=image_t, grid=bw_map, align_corners=True)\n', (4929, 4977), True, 'import torch.nn.functional as F\n'), ((2150, 2172), 'numpy.isnan', 'np.isnan', (['backward_img'], {}), '(backward_img)\n', (2158, 2172), True, 'import numpy as np\n'), ((3076, 3093), 'numpy.argwhere', 'np.argwhere', (['mask'], {}), '(mask)\n', (3087, 3093), True, 'import numpy as np\n'), ((3158, 3172), 'numpy.arange', 'np.arange', (['(256)'], {}), '(256)\n', (3167, 3172), True, 'import numpy as np\n'), ((3185, 3199), 'numpy.arange', 'np.arange', (['(256)'], {}), '(256)\n', (3194, 3199), True, 'import numpy as np\n'), ((3217, 3234), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (3228, 3234), True, 'import numpy as np\n'), ((3248, 3314), 'scipy.interpolate.griddata', 'griddata', (['(s_x, s_y)', 't_x', '(xi, yi)'], {'method': '"""linear"""', 'fill_value': '(0)'}), "((s_x, s_y), t_x, (xi, yi), method='linear', fill_value=0)\n", (3256, 3314), False, 'from scipy.interpolate import griddata\n'), ((3327, 3393), 'scipy.interpolate.griddata', 'griddata', (['(s_x, s_y)', 't_y', '(xi, yi)'], {'method': '"""linear"""', 'fill_value': '(0)'}), "((s_x, s_y), t_y, (xi, yi), method='linear', fill_value=0)\n", (3335, 3393), False, 'from scipy.interpolate import griddata\n'), ((3416, 3442), 'numpy.stack', 'np.stack', (['[zy, zx]'], {'axis': '(2)'}), '([zy, zx], axis=2)\n', (3424, 3442), True, 'import numpy as np\n'), ((3534, 3570), 'numpy.expand_dims', 'np.expand_dims', (['backward_img'], {'axis': '(0)'}), '(backward_img, axis=0)\n', (3548, 3570), True, 'import numpy as np\n'), ((3588, 3629), 'numpy.concatenate', 'np.concatenate', (['(output, backward_img)', '(0)'], {}), '((output, backward_img), 0)\n', (3602, 3629), True, 'import numpy as np\n'), ((5703, 5741), 'torch.nn.functional.l1_loss', 'nn.functional.l1_loss', (['predict', 'target'], {}), '(predict, target)\n', (5724, 5741), True, 'import torch.nn as nn\n'), ((5793, 5832), 'torch.nn.functional.mse_loss', 'nn.functional.mse_loss', (['predict', 'target'], {}), '(predict, target)\n', (5815, 5832), True, 'import torch.nn as nn\n'), ((6223, 6264), 'piq.ssim', 'piq.ssim', (['predict', 'target'], {'data_range': '(1.0)'}), '(predict, target, data_range=1.0)\n', (6231, 6264), False, 'import piq\n'), ((6314, 6367), 'piq.multi_scale_ssim', 'piq.multi_scale_ssim', (['predict', 'target'], {'data_range': '(1.0)'}), '(predict, target, data_range=1.0)\n', (6334, 6367), False, 'import piq\n'), ((724, 749), 'numpy.corrcoef', 'np.corrcoef', (['pred_i', 'gt_i'], {}), '(pred_i, gt_i)\n', (735, 749), True, 'import numpy as np\n'), ((1239, 1264), 'numpy.corrcoef', 'np.corrcoef', (['pred_i', 'gt_i'], {}), '(pred_i, gt_i)\n', (1250, 1264), True, 'import numpy as np\n'), ((3878, 3902), 'torch.from_numpy', 'torch.from_numpy', (['bw_map'], {}), '(bw_map)\n', (3894, 3902), True, 'import torch as torch\n'), ((4676, 4700), 'torch.from_numpy', 'torch.from_numpy', (['bw_map'], {}), '(bw_map)\n', (4692, 4700), True, 'import torch as torch\n'), ((6109, 6168), 'piq.psnr', 'piq.psnr', (['predict', 'target'], {'data_range': '(1.0)', 'reduction': '"""none"""'}), "(predict, target, data_range=1.0, reduction='none')\n", (6117, 6168), False, 'import piq\n')]
import argparse import os import numpy as np import sys import json from os import listdir import csv from os.path import isfile, join from face_network import create_face_network import cv2 import argparse from keras.optimizers import Adam, SGD from keras.models import load_model from emotion_model import * from utils.datasets import get_labels from utils.inference import detect_faces from utils.inference import draw_text from utils.inference import draw_bounding_box from utils.inference import apply_offsets from utils.inference import load_detection_model from utils.inference import load_image from utils.preprocessor import preprocess_input from tempfile import TemporaryFile from keras.backend import tf as ktf from pprint import pprint import urllib.request import shutil import h5py import dlib import matplotlib.pyplot as plt import tensorflow as tf from imutils.face_utils import FaceAligner from imutils.face_utils import rect_to_bb import inception_resnet_v1 from tqdm import tqdm from pathlib import Path from keras.utils.data_utils import get_file import sys from keras.models import load_model from keras.models import Sequential from keras.models import load_model import numpy as np from time import gmtime, strftime os.environ['CUDA_VISIBLE_DEVICES'] = '' class Person_Input(): global model_creation_path global shape_detector global detection_model_path global emotion_model_path global gender_model_path global age_model_path global ethnic_model_path global ETHNIC model_creation_path = "./models/" shape_detector = "shape_predictor_68_face_landmarks.dat" detection_model_path = '../trained_models/detection_models/haarcascade_frontalface_default.xml' emotion_model_path = '../trained_models/emotion_models/fer2013_mini_XCEPTION.102-0.66.hdf5' gender_model_path = '../trained_models/gender_models/simple_CNN.81-0.96.hdf5' #For another way to calculate age. #age_model_path = '../trained_models/age_models/weights.25000-0.03.hdf5' ethnic_model_path = '../trained_models/ethnic_models/weights_ethnic.hdf5' ETHNIC = {0: 'Asian', 1: 'Caucasian', 2: "African", 3: "Hispanic"} def __init__(self, path_to_image): self.path_to_image = path_to_image def get_emotion(self, image_path_, face_detection, emotion_classifier, gender_classifier): emotion_labels = get_labels('fer2013') # hyper-parameters for bounding boxes shape # change for variance emotion_offsets = (20, 40) emotion_offsets = (0, 0) # loading models # getting input model shapes for inference emotion_target_size = emotion_classifier.input_shape[1:3] # loading images rgb_image = load_image(image_path_, grayscale=False) gray_image = load_image(image_path_, grayscale=True) gray_image = np.squeeze(gray_image) gray_image = gray_image.astype('uint8') faces = detect_faces(face_detection, gray_image) for face_coordinates in faces: x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets) gray_face = gray_image[y1:y2, x1:x2] rgb_face = rgb_image[y1:y2, x1:x2] try: gray_face = cv2.resize(gray_face, (emotion_target_size)) rgb_face = rgb_image[y1:y2, x1:x2] except: continue rgb_face = preprocess_input(rgb_face, False) rgb_face = np.expand_dims(rgb_face, 0) gray_face = preprocess_input(gray_face, True) gray_face = np.expand_dims(gray_face, 0) gray_face = np.expand_dims(gray_face, -1) emotion_label_arg = np.argmax(emotion_classifier.predict(gray_face)) emotion_text = emotion_labels[emotion_label_arg] return emotion_text def get_gender(self, image_path_, face_detection, emotion_classifier, gender_classifier): gender_labels = get_labels('imdb') # hyper-parameters for bounding boxes shape # change for variance gender_offsets = (30, 60) gender_offsets = (10, 10) emotion_offsets = (20, 40) emotion_offsets = (0, 0) # loading models # getting input model shapes for inference gender_target_size = gender_classifier.input_shape[1:3] # loading images rgb_image = load_image(image_path_, grayscale=False) gray_image = load_image(image_path_, grayscale=True) gray_image = np.squeeze(gray_image) gray_image = gray_image.astype('uint8') faces = detect_faces(face_detection, gray_image) for face_coordinates in faces: x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets) gray_face = gray_image[y1:y2, x1:x2] rgb_face = rgb_image[y1:y2, x1:x2] try: rgb_face = cv2.resize(rgb_face, (gender_target_size)) gray_face = cv2.resize(gray_face, (emotion_target_size)) except: continue rgb_face = preprocess_input(rgb_face, False) rgb_face = np.expand_dims(rgb_face, 0) gender_prediction = gender_classifier.predict(rgb_face) gender_label_arg = np.argmax(gender_prediction) gender_text = gender_labels[gender_label_arg] gray_face = preprocess_input(gray_face, True) gray_face = np.expand_dims(gray_face, 0) gray_face = np.expand_dims(gray_face, -1) return gender_text #another way to find age. def get_age2(self, sess,age,gender, train_mode,images_pl, image_path): #image_path = '/Users/adelwang/Documents/Hackery/Gender-Age-Expression/GenderExpression2/images/will.jpg' # for face detection detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") fa = FaceAligner(predictor, desiredFaceWidth=160) # load model and weights img_size = 160 img = cv2.imread(image_path, cv2.IMREAD_COLOR) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) input_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_h, img_w, _ = np.shape(input_img) # detect faces using dlib detector detected = detector(input_img, 1) faces = np.empty((len(detected), img_size, img_size, 3)) for i, d in enumerate(detected): x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height() xw1 = max(int(x1 - 0.4 * w), 0) yw1 = max(int(y1 - 0.4 * h), 0) xw2 = min(int(x2 + 0.4 * w), img_w - 1) yw2 = min(int(y2 + 0.4 * h), img_h - 1) cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2) # cv2.rectangle(img, (xw1, yw1), (xw2, yw2), (255, 0, 0), 2) faces[i, :, :, :] = fa.align(input_img, gray, detected[i]) # faces[i,:,:,:] = cv2.resize(img[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size, img_size)) if len(detected) > 0: # predict ages and genders of the detected faces ages, genders = sess.run([age, gender], feed_dict={images_pl: faces, train_mode: False}) #print(int(ages[i])) #print("F" if genders[i] == 0 else "M") return int(ages[i]) def get_age(self, aligned_images, model_path): with tf.Graph().as_default(): sess = tf.Session() images_pl = tf.placeholder(tf.float32, shape=[None, 160, 160, 3], name='input_image') images = tf.map_fn(lambda frame: tf.reverse_v2(frame, [-1]), images_pl) #BGR TO RGB images_norm = tf.map_fn(lambda frame: tf.image.per_image_standardization(frame), images) train_mode = tf.placeholder(tf.bool) age_logits, gender_logits, _ = inception_resnet_v1.inference(images_norm, keep_probability=0.8, phase_train=train_mode, weight_decay=1e-5) age_ = tf.cast(tf.constant([i for i in range(0, 101)]), tf.float32) age = tf.reduce_sum(tf.multiply(tf.nn.softmax(age_logits), age_)) init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) sess.run(init_op) saver = tf.train.Saver() ckpt = tf.train.get_checkpoint_state(model_path) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) print("restore and continue training!") else: pass return sess.run(age, feed_dict={images_pl: aligned_images, train_mode: False}) #return sess.run([age, gender], feed_dict={images_pl: aligned_images, train_mode: False}) def predict_ethnic(self, name): means = np.load('means_ethnic.npy') model = create_face_network(nb_class=4, hidden_dim=512, shape=(224, 224, 3)) model.load_weights('weights_ethnic.hdf5') im = cv2.imread(name, cv2.IMREAD_COLOR) im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB) im = cv2.resize(im, (224, 224)) im = np.float64(im) im /= 255.0 im = im - means #return model.predict(np.array([im])) return model.predict(np.array([im])) def load_image(self, image_path, shape_predictor): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(shape_predictor) fa = FaceAligner(predictor, desiredFaceWidth=160) image = cv2.imread(image_path, cv2.IMREAD_COLOR) # image = imutils.resize(image, width=256) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) rects = detector(gray, 2) rect_nums = len(rects) XY, aligned_images = [], [] if rect_nums == 0: aligned_images.append(image) return aligned_images, image, rect_nums, XY else: for i in range(rect_nums): aligned_image = fa.align(image, gray, rects[i]) aligned_images.append(aligned_image) (x, y, w, h) = rect_to_bb(rects[i]) image = cv2.rectangle(image, (x, y), (x + w, y + h), color=(255, 0, 0), thickness=2) XY.append((x, y)) return np.array(aligned_images), image, rect_nums, XY def load_network(self, model_path): sess = tf.Session() images_pl = tf.placeholder(tf.float32, shape=[None, 160, 160, 3], name='input_image') images_norm = tf.map_fn(lambda frame: tf.image.per_image_standardization(frame), images_pl) train_mode = tf.placeholder(tf.bool) age_logits, gender_logits, _ = inception_resnet_v1.inference(images_norm, keep_probability=0.8, phase_train=train_mode, weight_decay=1e-5) gender = tf.argmax(tf.nn.softmax(gender_logits), 1) age_ = tf.cast(tf.constant([i for i in range(0, 101)]), tf.float32) age = tf.reduce_sum(tf.multiply(tf.nn.softmax(age_logits), age_), axis=1) init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) sess.run(init_op) saver = tf.train.Saver() ckpt = tf.train.get_checkpoint_state(model_path) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) else: pass return sess,age,gender, train_mode,images_pl def face_detection(self, detection_model_path): global face_detection face_detection = load_detection_model(detection_model_path) return face_detection def getFacialInsights(self, path_to_file): if path_to_file is None: return 0 image_path = '/Users/adelwang/Documents/Hackery/Gender-Age-Expression/GenderExpression2/images/obama1.jpg' path_to_file = '/Users/adelwang/Documents/Hackery/Gender-Age-Expression/GenderExpression2/images' shape_detector = "shape_predictor_68_face_landmarks.dat" model_path = "./models/" person = Person_Input(path_to_file) face_detection = load_detection_model(detection_model_path) emotion_classifier = load_model(emotion_model_path, compile=False) gender_classifier = load_model(gender_model_path, compile=False) #aligned_image, image, rect_nums, XY = person.load_image(image_path, shape_detector) five_insights = [None]*5 count = 0 sess, age_, gender_, train_mode,images_pl = person.load_network("./models") for f in listdir(path_to_file): if isfile(join(path_to_file, f)) and not f.startswith('.'): image_path_= join(path_to_file, f) emotion = person.get_emotion(image_path_, face_detection, emotion_classifier, gender_classifier) gender = person.get_gender(image_path_, face_detection, emotion_classifier, gender_classifier) #Another way to get age. #sess, age, gender_, train_mode,images_pl = person.load_network("./models") #aligned_image, image, rect_nums, XY = person.load_image(image_path_, shape_detector) #age = person.get_age(aligned_image, shape_detector) age = person.get_age2(sess,age_,gender_,train_mode,images_pl, image_path_) result = person.predict_ethnic(image_path) ethnicity = ETHNIC[np.argmax(result)] #one_person_insight_ = {'age':int(age), 'gender':gender, 'expression':emotion, 'ethnicity': ethnicity} one_person_insight_ = {'age':int(age), 'gender':gender, 'expression':emotion} one_person_insight = json.dumps(one_person_insight_) five_insights[count] = one_person_insight count += 1 #print(five_insights) return five_insights #pass in the file name getFacialInsights("fileName", "fileName")
[ "cv2.rectangle", "tensorflow.local_variables_initializer", "numpy.array", "tensorflow.reverse_v2", "tensorflow.nn.softmax", "utils.preprocessor.preprocess_input", "imutils.face_utils.FaceAligner", "tensorflow.Graph", "os.listdir", "numpy.float64", "utils.inference.detect_faces", "tensorflow.Se...
[((12651, 12693), 'utils.inference.load_detection_model', 'load_detection_model', (['detection_model_path'], {}), '(detection_model_path)\n', (12671, 12693), False, 'from utils.inference import load_detection_model\n'), ((12719, 12764), 'keras.models.load_model', 'load_model', (['emotion_model_path'], {'compile': '(False)'}), '(emotion_model_path, compile=False)\n', (12729, 12764), False, 'from keras.models import load_model\n'), ((12789, 12833), 'keras.models.load_model', 'load_model', (['gender_model_path'], {'compile': '(False)'}), '(gender_model_path, compile=False)\n', (12799, 12833), False, 'from keras.models import load_model\n'), ((13065, 13086), 'os.listdir', 'listdir', (['path_to_file'], {}), '(path_to_file)\n', (13072, 13086), False, 'from os import listdir\n'), ((2401, 2422), 'utils.datasets.get_labels', 'get_labels', (['"""fer2013"""'], {}), "('fer2013')\n", (2411, 2422), False, 'from utils.datasets import get_labels\n'), ((2771, 2811), 'utils.inference.load_image', 'load_image', (['image_path_'], {'grayscale': '(False)'}), '(image_path_, grayscale=False)\n', (2781, 2811), False, 'from utils.inference import load_image\n'), ((2833, 2872), 'utils.inference.load_image', 'load_image', (['image_path_'], {'grayscale': '(True)'}), '(image_path_, grayscale=True)\n', (2843, 2872), False, 'from utils.inference import load_image\n'), ((2894, 2916), 'numpy.squeeze', 'np.squeeze', (['gray_image'], {}), '(gray_image)\n', (2904, 2916), True, 'import numpy as np\n'), ((2982, 3022), 'utils.inference.detect_faces', 'detect_faces', (['face_detection', 'gray_image'], {}), '(face_detection, gray_image)\n', (2994, 3022), False, 'from utils.inference import detect_faces\n'), ((4000, 4018), 'utils.datasets.get_labels', 'get_labels', (['"""imdb"""'], {}), "('imdb')\n", (4010, 4018), False, 'from utils.datasets import get_labels\n'), ((4429, 4469), 'utils.inference.load_image', 'load_image', (['image_path_'], {'grayscale': '(False)'}), '(image_path_, grayscale=False)\n', (4439, 4469), False, 'from utils.inference import load_image\n'), ((4491, 4530), 'utils.inference.load_image', 'load_image', (['image_path_'], {'grayscale': '(True)'}), '(image_path_, grayscale=True)\n', (4501, 4530), False, 'from utils.inference import load_image\n'), ((4552, 4574), 'numpy.squeeze', 'np.squeeze', (['gray_image'], {}), '(gray_image)\n', (4562, 4574), True, 'import numpy as np\n'), ((4640, 4680), 'utils.inference.detect_faces', 'detect_faces', (['face_detection', 'gray_image'], {}), '(face_detection, gray_image)\n', (4652, 4680), False, 'from utils.inference import detect_faces\n'), ((5879, 5911), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (5909, 5911), False, 'import dlib\n'), ((5932, 5993), 'dlib.shape_predictor', 'dlib.shape_predictor', (['"""shape_predictor_68_face_landmarks.dat"""'], {}), "('shape_predictor_68_face_landmarks.dat')\n", (5952, 5993), False, 'import dlib\n'), ((6007, 6051), 'imutils.face_utils.FaceAligner', 'FaceAligner', (['predictor'], {'desiredFaceWidth': '(160)'}), '(predictor, desiredFaceWidth=160)\n', (6018, 6051), False, 'from imutils.face_utils import FaceAligner\n'), ((6124, 6164), 'cv2.imread', 'cv2.imread', (['image_path', 'cv2.IMREAD_COLOR'], {}), '(image_path, cv2.IMREAD_COLOR)\n', (6134, 6164), False, 'import cv2\n'), ((6179, 6216), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (6191, 6216), False, 'import cv2\n'), ((6231, 6268), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_GRAY2RGB'], {}), '(img, cv2.COLOR_GRAY2RGB)\n', (6243, 6268), False, 'import cv2\n'), ((6289, 6325), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (6301, 6325), False, 'import cv2\n'), ((6341, 6378), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (6353, 6378), False, 'import cv2\n'), ((6405, 6424), 'numpy.shape', 'np.shape', (['input_img'], {}), '(input_img)\n', (6413, 6424), True, 'import numpy as np\n'), ((9217, 9244), 'numpy.load', 'np.load', (['"""means_ethnic.npy"""'], {}), "('means_ethnic.npy')\n", (9224, 9244), True, 'import numpy as np\n'), ((9262, 9330), 'face_network.create_face_network', 'create_face_network', ([], {'nb_class': '(4)', 'hidden_dim': '(512)', 'shape': '(224, 224, 3)'}), '(nb_class=4, hidden_dim=512, shape=(224, 224, 3))\n', (9281, 9330), False, 'from face_network import create_face_network\n'), ((9395, 9429), 'cv2.imread', 'cv2.imread', (['name', 'cv2.IMREAD_COLOR'], {}), '(name, cv2.IMREAD_COLOR)\n', (9405, 9429), False, 'import cv2\n'), ((9443, 9479), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2GRAY'], {}), '(im, cv2.COLOR_BGR2GRAY)\n', (9455, 9479), False, 'import cv2\n'), ((9493, 9529), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_GRAY2RGB'], {}), '(im, cv2.COLOR_GRAY2RGB)\n', (9505, 9529), False, 'import cv2\n'), ((9543, 9569), 'cv2.resize', 'cv2.resize', (['im', '(224, 224)'], {}), '(im, (224, 224))\n', (9553, 9569), False, 'import cv2\n'), ((9583, 9597), 'numpy.float64', 'np.float64', (['im'], {}), '(im)\n', (9593, 9597), True, 'import numpy as np\n'), ((9808, 9840), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (9838, 9840), False, 'import dlib\n'), ((9861, 9898), 'dlib.shape_predictor', 'dlib.shape_predictor', (['shape_predictor'], {}), '(shape_predictor)\n', (9881, 9898), False, 'import dlib\n'), ((9912, 9956), 'imutils.face_utils.FaceAligner', 'FaceAligner', (['predictor'], {'desiredFaceWidth': '(160)'}), '(predictor, desiredFaceWidth=160)\n', (9923, 9956), False, 'from imutils.face_utils import FaceAligner\n'), ((9973, 10013), 'cv2.imread', 'cv2.imread', (['image_path', 'cv2.IMREAD_COLOR'], {}), '(image_path, cv2.IMREAD_COLOR)\n', (9983, 10013), False, 'import cv2\n'), ((10080, 10119), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (10092, 10119), False, 'import cv2\n'), ((10824, 10836), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (10834, 10836), True, 'import tensorflow as tf\n'), ((10857, 10930), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 160, 160, 3]', 'name': '"""input_image"""'}), "(tf.float32, shape=[None, 160, 160, 3], name='input_image')\n", (10871, 10930), True, 'import tensorflow as tf\n'), ((11052, 11075), 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {}), '(tf.bool)\n', (11066, 11075), True, 'import tensorflow as tf\n'), ((11115, 11227), 'inception_resnet_v1.inference', 'inception_resnet_v1.inference', (['images_norm'], {'keep_probability': '(0.8)', 'phase_train': 'train_mode', 'weight_decay': '(1e-05)'}), '(images_norm, keep_probability=0.8,\n phase_train=train_mode, weight_decay=1e-05)\n', (11144, 11227), False, 'import inception_resnet_v1\n'), ((11744, 11760), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (11758, 11760), True, 'import tensorflow as tf\n'), ((11776, 11817), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['model_path'], {}), '(model_path)\n', (11805, 11817), True, 'import tensorflow as tf\n'), ((12118, 12160), 'utils.inference.load_detection_model', 'load_detection_model', (['detection_model_path'], {}), '(detection_model_path)\n', (12138, 12160), False, 'from utils.inference import load_detection_model\n'), ((3091, 3139), 'utils.inference.apply_offsets', 'apply_offsets', (['face_coordinates', 'emotion_offsets'], {}), '(face_coordinates, emotion_offsets)\n', (3104, 3139), False, 'from utils.inference import apply_offsets\n'), ((3447, 3480), 'utils.preprocessor.preprocess_input', 'preprocess_input', (['rgb_face', '(False)'], {}), '(rgb_face, False)\n', (3463, 3480), False, 'from utils.preprocessor import preprocess_input\n'), ((3504, 3531), 'numpy.expand_dims', 'np.expand_dims', (['rgb_face', '(0)'], {}), '(rgb_face, 0)\n', (3518, 3531), True, 'import numpy as np\n'), ((3557, 3590), 'utils.preprocessor.preprocess_input', 'preprocess_input', (['gray_face', '(True)'], {}), '(gray_face, True)\n', (3573, 3590), False, 'from utils.preprocessor import preprocess_input\n'), ((3615, 3643), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(0)'], {}), '(gray_face, 0)\n', (3629, 3643), True, 'import numpy as np\n'), ((3668, 3697), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(-1)'], {}), '(gray_face, -1)\n', (3682, 3697), True, 'import numpy as np\n'), ((4749, 4797), 'utils.inference.apply_offsets', 'apply_offsets', (['face_coordinates', 'emotion_offsets'], {}), '(face_coordinates, emotion_offsets)\n', (4762, 4797), False, 'from utils.inference import apply_offsets\n'), ((5124, 5157), 'utils.preprocessor.preprocess_input', 'preprocess_input', (['rgb_face', '(False)'], {}), '(rgb_face, False)\n', (5140, 5157), False, 'from utils.preprocessor import preprocess_input\n'), ((5181, 5208), 'numpy.expand_dims', 'np.expand_dims', (['rgb_face', '(0)'], {}), '(rgb_face, 0)\n', (5195, 5208), True, 'import numpy as np\n'), ((5308, 5336), 'numpy.argmax', 'np.argmax', (['gender_prediction'], {}), '(gender_prediction)\n', (5317, 5336), True, 'import numpy as np\n'), ((5420, 5453), 'utils.preprocessor.preprocess_input', 'preprocess_input', (['gray_face', '(True)'], {}), '(gray_face, True)\n', (5436, 5453), False, 'from utils.preprocessor import preprocess_input\n'), ((5478, 5506), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(0)'], {}), '(gray_face, 0)\n', (5492, 5506), True, 'import numpy as np\n'), ((5531, 5560), 'numpy.expand_dims', 'np.expand_dims', (['gray_face', '(-1)'], {}), '(gray_face, -1)\n', (5545, 5560), True, 'import numpy as np\n'), ((6929, 6983), 'cv2.rectangle', 'cv2.rectangle', (['img', '(x1, y1)', '(x2, y2)', '(255, 0, 0)', '(2)'], {}), '(img, (x1, y1), (x2, y2), (255, 0, 0), 2)\n', (6942, 6983), False, 'import cv2\n'), ((7642, 7654), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (7652, 7654), True, 'import tensorflow as tf\n'), ((7679, 7752), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 160, 160, 3]', 'name': '"""input_image"""'}), "(tf.float32, shape=[None, 160, 160, 3], name='input_image')\n", (7693, 7752), True, 'import tensorflow as tf\n'), ((7975, 7998), 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {}), '(tf.bool)\n', (7989, 7998), True, 'import tensorflow as tf\n'), ((8043, 8155), 'inception_resnet_v1.inference', 'inception_resnet_v1.inference', (['images_norm'], {'keep_probability': '(0.8)', 'phase_train': 'train_mode', 'weight_decay': '(1e-05)'}), '(images_norm, keep_probability=0.8,\n phase_train=train_mode, weight_decay=1e-05)\n', (8072, 8155), False, 'import inception_resnet_v1\n'), ((8655, 8671), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (8669, 8671), True, 'import tensorflow as tf\n'), ((8704, 8745), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['model_path'], {}), '(model_path)\n', (8733, 8745), True, 'import tensorflow as tf\n'), ((9717, 9731), 'numpy.array', 'np.array', (['[im]'], {}), '([im])\n', (9725, 9731), True, 'import numpy as np\n'), ((11388, 11416), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['gender_logits'], {}), '(gender_logits)\n', (11401, 11416), True, 'import tensorflow as tf\n'), ((11606, 11639), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (11637, 11639), True, 'import tensorflow as tf\n'), ((11668, 11700), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (11698, 11700), True, 'import tensorflow as tf\n'), ((13181, 13202), 'os.path.join', 'join', (['path_to_file', 'f'], {}), '(path_to_file, f)\n', (13185, 13202), False, 'from os.path import isfile, join\n'), ((14138, 14169), 'json.dumps', 'json.dumps', (['one_person_insight_'], {}), '(one_person_insight_)\n', (14148, 14169), False, 'import json\n'), ((3282, 3324), 'cv2.resize', 'cv2.resize', (['gray_face', 'emotion_target_size'], {}), '(gray_face, emotion_target_size)\n', (3292, 3324), False, 'import cv2\n'), ((4939, 4979), 'cv2.resize', 'cv2.resize', (['rgb_face', 'gender_target_size'], {}), '(rgb_face, gender_target_size)\n', (4949, 4979), False, 'import cv2\n'), ((5010, 5052), 'cv2.resize', 'cv2.resize', (['gray_face', 'emotion_target_size'], {}), '(gray_face, emotion_target_size)\n', (5020, 5052), False, 'import cv2\n'), ((8505, 8538), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (8536, 8538), True, 'import tensorflow as tf\n'), ((8571, 8603), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (8601, 8603), True, 'import tensorflow as tf\n'), ((10546, 10566), 'imutils.face_utils.rect_to_bb', 'rect_to_bb', (['rects[i]'], {}), '(rects[i])\n', (10556, 10566), False, 'from imutils.face_utils import rect_to_bb\n'), ((10591, 10667), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x, y)', '(x + w, y + h)'], {'color': '(255, 0, 0)', 'thickness': '(2)'}), '(image, (x, y), (x + w, y + h), color=(255, 0, 0), thickness=2)\n', (10604, 10667), False, 'import cv2\n'), ((10721, 10745), 'numpy.array', 'np.array', (['aligned_images'], {}), '(aligned_images)\n', (10729, 10745), True, 'import numpy as np\n'), ((10977, 11018), 'tensorflow.image.per_image_standardization', 'tf.image.per_image_standardization', (['frame'], {}), '(frame)\n', (11011, 11018), True, 'import tensorflow as tf\n'), ((11537, 11562), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['age_logits'], {}), '(age_logits)\n', (11550, 11562), True, 'import tensorflow as tf\n'), ((13106, 13127), 'os.path.join', 'join', (['path_to_file', 'f'], {}), '(path_to_file, f)\n', (13110, 13127), False, 'from os.path import isfile, join\n'), ((13881, 13898), 'numpy.argmax', 'np.argmax', (['result'], {}), '(result)\n', (13890, 13898), True, 'import numpy as np\n'), ((7598, 7608), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (7606, 7608), True, 'import tensorflow as tf\n'), ((7798, 7824), 'tensorflow.reverse_v2', 'tf.reverse_v2', (['frame', '[-1]'], {}), '(frame, [-1])\n', (7811, 7824), True, 'import tensorflow as tf\n'), ((7899, 7940), 'tensorflow.image.per_image_standardization', 'tf.image.per_image_standardization', (['frame'], {}), '(frame)\n', (7933, 7940), True, 'import tensorflow as tf\n'), ((8440, 8465), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['age_logits'], {}), '(age_logits)\n', (8453, 8465), True, 'import tensorflow as tf\n')]
# Copyright (c) 2019 Alibaba Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import print_function from __future__ import division import tensorflow as tf import gym from gym.spaces import Discrete, Box import numpy as np from easy_rl.agents import agents from easy_rl.models import DQNModel from easy_rl.utils.window_stat import WindowStat MODEL_CONFIG = dict( # specific type="LinUCB") AGENT_CONFIG = dict( type="Agent", sample_batch_size=1, buffer_size=1, learning_starts=0, prioritized_replay=False, prioritized_replay_alpha=0.6, prioritized_replay_beta=0.4, batch_size=1, use_gae=False, compute_targets=False, ) np.random.seed(0) class MaxComponentEnv(gym.Env): def __init__(self, num_arms=2): self._num_arms = num_arms self.observation_space = Box( low=np.zeros((num_arms, ), dtype=np.float32), high=np.ones((num_arms, ), dtype=np.float32)) self.action_space = Discrete(num_arms) def reset(self, **kwargs): self._cur_state = np.random.uniform(0, 1.0, size=(self._num_arms, )) return self._cur_state def step(self, action): reward = self._cur_state[action] self._cur_state = np.random.uniform(0, 1.0, size=(self._num_arms, )) return self._cur_state, reward, True, {} def main(): env = MaxComponentEnv(num_arms=6) agent_class = agents[AGENT_CONFIG["type"]] agent = agent_class( env.observation_space, env.action_space, AGENT_CONFIG, MODEL_CONFIG, distributed_spec={}, export_dir="hook_dump_dir") reward_window = WindowStat("reward", 50) length_window = WindowStat("length", 50) loss_window = WindowStat("loss", 50) obs, actions, rewards, next_obs, dones = list(), list(), list(), list( ), list() act_count = 0 for i in range(100): ob = env.reset() done = False episode_reward = .0 episode_len = 0 while not done: action, results = agent.act( [ob], deterministic=False, use_perturbed_action=False) next_ob, reward, done, info = env.step(action[0]) act_count += 1 obs.append(ob) actions.append(action[0]) rewards.append(reward) next_obs.append(next_ob) dones.append(done) if agent.ready_to_send: agent.send_experience( obs=obs, actions=actions, rewards=rewards, next_obs=next_obs, dones=dones) if agent.ready_to_receive: batch_data = agent.receive_experience() res = agent.learn(batch_data) loss_window.push(res['loss']) if AGENT_CONFIG.get("prioritized_replay", False): agent.update_priorities( indexes=batch_data["indexes"], td_error=res["td_error"]) ob = next_ob episode_reward += reward episode_len += 1 if act_count % 5 == 0: print("timestep:", act_count, reward_window, length_window) agent.add_episode(1) reward_window.push(episode_reward) length_window.push(episode_len) agent.export_saved_model() print("Done.") if __name__ == "__main__": main()
[ "numpy.ones", "gym.spaces.Discrete", "easy_rl.utils.window_stat.WindowStat", "numpy.zeros", "numpy.random.seed", "numpy.random.uniform" ]
[((1330, 1347), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1344, 1347), True, 'import numpy as np\n'), ((2301, 2325), 'easy_rl.utils.window_stat.WindowStat', 'WindowStat', (['"""reward"""', '(50)'], {}), "('reward', 50)\n", (2311, 2325), False, 'from easy_rl.utils.window_stat import WindowStat\n'), ((2346, 2370), 'easy_rl.utils.window_stat.WindowStat', 'WindowStat', (['"""length"""', '(50)'], {}), "('length', 50)\n", (2356, 2370), False, 'from easy_rl.utils.window_stat import WindowStat\n'), ((2389, 2411), 'easy_rl.utils.window_stat.WindowStat', 'WindowStat', (['"""loss"""', '(50)'], {}), "('loss', 50)\n", (2399, 2411), False, 'from easy_rl.utils.window_stat import WindowStat\n'), ((1634, 1652), 'gym.spaces.Discrete', 'Discrete', (['num_arms'], {}), '(num_arms)\n', (1642, 1652), False, 'from gym.spaces import Discrete, Box\n'), ((1711, 1760), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1.0)'], {'size': '(self._num_arms,)'}), '(0, 1.0, size=(self._num_arms,))\n', (1728, 1760), True, 'import numpy as np\n'), ((1889, 1938), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1.0)'], {'size': '(self._num_arms,)'}), '(0, 1.0, size=(self._num_arms,))\n', (1906, 1938), True, 'import numpy as np\n'), ((1506, 1545), 'numpy.zeros', 'np.zeros', (['(num_arms,)'], {'dtype': 'np.float32'}), '((num_arms,), dtype=np.float32)\n', (1514, 1545), True, 'import numpy as np\n'), ((1565, 1603), 'numpy.ones', 'np.ones', (['(num_arms,)'], {'dtype': 'np.float32'}), '((num_arms,), dtype=np.float32)\n', (1572, 1603), True, 'import numpy as np\n')]
import cv2 import numpy as np from PIL import ImageGrab from mss import mss import SendKeys import time from datetime import datetime cod = [] accel = 170 counta = 0 def findDino(): time.sleep(3) dinoimg = cv2.imread('dino.png', 0) w, h = dinoimg.shape[::-1] img = ImageGrab.grab() imgcv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) imgcv = cv2.cvtColor(imgcv, cv2.COLOR_BGR2GRAY) res = cv2.matchTemplate(imgcv, dinoimg, cv2.TM_CCOEFF) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) top_left = max_loc bottom_right = (top_left[0] + w, top_left[1] + h) global cod cod = [top_left[1] + 86, bottom_right[1] - 40, top_left[0] + 450, bottom_right[0] + 350] def pular(): send = "{SPACE}" SendKeys.SendKeys(send) def ajustaImg(): monitor = {'top': cod[1] - 100, 'left': cod[2] - int(accel), 'width': 10, 'height': 100} with mss() as sct: imgcv = np.array(sct.grab(monitor)) imgcv = cv2.cvtColor(imgcv, cv2.COLOR_BGR2GRAY) _, imgcv = cv2.threshold(imgcv, 128, 255, cv2.THRESH_BINARY) #cv2.imwrite("kappa"+str(counta)+".png", imgcv) #global counta #counta += 1 tempoflag = {'top': cod[1] + 100, 'left': cod[2] - int(accel), 'width': 10, 'height': 10} with mss() as sct: imgflag = np.array(sct.grab(tempoflag)) imgflag = cv2.cvtColor(imgflag, cv2.COLOR_BGR2GRAY) _, imgflag = cv2.threshold(imgflag, 128, 255, cv2.THRESH_BINARY) if cv2.countNonZero(imgflag) > 80: if cv2.countNonZero(imgcv) < 900: # print("Jump") pular() else: if cv2.countNonZero(imgcv) > 20: # print("Jump") pular() def tirarPrint(): findDino() dt = datetime.now().second count = 0 global accel accel += 0.05 while (1): if dt != datetime.now().second: print(count) count = 0 dt = datetime.now().second ajustaImg() count += 1 tirarPrint() """ DEBUG DE FPSTRABSON def tirarPri nt(): cod = findDino() dt = datetime.now().second count = 0 while(1): if dt != datetime.now().second: print (count) count = 0 dt = datetime.now().second ajustaImg(cod) count += 1 """
[ "cv2.countNonZero", "mss.mss", "cv2.threshold", "SendKeys.SendKeys", "PIL.ImageGrab.grab", "time.sleep", "cv2.minMaxLoc", "numpy.array", "datetime.datetime.now", "cv2.cvtColor", "cv2.matchTemplate", "cv2.imread" ]
[((188, 201), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (198, 201), False, 'import time\n'), ((216, 241), 'cv2.imread', 'cv2.imread', (['"""dino.png"""', '(0)'], {}), "('dino.png', 0)\n", (226, 241), False, 'import cv2\n'), ((284, 300), 'PIL.ImageGrab.grab', 'ImageGrab.grab', ([], {}), '()\n', (298, 300), False, 'from PIL import ImageGrab\n'), ((373, 412), 'cv2.cvtColor', 'cv2.cvtColor', (['imgcv', 'cv2.COLOR_BGR2GRAY'], {}), '(imgcv, cv2.COLOR_BGR2GRAY)\n', (385, 412), False, 'import cv2\n'), ((424, 472), 'cv2.matchTemplate', 'cv2.matchTemplate', (['imgcv', 'dinoimg', 'cv2.TM_CCOEFF'], {}), '(imgcv, dinoimg, cv2.TM_CCOEFF)\n', (441, 472), False, 'import cv2\n'), ((514, 532), 'cv2.minMaxLoc', 'cv2.minMaxLoc', (['res'], {}), '(res)\n', (527, 532), False, 'import cv2\n'), ((759, 782), 'SendKeys.SendKeys', 'SendKeys.SendKeys', (['send'], {}), '(send)\n', (776, 782), False, 'import SendKeys\n'), ((974, 1013), 'cv2.cvtColor', 'cv2.cvtColor', (['imgcv', 'cv2.COLOR_BGR2GRAY'], {}), '(imgcv, cv2.COLOR_BGR2GRAY)\n', (986, 1013), False, 'import cv2\n'), ((1029, 1078), 'cv2.threshold', 'cv2.threshold', (['imgcv', '(128)', '(255)', 'cv2.THRESH_BINARY'], {}), '(imgcv, 128, 255, cv2.THRESH_BINARY)\n', (1042, 1078), False, 'import cv2\n'), ((1349, 1390), 'cv2.cvtColor', 'cv2.cvtColor', (['imgflag', 'cv2.COLOR_BGR2GRAY'], {}), '(imgflag, cv2.COLOR_BGR2GRAY)\n', (1361, 1390), False, 'import cv2\n'), ((1408, 1459), 'cv2.threshold', 'cv2.threshold', (['imgflag', '(128)', '(255)', 'cv2.THRESH_BINARY'], {}), '(imgflag, 128, 255, cv2.THRESH_BINARY)\n', (1421, 1459), False, 'import cv2\n'), ((326, 339), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (334, 339), True, 'import numpy as np\n'), ((903, 908), 'mss.mss', 'mss', ([], {}), '()\n', (906, 908), False, 'from mss import mss\n'), ((1272, 1277), 'mss.mss', 'mss', ([], {}), '()\n', (1275, 1277), False, 'from mss import mss\n'), ((1468, 1493), 'cv2.countNonZero', 'cv2.countNonZero', (['imgflag'], {}), '(imgflag)\n', (1484, 1493), False, 'import cv2\n'), ((1732, 1746), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1744, 1746), False, 'from datetime import datetime\n'), ((1511, 1534), 'cv2.countNonZero', 'cv2.countNonZero', (['imgcv'], {}), '(imgcv)\n', (1527, 1534), False, 'import cv2\n'), ((1611, 1634), 'cv2.countNonZero', 'cv2.countNonZero', (['imgcv'], {}), '(imgcv)\n', (1627, 1634), False, 'import cv2\n'), ((1835, 1849), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1847, 1849), False, 'from datetime import datetime\n'), ((1922, 1936), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1934, 1936), False, 'from datetime import datetime\n')]
# <NAME> CPSC 479 SEC 1 # This is the main python file containing the K-nearest neighbor classifier # Import libraries import numpy as np import pandas as pd from mpi4py import MPI # MPI_Init() automatically called when you import MPI from library from math import sqrt, ceil # Distance function returns Euclidean distance between two datapoints with same number of features def getDistance(x, y): distance = 0 for i in range(len(x) - 1): distance += ((x[i] - y[i]) ** 2) return sqrt(distance) # Initialize multiprocess communication, each process is identified by it's rank comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() # Initialize global vairables training_set = [] partitions = [] testing_set = [] distances = [] k = 15 # Tasks for the master rank if rank == 0: # Import training and testing data df = pd.read_csv("training_set.csv") training_set = df[['MovingTime', 'Distance', 'MaxSpeed', 'ElevationGain', 'Class']].to_numpy() df = pd.read_csv("testing_set.csv") testing_set = df[['MovingTime', 'Distance', 'MaxSpeed', 'ElevationGain', 'Class']].to_numpy() # Partition training data to send to worker processes pts_per_proc = len(training_set)//size for i in range(size): partitions.append([]) for i in range(len(training_set)): if i < pts_per_proc: partitions[0].append(training_set[i]) elif i < (pts_per_proc * 2): partitions[1].append(training_set[i]) elif i < (pts_per_proc * 3): partitions[2].append(training_set[i]) else: partitions[3].append(training_set[i]) # Scatter training data to worker porcesses partitions = comm.scatter(partitions, root=0) # Broadcast testing data to worker processes testing_set = comm.bcast(testing_set, root=0) # Each process calculataes distance from testing data to training data for point in partitions: distances.append(getDistance(point, testing_set[0])) # Gather results from worker processes distances = comm.gather(distances, root=0) # Master process does the rest of the work if rank == 0: # Choose k closest points to training point closest = [] # array of closest indices k_dist = [] # distance of the k closest neigbors dist_vect = [] # distances from training set and testing point # Reshape data gathered from other processors for i in range(len(distances)): for j in range(len(distances[i])): dist_vect.append(distances[i][j]) # create a copy of distance array and sort it to get closest values k_dist = dist_vect.copy() k_dist = np.sort(k_dist) # Find the corresponding datapoints from closest values for i in range(k): for j in range(len(dist_vect)): if k_dist[i] == dist_vect[j]: closest.append(j) # Classify test point classes = [0, 0, 0] for i in closest: if training_set[i][4] == 0: classes[0] += 1 elif training_set[i][4] == 1: classes[1] += 1 elif training_set[i][4] == 2: classes[2] += 1 predicted = classes.index(max(classes)) actual = int(testing_set[0][4]) # print results print("---------------------------------------------") print(" Training points -", len(dist_vect)) print(" K -", k) if classes[0] != 0: print("Neighbors in class 0 -", classes[0]) if classes[1] != 0: print("Neighbors in class 1 -", classes[1]) if classes[2] != 0: print("Neighbors in class 2 -", classes[2]) print(" Predicted class -", predicted) print(" Actual class -", actual) print("---------------------------------------------")
[ "numpy.sort", "math.sqrt", "pandas.read_csv" ]
[((508, 522), 'math.sqrt', 'sqrt', (['distance'], {}), '(distance)\n', (512, 522), False, 'from math import sqrt, ceil\n'), ((872, 903), 'pandas.read_csv', 'pd.read_csv', (['"""training_set.csv"""'], {}), "('training_set.csv')\n", (883, 903), True, 'import pandas as pd\n'), ((1012, 1042), 'pandas.read_csv', 'pd.read_csv', (['"""testing_set.csv"""'], {}), "('testing_set.csv')\n", (1023, 1042), True, 'import pandas as pd\n'), ((2658, 2673), 'numpy.sort', 'np.sort', (['k_dist'], {}), '(k_dist)\n', (2665, 2673), True, 'import numpy as np\n')]
"""Simple example wrapper for basic usage of vis_cpu.""" import numpy as np from pyuvdata.uvbeam import UVBeam from . import conversions, vis_cpu def simulate_vis( ants, fluxes, ra, dec, freqs, lsts, beams, pixel_beams=False, beam_npix=63, polarized=False, precision=1, latitude=-30.7215 * np.pi / 180.0, use_feed="x", ): """ Run a basic simulation using ``vis_cpu``. This wrapper handles the necessary coordinate conversions etc. Parameters ---------- ants : dict Dictionary of antenna positions. The keys are the antenna names (integers) and the values are the Cartesian x,y,z positions of the antennas (in meters) relative to the array center. fluxes : array_like 2D array with the flux of each source as a function of frequency, of shape (NSRCS, NFREQS). ra, dec : array_like Arrays of source RA and Dec positions in radians. RA goes from [0, 2 pi] and Dec from [-pi, +pi]. freqs : array_like Frequency channels for the simulation, in Hz. lsts : array_like Local sidereal times for the simulation, in radians. Range is [0, 2 pi]. beams : list of ``UVBeam`` objects Beam objects to use for each antenna. pixel_beams : bool, optional If True, interpolate the beams onto a pixel grid. Otherwise, use the ``UVBeam`` interpolation method directly. beam_npix : int, optional If ``pixel_beam == True``, sets the pixel grid resolution along each dimension (corresponds to the ``n_pix_lm`` parameter of the `conversions.uvbeam_to_lm` function). polarized : bool, optional If True, use polarized beams and calculate all available linearly- polarized visibilities, e.g. V_nn, V_ne, V_en, V_ee. Default: False (only uses the 'ee' polarization). precision : int, optional Which precision setting to use for :func:`~vis_cpu`. If set to ``1``, uses the (``np.float32``, ``np.complex64``) dtypes. If set to ``2``, uses the (``np.float64``, ``np.complex128``) dtypes. latitude : float, optional The latitude of the center of the array, in radians. The default is the HERA latitude = -30.7215 * pi / 180. Returns ------- vis : array_like Complex array of shape (NAXES, NFEED, NFREQS, NTIMES, NANTS, NANTS) if ``polarized == True``, or (NFREQS, NTIMES, NANTS, NANTS) otherwise. """ assert len(ants) == len( beams ), "The `beams` list must have as many entries as the ``ants`` dict." assert fluxes.shape == ( ra.size, freqs.size, ), "The `fluxes` array must have shape (NSRCS, NFREQS)." # Determine precision if precision == 1: complex_dtype = np.complex64 else: complex_dtype = np.complex128 # Get polarization information from beams if polarized: try: naxes = beams[0].Naxes_vec nfeeds = beams[0].Nfeeds except AttributeError: # If Naxes_vec and Nfeeds properties aren't set, assume all pol. naxes = nfeeds = 2 # Antenna x,y,z positions antpos = np.array([ants[k] for k in ants.keys()]) nants = antpos.shape[0] # Source coordinate transform, from equatorial to Cartesian crd_eq = conversions.point_source_crd_eq(ra, dec) # Get coordinate transforms as a function of LST eq2tops = np.array([conversions.eci_to_enu_matrix(lst, latitude) for lst in lsts]) # Create beam pixel models (if requested) if pixel_beams: beam_pix = [ conversions.uvbeam_to_lm( beam, freqs, n_pix_lm=beam_npix, polarized=polarized, use_feed=use_feed ) for beam in beams ] beam_cube = np.array(beam_pix) else: beams = [ conversions.prepare_beam(beam, polarized=polarized, use_feed=use_feed) for beam in beams ] # Run vis_cpu with pixel beams if polarized: vis = np.zeros( (naxes, nfeeds, freqs.size, lsts.size, nants, nants), dtype=complex_dtype ) else: vis = np.zeros((freqs.size, lsts.size, nants, nants), dtype=complex_dtype) # Loop over frequencies and call vis_cpu for either UVBeam or pixel beams for i in range(freqs.size): if pixel_beams: # Get per-freq. pixel beam bm = beam_cube[:, :, :, i, :, :] if polarized else beam_cube[:, i, :, :] # Run vis_cpu v = vis_cpu( antpos, freqs[i], eq2tops, crd_eq, fluxes[:, i], bm_cube=bm, precision=precision, polarized=polarized, ) if polarized: vis[:, :, i] = v # v.shape: (nax, nfeed, ntimes, nant, nant) else: vis[i] = v # v.shape: (ntimes, nant, nant) else: v = vis_cpu( antpos, freqs[i], eq2tops, crd_eq, fluxes[:, i], beam_list=beams, precision=precision, polarized=polarized, ) if polarized: vis[:, :, i] = v # v.shape: (nax, nfeed, ntimes, nant, nant) else: vis[i] = v # v.shape: (ntimes, nant, nant) return vis
[ "numpy.array", "numpy.zeros" ]
[((3839, 3857), 'numpy.array', 'np.array', (['beam_pix'], {}), '(beam_pix)\n', (3847, 3857), True, 'import numpy as np\n'), ((4077, 4165), 'numpy.zeros', 'np.zeros', (['(naxes, nfeeds, freqs.size, lsts.size, nants, nants)'], {'dtype': 'complex_dtype'}), '((naxes, nfeeds, freqs.size, lsts.size, nants, nants), dtype=\n complex_dtype)\n', (4085, 4165), True, 'import numpy as np\n'), ((4207, 4275), 'numpy.zeros', 'np.zeros', (['(freqs.size, lsts.size, nants, nants)'], {'dtype': 'complex_dtype'}), '((freqs.size, lsts.size, nants, nants), dtype=complex_dtype)\n', (4215, 4275), True, 'import numpy as np\n')]
import Dataset_Generator as dg import Evaluation as eval import Plot_Graph as ploter hd_dataset = dg.get_hd_dataset(5000) reduced_hd = eval.pca_dim_reduction(hd_dataset, 3) ploter.plot3D(reduced_hd) broken_swiss_roll_dataset = dg.get_broken_swiss_roll_dataset(5000) ploter.plot3D(broken_swiss_roll_dataset) reduced_broken_swiss = eval.pca_dim_reduction(broken_swiss_roll_dataset, 2) ploter.plot2D(reduced_broken_swiss) broken_helix_dataset = dg.get_helix_dataset(5000) ploter.plot3D(broken_helix_dataset) reduced_helix = eval.pca_dim_reduction(broken_helix_dataset, 2) ploter.plot2D(reduced_helix) swiss_roll_dataset = dg.get_swiss_roll_dataset(5000) ploter.plot3D(swiss_roll_dataset) reduced_swiss = eval.pca_dim_reduction(swiss_roll_dataset, 2) ploter.plot2D(reduced_swiss) twin_peaks_dataset = dg.get_twin_peaks(5000) ploter.plot3D(twin_peaks_dataset) reduced_twin_peaks = eval.pca_dim_reduction(twin_peaks_dataset, 2) ploter.plot2D(reduced_twin_peaks) # ***********************************scripts to evaluate Trust # Swiss roll import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_swiss_roll_dataset(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 2) trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) # Helix import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_helix_dataset(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 1) trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) # Twin peaks import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_twin_peaks(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 2) trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) # Broken Swiss import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_broken_swiss_roll_dataset(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 2) trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) # HD import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_hd_dataset(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 5) trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) # ***********************************scripts to evaluate Continuity # Swiss roll import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_swiss_roll_dataset(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 2) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # Helix import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_helix_dataset(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 1) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # Twin peaks import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_twin_peaks(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 2) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # Broken Swiss import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_broken_swiss_roll_dataset(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 2) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # HD import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_hd_dataset(5000) reduced_dataset = eval.pca_dim_reduction(dataset, 5) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # ***********************************scripts to test label_generation and generalization error import Dataset_Generator as dg import Evaluation as eval dataset = dg.get_broken_swiss_roll_dataset(5000) labels = eval.get_artificial_dataset_labels(dataset) reduced_dataset = eval.pca_dim_reduction(dataset, 2) error = eval.get_generalization_error(reduced_dataset, dataset) # ***********************************scripts to read MNIST from mnist import MNIST mndata = MNIST('/Users/evanxia/Dropbox/CSE569/MNIST_dataset') images, labels = mndata.load_training() # ***********************************scripts to test Trustworthiness and continuity in Natural dataset using LLE # MNIST import Evaluation as eval import MyLLE as lle import numpy as np dataset, labels = eval.get_natural_dataset_samples() reduced_dataset, error = lle.locally_linear_embedding(np.array(dataset, np.float64), 5, 20) reduced_dataset = reduced_dataset.tolist() trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # ***********************************scripts to test Trustworthiness and continuity in artificial dataset using LLE # Swiss roll import Dataset_Generator as dg import Evaluation as eval import MyLLE as lle import numpy as np dataset = dg.get_swiss_roll_dataset(5000) reduced_dataset, error = lle.locally_linear_embedding(np.array(dataset, np.float64), 5, 2) reduced_dataset = reduced_dataset.tolist() trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # Helix import Dataset_Generator as dg import Evaluation as eval import MyLLE as lle import numpy as np dataset = dg.get_helix_dataset(5000) reduced_dataset, error = lle.locally_linear_embedding(np.array(dataset, np.float64), 5, 1) reduced_dataset = reduced_dataset.tolist() trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # Twin peaks import Dataset_Generator as dg import Evaluation as eval import MyLLE as lle import numpy as np dataset = dg.get_twin_peaks(5000) reduced_dataset, error = lle.locally_linear_embedding(np.array(dataset, np.float64), 5, 2) reduced_dataset = reduced_dataset.tolist() trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # Broken Swiss import Dataset_Generator as dg import Evaluation as eval import MyLLE as lle import numpy as np dataset = dg.get_broken_swiss_roll_dataset(5000) reduced_dataset, error = lle.locally_linear_embedding(np.array(dataset, np.float64), 5, 2) reduced_dataset = reduced_dataset.tolist() trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # HD import Dataset_Generator as dg import Evaluation as eval import MyLLE as lle import numpy as np dataset = dg.get_hd_dataset(5000) reduced_dataset, error = lle.locally_linear_embedding(np.array(dataset, np.float64), 5, 5) reduced_dataset = reduced_dataset.tolist() trust = eval.get_trustworthiness(reduced_dataset, dataset, 12) continuity = eval.get_continuity(reduced_dataset, dataset, 12) # Following code evaluate the generalization error of original datasets import time import Evaluation as evaluation import pickle original_datasets = pickle.load(open('original_datasets.p', 'rb')) datasets_labels = pickle.load(open('datasets_labels.p', 'rb')) for key in original_datasets: name = key error = evaluation.get_generalization_error(original_datasets[key], datasets_labels[key]) print("The Generalization Error of the " + name + " is: " + str(error)) # Plot all original datasets with labels import time import Evaluation as evaluation import pickle import Plot_Graph as pg original_datasets = pickle.load(open('original_datasets.p', 'rb')) datasets_labels = pickle.load(open('datasets_labels.p', 'rb')) pca_reduced_datasets = pickle.load(open('pca_reduced_datasets.p', 'rb')) lle_reduced_datasets_under_diff_k = pickle.load(open('lle_reduced_datasets_under_diff_k.p', 'rb')) for key in original_datasets: pg.plot3D_color(original_datasets[key], datasets_labels[key]) # Plot lle_reduced datasets with k == 12 import time import Evaluation as evaluation import pickle import Plot_Graph as pg original_datasets = pickle.load(open('original_datasets.p', 'rb')) datasets_labels = pickle.load(open('datasets_labels.p', 'rb')) pca_reduced_datasets = pickle.load(open('pca_reduced_datasets.p', 'rb')) lle_reduced_datasets_under_diff_k = pickle.load(open('lle_reduced_datasets_under_diff_k.p', 'rb')) k = 9 for key in lle_reduced_datasets_under_diff_k[k - 5]: print(key) if key == "helix": pg.plot1D_color(lle_reduced_datasets_under_diff_k[k - 5][key], datasets_labels[key]) else: pg.plot2D_color(lle_reduced_datasets_under_diff_k[k - 5][key], datasets_labels[key]) # Plot pca_reduced datasets import time import Evaluation as evaluation import pickle import Plot_Graph as pg original_datasets = pickle.load(open('original_datasets.p', 'rb')) datasets_labels = pickle.load(open('datasets_labels.p', 'rb')) pca_reduced_datasets = pickle.load(open('pca_reduced_datasets.p', 'rb')) lle_reduced_datasets_under_diff_k = pickle.load(open('lle_reduced_datasets_under_diff_k.p', 'rb')) for key in pca_reduced_datasets: print(key) if key == "helix": pg.plot1D_color(pca_reduced_datasets[key], datasets_labels[key]) else: pg.plot2D_color(pca_reduced_datasets[key], datasets_labels[key])
[ "Dataset_Generator.get_broken_swiss_roll_dataset", "Dataset_Generator.get_swiss_roll_dataset", "mnist.MNIST", "Plot_Graph.plot3D_color", "Dataset_Generator.get_helix_dataset", "Plot_Graph.plot1D_color", "Evaluation.get_continuity", "Plot_Graph.plot2D", "Plot_Graph.plot3D", "Dataset_Generator.get_h...
[((99, 122), 'Dataset_Generator.get_hd_dataset', 'dg.get_hd_dataset', (['(5000)'], {}), '(5000)\n', (116, 122), True, 'import Dataset_Generator as dg\n'), ((136, 173), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['hd_dataset', '(3)'], {}), '(hd_dataset, 3)\n', (158, 173), True, 'import Evaluation as eval\n'), ((174, 199), 'Plot_Graph.plot3D', 'ploter.plot3D', (['reduced_hd'], {}), '(reduced_hd)\n', (187, 199), True, 'import Plot_Graph as ploter\n'), ((229, 267), 'Dataset_Generator.get_broken_swiss_roll_dataset', 'dg.get_broken_swiss_roll_dataset', (['(5000)'], {}), '(5000)\n', (261, 267), True, 'import Dataset_Generator as dg\n'), ((268, 308), 'Plot_Graph.plot3D', 'ploter.plot3D', (['broken_swiss_roll_dataset'], {}), '(broken_swiss_roll_dataset)\n', (281, 308), True, 'import Plot_Graph as ploter\n'), ((332, 384), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['broken_swiss_roll_dataset', '(2)'], {}), '(broken_swiss_roll_dataset, 2)\n', (354, 384), True, 'import Evaluation as eval\n'), ((385, 420), 'Plot_Graph.plot2D', 'ploter.plot2D', (['reduced_broken_swiss'], {}), '(reduced_broken_swiss)\n', (398, 420), True, 'import Plot_Graph as ploter\n'), ((445, 471), 'Dataset_Generator.get_helix_dataset', 'dg.get_helix_dataset', (['(5000)'], {}), '(5000)\n', (465, 471), True, 'import Dataset_Generator as dg\n'), ((472, 507), 'Plot_Graph.plot3D', 'ploter.plot3D', (['broken_helix_dataset'], {}), '(broken_helix_dataset)\n', (485, 507), True, 'import Plot_Graph as ploter\n'), ((524, 571), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['broken_helix_dataset', '(2)'], {}), '(broken_helix_dataset, 2)\n', (546, 571), True, 'import Evaluation as eval\n'), ((572, 600), 'Plot_Graph.plot2D', 'ploter.plot2D', (['reduced_helix'], {}), '(reduced_helix)\n', (585, 600), True, 'import Plot_Graph as ploter\n'), ((623, 654), 'Dataset_Generator.get_swiss_roll_dataset', 'dg.get_swiss_roll_dataset', (['(5000)'], {}), '(5000)\n', (648, 654), True, 'import Dataset_Generator as dg\n'), ((655, 688), 'Plot_Graph.plot3D', 'ploter.plot3D', (['swiss_roll_dataset'], {}), '(swiss_roll_dataset)\n', (668, 688), True, 'import Plot_Graph as ploter\n'), ((705, 750), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['swiss_roll_dataset', '(2)'], {}), '(swiss_roll_dataset, 2)\n', (727, 750), True, 'import Evaluation as eval\n'), ((751, 779), 'Plot_Graph.plot2D', 'ploter.plot2D', (['reduced_swiss'], {}), '(reduced_swiss)\n', (764, 779), True, 'import Plot_Graph as ploter\n'), ((802, 825), 'Dataset_Generator.get_twin_peaks', 'dg.get_twin_peaks', (['(5000)'], {}), '(5000)\n', (819, 825), True, 'import Dataset_Generator as dg\n'), ((826, 859), 'Plot_Graph.plot3D', 'ploter.plot3D', (['twin_peaks_dataset'], {}), '(twin_peaks_dataset)\n', (839, 859), True, 'import Plot_Graph as ploter\n'), ((881, 926), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['twin_peaks_dataset', '(2)'], {}), '(twin_peaks_dataset, 2)\n', (903, 926), True, 'import Evaluation as eval\n'), ((927, 960), 'Plot_Graph.plot2D', 'ploter.plot2D', (['reduced_twin_peaks'], {}), '(reduced_twin_peaks)\n', (940, 960), True, 'import Plot_Graph as ploter\n'), ((1106, 1137), 'Dataset_Generator.get_swiss_roll_dataset', 'dg.get_swiss_roll_dataset', (['(5000)'], {}), '(5000)\n', (1131, 1137), True, 'import Dataset_Generator as dg\n'), ((1156, 1190), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(2)'], {}), '(dataset, 2)\n', (1178, 1190), True, 'import Evaluation as eval\n'), ((1199, 1253), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (1223, 1253), True, 'import Evaluation as eval\n'), ((1330, 1356), 'Dataset_Generator.get_helix_dataset', 'dg.get_helix_dataset', (['(5000)'], {}), '(5000)\n', (1350, 1356), True, 'import Dataset_Generator as dg\n'), ((1375, 1409), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(1)'], {}), '(dataset, 1)\n', (1397, 1409), True, 'import Evaluation as eval\n'), ((1418, 1472), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (1442, 1472), True, 'import Evaluation as eval\n'), ((1554, 1577), 'Dataset_Generator.get_twin_peaks', 'dg.get_twin_peaks', (['(5000)'], {}), '(5000)\n', (1571, 1577), True, 'import Dataset_Generator as dg\n'), ((1596, 1630), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(2)'], {}), '(dataset, 2)\n', (1618, 1630), True, 'import Evaluation as eval\n'), ((1639, 1693), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (1663, 1693), True, 'import Evaluation as eval\n'), ((1777, 1815), 'Dataset_Generator.get_broken_swiss_roll_dataset', 'dg.get_broken_swiss_roll_dataset', (['(5000)'], {}), '(5000)\n', (1809, 1815), True, 'import Dataset_Generator as dg\n'), ((1834, 1868), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(2)'], {}), '(dataset, 2)\n', (1856, 1868), True, 'import Evaluation as eval\n'), ((1877, 1931), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (1901, 1931), True, 'import Evaluation as eval\n'), ((2005, 2028), 'Dataset_Generator.get_hd_dataset', 'dg.get_hd_dataset', (['(5000)'], {}), '(5000)\n', (2022, 2028), True, 'import Dataset_Generator as dg\n'), ((2047, 2081), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(5)'], {}), '(dataset, 5)\n', (2069, 2081), True, 'import Evaluation as eval\n'), ((2090, 2144), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (2114, 2144), True, 'import Evaluation as eval\n'), ((2296, 2327), 'Dataset_Generator.get_swiss_roll_dataset', 'dg.get_swiss_roll_dataset', (['(5000)'], {}), '(5000)\n', (2321, 2327), True, 'import Dataset_Generator as dg\n'), ((2346, 2380), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(2)'], {}), '(dataset, 2)\n', (2368, 2380), True, 'import Evaluation as eval\n'), ((2394, 2443), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (2413, 2443), True, 'import Evaluation as eval\n'), ((2520, 2546), 'Dataset_Generator.get_helix_dataset', 'dg.get_helix_dataset', (['(5000)'], {}), '(5000)\n', (2540, 2546), True, 'import Dataset_Generator as dg\n'), ((2565, 2599), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(1)'], {}), '(dataset, 1)\n', (2587, 2599), True, 'import Evaluation as eval\n'), ((2613, 2662), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (2632, 2662), True, 'import Evaluation as eval\n'), ((2744, 2767), 'Dataset_Generator.get_twin_peaks', 'dg.get_twin_peaks', (['(5000)'], {}), '(5000)\n', (2761, 2767), True, 'import Dataset_Generator as dg\n'), ((2786, 2820), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(2)'], {}), '(dataset, 2)\n', (2808, 2820), True, 'import Evaluation as eval\n'), ((2834, 2883), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (2853, 2883), True, 'import Evaluation as eval\n'), ((2967, 3005), 'Dataset_Generator.get_broken_swiss_roll_dataset', 'dg.get_broken_swiss_roll_dataset', (['(5000)'], {}), '(5000)\n', (2999, 3005), True, 'import Dataset_Generator as dg\n'), ((3024, 3058), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(2)'], {}), '(dataset, 2)\n', (3046, 3058), True, 'import Evaluation as eval\n'), ((3072, 3121), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (3091, 3121), True, 'import Evaluation as eval\n'), ((3195, 3218), 'Dataset_Generator.get_hd_dataset', 'dg.get_hd_dataset', (['(5000)'], {}), '(5000)\n', (3212, 3218), True, 'import Dataset_Generator as dg\n'), ((3237, 3271), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(5)'], {}), '(dataset, 5)\n', (3259, 3271), True, 'import Evaluation as eval\n'), ((3285, 3334), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (3304, 3334), True, 'import Evaluation as eval\n'), ((3499, 3537), 'Dataset_Generator.get_broken_swiss_roll_dataset', 'dg.get_broken_swiss_roll_dataset', (['(5000)'], {}), '(5000)\n', (3531, 3537), True, 'import Dataset_Generator as dg\n'), ((3547, 3590), 'Evaluation.get_artificial_dataset_labels', 'eval.get_artificial_dataset_labels', (['dataset'], {}), '(dataset)\n', (3581, 3590), True, 'import Evaluation as eval\n'), ((3609, 3643), 'Evaluation.pca_dim_reduction', 'eval.pca_dim_reduction', (['dataset', '(2)'], {}), '(dataset, 2)\n', (3631, 3643), True, 'import Evaluation as eval\n'), ((3652, 3707), 'Evaluation.get_generalization_error', 'eval.get_generalization_error', (['reduced_dataset', 'dataset'], {}), '(reduced_dataset, dataset)\n', (3681, 3707), True, 'import Evaluation as eval\n'), ((3801, 3853), 'mnist.MNIST', 'MNIST', (['"""/Users/evanxia/Dropbox/CSE569/MNIST_dataset"""'], {}), "('/Users/evanxia/Dropbox/CSE569/MNIST_dataset')\n", (3806, 3853), False, 'from mnist import MNIST\n'), ((4101, 4135), 'Evaluation.get_natural_dataset_samples', 'eval.get_natural_dataset_samples', ([], {}), '()\n', (4133, 4135), True, 'import Evaluation as eval\n'), ((4279, 4333), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (4303, 4333), True, 'import Evaluation as eval\n'), ((4347, 4396), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (4366, 4396), True, 'import Evaluation as eval\n'), ((4633, 4664), 'Dataset_Generator.get_swiss_roll_dataset', 'dg.get_swiss_roll_dataset', (['(5000)'], {}), '(5000)\n', (4658, 4664), True, 'import Dataset_Generator as dg\n'), ((4807, 4861), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (4831, 4861), True, 'import Evaluation as eval\n'), ((4875, 4924), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (4894, 4924), True, 'import Evaluation as eval\n'), ((5041, 5067), 'Dataset_Generator.get_helix_dataset', 'dg.get_helix_dataset', (['(5000)'], {}), '(5000)\n', (5061, 5067), True, 'import Dataset_Generator as dg\n'), ((5210, 5264), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (5234, 5264), True, 'import Evaluation as eval\n'), ((5278, 5327), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (5297, 5327), True, 'import Evaluation as eval\n'), ((5448, 5471), 'Dataset_Generator.get_twin_peaks', 'dg.get_twin_peaks', (['(5000)'], {}), '(5000)\n', (5465, 5471), True, 'import Dataset_Generator as dg\n'), ((5614, 5668), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (5638, 5668), True, 'import Evaluation as eval\n'), ((5682, 5731), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (5701, 5731), True, 'import Evaluation as eval\n'), ((5854, 5892), 'Dataset_Generator.get_broken_swiss_roll_dataset', 'dg.get_broken_swiss_roll_dataset', (['(5000)'], {}), '(5000)\n', (5886, 5892), True, 'import Dataset_Generator as dg\n'), ((6035, 6089), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (6059, 6089), True, 'import Evaluation as eval\n'), ((6103, 6152), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (6122, 6152), True, 'import Evaluation as eval\n'), ((6265, 6288), 'Dataset_Generator.get_hd_dataset', 'dg.get_hd_dataset', (['(5000)'], {}), '(5000)\n', (6282, 6288), True, 'import Dataset_Generator as dg\n'), ((6431, 6485), 'Evaluation.get_trustworthiness', 'eval.get_trustworthiness', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (6455, 6485), True, 'import Evaluation as eval\n'), ((6499, 6548), 'Evaluation.get_continuity', 'eval.get_continuity', (['reduced_dataset', 'dataset', '(12)'], {}), '(reduced_dataset, dataset, 12)\n', (6518, 6548), True, 'import Evaluation as eval\n'), ((4190, 4219), 'numpy.array', 'np.array', (['dataset', 'np.float64'], {}), '(dataset, np.float64)\n', (4198, 4219), True, 'import numpy as np\n'), ((4719, 4748), 'numpy.array', 'np.array', (['dataset', 'np.float64'], {}), '(dataset, np.float64)\n', (4727, 4748), True, 'import numpy as np\n'), ((5122, 5151), 'numpy.array', 'np.array', (['dataset', 'np.float64'], {}), '(dataset, np.float64)\n', (5130, 5151), True, 'import numpy as np\n'), ((5526, 5555), 'numpy.array', 'np.array', (['dataset', 'np.float64'], {}), '(dataset, np.float64)\n', (5534, 5555), True, 'import numpy as np\n'), ((5947, 5976), 'numpy.array', 'np.array', (['dataset', 'np.float64'], {}), '(dataset, np.float64)\n', (5955, 5976), True, 'import numpy as np\n'), ((6343, 6372), 'numpy.array', 'np.array', (['dataset', 'np.float64'], {}), '(dataset, np.float64)\n', (6351, 6372), True, 'import numpy as np\n'), ((6868, 6954), 'Evaluation.get_generalization_error', 'evaluation.get_generalization_error', (['original_datasets[key]', 'datasets_labels[key]'], {}), '(original_datasets[key], datasets_labels\n [key])\n', (6903, 6954), True, 'import Evaluation as evaluation\n'), ((7487, 7548), 'Plot_Graph.plot3D_color', 'pg.plot3D_color', (['original_datasets[key]', 'datasets_labels[key]'], {}), '(original_datasets[key], datasets_labels[key])\n', (7502, 7548), True, 'import Plot_Graph as pg\n'), ((8081, 8169), 'Plot_Graph.plot1D_color', 'pg.plot1D_color', (['lle_reduced_datasets_under_diff_k[k - 5][key]', 'datasets_labels[key]'], {}), '(lle_reduced_datasets_under_diff_k[k - 5][key],\n datasets_labels[key])\n', (8096, 8169), True, 'import Plot_Graph as pg\n'), ((8184, 8272), 'Plot_Graph.plot2D_color', 'pg.plot2D_color', (['lle_reduced_datasets_under_diff_k[k - 5][key]', 'datasets_labels[key]'], {}), '(lle_reduced_datasets_under_diff_k[k - 5][key],\n datasets_labels[key])\n', (8199, 8272), True, 'import Plot_Graph as pg\n'), ((8763, 8827), 'Plot_Graph.plot1D_color', 'pg.plot1D_color', (['pca_reduced_datasets[key]', 'datasets_labels[key]'], {}), '(pca_reduced_datasets[key], datasets_labels[key])\n', (8778, 8827), True, 'import Plot_Graph as pg\n'), ((8846, 8910), 'Plot_Graph.plot2D_color', 'pg.plot2D_color', (['pca_reduced_datasets[key]', 'datasets_labels[key]'], {}), '(pca_reduced_datasets[key], datasets_labels[key])\n', (8861, 8910), True, 'import Plot_Graph as pg\n')]
'''Body Composition is a Slicer module that allows to segment different parts of the lungs in a manual or semi-automatic basis with the help of a customized Slicer Editor. It also performs a set of operations to analyze the different structures of the volume based on its label map, like Area, Mean, Std.Dev., etc. First version: <NAME> (ACIL, <EMAIL>). 11/2014''' import qt, vtk, ctk, slicer import numpy as np from slicer.ScriptedLoadableModule import * from CIP.logic.SlicerUtil import SlicerUtil import CIP.ui as CIPUI class CIP_Calibration(ScriptedLoadableModule): """Module that allows to segment different parts of the lungs in a manual or semi-automatic basis""" def __init__(self, parent): """Constructor for main class""" ScriptedLoadableModule.__init__(self, parent) self.parent.title = "Calibration" self.parent.categories = SlicerUtil.CIP_ModulesCategory self.parent.dependencies = [SlicerUtil.CIP_ModuleName] self.parent.contributors = ["<NAME> (<EMAIL>)", "Applied Chest Imaging Laboratory", "Brigham and Women's Hospital"] self.parent.helpText = "Calibrate a scan with air and blood" self.parent.acknowledgementText = SlicerUtil.ACIL_AcknowledgementText ###################################### # CIP_StructuresDetectionWidget ####################################### class CIP_CalibrationWidget(ScriptedLoadableModuleWidget): """GUI object""" def __init__(self, parent): ScriptedLoadableModuleWidget.__init__(self, parent) # from functools import partial # def __onNodeAddedObserver__(self, caller, eventId, callData): # """Node added to the Slicer scene""" # # if callData.GetClassName() == 'vtkMRMLScalarVolumeNode' \ # # and slicer.util.mainWindow().moduleSelector().selectedModule == self.moduleName: # # self.__onNewVolumeLoaded__(callData) # #if callData.GetClassName() == 'vtkMRMLLabelMapVolumeNode': # self._onNewLabelmapLoaded_(callData) # # # self.__onNodeAddedObserver__ = partial(__onNodeAddedObserver__, self) # self.__onNodeAddedObserver__.CallDataType = vtk.VTK_OBJECT self.firstLoad = True self.activeEditorTools = None self.pendingChangesIdsList = [] @property def labelmapNodeNameExtension(self): return "calibrationLabelMap" ################ # Main methods ################ def setup(self): """Init the widget """ # self.firstLoad = True ScriptedLoadableModuleWidget.setup(self) self.disableEvents = False # Create objects that can be used anywhere in the module. Example: in most cases there should be just one # object of the logic class self._initLogic_() ########## # Main area self.mainAreaCollapsibleButton = ctk.ctkCollapsibleButton() self.mainAreaCollapsibleButton.text = "Main area" self.layout.addWidget(self.mainAreaCollapsibleButton, SlicerUtil.ALIGNMENT_VERTICAL_TOP) # self.layout.addWidget(self.mainAreaCollapsibleButton) # self.mainLayout = qt.QGridLayout(self.mainAreaCollapsibleButton) self.mainLayout = qt.QFormLayout(self.mainAreaCollapsibleButton) row = 0 # Node selector volumeLabel = qt.QLabel("Active volume: ") volumeLabel.setStyleSheet("margin-left:5px") # self.mainLayout.addWidget(volumeLabel, row, 0) self.volumeSelector = slicer.qMRMLNodeComboBox() self.volumeSelector.nodeTypes = ("vtkMRMLScalarVolumeNode", "") self.volumeSelector.selectNodeUponCreation = True self.volumeSelector.autoFillBackground = True self.volumeSelector.addEnabled = False self.volumeSelector.noneEnabled = False self.volumeSelector.removeEnabled = False self.volumeSelector.showHidden = False self.volumeSelector.showChildNodeTypes = False self.volumeSelector.setMRMLScene(slicer.mrmlScene) self.volumeSelector.setMinimumWidth(150) # self.volumeSelector.setStyleSheet("margin: 15px 0") # self.volumeSelector.selectNodeUponCreation = False #self.mainLayout.addWidget(self.volumeSelector, row, 1) self.mainLayout.addRow(volumeLabel, self.volumeSelector) self.volumeSelector.connect('currentNodeChanged(vtkMRMLNode*)', self._onMainVolumeChanged_) row += 1 lb = qt.QLabel("Click to select the calibration type and, if needed, modify the HU value expected for that area") lb.setStyleSheet("margin:10px 0 10px 5px") self.mainLayout.addRow(lb) #self.mainLayout.addWidget(lb, row, 0, 1, 2) self.typeRadioButtonGroup = qt.QButtonGroup() self.typeRadioButtonGroup.connect("buttonClicked (QAbstractButton*)", self.__onTypeRadioButtonClicked__) row += 1 self.rbAir = qt.QRadioButton("Air") self.rbAir.setStyleSheet("margin-left:10px; margin-top: 5px") self.typeRadioButtonGroup.addButton(self.rbAir, 1) # self.mainLayout.addWidget(self.rbAir, row, 0) self.txtAir = qt.QLineEdit() self.txtAir.setText("-1000") self.txtAir.setFixedWidth(80) self.txtAir.setValidator(qt.QIntValidator()) self.mainLayout.addRow(self.rbAir, self.txtAir) row += 1 self.rbBlood = qt.QRadioButton("Blood") self.rbBlood.setStyleSheet("margin-left:10px; margin-top: 5px") self.typeRadioButtonGroup.addButton(self.rbBlood, 2) # self.mainLayout.addWidget(self.rbBlood, row, 0) self.txtBlood = qt.QLineEdit() self.txtBlood.setText("50") self.txtBlood.setFixedWidth(80) self.txtBlood.setValidator(qt.QIntValidator()) # self.mainLayout.addWidget(self.txtBlood, row, 1) self.mainLayout.addRow(self.rbBlood, self.txtBlood) row += 1 # Calibrate button self.calibrateButton = ctk.ctkPushButton() self.calibrateButton.setText("Calibrate") self.calibrateButton.toolTip = "Run the calibration" self.calibrateButton.setIcon(qt.QIcon("{0}/scale.png".format(SlicerUtil.CIP_ICON_DIR))) self.calibrateButton.setIconSize(qt.QSize(20, 20)) self.calibrateButton.setFixedWidth(135) self.mainLayout.addRow(None, self.calibrateButton) self.calibrateButton.connect('clicked()', self._onCalibrateButtonClicked_) self._createEditorWidget_() self.setEditorValues() @property def currentVolumeLoaded(self): return self.volumeSelector.currentNode() @property def colorNode(self): nodeName = "{}_colorNode".format(self.moduleName) colorTableNode = SlicerUtil.getNode(nodeName) if colorTableNode is None: colorTableNode = self.logic.createColormapNode(nodeName) return colorTableNode def _initLogic_(self): """Create a new logic object for the plugin""" self.logic = CIP_CalibrationLogic() def checkMasterAndLabelMapNodes(self): """Set an appropiate MasterNode LabelMapNode to the Editor. The options are: - There is no masterNode => try to load the one that the user is watching right now, and go on if so. - There is masterNode and there is no label map => create a default label map node with the name "MasterNodeName_structuresDetection" and set the StructuresDetectionColorMap - There is masterNode and there is label map => check if the name of the label map is "MasterNodeName_structuresDetection". - If so: set this one - Otherwise: create a new labelmap with the name 'MasterNodeName_structureslabelMap' """ if self.disableEvents: return # To avoid infinite loops if self.editorWidget.masterVolume: masterNode = self.editorWidget.masterVolume SlicerUtil.logDevelop("Master node in Editor = " + masterNode.GetName(), True) else: SlicerUtil.logDevelop("No master node in Editor. Retrieving it from the selector...", False) masterNode = self.getCurrentGrayscaleNode() if not masterNode: # There is no any volume node that the user is watching SlicerUtil.logDevelop("Still not master node. Exit", False) return labelmapNode = self.getOrCreateLabelmap(masterNode) displayNode = labelmapNode.GetDisplayNode() if displayNode: displayNode.SetAndObserveColorNodeID(self.colorNode.GetID()) else: SlicerUtil.logDevelop("There is no DisplayNode for label map " + labelmapNode.GetName(), True) slicer.app.applicationLogic().PropagateVolumeSelection(0) SlicerUtil.changeLabelmapOpacity(0.5) # Set the right volumes self.disableEvents = True #self.editorWidget.masterVolume = masterNode #self.editorWidget.labelmapVolume = labelmapNode # trigger editor events self.editorWidget.helper.setVolumes(masterNode, labelmapNode) self.disableEvents = False slicer.app.applicationLogic().FitSliceToAll() def getOrCreateLabelmap(self, masterNode): labelmapName = "{0}_{1}".format(masterNode.GetName(), self.labelmapNodeNameExtension) labelmapNode = SlicerUtil.getNode(labelmapName) if labelmapNode is None: # Create a labelmap for this scalar labelmapNode = slicer.modules.volumes.logic().CreateAndAddLabelVolume(slicer.mrmlScene, masterNode, labelmapName) # Make sure that the labelmap has this name (no suffixes) labelmapNode.SetName(labelmapName) SlicerUtil.logDevelop("New label map node created: " + labelmapName, includePythonConsole=True) else: SlicerUtil.logDevelop("Labelmap loaded", includePythonConsole=True) return labelmapNode def getCurrentGrayscaleNode(self): """Get the grayscale node that is currently active in the widget""" #return self.editorWidget.masterVolume return self.volumeSelector.currentNode() def getCurrentLabelMapNode(self): """Get the labelmap node that is currently active in the widget""" return self.editorWidget.labelmapVolume def setCurrentGrayscaleNode(self, node): """Get the grayscale node that is currently active in the widget""" self.editorWidget.masterVolume = node def setCurrentLabelMapNode(self, node): """Get the labelmap node that is currently active in the widget""" self.editorWidget.labelmapVolume = node def setEditorValues(self): """Set the right color in the editor""" self.editorWidget.toolsColor.colorSpin.setValue(self.typeRadioButtonGroup.checkedId()) self.editorWidget.setActiveEffect("PaintEffect") self.editorWidget.changePaintEffectRadius(1.5) # Show the paint tools self.editorWidget.editLabelMapsFrame.collapsed = False ############## # Aux methods ############## def _onMainVolumeChanged_(self, newVolumeNode): """ A volume was changed in the main volume selector :param newVolumeNode: :return: """ if not self.disableEvents: self.setCurrentGrayscaleNode(newVolumeNode) self.checkMasterAndLabelMapNodes() def _onPreNavigatorLabelmapLoaded_(self, volumeNodeName): self.labelmapToBeRemoved = SlicerUtil.getNode(volumeNodeName) def _onNavigatorLabelmapLoaded_(self, volumeNode, region, type): """When a labelmap is loaded in the CaseNavigator, remove possible preexisting nodes""" if self.labelmapToBeRemoved: slicer.mrmlScene.RemoveNode(self.labelmapToBeRemoved) self.labelmapToBeRemoved = None self.checkMasterAndLabelMapNodes() def _createEditorWidget_(self): """Create and initialize a customize Slicer Editor which contains just some the tools that we need for the segmentation""" if self.activeEditorTools is None: # We don't want Paint effect by default self.activeEditorTools = ( "DefaultTool", "DrawEffect", "PaintEffect", "RectangleEffect", "EraseLabel", "PreviousCheckPoint", "NextCheckPoint") self.editorWidget = CIPUI.CIP_EditorWidget(self.parent, showVolumesFrame=True, activeTools=self.activeEditorTools) self.editorWidget.setup() self.editorWidget.setThresholds(-50000, 50000) # Remove thresholds # Collapse Volumes selector by default self.editorWidget.volumes.collapsed = True # Remove current listeners for helper box and override them self.editorWidget.helper.masterSelector.disconnect("currentNodeChanged(vtkMRMLNode*)") self.editorWidget.helper.mergeSelector.disconnect("currentNodeChanged(vtkMRMLNode*)") # Force to select always a node. It is important to do this at this point, when the events are disconnected, # because otherwise the editor would display the color selector (just noisy for the user) self.editorWidget.helper.masterSelector.noneEnabled = False # Listen to the event when there is a Master Node selected in the HelperBox self.editorWidget.helper.masterSelector.connect("currentNodeChanged(vtkMRMLNode*)", self._onMasterNodeSelect_) def _collapseEditorWidget_(self, collapsed=True): """Collapse/expand the items in EditorWidget""" self.editorWidget.volumes.collapsed = collapsed self.editorWidget.editLabelMapsFrame.collapsed = collapsed def _onCalibrateButtonClicked_(self): error = self.logic.calibrate(self.currentVolumeLoaded, self.getCurrentLabelMapNode(), int(self.txtAir.text), int(self.txtBlood.text)) if error: slicer.util.warningDisplay(error) else: slicer.util.infoDisplay("Calibration completed") ######### # Events ######### def enter(self): """Method that is invoked when we switch to the module in slicer user interface""" self.disableEvents = False if self.firstLoad: self.firstLoad = False else: self.checkMasterAndLabelMapNodes() self.editorWidget.helper.masterSelector.connect("currentNodeChanged(vtkMRMLNode*)", self._onMasterNodeSelect_) def _onMasterNodeSelect_(self, node): if node: nodeName = node.GetName() if self.getCurrentGrayscaleNode() and self.getCurrentGrayscaleNode().GetName() != nodeName: SlicerUtil.logDevelop( "There was a selection of a new master node: {0}. Previous: {1}. We will invoke checkMasterAndLabelMapNodes". format(node.GetName(), self.editorWidget.masterVolume.GetName()), includePythonConsole=True) # Update Editor Master node to perform the needed actions. # We don't use "setVolumes" function because the interface must not be refeshed yet (it will be in checkMasterAndLabelMapNodes) self.setCurrentGrayscaleNode(node) # Remove label node to refresh the values properly self.setCurrentLabelMapNode(None) self.checkMasterAndLabelMapNodes() else: SlicerUtil.logDevelop("No master node selected. Trying to remove label map", False) self.editorWidget.cleanVolumes() self.setEditorValues() def __onTypeRadioButtonClicked__(self, button): """ One of the radio buttons has been pressed :param button: :return: """ self.setEditorValues() def __onSceneClosed__(self, arg1, arg2): self.pendingChangesIdsList = [] self.logic = CIP_CalibrationLogic() def exit(self): self.editorWidget.helper.masterSelector.disconnect("currentNodeChanged(vtkMRMLNode*)") self.disableEvents = True def cleanup(self): pass # CIP_StructuresDetectionLogic # This class makes all the operations not related with the user interface (download and handle volumes, etc.) # class CIP_CalibrationLogic(ScriptedLoadableModuleLogic): def __init__(self): """Constructor. """ ScriptedLoadableModuleLogic.__init__(self) def createColormapNode(self, nodeName): """ Create a new colormap node for the editor @param nodeName: """ colorNode = SlicerUtil.createNewColormapNode(nodeName, numberOfColors=3) colorNode.SetColor(0, "Background", 0, 0, 0, 0) colorNode.SetColor(1, "Air", 0, 1.0, 0) colorNode.SetColor(2, "Blood", 1.0, 0, 0) return colorNode def calibrate(self, scalarNode, labelmapNode, air_output, blood_output): """ Calibrate the volume. Take the mean value of each region marked and rescale the volume to the values specified by air_output and blood_output @param scalarNode: MRML Scalar node to be calibrated @param labelmapNode: MRML labelmap node @param air_output: value expecte for air @param blood_output: value expected for blood @return: error message if something goes wrong, or None if everything works fine """ s = slicer.util.array(scalarNode.GetName()) lm = slicer.util.array(labelmapNode.GetName()) mask = lm == 1 if not np.any(mask): return "Please mark some area corresponding to air in the volume" air_input = np.mean(s[mask]) mask = lm == 2 if not np.any(mask): return "Please mark some area corresponding to blood in the volume" blood_input = np.mean(s[mask]) # Find the line that passes through these points d = float(blood_input - air_input) if d == 0: # Prevent overflow d = 0.0000001 m = (blood_output - air_output) / d b = air_output - (m * air_input) # Adjust the CT a2 = s * m + b a2 = a2.astype(np.int16) slicer.util.updateVolumeFromArray(scalarNode, a2) @staticmethod def normalize_CT_image_intensity(image_array, min_value=-300, max_value=700, min_output=0.0, max_output=1.0, inplace=True): """ Threshold and adjust contrast range in a CT image. :param image_array: int numpy array (CT or partial CT image) :param min_value: int. Min threshold (everything below that value will be thresholded). If None, ignore :param max_value: int. Max threshold (everything below that value will be thresholded). If None, ignore :param min_output: float. Min output value :param max_output: float. Max output value :return: None if in_place==True. Otherwise, float numpy array with adapted intensity """ clip = min_value is not None or max_value is not None if min_value is None: min_value = np.min(image_array) if max_value is None: max_value = np.max(image_array) if clip: np.clip(image_array, min_value, max_value, image_array) if inplace and image_array.dtype != np.float32: raise Exception( "The image array must contain float32 elements, because the transformation will be performed in place") if not inplace: # Copy the array! image_array = image_array.astype(np.float32) # Change of range image_array -= min_value image_array /= (max_value - min_value) image_array *= (max_output - min_output) image_array += min_output if not inplace: return image_array
[ "numpy.clip", "slicer.modules.volumes.logic", "qt.QLineEdit", "CIP.logic.SlicerUtil.SlicerUtil.getNode", "qt.QFormLayout", "qt.QIntValidator", "slicer.qMRMLNodeComboBox", "numpy.mean", "ctk.ctkCollapsibleButton", "qt.QRadioButton", "numpy.max", "qt.QLabel", "slicer.app.applicationLogic", "...
[((2919, 2945), 'ctk.ctkCollapsibleButton', 'ctk.ctkCollapsibleButton', ([], {}), '()\n', (2943, 2945), False, 'import qt, vtk, ctk, slicer\n'), ((3266, 3312), 'qt.QFormLayout', 'qt.QFormLayout', (['self.mainAreaCollapsibleButton'], {}), '(self.mainAreaCollapsibleButton)\n', (3280, 3312), False, 'import qt, vtk, ctk, slicer\n'), ((3376, 3404), 'qt.QLabel', 'qt.QLabel', (['"""Active volume: """'], {}), "('Active volume: ')\n", (3385, 3404), False, 'import qt, vtk, ctk, slicer\n'), ((3546, 3572), 'slicer.qMRMLNodeComboBox', 'slicer.qMRMLNodeComboBox', ([], {}), '()\n', (3570, 3572), False, 'import qt, vtk, ctk, slicer\n'), ((4495, 4613), 'qt.QLabel', 'qt.QLabel', (['"""Click to select the calibration type and, if needed, modify the HU value expected for that area"""'], {}), "(\n 'Click to select the calibration type and, if needed, modify the HU value expected for that area'\n )\n", (4504, 4613), False, 'import qt, vtk, ctk, slicer\n'), ((4780, 4797), 'qt.QButtonGroup', 'qt.QButtonGroup', ([], {}), '()\n', (4795, 4797), False, 'import qt, vtk, ctk, slicer\n'), ((4949, 4971), 'qt.QRadioButton', 'qt.QRadioButton', (['"""Air"""'], {}), "('Air')\n", (4964, 4971), False, 'import qt, vtk, ctk, slicer\n'), ((5180, 5194), 'qt.QLineEdit', 'qt.QLineEdit', ([], {}), '()\n', (5192, 5194), False, 'import qt, vtk, ctk, slicer\n'), ((5421, 5445), 'qt.QRadioButton', 'qt.QRadioButton', (['"""Blood"""'], {}), "('Blood')\n", (5436, 5445), False, 'import qt, vtk, ctk, slicer\n'), ((5662, 5676), 'qt.QLineEdit', 'qt.QLineEdit', ([], {}), '()\n', (5674, 5676), False, 'import qt, vtk, ctk, slicer\n'), ((6003, 6022), 'ctk.ctkPushButton', 'ctk.ctkPushButton', ([], {}), '()\n', (6020, 6022), False, 'import qt, vtk, ctk, slicer\n'), ((6771, 6799), 'CIP.logic.SlicerUtil.SlicerUtil.getNode', 'SlicerUtil.getNode', (['nodeName'], {}), '(nodeName)\n', (6789, 6799), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((8802, 8839), 'CIP.logic.SlicerUtil.SlicerUtil.changeLabelmapOpacity', 'SlicerUtil.changeLabelmapOpacity', (['(0.5)'], {}), '(0.5)\n', (8834, 8839), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((9374, 9406), 'CIP.logic.SlicerUtil.SlicerUtil.getNode', 'SlicerUtil.getNode', (['labelmapName'], {}), '(labelmapName)\n', (9392, 9406), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((11517, 11551), 'CIP.logic.SlicerUtil.SlicerUtil.getNode', 'SlicerUtil.getNode', (['volumeNodeName'], {}), '(volumeNodeName)\n', (11535, 11551), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((12374, 12473), 'CIP.ui.CIP_EditorWidget', 'CIPUI.CIP_EditorWidget', (['self.parent'], {'showVolumesFrame': '(True)', 'activeTools': 'self.activeEditorTools'}), '(self.parent, showVolumesFrame=True, activeTools=self\n .activeEditorTools)\n', (12396, 12473), True, 'import CIP.ui as CIPUI\n'), ((16498, 16558), 'CIP.logic.SlicerUtil.SlicerUtil.createNewColormapNode', 'SlicerUtil.createNewColormapNode', (['nodeName'], {'numberOfColors': '(3)'}), '(nodeName, numberOfColors=3)\n', (16530, 16558), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((17558, 17574), 'numpy.mean', 'np.mean', (['s[mask]'], {}), '(s[mask])\n', (17565, 17574), True, 'import numpy as np\n'), ((17730, 17746), 'numpy.mean', 'np.mean', (['s[mask]'], {}), '(s[mask])\n', (17737, 17746), True, 'import numpy as np\n'), ((18098, 18147), 'slicer.util.updateVolumeFromArray', 'slicer.util.updateVolumeFromArray', (['scalarNode', 'a2'], {}), '(scalarNode, a2)\n', (18131, 18147), False, 'import qt, vtk, ctk, slicer\n'), ((5303, 5321), 'qt.QIntValidator', 'qt.QIntValidator', ([], {}), '()\n', (5319, 5321), False, 'import qt, vtk, ctk, slicer\n'), ((5788, 5806), 'qt.QIntValidator', 'qt.QIntValidator', ([], {}), '()\n', (5804, 5806), False, 'import qt, vtk, ctk, slicer\n'), ((6271, 6287), 'qt.QSize', 'qt.QSize', (['(20)', '(20)'], {}), '(20, 20)\n', (6279, 6287), False, 'import qt, vtk, ctk, slicer\n'), ((8059, 8156), 'CIP.logic.SlicerUtil.SlicerUtil.logDevelop', 'SlicerUtil.logDevelop', (['"""No master node in Editor. Retrieving it from the selector..."""', '(False)'], {}), "(\n 'No master node in Editor. Retrieving it from the selector...', False)\n", (8080, 8156), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((8316, 8375), 'CIP.logic.SlicerUtil.SlicerUtil.logDevelop', 'SlicerUtil.logDevelop', (['"""Still not master node. Exit"""', '(False)'], {}), "('Still not master node. Exit', False)\n", (8337, 8375), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((9743, 9842), 'CIP.logic.SlicerUtil.SlicerUtil.logDevelop', 'SlicerUtil.logDevelop', (["('New label map node created: ' + labelmapName)"], {'includePythonConsole': '(True)'}), "('New label map node created: ' + labelmapName,\n includePythonConsole=True)\n", (9764, 9842), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((9865, 9932), 'CIP.logic.SlicerUtil.SlicerUtil.logDevelop', 'SlicerUtil.logDevelop', (['"""Labelmap loaded"""'], {'includePythonConsole': '(True)'}), "('Labelmap loaded', includePythonConsole=True)\n", (9886, 9932), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((11768, 11821), 'slicer.mrmlScene.RemoveNode', 'slicer.mrmlScene.RemoveNode', (['self.labelmapToBeRemoved'], {}), '(self.labelmapToBeRemoved)\n', (11795, 11821), False, 'import qt, vtk, ctk, slicer\n'), ((13871, 13904), 'slicer.util.warningDisplay', 'slicer.util.warningDisplay', (['error'], {}), '(error)\n', (13897, 13904), False, 'import qt, vtk, ctk, slicer\n'), ((13931, 13979), 'slicer.util.infoDisplay', 'slicer.util.infoDisplay', (['"""Calibration completed"""'], {}), "('Calibration completed')\n", (13954, 13979), False, 'import qt, vtk, ctk, slicer\n'), ((15363, 15450), 'CIP.logic.SlicerUtil.SlicerUtil.logDevelop', 'SlicerUtil.logDevelop', (['"""No master node selected. Trying to remove label map"""', '(False)'], {}), "('No master node selected. Trying to remove label map',\n False)\n", (15384, 15450), False, 'from CIP.logic.SlicerUtil import SlicerUtil\n'), ((17446, 17458), 'numpy.any', 'np.any', (['mask'], {}), '(mask)\n', (17452, 17458), True, 'import numpy as np\n'), ((17614, 17626), 'numpy.any', 'np.any', (['mask'], {}), '(mask)\n', (17620, 17626), True, 'import numpy as np\n'), ((19021, 19040), 'numpy.min', 'np.min', (['image_array'], {}), '(image_array)\n', (19027, 19040), True, 'import numpy as np\n'), ((19095, 19114), 'numpy.max', 'np.max', (['image_array'], {}), '(image_array)\n', (19101, 19114), True, 'import numpy as np\n'), ((19144, 19199), 'numpy.clip', 'np.clip', (['image_array', 'min_value', 'max_value', 'image_array'], {}), '(image_array, min_value, max_value, image_array)\n', (19151, 19199), True, 'import numpy as np\n'), ((8736, 8765), 'slicer.app.applicationLogic', 'slicer.app.applicationLogic', ([], {}), '()\n', (8763, 8765), False, 'import qt, vtk, ctk, slicer\n'), ((9163, 9192), 'slicer.app.applicationLogic', 'slicer.app.applicationLogic', ([], {}), '()\n', (9190, 9192), False, 'import qt, vtk, ctk, slicer\n'), ((9515, 9545), 'slicer.modules.volumes.logic', 'slicer.modules.volumes.logic', ([], {}), '()\n', (9543, 9545), False, 'import qt, vtk, ctk, slicer\n')]
"""Data loading for SVMRank-style data sets.""" from typing import Callable from typing import List from typing import Optional from typing import Union import numpy as _np import torch as _torch import logging from scipy.sparse import coo_matrix as _coo_matrix from sklearn.datasets import load_svmlight_file as _load_svmlight_file from torch.utils.data import Dataset as _Dataset from pytorchltr.datasets.list_sampler import ListSampler from pytorchltr.datasets.svmrank.parser import parse_svmrank_file class SVMRankItem: """A single item from a :obj:`pytorchltr.datasets.svmrank.SVMRankDataset`.""" def __init__(self, features: _torch.FloatTensor, relevance: _torch.LongTensor, n: int, qid: int, sparse: bool): self.features = features self.relevance = relevance self.n = n self.qid = qid self.sparse = sparse class SVMRankBatch: """A batch of items from a :obj:`pytorchltr.datasets.svmrank.SVMRankDataset`.""" def __init__(self, features: _torch.FloatTensor, relevance: _torch.LongTensor, n: _torch.LongTensor, qid: _torch.LongTensor, sparse: bool): self.features = features self.relevance = relevance self.n = n self.qid = qid self.sparse = sparse _COLLATE_RETURN_TYPE = Callable[[List[SVMRankItem]], SVMRankBatch] class SVMRankDataset(_Dataset): def __init__(self, file: str, sparse: bool = False, normalize: bool = False, filter_queries: bool = False, zero_based: Union[str, int] = "auto"): """Creates an SVMRank-style dataset from a file. Args: file: The path to load the dataset from. sparse: Whether to load the features as sparse features. normalize: Whether to perform query-level normalization (requires non-sparse features). filter_queries: Whether to filter queries that have no relevant documents associated with them. zero_based: The zero based index. """ logging.info("loading svmrank dataset from %s", file) # Load svmlight file if not sparse: # Use faster cython dense parser self._xs, self._ys, qids = parse_svmrank_file(file) else: # Use sklearn's sparse-support parser self._xs, self._ys, qids = _load_svmlight_file( file, query_id=True, zero_based=zero_based) # Compute query offsets and unique qids self._offsets = _np.hstack( [[0], _np.where(qids[1:] != qids[:-1])[0] + 1, [len(qids)]]) self._unique_qids = qids[self._offsets[:-1]] # Densify self._sparse = sparse # if not sparse: # self._xs = self._xs.A # Normalize xs if normalize: if sparse: raise NotImplementedError( "Normalization without dense features is not supported.") self._normalize() # Filter queries without any relevant documents if filter_queries: indices = [] for i, (start, end) in enumerate(zip(self._offsets[:-1], self._offsets[1:])): if _np.sum(self._ys[start:end]) > 0.0: indices.append(i) self._indices = _np.array(indices) else: self._indices = _np.arange(len(self._unique_qids)) # Compute qid map and dataset length self._qid_map = { self._unique_qids[self._indices[index]]: index for index in range(len(self._indices)) } self._n = len(self._indices) def _normalize(self): """Performs query-level feature normalization on the dataset.""" for start, end in zip(self._offsets[:-1], self._offsets[1:]): self._xs[start:end, :] -= _np.min(self._xs[start:end, :], axis=0) m = _np.max(self._xs[start:end, :], axis=0) m[m == 0.0] = 1.0 self._xs[start:end, :] /= m def get_index(self, qid: int) -> int: """Returns the dataset item index for given qid (if it exists). Args: qid: The qid to look up. Returns: The corresponding the dataset index for given qid. """ return self._qid_map[qid] @staticmethod def collate_fn(list_sampler: Optional[ListSampler] = None) -> _COLLATE_RETURN_TYPE: # noqa: E501 r"""Returns a collate_fn that can be used to collate batches. Args: list_sampler: Sampler to use for sampling lists of documents. """ if list_sampler is None: list_sampler = ListSampler() def _collate_fn(batch: List[SVMRankItem]) -> SVMRankBatch: # Check if batch is sparse or not sparse = batch[0].sparse # Compute list size list_size = max([list_sampler.max_list_size(b.relevance) for b in batch]) # Create output tensors from batch if sparse: out_features = [] else: out_features = _torch.zeros( (len(batch), list_size, batch[0].features.shape[1])) out_relevance = _torch.zeros( (len(batch), list_size), dtype=_torch.long) out_qid = _torch.zeros(len(batch), dtype=_torch.long) out_n = _torch.zeros(len(batch), dtype=_torch.long) # Collate the whole batch for batch_index, sample in enumerate(batch): # Generate random indices when we exceed the list_size. xs = sample.features if xs.shape[0] > list_size: rng_indices = list_sampler(sample.relevance) # Collate features if sparse: xs_coalesce = xs.coalesce() ind = xs_coalesce.indices() val = xs_coalesce.values() if xs.shape[0] > list_size: mask = [ind[0, :] == i for i in rng_indices] for i in range(len(mask)): ind[0, mask[i]] = int(i) ind = ind[:, sum(mask)] val = val[sum(mask)] ind_l = _torch.ones((1, ind.shape[1]), dtype=ind.dtype) * batch_index ind = _torch.cat([ind_l, ind], dim=0) out_features.append((ind, val)) else: if xs.shape[0] > list_size: out_features[batch_index, :, :] = xs[rng_indices, :] else: out_features[batch_index, 0:xs.shape[0], :] = xs # Collate relevance if xs.shape[0] > list_size: rel = sample.relevance[rng_indices] rel_n = len(rng_indices) out_relevance[batch_index, 0:rel_n] = rel else: rel = sample.relevance rel_n = len(sample.relevance) out_relevance[batch_index, 0:rel_n] = rel # Collate qid and n out_qid[batch_index] = int(sample.qid) out_n[batch_index] = min(int(sample.n), list_size) if sparse: ind = _torch.cat([d[0] for d in out_features], dim=1) val = _torch.cat([d[1] for d in out_features], dim=0) size = (len(batch), list_size, batch[0].features.shape[1]) out_features = _torch.sparse.FloatTensor( ind, val, _torch.Size(size)) return SVMRankBatch(out_features, out_relevance, out_n, out_qid, sparse) return _collate_fn def __getitem__(self, index: int) -> SVMRankItem: r""" Returns the item at given index. Args: index (int): The index. Returns: A :obj:`pytorchltr.datasets.svmrank.SVMRankItem` that contains features, relevance, qid, n and sparse fields. """ # Extract query features and relevance labels qid = self._unique_qids[self._indices[index]] start = self._offsets[self._indices[index]] end = self._offsets[self._indices[index] + 1] features = self._xs[start:end, :] y = _torch.LongTensor(self._ys[start:end]) n = end - start # Compute sparse or dense torch tensor if self._sparse: coo = _coo_matrix(features) ind = _torch.LongTensor(_np.vstack((coo.row, coo.col))) val = _torch.FloatTensor(coo.data) features = _torch.sparse.FloatTensor( ind, val, _torch.Size(coo.shape)) else: features = _torch.FloatTensor(features) # Return data sample return SVMRankItem(features, y, n, qid, self._sparse) def __len__(self) -> int: r""" Returns: int: The length of the dataset. """ return self._n
[ "sklearn.datasets.load_svmlight_file", "torch.LongTensor", "pytorchltr.datasets.list_sampler.ListSampler", "torch.Size", "numpy.where", "numpy.max", "pytorchltr.datasets.svmrank.parser.parse_svmrank_file", "numpy.array", "numpy.sum", "scipy.sparse.coo_matrix", "numpy.vstack", "numpy.min", "l...
[((2101, 2154), 'logging.info', 'logging.info', (['"""loading svmrank dataset from %s"""', 'file'], {}), "('loading svmrank dataset from %s', file)\n", (2113, 2154), False, 'import logging\n'), ((8527, 8565), 'torch.LongTensor', '_torch.LongTensor', (['self._ys[start:end]'], {}), '(self._ys[start:end])\n', (8544, 8565), True, 'import torch as _torch\n'), ((2292, 2316), 'pytorchltr.datasets.svmrank.parser.parse_svmrank_file', 'parse_svmrank_file', (['file'], {}), '(file)\n', (2310, 2316), False, 'from pytorchltr.datasets.svmrank.parser import parse_svmrank_file\n'), ((2420, 2483), 'sklearn.datasets.load_svmlight_file', '_load_svmlight_file', (['file'], {'query_id': '(True)', 'zero_based': 'zero_based'}), '(file, query_id=True, zero_based=zero_based)\n', (2439, 2483), True, 'from sklearn.datasets import load_svmlight_file as _load_svmlight_file\n'), ((3411, 3429), 'numpy.array', '_np.array', (['indices'], {}), '(indices)\n', (3420, 3429), True, 'import numpy as _np\n'), ((3944, 3983), 'numpy.min', '_np.min', (['self._xs[start:end, :]'], {'axis': '(0)'}), '(self._xs[start:end, :], axis=0)\n', (3951, 3983), True, 'import numpy as _np\n'), ((4000, 4039), 'numpy.max', '_np.max', (['self._xs[start:end, :]'], {'axis': '(0)'}), '(self._xs[start:end, :], axis=0)\n', (4007, 4039), True, 'import numpy as _np\n'), ((4755, 4768), 'pytorchltr.datasets.list_sampler.ListSampler', 'ListSampler', ([], {}), '()\n', (4766, 4768), False, 'from pytorchltr.datasets.list_sampler import ListSampler\n'), ((8681, 8702), 'scipy.sparse.coo_matrix', '_coo_matrix', (['features'], {}), '(features)\n', (8692, 8702), True, 'from scipy.sparse import coo_matrix as _coo_matrix\n'), ((8789, 8817), 'torch.FloatTensor', '_torch.FloatTensor', (['coo.data'], {}), '(coo.data)\n', (8807, 8817), True, 'import torch as _torch\n'), ((8955, 8983), 'torch.FloatTensor', '_torch.FloatTensor', (['features'], {}), '(features)\n', (8973, 8983), True, 'import torch as _torch\n'), ((7488, 7535), 'torch.cat', '_torch.cat', (['[d[0] for d in out_features]'], {'dim': '(1)'}), '([d[0] for d in out_features], dim=1)\n', (7498, 7535), True, 'import torch as _torch\n'), ((7558, 7605), 'torch.cat', '_torch.cat', (['[d[1] for d in out_features]'], {'dim': '(0)'}), '([d[1] for d in out_features], dim=0)\n', (7568, 7605), True, 'import torch as _torch\n'), ((8739, 8769), 'numpy.vstack', '_np.vstack', (['(coo.row, coo.col)'], {}), '((coo.row, coo.col))\n', (8749, 8769), True, 'import numpy as _np\n'), ((8894, 8916), 'torch.Size', '_torch.Size', (['coo.shape'], {}), '(coo.shape)\n', (8905, 8916), True, 'import torch as _torch\n'), ((3309, 3337), 'numpy.sum', '_np.sum', (['self._ys[start:end]'], {}), '(self._ys[start:end])\n', (3316, 3337), True, 'import numpy as _np\n'), ((6532, 6563), 'torch.cat', '_torch.cat', (['[ind_l, ind]'], {'dim': '(0)'}), '([ind_l, ind], dim=0)\n', (6542, 6563), True, 'import torch as _torch\n'), ((7769, 7786), 'torch.Size', '_torch.Size', (['size'], {}), '(size)\n', (7780, 7786), True, 'import torch as _torch\n'), ((2604, 2636), 'numpy.where', '_np.where', (['(qids[1:] != qids[:-1])'], {}), '(qids[1:] != qids[:-1])\n', (2613, 2636), True, 'import numpy as _np\n'), ((6404, 6451), 'torch.ones', '_torch.ones', (['(1, ind.shape[1])'], {'dtype': 'ind.dtype'}), '((1, ind.shape[1]), dtype=ind.dtype)\n', (6415, 6451), True, 'import torch as _torch\n')]
import numpy as np from simdkalman.primitives import predict, update # define model state_transition = np.array([[1,1],[0,1]]) process_noise = np.eye(2)*0.01 observation_model = np.array([[1,0]]) observation_noise = np.array([[1.0]]) # initial state m = np.array([0, 1]) P = np.eye(2) # predict next state m, P = predict(m, P, state_transition, process_noise) # first observation y = np.array([4]) m, P = update(m, P, observation_model, observation_noise, y) # predict second state m, P = predict(m, P, state_transition, process_noise) print('mean') print(m) print('cov') print(P)
[ "simdkalman.primitives.predict", "numpy.array", "numpy.eye", "simdkalman.primitives.update" ]
[((104, 130), 'numpy.array', 'np.array', (['[[1, 1], [0, 1]]'], {}), '([[1, 1], [0, 1]])\n', (112, 130), True, 'import numpy as np\n'), ((179, 197), 'numpy.array', 'np.array', (['[[1, 0]]'], {}), '([[1, 0]])\n', (187, 197), True, 'import numpy as np\n'), ((217, 234), 'numpy.array', 'np.array', (['[[1.0]]'], {}), '([[1.0]])\n', (225, 234), True, 'import numpy as np\n'), ((256, 272), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (264, 272), True, 'import numpy as np\n'), ((277, 286), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (283, 286), True, 'import numpy as np\n'), ((316, 362), 'simdkalman.primitives.predict', 'predict', (['m', 'P', 'state_transition', 'process_noise'], {}), '(m, P, state_transition, process_noise)\n', (323, 362), False, 'from simdkalman.primitives import predict, update\n'), ((388, 401), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (396, 401), True, 'import numpy as np\n'), ((409, 462), 'simdkalman.primitives.update', 'update', (['m', 'P', 'observation_model', 'observation_noise', 'y'], {}), '(m, P, observation_model, observation_noise, y)\n', (415, 462), False, 'from simdkalman.primitives import predict, update\n'), ((494, 540), 'simdkalman.primitives.predict', 'predict', (['m', 'P', 'state_transition', 'process_noise'], {}), '(m, P, state_transition, process_noise)\n', (501, 540), False, 'from simdkalman.primitives import predict, update\n'), ((144, 153), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (150, 153), True, 'import numpy as np\n')]
from numba.pycc import CC from numpy import zeros cc = CC('UnsatStor_inner_compiled') @cc.export('UnsatStor_inner', '(int64,int64[:,::1],float64,float64,float64[:,:,::1],float64[:,:,::1])') def UnsatStor_inner(NYrs, DaysMonth, MaxWaterCap, UnsatStor_0, infiltration, DailyET): unsatstor = zeros((NYrs, 12, 31)) unsatstor_carryover = UnsatStor_0 et = zeros((NYrs, 12, 31)) for Y in range(NYrs): for i in range(12): for j in range(DaysMonth[Y][i]): unsatstor[Y][i][j] = unsatstor_carryover unsatstor[Y][i][j] = unsatstor[Y][i][j] + infiltration[Y][i][j] if DailyET[Y][i][j] >= unsatstor[Y][i][j]: et[Y][i][j] = unsatstor[Y][i][j] unsatstor[Y][i][j] = 0 else: et[Y][i][j] = DailyET[Y][i][j] unsatstor[Y][i][j] = unsatstor[Y][i][j] - DailyET[Y][i][j] if unsatstor[Y][i][j] > MaxWaterCap: unsatstor[Y][i][j] = MaxWaterCap else: pass unsatstor_carryover = unsatstor[Y][i][j] return unsatstor, et, unsatstor_carryover
[ "numba.pycc.CC", "numpy.zeros" ]
[((56, 86), 'numba.pycc.CC', 'CC', (['"""UnsatStor_inner_compiled"""'], {}), "('UnsatStor_inner_compiled')\n", (58, 86), False, 'from numba.pycc import CC\n'), ((296, 317), 'numpy.zeros', 'zeros', (['(NYrs, 12, 31)'], {}), '((NYrs, 12, 31))\n', (301, 317), False, 'from numpy import zeros\n'), ((365, 386), 'numpy.zeros', 'zeros', (['(NYrs, 12, 31)'], {}), '((NYrs, 12, 31))\n', (370, 386), False, 'from numpy import zeros\n')]
# -*- coding: utf-8 -*- import operator import sys import numpy as np import tensorflow as tf from jtr.nn.models import get_total_trainable_variables from jtr.util.tfutil import tfrun class Vocab(object): """ Vocab objects for use in jtr pipelines. Example: >>> #Test Vocab without pre-trained embeddings >>> vocab = Vocab() >>> print(vocab("blah")) 1 >>> print(vocab("bluh")) 2 >>> print(vocab("bleh")) 3 >>> print(vocab("bluh")) 2 >>> print(vocab("hello")) 4 >>> print(vocab("world")) 5 >>> #Sym2id before freezing: >>> for k in sorted(vocab.sym2id.keys()): ... print(k,' : ',vocab.sym2id[k]) <UNK> : 0 blah : 1 bleh : 3 bluh : 2 hello : 4 world : 5 >>> #Sym2id after freezing (no difference, because no pre-trained embeddings used): >>> vocab.freeze() >>> for k in sorted(vocab.sym2id.keys()): ... print(k,' : ',vocab.sym2id[k]) <UNK> : 0 blah : 1 bleh : 3 bluh : 2 hello : 4 world : 5 >>> #Test Vocab with pre-trained embeddings >>> def emb(w): ... v = {'blah':[1.7,0,.3],'bluh':[0,1.5,0.5],'bleh':[0,0,2]} ... return None if not w in v else v[w] >>> vocab = Vocab(emb=emb) >>> print(vocab("blah")) -1 >>> print(vocab("bluh")) -2 >>> print(vocab("bleh")) -3 >>> print(vocab("bluh")) -2 >>> print(vocab("hello")) 1 >>> print(vocab("world")) 2 >>> #Sym2id before freezing: >>> for k in sorted(vocab.sym2id.keys()): ... print(k,' : ',vocab.sym2id[k]) <UNK> : 0 blah : -1 bleh : -3 bluh : -2 hello : 1 world : 2 >>> #Sym2id after freezing: normalized (positive) ids, also for pre-trained terms >>> vocab.freeze() >>> for k in sorted(vocab.sym2id.keys()): ... print(k,' : ',vocab.sym2id[k]) <UNK> : 0 blah : 3 bleh : 5 bluh : 4 hello : 1 world : 2 >>> #Test pretrained and out-of-vocab id's before freezing >>> vocab.unfreeze() >>> vocab.get_ids_pretrained() [-1, -2, -3] >>> vocab.get_ids_oov() [0, 1, 2] >>> #Test pretrained and out-of-vocab id's after freezing >>> vocab.freeze() >>> vocab.get_ids_pretrained() [3, 4, 5] >>> vocab.get_ids_oov() [0, 1, 2] >>> #Test calling frozen Vocab object >>> vocab(['bluh','world','wake','up']) #last 2 are new words, hence unknown [4, 2, 0, 0] >>> #Test calling unfrozen Vocab object >>> vocab.unfreeze() >>> vocab(['bluh','world','wake','up']) #last 2 are new words, hence added to Vocab [-2, 2, 3, 4] >>> #Test sym2id after freezing again >>> vocab.freeze() >>> for k in sorted(vocab.sym2id.keys()): ... print(k,' : ',vocab.sym2id[k]) <UNK> : 0 blah : 5 bleh : 7 bluh : 6 hello : 1 up : 4 wake : 3 world : 2 """ DEFAULT_UNK = "<UNK>" def __init__(self, unk=DEFAULT_UNK, emb=None, init_from_embeddings=False): """ Creates Vocab object. Args: `unk`: symbol for unknown term (default: "<UNK>"). If set to `None`, and `None` is not included as symbol while unfrozen, it will return `None` upon calling `get_id(None)` when frozen. `emb`: function handle; returns pre-trained embedding (fixed-size numerical list or ndarray) for a given symbol, and None for unknown symbols. """ self.next_neg = -1 self.unk = unk self.emb = emb if emb is not None else lambda _:None #if emb is None: same behavior as for o-o-v words if init_from_embeddings and emb is not None: self.sym2id = dict(emb.vocabulary.word2idx) self.id2sym = {v: k for k, v in emb.vocabulary.word2idx.items()} if unk is not None and unk not in self.sym2id: self.sym2id[unk] = len(self.sym2id) self.id2sym[len(self.id2sym)] = unk self.sym2freqs = {w: emb.vocabulary.get_word_count(w) for w in self.sym2id} self.frozen = True self.next_pos = 0 else: self.sym2id = {} # with pos and neg indices self.id2sym = {} self.next_pos = 0 self.sym2freqs = {} if unk is not None: self.sym2id[unk] = 0 # with pos and neg indices self.id2sym[0] = unk self.next_pos = 1 self.sym2freqs[unk] = 0 self.frozen = False if emb is not None and hasattr(emb, "lookup") and isinstance(emb.lookup, np.ndarray): self.emb_length = emb.lookup.shape[1] else: self.emb_length = None def freeze(self): """Freeze current Vocab object (set `self.frozen` to True). To be used after loading symbols from a given corpus; transforms all internal symbol id's to positive indices (for use in tensors). - additional calls to the __call__ method will return the id for the unknown symbold - out-of-vocab id's are positive integers and do not change - id's of symbols with pre-trained embeddings are converted to positive integer id's, counting up from the all out-of-vocab id's. """ # if any pretrained have been encountered if not self.frozen and self.next_neg < -1: sym2id = {sym: self._normalize(id) for sym,id in self.sym2id.items()} id2sym = {self._normalize(id): sym for id,sym in self.id2sym.items()} self.sym2id = sym2id self.id2sym = id2sym self.frozen = True def unfreeze(self): """Unfreeze current Vocab object (set `self.frozen` to False). Caution: use with care! Unfreezing a Vocab, adding new terms, and again Freezing it, will result in shifted id's for pre-trained symbols. - maps all normalized id's to the original internal id's. - additional calls to __call__ will allow adding new symbols to the vocabulary. """ if self.frozen and self.next_neg < -1: sym2id = {sym: self._denormalize(id) for sym, id in self.sym2id.items()} id2sym = {self._denormalize(id): sym for id, sym in self.id2sym.items()} self.sym2id = sym2id self.id2sym = id2sym self.frozen = False def get_id(self, sym): """ Returns the id of `sym`; different behavior depending on the state of the Vocab: - In case self.frozen==False (default): returns internal id, that is, positive for out-of-vocab symbol, negative for symbol found in `self.emb`. If `sym` is a new symbol, it is added to the Vocab. - In case self.frozen==True (after explicit call to 'freeze()', or after building a `NeuralVocab` with it): Returns normalized id (positive integer, also for symbols with pre-trained embedding) If `sym` is a new symbol, the id for unknown terms is returned, if available, and otherwise `None` (only possible when input argument `unk` for `Vocab.__init__()` was set to `None`, e.g. ; for classification labels; it is assumed action is taken in the pipeline creating or calling the `Vocab` object, when `None` is encountered). Args: `sym`: symbol (e.g., token) """ if not self.frozen: vec = self.emb(sym) if self.emb_length is None and vec is not None: self.emb_length = len(vec) if isinstance(vec, list) else vec.shape[0] if sym not in self.sym2id: if vec is None: self.sym2id[sym] = self.next_pos self.id2sym[self.next_pos] = sym self.next_pos += 1 else: self.sym2id[sym] = self.next_neg self.id2sym[self.next_neg] = sym self.next_neg -= 1 self.sym2freqs[sym] = 1 else: self.sym2freqs[sym] += 1 if sym in self.sym2id: return self.sym2id[sym] else: if self.unk in self.sym2id: return self.sym2id[self.unk] # can happen for `Vocab` initialized with `unk` argument set to `None` else: return None def get_sym(self, id): """returns symbol for a given id (consistent with the `self.frozen` state), and None if not found.""" return None if not id in self.id2sym else self.id2sym[id] def __call__(self, *args, **kwargs): """ calls the `get_id` function for the provided symbol(s), which adds symbols to the Vocab if needed and allowed, and returns their id(s). Args: *args: a single symbol, a list of symbols, or multiple symbols """ symbols = args if len(args) == 1: if isinstance(args[0], list): symbols = args[0] else: return self.get_id(args[0]) return [self.get_id(sym) for sym in symbols] def __len__(self): """returns number of unique symbols (including the unknown symbol)""" return len(self.id2sym) def __contains__(self, sym): """checks if `sym` already in the Vocab object""" return sym in self.sym2id def _normalize(self, id): """map original (pos/neg) ids to normalized (non-neg) ids: first new symbols, then those in emb""" # e.g. -1 should be mapped to self.next_pos + 0 # e.g. -3 should be mapped to self.next_pos + 2 return id if id >=0 else self.next_pos - id - 1 def _denormalize(self,id): # self.next_pos + i is mapped back to -1-i return id if id < self.next_pos else -1-(id-self.next_pos) def get_ids_pretrained(self): """return internal or normalized id's (depending on frozen/unfrozen state) for symbols that have an embedding in `self.emb` """ if self.frozen: return list(range(self.next_pos,self.next_pos+self.count_pretrained())) else: return list(range(-1,self.next_neg,-1)) def get_ids_oov(self): """return out-of-vocab id's (indep. of frozen/unfrozen state)""" return list(range(self.next_pos)) def count_pretrained(self): """equivalent to `len(get_ids_pretrained())`""" return -self.next_neg - 1 def count_oov(self): """equivalent to `len(get_ids_oov())`""" return self.next_pos def prune(self, min_freq=5, max_size=sys.maxsize): """returns new Vocab object, pruned based on minimum symbol frequency""" pruned_vocab = Vocab(unk=self.unk, emb=self.emb) cnt = 0 for sym, freq in sorted(self.sym2freqs.items(), key=operator.itemgetter(1), reverse=True): # for sym in self.sym2freqs: # freq = self.sym2freqs[sym] cnt += 1 if freq >= min_freq and cnt < max_size: pruned_vocab(sym) pruned_vocab.sym2freqs[sym] = freq if self.frozen: # if original Vocab was frozen, freeze new one pruned_vocab.freeze() return pruned_vocab class NeuralVocab(Vocab): """ Wrapper around Vocab to go from indices to tensors. Example: >>> #Start from same Vocab as the doctest example in Vocab >>> def emb(w): ... v = {'blah':[1.7,0,.3],'bluh':[0,1.5,0.5],'bleh':[0,0,2]} ... return None if not w in v else v[w] >>> vocab = Vocab(emb=emb) >>> vocab("blah", "bluh", "bleh", "hello", "world") #symbols as multiple arguments [-1, -2, -3, 1, 2] >>> vocab(['bluh','world','wake','up']) #as list of symbols [-2, 2, 3, 4] >>> #Create NeuralVocab object >>> with tf.variable_scope('neural_test1'): ... nvocab = NeuralVocab(vocab, None, 3, unit_normalize=True) ... tfrun(nvocab(vocab("world"))) array([ 0.46077079, 0.38316524, -0.63771147], dtype=float32) >>> tra1 = get_total_trainable_variables() >>> #Test NeuralVocab with pre-trained embeddings (case: input_size larger than pre-trained embeddings) >>> with tf.variable_scope('neural_test2'): ... for w in ['blah','bluh','bleh']: ... w, emb(w) ... nvocab = NeuralVocab(vocab, None, 4, unit_normalize=True, use_pretrained=True, train_pretrained=False) ... tfrun(nvocab.embedding_matrix) ('blah', [1.7, 0, 0.3]) ('bluh', [0, 1.5, 0.5]) ('bleh', [0, 0, 2]) array([[-0.26461828, 0.65265107, 0.39575091, -0.30496973], [ 0.48515028, 0.19880073, -0.02314733, -0.02336031], [ 0.26688093, -0.24634691, 0.2248017 , 0.24709973], [-0.39200979, -0.49848005, -1.11226082, -0.15154324], [ 0.46785676, 1.64755058, 0.15274598, 0.17200644], [ 0.98478359, 0. , 0.17378533, -0.46795556], [ 0. , 0.94868326, 0.31622776, -0.72465843], [ 0. , 0. , 1. , -0.46098801]], dtype=float32) >>> get_total_trainable_variables()-tra1 23 Interpretation of number of trainable variables from neural_test2: out-of-vocab: 8 - 3 = 5 symbols, with each 4 dimensions = 20; for fixed pre-trained embeddings with length 3, three times 1 extra trainable dimension for total embedding length 4. Total is 23. """ def __init__(self, base_vocab, embedding_matrix=None, input_size=None, reduced_input_size=None, use_pretrained=True, train_pretrained=False, unit_normalize=True): """ Creates NeuralVocab object from a given Vocab object `base_vocab`. Pre-calculates embedding vector (as `Tensor` object) for each symbol in Vocab Args: `base_vocab`: `embedding_matrix`: tensor with shape (len_vocab, input_size). If provided, the arguments `input_size`, `use_trained`, `train_pretrained`, and `unit_normalize` are ignored. `input_size`: integer; embedding length in case embedding matrix not provided, else ignored. If shorter than pre-trained embeddings, only their first `input_size` dimensions are used. If longer, extra (Trainable) dimensions are added. `reduced_input_size`: integer; optional; ignored in case `None`. If set to positive integer, an additional linear layer is introduced to reduce (or extend) the embeddings to the indicated size. `use_pretrained`: boolean; True (default): use pre-trained if available through `base_vocab`. False: ignore pre-trained embeddings accessible through `base_vocab` `train_pretrained`: boolean; False (default): fix pretrained embeddings. True: continue training. Ignored if embedding_matrix is given. `unit_normalize`: initialize pre-trained vectors with unit norm (note: randomly initialized embeddings are always initialized with expected unit norm) """ super(NeuralVocab, self).__init__(unk=base_vocab.unk, emb=base_vocab.emb) assert (embedding_matrix, input_size) is not (None, None), "if no embedding_matrix is provided, define input_size" self.freeze() #has no actual functionality here base_vocab.freeze() #freeze if not frozen (to ensure fixed non-negative indices) self.sym2id = base_vocab.sym2id self.id2sym = base_vocab.id2sym self.sym2freqs = base_vocab.sym2freqs self.unit_normalize = unit_normalize def np_normalize(v): return v / np.sqrt(np.sum(np.square(v))) if embedding_matrix is None: # construct part oov n_oov = base_vocab.count_oov() n_pre = base_vocab.count_pretrained() E_oov = tf.get_variable("embeddings_oov", [n_oov, input_size], initializer=tf.random_normal_initializer(0, 1./np.sqrt(input_size)), trainable=True, dtype="float32") # stdev = 1/sqrt(length): then expected initial L2 norm is 1 # construct part pretrained if use_pretrained and base_vocab.emb_length is not None: # load embeddings into numpy tensor with shape (count_pretrained, min(input_size,emb_length)) np_E_pre = np.zeros([n_pre, min(input_size, base_vocab.emb_length)]).astype("float32") for id in base_vocab.get_ids_pretrained(): sym = base_vocab.id2sym[id] i = id - n_oov #shifted to start from 0 np_E_pre[i, :] = base_vocab.emb(sym)[:min(input_size,base_vocab.emb_length)] if unit_normalize: np_E_pre[i, :] = np_normalize(np_E_pre[i, :]) E_pre = tf.get_variable("embeddings_pretrained", initializer=tf.identity(np_E_pre), trainable=train_pretrained, dtype="float32") if input_size > base_vocab.emb_length: E_pre_ext = tf.get_variable("embeddings_extra", [n_pre, input_size-base_vocab.emb_length], initializer=tf.random_normal_initializer(0.0, 1. / np.sqrt(base_vocab.emb_length)), dtype="float32", trainable=True) # note: stdev = 1/sqrt(emb_length) means: elements from same normal distr. as normalized first part (in case normally distr.) E_pre = tf.concat([E_pre, E_pre_ext], 1, name="embeddings_pretrained_extended") else: # initialize all randomly anyway E_pre = tf.get_variable("embeddings_not_pretrained", [n_pre, input_size], initializer=tf.random_normal_initializer(0., 1./np.sqrt(input_size)), trainable=True, dtype="float32") # again: initialize with expected unit norm # must be provided is embedding_matrix is None self.input_size = input_size self.embedding_matrix = tf.concat([E_oov, E_pre], 0, name="embeddings") else: # ignore input argument input_size self.input_size = embedding_matrix.get_shape()[1] self.embedding_matrix = embedding_matrix if isinstance(reduced_input_size, int) and reduced_input_size > 0: # uniform=False for truncated normal init = tf.contrib.layers.xavier_initializer(uniform=True) self.embedding_matrix = tf.contrib.layers.fully_connected(self.embedding_matrix, reduced_input_size, weights_initializer=init, activation_fn=None) # pre-assign embedding vectors to all ids # always OK if frozen self.id2vec = [tf.nn.embedding_lookup(self.embedding_matrix, idx) for idx in range(len(self))] def embed_symbol(self, ids): """returns embedded id's Args: `ids`: integer, ndarray with np.int32 integers, or tensor with tf.int32 integers. These integers correspond to (normalized) id's for symbols in `self.base_vocab`. Returns: tensor with id's embedded by numerical vectors (in last dimension) """ return tf.nn.embedding_lookup(self.embedding_matrix, ids) def __call__(self, *args, **kwargs): """ Calling the NeuralVocab object with symbol id's, returns a `Tensor` with corresponding embeddings. Args: `*args`: `Tensor` with integer indices (such as a placeholder, to be evaluated when run in a `tf.Session`), or list of integer id's, or just multiple integer ids as input arguments Returns: Embedded `Tensor` in case a `Tensor` was provided as input, and otherwise a list of embedded input id's under the form of fixed-length embeddings (`Tensor` objects). """ # tuple with length 1: then either list with ids, tensor with ids, or single id if len(args) == 1: if isinstance(args[0], list): ids = args[0] elif tf.contrib.framework.is_tensor(args[0]): # return embedded tensor return self.embed_symbol(args[0]) else: return self.id2vec[args[0]] else: # tuple with ids ids = args return [self.id2vec[id] for id in ids] def get_embedding_matrix(self): return self.embedding_matrix if __name__ == '__main__': import doctest tf.set_random_seed(1337) print(doctest.testmod())
[ "tensorflow.contrib.framework.is_tensor", "tensorflow.nn.embedding_lookup", "numpy.sqrt", "tensorflow.contrib.layers.fully_connected", "tensorflow.contrib.layers.xavier_initializer", "numpy.square", "tensorflow.concat", "doctest.testmod", "tensorflow.identity", "operator.itemgetter", "tensorflow...
[((21423, 21447), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1337)'], {}), '(1337)\n', (21441, 21447), True, 'import tensorflow as tf\n'), ((20108, 20158), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.embedding_matrix', 'ids'], {}), '(self.embedding_matrix, ids)\n', (20130, 20158), True, 'import tensorflow as tf\n'), ((21459, 21476), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (21474, 21476), False, 'import doctest\n'), ((18862, 18909), 'tensorflow.concat', 'tf.concat', (['[E_oov, E_pre]', '(0)'], {'name': '"""embeddings"""'}), "([E_oov, E_pre], 0, name='embeddings')\n", (18871, 18909), True, 'import tensorflow as tf\n'), ((19251, 19301), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {'uniform': '(True)'}), '(uniform=True)\n', (19287, 19301), True, 'import tensorflow as tf\n'), ((19338, 19464), 'tensorflow.contrib.layers.fully_connected', 'tf.contrib.layers.fully_connected', (['self.embedding_matrix', 'reduced_input_size'], {'weights_initializer': 'init', 'activation_fn': 'None'}), '(self.embedding_matrix, reduced_input_size,\n weights_initializer=init, activation_fn=None)\n', (19371, 19464), True, 'import tensorflow as tf\n'), ((19635, 19685), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.embedding_matrix', 'idx'], {}), '(self.embedding_matrix, idx)\n', (19657, 19685), True, 'import tensorflow as tf\n'), ((11328, 11350), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (11347, 11350), False, 'import operator\n'), ((21002, 21041), 'tensorflow.contrib.framework.is_tensor', 'tf.contrib.framework.is_tensor', (['args[0]'], {}), '(args[0])\n', (21032, 21041), True, 'import tensorflow as tf\n'), ((18225, 18296), 'tensorflow.concat', 'tf.concat', (['[E_pre, E_pre_ext]', '(1)'], {'name': '"""embeddings_pretrained_extended"""'}), "([E_pre, E_pre_ext], 1, name='embeddings_pretrained_extended')\n", (18234, 18296), True, 'import tensorflow as tf\n'), ((16294, 16306), 'numpy.square', 'np.square', (['v'], {}), '(v)\n', (16303, 16306), True, 'import numpy as np\n'), ((17611, 17632), 'tensorflow.identity', 'tf.identity', (['np_E_pre'], {}), '(np_E_pre)\n', (17622, 17632), True, 'import tensorflow as tf\n'), ((16632, 16651), 'numpy.sqrt', 'np.sqrt', (['input_size'], {}), '(input_size)\n', (16639, 16651), True, 'import numpy as np\n'), ((18570, 18589), 'numpy.sqrt', 'np.sqrt', (['input_size'], {}), '(input_size)\n', (18577, 18589), True, 'import numpy as np\n'), ((17985, 18015), 'numpy.sqrt', 'np.sqrt', (['base_vocab.emb_length'], {}), '(base_vocab.emb_length)\n', (17992, 18015), True, 'import numpy as np\n')]
# 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 # # https://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. # NOTE: This file is copied (rather than symlinked) since a symlink **outside** # of the package tree won't get copied during a ``pip install``. import os import pathlib import subprocess import sys import numpy as np import setuptools FORTRAN_LIBRARY_PREFIX = "libraries: =" GFORTRAN_MISSING_LIBS = """\ ``gfortran`` default library path not found via: $ gfortran -print-search-dirs {}""" GFORTRAN_BAD_PATH = "``gfortran`` library path {} is not a directory." def gfortran_search_path(): """Get the library directory paths for ``gfortran``. Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs`` and then parses the paths. If this fails for any reason, this method will print an error and return ``library_dirs``. Returns: List[str]: The library directories for ``gfortran``. """ cmd = ("gfortran", "-print-search-dirs") process = subprocess.Popen(cmd, stdout=subprocess.PIPE) return_code = process.wait() # Bail out if the command failed. if return_code != 0: return [] cmd_output = process.stdout.read().decode("utf-8") # Find single line starting with ``libraries: ``. search_lines = cmd_output.strip().split("\n") library_lines = [ line[len(FORTRAN_LIBRARY_PREFIX) :] for line in search_lines if line.startswith(FORTRAN_LIBRARY_PREFIX) ] if len(library_lines) != 1: msg = GFORTRAN_MISSING_LIBS.format(cmd_output) print(msg, file=sys.stderr) return [] # Go through each library in the ``libraries: = ...`` line. library_line = library_lines[0] accepted = set() for part in library_line.split(os.pathsep): full_path = os.path.abspath(part.strip()) if os.path.isdir(full_path): accepted.add(full_path) else: # Ignore anything that isn't a directory. msg = GFORTRAN_BAD_PATH.format(full_path) print(msg, file=sys.stderr) return sorted(accepted) def get_extra_objects(here): return ( os.path.join(here, "object_files", "types.o"), os.path.join(here, "object_files", "forall_.o"), os.path.join(here, "object_files", "do_.o"), os.path.join(here, "object_files", "spread_.o"), os.path.join(here, "object_files", "serial_.o"), os.path.join(here, "object_files", "vs_algorithm.o"), ) def extension_modules(here, name): extra_objects = get_extra_objects(here) missing = [path for path in extra_objects if not os.path.isfile(path)] if missing: parts = ["Missing object file(s):"] parts.extend(f"- {path}" for path in missing) parts.extend( [ "", f"here: {here}", f"__file__: {__file__}", "", "files in `here`:", ] ) files_here = pathlib.Path(here).glob("*") parts.extend(f"- {path}" for path in files_here) msg = "\n".join(parts) raise RuntimeError(msg) extension = setuptools.Extension( f"{name}._binary", [os.path.join(name, "_binary.c")], extra_objects=extra_objects, include_dirs=[np.get_include()], libraries=["gfortran"], library_dirs=gfortran_search_path(), ) return [extension] def do_setup(here, name): ext_modules = extension_modules(here, name) setuptools.setup( name=name, packages=[name], install_requires=["numpy"], ext_modules=ext_modules, )
[ "pathlib.Path", "subprocess.Popen", "os.path.join", "setuptools.setup", "os.path.isfile", "os.path.isdir", "numpy.get_include" ]
[((1454, 1499), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'stdout': 'subprocess.PIPE'}), '(cmd, stdout=subprocess.PIPE)\n', (1470, 1499), False, 'import subprocess\n'), ((3970, 4071), 'setuptools.setup', 'setuptools.setup', ([], {'name': 'name', 'packages': '[name]', 'install_requires': "['numpy']", 'ext_modules': 'ext_modules'}), "(name=name, packages=[name], install_requires=['numpy'],\n ext_modules=ext_modules)\n", (3986, 4071), False, 'import setuptools\n'), ((2302, 2326), 'os.path.isdir', 'os.path.isdir', (['full_path'], {}), '(full_path)\n', (2315, 2326), False, 'import os\n'), ((2607, 2652), 'os.path.join', 'os.path.join', (['here', '"""object_files"""', '"""types.o"""'], {}), "(here, 'object_files', 'types.o')\n", (2619, 2652), False, 'import os\n'), ((2662, 2709), 'os.path.join', 'os.path.join', (['here', '"""object_files"""', '"""forall_.o"""'], {}), "(here, 'object_files', 'forall_.o')\n", (2674, 2709), False, 'import os\n'), ((2719, 2762), 'os.path.join', 'os.path.join', (['here', '"""object_files"""', '"""do_.o"""'], {}), "(here, 'object_files', 'do_.o')\n", (2731, 2762), False, 'import os\n'), ((2772, 2819), 'os.path.join', 'os.path.join', (['here', '"""object_files"""', '"""spread_.o"""'], {}), "(here, 'object_files', 'spread_.o')\n", (2784, 2819), False, 'import os\n'), ((2829, 2876), 'os.path.join', 'os.path.join', (['here', '"""object_files"""', '"""serial_.o"""'], {}), "(here, 'object_files', 'serial_.o')\n", (2841, 2876), False, 'import os\n'), ((2886, 2938), 'os.path.join', 'os.path.join', (['here', '"""object_files"""', '"""vs_algorithm.o"""'], {}), "(here, 'object_files', 'vs_algorithm.o')\n", (2898, 2938), False, 'import os\n'), ((3672, 3703), 'os.path.join', 'os.path.join', (['name', '"""_binary.c"""'], {}), "(name, '_binary.c')\n", (3684, 3703), False, 'import os\n'), ((3080, 3100), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (3094, 3100), False, 'import os\n'), ((3447, 3465), 'pathlib.Path', 'pathlib.Path', (['here'], {}), '(here)\n', (3459, 3465), False, 'import pathlib\n'), ((3765, 3781), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (3779, 3781), True, 'import numpy as np\n')]
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F # if gpu is to be used device = torch.device("cuda" if torch.cuda.is_available() else "cpu") WEIGHTS_FINAL_INIT = 3e-3 BIAS_FINAL_INIT = 3e-4 def fan_in_uniform_init(tensor, fan_in=None): """Utility function for initializing actor and critic""" if fan_in is None: fan_in = tensor.size(-1) w = 1. / np.sqrt(fan_in) nn.init.uniform_(tensor, -w, w) class Actor(nn.Module): def __init__(self, hidden_size, num_inputs, action_space): super(Actor, self).__init__() self.action_space = action_space num_outputs = action_space.shape[0] # Layer 1 self.linear1 = nn.Linear(num_inputs, hidden_size[0]) self.ln1 = nn.LayerNorm(hidden_size[0]) # Layer 2 self.linear2 = nn.Linear(hidden_size[0], hidden_size[1]) self.ln2 = nn.LayerNorm(hidden_size[1]) # Output Layer self.mu = nn.Linear(hidden_size[1], num_outputs) # Weight Init fan_in_uniform_init(self.linear1.weight) fan_in_uniform_init(self.linear1.bias) fan_in_uniform_init(self.linear2.weight) fan_in_uniform_init(self.linear2.bias) nn.init.uniform_(self.mu.weight, -WEIGHTS_FINAL_INIT, WEIGHTS_FINAL_INIT) nn.init.uniform_(self.mu.bias, -BIAS_FINAL_INIT, BIAS_FINAL_INIT) def forward(self, inputs): x = inputs # Layer 1 x = self.linear1(x) x = self.ln1(x) x = F.relu(x) # Layer 2 x = self.linear2(x) x = self.ln2(x) x = F.relu(x) # Output mu = torch.tanh(self.mu(x)) return mu class Critic(nn.Module): def __init__(self, hidden_size, num_inputs, action_space): super(Critic, self).__init__() self.action_space = action_space num_outputs = action_space.shape[0] # Layer 1 self.linear1 = nn.Linear(num_inputs, hidden_size[0]) self.ln1 = nn.LayerNorm(hidden_size[0]) # Layer 2 # In the second layer the actions will be inserted also self.linear2 = nn.Linear(hidden_size[0] + num_outputs, hidden_size[1]) self.ln2 = nn.LayerNorm(hidden_size[1]) # Output layer (single value) self.V = nn.Linear(hidden_size[1], 1) # Weight Init fan_in_uniform_init(self.linear1.weight) fan_in_uniform_init(self.linear1.bias) fan_in_uniform_init(self.linear2.weight) fan_in_uniform_init(self.linear2.bias) nn.init.uniform_(self.V.weight, -WEIGHTS_FINAL_INIT, WEIGHTS_FINAL_INIT) nn.init.uniform_(self.V.bias, -BIAS_FINAL_INIT, BIAS_FINAL_INIT) def forward(self, inputs, actions): x = inputs # Layer 1 x = self.linear1(x) x = self.ln1(x) x = F.relu(x) # Layer 2 x = torch.cat((x, actions), 1) # Insert the actions x = self.linear2(x) x = self.ln2(x) x = F.relu(x) # Output V = self.V(x) return V
[ "numpy.sqrt", "torch.nn.LayerNorm", "torch.cuda.is_available", "torch.nn.Linear", "torch.nn.functional.relu", "torch.nn.init.uniform_", "torch.cat" ]
[((428, 459), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['tensor', '(-w)', 'w'], {}), '(tensor, -w, w)\n', (444, 459), True, 'import torch.nn as nn\n'), ((142, 167), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (165, 167), False, 'import torch\n'), ((408, 423), 'numpy.sqrt', 'np.sqrt', (['fan_in'], {}), '(fan_in)\n', (415, 423), True, 'import numpy as np\n'), ((714, 751), 'torch.nn.Linear', 'nn.Linear', (['num_inputs', 'hidden_size[0]'], {}), '(num_inputs, hidden_size[0])\n', (723, 751), True, 'import torch.nn as nn\n'), ((771, 799), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['hidden_size[0]'], {}), '(hidden_size[0])\n', (783, 799), True, 'import torch.nn as nn\n'), ((842, 883), 'torch.nn.Linear', 'nn.Linear', (['hidden_size[0]', 'hidden_size[1]'], {}), '(hidden_size[0], hidden_size[1])\n', (851, 883), True, 'import torch.nn as nn\n'), ((903, 931), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['hidden_size[1]'], {}), '(hidden_size[1])\n', (915, 931), True, 'import torch.nn as nn\n'), ((974, 1012), 'torch.nn.Linear', 'nn.Linear', (['hidden_size[1]', 'num_outputs'], {}), '(hidden_size[1], num_outputs)\n', (983, 1012), True, 'import torch.nn as nn\n'), ((1238, 1311), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['self.mu.weight', '(-WEIGHTS_FINAL_INIT)', 'WEIGHTS_FINAL_INIT'], {}), '(self.mu.weight, -WEIGHTS_FINAL_INIT, WEIGHTS_FINAL_INIT)\n', (1254, 1311), True, 'import torch.nn as nn\n'), ((1320, 1385), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['self.mu.bias', '(-BIAS_FINAL_INIT)', 'BIAS_FINAL_INIT'], {}), '(self.mu.bias, -BIAS_FINAL_INIT, BIAS_FINAL_INIT)\n', (1336, 1385), True, 'import torch.nn as nn\n'), ((1520, 1529), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (1526, 1529), True, 'import torch.nn.functional as F\n'), ((1613, 1622), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (1619, 1622), True, 'import torch.nn.functional as F\n'), ((1951, 1988), 'torch.nn.Linear', 'nn.Linear', (['num_inputs', 'hidden_size[0]'], {}), '(num_inputs, hidden_size[0])\n', (1960, 1988), True, 'import torch.nn as nn\n'), ((2008, 2036), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['hidden_size[0]'], {}), '(hidden_size[0])\n', (2020, 2036), True, 'import torch.nn as nn\n'), ((2144, 2199), 'torch.nn.Linear', 'nn.Linear', (['(hidden_size[0] + num_outputs)', 'hidden_size[1]'], {}), '(hidden_size[0] + num_outputs, hidden_size[1])\n', (2153, 2199), True, 'import torch.nn as nn\n'), ((2219, 2247), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['hidden_size[1]'], {}), '(hidden_size[1])\n', (2231, 2247), True, 'import torch.nn as nn\n'), ((2304, 2332), 'torch.nn.Linear', 'nn.Linear', (['hidden_size[1]', '(1)'], {}), '(hidden_size[1], 1)\n', (2313, 2332), True, 'import torch.nn as nn\n'), ((2558, 2630), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['self.V.weight', '(-WEIGHTS_FINAL_INIT)', 'WEIGHTS_FINAL_INIT'], {}), '(self.V.weight, -WEIGHTS_FINAL_INIT, WEIGHTS_FINAL_INIT)\n', (2574, 2630), True, 'import torch.nn as nn\n'), ((2639, 2703), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['self.V.bias', '(-BIAS_FINAL_INIT)', 'BIAS_FINAL_INIT'], {}), '(self.V.bias, -BIAS_FINAL_INIT, BIAS_FINAL_INIT)\n', (2655, 2703), True, 'import torch.nn as nn\n'), ((2847, 2856), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (2853, 2856), True, 'import torch.nn.functional as F\n'), ((2888, 2914), 'torch.cat', 'torch.cat', (['(x, actions)', '(1)'], {}), '((x, actions), 1)\n', (2897, 2914), False, 'import torch\n'), ((3001, 3010), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (3007, 3010), True, 'import torch.nn.functional as F\n')]
""" Created on Tuesday 20 February 2018 Last update: Sunday 11 March 2018 @author: <NAME> <EMAIL> Solution for the lecture optimal transport """ from itertools import permutations import numpy as np from sklearn.metrics.pairwise import pairwise_distances from random import shuffle blue = '#264653' green = '#2a9d8f' yellow = '#e9c46a' orange = '#f4a261' red = '#e76f51' black = '#50514F' def shuffle_rows(X): """ Randomly shuffles rows of a numpy matrix """ n, _ = X.shape indices = list(range(n)) shuffle(indices) X[:] = X[indices] def monge_brute_force(C): """ Solves the Monge assignment problem using brute force. Inputs: - C: cost matrix (square, size n x n) Outputs: - best_perm: optimal assigments (list of n indices matching the rows to the columns) - best_cost: optimal cost corresponding to the best permutation DO NOT USE FOR PROBLEMS OF A SIZE LARGER THAN 12!!! """ n, m = C.shape assert n==m # C should be square best_perm = None best_cost = np.inf for perm in permutations(range(n)): cost = 0 for i, p_i in enumerate(perm): cost += C[i, p_i] if cost < best_cost: best_cost = cost best_perm = perm return best_perm, best_cost def compute_optimal_transport(C, a, b, lam, epsilon=1e-8, verbose=False, return_iterations=False): """ Computes the optimal transport matrix and Slinkhorn distance using the Sinkhorn-Knopp algorithm Inputs: - C : cost matrix (n x m) - a : vector of marginals (n, ) - b : vector of marginals (m, ) - lam : strength of the entropic regularization - epsilon : convergence parameter - verbose : report number of steps while running - return_iterations : report number of iterations till convergence, default False Output: - P : optimal transport matrix (n x m) - dist : Sinkhorn distance - n_iterations : number of iterations, if `return_iterations` is set to True """ n, m = C.shape P = np.exp(- lam * C) iteration = 0 while True: iteration += 1 u = P.sum(1) # marginals of rows max_deviation = np.max(np.abs(u - a)) if verbose: print('Iteration {}: max deviation={}'.format( iteration, max_deviation )) if max_deviation < epsilon: break # scale rows P *= (a / u).reshape((-1, 1)) # scale columns P *= (b / P.sum(0)).reshape((1, -1)) if return_iterations: return P, np.sum(P * C), iteration else: return P, np.sum(P * C) def barrycenters_entropic(B, C, weights, lam=1, L=100): """ Finds a barrycenter of Sinkhorn distances for a set of proabiltiy vectors (of same dimension) with a cost matrix and a set of weigths. Inputs: - B: matrix containing the probability vectors (n x s), positive and normalized - C: cost matrix (n x n), same everywhere - weigths: s weights for the relative importance - lam: strength of the entropic regularization - L: number of Sinkhorn updates Output: - a: barrycenter (probability vector) """ n, s = B.shape K = np.exp(- lam * C) U = np.ones_like(B) / n V = np.zeros_like(B) a = np.zeros((n, 1)) for step in range(L): # update V V[:] = B / (K.T @ U) # update a a[:] = np.exp(np.sum(np.log(K @ V) * weights.reshape((1, s)), axis=1, keepdims=True)) U[:] = a / (K @ V) return a if __name__ == '__main__': import matplotlib.pyplot as plt B = np.zeros((10, 2)) B[:5,0] = 0.2 B[5:,1] = 0.2 C = pairwise_distances(np.arange(10).reshape((-1,1)), metric='sqeuclidean') A = np.zeros((10, 11)) for i in range(11): A[:,i] = barrycenters_entropic(B, C, np.array((1-i/10, 0+i/10)))[:,0] plt.imshow(A, interpolation='nearest') plt.savefig('Figures/simpleinterpol.png') # images dim = 50 B = np.zeros((dim**2, 4)) # square square = np.zeros((dim, dim)) square[dim//4:-dim//4,:][:,dim//4:-dim//4] = 1 B[:,0] = square.flatten() # circle circle = np.array([[(i-dim/2)**2+(j-dim/2)**2 < dim**2 / 4**2 for i in range(dim)] for j in range(dim)], dtype=float) circle -= np.array([[(i-dim/2)**2+(j-dim/2)**2 < dim**2 / 6**2 for i in range(dim)] for j in range(dim)], dtype=float) B[:,1] = circle.flatten() # diamond diamond = np.array([[np.abs(i-dim/2)+np.abs(j-dim/2) < dim/4 for i in range(dim)] for j in range(dim)], dtype=float) B[:,2] = diamond.flatten() """ # cross cross = np.zeros((dim, dim)) cross[dim//3:-dim//3,:] = 1 cross[:, dim//3:-dim//3] = 1 B[:,3] = cross.flatten() """ # two blobs two_blobs = np.zeros((dim, dim)) two_blobs[:] += np.array([[(i-dim/4)**2+(j-dim/4)**2 < (dim/10)**2 for i in range(dim)] for j in range(dim)], dtype=float) two_blobs[:] += np.array([[(i-dim/4*3)**2+(j-dim/4*3)**2 < (dim/10)**2 for i in range(dim)] for j in range(dim)], dtype=float) B[:,3] = two_blobs.flatten() B /= B.sum(0) C = pairwise_distances([[i/dim, j/dim] for i in range(dim) for j in range(dim)], metric="sqeuclidean") A = np.zeros((dim**2, 25)) image_nr = 0 for di in np.linspace(0, 1, 5): for dj in np.linspace(0, 1, 5): weights = np.array([ (1-di) * (1-dj), di * (1-dj), (1-di) * dj, di * dj ]) A[:,image_nr] = barrycenters_entropic(B, C, weights, lam=500, L=50)[:,0] image_nr += 1 fig, axes = plt.subplots(nrows=5, ncols=5) for i in range(5): for j in range(5): ax = axes[i, j] ax.imshow(A[:,i+5*j].reshape((dim,dim)) > 1e-5, cmap='Greys', interpolation='nearest') ax.set_yticks([]) ax.set_xticks([]) plt.savefig('Figures/barrycenters.png')
[ "matplotlib.pyplot.imshow", "numpy.ones_like", "numpy.abs", "matplotlib.pyplot.savefig", "random.shuffle", "numpy.log", "numpy.exp", "numpy.sum", "numpy.zeros", "numpy.linspace", "numpy.array", "numpy.zeros_like", "matplotlib.pyplot.subplots", "numpy.arange" ]
[((528, 544), 'random.shuffle', 'shuffle', (['indices'], {}), '(indices)\n', (535, 544), False, 'from random import shuffle\n'), ((2186, 2202), 'numpy.exp', 'np.exp', (['(-lam * C)'], {}), '(-lam * C)\n', (2192, 2202), True, 'import numpy as np\n'), ((3410, 3426), 'numpy.exp', 'np.exp', (['(-lam * C)'], {}), '(-lam * C)\n', (3416, 3426), True, 'import numpy as np\n'), ((3464, 3480), 'numpy.zeros_like', 'np.zeros_like', (['B'], {}), '(B)\n', (3477, 3480), True, 'import numpy as np\n'), ((3489, 3505), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (3497, 3505), True, 'import numpy as np\n'), ((3806, 3823), 'numpy.zeros', 'np.zeros', (['(10, 2)'], {}), '((10, 2))\n', (3814, 3823), True, 'import numpy as np\n'), ((3966, 3984), 'numpy.zeros', 'np.zeros', (['(10, 11)'], {}), '((10, 11))\n', (3974, 3984), True, 'import numpy as np\n'), ((4092, 4130), 'matplotlib.pyplot.imshow', 'plt.imshow', (['A'], {'interpolation': '"""nearest"""'}), "(A, interpolation='nearest')\n", (4102, 4130), True, 'import matplotlib.pyplot as plt\n'), ((4135, 4176), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Figures/simpleinterpol.png"""'], {}), "('Figures/simpleinterpol.png')\n", (4146, 4176), True, 'import matplotlib.pyplot as plt\n'), ((4212, 4235), 'numpy.zeros', 'np.zeros', (['(dim ** 2, 4)'], {}), '((dim ** 2, 4))\n', (4220, 4235), True, 'import numpy as np\n'), ((4261, 4281), 'numpy.zeros', 'np.zeros', (['(dim, dim)'], {}), '((dim, dim))\n', (4269, 4281), True, 'import numpy as np\n'), ((5033, 5053), 'numpy.zeros', 'np.zeros', (['(dim, dim)'], {}), '((dim, dim))\n', (5041, 5053), True, 'import numpy as np\n'), ((5502, 5526), 'numpy.zeros', 'np.zeros', (['(dim ** 2, 25)'], {}), '((dim ** 2, 25))\n', (5510, 5526), True, 'import numpy as np\n'), ((5557, 5577), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(5)'], {}), '(0, 1, 5)\n', (5568, 5577), True, 'import numpy as np\n'), ((5954, 5984), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(5)', 'ncols': '(5)'}), '(nrows=5, ncols=5)\n', (5966, 5984), True, 'import matplotlib.pyplot as plt\n'), ((6255, 6294), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Figures/barrycenters.png"""'], {}), "('Figures/barrycenters.png')\n", (6266, 6294), True, 'import matplotlib.pyplot as plt\n'), ((3436, 3451), 'numpy.ones_like', 'np.ones_like', (['B'], {}), '(B)\n', (3448, 3451), True, 'import numpy as np\n'), ((5597, 5617), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(5)'], {}), '(0, 1, 5)\n', (5608, 5617), True, 'import numpy as np\n'), ((2334, 2347), 'numpy.abs', 'np.abs', (['(u - a)'], {}), '(u - a)\n', (2340, 2347), True, 'import numpy as np\n'), ((2722, 2735), 'numpy.sum', 'np.sum', (['(P * C)'], {}), '(P * C)\n', (2728, 2735), True, 'import numpy as np\n'), ((2775, 2788), 'numpy.sum', 'np.sum', (['(P * C)'], {}), '(P * C)\n', (2781, 2788), True, 'import numpy as np\n'), ((5641, 5711), 'numpy.array', 'np.array', (['[(1 - di) * (1 - dj), di * (1 - dj), (1 - di) * dj, di * dj]'], {}), '([(1 - di) * (1 - dj), di * (1 - dj), (1 - di) * dj, di * dj])\n', (5649, 5711), True, 'import numpy as np\n'), ((3888, 3901), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (3897, 3901), True, 'import numpy as np\n'), ((4054, 4088), 'numpy.array', 'np.array', (['(1 - i / 10, 0 + i / 10)'], {}), '((1 - i / 10, 0 + i / 10))\n', (4062, 4088), True, 'import numpy as np\n'), ((3629, 3642), 'numpy.log', 'np.log', (['(K @ V)'], {}), '(K @ V)\n', (3635, 3642), True, 'import numpy as np\n'), ((4708, 4727), 'numpy.abs', 'np.abs', (['(i - dim / 2)'], {}), '(i - dim / 2)\n', (4714, 4727), True, 'import numpy as np\n'), ((4724, 4743), 'numpy.abs', 'np.abs', (['(j - dim / 2)'], {}), '(j - dim / 2)\n', (4730, 4743), True, 'import numpy as np\n')]
# Credits (inspired & adapted from) @ https://github.com/lcswillems/torch-rl import torch from typing import Tuple import numpy as np from utils.dictlist import DictList from .base import AgentBase class SimulateDict: def __init__(self, obj): self._obj = obj def __getitem__(self, item): return self._obj class BatchBase(AgentBase): """ The base class for the RL algorithms. """ def __init__(self, *args, **kwargs): """ cfg Should contain the following (at least for the base): :cfg num_frames_per_proc: int - the number of frames collected by every process for an update """ super().__init__(*args, **kwargs) cfg = self.cfg # -- Store helpers values self.num_frames_per_proc = cfg.num_frames_per_proc self.use_gae_return = getattr(cfg, "use_gae_return", True) self.num_frames = self.num_frames_per_proc * self.num_procs self._protect_env_data = True # Get from base recurrent = self.recurrent num_procs = self.num_procs device = self.device # -- Initialize experience data holders shape = (self.num_frames_per_proc, num_procs) if recurrent: assert self.num_frames_per_proc % self.recurrence == 0, "Use all observations!" # Get memory size from model self.memory = torch.zeros(shape[1], self.model.memory_size, device=device) self.memories = torch.zeros(*shape, self.model.memory_size, device=device) self.obs = self.env.reset() self.obss = [None] * (shape[0]) self.mask = torch.zeros(shape[1], device=device) self.masks = torch.zeros(*shape, device=device) self.actions = torch.zeros(*shape, device=device, dtype=torch.int) self.values = torch.zeros(*shape, device=device) self.rewards = torch.zeros(*shape, device=device) self.advantages = torch.zeros(*shape, device=device) self.log_probs = torch.zeros(*shape, device=device) self.termination_target = torch.zeros(*shape, device=device) self.op_used = torch.zeros(*shape, device=device) self.new_op_mask = torch.zeros(*shape, device=device) self.obs_termination_target = torch.zeros(num_procs, device=device) if not self.use_gae_return: self.rreturn = torch.zeros(*shape, device=device) self.log_episode_return = torch.zeros(num_procs, device=device) self.log_episode_num_frames = torch.zeros(num_procs, device=device) # -- Init evaluation environments and storage data if self.has_evaluator: eval_envs = self.eval_envs obs = eval_envs.reset() if self.recurrent: self.eval_memory = torch.zeros(len(obs), self.model.memory_size, device=device) self.eval_mask = torch.ones(len(obs), device=device) self.eval_rewards = torch.zeros(len(obs), device=device) def update_parameters(self) -> dict: """ [REPLACE] Implement agent training """ # -- Collect experiences exps, logs = self._collect_experiences() # -- Train Loop # ... return logs def _collect_experiences(self) -> Tuple[DictList, dict]: """ Collects rollouts and computes advantages. Runs several environments concurrently. The next actions are computed in a batch mode for all environments at the same time. The rollouts and advantages from all environments are concatenated together. * considers model with recurrent data Returns ------- exps : DictList --> shapes: (num_frames_per_proc * num_envs, ...) Contains actions, rewards, advantages etc as attributes. Each attribute, e.g. `exps.reward` has a shape (self.num_frames_per_proc * num_envs, ...). k-th block of consecutive `self.num_frames_per_proc` frames contains data obtained from the k-th environment. Be careful not to mix data from different environments! logs : dict Useful stats about the training process, including the average reward etc. """ model = self.model num_procs = self.num_procs num_frames_per_proc = self.num_frames_per_proc preprocess_obss = self.preprocess_obss device = self.device recurrent = self.recurrent log_episode_return = self.log_episode_return log_episode_num_frames = self.log_episode_num_frames discount = self.discount gae_lambda = self.gae_lambda masks = self.masks values = self.values advantages = self.advantages rewards = self.rewards actions = self.actions obss = self.obss log_probs = self.log_probs termination_target = self.termination_target use_gae_return = self.use_gae_return protect_env_data = self._protect_env_data memory = None dtype = torch.float self.log_done_counter = 0 self.log_return = log_return = [] self.log_num_frames = log_num_frames = [] for i in range(num_frames_per_proc): # -- Do one agent-environment interaction preprocessed_obs = preprocess_obss(self.obs, device=device) with torch.no_grad(): if recurrent: res_m = model( preprocessed_obs, mask=self.mask, memory=self.memory * self.mask.unsqueeze(1) ) else: res_m = model(preprocessed_obs, mask=self.mask) action, act_log_prob, value = res_m["actions"], \ res_m["act_log_probs"], \ res_m["values"] obs, reward, done, info = self.env.step(self._process_actions_for_step(action, res_m)) if not protect_env_data: obs, reward, done, info = list(obs), list(reward), list(done), list(info) # -- Process other useful information each step self._collect_experiences_step(i, obs, reward, done, info, preprocessed_obs, res_m) # -- Update experiences values obss[i] = self.obs termination_target[i] = self.obs_termination_target if "termination_target" in res_m: self.obs_termination_target = res_m["termination_target"] self.op_used[i] = res_m["crt_op_idx"] self.new_op_mask[i] = res_m["new_op_mask"] self.obs = obs if recurrent: self.memories[i] = self.memory self.memory = res_m["memory"] masks[i] = self.mask self.mask = torch.tensor(1.) - torch.tensor(done, device=device, dtype=dtype) actions[i] = action values[i] = value rewards[i] = torch.tensor(reward, device=device) log_probs[i] = act_log_prob # Update log values log_episode_return += torch.tensor(reward, device=device, dtype=dtype) log_episode_num_frames += torch.ones(num_procs, device=device) for j, done_ in enumerate(done): if done_: self.log_done_counter += 1 log_return.append(log_episode_return[j].item()) log_num_frames.append(log_episode_num_frames[j].item()) log_episode_return *= self.mask log_episode_num_frames *= self.mask # -- Add advantage and return to experiences preprocessed_obs = preprocess_obss(self.obs, device=device) with torch.no_grad(): if recurrent: res_last_obs = model(preprocessed_obs, memory=self.memory * self.mask.unsqueeze(1)) next_value = res_last_obs["values"] else: res_last_obs = model(preprocessed_obs) next_value = res_last_obs["values"] if not use_gae_return: rreturn = self.rreturn for i in reversed(range(num_frames_per_proc)): next_mask = masks[i + 1] if i < num_frames_per_proc - 1 else self.mask next_value = values[i + 1] if i < num_frames_per_proc - 1 else next_value next_advantage = advantages[i + 1] if i < num_frames_per_proc - 1 else 0 delta = rewards[i] + discount * next_value * next_mask - values[i] advantages[i] = delta + discount * gae_lambda * next_advantage * next_mask if not use_gae_return: next_rreturn = rreturn[i + 1] if i < num_frames_per_proc - 1 else next_value rreturn[i] = next_rreturn * discount * next_mask + rewards[i] # Define experiences: # the whole experience is the concatenation of the experience # of each process. # In comments below: # - T is self.num_frames_per_proc, # - P is self.num_procs, # - D is the dimensionality. exps = DictList() exps.obs = [obss[i][j] for j in range(num_procs) for i in range(num_frames_per_proc)] if recurrent: # T x P x D -> P x T x D -> (P * T) x D exps.memory = self.memories.transpose(0, 1).reshape(-1, *self.memories.shape[2:]) # T x P -> P x T -> (P * T) x 1 exps.mask = masks.transpose(0, 1).reshape(-1).unsqueeze(1) # for all tensors below, T x P -> P x T -> P * T exps.action = actions.transpose(0, 1).reshape(-1) exps.value = values.transpose(0, 1).reshape(-1) exps.reward = rewards.transpose(0, 1).reshape(-1) exps.advantage = advantages.transpose(0, 1).reshape(-1) exps.returnn = (exps.value + exps.advantage) if use_gae_return else \ self.rreturn.transpose(0, 1).reshape(-1) exps.log_prob = log_probs.transpose(0, 1).reshape(-1) exps.termination_target = termination_target.transpose(0, 1).reshape(-1) # Pre-process experiences exps.obs = preprocess_obss(exps.obs, device=device) exps.res_last_obs = SimulateDict(res_last_obs) log = { "return_per_episode": log_return, "num_frames_per_episode": log_num_frames, "num_frames": [self.num_frames] } extra_logs = self._collect_experiences_finished() log.update(extra_logs) return exps, log def _process_actions_for_step(self, actions, model_results): return actions.cpu().numpy() def _get_batches_starting_indexes(self, batch_size: int, shift_start_idx: bool = False): """ Get batches of indexes. Take recurrence into consideration to separate indexes. """ recurrence = self.recurrence num_frames = self.num_frames indexes = np.arange(0, num_frames, recurrence) indexes = np.random.permutation(indexes) # Shift starting indexes by recurrence//2 if shift_start_idx: # Eliminate last index from environment trajectory (so not to overshoot) indexes = indexes[(indexes + recurrence) % self.num_frames_per_proc != 0] indexes += recurrence // 2 num_indexes = batch_size // recurrence batches_starting_indexes = [indexes[i:i+num_indexes] for i in range(0, len(indexes), num_indexes)] return batches_starting_indexes def _save_experience(self, update_step: int, exps: DictList, logs: dict): if self.save_experience <= 0: return # TODO Hackish way to save experience - norm_value = self.max_image_value nstep = self.save_experience * self.num_frames_per_proc experience = dict() experience["logs"] = logs experience["obs_image"] = (exps.obs.image[:nstep].cpu() * norm_value).byte() experience["mask"] = exps.mask[:nstep].cpu() experience["action"] = exps.action[:nstep].cpu() experience["reward"] = exps.reward[:nstep].cpu() experience["num_procs"] = self.save_experience experience["frames_per_proc"] = self.num_frames_per_proc experience["norm_value"] = norm_value torch.save(experience, f"{self.experience_dir}/exp_update_{update_step}")
[ "torch.ones", "torch.tensor", "torch.save", "utils.dictlist.DictList", "torch.no_grad", "torch.zeros", "numpy.arange", "numpy.random.permutation" ]
[((1657, 1693), 'torch.zeros', 'torch.zeros', (['shape[1]'], {'device': 'device'}), '(shape[1], device=device)\n', (1668, 1693), False, 'import torch\n'), ((1715, 1749), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device'}), '(*shape, device=device)\n', (1726, 1749), False, 'import torch\n'), ((1773, 1824), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device', 'dtype': 'torch.int'}), '(*shape, device=device, dtype=torch.int)\n', (1784, 1824), False, 'import torch\n'), ((1847, 1881), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device'}), '(*shape, device=device)\n', (1858, 1881), False, 'import torch\n'), ((1905, 1939), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device'}), '(*shape, device=device)\n', (1916, 1939), False, 'import torch\n'), ((1966, 2000), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device'}), '(*shape, device=device)\n', (1977, 2000), False, 'import torch\n'), ((2026, 2060), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device'}), '(*shape, device=device)\n', (2037, 2060), False, 'import torch\n'), ((2095, 2129), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device'}), '(*shape, device=device)\n', (2106, 2129), False, 'import torch\n'), ((2153, 2187), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device'}), '(*shape, device=device)\n', (2164, 2187), False, 'import torch\n'), ((2215, 2249), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device'}), '(*shape, device=device)\n', (2226, 2249), False, 'import torch\n'), ((2288, 2325), 'torch.zeros', 'torch.zeros', (['num_procs'], {'device': 'device'}), '(num_procs, device=device)\n', (2299, 2325), False, 'import torch\n'), ((2460, 2497), 'torch.zeros', 'torch.zeros', (['num_procs'], {'device': 'device'}), '(num_procs, device=device)\n', (2471, 2497), False, 'import torch\n'), ((2536, 2573), 'torch.zeros', 'torch.zeros', (['num_procs'], {'device': 'device'}), '(num_procs, device=device)\n', (2547, 2573), False, 'import torch\n'), ((9160, 9170), 'utils.dictlist.DictList', 'DictList', ([], {}), '()\n', (9168, 9170), False, 'from utils.dictlist import DictList\n'), ((11024, 11060), 'numpy.arange', 'np.arange', (['(0)', 'num_frames', 'recurrence'], {}), '(0, num_frames, recurrence)\n', (11033, 11060), True, 'import numpy as np\n'), ((11083, 11113), 'numpy.random.permutation', 'np.random.permutation', (['indexes'], {}), '(indexes)\n', (11104, 11113), True, 'import numpy as np\n'), ((12490, 12563), 'torch.save', 'torch.save', (['experience', 'f"""{self.experience_dir}/exp_update_{update_step}"""'], {}), "(experience, f'{self.experience_dir}/exp_update_{update_step}')\n", (12500, 12563), False, 'import torch\n'), ((1411, 1471), 'torch.zeros', 'torch.zeros', (['shape[1]', 'self.model.memory_size'], {'device': 'device'}), '(shape[1], self.model.memory_size, device=device)\n', (1422, 1471), False, 'import torch\n'), ((1500, 1558), 'torch.zeros', 'torch.zeros', (['*shape', 'self.model.memory_size'], {'device': 'device'}), '(*shape, self.model.memory_size, device=device)\n', (1511, 1558), False, 'import torch\n'), ((2390, 2424), 'torch.zeros', 'torch.zeros', (['*shape'], {'device': 'device'}), '(*shape, device=device)\n', (2401, 2424), False, 'import torch\n'), ((7035, 7070), 'torch.tensor', 'torch.tensor', (['reward'], {'device': 'device'}), '(reward, device=device)\n', (7047, 7070), False, 'import torch\n'), ((7178, 7226), 'torch.tensor', 'torch.tensor', (['reward'], {'device': 'device', 'dtype': 'dtype'}), '(reward, device=device, dtype=dtype)\n', (7190, 7226), False, 'import torch\n'), ((7265, 7301), 'torch.ones', 'torch.ones', (['num_procs'], {'device': 'device'}), '(num_procs, device=device)\n', (7275, 7301), False, 'import torch\n'), ((7793, 7808), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7806, 7808), False, 'import torch\n'), ((5397, 5412), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5410, 5412), False, 'import torch\n'), ((6881, 6898), 'torch.tensor', 'torch.tensor', (['(1.0)'], {}), '(1.0)\n', (6893, 6898), False, 'import torch\n'), ((6900, 6946), 'torch.tensor', 'torch.tensor', (['done'], {'device': 'device', 'dtype': 'dtype'}), '(done, device=device, dtype=dtype)\n', (6912, 6946), False, 'import torch\n')]
from __future__ import annotations import numpy as np import pytest from .helpers import ( # noqa: F401 assert_eq, line_delim_records_file, load_records_eager, load_records_lazy, ) def test_ufunc_add(line_delim_records_file) -> None: # noqa: F811 daa = load_records_lazy(line_delim_records_file).analysis.x1 caa = load_records_eager(line_delim_records_file).analysis.x1 a1 = daa + 2 a2 = caa + 2 assert_eq(a1, a2) def test_ufunc_sin(line_delim_records_file) -> None: # noqa: F811 daa = load_records_lazy(line_delim_records_file).analysis.x1 caa = load_records_eager(line_delim_records_file).analysis.x1 a1 = np.sin(daa) a2 = np.sin(caa) assert_eq(a1, a2) @pytest.mark.parametrize("f", [np.add.accumulate, np.add.reduce]) def test_ufunc_method_raise(line_delim_records_file, f) -> None: # noqa: F811 daa = load_records_lazy(line_delim_records_file).analysis.x1 with pytest.raises(NotImplementedError, match="Array ufunc supports only method"): f(daa, daa)
[ "numpy.sin", "pytest.mark.parametrize", "pytest.raises" ]
[((723, 787), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""f"""', '[np.add.accumulate, np.add.reduce]'], {}), "('f', [np.add.accumulate, np.add.reduce])\n", (746, 787), False, 'import pytest\n'), ((665, 676), 'numpy.sin', 'np.sin', (['daa'], {}), '(daa)\n', (671, 676), True, 'import numpy as np\n'), ((686, 697), 'numpy.sin', 'np.sin', (['caa'], {}), '(caa)\n', (692, 697), True, 'import numpy as np\n'), ((941, 1017), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {'match': '"""Array ufunc supports only method"""'}), "(NotImplementedError, match='Array ufunc supports only method')\n", (954, 1017), False, 'import pytest\n')]
#<NAME> from estrategias.jogadores import Jogador import numpy import numpy as np import os.path from numpy import round import pickle import random listaRep5=[] def n_melhores(a1,n): 'a=lista n=posições' a=list(a1) a.sort() return a[-n:] class MeuJogador(Jogador): def __init__(self): Jogador.__init__(self) def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores): n_jogadores=len(reputacoes_dos_jogadores) 'criação' global listaRep5 arquivo5 = open('estrategias/ArquivoD.pck', 'wb') listaRep5.append(round(reputacao_atual,12)) pickle.dump(listaRep5, arquivo5) arquivo5.close() 'criado' meta_reputacao=0.6 meta_rodada=150 if rodada > meta_rodada: escolhas=[] for i in range(len(reputacoes_dos_jogadores)): if reputacoes_dos_jogadores[i] == reputacao_atual: escolhas=escolhas+['c'] else: escolhas=escolhas+['d'] return escolhas else: escolhas=[] for i in range(len(reputacoes_dos_jogadores)): if (rodada != 1) and (reputacoes_dos_jogadores[i]==1 or reputacoes_dos_jogadores[i]==0): escolhas=escolhas+['d'] elif reputacao_atual > meta_reputacao: escolhas=escolhas+['d'] else: escolhas=escolhas+['c'] if rodada>12: 'ajudando eren' Existe=os.path.exists('estrategias/ArquivoA.pck') if Existe==True: #Busca informação' file = open('estrategias/ArquivoA.pck','rb') x = pickle.load(file) file.close() for i in range(len(reputacoes_dos_jogadores)): casas_dec=12 booleano=True while booleano==True: if round(reputacoes_dos_jogadores[i],casas_dec)!=round(x[-1],casas_dec): casas_dec-=1 booleano=True else: booleano=False if casas_dec==3: break if round(reputacoes_dos_jogadores[i],casas_dec)==round(x[-1],casas_dec): escolhas[i]='c' 'ajudando levi' Existe=os.path.exists('estrategias/ArquivoB.pck') if Existe==True: #Busca informação' file = open('estrategias/ArquivoB.pck','rb') x = pickle.load(file) file.close() for i in range(len(reputacoes_dos_jogadores)): casas_dec=12 booleano=True while booleano==True: if round(reputacoes_dos_jogadores[i],casas_dec)!=round(x[-1],casas_dec): casas_dec-=1 booleano=True else: booleano=False if casas_dec==3: break if round(reputacoes_dos_jogadores[i],casas_dec)==round(x[-1],casas_dec): escolhas[i]='c' 'ajudando barbie' Existe1=os.path.exists('estrategias/ArquivoC.pck') if Existe1==True: #Busca informação' file = open('estrategias/ArquivoC.pck','rb') x = pickle.load(file) file.close() for i in range(len(reputacoes_dos_jogadores)): casas_dec=12 booleano=True while booleano==True: if round(reputacoes_dos_jogadores[i],casas_dec)!=round(x[-1],casas_dec): casas_dec-=3 booleano=True else: booleano=False if casas_dec==3: break if round(reputacoes_dos_jogadores[i],casas_dec)==round(x[-1],casas_dec): escolhas[i]='c' if comida_atual-3*len(reputacoes_dos_jogadores)<100: if len(reputacoes_dos_jogadores)<4: if rodada%20==0: escolhas=['d']*len(reputacoes_dos_jogadores) if len(reputacoes_dos_jogadores)<5: if comida_atual<50: if rodada%100==0: print('=================') print('= T A T A K A E =') print('=================') return escolhas
[ "numpy.round", "pickle.load", "pickle.dump", "estrategias.jogadores.Jogador.__init__" ]
[((325, 347), 'estrategias.jogadores.Jogador.__init__', 'Jogador.__init__', (['self'], {}), '(self)\n', (341, 347), False, 'from estrategias.jogadores import Jogador\n'), ((675, 707), 'pickle.dump', 'pickle.dump', (['listaRep5', 'arquivo5'], {}), '(listaRep5, arquivo5)\n', (686, 707), False, 'import pickle\n'), ((640, 666), 'numpy.round', 'round', (['reputacao_atual', '(12)'], {}), '(reputacao_atual, 12)\n', (645, 666), False, 'from numpy import round\n'), ((1894, 1911), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (1905, 1911), False, 'import pickle\n'), ((2824, 2841), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (2835, 2841), False, 'import pickle\n'), ((3758, 3775), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (3769, 3775), False, 'import pickle\n'), ((2471, 2516), 'numpy.round', 'round', (['reputacoes_dos_jogadores[i]', 'casas_dec'], {}), '(reputacoes_dos_jogadores[i], casas_dec)\n', (2476, 2516), False, 'from numpy import round\n'), ((2517, 2540), 'numpy.round', 'round', (['x[-1]', 'casas_dec'], {}), '(x[-1], casas_dec)\n', (2522, 2540), False, 'from numpy import round\n'), ((3401, 3446), 'numpy.round', 'round', (['reputacoes_dos_jogadores[i]', 'casas_dec'], {}), '(reputacoes_dos_jogadores[i], casas_dec)\n', (3406, 3446), False, 'from numpy import round\n'), ((3447, 3470), 'numpy.round', 'round', (['x[-1]', 'casas_dec'], {}), '(x[-1], casas_dec)\n', (3452, 3470), False, 'from numpy import round\n'), ((4335, 4380), 'numpy.round', 'round', (['reputacoes_dos_jogadores[i]', 'casas_dec'], {}), '(reputacoes_dos_jogadores[i], casas_dec)\n', (4340, 4380), False, 'from numpy import round\n'), ((4381, 4404), 'numpy.round', 'round', (['x[-1]', 'casas_dec'], {}), '(x[-1], casas_dec)\n', (4386, 4404), False, 'from numpy import round\n'), ((2146, 2191), 'numpy.round', 'round', (['reputacoes_dos_jogadores[i]', 'casas_dec'], {}), '(reputacoes_dos_jogadores[i], casas_dec)\n', (2151, 2191), False, 'from numpy import round\n'), ((2192, 2215), 'numpy.round', 'round', (['x[-1]', 'casas_dec'], {}), '(x[-1], casas_dec)\n', (2197, 2215), False, 'from numpy import round\n'), ((3076, 3121), 'numpy.round', 'round', (['reputacoes_dos_jogadores[i]', 'casas_dec'], {}), '(reputacoes_dos_jogadores[i], casas_dec)\n', (3081, 3121), False, 'from numpy import round\n'), ((3122, 3145), 'numpy.round', 'round', (['x[-1]', 'casas_dec'], {}), '(x[-1], casas_dec)\n', (3127, 3145), False, 'from numpy import round\n'), ((4010, 4055), 'numpy.round', 'round', (['reputacoes_dos_jogadores[i]', 'casas_dec'], {}), '(reputacoes_dos_jogadores[i], casas_dec)\n', (4015, 4055), False, 'from numpy import round\n'), ((4056, 4079), 'numpy.round', 'round', (['x[-1]', 'casas_dec'], {}), '(x[-1], casas_dec)\n', (4061, 4079), False, 'from numpy import round\n')]
from gui.window import Form from gui.draw import * from PIL import Image, ImageQt import random, io, os import numpy as np import torch import cv2 import torchvision.transforms as transforms from util import util import os import torch import torch.nn.functional as F import torchvision.transforms.functional as TF from pconv.model import PConvUNet class model(QtWidgets.QWidget, Form): shape = 'line' CurrentWidth = 1 def __init__(self, opt): super(model, self).__init__() self.setupUi(self) self.opt = opt # self.show_image = None self.show_result_flag = False self.opt.loadSize = [256, 256] self.img_root = './results/' self.graphicsView_2.setMaximumSize(self.opt.loadSize[0]+30, self.opt.loadSize[1]+30) self.device = torch.device("cpu") # Define the model print("Loading the Model...") self.model = PConvUNet(finetune=False, layer_size=7) self.model.load_state_dict(torch.load("model.pth", map_location=self.device)['model']) self.model.to(self.device) self.model.eval() # show logo self.show_logo() # original mask self.new_painter() # selcet model #self.comboBox.activated.connect(self.load_model) # load image self.pushButton.clicked.connect(self.load_image) # save result self.pushButton_4.clicked.connect(self.save_result) # draw/erasure the mask self.radioButton.toggled.connect(lambda: self.draw_mask('line')) self.radioButton_2.toggled.connect(lambda: self.draw_mask('rectangle')) self.spinBox.valueChanged.connect(self.change_thickness) # erase self.pushButton_5.clicked.connect(self.clear_mask) # fill image, image process self.transform = transforms.Compose([transforms.ToTensor()]) self.pushButton_3.clicked.connect(self.predict) # show the result self.pushButton_6.clicked.connect(self.show_result) def showImage(self, fname): """Show the masked images""" #value = self.comboBox.currentIndex() img = Image.open(fname).convert('RGB') self.img_original = img.resize(self.opt.loadSize) self.img = self.img_original self.show_image = ImageQt.ImageQt(self.img) self.new_painter(self.show_image) def show_result(self): """Show the results and original image""" if self.show_result_flag: self.show_result_flag = False out = TF.to_pil_image(self.img_out) new_pil_image = out new_qt_image = ImageQt.ImageQt(new_pil_image) else: self.show_result_flag = True new_qt_image = ImageQt.ImageQt(self.img_original) self.graphicsView_2.scene = QtWidgets.QGraphicsScene() item = QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap.fromImage(new_qt_image)) self.graphicsView_2.scene.addItem(item) self.graphicsView_2.setScene(self.graphicsView_2.scene) def show_logo(self): img = QtWidgets.QLabel(self) img.setGeometry(750, 20, 140, 50) # read images pixmap = QtGui.QPixmap("./gui/icon.png") pixmap = pixmap.scaled(100, 100, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation) img.setPixmap(pixmap) img.show() def load_model(self): """Load different kind models for different datasets and mask types""" #value = self.comboBox.currentIndex() if value == 0: raise NotImplementedError("Please choose a model") else: # define the model type and dataset type index = value-1 self.opt.name = self.model_name[index] self.model = create_model(self.opt) def load_image(self): """Load the image""" self.fname, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'select the image', os.path.expanduser("~"), 'Image files(*.jpg *.png)') self.showImage(self.fname) def save_result(self): self.opt.results_dir = "./results" """Save the results to the disk""" util.mkdir(self.opt.results_dir) img_name = self.fname.split('/')[-1] # save the original image original_name = '%s_%s' % ('original', img_name) original_path = os.path.join(self.opt.results_dir, original_name) img_original = util.tensor2im(self.img_truth) util.save_image(img_original, original_path) # save the mask mask_name = '%s_%d_%s' % ('mask', self.PaintPanel.iteration, img_name) mask_path = os.path.join(self.opt.results_dir, mask_name) img_mask = util.tensor2im(self.img_c) ret, img_mask = cv2.threshold(img_mask, 150, 255, cv2.THRESH_BINARY) util.save_image(img_mask, mask_path) # save the results result_name = '%s_%d_%s' % ('result', self.PaintPanel.iteration, img_name) result_path = os.path.join(self.opt.results_dir, result_name) img_result = TF.to_pil_image(self.img_out) img_result = np.array(img_result) util.save_image(img_result, result_path) def new_painter(self, image=None): """Build a painter to load and process the image""" # painter self.PaintPanel = painter(self, image) self.PaintPanel.close() self.stackedWidget.insertWidget(0, self.PaintPanel) self.stackedWidget.setCurrentWidget(self.PaintPanel) def change_thickness(self, num): """Change the width of the painter""" self.CurrentWidth = num self.PaintPanel.CurrentWidth = num def draw_mask(self, maskStype): """Draw the mask""" self.shape = maskStype self.PaintPanel.shape = maskStype def clear_mask(self): """Clear the mask""" self.showImage(self.fname) if self.PaintPanel.Brush: self.PaintPanel.Brush = False else: self.PaintPanel.Brush = True def set_input(self): """Set the input for the network""" # get the test mask from painter self.PaintPanel.saveDraw() buffer = QtCore.QBuffer() buffer.open(QtCore.QBuffer.ReadWrite) self.PaintPanel.map.save(buffer, 'PNG') pil_im = Image.open(io.BytesIO(buffer.data())) # transform the image to the tensor img = self.transform(self.img) #value = self.comboBox.currentIndex() mask = torch.autograd.Variable(self.transform(pil_im)).unsqueeze(0) # mask from the random mask # mask = Image.open(self.mname) # mask = torch.autograd.Variable(self.transform(mask)).unsqueeze(0) mask = (mask < 1).float() # get I_m and I_c for image with mask and complement regions for training mask = mask self.img_truth = img * 2 - 1 self.img_m = mask * self.img_truth self.img_c = mask return self.img_m, self.img_c, self.img_truth, mask def predict(self): # Loading Input and Mask print("Loading the inputs...") img_m, img_c, img_truth, mask = self.set_input() img_original = util.tensor2im(img_truth) org = Image.fromarray(img_original) org = TF.to_tensor(org.convert('RGB')) img_mask = util.tensor2im(img_c) ret, img_mask = cv2.threshold(img_mask, 150, 255, cv2.THRESH_BINARY) mask = Image.fromarray(img_mask) mask = mask.convert('L') mask = mask.point(lambda x: 0 if x<128 else 255, '1') mask = TF.to_tensor(mask.convert('RGB')) inp = org * mask # Model prediction print("Model Prediction...") with torch.no_grad(): inp_ = inp.unsqueeze(0).to(self.device) mask_ = mask.unsqueeze(0).to(self.device) raw_out, _ = self.model(inp_, mask_) # Post process raw_out = raw_out.to(torch.device('cpu')).squeeze() raw_out = raw_out.clamp(0.0, 1.0) out = mask * inp + (1 - mask) * raw_out self.img_out = out self.show_result_flag = True self.show_result()
[ "PIL.Image.fromarray", "PIL.Image.open", "torchvision.transforms.ToTensor", "cv2.threshold", "torchvision.transforms.functional.to_pil_image", "util.util.tensor2im", "torch.load", "os.path.join", "pconv.model.PConvUNet", "numpy.array", "util.util.mkdir", "torch.no_grad", "util.util.save_imag...
[((811, 830), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (823, 830), False, 'import torch\n'), ((918, 957), 'pconv.model.PConvUNet', 'PConvUNet', ([], {'finetune': '(False)', 'layer_size': '(7)'}), '(finetune=False, layer_size=7)\n', (927, 957), False, 'from pconv.model import PConvUNet\n'), ((2315, 2340), 'PIL.ImageQt.ImageQt', 'ImageQt.ImageQt', (['self.img'], {}), '(self.img)\n', (2330, 2340), False, 'from PIL import Image, ImageQt\n'), ((4158, 4190), 'util.util.mkdir', 'util.mkdir', (['self.opt.results_dir'], {}), '(self.opt.results_dir)\n', (4168, 4190), False, 'from util import util\n'), ((4352, 4401), 'os.path.join', 'os.path.join', (['self.opt.results_dir', 'original_name'], {}), '(self.opt.results_dir, original_name)\n', (4364, 4401), False, 'import os\n'), ((4425, 4455), 'util.util.tensor2im', 'util.tensor2im', (['self.img_truth'], {}), '(self.img_truth)\n', (4439, 4455), False, 'from util import util\n'), ((4464, 4508), 'util.util.save_image', 'util.save_image', (['img_original', 'original_path'], {}), '(img_original, original_path)\n', (4479, 4508), False, 'from util import util\n'), ((4633, 4678), 'os.path.join', 'os.path.join', (['self.opt.results_dir', 'mask_name'], {}), '(self.opt.results_dir, mask_name)\n', (4645, 4678), False, 'import os\n'), ((4698, 4724), 'util.util.tensor2im', 'util.tensor2im', (['self.img_c'], {}), '(self.img_c)\n', (4712, 4724), False, 'from util import util\n'), ((4749, 4801), 'cv2.threshold', 'cv2.threshold', (['img_mask', '(150)', '(255)', 'cv2.THRESH_BINARY'], {}), '(img_mask, 150, 255, cv2.THRESH_BINARY)\n', (4762, 4801), False, 'import cv2\n'), ((4810, 4846), 'util.util.save_image', 'util.save_image', (['img_mask', 'mask_path'], {}), '(img_mask, mask_path)\n', (4825, 4846), False, 'from util import util\n'), ((4980, 5027), 'os.path.join', 'os.path.join', (['self.opt.results_dir', 'result_name'], {}), '(self.opt.results_dir, result_name)\n', (4992, 5027), False, 'import os\n'), ((5049, 5078), 'torchvision.transforms.functional.to_pil_image', 'TF.to_pil_image', (['self.img_out'], {}), '(self.img_out)\n', (5064, 5078), True, 'import torchvision.transforms.functional as TF\n'), ((5100, 5120), 'numpy.array', 'np.array', (['img_result'], {}), '(img_result)\n', (5108, 5120), True, 'import numpy as np\n'), ((5129, 5169), 'util.util.save_image', 'util.save_image', (['img_result', 'result_path'], {}), '(img_result, result_path)\n', (5144, 5169), False, 'from util import util\n'), ((7175, 7200), 'util.util.tensor2im', 'util.tensor2im', (['img_truth'], {}), '(img_truth)\n', (7189, 7200), False, 'from util import util\n'), ((7215, 7244), 'PIL.Image.fromarray', 'Image.fromarray', (['img_original'], {}), '(img_original)\n', (7230, 7244), False, 'from PIL import Image, ImageQt\n'), ((7312, 7333), 'util.util.tensor2im', 'util.tensor2im', (['img_c'], {}), '(img_c)\n', (7326, 7333), False, 'from util import util\n'), ((7358, 7410), 'cv2.threshold', 'cv2.threshold', (['img_mask', '(150)', '(255)', 'cv2.THRESH_BINARY'], {}), '(img_mask, 150, 255, cv2.THRESH_BINARY)\n', (7371, 7410), False, 'import cv2\n'), ((7426, 7451), 'PIL.Image.fromarray', 'Image.fromarray', (['img_mask'], {}), '(img_mask)\n', (7441, 7451), False, 'from PIL import Image, ImageQt\n'), ((2555, 2584), 'torchvision.transforms.functional.to_pil_image', 'TF.to_pil_image', (['self.img_out'], {}), '(self.img_out)\n', (2570, 2584), True, 'import torchvision.transforms.functional as TF\n'), ((2644, 2674), 'PIL.ImageQt.ImageQt', 'ImageQt.ImageQt', (['new_pil_image'], {}), '(new_pil_image)\n', (2659, 2674), False, 'from PIL import Image, ImageQt\n'), ((2757, 2791), 'PIL.ImageQt.ImageQt', 'ImageQt.ImageQt', (['self.img_original'], {}), '(self.img_original)\n', (2772, 2791), False, 'from PIL import Image, ImageQt\n'), ((3948, 3971), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (3966, 3971), False, 'import os\n'), ((7699, 7714), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7712, 7714), False, 'import torch\n'), ((993, 1042), 'torch.load', 'torch.load', (['"""model.pth"""'], {'map_location': 'self.device'}), "('model.pth', map_location=self.device)\n", (1003, 1042), False, 'import torch\n'), ((1864, 1885), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1883, 1885), True, 'import torchvision.transforms as transforms\n'), ((2161, 2178), 'PIL.Image.open', 'Image.open', (['fname'], {}), '(fname)\n', (2171, 2178), False, 'from PIL import Image, ImageQt\n'), ((7924, 7943), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (7936, 7943), False, 'import torch\n')]
# Write exponential sweep to csv for testing. # The sweep was manually inspected. # The time signal was inspected for smootheness and maximum amplitudes of +/-1. # The spectrum was inspected for the ripple at the edges of the frequency range # (typical for time domain sweep generation) and the 1/f slope. import numpy as np from pyfar.signals import exponential_sweep_time sweep = exponential_sweep_time(2**10, [1e3, 20e3]).time np.savetxt("signals.exponential_sweep_time.csv", sweep)
[ "pyfar.signals.exponential_sweep_time", "numpy.savetxt" ]
[((431, 486), 'numpy.savetxt', 'np.savetxt', (['"""signals.exponential_sweep_time.csv"""', 'sweep'], {}), "('signals.exponential_sweep_time.csv', sweep)\n", (441, 486), True, 'import numpy as np\n'), ((383, 433), 'pyfar.signals.exponential_sweep_time', 'exponential_sweep_time', (['(2 ** 10)', '[1000.0, 20000.0]'], {}), '(2 ** 10, [1000.0, 20000.0])\n', (405, 433), False, 'from pyfar.signals import exponential_sweep_time\n')]
import numpy as np import skimage.color import skimage.filters import skimage.io import skimage.viewer # read and display the original image image = skimage.io.imread('images/coins.png') viewer = skimage.viewer.ImageViewer(image) viewer.show() # blur and grayscale before thresholding blur = skimage.color.rgb2gray(image) blur = skimage.filters.gaussian(image, sigma=sigma) # perform adaptive thresholding t = skimage.filters.threshold_otsu(blur) mask = blur > t viewer = skimage.viewer.ImageViewer(mask) viewer.show() # use the mask to select the "interesting" part of the image sel = np.zeros_like(image) sel[mask] = image[mask] # display the result viewer = skimage.viewer.ImageViewer(sel) viewer.show()
[ "numpy.zeros_like" ]
[((592, 612), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (605, 612), True, 'import numpy as np\n')]
# Import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('Social_Network_Ads.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print(f"X = {X}") print(f"Y = {Y}") print() # Split Dataset: Training Set and Test Set from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0) print(f"X_train = {X_train}") print(f"X_test = {X_test}") print(f"Y_train = {Y_train}") print(f"Y_test = {Y_test}") print() # Feature Scaling (done after splitting to avoid information leakage.) from sklearn.preprocessing import StandardScaler standardScaler = StandardScaler() X_train_scaled = standardScaler.fit_transform(X_train) X_test_scaled = standardScaler.transform(X_test) print(f"X_train_scaled = {X_train_scaled}") print(f"X_test_scaled = {X_test_scaled}") print() # K Nearest Neighbors (K-NN) Classifier ## A non-linear model. ## When a data point has an equal number of neighbors, one category is randomly chosen. ### 1. Choose the number K of neighbors (commonly 5). ### 2. Take the K nearest neighbors of data point according to the Euclidean distance. ### 3. Among these K neighbors, count the number of data points in each category. ### 4. Assign the new data point to the category where you counted the most neighbors. # Create and train K Neighbors Classifier Model ## Use the minkowski distance metric and a power parameter of 2 to use the Euclidean metric. from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2) classifier.fit(X_train_scaled, Y_train) # Predict if-purchase for 30 year old customer earning $87,000 Y_predict = classifier.predict(standardScaler.transform([[30, 87000]])) # Output prediction salary for a position 6 print(f"Purchase possible from 30 year old earning $87,000? = {Y_predict}.") print() # Predict using K Nearest-Neighbors (K-NN) model Y_predict = classifier.predict(X_test_scaled) print(f"[Y_predict Y_test] = {np.concatenate((Y_predict.reshape(len(Y_predict), 1), Y_test.reshape(len(Y_test), 1)), axis = 1)}") print() # Create Confusion Matrix ## Not the optimal method to evaluate the performance of the model - K-Fold Cross Validation is preferred and it involves using validation tests. from sklearn.metrics import confusion_matrix print(f"Confusion Matrix = {confusion_matrix(Y_test, Y_predict)}") print() # Generate Accuracy Score from sklearn.metrics import accuracy_score print(f"Accuracy Score = {accuracy_score(Y_test, Y_predict)}") # Output Training Set Results from matplotlib.colors import ListedColormap X_set, Y_set = standardScaler.inverse_transform(X_train_scaled), Y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 10, stop = X_set[:, 0].max() + 10, step = 1), np.arange(start = X_set[:, 1].min() - 1000, stop = X_set[:, 1].max() + 1000, step = 1)) plt.contourf(X1, X2, classifier.predict(standardScaler.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(Y_train)): plt.scatter(X_set[Y_train == j, 0], X_set[Y_train == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('K Nearest Neighbors (K-NN) (Training Set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.savefig('K_Nearest_Neighbors_Training_Set_Results.png') plt.clf() # Output Test Set Results from matplotlib.colors import ListedColormap X_set, Y_set = standardScaler.inverse_transform(X_test_scaled), Y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 10, stop = X_set[:, 0].max() + 10, step = 1), np.arange(start = X_set[:, 1].min() - 1000, stop = X_set[:, 1].max() + 1000, step = 1)) plt.contourf(X1, X2, classifier.predict(standardScaler.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(Y_test)): plt.scatter(X_set[Y_test == j, 0], X_set[Y_test == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('K Nearest Neighbors (K-NN) (Test Set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.savefig('K_Nearest_Neighbors_Test_Set_Results.png') plt.clf()
[ "matplotlib.pyplot.savefig", "numpy.unique", "pandas.read_csv", "matplotlib.pyplot.ylabel", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.clf", "sklearn.neighbors.KNeighborsClassifier", "matplotlib.colors.ListedColormap", "sklearn.preprocessing.Standard...
[((118, 155), 'pandas.read_csv', 'pd.read_csv', (['"""Social_Network_Ads.csv"""'], {}), "('Social_Network_Ads.csv')\n", (129, 155), True, 'import pandas as pd\n'), ((396, 450), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.25)', 'random_state': '(0)'}), '(X, Y, test_size=0.25, random_state=0)\n', (412, 450), False, 'from sklearn.model_selection import train_test_split\n'), ((718, 734), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (732, 734), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1604, 1664), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'n_neighbors': '(5)', 'metric': '"""minkowski"""', 'p': '(2)'}), "(n_neighbors=5, metric='minkowski', p=2)\n", (1624, 1664), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((3408, 3462), 'matplotlib.pyplot.title', 'plt.title', (['"""K Nearest Neighbors (K-NN) (Training Set)"""'], {}), "('K Nearest Neighbors (K-NN) (Training Set)')\n", (3417, 3462), True, 'import matplotlib.pyplot as plt\n'), ((3463, 3480), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Age"""'], {}), "('Age')\n", (3473, 3480), True, 'import matplotlib.pyplot as plt\n'), ((3481, 3511), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Estimated Salary"""'], {}), "('Estimated Salary')\n", (3491, 3511), True, 'import matplotlib.pyplot as plt\n'), ((3512, 3524), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3522, 3524), True, 'import matplotlib.pyplot as plt\n'), ((3525, 3584), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""K_Nearest_Neighbors_Training_Set_Results.png"""'], {}), "('K_Nearest_Neighbors_Training_Set_Results.png')\n", (3536, 3584), True, 'import matplotlib.pyplot as plt\n'), ((3585, 3594), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (3592, 3594), True, 'import matplotlib.pyplot as plt\n'), ((4357, 4407), 'matplotlib.pyplot.title', 'plt.title', (['"""K Nearest Neighbors (K-NN) (Test Set)"""'], {}), "('K Nearest Neighbors (K-NN) (Test Set)')\n", (4366, 4407), True, 'import matplotlib.pyplot as plt\n'), ((4408, 4425), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Age"""'], {}), "('Age')\n", (4418, 4425), True, 'import matplotlib.pyplot as plt\n'), ((4426, 4456), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Estimated Salary"""'], {}), "('Estimated Salary')\n", (4436, 4456), True, 'import matplotlib.pyplot as plt\n'), ((4457, 4469), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4467, 4469), True, 'import matplotlib.pyplot as plt\n'), ((4470, 4525), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""K_Nearest_Neighbors_Test_Set_Results.png"""'], {}), "('K_Nearest_Neighbors_Test_Set_Results.png')\n", (4481, 4525), True, 'import matplotlib.pyplot as plt\n'), ((4526, 4535), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (4533, 4535), True, 'import matplotlib.pyplot as plt\n'), ((3271, 3289), 'numpy.unique', 'np.unique', (['Y_train'], {}), '(Y_train)\n', (3280, 3289), True, 'import numpy as np\n'), ((4223, 4240), 'numpy.unique', 'np.unique', (['Y_test'], {}), '(Y_test)\n', (4232, 4240), True, 'import numpy as np\n'), ((3157, 3189), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["('red', 'green')"], {}), "(('red', 'green'))\n", (3171, 3189), False, 'from matplotlib.colors import ListedColormap\n'), ((4109, 4141), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["('red', 'green')"], {}), "(('red', 'green'))\n", (4123, 4141), False, 'from matplotlib.colors import ListedColormap\n'), ((2457, 2492), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['Y_test', 'Y_predict'], {}), '(Y_test, Y_predict)\n', (2473, 2492), False, 'from sklearn.metrics import confusion_matrix\n'), ((2600, 2633), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['Y_test', 'Y_predict'], {}), '(Y_test, Y_predict)\n', (2614, 2633), False, 'from sklearn.metrics import accuracy_score\n'), ((3360, 3392), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["('red', 'green')"], {}), "(('red', 'green'))\n", (3374, 3392), False, 'from matplotlib.colors import ListedColormap\n'), ((4309, 4341), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["('red', 'green')"], {}), "(('red', 'green'))\n", (4323, 4341), False, 'from matplotlib.colors import ListedColormap\n')]
import sys sys.path.append('../') import numpy as np import matplotlib.pyplot as plt import matplotlib import matplotlib.gridspec as gridspec from mpl_toolkits.axes_grid1 import make_axes_locatable import seaborn as sns from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation from analysis_functions import calculate_recall_time_quantities, get_weights from analysis_functions import get_weights_collections def generate_plot_for_variable(filename, x_values, xlabel): format = '.pdf' folder = './plot_producers/off_line_rule_learning_' fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) ax.plot(x_values, w_self_vector, 'o-', markersize=markersize, linewidth=linewidth, label=r'$w_{self}$') ax.plot(x_values, w_next_vector, 'o-', markersize=markersize, linewidth=linewidth, label=r'$w_{next}$') ax.plot(x_values, w_rest_vector, 'o-', markersize=markersize, linewidth=linewidth, label=r'$w_{rest}$') ax.axhline(0, ls='--', color='gray') ax.axvline(0, ls='--', color='gray') ax.set_ylabel(r'$w$') ax.set_xlabel(xlabel) ax.legend() type = 'w' aux_filename = folder + filename + type + format fig.savefig(aux_filename, frameon=False, dpi=110, bbox_inches='tight') fig.clear() fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) ax.plot(x_values, factor * Pij_self_vector, 'o-', markersize=markersize, linewidth=linewidth, label=r'$P_{self}$') ax.plot(x_values, factor * Pij_next_vector, 'o-', markersize=markersize, linewidth=linewidth, label=r'$P_{next}$') ax.plot(x_values, factor * Pij_rest_vector, 'o-', markersize=markersize, linewidth=linewidth, label=r'$P_{rest}$') ax.plot(x_values, factor * pi_self_vector, 'o-', markersize=markersize, linewidth=linewidth, label=r'$p_i * p_j s$', color='black') ax.axhline(0, ls='--', color='gray') ax.axvline(0, ls='--', color='gray') ax.set_ylabel(r'Probabilities') ax.set_xlabel(xlabel) ax.legend() type = 'p' aux_filename = folder + filename + type + format fig.savefig(aux_filename, frameon=False, dpi=110, bbox_inches='tight') fig.clear() fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) ax.plot(x_values, persistence_time_vector, 'o-', markersize=markersize, linewidth=linewidth, label=r'$T_{persistence}$') ax.plot(x_values, success_vector / 100.0, 'o-', markersize=markersize, linewidth=linewidth, label=r'Success') ax.axhline(0, ls='--', color='gray') ax.axvline(0, ls='--', color='gray') ax.set_ylabel(r'$T_{persistence} (s)$') ax.set_xlabel(xlabel) ax.legend() type = 'time' aux_filename = folder + filename + type + format fig.savefig(aux_filename, frameon=False, dpi=110, bbox_inches='tight') fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) ax.plot(x_values[:-1], np.diff(Pij_self_vector) / np.abs(Pij_self_vector[:-1]), 'o-', markersize=markersize, linewidth=linewidth, label=r'$P_{self}$', alpha=alpha) ax.plot(x_values[:-1], np.diff(Pij_next_vector) / np.abs(Pij_next_vector[:-1]), 'o-', markersize=markersize, linewidth=linewidth, label=r'$P_{next}$', alpha=alpha) ax.plot(x_values[:-1], np.diff(Pij_rest_vector) / np.abs(Pij_rest_vector[:-1]), 'o-', markersize=markersize, linewidth=linewidth, label=r'$P_{rest}$', alpha=alpha) ax.plot(x_values[:-1], np.diff(pi_self_vector) / np.abs(pi_self_vector[:-1]), 'o-', alpha=alpha, markersize=markersize, linewidth=linewidth, color='black', label=r'$p_i * p_j$') ax.axhline(0, ls='--', color='gray') ax.axvline(0, ls='--', color='gray') ax.set_ylabel(r'$\Delta $ Probabilities') ax.set_xlabel(xlabel) ax.legend() type = 'diff' aux_filename = folder + filename + type + format fig.savefig(aux_filename, frameon=False, dpi=110, bbox_inches='tight') plt.close() sns.set(font_scale=2.8) sns.set_style(style='white') epsilon = 10e-10 from_pattern = 2 to_pattern = 3 figsize = (16, 12) markersize = 25 linewidth = 10 factor = 1.0 alpha = 0.8 normal_palette = sns.color_palette() plot_training_time = False plot_tau_z = False plot_resting_time = False plot_epochs = False plot_inter_sequence_time = False plot_inter_pulse_interval = False plot_minicolumns_fixed = True plot_minicolumns_var = True plot_hypercolumns = False ##################### # General parameters ##################### always_learning = False strict_maximum = True perfect = False z_transfer = False k_perfect = True diagonal_zero = False normalized_currents = True g_w_ampa = 2.0 g_w = 0.0 g_a = 10.0 tau_a = 0.250 G = 1.0 sigma = 0.0 tau_m = 0.020 tau_z_pre_ampa = 0.025 tau_z_post_ampa = 0.025 tau_p = 10.0 hypercolumns = 1 minicolumns = 10 n_patterns = 10 # Manager properties dt = 0.001 values_to_save = ['o'] # Protocol training_time = 0.100 inter_sequence_interval = 1.0 inter_pulse_interval = 0.0 epochs = 3 resting_time = 3.0 # Recall T_recall = 3.0 n = 1 T_cue = 0.050 ############################## # Training time ############################## if plot_training_time: epsilon_ = epsilon num = 20 training_times = np.linspace(0.050, 1.0, num=num) success_vector = np.zeros(num) persistence_time_vector = np.zeros(num) w_self_vector = np.zeros(num) w_next_vector = np.zeros(num) w_rest_vector = np.zeros(num) pi_self_vector = np.zeros(num) Pij_self_vector = np.zeros(num) pi_next_vector = np.zeros(num) Pij_next_vector = np.zeros(num) pi_rest_vector = np.zeros(num) Pij_rest_vector = np.zeros(num) for index, training_time_ in enumerate(training_times): matrix = create_orthogonal_canonical_representation(minicolumns, hypercolumns)[:n_patterns] network_representation = build_network_representation(matrix, minicolumns, hypercolumns) timed_input = TimedInput(network_representation, dt, training_time_, inter_pulse_interval=inter_pulse_interval, inter_sequence_interval=inter_sequence_interval, epochs=epochs, resting_time=resting_time) S = timed_input.build_timed_input() z_pre = timed_input.build_filtered_input_pre(tau_z_pre_ampa) z_post = timed_input.build_filtered_input_post(tau_z_pre_ampa) pi, pj, P = timed_input.calculate_probabilities_from_time_signal(filtered=True) w_timed, beta_timed = get_weights_from_probabilities(pi, pj, P, minicolumns, hypercolumns, epsilon_) nn = BCPNNPerfect(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p, z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=always_learning, normalized_currents=normalized_currents) # Build the manager manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save) # Build the protocol for training nn.w_ampa = w_timed # Recall patterns_indexes = [i for i in range(n_patterns)] sequences = [patterns_indexes] # manager.run_network_recall(T_recall=1.0, T_cue=0.100, I_cue=0, reset=True, empty_history=True) aux = calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences) total_sequence_time, mean, std, success, timings = aux w_self, w_next, w_rest = get_weights(manager, from_pattern, to_pattern, mean=False) success_vector[index] = success persistence_time_vector[index] = mean w_self_vector[index] = w_self w_next_vector[index] = w_next w_rest_vector[index] = w_rest pi_self_vector[index] = pi[from_pattern] * pj[from_pattern] Pij_self_vector[index] = P[from_pattern, from_pattern] pi_next_vector[index] = pi[from_pattern] * pj[to_pattern] Pij_next_vector[index] = P[to_pattern, from_pattern] pi_rest_vector[index] = pi[from_pattern] * pj[to_pattern + 1] Pij_rest_vector[index] = P[to_pattern + 1, from_pattern] # Plot filename = 'training_time_' x_values = training_times xlabel = r'Training Time (s)' generate_plot_for_variable(filename, x_values, xlabel) ############################## # tau_z ############################### if plot_tau_z: num = 15 tau_z_vector = np.linspace(0.025, 0.250, num=num) success_vector = np.zeros(num) persistence_time_vector = np.zeros(num) w_self_vector = np.zeros(num) w_next_vector = np.zeros(num) w_rest_vector = np.zeros(num) pi_self_vector = np.zeros(num) Pij_self_vector = np.zeros(num) pi_next_vector = np.zeros(num) Pij_next_vector = np.zeros(num) pi_rest_vector = np.zeros(num) Pij_rest_vector = np.zeros(num) for index, tau_z_pre_ampa_ in enumerate(tau_z_vector): matrix = create_orthogonal_canonical_representation(minicolumns, hypercolumns)[:n_patterns] network_representation = build_network_representation(matrix, minicolumns, hypercolumns) timed_input = TimedInput(network_representation, dt, training_time, inter_pulse_interval=inter_pulse_interval, inter_sequence_interval=inter_sequence_interval, epochs=epochs, resting_time=resting_time) S = timed_input.build_timed_input() z_pre = timed_input.build_filtered_input_pre(tau_z_pre_ampa_) z_post = timed_input.build_filtered_input_post(tau_z_pre_ampa_) pi, pj, P = timed_input.calculate_probabilities_from_time_signal(filtered=True) w_timed, beta_timed = get_weights_from_probabilities(pi, pj, P, minicolumns, hypercolumns, epsilon) # Patterns parameters nn = BCPNNPerfect(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=tau_z_pre_ampa_, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p, z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=always_learning, normalized_currents=normalized_currents) # Build the manager manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save) # Build the protocol for training nn.w_ampa = w_timed # Recall patterns_indexes = [i for i in range(n_patterns)] sequences = [patterns_indexes] # manager.run_network_recall(T_recall=1.0, T_cue=0.100, I_cue=0, reset=True, empty_history=True) aux = calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences) total_sequence_time, mean, std, success, timings = aux w_self, w_next, w_rest = get_weights(manager, from_pattern, to_pattern, mean=False) success_vector[index] = success persistence_time_vector[index] = mean w_self_vector[index] = w_self w_next_vector[index] = w_next w_rest_vector[index] = w_rest pi_self_vector[index] = pi[from_pattern] * pj[from_pattern] Pij_self_vector[index] = P[from_pattern, from_pattern] pi_next_vector[index] = pi[from_pattern] * pj[to_pattern] Pij_next_vector[index] = P[to_pattern, from_pattern] pi_rest_vector[index] = pi[from_pattern] * pj[to_pattern + 1] Pij_rest_vector[index] = P[to_pattern + 1, from_pattern] # Plot filename = 'tau_z_' x_values = tau_z_vector xlabel = r'$\tau_z$ (s)' generate_plot_for_variable(filename, x_values, xlabel) ######################### # Resting time ######################### if plot_resting_time: num = 15 resting_times = np.linspace(0.0, 3.0, num=num) success_vector = np.zeros(num) persistence_time_vector = np.zeros(num) w_self_vector = np.zeros(num) w_next_vector = np.zeros(num) w_rest_vector = np.zeros(num) pi_self_vector = np.zeros(num) Pij_self_vector = np.zeros(num) pi_next_vector = np.zeros(num) Pij_next_vector = np.zeros(num) pi_rest_vector = np.zeros(num) Pij_rest_vector = np.zeros(num) for index, resting_time_ in enumerate(resting_times): matrix = create_orthogonal_canonical_representation(minicolumns, hypercolumns)[:n_patterns] network_representation = build_network_representation(matrix, minicolumns, hypercolumns) timed_input = TimedInput(network_representation, dt, training_time, inter_pulse_interval=inter_pulse_interval, inter_sequence_interval=inter_sequence_interval, epochs=epochs, resting_time=resting_time_) S = timed_input.build_timed_input() z_pre = timed_input.build_filtered_input_pre(tau_z_pre_ampa) z_post = timed_input.build_filtered_input_post(tau_z_pre_ampa) pi, pj, P = timed_input.calculate_probabilities_from_time_signal(filtered=True) w_timed, beta_timed = get_weights_from_probabilities(pi, pj, P, minicolumns, hypercolumns, epsilon) # Patterns parameters nn = BCPNNPerfect(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p, z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=always_learning, normalized_currents=normalized_currents) # Build the manager manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save) # Build the protocol for training nn.w_ampa = w_timed # Recall patterns_indexes = [i for i in range(n_patterns)] sequences = [patterns_indexes] # manager.run_network_recall(T_recall=1.0, T_cue=0.100, I_cue=0, reset=True, empty_history=True) aux = calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences) total_sequence_time, mean, std, success, timings = aux w_self, w_next, w_rest = get_weights(manager, from_pattern, to_pattern, mean=False) success_vector[index] = success persistence_time_vector[index] = mean w_self_vector[index] = w_self w_next_vector[index] = w_next w_rest_vector[index] = w_rest pi_self_vector[index] = pi[from_pattern] * pj[from_pattern] Pij_self_vector[index] = P[from_pattern, from_pattern] pi_next_vector[index] = pi[from_pattern] * pj[to_pattern] Pij_next_vector[index] = P[to_pattern, from_pattern] pi_rest_vector[index] = pi[from_pattern] * pj[to_pattern + 1] Pij_rest_vector[index] = P[to_pattern + 1, from_pattern] # Plot filename = 'resting_' x_values = resting_times xlabel = r'Resting time (s)' generate_plot_for_variable(filename, x_values, xlabel) ########################### # Epochs ########################### if plot_epochs: num = 15 epochs_vector = np.arange(1, 10, 1, dtype='int') success_vector = np.zeros(epochs_vector.size) persistence_time_vector = np.zeros(epochs_vector.size) w_self_vector = np.zeros(epochs_vector.size) w_next_vector = np.zeros(epochs_vector.size) w_rest_vector = np.zeros(epochs_vector.size) pi_self_vector = np.zeros(epochs_vector.size) Pij_self_vector = np.zeros(epochs_vector.size) pi_next_vector = np.zeros(epochs_vector.size) Pij_next_vector = np.zeros(epochs_vector.size) pi_rest_vector = np.zeros(epochs_vector.size) Pij_rest_vector = np.zeros(epochs_vector.size) for index, epochs_ in enumerate(epochs_vector): matrix = create_orthogonal_canonical_representation(minicolumns, hypercolumns)[:n_patterns] network_representation = build_network_representation(matrix, minicolumns, hypercolumns) timed_input = TimedInput(network_representation, dt, training_time, inter_pulse_interval=inter_pulse_interval, inter_sequence_interval=inter_sequence_interval, epochs=epochs_, resting_time=resting_time) S = timed_input.build_timed_input() z_pre = timed_input.build_filtered_input_pre(tau_z_pre_ampa) z_post = timed_input.build_filtered_input_post(tau_z_pre_ampa) pi, pj, P = timed_input.calculate_probabilities_from_time_signal(filtered=True) w_timed, beta_timed = get_weights_from_probabilities(pi, pj, P, minicolumns, hypercolumns, epsilon) # Patterns parameters nn = BCPNNPerfect(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p, z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=always_learning, normalized_currents=normalized_currents) # Build the manager manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save) # Build the protocol for training nn.w_ampa = w_timed # Recall patterns_indexes = [i for i in range(n_patterns)] sequences = [patterns_indexes] # manager.run_network_recall(T_recall=1.0, T_cue=0.100, I_cue=0, reset=True, empty_history=True) aux = calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences) total_sequence_time, mean, std, success, timings = aux w_self, w_next, w_rest = get_weights(manager, from_pattern, to_pattern, mean=False) success_vector[index] = success persistence_time_vector[index] = mean w_self_vector[index] = w_self w_next_vector[index] = w_next w_rest_vector[index] = w_rest pi_self_vector[index] = pi[from_pattern] * pj[from_pattern] Pij_self_vector[index] = P[from_pattern, from_pattern] pi_next_vector[index] = pi[from_pattern] * pj[to_pattern] Pij_next_vector[index] = P[to_pattern, from_pattern] pi_rest_vector[index] = pi[from_pattern] * pj[to_pattern + 1] Pij_rest_vector[index] = P[to_pattern + 1, from_pattern] # Plot filename = 'epochs_' x_values = epochs_vector xlabel = r'Epochs' generate_plot_for_variable(filename, x_values, xlabel) ############################# # Inter-sequence times ############################# if plot_inter_sequence_time: num = 15 inter_sequence_times = np.linspace(0.0, 3.0, num=num) success_vector = np.zeros(num) persistence_time_vector = np.zeros(num) w_self_vector = np.zeros(num) w_next_vector = np.zeros(num) w_rest_vector = np.zeros(num) pi_self_vector = np.zeros(num) Pij_self_vector = np.zeros(num) pi_next_vector = np.zeros(num) Pij_next_vector = np.zeros(num) pi_rest_vector = np.zeros(num) Pij_rest_vector = np.zeros(num) for index, inter_sequence_interval_ in enumerate(inter_sequence_times): matrix = create_orthogonal_canonical_representation(minicolumns, hypercolumns)[:n_patterns] network_representation = build_network_representation(matrix, minicolumns, hypercolumns) timed_input = TimedInput(network_representation, dt, training_time, inter_pulse_interval=inter_pulse_interval, inter_sequence_interval=inter_sequence_interval_, epochs=epochs, resting_time=resting_time) S = timed_input.build_timed_input() z_pre = timed_input.build_filtered_input_pre(tau_z_pre_ampa) z_post = timed_input.build_filtered_input_post(tau_z_pre_ampa) pi, pj, P = timed_input.calculate_probabilities_from_time_signal(filtered=True) w_timed, beta_timed = get_weights_from_probabilities(pi, pj, P, minicolumns, hypercolumns, epsilon) # Patterns parameters nn = BCPNNPerfect(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p, z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=always_learning, normalized_currents=normalized_currents) # Build the manager manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save) # Build the protocol for training nn.w_ampa = w_timed # Recall patterns_indexes = [i for i in range(n_patterns)] sequences = [patterns_indexes] # manager.run_network_recall(T_recall=1.0, T_cue=0.100, I_cue=0, reset=True, empty_history=True) aux = calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences) total_sequence_time, mean, std, success, timings = aux w_self, w_next, w_rest = get_weights(manager, from_pattern, to_pattern, mean=False) success_vector[index] = success persistence_time_vector[index] = mean w_self_vector[index] = w_self w_next_vector[index] = w_next w_rest_vector[index] = w_rest pi_self_vector[index] = pi[from_pattern] * pj[from_pattern] Pij_self_vector[index] = P[from_pattern, from_pattern] pi_next_vector[index] = pi[from_pattern] * pj[to_pattern] Pij_next_vector[index] = P[to_pattern, from_pattern] pi_rest_vector[index] = pi[from_pattern] * pj[to_pattern + 1] Pij_rest_vector[index] = P[to_pattern + 1, from_pattern] # Plot filename = 'ISI_' x_values = inter_sequence_times xlabel = r'$ISI (s)$' generate_plot_for_variable(filename, x_values, xlabel) ########################## # Inter Pulse Interval ########################## if plot_inter_pulse_interval: num = 15 inter_pulse_times = np.linspace(0.0, 1.0, num=num) success_vector = np.zeros(num) persistence_time_vector = np.zeros(num) w_self_vector = np.zeros(num) w_next_vector = np.zeros(num) w_rest_vector = np.zeros(num) pi_self_vector = np.zeros(num) Pij_self_vector = np.zeros(num) pi_next_vector = np.zeros(num) Pij_next_vector = np.zeros(num) pi_rest_vector = np.zeros(num) Pij_rest_vector = np.zeros(num) for index, inter_pulse_interval_ in enumerate(inter_pulse_times): matrix = create_orthogonal_canonical_representation(minicolumns, hypercolumns)[:n_patterns] network_representation = build_network_representation(matrix, minicolumns, hypercolumns) timed_input = TimedInput(network_representation, dt, training_time, inter_pulse_interval=inter_pulse_interval_, inter_sequence_interval=inter_sequence_interval, epochs=epochs, resting_time=resting_time) S = timed_input.build_timed_input() z_pre = timed_input.build_filtered_input_pre(tau_z_pre_ampa) z_post = timed_input.build_filtered_input_post(tau_z_pre_ampa) pi, pj, P = timed_input.calculate_probabilities_from_time_signal(filtered=True) w_timed, beta_timed = get_weights_from_probabilities(pi, pj, P, minicolumns, hypercolumns, epsilon) # Patterns parameters nn = BCPNNPerfect(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p, z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=always_learning, normalized_currents=normalized_currents) # Build the manager manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save) # Build the protocol for training nn.w_ampa = w_timed # Recall patterns_indexes = [i for i in range(n_patterns)] sequences = [patterns_indexes] # manager.run_network_recall(T_recall=1.0, T_cue=0.100, I_cue=0, reset=True, empty_history=True) aux = calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences) total_sequence_time, mean, std, success, timings = aux w_self, w_next, w_rest = get_weights(manager, from_pattern, to_pattern, mean=False) success_vector[index] = success persistence_time_vector[index] = mean w_self_vector[index] = w_self w_next_vector[index] = w_next w_rest_vector[index] = w_rest pi_self_vector[index] = pi[from_pattern] * pj[from_pattern] Pij_self_vector[index] = P[from_pattern, from_pattern] pi_next_vector[index] = pi[from_pattern] * pj[to_pattern] Pij_next_vector[index] = P[to_pattern, from_pattern] pi_rest_vector[index] = pi[from_pattern] * pj[to_pattern + 1] Pij_rest_vector[index] = P[to_pattern + 1, from_pattern] # Plot filename = 'IPI_' x_values = inter_pulse_times xlabel = r'$IPI (s)$' generate_plot_for_variable(filename, x_values, xlabel) ######################## # Minicolumns ######################## if plot_minicolumns_fixed: num = 20 minicolumns_vector = np.linspace(10, 100, num=num, dtype='int') success_vector = np.zeros(num) persistence_time_vector = np.zeros(num) w_self_vector = np.zeros(num) w_next_vector = np.zeros(num) w_rest_vector = np.zeros(num) pi_self_vector = np.zeros(num) Pij_self_vector = np.zeros(num) pi_next_vector = np.zeros(num) Pij_next_vector = np.zeros(num) pi_rest_vector = np.zeros(num) Pij_rest_vector = np.zeros(num) for index, minicolumns_ in enumerate(minicolumns_vector): matrix = create_orthogonal_canonical_representation(minicolumns_, hypercolumns)[:n_patterns] network_representation = build_network_representation(matrix, minicolumns_, hypercolumns) timed_input = TimedInput(network_representation, dt, training_time, inter_pulse_interval=inter_pulse_interval, inter_sequence_interval=inter_sequence_interval, epochs=epochs, resting_time=resting_time) S = timed_input.build_timed_input() z_pre = timed_input.build_filtered_input_pre(tau_z_pre_ampa) z_post = timed_input.build_filtered_input_post(tau_z_pre_ampa) pi, pj, P = timed_input.calculate_probabilities_from_time_signal(filtered=True) w_timed, beta_timed = get_weights_from_probabilities(pi, pj, P, minicolumns_, hypercolumns, epsilon) # Patterns parameters nn = BCPNNPerfect(hypercolumns, minicolumns_, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p, z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=always_learning, normalized_currents=normalized_currents) # Build the manager manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save) # Build the protocol for training nn.w_ampa = w_timed # Recall patterns_indexes = [i for i in range(n_patterns)] sequences = [patterns_indexes] T_recall = 0.200 * n_patterns # manager.run_network_recall(T_recall=1.0, T_cue=0.100, I_cue=0, reset=True, empty_history=True) aux = calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences) total_sequence_time, mean, std, success, timings = aux w_self, w_next, w_rest = get_weights(manager, from_pattern, to_pattern, mean=False) w_rest = w_timed[to_pattern + 1, from_pattern] success_vector[index] = success persistence_time_vector[index] = mean w_self_vector[index] = w_self w_next_vector[index] = w_next w_rest_vector[index] = w_rest pi_self_vector[index] = pi[from_pattern] * pj[from_pattern] Pij_self_vector[index] = P[from_pattern, from_pattern] pi_next_vector[index] = pi[from_pattern] * pj[to_pattern] Pij_next_vector[index] = P[to_pattern, from_pattern] pi_rest_vector[index] = pi[from_pattern] * pj[to_pattern + 1] Pij_rest_vector[index] = P[to_pattern + 1, from_pattern] # Plot filename = 'minicolumns_fixed_' x_values = minicolumns_vector xlabel = r'Minicolumns' generate_plot_for_variable(filename, x_values, xlabel) ############################### # Minicolumns Variable ############################### if plot_minicolumns_var: num = 20 minicolumns_vector = np.linspace(10, 100, num=num, dtype='int') success_vector = np.zeros(num) persistence_time_vector = np.zeros(num) w_self_vector = np.zeros(num) w_next_vector = np.zeros(num) w_rest_vector = np.zeros(num) pi_self_vector = np.zeros(num) Pij_self_vector = np.zeros(num) pi_next_vector = np.zeros(num) Pij_next_vector = np.zeros(num) pi_rest_vector = np.zeros(num) Pij_rest_vector = np.zeros(num) for index, minicolumns_ in enumerate(minicolumns_vector): n_patterns_ = minicolumns_ matrix = create_orthogonal_canonical_representation(minicolumns_, hypercolumns)[:n_patterns_] network_representation = build_network_representation(matrix, minicolumns_, hypercolumns) timed_input = TimedInput(network_representation, dt, training_time, inter_pulse_interval=inter_pulse_interval, inter_sequence_interval=inter_sequence_interval, epochs=epochs, resting_time=resting_time) S = timed_input.build_timed_input() z_pre = timed_input.build_filtered_input_pre(tau_z_pre_ampa) z_post = timed_input.build_filtered_input_post(tau_z_pre_ampa) pi, pj, P = timed_input.calculate_probabilities_from_time_signal(filtered=True) w_timed, beta_timed = get_weights_from_probabilities(pi, pj, P, minicolumns_, hypercolumns, epsilon) # Patterns parameters nn = BCPNNPerfect(hypercolumns, minicolumns_, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p, z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=always_learning, normalized_currents=normalized_currents) # Build the manager manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save) # Build the protocol for training nn.w_ampa = w_timed # Recall patterns_indexes = [i for i in range(n_patterns_)] sequences = [patterns_indexes] T_recall = 0.200 * n_patterns_ aux = calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences) total_sequence_time, mean, std, success, timings = aux w_self, w_next, w_rest = get_weights(manager, from_pattern, to_pattern, mean=False) success_vector[index] = success persistence_time_vector[index] = mean w_self_vector[index] = w_self w_next_vector[index] = w_next w_rest_vector[index] = w_rest pi_self_vector[index] = pi[from_pattern] * pj[from_pattern] Pij_self_vector[index] = P[from_pattern, from_pattern] pi_next_vector[index] = pi[from_pattern] * pj[to_pattern] Pij_next_vector[index] = P[to_pattern, from_pattern] pi_rest_vector[index] = pi[from_pattern] * pj[to_pattern + 1] Pij_rest_vector[index] = P[to_pattern + 1, from_pattern] # Plot filename = 'minicolumns_var_' x_values = minicolumns_vector xlabel = r'Minicolumns' generate_plot_for_variable(filename, x_values, xlabel) ####################### # Hypercolumns ####################### if plot_hypercolumns: num = 10 hypercolumns_vector = np.linspace(1, 10, num=num, dtype='int') success_vector = np.zeros(num) persistence_time_vector = np.zeros(num) w_self_vector = np.zeros(num) w_next_vector = np.zeros(num) w_rest_vector = np.zeros(num) pi_self_vector = np.zeros(num) Pij_self_vector = np.zeros(num) pi_next_vector = np.zeros(num) Pij_next_vector = np.zeros(num) pi_rest_vector = np.zeros(num) Pij_rest_vector = np.zeros(num) for index, hypercolumns_ in enumerate(hypercolumns_vector): matrix = create_orthogonal_canonical_representation(minicolumns, hypercolumns_)[:n_patterns] network_representation = build_network_representation(matrix, minicolumns, hypercolumns_) timed_input = TimedInput(network_representation, dt, training_time, inter_pulse_interval=inter_pulse_interval, inter_sequence_interval=inter_sequence_interval, epochs=epochs, resting_time=resting_time) S = timed_input.build_timed_input() z_pre = timed_input.build_filtered_input_pre(tau_z_pre_ampa) z_post = timed_input.build_filtered_input_post(tau_z_pre_ampa) pi, pj, P = timed_input.calculate_probabilities_from_time_signal(filtered=True) w_timed, beta_timed = get_weights_from_probabilities(pi, pj, P, minicolumns, hypercolumns_, epsilon) # Patterns parameters nn = BCPNNPerfect(hypercolumns_, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p, z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=always_learning, normalized_currents=normalized_currents) # Build the manager manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save) # Build the protocol for training nn.w_ampa = w_timed # Recall patterns_indexes = [i for i in range(n_patterns)] sequences = [patterns_indexes] # manager.run_network_recall(T_recall=1.0, T_cue=0.100, I_cue=0, reset=True, empty_history=True) aux = calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences) total_sequence_time, mean, std, success, timings = aux w_self, w_next, w_rest = get_weights(manager, from_pattern, to_pattern, mean=False) w_rest = w_timed[to_pattern + 1, from_pattern] success_vector[index] = success persistence_time_vector[index] = mean w_self_vector[index] = w_self w_next_vector[index] = w_next w_rest_vector[index] = w_rest pi_self_vector[index] = pi[from_pattern] * pj[from_pattern] Pij_self_vector[index] = P[from_pattern, from_pattern] pi_next_vector[index] = pi[from_pattern] * pj[to_pattern] Pij_next_vector[index] = P[to_pattern, from_pattern] pi_rest_vector[index] = pi[from_pattern] * pj[to_pattern + 1] Pij_rest_vector[index] = P[to_pattern + 1, from_pattern] # Plot filename = 'hypercolumns_' x_values = hypercolumns_vector xlabel = r'Hypercolumns' generate_plot_for_variable(filename, x_values, xlabel) plt.close()
[ "connectivity_functions.create_orthogonal_canonical_representation", "seaborn.set_style", "analysis_functions.get_weights", "network.BCPNNPerfect", "connectivity_functions.build_network_representation", "sys.path.append", "numpy.arange", "seaborn.set", "seaborn.color_palette", "numpy.diff", "con...
[((11, 33), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (26, 33), False, 'import sys\n'), ((4212, 4235), 'seaborn.set', 'sns.set', ([], {'font_scale': '(2.8)'}), '(font_scale=2.8)\n', (4219, 4235), True, 'import seaborn as sns\n'), ((4236, 4264), 'seaborn.set_style', 'sns.set_style', ([], {'style': '"""white"""'}), "(style='white')\n", (4249, 4264), True, 'import seaborn as sns\n'), ((4408, 4427), 'seaborn.color_palette', 'sns.color_palette', ([], {}), '()\n', (4425, 4427), True, 'import seaborn as sns\n'), ((36671, 36682), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (36680, 36682), True, 'import matplotlib.pyplot as plt\n'), ((795, 822), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (805, 822), True, 'import matplotlib.pyplot as plt\n'), ((1500, 1527), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (1510, 1527), True, 'import matplotlib.pyplot as plt\n'), ((2433, 2460), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (2443, 2460), True, 'import matplotlib.pyplot as plt\n'), ((3082, 3109), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (3092, 3109), True, 'import matplotlib.pyplot as plt\n'), ((4199, 4210), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4208, 4210), True, 'import matplotlib.pyplot as plt\n'), ((5463, 5494), 'numpy.linspace', 'np.linspace', (['(0.05)', '(1.0)'], {'num': 'num'}), '(0.05, 1.0, num=num)\n', (5474, 5494), True, 'import numpy as np\n'), ((5517, 5530), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5525, 5530), True, 'import numpy as np\n'), ((5561, 5574), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5569, 5574), True, 'import numpy as np\n'), ((5596, 5609), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5604, 5609), True, 'import numpy as np\n'), ((5630, 5643), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5638, 5643), True, 'import numpy as np\n'), ((5664, 5677), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5672, 5677), True, 'import numpy as np\n'), ((5700, 5713), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5708, 5713), True, 'import numpy as np\n'), ((5736, 5749), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5744, 5749), True, 'import numpy as np\n'), ((5771, 5784), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5779, 5784), True, 'import numpy as np\n'), ((5807, 5820), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5815, 5820), True, 'import numpy as np\n'), ((5842, 5855), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5850, 5855), True, 'import numpy as np\n'), ((5878, 5891), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (5886, 5891), True, 'import numpy as np\n'), ((8874, 8907), 'numpy.linspace', 'np.linspace', (['(0.025)', '(0.25)'], {'num': 'num'}), '(0.025, 0.25, num=num)\n', (8885, 8907), True, 'import numpy as np\n'), ((8930, 8943), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (8938, 8943), True, 'import numpy as np\n'), ((8974, 8987), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (8982, 8987), True, 'import numpy as np\n'), ((9008, 9021), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (9016, 9021), True, 'import numpy as np\n'), ((9042, 9055), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (9050, 9055), True, 'import numpy as np\n'), ((9076, 9089), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (9084, 9089), True, 'import numpy as np\n'), ((9112, 9125), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (9120, 9125), True, 'import numpy as np\n'), ((9148, 9161), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (9156, 9161), True, 'import numpy as np\n'), ((9183, 9196), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (9191, 9196), True, 'import numpy as np\n'), ((9219, 9232), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (9227, 9232), True, 'import numpy as np\n'), ((9254, 9267), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (9262, 9267), True, 'import numpy as np\n'), ((9290, 9303), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (9298, 9303), True, 'import numpy as np\n'), ((12305, 12335), 'numpy.linspace', 'np.linspace', (['(0.0)', '(3.0)'], {'num': 'num'}), '(0.0, 3.0, num=num)\n', (12316, 12335), True, 'import numpy as np\n'), ((12357, 12370), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12365, 12370), True, 'import numpy as np\n'), ((12401, 12414), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12409, 12414), True, 'import numpy as np\n'), ((12435, 12448), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12443, 12448), True, 'import numpy as np\n'), ((12469, 12482), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12477, 12482), True, 'import numpy as np\n'), ((12503, 12516), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12511, 12516), True, 'import numpy as np\n'), ((12539, 12552), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12547, 12552), True, 'import numpy as np\n'), ((12575, 12588), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12583, 12588), True, 'import numpy as np\n'), ((12610, 12623), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12618, 12623), True, 'import numpy as np\n'), ((12646, 12659), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12654, 12659), True, 'import numpy as np\n'), ((12681, 12694), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12689, 12694), True, 'import numpy as np\n'), ((12717, 12730), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (12725, 12730), True, 'import numpy as np\n'), ((15731, 15763), 'numpy.arange', 'np.arange', (['(1)', '(10)', '(1)'], {'dtype': '"""int"""'}), "(1, 10, 1, dtype='int')\n", (15740, 15763), True, 'import numpy as np\n'), ((15785, 15813), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (15793, 15813), True, 'import numpy as np\n'), ((15844, 15872), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (15852, 15872), True, 'import numpy as np\n'), ((15893, 15921), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (15901, 15921), True, 'import numpy as np\n'), ((15942, 15970), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (15950, 15970), True, 'import numpy as np\n'), ((15991, 16019), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (15999, 16019), True, 'import numpy as np\n'), ((16042, 16070), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (16050, 16070), True, 'import numpy as np\n'), ((16093, 16121), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (16101, 16121), True, 'import numpy as np\n'), ((16143, 16171), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (16151, 16171), True, 'import numpy as np\n'), ((16194, 16222), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (16202, 16222), True, 'import numpy as np\n'), ((16244, 16272), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (16252, 16272), True, 'import numpy as np\n'), ((16295, 16323), 'numpy.zeros', 'np.zeros', (['epochs_vector.size'], {}), '(epochs_vector.size)\n', (16303, 16323), True, 'import numpy as np\n'), ((19346, 19376), 'numpy.linspace', 'np.linspace', (['(0.0)', '(3.0)'], {'num': 'num'}), '(0.0, 3.0, num=num)\n', (19357, 19376), True, 'import numpy as np\n'), ((19398, 19411), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19406, 19411), True, 'import numpy as np\n'), ((19442, 19455), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19450, 19455), True, 'import numpy as np\n'), ((19476, 19489), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19484, 19489), True, 'import numpy as np\n'), ((19510, 19523), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19518, 19523), True, 'import numpy as np\n'), ((19544, 19557), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19552, 19557), True, 'import numpy as np\n'), ((19580, 19593), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19588, 19593), True, 'import numpy as np\n'), ((19616, 19629), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19624, 19629), True, 'import numpy as np\n'), ((19651, 19664), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19659, 19664), True, 'import numpy as np\n'), ((19687, 19700), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19695, 19700), True, 'import numpy as np\n'), ((19722, 19735), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19730, 19735), True, 'import numpy as np\n'), ((19758, 19771), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (19766, 19771), True, 'import numpy as np\n'), ((22813, 22843), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)'], {'num': 'num'}), '(0.0, 1.0, num=num)\n', (22824, 22843), True, 'import numpy as np\n'), ((22865, 22878), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (22873, 22878), True, 'import numpy as np\n'), ((22909, 22922), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (22917, 22922), True, 'import numpy as np\n'), ((22943, 22956), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (22951, 22956), True, 'import numpy as np\n'), ((22977, 22990), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (22985, 22990), True, 'import numpy as np\n'), ((23011, 23024), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (23019, 23024), True, 'import numpy as np\n'), ((23047, 23060), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (23055, 23060), True, 'import numpy as np\n'), ((23083, 23096), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (23091, 23096), True, 'import numpy as np\n'), ((23118, 23131), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (23126, 23131), True, 'import numpy as np\n'), ((23154, 23167), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (23162, 23167), True, 'import numpy as np\n'), ((23189, 23202), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (23197, 23202), True, 'import numpy as np\n'), ((23225, 23238), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (23233, 23238), True, 'import numpy as np\n'), ((26260, 26302), 'numpy.linspace', 'np.linspace', (['(10)', '(100)'], {'num': 'num', 'dtype': '"""int"""'}), "(10, 100, num=num, dtype='int')\n", (26271, 26302), True, 'import numpy as np\n'), ((26324, 26337), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26332, 26337), True, 'import numpy as np\n'), ((26368, 26381), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26376, 26381), True, 'import numpy as np\n'), ((26402, 26415), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26410, 26415), True, 'import numpy as np\n'), ((26436, 26449), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26444, 26449), True, 'import numpy as np\n'), ((26470, 26483), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26478, 26483), True, 'import numpy as np\n'), ((26506, 26519), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26514, 26519), True, 'import numpy as np\n'), ((26542, 26555), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26550, 26555), True, 'import numpy as np\n'), ((26577, 26590), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26585, 26590), True, 'import numpy as np\n'), ((26613, 26626), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26621, 26626), True, 'import numpy as np\n'), ((26648, 26661), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26656, 26661), True, 'import numpy as np\n'), ((26684, 26697), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (26692, 26697), True, 'import numpy as np\n'), ((29844, 29886), 'numpy.linspace', 'np.linspace', (['(10)', '(100)'], {'num': 'num', 'dtype': '"""int"""'}), "(10, 100, num=num, dtype='int')\n", (29855, 29886), True, 'import numpy as np\n'), ((29908, 29921), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (29916, 29921), True, 'import numpy as np\n'), ((29952, 29965), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (29960, 29965), True, 'import numpy as np\n'), ((29986, 29999), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (29994, 29999), True, 'import numpy as np\n'), ((30020, 30033), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (30028, 30033), True, 'import numpy as np\n'), ((30054, 30067), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (30062, 30067), True, 'import numpy as np\n'), ((30090, 30103), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (30098, 30103), True, 'import numpy as np\n'), ((30126, 30139), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (30134, 30139), True, 'import numpy as np\n'), ((30161, 30174), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (30169, 30174), True, 'import numpy as np\n'), ((30197, 30210), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (30205, 30210), True, 'import numpy as np\n'), ((30232, 30245), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (30240, 30245), True, 'import numpy as np\n'), ((30268, 30281), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (30276, 30281), True, 'import numpy as np\n'), ((33278, 33318), 'numpy.linspace', 'np.linspace', (['(1)', '(10)'], {'num': 'num', 'dtype': '"""int"""'}), "(1, 10, num=num, dtype='int')\n", (33289, 33318), True, 'import numpy as np\n'), ((33340, 33353), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33348, 33353), True, 'import numpy as np\n'), ((33384, 33397), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33392, 33397), True, 'import numpy as np\n'), ((33418, 33431), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33426, 33431), True, 'import numpy as np\n'), ((33452, 33465), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33460, 33465), True, 'import numpy as np\n'), ((33486, 33499), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33494, 33499), True, 'import numpy as np\n'), ((33522, 33535), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33530, 33535), True, 'import numpy as np\n'), ((33558, 33571), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33566, 33571), True, 'import numpy as np\n'), ((33593, 33606), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33601, 33606), True, 'import numpy as np\n'), ((33629, 33642), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33637, 33642), True, 'import numpy as np\n'), ((33664, 33677), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33672, 33677), True, 'import numpy as np\n'), ((33700, 33713), 'numpy.zeros', 'np.zeros', (['num'], {}), '(num)\n', (33708, 33713), True, 'import numpy as np\n'), ((6087, 6150), 'connectivity_functions.build_network_representation', 'build_network_representation', (['matrix', 'minicolumns', 'hypercolumns'], {}), '(matrix, minicolumns, hypercolumns)\n', (6115, 6150), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((6174, 6371), 'network.TimedInput', 'TimedInput', (['network_representation', 'dt', 'training_time_'], {'inter_pulse_interval': 'inter_pulse_interval', 'inter_sequence_interval': 'inter_sequence_interval', 'epochs': 'epochs', 'resting_time': 'resting_time'}), '(network_representation, dt, training_time_, inter_pulse_interval\n =inter_pulse_interval, inter_sequence_interval=inter_sequence_interval,\n epochs=epochs, resting_time=resting_time)\n', (6184, 6371), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((6763, 6841), 'connectivity_functions.get_weights_from_probabilities', 'get_weights_from_probabilities', (['pi', 'pj', 'P', 'minicolumns', 'hypercolumns', 'epsilon_'], {}), '(pi, pj, P, minicolumns, hypercolumns, epsilon_)\n', (6793, 6841), False, 'from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation\n'), ((6856, 7271), 'network.BCPNNPerfect', 'BCPNNPerfect', (['hypercolumns', 'minicolumns'], {'g_w_ampa': 'g_w_ampa', 'g_w': 'g_w', 'g_a': 'g_a', 'tau_a': 'tau_a', 'tau_m': 'tau_m', 'sigma': 'sigma', 'G': 'G', 'tau_z_pre_ampa': 'tau_z_pre_ampa', 'tau_z_post_ampa': 'tau_z_post_ampa', 'tau_p': 'tau_p', 'z_transfer': 'z_transfer', 'diagonal_zero': 'diagonal_zero', 'strict_maximum': 'strict_maximum', 'perfect': 'perfect', 'k_perfect': 'k_perfect', 'always_learning': 'always_learning', 'normalized_currents': 'normalized_currents'}), '(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a,\n tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=\n tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p,\n z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=\n strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=\n always_learning, normalized_currents=normalized_currents)\n', (6868, 7271), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((7400, 7459), 'network.NetworkManager', 'NetworkManager', ([], {'nn': 'nn', 'dt': 'dt', 'values_to_save': 'values_to_save'}), '(nn=nn, dt=dt, values_to_save=values_to_save)\n', (7414, 7459), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((7765, 7837), 'analysis_functions.calculate_recall_time_quantities', 'calculate_recall_time_quantities', (['manager', 'T_recall', 'T_cue', 'n', 'sequences'], {}), '(manager, T_recall, T_cue, n, sequences)\n', (7797, 7837), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((7934, 7992), 'analysis_functions.get_weights', 'get_weights', (['manager', 'from_pattern', 'to_pattern'], {'mean': '(False)'}), '(manager, from_pattern, to_pattern, mean=False)\n', (7945, 7992), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((9498, 9561), 'connectivity_functions.build_network_representation', 'build_network_representation', (['matrix', 'minicolumns', 'hypercolumns'], {}), '(matrix, minicolumns, hypercolumns)\n', (9526, 9561), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((9585, 9781), 'network.TimedInput', 'TimedInput', (['network_representation', 'dt', 'training_time'], {'inter_pulse_interval': 'inter_pulse_interval', 'inter_sequence_interval': 'inter_sequence_interval', 'epochs': 'epochs', 'resting_time': 'resting_time'}), '(network_representation, dt, training_time, inter_pulse_interval=\n inter_pulse_interval, inter_sequence_interval=inter_sequence_interval,\n epochs=epochs, resting_time=resting_time)\n', (9595, 9781), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((10175, 10252), 'connectivity_functions.get_weights_from_probabilities', 'get_weights_from_probabilities', (['pi', 'pj', 'P', 'minicolumns', 'hypercolumns', 'epsilon'], {}), '(pi, pj, P, minicolumns, hypercolumns, epsilon)\n', (10205, 10252), False, 'from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation\n'), ((10297, 10713), 'network.BCPNNPerfect', 'BCPNNPerfect', (['hypercolumns', 'minicolumns'], {'g_w_ampa': 'g_w_ampa', 'g_w': 'g_w', 'g_a': 'g_a', 'tau_a': 'tau_a', 'tau_m': 'tau_m', 'sigma': 'sigma', 'G': 'G', 'tau_z_pre_ampa': 'tau_z_pre_ampa_', 'tau_z_post_ampa': 'tau_z_post_ampa', 'tau_p': 'tau_p', 'z_transfer': 'z_transfer', 'diagonal_zero': 'diagonal_zero', 'strict_maximum': 'strict_maximum', 'perfect': 'perfect', 'k_perfect': 'k_perfect', 'always_learning': 'always_learning', 'normalized_currents': 'normalized_currents'}), '(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a,\n tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=\n tau_z_pre_ampa_, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p,\n z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=\n strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=\n always_learning, normalized_currents=normalized_currents)\n', (10309, 10713), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((10842, 10901), 'network.NetworkManager', 'NetworkManager', ([], {'nn': 'nn', 'dt': 'dt', 'values_to_save': 'values_to_save'}), '(nn=nn, dt=dt, values_to_save=values_to_save)\n', (10856, 10901), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((11207, 11279), 'analysis_functions.calculate_recall_time_quantities', 'calculate_recall_time_quantities', (['manager', 'T_recall', 'T_cue', 'n', 'sequences'], {}), '(manager, T_recall, T_cue, n, sequences)\n', (11239, 11279), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((11376, 11434), 'analysis_functions.get_weights', 'get_weights', (['manager', 'from_pattern', 'to_pattern'], {'mean': '(False)'}), '(manager, from_pattern, to_pattern, mean=False)\n', (11387, 11434), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((12924, 12987), 'connectivity_functions.build_network_representation', 'build_network_representation', (['matrix', 'minicolumns', 'hypercolumns'], {}), '(matrix, minicolumns, hypercolumns)\n', (12952, 12987), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((13011, 13208), 'network.TimedInput', 'TimedInput', (['network_representation', 'dt', 'training_time'], {'inter_pulse_interval': 'inter_pulse_interval', 'inter_sequence_interval': 'inter_sequence_interval', 'epochs': 'epochs', 'resting_time': 'resting_time_'}), '(network_representation, dt, training_time, inter_pulse_interval=\n inter_pulse_interval, inter_sequence_interval=inter_sequence_interval,\n epochs=epochs, resting_time=resting_time_)\n', (13021, 13208), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((13600, 13677), 'connectivity_functions.get_weights_from_probabilities', 'get_weights_from_probabilities', (['pi', 'pj', 'P', 'minicolumns', 'hypercolumns', 'epsilon'], {}), '(pi, pj, P, minicolumns, hypercolumns, epsilon)\n', (13630, 13677), False, 'from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation\n'), ((13724, 14139), 'network.BCPNNPerfect', 'BCPNNPerfect', (['hypercolumns', 'minicolumns'], {'g_w_ampa': 'g_w_ampa', 'g_w': 'g_w', 'g_a': 'g_a', 'tau_a': 'tau_a', 'tau_m': 'tau_m', 'sigma': 'sigma', 'G': 'G', 'tau_z_pre_ampa': 'tau_z_pre_ampa', 'tau_z_post_ampa': 'tau_z_post_ampa', 'tau_p': 'tau_p', 'z_transfer': 'z_transfer', 'diagonal_zero': 'diagonal_zero', 'strict_maximum': 'strict_maximum', 'perfect': 'perfect', 'k_perfect': 'k_perfect', 'always_learning': 'always_learning', 'normalized_currents': 'normalized_currents'}), '(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a,\n tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=\n tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p,\n z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=\n strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=\n always_learning, normalized_currents=normalized_currents)\n', (13736, 14139), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((14268, 14327), 'network.NetworkManager', 'NetworkManager', ([], {'nn': 'nn', 'dt': 'dt', 'values_to_save': 'values_to_save'}), '(nn=nn, dt=dt, values_to_save=values_to_save)\n', (14282, 14327), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((14633, 14705), 'analysis_functions.calculate_recall_time_quantities', 'calculate_recall_time_quantities', (['manager', 'T_recall', 'T_cue', 'n', 'sequences'], {}), '(manager, T_recall, T_cue, n, sequences)\n', (14665, 14705), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((14802, 14860), 'analysis_functions.get_weights', 'get_weights', (['manager', 'from_pattern', 'to_pattern'], {'mean': '(False)'}), '(manager, from_pattern, to_pattern, mean=False)\n', (14813, 14860), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((16510, 16573), 'connectivity_functions.build_network_representation', 'build_network_representation', (['matrix', 'minicolumns', 'hypercolumns'], {}), '(matrix, minicolumns, hypercolumns)\n', (16538, 16573), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((16597, 16794), 'network.TimedInput', 'TimedInput', (['network_representation', 'dt', 'training_time'], {'inter_pulse_interval': 'inter_pulse_interval', 'inter_sequence_interval': 'inter_sequence_interval', 'epochs': 'epochs_', 'resting_time': 'resting_time'}), '(network_representation, dt, training_time, inter_pulse_interval=\n inter_pulse_interval, inter_sequence_interval=inter_sequence_interval,\n epochs=epochs_, resting_time=resting_time)\n', (16607, 16794), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((17189, 17266), 'connectivity_functions.get_weights_from_probabilities', 'get_weights_from_probabilities', (['pi', 'pj', 'P', 'minicolumns', 'hypercolumns', 'epsilon'], {}), '(pi, pj, P, minicolumns, hypercolumns, epsilon)\n', (17219, 17266), False, 'from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation\n'), ((17312, 17727), 'network.BCPNNPerfect', 'BCPNNPerfect', (['hypercolumns', 'minicolumns'], {'g_w_ampa': 'g_w_ampa', 'g_w': 'g_w', 'g_a': 'g_a', 'tau_a': 'tau_a', 'tau_m': 'tau_m', 'sigma': 'sigma', 'G': 'G', 'tau_z_pre_ampa': 'tau_z_pre_ampa', 'tau_z_post_ampa': 'tau_z_post_ampa', 'tau_p': 'tau_p', 'z_transfer': 'z_transfer', 'diagonal_zero': 'diagonal_zero', 'strict_maximum': 'strict_maximum', 'perfect': 'perfect', 'k_perfect': 'k_perfect', 'always_learning': 'always_learning', 'normalized_currents': 'normalized_currents'}), '(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a,\n tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=\n tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p,\n z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=\n strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=\n always_learning, normalized_currents=normalized_currents)\n', (17324, 17727), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((17856, 17915), 'network.NetworkManager', 'NetworkManager', ([], {'nn': 'nn', 'dt': 'dt', 'values_to_save': 'values_to_save'}), '(nn=nn, dt=dt, values_to_save=values_to_save)\n', (17870, 17915), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((18221, 18293), 'analysis_functions.calculate_recall_time_quantities', 'calculate_recall_time_quantities', (['manager', 'T_recall', 'T_cue', 'n', 'sequences'], {}), '(manager, T_recall, T_cue, n, sequences)\n', (18253, 18293), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((18390, 18448), 'analysis_functions.get_weights', 'get_weights', (['manager', 'from_pattern', 'to_pattern'], {'mean': '(False)'}), '(manager, from_pattern, to_pattern, mean=False)\n', (18401, 18448), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((19983, 20046), 'connectivity_functions.build_network_representation', 'build_network_representation', (['matrix', 'minicolumns', 'hypercolumns'], {}), '(matrix, minicolumns, hypercolumns)\n', (20011, 20046), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((20070, 20267), 'network.TimedInput', 'TimedInput', (['network_representation', 'dt', 'training_time'], {'inter_pulse_interval': 'inter_pulse_interval', 'inter_sequence_interval': 'inter_sequence_interval_', 'epochs': 'epochs', 'resting_time': 'resting_time'}), '(network_representation, dt, training_time, inter_pulse_interval=\n inter_pulse_interval, inter_sequence_interval=inter_sequence_interval_,\n epochs=epochs, resting_time=resting_time)\n', (20080, 20267), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((20659, 20736), 'connectivity_functions.get_weights_from_probabilities', 'get_weights_from_probabilities', (['pi', 'pj', 'P', 'minicolumns', 'hypercolumns', 'epsilon'], {}), '(pi, pj, P, minicolumns, hypercolumns, epsilon)\n', (20689, 20736), False, 'from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation\n'), ((20781, 21196), 'network.BCPNNPerfect', 'BCPNNPerfect', (['hypercolumns', 'minicolumns'], {'g_w_ampa': 'g_w_ampa', 'g_w': 'g_w', 'g_a': 'g_a', 'tau_a': 'tau_a', 'tau_m': 'tau_m', 'sigma': 'sigma', 'G': 'G', 'tau_z_pre_ampa': 'tau_z_pre_ampa', 'tau_z_post_ampa': 'tau_z_post_ampa', 'tau_p': 'tau_p', 'z_transfer': 'z_transfer', 'diagonal_zero': 'diagonal_zero', 'strict_maximum': 'strict_maximum', 'perfect': 'perfect', 'k_perfect': 'k_perfect', 'always_learning': 'always_learning', 'normalized_currents': 'normalized_currents'}), '(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a,\n tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=\n tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p,\n z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=\n strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=\n always_learning, normalized_currents=normalized_currents)\n', (20793, 21196), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((21325, 21384), 'network.NetworkManager', 'NetworkManager', ([], {'nn': 'nn', 'dt': 'dt', 'values_to_save': 'values_to_save'}), '(nn=nn, dt=dt, values_to_save=values_to_save)\n', (21339, 21384), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((21690, 21762), 'analysis_functions.calculate_recall_time_quantities', 'calculate_recall_time_quantities', (['manager', 'T_recall', 'T_cue', 'n', 'sequences'], {}), '(manager, T_recall, T_cue, n, sequences)\n', (21722, 21762), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((21859, 21917), 'analysis_functions.get_weights', 'get_weights', (['manager', 'from_pattern', 'to_pattern'], {'mean': '(False)'}), '(manager, from_pattern, to_pattern, mean=False)\n', (21870, 21917), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((23443, 23506), 'connectivity_functions.build_network_representation', 'build_network_representation', (['matrix', 'minicolumns', 'hypercolumns'], {}), '(matrix, minicolumns, hypercolumns)\n', (23471, 23506), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((23530, 23727), 'network.TimedInput', 'TimedInput', (['network_representation', 'dt', 'training_time'], {'inter_pulse_interval': 'inter_pulse_interval_', 'inter_sequence_interval': 'inter_sequence_interval', 'epochs': 'epochs', 'resting_time': 'resting_time'}), '(network_representation, dt, training_time, inter_pulse_interval=\n inter_pulse_interval_, inter_sequence_interval=inter_sequence_interval,\n epochs=epochs, resting_time=resting_time)\n', (23540, 23727), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((24122, 24199), 'connectivity_functions.get_weights_from_probabilities', 'get_weights_from_probabilities', (['pi', 'pj', 'P', 'minicolumns', 'hypercolumns', 'epsilon'], {}), '(pi, pj, P, minicolumns, hypercolumns, epsilon)\n', (24152, 24199), False, 'from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation\n'), ((24245, 24660), 'network.BCPNNPerfect', 'BCPNNPerfect', (['hypercolumns', 'minicolumns'], {'g_w_ampa': 'g_w_ampa', 'g_w': 'g_w', 'g_a': 'g_a', 'tau_a': 'tau_a', 'tau_m': 'tau_m', 'sigma': 'sigma', 'G': 'G', 'tau_z_pre_ampa': 'tau_z_pre_ampa', 'tau_z_post_ampa': 'tau_z_post_ampa', 'tau_p': 'tau_p', 'z_transfer': 'z_transfer', 'diagonal_zero': 'diagonal_zero', 'strict_maximum': 'strict_maximum', 'perfect': 'perfect', 'k_perfect': 'k_perfect', 'always_learning': 'always_learning', 'normalized_currents': 'normalized_currents'}), '(hypercolumns, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=g_a,\n tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=\n tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p,\n z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=\n strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=\n always_learning, normalized_currents=normalized_currents)\n', (24257, 24660), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((24789, 24848), 'network.NetworkManager', 'NetworkManager', ([], {'nn': 'nn', 'dt': 'dt', 'values_to_save': 'values_to_save'}), '(nn=nn, dt=dt, values_to_save=values_to_save)\n', (24803, 24848), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((25154, 25226), 'analysis_functions.calculate_recall_time_quantities', 'calculate_recall_time_quantities', (['manager', 'T_recall', 'T_cue', 'n', 'sequences'], {}), '(manager, T_recall, T_cue, n, sequences)\n', (25186, 25226), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((25323, 25381), 'analysis_functions.get_weights', 'get_weights', (['manager', 'from_pattern', 'to_pattern'], {'mean': '(False)'}), '(manager, from_pattern, to_pattern, mean=False)\n', (25334, 25381), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((26896, 26960), 'connectivity_functions.build_network_representation', 'build_network_representation', (['matrix', 'minicolumns_', 'hypercolumns'], {}), '(matrix, minicolumns_, hypercolumns)\n', (26924, 26960), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((26984, 27180), 'network.TimedInput', 'TimedInput', (['network_representation', 'dt', 'training_time'], {'inter_pulse_interval': 'inter_pulse_interval', 'inter_sequence_interval': 'inter_sequence_interval', 'epochs': 'epochs', 'resting_time': 'resting_time'}), '(network_representation, dt, training_time, inter_pulse_interval=\n inter_pulse_interval, inter_sequence_interval=inter_sequence_interval,\n epochs=epochs, resting_time=resting_time)\n', (26994, 27180), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((27572, 27650), 'connectivity_functions.get_weights_from_probabilities', 'get_weights_from_probabilities', (['pi', 'pj', 'P', 'minicolumns_', 'hypercolumns', 'epsilon'], {}), '(pi, pj, P, minicolumns_, hypercolumns, epsilon)\n', (27602, 27650), False, 'from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation\n'), ((27697, 28114), 'network.BCPNNPerfect', 'BCPNNPerfect', (['hypercolumns', 'minicolumns_'], {'g_w_ampa': 'g_w_ampa', 'g_w': 'g_w', 'g_a': 'g_a', 'tau_a': 'tau_a', 'tau_m': 'tau_m', 'sigma': 'sigma', 'G': 'G', 'tau_z_pre_ampa': 'tau_z_pre_ampa', 'tau_z_post_ampa': 'tau_z_post_ampa', 'tau_p': 'tau_p', 'z_transfer': 'z_transfer', 'diagonal_zero': 'diagonal_zero', 'strict_maximum': 'strict_maximum', 'perfect': 'perfect', 'k_perfect': 'k_perfect', 'always_learning': 'always_learning', 'normalized_currents': 'normalized_currents'}), '(hypercolumns, minicolumns_, g_w_ampa=g_w_ampa, g_w=g_w, g_a=\n g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=\n tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p,\n z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=\n strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=\n always_learning, normalized_currents=normalized_currents)\n', (27709, 28114), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((28242, 28301), 'network.NetworkManager', 'NetworkManager', ([], {'nn': 'nn', 'dt': 'dt', 'values_to_save': 'values_to_save'}), '(nn=nn, dt=dt, values_to_save=values_to_save)\n', (28256, 28301), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((28645, 28717), 'analysis_functions.calculate_recall_time_quantities', 'calculate_recall_time_quantities', (['manager', 'T_recall', 'T_cue', 'n', 'sequences'], {}), '(manager, T_recall, T_cue, n, sequences)\n', (28677, 28717), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((28814, 28872), 'analysis_functions.get_weights', 'get_weights', (['manager', 'from_pattern', 'to_pattern'], {'mean': '(False)'}), '(manager, from_pattern, to_pattern, mean=False)\n', (28825, 28872), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((30515, 30579), 'connectivity_functions.build_network_representation', 'build_network_representation', (['matrix', 'minicolumns_', 'hypercolumns'], {}), '(matrix, minicolumns_, hypercolumns)\n', (30543, 30579), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((30603, 30799), 'network.TimedInput', 'TimedInput', (['network_representation', 'dt', 'training_time'], {'inter_pulse_interval': 'inter_pulse_interval', 'inter_sequence_interval': 'inter_sequence_interval', 'epochs': 'epochs', 'resting_time': 'resting_time'}), '(network_representation, dt, training_time, inter_pulse_interval=\n inter_pulse_interval, inter_sequence_interval=inter_sequence_interval,\n epochs=epochs, resting_time=resting_time)\n', (30613, 30799), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((31194, 31272), 'connectivity_functions.get_weights_from_probabilities', 'get_weights_from_probabilities', (['pi', 'pj', 'P', 'minicolumns_', 'hypercolumns', 'epsilon'], {}), '(pi, pj, P, minicolumns_, hypercolumns, epsilon)\n', (31224, 31272), False, 'from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation\n'), ((31318, 31735), 'network.BCPNNPerfect', 'BCPNNPerfect', (['hypercolumns', 'minicolumns_'], {'g_w_ampa': 'g_w_ampa', 'g_w': 'g_w', 'g_a': 'g_a', 'tau_a': 'tau_a', 'tau_m': 'tau_m', 'sigma': 'sigma', 'G': 'G', 'tau_z_pre_ampa': 'tau_z_pre_ampa', 'tau_z_post_ampa': 'tau_z_post_ampa', 'tau_p': 'tau_p', 'z_transfer': 'z_transfer', 'diagonal_zero': 'diagonal_zero', 'strict_maximum': 'strict_maximum', 'perfect': 'perfect', 'k_perfect': 'k_perfect', 'always_learning': 'always_learning', 'normalized_currents': 'normalized_currents'}), '(hypercolumns, minicolumns_, g_w_ampa=g_w_ampa, g_w=g_w, g_a=\n g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=\n tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p,\n z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=\n strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=\n always_learning, normalized_currents=normalized_currents)\n', (31330, 31735), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((31863, 31922), 'network.NetworkManager', 'NetworkManager', ([], {'nn': 'nn', 'dt': 'dt', 'values_to_save': 'values_to_save'}), '(nn=nn, dt=dt, values_to_save=values_to_save)\n', (31877, 31922), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((32163, 32235), 'analysis_functions.calculate_recall_time_quantities', 'calculate_recall_time_quantities', (['manager', 'T_recall', 'T_cue', 'n', 'sequences'], {}), '(manager, T_recall, T_cue, n, sequences)\n', (32195, 32235), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((32332, 32390), 'analysis_functions.get_weights', 'get_weights', (['manager', 'from_pattern', 'to_pattern'], {'mean': '(False)'}), '(manager, from_pattern, to_pattern, mean=False)\n', (32343, 32390), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((33913, 33977), 'connectivity_functions.build_network_representation', 'build_network_representation', (['matrix', 'minicolumns', 'hypercolumns_'], {}), '(matrix, minicolumns, hypercolumns_)\n', (33941, 33977), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((34001, 34197), 'network.TimedInput', 'TimedInput', (['network_representation', 'dt', 'training_time'], {'inter_pulse_interval': 'inter_pulse_interval', 'inter_sequence_interval': 'inter_sequence_interval', 'epochs': 'epochs', 'resting_time': 'resting_time'}), '(network_representation, dt, training_time, inter_pulse_interval=\n inter_pulse_interval, inter_sequence_interval=inter_sequence_interval,\n epochs=epochs, resting_time=resting_time)\n', (34011, 34197), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((34592, 34670), 'connectivity_functions.get_weights_from_probabilities', 'get_weights_from_probabilities', (['pi', 'pj', 'P', 'minicolumns', 'hypercolumns_', 'epsilon'], {}), '(pi, pj, P, minicolumns, hypercolumns_, epsilon)\n', (34622, 34670), False, 'from connectivity_functions import get_weights_from_probabilities, get_probabilities_from_network_representation\n'), ((34716, 35133), 'network.BCPNNPerfect', 'BCPNNPerfect', (['hypercolumns_', 'minicolumns'], {'g_w_ampa': 'g_w_ampa', 'g_w': 'g_w', 'g_a': 'g_a', 'tau_a': 'tau_a', 'tau_m': 'tau_m', 'sigma': 'sigma', 'G': 'G', 'tau_z_pre_ampa': 'tau_z_pre_ampa', 'tau_z_post_ampa': 'tau_z_post_ampa', 'tau_p': 'tau_p', 'z_transfer': 'z_transfer', 'diagonal_zero': 'diagonal_zero', 'strict_maximum': 'strict_maximum', 'perfect': 'perfect', 'k_perfect': 'k_perfect', 'always_learning': 'always_learning', 'normalized_currents': 'normalized_currents'}), '(hypercolumns_, minicolumns, g_w_ampa=g_w_ampa, g_w=g_w, g_a=\n g_a, tau_a=tau_a, tau_m=tau_m, sigma=sigma, G=G, tau_z_pre_ampa=\n tau_z_pre_ampa, tau_z_post_ampa=tau_z_post_ampa, tau_p=tau_p,\n z_transfer=z_transfer, diagonal_zero=diagonal_zero, strict_maximum=\n strict_maximum, perfect=perfect, k_perfect=k_perfect, always_learning=\n always_learning, normalized_currents=normalized_currents)\n', (34728, 35133), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((35261, 35320), 'network.NetworkManager', 'NetworkManager', ([], {'nn': 'nn', 'dt': 'dt', 'values_to_save': 'values_to_save'}), '(nn=nn, dt=dt, values_to_save=values_to_save)\n', (35275, 35320), False, 'from network import Protocol, NetworkManager, BCPNNPerfect, TimedInput\n'), ((35626, 35698), 'analysis_functions.calculate_recall_time_quantities', 'calculate_recall_time_quantities', (['manager', 'T_recall', 'T_cue', 'n', 'sequences'], {}), '(manager, T_recall, T_cue, n, sequences)\n', (35658, 35698), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((35795, 35853), 'analysis_functions.get_weights', 'get_weights', (['manager', 'from_pattern', 'to_pattern'], {'mean': '(False)'}), '(manager, from_pattern, to_pattern, mean=False)\n', (35806, 35853), False, 'from analysis_functions import calculate_recall_time_quantities, get_weights\n'), ((3168, 3192), 'numpy.diff', 'np.diff', (['Pij_self_vector'], {}), '(Pij_self_vector)\n', (3175, 3192), True, 'import numpy as np\n'), ((3195, 3223), 'numpy.abs', 'np.abs', (['Pij_self_vector[:-1]'], {}), '(Pij_self_vector[:-1])\n', (3201, 3223), True, 'import numpy as np\n'), ((3348, 3372), 'numpy.diff', 'np.diff', (['Pij_next_vector'], {}), '(Pij_next_vector)\n', (3355, 3372), True, 'import numpy as np\n'), ((3375, 3403), 'numpy.abs', 'np.abs', (['Pij_next_vector[:-1]'], {}), '(Pij_next_vector[:-1])\n', (3381, 3403), True, 'import numpy as np\n'), ((3528, 3552), 'numpy.diff', 'np.diff', (['Pij_rest_vector'], {}), '(Pij_rest_vector)\n', (3535, 3552), True, 'import numpy as np\n'), ((3555, 3583), 'numpy.abs', 'np.abs', (['Pij_rest_vector[:-1]'], {}), '(Pij_rest_vector[:-1])\n', (3561, 3583), True, 'import numpy as np\n'), ((3708, 3731), 'numpy.diff', 'np.diff', (['pi_self_vector'], {}), '(pi_self_vector)\n', (3715, 3731), True, 'import numpy as np\n'), ((3734, 3761), 'numpy.abs', 'np.abs', (['pi_self_vector[:-1]'], {}), '(pi_self_vector[:-1])\n', (3740, 3761), True, 'import numpy as np\n'), ((5971, 6040), 'connectivity_functions.create_orthogonal_canonical_representation', 'create_orthogonal_canonical_representation', (['minicolumns', 'hypercolumns'], {}), '(minicolumns, hypercolumns)\n', (6013, 6040), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((9382, 9451), 'connectivity_functions.create_orthogonal_canonical_representation', 'create_orthogonal_canonical_representation', (['minicolumns', 'hypercolumns'], {}), '(minicolumns, hypercolumns)\n', (9424, 9451), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((12808, 12877), 'connectivity_functions.create_orthogonal_canonical_representation', 'create_orthogonal_canonical_representation', (['minicolumns', 'hypercolumns'], {}), '(minicolumns, hypercolumns)\n', (12850, 12877), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((16394, 16463), 'connectivity_functions.create_orthogonal_canonical_representation', 'create_orthogonal_canonical_representation', (['minicolumns', 'hypercolumns'], {}), '(minicolumns, hypercolumns)\n', (16436, 16463), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((19867, 19936), 'connectivity_functions.create_orthogonal_canonical_representation', 'create_orthogonal_canonical_representation', (['minicolumns', 'hypercolumns'], {}), '(minicolumns, hypercolumns)\n', (19909, 19936), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((23327, 23396), 'connectivity_functions.create_orthogonal_canonical_representation', 'create_orthogonal_canonical_representation', (['minicolumns', 'hypercolumns'], {}), '(minicolumns, hypercolumns)\n', (23369, 23396), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((26779, 26849), 'connectivity_functions.create_orthogonal_canonical_representation', 'create_orthogonal_canonical_representation', (['minicolumns_', 'hypercolumns'], {}), '(minicolumns_, hypercolumns)\n', (26821, 26849), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((30397, 30467), 'connectivity_functions.create_orthogonal_canonical_representation', 'create_orthogonal_canonical_representation', (['minicolumns_', 'hypercolumns'], {}), '(minicolumns_, hypercolumns)\n', (30439, 30467), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n'), ((33796, 33866), 'connectivity_functions.create_orthogonal_canonical_representation', 'create_orthogonal_canonical_representation', (['minicolumns', 'hypercolumns_'], {}), '(minicolumns, hypercolumns_)\n', (33838, 33866), False, 'from connectivity_functions import create_orthogonal_canonical_representation, build_network_representation\n')]
from __future__ import print_function, absolute_import from collections import OrderedDict from ._result_base import H5NastranResultBase from h5Nastran.post_process.result_readers.punch import PunchReader import numpy as np import tables from six import iteritems class H5NastranResultPunch(H5NastranResultBase): def __init__(self, *args, **kwargs): super(H5NastranResultPunch, self).__init__(*args, **kwargs) def load_punch(self, filename): if self._bdf is None: raise Exception('BDF must be loaded first!') if self._f06 is not None: raise Exception('F06 has already been loaded. Cannot load punch file after f06.') self._punch = filename self._punch_subcase_ids.clear() reader = PunchReader(filename) reader.register_callback(self._load_punch_table) reader.read() self.h5f.flush() for table in self._tables: table.finalize() self._tables.clear() self._write_unsupported_tables() self._punch_finalize() def _punch_finalize(self): dtype = np.dtype([('SUBCASE_ID', '<i8'), ('LOAD_FACTOR', '<f8'), ('DOMAIN_ID', '<i8')]) format = tables.descr_from_dtype(dtype)[0] self.h5f.create_table(self.table_paths.subcase_path, self.table_paths.subcase_table, format, 'SUBCASES', expectedrows=len(self._punch_subcase_ids), createparents=True) table = self.h5f.get_node(self.table_paths.subcase) data = np.zeros(len(self._punch_subcase_ids), dtype=dtype) subcase_id = data['SUBCASE_ID'] load_factor = data['LOAD_FACTOR'] domain_id = data['DOMAIN_ID'] for key, domain_id_ in iteritems(self._punch_subcase_ids): index = domain_id_ - 1 subcase_id_, load_factor_ = key subcase_id[index] = subcase_id_ load_factor[index] = load_factor_ domain_id[index] = domain_id_ table.append(data) self.h5f.flush() def _load_punch_table(self, table_data): key = table_data.header.subcase_id_num, table_data.header.load_factor if key not in self._punch_subcase_ids: self._punch_subcase_ids[key] = len(self._punch_subcase_ids) + 1 results_type = table_data.header.results_type_basic table = self._result_tables.get(results_type, None) if table is None: return self._unsupported_table(table_data) table.write_punch_data(table_data) self._tables.add(table)
[ "h5Nastran.post_process.result_readers.punch.PunchReader", "tables.descr_from_dtype", "numpy.dtype", "six.iteritems" ]
[((780, 801), 'h5Nastran.post_process.result_readers.punch.PunchReader', 'PunchReader', (['filename'], {}), '(filename)\n', (791, 801), False, 'from h5Nastran.post_process.result_readers.punch import PunchReader\n'), ((1122, 1201), 'numpy.dtype', 'np.dtype', (["[('SUBCASE_ID', '<i8'), ('LOAD_FACTOR', '<f8'), ('DOMAIN_ID', '<i8')]"], {}), "([('SUBCASE_ID', '<i8'), ('LOAD_FACTOR', '<f8'), ('DOMAIN_ID', '<i8')])\n", (1130, 1201), True, 'import numpy as np\n'), ((1741, 1775), 'six.iteritems', 'iteritems', (['self._punch_subcase_ids'], {}), '(self._punch_subcase_ids)\n', (1750, 1775), False, 'from six import iteritems\n'), ((1219, 1249), 'tables.descr_from_dtype', 'tables.descr_from_dtype', (['dtype'], {}), '(dtype)\n', (1242, 1249), False, 'import tables\n')]
# -*- coding: utf-8 -*- """ @author: NysanAskar """ import numpy as np import tensorflow as tf from keras import backend as K import keras from tensorflow.keras.layers import ( Add, Input, ) from utils import xywh_to_x1y1x2y2, broadcast_iou, binary_cross_entropy anchors_wh = np.array([[10, 13], [16, 30], [33, 23], [30, 61], [62, 45], [59, 119], [116, 90], [156, 198], [373, 326]], np.float32) / 416 TOTAL_CLASSES = 80 backbone = [ (32, 3, 1, 'same', 'mish', '0'), ["SPP", 1, '1'], (64, 3, 1, 'same', 'mish', '2'), ["CSP", 2, '3'], (128, 1, 1, 'same', 'mish', '4'), ["CSP", 8, '5'], (256, 1, 1, 'same', 'mish', '6'), ["CSP", 8, '7'], (512, 1, 1, 'same', 'mish', '8'), ["CSP", 4, '9'], (1024, 1, 1, 'same', 'mish', '10'), ] neck = [ (512, 1, 1, 'same', 'leaky', '0'),# input_3 (1024, 3, 1, 'same', 'leaky', '1'), ["M", '2'], (512, 1, 1, 'same', 'leaky', '3'), (1024, 3, 1, 'same', 'leaky', '4'), (512, 1, 1, 'same', 'leaky', '5'),# output_3 (256, 1, 1, 'same', 'leaky', '6'), "U", #'7' ["C",'8'], (256, 1, 1, 'same', 'mish', '9'), (512, 3, 1, 'same', 'mish', '10'), (256, 1, 1, 'same', 'mish', '11'), (512, 3, 1, 'same', 'mish', '12'), (256, 1, 1, 'same', 'mish', '13'),# output_2 (128, 1, 1, 'same', 'leaky', '14'), "U", #'15' ["C",'16'], (128, 1, 1, 'same', 'leaky', '17'), (256, 3, 1, 'same', 'mish', '18'), (128, 1, 1, 'same', 'leaky', '19'), (256, 3, 1, 'same', 'mish', '20'), (128, 1, 1, 'same', 'leaky', '21'), (256, 3, 1, 'same', 'mish', '22'),# output_1 ] head = [ ["S", 256, '0'],# input_3 -> output_1 (256, 3, 2, 'valid', 'leaky', '1'),# input_3 ["C", 256, '2'], # concatanate with input_2 (512, 3, 1, 'same', 'leaky', '3'), (256, 1, 1, 'same', 'leaky', '4'), (512, 3, 1, 'same', 'leaky', '5'), (256, 1, 1, 'same', 'leaky', '6'), ["S", 256, '7'],# output_2 (512, 3, 2, 'valid', 'leaky', '8'), ["C", 512, '9'], # concatanate with input_1 (1024, 3, 1, 'same', 'leaky', '10'), (512, 1, 1, 'same', 'leaky', '11'),# output_2 (1024, 3, 1, 'same', 'leaky', '12'), (512, 1, 1, 'same', 'leaky', '13'), ["S", 512, '14'],# output_3 ] class Mish(tf.keras.layers.Layer): ''' Mish Activation Function. .. math:: Mish(x) = x * tanh(softplus(x)) ''' def __init__(self, **kwargs): super(Mish, self).__init__(**kwargs) def call(self, inputs): return inputs * K.tanh(K.softplus(inputs)) class CNNBlock(tf.keras.layers.Layer): def __init__(self, out_channels, bn_act=True, padding='same', activation='leaky',**kwargs): super().__init__() self.padding = padding self.conv = tf.keras.layers.Conv2D(filters = out_channels, use_bias=not bn_act, padding=padding, **kwargs) self.bn = tf.keras.layers.BatchNormalization() self.leaky = tf.keras.layers.LeakyReLU(0.1) self.use_bn_act = bn_act self.zero_pad = tf.keras.layers.ZeroPadding2D(padding=(1, 1)) self.activ_func = activation self.mish = Mish() def call(self, input_tensor): if self.activ_func == 'leaky': if self.padding == 'same': if self.use_bn_act: return self.leaky(self.bn(self.conv(input_tensor))) else: return self.conv(input_tensor) else: if self.use_bn_act: z = self.zero_pad(input_tensor) return self.leaky(self.bn(self.conv(z))) else: z = self.zero_pad(input_tensor) return self.conv(z) # TensorShape([3, 224, 224, 5]) elif self.activ_func == 'mish': if self.padding == 'same': if self.use_bn_act: return self.mish(self.bn(self.conv(input_tensor))) else: return self.conv(input_tensor) else: if self.use_bn_act: z = self.zero_pad(input_tensor) return self.mish(self.bn(self.conv(z))) else: z = self.zero_pad(input_tensor) return self.conv(z) # TensorShape([3, 224, 224, 5]) class ResidualBlock(tf.keras.layers.Layer): def __init__(self, channels, use_residual=True, num_repeats=1): super().__init__() self.layers = [] for _ in range(num_repeats): self.layers += [ keras.Sequential([ CNNBlock(channels, kernel_size=1, activation='mish'), CNNBlock(channels, kernel_size=3, padding='same', activation='mish')] )] self.use_residual = use_residual self.num_repeats = num_repeats def call(self, input_tensor): for layer in self.layers: if self.use_residual: x = Add()([input_tensor,layer(input_tensor)]) else: x = layer(input_tensor) return x # TensorShape([3, 224, 224, 5]) class CSPBlock(tf.keras.layers.Layer): def __init__(self, channels, num_res_block=1): super().__init__() self.conv_1 = CNNBlock(out_channels=channels, padding='valid', activation='mish', kernel_size=3, strides=2) self.conv_2 = CNNBlock(out_channels=channels//2, padding='same', activation='mish', kernel_size=1, strides=1) self.conv_3 = CNNBlock(out_channels=channels//2, padding='same', activation='mish', kernel_size=1, strides=1) self.res_block = ResidualBlock(channels=channels//2, num_repeats=num_res_block) def call(self, input_tensor): x = self.conv_1(input_tensor) x_1 = self.conv_2(x) x_2 = self.conv_2(x) x_2 = self.res_block(x_2) x_2 = self.conv_3(x_2) x = tf.concat([x_1, x_2], -1) return x # tf.Tensor: shape=(3, 208, 208, 256) class backbone_layers(tf.keras.layers.Layer): def __init__(self, in_channels=3): super().__init__() self.in_channels = in_channels self.layers = self._create_conv_layers() def call(self, x): outputs = [] # for each scale for i, layer in enumerate(self.layers): if i in [6, 8, 10]: outputs.append(layer(x)) x = layer(x) return outputs def _create_conv_layers(self): layers = [] in_channels = self.in_channels for module in backbone: if isinstance(module, tuple): out_channels, kernel_size, strides, padding, ac_faunc, name_layer = module layers.append( CNNBlock( out_channels, kernel_size=kernel_size, strides=strides, padding=padding, activation = ac_faunc, name = name_layer)) in_channels = out_channels elif isinstance(module, list): num_repeats = module[1] layers.append(CSPBlock(in_channels*2, num_res_block=num_repeats)) return layers class max_pool(tf.keras.layers.Layer): def __init__(self): super().__init__() self.conv_1 = CNNBlock(out_channels=512, kernel_size=1,strides=1, padding='same', activation = 'leaky') self.max_1 = tf.keras.layers.MaxPool2D((5, 5), strides=1, padding="same") self.max_2 = tf.keras.layers.MaxPool2D((9, 9), strides=1, padding="same") self.max_3 = tf.keras.layers.MaxPool2D((13, 13), strides=1, padding="same") def call(self, x): x_1 = self.conv_1(x) x_max_1 = self.max_1(x_1) x_max_2 = self.max_2(x_1) x_max_3 = self.max_3(x_1) x = tf.concat([x_1, x_max_1,x_max_2,x_max_3], -1) return x class concat(tf.keras.layers.Layer): def __init__(self, channels, ): super().__init__() self.conc = tf.keras.layers.Concatenate(axis=-1) self.conv = CNNBlock(out_channels=channels, kernel_size=1,strides=1, padding='same', activation = 'leaky') def call(self, x_1, x_2): x_2 = self.conv(x_2) x = self.conc([x_1, x_2,]) return x class yolov4_neck(tf.keras.layers.Layer): def __init__(self): super().__init__() self.layers = self._create_conv_layers() def call(self, input_tensor): outputs = [] # for each scale route_connections = [] inputs = input_tensor[:2] x = input_tensor[2] for i, layer in enumerate(self.layers): if i in [5, 13, 22]: outputs.append(layer(x)) elif isinstance(layer, tf.keras.layers.UpSampling2D): route_connections.append(layer(x)) x = layer(x) elif isinstance(layer, concat): x = layer(route_connections.pop(), inputs.pop()) else: x = layer(x) return outputs def _create_conv_layers(self): layers = [] for module in neck: if isinstance(module, tuple): out_channels, kernel_size, strides, padding, act_func, name = module layers.append( CNNBlock( out_channels, kernel_size=kernel_size, strides=strides, padding=padding, activation=act_func)) in_channels = out_channels elif isinstance(module, list): l = module[0] if l == 'M': layers.append(max_pool()) elif l == 'C': layers.append(concat(in_channels)) elif isinstance(module, str): layers.append(tf.keras.layers.UpSampling2D(size=2)) return layers class ScalePrediction(tf.keras.layers.Layer): def __init__(self, in_channels, num_classes): super().__init__() self.conv_1 = CNNBlock(2 * in_channels, kernel_size=3, padding='same') self.conv_2 = CNNBlock((num_classes + 5) * 3, bn_act=False, kernel_size=1) self.num_classes = num_classes def call(self, input_tensor): if input_tensor.get_shape()[1] == 52: x = self.conv_2(input_tensor) x = tf.reshape(x, shape=(K.shape(x)[0], K.shape(x)[1], K.shape(x)[2], 3, self.num_classes + 5)) return x else: x = self.conv_1(input_tensor) x = self.conv_2(x) x = tf.reshape(x, shape=(K.shape(x)[0], K.shape(x)[1], K.shape(x)[2], 3, self.num_classes + 5)) return x # TensorShape([3, 416, 416, 3, 85]) class concat_head(tf.keras.layers.Layer): def __init__(self, in_channels): super().__init__() self.ch = in_channels self.conc = tf.keras.layers.Concatenate(axis=-1) self.conv = CNNBlock(self.ch, kernel_size=1,strides=1, padding='same', activation = 'leaky') def call(self, x_1, x_2): x = self.conc([x_1, x_2,]) x = self.conv(x) return x class yolov4_head(tf.keras.layers.Layer): def __init__(self, num_classes): self.num_classes = num_classes super().__init__() self.layers = self._create_conv_layers() def call(self, input_tensor): outputs = [] # for each scale inputs = input_tensor[:2] x = input_tensor[2] for i, layer in enumerate(self.layers): if i in [0, 7, 14]: outputs.append(layer(x)) continue elif isinstance(layer, concat_head): x = layer(x, inputs.pop()) else: x = layer(x) return outputs def _create_conv_layers(self): layers = [] for module in head: if isinstance(module, tuple): out_channels, kernel_size, strides, padding, act_func, name = module layers.append( CNNBlock( out_channels, kernel_size=kernel_size, strides=strides, padding=padding, activation=act_func)) in_channels = out_channels elif isinstance(module, list): l, c = module[0], module[1] if l == 'C': layers.append(concat_head(in_channels=c)) elif l == 'S': layers.append(ScalePrediction(in_channels=c, num_classes= self.num_classes)) return layers def YoloV4(num_classes, shape=(416, 416, 3), training=True): inputs = Input(shape=shape) model_backbone = backbone_layers() out_backbone = model_backbone(inputs) model_neck = yolov4_neck() out_neck = model_neck(out_backbone) model_head = yolov4_head(num_classes) y_small, y_medium, y_large = model_head(out_neck) return tf.keras.Model(inputs, (y_small, y_medium, y_large)) def get_absolute_yolo_box(y_pred, valid_anchors_wh, num_classes): """ inputs: y_pred: Prediction tensor from the model output, in the shape of (batch, grid, grid, anchor, 5 + num_classes) outputs: y_box: boxes in shape of (batch, grid, grid, anchor, 4), the last dimension is (xmin, ymin, xmax, ymax) objectness: probability that an object exists classes: probability of classes """ t_xy, t_wh, objectness, classes = tf.split( y_pred, (2, 2, 1, num_classes), axis=-1) objectness = tf.sigmoid(objectness) classes = tf.sigmoid(classes) grid_size = tf.shape(y_pred)[1] C_xy = tf.meshgrid(tf.range(grid_size), tf.range(grid_size)) C_xy = tf.stack(C_xy, axis=-1) C_xy = tf.expand_dims(C_xy, axis=2) # [gx, gy, 1, 2] b_xy = tf.sigmoid(t_xy) + tf.cast(C_xy, tf.float32) b_xy = b_xy / tf.cast(grid_size, tf.float32) b_wh = tf.exp(t_wh) * valid_anchors_wh y_box = tf.concat([b_xy, b_wh], axis=-1) return y_box, objectness, classes def get_relative_yolo_box(y_true, valid_anchors_wh): """ This is the inverse of `get_absolute_yolo_box` above. """ grid_size = tf.shape(y_true)[1] C_xy = tf.meshgrid(tf.range(grid_size), tf.range(grid_size)) C_xy = tf.expand_dims(tf.stack(C_xy, axis=-1), axis=2) b_xy = y_true[..., 0:2] b_wh = y_true[..., 2:4] t_xy = b_xy * tf.cast(grid_size, tf.float32) - tf.cast(C_xy, tf.float32) t_wh = tf.math.log(b_wh / valid_anchors_wh) # b_wh could have some cells are 0, divided by anchor could result in inf or nan t_wh = tf.where( tf.logical_or(tf.math.is_inf(t_wh), tf.math.is_nan(t_wh)), tf.zeros_like(t_wh), t_wh) y_box = tf.concat([t_xy, t_wh], axis=-1) return y_box class YoloLoss(object): def __init__(self, num_classes, valid_anchors_wh): self.num_classes = num_classes self.ignore_thresh = 0.5 self.valid_anchors_wh = valid_anchors_wh self.lambda_coord = 5.0 self.lamda_noobj = 0.5 def __call__(self, y_true, y_pred): pred_xy_rel = tf.sigmoid(y_pred[..., 0:2]) # (None, grid, grid, 3,2) pred_wh_rel = y_pred[..., 2:4] # (None, grid, grid, 3,2) pred_box_abs, pred_obj, pred_class = get_absolute_yolo_box( y_pred, self.valid_anchors_wh, self.num_classes) # # pred_box_abs (None, grid, grid, 3, 4), pred_obj (None, grid, grid, 3, 1), pred_class (None, grid, grid, 3, num_classes) pred_box_abs = xywh_to_x1y1x2y2(pred_box_abs) true_xy_abs, true_wh_abs, true_obj, true_class = tf.split( y_true, (2, 2, 1, self.num_classes), axis=-1) # # true_xy_abs (None, grid, grid, 3, 2), true_wh_abs (None, grid, grid, 3, 2), true_obj (None, grid, grid, 3, 1), true_class (None, grid, grid, 3, num_classes) true_box_abs = tf.concat([true_xy_abs, true_wh_abs], axis=-1) #true_box_abs (None, grid, grid, 3, 4) true_box_abs = xywh_to_x1y1x2y2(true_box_abs) true_box_rel = get_relative_yolo_box(y_true, self.valid_anchors_wh) true_xy_rel = true_box_rel[..., 0:2] true_wh_rel = true_box_rel[..., 2:4] weight = 2 - true_wh_abs[..., 0] * true_wh_abs[..., 1] # (None, grid, grid, 3) xy_loss = self.calc_xy_loss(true_obj, true_xy_rel, pred_xy_rel, weight) wh_loss = self.calc_wh_loss(true_obj, true_wh_rel, pred_wh_rel, weight) class_loss, class_accuracy = self.calc_class_loss(true_obj, true_class, pred_class) ignore_mask, mIoU = self.calc_ignore_mask(true_obj, true_box_abs, pred_box_abs) obj_loss = self.calc_obj_loss(true_obj, pred_obj, ignore_mask) return xy_loss + wh_loss + class_loss + obj_loss, (xy_loss, wh_loss, class_loss, obj_loss,class_accuracy, mIoU) def calc_ignore_mask(self, true_obj, true_box, pred_box): # YOLOv3: true_box_shape = tf.shape(true_box) # (None, 13, 13, 3, 4) pred_box_shape = tf.shape(pred_box) # (None, 507, 4) true_box = tf.reshape(true_box, [true_box_shape[0], -1, 4]) # sort true_box to have non-zero boxes rank first true_box = tf.sort(true_box, axis=1, direction="DESCENDING") # (None, 100, 4) true_box = true_box[:, 0:100, :] # (None, 507, 4) pred_box = tf.reshape(pred_box, [pred_box_shape[0], -1, 4]) # (None, 507, 100) iou = broadcast_iou(pred_box, true_box) # (None, 507) best_iou = tf.reduce_max(iou, axis=-1) # (None, 13, 13, 3) best_iou = tf.reshape(best_iou, [pred_box_shape[0], pred_box_shape[1], pred_box_shape[2], pred_box_shape[3]]) # ignore_mask = 1 => don't ignore # ignore_mask = 0 => should ignore ignore_mask = tf.cast(best_iou < self.ignore_thresh, tf.float32) # (None, 13, 13, 3, 1) ignore_mask = tf.expand_dims(ignore_mask, axis=-1) # (None, 13, 13, 3, 1) best_iou = tf.expand_dims(best_iou, axis=-1) # (None, ) max_iou = tf.reduce_sum((best_iou*true_obj), axis=[1,2,3,4]) / tf.reduce_sum((true_obj[0])+0.001) return ignore_mask, max_iou def calc_obj_loss(self, true_obj, pred_obj, ignore_mask): """ calculate loss of objectness: sum of L2 distances inputs: true_obj: objectness from ground truth in shape of (batch, grid, grid, anchor, num_classes) pred_obj: objectness from model prediction in shape of (batch, grid, grid, anchor, num_classes) outputs: obj_loss: objectness loss """ obj_entropy = binary_cross_entropy(pred_obj, true_obj) obj_loss = true_obj * obj_entropy noobj_loss = (1 - true_obj) * obj_entropy * ignore_mask obj_loss = tf.reduce_sum(obj_loss, axis=(1, 2, 3, 4)) noobj_loss = tf.reduce_sum( noobj_loss, axis=(1, 2, 3, 4)) * self.lamda_noobj return obj_loss + noobj_loss def calc_class_loss(self, true_obj, true_class, pred_class): """ calculate loss of class prediction inputs: true_obj: if the object present from ground truth in shape of (batch, grid, grid, anchor, 1) true_class: one-hot class from ground truth in shape of (batch, grid, grid, anchor, num_classes) pred_class: one-hot class from model prediction in shape of (batch, grid, grid, anchor, num_classes) outputs: class_loss: class loss """ pred_class_new = tf.cast(pred_class>0.5, tf.float32) class_accuracy = 1 - tf.reduce_sum(tf.abs(pred_class_new - true_class), axis=[1,2,3,4]) / tf.cast(tf.size(true_class[0]), tf.float32) class_loss = binary_cross_entropy(pred_class, true_class) class_loss = true_obj * class_loss class_loss = tf.reduce_sum(class_loss, axis=(1, 2, 3, 4)) return class_loss, class_accuracy def calc_xy_loss(self, true_obj, true_xy, pred_xy, weight): """ calculate loss of the centroid coordinate: sum of L2 distances inputs: true_obj: if the object present from ground truth in shape of (batch, grid, grid, anchor, 1) true_xy: centroid x and y from ground truth in shape of (batch, grid, grid, anchor, 2) pred_xy: centroid x and y from model prediction in shape of (batch, grid, grid, anchor, 2) weight: weight adjustment, reward smaller bounding box outputs: xy_loss: centroid loss """ # shape (batch, grid, grid, anchor), eg. (32, 13, 13, 3) xy_loss = tf.reduce_sum(tf.square(true_xy - pred_xy), axis=-1) # in order to element-wise multiply the result from tf.reduce_sum # we need to squeeze one dimension for objectness here true_obj = tf.squeeze(true_obj, axis=-1) xy_loss = true_obj * xy_loss * weight xy_loss = tf.reduce_sum(xy_loss, axis=(1, 2, 3)) * self.lambda_coord return xy_loss # (batch_size/None, ) def calc_wh_loss(self, true_obj, true_wh, pred_wh, weight): """ calculate loss of the width and height: sum of L2 distances inputs: true_obj: if the object present from ground truth in shape of (batch, grid, grid, anchor, 1) true_wh: width and height from ground truth in shape of (batch, grid, grid, anchor, 2) pred_wh: width and height from model prediction in shape of (batch, grid, grid, anchor, 2) weight: weight adjustment, reward smaller bounding box outputs: wh_loss: width and height loss """ # shape (batch, grid, grid, anchor), eg. (32, 13, 13, 3) wh_loss = tf.reduce_sum(tf.square(true_wh - pred_wh), axis=-1) true_obj = tf.squeeze(true_obj, axis=-1) wh_loss = true_obj * wh_loss * weight wh_loss = tf.reduce_sum(wh_loss, axis=(1, 2, 3)) * self.lambda_coord return wh_loss # (batch_size/None,)
[ "tensorflow.shape", "tensorflow.sort", "keras.backend.shape", "tensorflow.math.log", "tensorflow.reduce_sum", "tensorflow.split", "keras.backend.softplus", "tensorflow.keras.layers.BatchNormalization", "numpy.array", "tensorflow.cast", "tensorflow.keras.layers.Input", "tensorflow.keras.layers....
[((303, 425), 'numpy.array', 'np.array', (['[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45], [59, 119], [116, 90], [\n 156, 198], [373, 326]]', 'np.float32'], {}), '([[10, 13], [16, 30], [33, 23], [30, 61], [62, 45], [59, 119], [116,\n 90], [156, 198], [373, 326]], np.float32)\n', (311, 425), True, 'import numpy as np\n'), ((13170, 13188), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': 'shape'}), '(shape=shape)\n', (13175, 13188), False, 'from tensorflow.keras.layers import Add, Input\n'), ((13455, 13507), 'tensorflow.keras.Model', 'tf.keras.Model', (['inputs', '(y_small, y_medium, y_large)'], {}), '(inputs, (y_small, y_medium, y_large))\n', (13469, 13507), True, 'import tensorflow as tf\n'), ((13975, 14024), 'tensorflow.split', 'tf.split', (['y_pred', '(2, 2, 1, num_classes)'], {'axis': '(-1)'}), '(y_pred, (2, 2, 1, num_classes), axis=-1)\n', (13983, 14024), True, 'import tensorflow as tf\n'), ((14053, 14075), 'tensorflow.sigmoid', 'tf.sigmoid', (['objectness'], {}), '(objectness)\n', (14063, 14075), True, 'import tensorflow as tf\n'), ((14091, 14110), 'tensorflow.sigmoid', 'tf.sigmoid', (['classes'], {}), '(classes)\n', (14101, 14110), True, 'import tensorflow as tf\n'), ((14226, 14249), 'tensorflow.stack', 'tf.stack', (['C_xy'], {'axis': '(-1)'}), '(C_xy, axis=-1)\n', (14234, 14249), True, 'import tensorflow as tf\n'), ((14262, 14290), 'tensorflow.expand_dims', 'tf.expand_dims', (['C_xy'], {'axis': '(2)'}), '(C_xy, axis=2)\n', (14276, 14290), True, 'import tensorflow as tf\n'), ((14473, 14505), 'tensorflow.concat', 'tf.concat', (['[b_xy, b_wh]'], {'axis': '(-1)'}), '([b_xy, b_wh], axis=-1)\n', (14482, 14505), True, 'import tensorflow as tf\n'), ((14991, 15027), 'tensorflow.math.log', 'tf.math.log', (['(b_wh / valid_anchors_wh)'], {}), '(b_wh / valid_anchors_wh)\n', (15002, 15027), True, 'import tensorflow as tf\n'), ((15253, 15285), 'tensorflow.concat', 'tf.concat', (['[t_xy, t_wh]'], {'axis': '(-1)'}), '([t_xy, t_wh], axis=-1)\n', (15262, 15285), True, 'import tensorflow as tf\n'), ((2899, 2996), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': 'out_channels', 'use_bias': '(not bn_act)', 'padding': 'padding'}), '(filters=out_channels, use_bias=not bn_act, padding=\n padding, **kwargs)\n', (2921, 2996), True, 'import tensorflow as tf\n'), ((3013, 3049), 'tensorflow.keras.layers.BatchNormalization', 'tf.keras.layers.BatchNormalization', ([], {}), '()\n', (3047, 3049), True, 'import tensorflow as tf\n'), ((3072, 3102), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', (['(0.1)'], {}), '(0.1)\n', (3097, 3102), True, 'import tensorflow as tf\n'), ((3162, 3207), 'tensorflow.keras.layers.ZeroPadding2D', 'tf.keras.layers.ZeroPadding2D', ([], {'padding': '(1, 1)'}), '(padding=(1, 1))\n', (3191, 3207), True, 'import tensorflow as tf\n'), ((6168, 6193), 'tensorflow.concat', 'tf.concat', (['[x_1, x_2]', '(-1)'], {}), '([x_1, x_2], -1)\n', (6177, 6193), True, 'import tensorflow as tf\n'), ((7729, 7789), 'tensorflow.keras.layers.MaxPool2D', 'tf.keras.layers.MaxPool2D', (['(5, 5)'], {'strides': '(1)', 'padding': '"""same"""'}), "((5, 5), strides=1, padding='same')\n", (7754, 7789), True, 'import tensorflow as tf\n'), ((7812, 7872), 'tensorflow.keras.layers.MaxPool2D', 'tf.keras.layers.MaxPool2D', (['(9, 9)'], {'strides': '(1)', 'padding': '"""same"""'}), "((9, 9), strides=1, padding='same')\n", (7837, 7872), True, 'import tensorflow as tf\n'), ((7895, 7957), 'tensorflow.keras.layers.MaxPool2D', 'tf.keras.layers.MaxPool2D', (['(13, 13)'], {'strides': '(1)', 'padding': '"""same"""'}), "((13, 13), strides=1, padding='same')\n", (7920, 7957), True, 'import tensorflow as tf\n'), ((8130, 8177), 'tensorflow.concat', 'tf.concat', (['[x_1, x_max_1, x_max_2, x_max_3]', '(-1)'], {}), '([x_1, x_max_1, x_max_2, x_max_3], -1)\n', (8139, 8177), True, 'import tensorflow as tf\n'), ((8322, 8358), 'tensorflow.keras.layers.Concatenate', 'tf.keras.layers.Concatenate', ([], {'axis': '(-1)'}), '(axis=-1)\n', (8349, 8358), True, 'import tensorflow as tf\n'), ((11304, 11340), 'tensorflow.keras.layers.Concatenate', 'tf.keras.layers.Concatenate', ([], {'axis': '(-1)'}), '(axis=-1)\n', (11331, 11340), True, 'import tensorflow as tf\n'), ((14128, 14144), 'tensorflow.shape', 'tf.shape', (['y_pred'], {}), '(y_pred)\n', (14136, 14144), True, 'import tensorflow as tf\n'), ((14172, 14191), 'tensorflow.range', 'tf.range', (['grid_size'], {}), '(grid_size)\n', (14180, 14191), True, 'import tensorflow as tf\n'), ((14193, 14212), 'tensorflow.range', 'tf.range', (['grid_size'], {}), '(grid_size)\n', (14201, 14212), True, 'import tensorflow as tf\n'), ((14321, 14337), 'tensorflow.sigmoid', 'tf.sigmoid', (['t_xy'], {}), '(t_xy)\n', (14331, 14337), True, 'import tensorflow as tf\n'), ((14340, 14365), 'tensorflow.cast', 'tf.cast', (['C_xy', 'tf.float32'], {}), '(C_xy, tf.float32)\n', (14347, 14365), True, 'import tensorflow as tf\n'), ((14385, 14415), 'tensorflow.cast', 'tf.cast', (['grid_size', 'tf.float32'], {}), '(grid_size, tf.float32)\n', (14392, 14415), True, 'import tensorflow as tf\n'), ((14428, 14440), 'tensorflow.exp', 'tf.exp', (['t_wh'], {}), '(t_wh)\n', (14434, 14440), True, 'import tensorflow as tf\n'), ((14697, 14713), 'tensorflow.shape', 'tf.shape', (['y_true'], {}), '(y_true)\n', (14705, 14713), True, 'import tensorflow as tf\n'), ((14741, 14760), 'tensorflow.range', 'tf.range', (['grid_size'], {}), '(grid_size)\n', (14749, 14760), True, 'import tensorflow as tf\n'), ((14762, 14781), 'tensorflow.range', 'tf.range', (['grid_size'], {}), '(grid_size)\n', (14770, 14781), True, 'import tensorflow as tf\n'), ((14810, 14833), 'tensorflow.stack', 'tf.stack', (['C_xy'], {'axis': '(-1)'}), '(C_xy, axis=-1)\n', (14818, 14833), True, 'import tensorflow as tf\n'), ((14953, 14978), 'tensorflow.cast', 'tf.cast', (['C_xy', 'tf.float32'], {}), '(C_xy, tf.float32)\n', (14960, 14978), True, 'import tensorflow as tf\n'), ((15213, 15232), 'tensorflow.zeros_like', 'tf.zeros_like', (['t_wh'], {}), '(t_wh)\n', (15226, 15232), True, 'import tensorflow as tf\n'), ((15642, 15670), 'tensorflow.sigmoid', 'tf.sigmoid', (['y_pred[..., 0:2]'], {}), '(y_pred[..., 0:2])\n', (15652, 15670), True, 'import tensorflow as tf\n'), ((16043, 16073), 'utils.xywh_to_x1y1x2y2', 'xywh_to_x1y1x2y2', (['pred_box_abs'], {}), '(pred_box_abs)\n', (16059, 16073), False, 'from utils import xywh_to_x1y1x2y2, broadcast_iou, binary_cross_entropy\n'), ((16132, 16186), 'tensorflow.split', 'tf.split', (['y_true', '(2, 2, 1, self.num_classes)'], {'axis': '(-1)'}), '(y_true, (2, 2, 1, self.num_classes), axis=-1)\n', (16140, 16186), True, 'import tensorflow as tf\n'), ((16387, 16433), 'tensorflow.concat', 'tf.concat', (['[true_xy_abs, true_wh_abs]'], {'axis': '(-1)'}), '([true_xy_abs, true_wh_abs], axis=-1)\n', (16396, 16433), True, 'import tensorflow as tf\n'), ((16497, 16527), 'utils.xywh_to_x1y1x2y2', 'xywh_to_x1y1x2y2', (['true_box_abs'], {}), '(true_box_abs)\n', (16513, 16527), False, 'from utils import xywh_to_x1y1x2y2, broadcast_iou, binary_cross_entropy\n'), ((17607, 17625), 'tensorflow.shape', 'tf.shape', (['true_box'], {}), '(true_box)\n', (17615, 17625), True, 'import tensorflow as tf\n'), ((17684, 17702), 'tensorflow.shape', 'tf.shape', (['pred_box'], {}), '(pred_box)\n', (17692, 17702), True, 'import tensorflow as tf\n'), ((17749, 17797), 'tensorflow.reshape', 'tf.reshape', (['true_box', '[true_box_shape[0], -1, 4]'], {}), '(true_box, [true_box_shape[0], -1, 4])\n', (17759, 17797), True, 'import tensorflow as tf\n'), ((17877, 17926), 'tensorflow.sort', 'tf.sort', (['true_box'], {'axis': '(1)', 'direction': '"""DESCENDING"""'}), "(true_box, axis=1, direction='DESCENDING')\n", (17884, 17926), True, 'import tensorflow as tf\n'), ((18041, 18089), 'tensorflow.reshape', 'tf.reshape', (['pred_box', '[pred_box_shape[0], -1, 4]'], {}), '(pred_box, [pred_box_shape[0], -1, 4])\n', (18051, 18089), True, 'import tensorflow as tf\n'), ((18133, 18166), 'utils.broadcast_iou', 'broadcast_iou', (['pred_box', 'true_box'], {}), '(pred_box, true_box)\n', (18146, 18166), False, 'from utils import xywh_to_x1y1x2y2, broadcast_iou, binary_cross_entropy\n'), ((18210, 18237), 'tensorflow.reduce_max', 'tf.reduce_max', (['iou'], {'axis': '(-1)'}), '(iou, axis=-1)\n', (18223, 18237), True, 'import tensorflow as tf\n'), ((18287, 18390), 'tensorflow.reshape', 'tf.reshape', (['best_iou', '[pred_box_shape[0], pred_box_shape[1], pred_box_shape[2], pred_box_shape[3]]'], {}), '(best_iou, [pred_box_shape[0], pred_box_shape[1], pred_box_shape[\n 2], pred_box_shape[3]])\n', (18297, 18390), True, 'import tensorflow as tf\n'), ((18496, 18546), 'tensorflow.cast', 'tf.cast', (['(best_iou < self.ignore_thresh)', 'tf.float32'], {}), '(best_iou < self.ignore_thresh, tf.float32)\n', (18503, 18546), True, 'import tensorflow as tf\n'), ((18602, 18638), 'tensorflow.expand_dims', 'tf.expand_dims', (['ignore_mask'], {'axis': '(-1)'}), '(ignore_mask, axis=-1)\n', (18616, 18638), True, 'import tensorflow as tf\n'), ((18691, 18724), 'tensorflow.expand_dims', 'tf.expand_dims', (['best_iou'], {'axis': '(-1)'}), '(best_iou, axis=-1)\n', (18705, 18724), True, 'import tensorflow as tf\n'), ((19342, 19382), 'utils.binary_cross_entropy', 'binary_cross_entropy', (['pred_obj', 'true_obj'], {}), '(pred_obj, true_obj)\n', (19362, 19382), False, 'from utils import xywh_to_x1y1x2y2, broadcast_iou, binary_cross_entropy\n'), ((19515, 19557), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['obj_loss'], {'axis': '(1, 2, 3, 4)'}), '(obj_loss, axis=(1, 2, 3, 4))\n', (19528, 19557), True, 'import tensorflow as tf\n'), ((20245, 20282), 'tensorflow.cast', 'tf.cast', (['(pred_class > 0.5)', 'tf.float32'], {}), '(pred_class > 0.5, tf.float32)\n', (20252, 20282), True, 'import tensorflow as tf\n'), ((20446, 20490), 'utils.binary_cross_entropy', 'binary_cross_entropy', (['pred_class', 'true_class'], {}), '(pred_class, true_class)\n', (20466, 20490), False, 'from utils import xywh_to_x1y1x2y2, broadcast_iou, binary_cross_entropy\n'), ((20557, 20601), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['class_loss'], {'axis': '(1, 2, 3, 4)'}), '(class_loss, axis=(1, 2, 3, 4))\n', (20570, 20601), True, 'import tensorflow as tf\n'), ((21538, 21567), 'tensorflow.squeeze', 'tf.squeeze', (['true_obj'], {'axis': '(-1)'}), '(true_obj, axis=-1)\n', (21548, 21567), True, 'import tensorflow as tf\n'), ((22496, 22525), 'tensorflow.squeeze', 'tf.squeeze', (['true_obj'], {'axis': '(-1)'}), '(true_obj, axis=-1)\n', (22506, 22525), True, 'import tensorflow as tf\n'), ((14920, 14950), 'tensorflow.cast', 'tf.cast', (['grid_size', 'tf.float32'], {}), '(grid_size, tf.float32)\n', (14927, 14950), True, 'import tensorflow as tf\n'), ((15159, 15179), 'tensorflow.math.is_inf', 'tf.math.is_inf', (['t_wh'], {}), '(t_wh)\n', (15173, 15179), True, 'import tensorflow as tf\n'), ((15181, 15201), 'tensorflow.math.is_nan', 'tf.math.is_nan', (['t_wh'], {}), '(t_wh)\n', (15195, 15201), True, 'import tensorflow as tf\n'), ((18768, 18821), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(best_iou * true_obj)'], {'axis': '[1, 2, 3, 4]'}), '(best_iou * true_obj, axis=[1, 2, 3, 4])\n', (18781, 18821), True, 'import tensorflow as tf\n'), ((18821, 18855), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(true_obj[0] + 0.001)'], {}), '(true_obj[0] + 0.001)\n', (18834, 18855), True, 'import tensorflow as tf\n'), ((19580, 19624), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['noobj_loss'], {'axis': '(1, 2, 3, 4)'}), '(noobj_loss, axis=(1, 2, 3, 4))\n', (19593, 19624), True, 'import tensorflow as tf\n'), ((21338, 21366), 'tensorflow.square', 'tf.square', (['(true_xy - pred_xy)'], {}), '(true_xy - pred_xy)\n', (21347, 21366), True, 'import tensorflow as tf\n'), ((21634, 21672), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['xy_loss'], {'axis': '(1, 2, 3)'}), '(xy_loss, axis=(1, 2, 3))\n', (21647, 21672), True, 'import tensorflow as tf\n'), ((22437, 22465), 'tensorflow.square', 'tf.square', (['(true_wh - pred_wh)'], {}), '(true_wh - pred_wh)\n', (22446, 22465), True, 'import tensorflow as tf\n'), ((22592, 22630), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['wh_loss'], {'axis': '(1, 2, 3)'}), '(wh_loss, axis=(1, 2, 3))\n', (22605, 22630), True, 'import tensorflow as tf\n'), ((2659, 2677), 'keras.backend.softplus', 'K.softplus', (['inputs'], {}), '(inputs)\n', (2669, 2677), True, 'from keras import backend as K\n'), ((5146, 5151), 'tensorflow.keras.layers.Add', 'Add', ([], {}), '()\n', (5149, 5151), False, 'from tensorflow.keras.layers import Add, Input\n'), ((20325, 20360), 'tensorflow.abs', 'tf.abs', (['(pred_class_new - true_class)'], {}), '(pred_class_new - true_class)\n', (20331, 20360), True, 'import tensorflow as tf\n'), ((20388, 20410), 'tensorflow.size', 'tf.size', (['true_class[0]'], {}), '(true_class[0])\n', (20395, 20410), True, 'import tensorflow as tf\n'), ((10229, 10265), 'tensorflow.keras.layers.UpSampling2D', 'tf.keras.layers.UpSampling2D', ([], {'size': '(2)'}), '(size=2)\n', (10257, 10265), True, 'import tensorflow as tf\n'), ((10789, 10799), 'keras.backend.shape', 'K.shape', (['x'], {}), '(x)\n', (10796, 10799), True, 'from keras import backend as K\n'), ((10804, 10814), 'keras.backend.shape', 'K.shape', (['x'], {}), '(x)\n', (10811, 10814), True, 'from keras import backend as K\n'), ((10819, 10829), 'keras.backend.shape', 'K.shape', (['x'], {}), '(x)\n', (10826, 10829), True, 'from keras import backend as K\n'), ((11010, 11020), 'keras.backend.shape', 'K.shape', (['x'], {}), '(x)\n', (11017, 11020), True, 'from keras import backend as K\n'), ((11025, 11035), 'keras.backend.shape', 'K.shape', (['x'], {}), '(x)\n', (11032, 11035), True, 'from keras import backend as K\n'), ((11040, 11050), 'keras.backend.shape', 'K.shape', (['x'], {}), '(x)\n', (11047, 11050), True, 'from keras import backend as K\n')]
import numpy as np import tensorflow as tf import tensorflow.keras.backend as K from tf_keras_vis import ModelVisualization from tf_keras_vis.utils import check_steps, listify class Saliency(ModelVisualization): def __call__(self, loss, seed_input, smooth_samples=0, smooth_noise=0.20, keepdims=False, gradient_modifier=lambda grads: K.abs(grads), training=False): """Generate an attention map that appears how output value changes with respect to a small change in input image pixels. See details: https://arxiv.org/pdf/1706.03825.pdf # Arguments loss: A loss function. If the model has multiple outputs, you can use a different loss on each output by passing a list of losses. seed_input: An N-dim Numpy array. If the model has multiple inputs, you have to pass a list of N-dim Numpy arrays. smooth_samples: The number of calculating gradients iterations. If set to zero, the noise for smoothing won't be generated. smooth_noise: Noise level that is recommended no tweaking when there is no reason. keepdims: A boolean that whether to keep the channels-dim or not. gradient_modifier: A function to modify gradients. By default, the function modify gradients to `absolute` values. training: A bool whether the model's trainig-mode turn on or off. # Returns The heatmap image indicating the `seed_input` regions whose change would most contribute towards maximizing the loss value, Or a list of their images. A list of Numpy arrays that the model inputs that maximize the out of `loss`. # Raises ValueError: In case of invalid arguments for `loss`, or `seed_input`. """ # Preparing losses = self._get_losses_for_multiple_outputs(loss) seed_inputs = self._get_seed_inputs_for_multiple_inputs(seed_input) # Processing saliency if smooth_samples > 0: smooth_samples = check_steps(smooth_samples) seed_inputs = (tf.tile(X, (smooth_samples, ) + tuple(np.ones(X.ndim - 1, np.int))) for X in seed_inputs) seed_inputs = (tf.reshape(X, (smooth_samples, -1) + tuple(X.shape[1:])) for X in seed_inputs) seed_inputs = ((X, tuple(range(X.ndim)[2:])) for X in seed_inputs) seed_inputs = ((X, smooth_noise * (tf.math.reduce_max(X, axis=axis, keepdims=True) - tf.math.reduce_min(X, axis=axis, keepdims=True))) for X, axis in seed_inputs) seed_inputs = (X + np.random.normal(0., sigma, X.shape) for X, sigma in seed_inputs) seed_inputs = list(seed_inputs) total = (np.zeros_like(X[0]) for X in seed_inputs) for i in range(smooth_samples): grads = self._get_gradients([X[i] for X in seed_inputs], losses, gradient_modifier, training) total = (total + g for total, g in zip(total, grads)) grads = [g / smooth_samples for g in total] else: grads = self._get_gradients(seed_inputs, losses, gradient_modifier, training) # Visualizing if not keepdims: grads = [np.max(g, axis=-1) for g in grads] if len(self.model.inputs) == 1 and not isinstance(seed_input, list): grads = grads[0] return grads def _get_gradients(self, seed_inputs, losses, gradient_modifier, training): with tf.GradientTape(watch_accessed_variables=False, persistent=True) as tape: tape.watch(seed_inputs) outputs = self.model(seed_inputs, training=training) outputs = listify(outputs) loss_values = [loss(output) for output, loss in zip(outputs, losses)] grads = tape.gradient(loss_values, seed_inputs, unconnected_gradients=tf.UnconnectedGradients.ZERO) if gradient_modifier is not None: grads = [gradient_modifier(g) for g in grads] return grads
[ "numpy.random.normal", "tf_keras_vis.utils.check_steps", "numpy.ones", "tf_keras_vis.utils.listify", "numpy.zeros_like", "numpy.max", "tensorflow.GradientTape", "tensorflow.math.reduce_max", "tensorflow.keras.backend.abs", "tensorflow.math.reduce_min" ]
[((443, 455), 'tensorflow.keras.backend.abs', 'K.abs', (['grads'], {}), '(grads)\n', (448, 455), True, 'import tensorflow.keras.backend as K\n'), ((2204, 2231), 'tf_keras_vis.utils.check_steps', 'check_steps', (['smooth_samples'], {}), '(smooth_samples)\n', (2215, 2231), False, 'from tf_keras_vis.utils import check_steps, listify\n'), ((3793, 3857), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {'watch_accessed_variables': '(False)', 'persistent': '(True)'}), '(watch_accessed_variables=False, persistent=True)\n', (3808, 3857), True, 'import tensorflow as tf\n'), ((3990, 4006), 'tf_keras_vis.utils.listify', 'listify', (['outputs'], {}), '(outputs)\n', (3997, 4006), False, 'from tf_keras_vis.utils import check_steps, listify\n'), ((2999, 3018), 'numpy.zeros_like', 'np.zeros_like', (['X[0]'], {}), '(X[0])\n', (3012, 3018), True, 'import numpy as np\n'), ((3537, 3555), 'numpy.max', 'np.max', (['g'], {'axis': '(-1)'}), '(g, axis=-1)\n', (3543, 3555), True, 'import numpy as np\n'), ((2868, 2905), 'numpy.random.normal', 'np.random.normal', (['(0.0)', 'sigma', 'X.shape'], {}), '(0.0, sigma, X.shape)\n', (2884, 2905), True, 'import numpy as np\n'), ((2297, 2324), 'numpy.ones', 'np.ones', (['(X.ndim - 1)', 'np.int'], {}), '(X.ndim - 1, np.int)\n', (2304, 2324), True, 'import numpy as np\n'), ((2635, 2682), 'tensorflow.math.reduce_max', 'tf.math.reduce_max', (['X'], {'axis': 'axis', 'keepdims': '(True)'}), '(X, axis=axis, keepdims=True)\n', (2653, 2682), True, 'import tensorflow as tf\n'), ((2732, 2779), 'tensorflow.math.reduce_min', 'tf.math.reduce_min', (['X'], {'axis': 'axis', 'keepdims': '(True)'}), '(X, axis=axis, keepdims=True)\n', (2750, 2779), True, 'import tensorflow as tf\n')]
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.colors import LinearSegmentedColormap import matplotlib.gridspec as gridspec import matplotlib.patches as patches class ContagionSimulator: def __init__(self): pass def set_params(self, params): """ Set model parameters from dictionary """ self.__dict__.update(params) pass def initialise(self): """ Initialise buffers for simulation """ nagents = self.nagents """ Initialise agents """ # Position self.x = np.random.rand(nagents) self.y = np.random.rand(nagents) # Cache initial positions self.xbak = self.x.copy() self.ybak = self.y.copy() # Direction alpha = 2 * np.pi * np.random.rand(nagents) self.dx = self.dr * np.sin(alpha) self.dy = self.dr * np.cos(alpha) # Agent status self.doesSD = np.floor(np.random.rand(nagents) + self.fractSD).astype(bool) self.isVulnerable = np.ones(nagents, dtype=bool) self.isSick = np.zeros(nagents, dtype=bool) self.isImmune = np.zeros(nagents, dtype=bool) self.agentStatus = np.zeros(nagents, dtype=int) self.tSick = np.zeros(nagents) # Patient zero (literally, because Python starts counting at 0 and not 1 like in MATLAB) iseed = 0 self.isSick[iseed] = True self.doesSD[iseed] = False self.agentStatus[iseed] = 1 """ Initialise events and times """ self.tGoToMarket = np.random.randint(low=1, high=self.dtGoToMarket, size=nagents) self.tAtMarket = np.zeros(nagents) self.isAtMarket = np.zeros(nagents, dtype=bool) self.stayAtMarket = np.zeros(nagents, dtype=bool) """ Initialise health status counts """ nt = self.nt self.nvulnerable = np.zeros(nt) * np.nan self.nsick = np.zeros(nt) * np.nan self.nimmune = np.zeros(nt) * np.nan self.tt = np.arange(nt) / self.tstepsperday pass def run_simulation(self, fig, save_file="contagion.mp4"): # Initialise buffers self.initialise() # Create animation from simulation self.fig = fig self.ani = animation.FuncAnimation( self.fig, self.update_plot, interval=100, init_func=self.init_plot, blit=True, frames=self.nt, repeat=False ) self.ani.save(save_file) plt.show() pass def go_to_market(self, ia): """ Position an agent at a random location inside the market """ self.x[ia] = self.xmarket + np.random.rand() * self.marketsize self.y[ia] = self.ymarket + np.random.rand() * self.marketsize self.tGoToMarket[ia] = -1 self.isAtMarket[ia] = True pass def return_from_market(self, ia): """ Place an agent back from the market to its original position """ self.x[ia] = self.xbak[ia] self.y[ia] = self.ybak[ia] self.tGoToMarket[ia] = self.dtGoToMarket self.tAtMarket[ia] = 0 self.isAtMarket[ia] = False pass def take_step(self, ia): """ Let the agent move around one step """ xnew = self.x[ia] + self.dx[ia] ynew = self.y[ia] + self.dy[ia] # Check for domain boundaries hitWall = (xnew > 1) | (xnew < 0) | (ynew > 1) | (ynew < 0) ntries = 0 stillTrying = True # If the agent is moving outside of the domain while hitWall and stillTrying: # New random direction vector alpha = 2 * np.pi * np.random.rand() self.dx[ia] = self.dr * np.sin(alpha) self.dy[ia] = self.dr * np.cos(alpha) # New location xnew = self.x[ia] + self.dx[ia] ynew = self.y[ia] + self.dy[ia] # If new location is still outside domain: try again hitWall = (xnew > 1) | (xnew < 0) | (ynew > 1) | (ynew < 0) ntries += 1 if ntries > 100: stillTrying = False # Update position self.x[ia] = xnew self.y[ia] = ynew pass def stay_put(self, ia): """ Do nothing """ pass def check_health(self, ia): """ Check the health status of the agent """ if self.isSick[ia]: # Increment sick timer self.tSick[ia] += 1 # If sick timer exceeds time to get better if self.tSick[ia] > self.dtHeal: # Agent is no longer sick self.isSick[ia] = False # AGent is immune self.isImmune[ia] = True self.agentStatus[ia] = 2 def check_contagion(self, ia): """ Let the agent contaminate others """ if self.isSick[ia]: # Compute the distance between the agent and others xdist = self.x[ia] - self.x ydist = self.y[ia] - self.y r = np.sqrt(xdist**2 + ydist**2) # All agents within contagion distance meetAgents = (r <= self.rcont) # Who is at home? isHome = (self.x == self.xbak) & (self.y == self.ybak) # Infect those within contagion distance, # who are not immune, and who are not at home inds = (meetAgents & ~self.isImmune & ~isHome) self.isSick[inds] = True self.agentStatus[inds] = 1 def count_cases(self, it): """ Count the number of sick/immune agents """ self.isVulnerable = (~self.isSick & ~self.isImmune) self.nvulnerable[it] = self.isVulnerable.sum() self.nsick[it] = self.isSick.sum() self.nimmune[it] = self.isImmune.sum() nall = self.nvulnerable[it] + self.nsick[it] + self.nimmune[it] if nall != self.nagents: print("Counts don't add up") self.break_simulation = True pass def simulation_step(self, it): """ Perform one simulation step """ tGoToMarket = self.tGoToMarket isAtMarket = self.isAtMarket tAtMarket = self.tAtMarket stayAtMarket = self.stayAtMarket dtAtMarket = self.dtAtMarket xbak = self.xbak ybak = self.ybak x = self.x y = self.y doesSD = self.doesSD # Loop over all agents for ia in range(self.nagents): # Decrement time to go to the market tGoToMarket[ia] -= 1 # If agent is at the market if isAtMarket[ia]: # Increment time at the market tAtMarket[ia] += 1 # Check if agent will stay at the market stayAtMarket[ia] = (tAtMarket[ia] < dtAtMarket) else: xbak[ia] = x[ia] ybak[ia] = y[ia] # Reset nextMove nextMove = None # If agent doesn't need to go to the market if tGoToMarket[ia] > 0: # If agent doesn't practise social distancing if not doesSD[ia]: # Walk around nextMove = "take_step" # If agent practises social distancing else: # Stay put nextMove = "stay_put" # If agent is at the market if isAtMarket[ia]: # If agent still needs toilet paper if tAtMarket[ia] < dtAtMarket: nextMove = "stay_put" # Else go home elif tAtMarket[ia] == dtAtMarket: nextMove = "return_from_market" # If agent needs toilet paper if tGoToMarket[ia] == 0: nextMove = "go_to_market" # print(f"Next action of agent {ia} at ({x[ia]}, {y[ia]}): {nextMove}") # If the nextMove is not defined (should never happen if nextMove is None: print(it, ia, tGoToMarket[ia], isAtMarket[ia]) exit() # Call the method corresponding to nextMove move = getattr(self, nextMove) move(ia) # Check health status self.check_health(ia) # Contaminate others self.check_contagion(ia) # Count cases self.count_cases(it) pass def init_plot(self): """ Initialise the animation window """ # Initialise buffers self.initialise() # Location of the market ms = self.marketsize xm = self.xmarket ym = self.ymarket rect = patches.Rectangle((xm, ym), ms, ms, linewidth=2, edgecolor="k", facecolor="none") # Health status colours self.colours = ["C0", "r", "C2"] cm = LinearSegmentedColormap.from_list("agent_colours", self.colours, N=3) # Plotting panels gs = gridspec.GridSpec(ncols=1, nrows=3, figure=self.fig) # Panel 1: time series of health status self.ax_plt = self.fig.add_subplot(gs[0]) # Number of sick agents self.nsick_plt, = self.ax_plt.plot(self.tt[0], self.nsick[0], "-", c="r", label="Sick") # Number of immune agents self.nimmune_plt, = self.ax_plt.plot(self.tt[0], self.nimmune[0], "-", c="C2", label="Immune") # Format axes self.ax_plt.set_xlim((0, self.nt / self.tstepsperday)) self.ax_plt.set_ylim((-1, 1.1*self.nagents)) self.ax_plt.legend(ncol=1, loc="upper left") self.ax_plt.set_ylabel("Count") self.ax_plt.set_xlabel("Time [days]") # Panel 2: scatter plot of agents self.ax_sct = self.fig.add_subplot(gs[1:]) # Add supermarket self.ax_sct.add_patch(rect) # Plot agents self.sct = self.ax_sct.scatter(self.x, self.y, c=self.agentStatus, cmap=cm, vmin=0, vmax=2) # Format axes self.ax_sct.set_xlim((0, 1)) self.ax_sct.set_ylim((0, 1)) self.ax_sct.set_xticks([]) self.ax_sct.set_yticks([]) self.fig.tight_layout() self.fig.subplots_adjust(top=0.95, bottom=0.05, left=0.1, right=0.95) return self.nsick_plt, self.nimmune_plt, self.sct, def update_plot(self, it): # Do one simulation step self.simulation_step(it) # Agent coordinates pos = np.c_[self.x, self.y] # Update agent positions self.sct.set_offsets(pos) # Update agent colours self.sct.set_array(self.agentStatus) # Update time series self.nsick_plt.set_data(self.tt[:it], self.nsick[:it]) self.nimmune_plt.set_data(self.tt[:it], self.nimmune[:it]) return self.nsick_plt, self.nimmune_plt, self.sct, if __name__ == "__main__": params = { # Model parameters "nagents": 200, # No. of agents "tstepsperday": 5, # No. of time steps per day (affects display only) "nt": 150, # No. of time steps of simulation "fractSD": .75, # Fraction of people who practice social distancing "dtGoToMarket": 25, # Every <dtGoToMarket> time steps, people go to the market "dtAtMarket": 1, # No. of time steps spent at market "dtHeal": 50, # Time after which peple recover, and become immune "rcont": .04, # Distance below which agents pass on disease "dr": .02, # Step length per time step "marketsize": .1, # Market size "xmarket": .5, # Market location "ymarket": .5, } simulator = ContagionSimulator() simulator.set_params(params) simulator.run_simulation(plt.figure())
[ "matplotlib.patches.Rectangle", "numpy.sqrt", "numpy.ones", "numpy.random.rand", "matplotlib.animation.FuncAnimation", "numpy.zeros", "numpy.random.randint", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.figure", "numpy.cos", "numpy.sin", "matplotlib.colors.LinearSegmentedColormap.from_li...
[((654, 677), 'numpy.random.rand', 'np.random.rand', (['nagents'], {}), '(nagents)\n', (668, 677), True, 'import numpy as np\n'), ((695, 718), 'numpy.random.rand', 'np.random.rand', (['nagents'], {}), '(nagents)\n', (709, 718), True, 'import numpy as np\n'), ((1113, 1141), 'numpy.ones', 'np.ones', (['nagents'], {'dtype': 'bool'}), '(nagents, dtype=bool)\n', (1120, 1141), True, 'import numpy as np\n'), ((1164, 1193), 'numpy.zeros', 'np.zeros', (['nagents'], {'dtype': 'bool'}), '(nagents, dtype=bool)\n', (1172, 1193), True, 'import numpy as np\n'), ((1218, 1247), 'numpy.zeros', 'np.zeros', (['nagents'], {'dtype': 'bool'}), '(nagents, dtype=bool)\n', (1226, 1247), True, 'import numpy as np\n'), ((1275, 1303), 'numpy.zeros', 'np.zeros', (['nagents'], {'dtype': 'int'}), '(nagents, dtype=int)\n', (1283, 1303), True, 'import numpy as np\n'), ((1325, 1342), 'numpy.zeros', 'np.zeros', (['nagents'], {}), '(nagents)\n', (1333, 1342), True, 'import numpy as np\n'), ((1652, 1714), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': 'self.dtGoToMarket', 'size': 'nagents'}), '(low=1, high=self.dtGoToMarket, size=nagents)\n', (1669, 1714), True, 'import numpy as np\n'), ((1740, 1757), 'numpy.zeros', 'np.zeros', (['nagents'], {}), '(nagents)\n', (1748, 1757), True, 'import numpy as np\n'), ((1784, 1813), 'numpy.zeros', 'np.zeros', (['nagents'], {'dtype': 'bool'}), '(nagents, dtype=bool)\n', (1792, 1813), True, 'import numpy as np\n'), ((1842, 1871), 'numpy.zeros', 'np.zeros', (['nagents'], {'dtype': 'bool'}), '(nagents, dtype=bool)\n', (1850, 1871), True, 'import numpy as np\n'), ((2364, 2501), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['self.fig', 'self.update_plot'], {'interval': '(100)', 'init_func': 'self.init_plot', 'blit': '(True)', 'frames': 'self.nt', 'repeat': '(False)'}), '(self.fig, self.update_plot, interval=100, init_func\n =self.init_plot, blit=True, frames=self.nt, repeat=False)\n', (2387, 2501), True, 'import matplotlib.animation as animation\n'), ((2572, 2582), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2580, 2582), True, 'import matplotlib.pyplot as plt\n'), ((8894, 8980), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(xm, ym)', 'ms', 'ms'], {'linewidth': '(2)', 'edgecolor': '"""k"""', 'facecolor': '"""none"""'}), "((xm, ym), ms, ms, linewidth=2, edgecolor='k', facecolor=\n 'none')\n", (8911, 8980), True, 'import matplotlib.patches as patches\n'), ((9063, 9132), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'LinearSegmentedColormap.from_list', (['"""agent_colours"""', 'self.colours'], {'N': '(3)'}), "('agent_colours', self.colours, N=3)\n", (9096, 9132), False, 'from matplotlib.colors import LinearSegmentedColormap\n'), ((9173, 9225), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', ([], {'ncols': '(1)', 'nrows': '(3)', 'figure': 'self.fig'}), '(ncols=1, nrows=3, figure=self.fig)\n', (9190, 9225), True, 'import matplotlib.gridspec as gridspec\n'), ((11965, 11977), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (11975, 11977), True, 'import matplotlib.pyplot as plt\n'), ((869, 892), 'numpy.random.rand', 'np.random.rand', (['nagents'], {}), '(nagents)\n', (883, 892), True, 'import numpy as np\n'), ((921, 934), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (927, 934), True, 'import numpy as np\n'), ((963, 976), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (969, 976), True, 'import numpy as np\n'), ((1985, 1997), 'numpy.zeros', 'np.zeros', (['nt'], {}), '(nt)\n', (1993, 1997), True, 'import numpy as np\n'), ((2028, 2040), 'numpy.zeros', 'np.zeros', (['nt'], {}), '(nt)\n', (2036, 2040), True, 'import numpy as np\n'), ((2073, 2085), 'numpy.zeros', 'np.zeros', (['nt'], {}), '(nt)\n', (2081, 2085), True, 'import numpy as np\n'), ((2113, 2126), 'numpy.arange', 'np.arange', (['nt'], {}), '(nt)\n', (2122, 2126), True, 'import numpy as np\n'), ((5190, 5222), 'numpy.sqrt', 'np.sqrt', (['(xdist ** 2 + ydist ** 2)'], {}), '(xdist ** 2 + ydist ** 2)\n', (5197, 5222), True, 'import numpy as np\n'), ((2754, 2770), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (2768, 2770), True, 'import numpy as np\n'), ((2825, 2841), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (2839, 2841), True, 'import numpy as np\n'), ((3771, 3787), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3785, 3787), True, 'import numpy as np\n'), ((3824, 3837), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (3830, 3837), True, 'import numpy as np\n'), ((3874, 3887), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (3880, 3887), True, 'import numpy as np\n'), ((1032, 1055), 'numpy.random.rand', 'np.random.rand', (['nagents'], {}), '(nagents)\n', (1046, 1055), True, 'import numpy as np\n')]
import numpy as np from sbrfuzzy import * entrada = open("dados.txt","a") v = np.arange(0,300.5,0.5) v1 = variavellinguistica("População",np.arange(0,300.5,0.5)) v1.adicionar("muito-baixa","trapezoidal",[0,0,25,45]) v1.adicionar("baixa","triangular",[30,50,70]) v1.adicionar("media","triangular",[55,75,110]) v1.adicionar("media-alta","triangular",[110,165,185]) v1.adicionar("alta","triangular",[160,190,210]) v1.adicionar("muito-alta","trapezoidal",[200,210,300,300]) v2 = variavellinguistica("Variação",np.arange(-4,10.5,0.5)) v2.adicionar("baixa-negativa","triangular",[-3,0,0]) v2.adicionar("baixa-positiva","triangular",[0,0,3.4]) v2.adicionar("media","triangular",[2,5,8]) v2.adicionar("alta","trapezoidal",[6,9,12,12]) h = 0.5 x = [2,4,8,16] br = ["muito-baixa então media", "baixa então alta", "media então alta", "media-alta então media", "alta então baixa-positiva", "muito-alta então baixa-negativa"] aux=[] retornos=[] it = [i for i in range(250)] for i in x: x0 = i for i in it: f = controlador(br,[v1,v2],[x0]) aux.append( x0 ) x0 = x0 + h*f.mamdani() retornos.append( aux ) aux=[] for i in range( len(retornos[0]) ):entrada.write(str(it[i]) + "\t" + str(retornos[0][i]) + "\t" + str(retornos[1][i]) + "\t" + str(retornos[2][i]) + "\t" + str(retornos[3][i]) + "\n") entrada.close()
[ "numpy.arange" ]
[((79, 103), 'numpy.arange', 'np.arange', (['(0)', '(300.5)', '(0.5)'], {}), '(0, 300.5, 0.5)\n', (88, 103), True, 'import numpy as np\n'), ((142, 166), 'numpy.arange', 'np.arange', (['(0)', '(300.5)', '(0.5)'], {}), '(0, 300.5, 0.5)\n', (151, 166), True, 'import numpy as np\n'), ((511, 535), 'numpy.arange', 'np.arange', (['(-4)', '(10.5)', '(0.5)'], {}), '(-4, 10.5, 0.5)\n', (520, 535), True, 'import numpy as np\n')]
import codecs import os import random import pickle import sys import numpy as np import tensorflow as tf from tqdm import tqdm from transformers import BertTokenizer, TFBertModel from io_utils.io_utils import load_data from data_processing.feature_extraction import calc_features from data_processing.feature_extraction import calc_features_and_labels def main(): random.seed(42) np.random.seed(42) tf.random.set_seed(42) if len(sys.argv) < 2: err_msg = 'The source file is not specified!' raise ValueError(err_msg) src_fname = os.path.normpath(sys.argv[1]) if len(sys.argv) < 3: err_msg = 'The BERT model name is not specified!' raise ValueError(err_msg) bert_path = os.path.normpath(sys.argv[2]) if len(sys.argv) < 4: err_msg = 'The destination file with features is not specified!' raise ValueError(err_msg) dst_fname = os.path.normpath(sys.argv[3]) if len(sys.argv) < 5: err_msg = 'The source data kind is not specified! ' \ 'Possible values: text, annotation.' raise ValueError(err_msg) source_data_kind = sys.argv[4].strip().lower() if source_data_kind not in {'text', 'annotation'}: err_msg = f'{sys.argv[4]} is wrong source data kind!' \ f'Possible values: text, annotation.' raise ValueError(err_msg) if len(sys.argv) < 6: err_msg = 'The maximal sentence length is not specified!' raise ValueError(err_msg) try: max_len = int(sys.argv[5]) except: max_len = 0 if max_len <= 0: err_msg = f'The maximal sentence length = {sys.argv[5]} ' \ f'is inadmissible!' raise ValueError(err_msg) if source_data_kind == 'annotation': if len(sys.argv) < 7: err_msg = 'The named entity vocabulary is not specified!' raise ValueError(err_msg) ne_voc_fname = os.path.normpath(sys.argv[6]) if not os.path.isfile(ne_voc_fname): err_msg = f'The file "{ne_voc_fname}" does not exist!' raise IOError(err_msg) with codecs.open(ne_voc_fname, mode='r', encoding='utf-8') as fp: named_entity_list = list(filter( lambda it2: len(it2) > 0, map(lambda it1: it1.strip(), fp.readlines()) )) if len(named_entity_list) < 1: raise ValueError(f'The file "{ne_voc_fname}" is empty!') else: named_entity_list = [] if not os.path.isfile(src_fname): err_msg = f'The file "{src_fname}" does not exist!' raise IOError(err_msg) if len(dst_fname.strip()) == 0: raise ValueError('The destination file name is empty!') dst_dir = os.path.dirname(dst_fname) if len(dst_dir) > 0: if not os.path.isdir(dst_dir): err_msg = f'The directory "{dst_dir}" does not exist!' raise IOError(err_msg) bert_tokenizer = BertTokenizer.from_pretrained(bert_path) bert_model = TFBertModel.from_pretrained(bert_path) features = [] if source_data_kind == 'annotation': labels = [[] for _ in range(len(named_entity_list))] source_data = load_data(src_fname) for cur_id in tqdm(sorted(list(source_data.keys()))): text, ners = source_data[cur_id] X, y = calc_features_and_labels( bert_tokenizer, bert_model, max_len, named_entity_list, text, ners ) features.append(X) for idx in range(len(named_entity_list)): labels[idx].append(y[idx]) features = np.vstack(features) for idx in range(len(named_entity_list)): labels[idx] = np.vstack(labels[idx]) print('') print(f'X.shape = {features.shape}') for ne_id, ne_cls in enumerate(named_entity_list): print(f'y[{ne_cls}].shape = {labels[ne_id].shape}') with open(dst_fname, 'wb') as fp: pickle.dump( obj=(features, labels), file=fp, protocol=pickle.HIGHEST_PROTOCOL ) else: with codecs.open(src_fname, mode='r', encoding='utf-8', errors='ignore') as fp: cur_line = fp.readline() while len(cur_line) > 0: prep_line = cur_line.strip() if len(prep_line) > 0: X = calc_features( bert_tokenizer, bert_model, max_len, prep_line ) features.append(X) cur_line = fp.readline() features = np.vstack(features) print('') print(f'X.shape = {features.shape}') with open(dst_fname, 'wb') as fp: pickle.dump( obj=features, file=fp, protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == '__main__': main()
[ "pickle.dump", "tensorflow.random.set_seed", "transformers.TFBertModel.from_pretrained", "io_utils.io_utils.load_data", "data_processing.feature_extraction.calc_features", "transformers.BertTokenizer.from_pretrained", "random.seed", "os.path.normpath", "os.path.dirname", "os.path.isfile", "os.pa...
[((373, 388), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (384, 388), False, 'import random\n'), ((393, 411), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (407, 411), True, 'import numpy as np\n'), ((416, 438), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(42)'], {}), '(42)\n', (434, 438), True, 'import tensorflow as tf\n'), ((570, 599), 'os.path.normpath', 'os.path.normpath', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (586, 599), False, 'import os\n'), ((734, 763), 'os.path.normpath', 'os.path.normpath', (['sys.argv[2]'], {}), '(sys.argv[2])\n', (750, 763), False, 'import os\n'), ((913, 942), 'os.path.normpath', 'os.path.normpath', (['sys.argv[3]'], {}), '(sys.argv[3])\n', (929, 942), False, 'import os\n'), ((2752, 2778), 'os.path.dirname', 'os.path.dirname', (['dst_fname'], {}), '(dst_fname)\n', (2767, 2778), False, 'import os\n'), ((2967, 3007), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['bert_path'], {}), '(bert_path)\n', (2996, 3007), False, 'from transformers import BertTokenizer, TFBertModel\n'), ((3025, 3063), 'transformers.TFBertModel.from_pretrained', 'TFBertModel.from_pretrained', (['bert_path'], {}), '(bert_path)\n', (3052, 3063), False, 'from transformers import BertTokenizer, TFBertModel\n'), ((1945, 1974), 'os.path.normpath', 'os.path.normpath', (['sys.argv[6]'], {}), '(sys.argv[6])\n', (1961, 1974), False, 'import os\n'), ((2520, 2545), 'os.path.isfile', 'os.path.isfile', (['src_fname'], {}), '(src_fname)\n', (2534, 2545), False, 'import os\n'), ((3207, 3227), 'io_utils.io_utils.load_data', 'load_data', (['src_fname'], {}), '(src_fname)\n', (3216, 3227), False, 'from io_utils.io_utils import load_data\n'), ((3688, 3707), 'numpy.vstack', 'np.vstack', (['features'], {}), '(features)\n', (3697, 3707), True, 'import numpy as np\n'), ((4772, 4791), 'numpy.vstack', 'np.vstack', (['features'], {}), '(features)\n', (4781, 4791), True, 'import numpy as np\n'), ((1990, 2018), 'os.path.isfile', 'os.path.isfile', (['ne_voc_fname'], {}), '(ne_voc_fname)\n', (2004, 2018), False, 'import os\n'), ((2135, 2188), 'codecs.open', 'codecs.open', (['ne_voc_fname'], {'mode': '"""r"""', 'encoding': '"""utf-8"""'}), "(ne_voc_fname, mode='r', encoding='utf-8')\n", (2146, 2188), False, 'import codecs\n'), ((2819, 2841), 'os.path.isdir', 'os.path.isdir', (['dst_dir'], {}), '(dst_dir)\n', (2832, 2841), False, 'import os\n'), ((3354, 3450), 'data_processing.feature_extraction.calc_features_and_labels', 'calc_features_and_labels', (['bert_tokenizer', 'bert_model', 'max_len', 'named_entity_list', 'text', 'ners'], {}), '(bert_tokenizer, bert_model, max_len,\n named_entity_list, text, ners)\n', (3378, 3450), False, 'from data_processing.feature_extraction import calc_features_and_labels\n'), ((3784, 3806), 'numpy.vstack', 'np.vstack', (['labels[idx]'], {}), '(labels[idx])\n', (3793, 3806), True, 'import numpy as np\n'), ((4047, 4125), 'pickle.dump', 'pickle.dump', ([], {'obj': '(features, labels)', 'file': 'fp', 'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(obj=(features, labels), file=fp, protocol=pickle.HIGHEST_PROTOCOL)\n', (4058, 4125), False, 'import pickle\n'), ((4211, 4278), 'codecs.open', 'codecs.open', (['src_fname'], {'mode': '"""r"""', 'encoding': '"""utf-8"""', 'errors': '"""ignore"""'}), "(src_fname, mode='r', encoding='utf-8', errors='ignore')\n", (4222, 4278), False, 'import codecs\n'), ((4909, 4977), 'pickle.dump', 'pickle.dump', ([], {'obj': 'features', 'file': 'fp', 'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(obj=features, file=fp, protocol=pickle.HIGHEST_PROTOCOL)\n', (4920, 4977), False, 'import pickle\n'), ((4493, 4554), 'data_processing.feature_extraction.calc_features', 'calc_features', (['bert_tokenizer', 'bert_model', 'max_len', 'prep_line'], {}), '(bert_tokenizer, bert_model, max_len, prep_line)\n', (4506, 4554), False, 'from data_processing.feature_extraction import calc_features\n')]
import re import sys import numpy as np import pkg_resources import math from PyQt5 import uic, QtGui, QtCore from matplotlib.figure import Figure from isstools.widgets import (widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status) from isstools.elements import EmittingStream #Libs for ZeroMQ communication import socket from PyQt5.QtCore import QThread import zmq import pickle import pandas as pd from isstools.process_callbacks.callback import ProcessingCallback ui_path = pkg_resources.resource_filename('isstools', 'ui/XLive.ui') def auto_redraw_factory(fnc): def stale_callback(fig, stale): if fnc is not None: fnc(fig, stale) if stale and fig.canvas: fig.canvas.draw_idle() return stale_callback class XliveGui(*uic.loadUiType(ui_path)): progress_sig = QtCore.pyqtSignal() def __init__(self, plan_funcs=[], prep_traj_plan=None, diff_plans=[], RE=None, db=None, accelerator=None, mono=None, sdd = None, shutters_dict={}, det_dict={}, motors_dict={}, aux_plan_funcs={}, general_scan_func = None, sample_stages= None, window_title="XLive @QAS/07-BM NSLS-II", job_submitter=None, *args, **kwargs): ''' Parameters ---------- plan_funcs : list, optional functions that run plans (call RE(plan()) etc) prep_traj_plan : generator or None, optional a plan that prepares the trajectories RE : bluesky.RunEngine, optional a RunEngine instance db : databroker.Broker, optional the database to save acquired data to accelerator : mono : ophyd.Device, optional the monochromator. and has been kept from the legacy ISS code shutters_dict : dict, optional dictionary of available shutters det_dict : dict, optional dictionary of detectors motors_dict : dict, optional dictionary of motors general_scan_func : generator or None, optional receiving address: string, optinal the address for where to subscribe the Kafka Consumer to ''' self.window_title = window_title if 'write_html_log' in kwargs: self.html_log_func = kwargs['write_html_log'] del kwargs['write_html_log'] else: self.html_log_func = None if 'ic_amplifiers' in kwargs: self.ic_amplifiers = kwargs['ic_amplifiers'] del kwargs['ic_amplifiers'] else: self.ic_amplifiers = None if 'auto_tune_elements' in kwargs: self.auto_tune_dict = kwargs['auto_tune_elements'] del kwargs['auto_tune_elements'] else: self.auto_tune_dict = None if 'prepare_bl' in kwargs: self.prepare_bl_list = kwargs['prepare_bl'] self.prepare_bl_plan = kwargs['prepare_bl'][0] del kwargs['prepare_bl'] else: self.prepare_bl_list = [] self.prepare_bl_plan = None if 'set_gains_offsets' in kwargs: self.set_gains_offsets_scan = kwargs['set_gains_offsets'] del kwargs['set_gains_offsets'] else: self.set_gains_offsets_scan = None if 'sample_stages' in kwargs: self.sample_stages = kwargs['sample_stages'] del kwargs['sample_stages'] else: self.sample_stages = [] if 'processing_sender' in kwargs: self.sender = kwargs['processing_sender'] del kwargs['processing_sender'] else: self.sender = None super().__init__(*args, **kwargs) self.setupUi(self) self.det_dict = det_dict self.plan_funcs = plan_funcs self.plan_funcs_names = [plan.__name__ for plan in plan_funcs] self.prep_traj_plan = prep_traj_plan self.motors_dict = motors_dict self.shutters_dict = shutters_dict self.diff_plans = diff_plans self.RE = RE self.db = db if self.RE is not None: self.RE.is_aborted = False self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update_re_state) self.timer.start(1000) else: self.tabWidget.removeTab( [self.tabWidget.tabText(index) for index in range(self.tabWidget.count())].index('Run')) self.tabWidget.removeTab( [self.tabWidget.tabText(index) for index in range(self.tabWidget.count())].index('Run Batch')) self.push_re_abort.setEnabled(False) self.run_check_gains.setEnabled(False) self.mono = mono if self.mono is None: self.tabWidget.removeTab([self.tabWidget.tabText(index) for index in range(self.tabWidget.count())].index('Trajectory setup')) self.tabWidget.removeTab([self.tabWidget.tabText(index) for index in range(self.tabWidget.count())].index('Run')) self.tabWidget.removeTab([self.tabWidget.tabText(index) for index in range(self.tabWidget.count())].index('Run Batch')) else: self.mono.trajectory_progress.subscribe(self.update_progress) self.progress_sig.connect(self.update_progressbar) self.progressBar.setValue(0) # Activating ZeroMQ Receiving Socket self.run_mode = 'run' # Looking for analog pizzaboxes: regex = re.compile('pba\d{1}.*') matches = [det for det in self.det_dict if re.match(regex, det)] self.adc_list = [self.det_dict[x]['obj'] for x in self.det_dict if x in matches] # Looking for encoder pizzaboxes: regex = re.compile('pb\d{1}_enc.*') matches = [det for det in self.det_dict if re.match(regex, det)] self.enc_list = [self.det_dict[x]['obj'] for x in self.det_dict if x in matches] # Looking for xias: regex = re.compile('xia\d{1}') matches = [det for det in self.det_dict if re.match(regex, det)] self.xia_list = [self.det_dict[x]['obj'] for x in self.det_dict if x in matches] if len(self.xia_list): self.xia = self.xia_list[0] self.widget_sdd_manager = widget_sdd_manager.UISDDManager(self.xia_list) self.layout_sdd_manager.addWidget(self.widget_sdd_manager) else: self.tabWidget.removeTab([self.tabWidget.tabText(index) for index in range(self.tabWidget.count())].index('Silicon Drift Detector setup')) self.xia = None self.widget_general_info = widget_general_info.UIGeneralInfo(accelerator, RE, db) self.layout_general_info.addWidget(self.widget_general_info) if self.mono is not None: self.widget_trajectory_manager = widget_trajectory_manager.UITrajectoryManager(mono, self.run_prep_traj) self.layout_trajectory_manager.addWidget(self.widget_trajectory_manager) self.widget_processing = widget_processing.UIProcessing(mono, db, parent_gui = self ) self.layout_processing.addWidget(self.widget_processing) if self.RE is not None: self.widget_run = widget_run.UIRun(self.plan_funcs, db, shutters_dict, self.adc_list, self.enc_list, self.xia, self.html_log_func, self) self.layout_run.addWidget(self.widget_run) if self.mono is not None: self.widget_batch_mode = widget_batch_mode.UIBatchMode(self.plan_funcs, self.motors_dict, mono, RE, db, self.adc_list, self.enc_list, self.xia, self.run_prep_traj, self.widget_run.create_log_scan, sample_stages=sample_stages, parent_gui = self, job_submitter=job_submitter) self.layout_batch.addWidget(self.widget_batch_mode) self.widget_trajectory_manager.trajectoriesChanged.connect(self.widget_batch_mode.update_batch_traj) self.widget_beamline_setup = widget_beamline_setup.UIBeamlineSetup(RE, self.mono, db, self.adc_list, self.enc_list, self.det_dict, self.xia, self.ic_amplifiers, self.prepare_bl_plan, self.plan_funcs, self.prepare_bl_list, self.set_gains_offsets_scan, aux_plan_funcs, self.motors_dict, general_scan_func, self.widget_run.create_log_scan, self.auto_tune_dict, shutters_dict, self) self.layout_beamline_setup.addWidget(self.widget_beamline_setup) self.widget_run_diff = widget_run_diff.UIRunDiff(RE, db, self.diff_plans, parent_gui = self) self.layout_run_diff.addWidget(self.widget_run_diff) self.widget_sdd_manager = widget_sdd_manager.UISDDManager(self.plan_funcs, sdd, RE) self.layout_xspress3_setup.addWidget(self.widget_sdd_manager) self.layout_beamline_status.addWidget(widget_beamline_status.UIBeamlineStatus(self.shutters_dict)) self.filepaths = [] pc = ProcessingCallback(db=self.db, draw_func_interp=self.widget_run.draw_interpolated_data, draw_func_binned=self.widget_processing.new_bin_df_arrived) self.token = self.RE.subscribe(pc, 'stop') self.push_re_abort.clicked.connect(self.re_abort) # Redirect terminal output to GUI self.emitstream_out = EmittingStream.EmittingStream(self.textEdit_terminal) self.emitstream_err = EmittingStream.EmittingStream(self.textEdit_terminal) sys.stdout = self.emitstream_out sys.stderr = self.emitstream_err self.setWindowTitle(window_title) def update_progress(self, pvname=None, value=None, char_value=None, **kwargs): self.progress_sig.emit() self.progressValue = value def update_progressbar(self): value = np.round(self.progressValue) if not math.isnan(value): self.progressBar.setValue(int(value)) def __del__(self): # Restore sys.stdout sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ def run_prep_traj(self): self.RE(self.prep_traj_plan()) def plans_diff(self): self.RE(self.plans_diff()) def re_abort(self): if self.RE.state != 'idle': self.RE.abort() self.RE.is_aborted = True def update_re_state(self): palette = self.label_11.palette() if (self.RE.state == 'idle'): palette.setColor(self.label_11.foregroundRole(), QtGui.QColor(193, 140, 15)) elif (self.RE.state == 'running'): palette.setColor(self.label_11.foregroundRole(), QtGui.QColor(0, 165, 0)) elif (self.RE.state == 'paused'): palette.setColor(self.label_11.foregroundRole(), QtGui.QColor(255, 0, 0)) elif (self.RE.state == 'abort'): palette.setColor(self.label_11.foregroundRole(), QtGui.QColor(255, 0, 0)) self.label_11.setPalette(palette) self.label_11.setText(self.RE.state) # class ReceivingThread(QThread): # received_interp_data = QtCore.pyqtSignal(object) # received_bin_data = QtCore.pyqtSignal(object) # received_req_interp_data = QtCore.pyqtSignal(object) # def __init__(self, gui): # QThread.__init__(self) # self.setParent(gui) # # def run(self): # consumer = self.parent().consumer # for message in consumer: # # bruno concatenates and extra message at beginning of this packet # # we need to take it off # message = message.value[len(self.parent().hostname_filter):] # data = pickle.loads(message) # # if 'data' in data['processing_ret']: # #data['processing_ret']['data'] = pd.read_msgpack(data['processing_ret']['data']) # data['processing_ret']['data'] = data['processing_ret']['data'].decode() # # if data['type'] == 'spectroscopy': # if data['processing_ret']['type'] == 'interpolate': # self.received_interp_data.emit(data) # if data['processing_ret']['type'] == 'bin': # self.received_bin_data.emit(data) # if data['processing_ret']['type'] == 'request_interpolated_data': # self.received_req_interp_data.emit(data)
[ "re.compile", "PyQt5.QtGui.QColor", "PyQt5.uic.loadUiType", "isstools.widgets.widget_batch_mode.UIBatchMode", "isstools.widgets.widget_general_info.UIGeneralInfo", "isstools.elements.EmittingStream.EmittingStream", "isstools.widgets.widget_beamline_setup.UIBeamlineSetup", "numpy.round", "PyQt5.QtCor...
[((639, 697), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['"""isstools"""', '"""ui/XLive.ui"""'], {}), "('isstools', 'ui/XLive.ui')\n", (670, 697), False, 'import pkg_resources\n'), ((934, 957), 'PyQt5.uic.loadUiType', 'uic.loadUiType', (['ui_path'], {}), '(ui_path)\n', (948, 957), False, 'from PyQt5 import uic, QtGui, QtCore\n'), ((979, 998), 'PyQt5.QtCore.pyqtSignal', 'QtCore.pyqtSignal', ([], {}), '()\n', (996, 998), False, 'from PyQt5 import uic, QtGui, QtCore\n'), ((6103, 6128), 're.compile', 're.compile', (['"""pba\\\\d{1}.*"""'], {}), "('pba\\\\d{1}.*')\n", (6113, 6128), False, 'import re\n'), ((6349, 6377), 're.compile', 're.compile', (['"""pb\\\\d{1}_enc.*"""'], {}), "('pb\\\\d{1}_enc.*')\n", (6359, 6377), False, 'import re\n'), ((6584, 6607), 're.compile', 're.compile', (['"""xia\\\\d{1}"""'], {}), "('xia\\\\d{1}')\n", (6594, 6607), False, 'import re\n'), ((7263, 7317), 'isstools.widgets.widget_general_info.UIGeneralInfo', 'widget_general_info.UIGeneralInfo', (['accelerator', 'RE', 'db'], {}), '(accelerator, RE, db)\n', (7296, 7317), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((7658, 7715), 'isstools.widgets.widget_processing.UIProcessing', 'widget_processing.UIProcessing', (['mono', 'db'], {'parent_gui': 'self'}), '(mono, db, parent_gui=self)\n', (7688, 7715), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((11502, 11659), 'isstools.process_callbacks.callback.ProcessingCallback', 'ProcessingCallback', ([], {'db': 'self.db', 'draw_func_interp': 'self.widget_run.draw_interpolated_data', 'draw_func_binned': 'self.widget_processing.new_bin_df_arrived'}), '(db=self.db, draw_func_interp=self.widget_run.\n draw_interpolated_data, draw_func_binned=self.widget_processing.\n new_bin_df_arrived)\n', (11520, 11659), False, 'from isstools.process_callbacks.callback import ProcessingCallback\n'), ((11836, 11889), 'isstools.elements.EmittingStream.EmittingStream', 'EmittingStream.EmittingStream', (['self.textEdit_terminal'], {}), '(self.textEdit_terminal)\n', (11865, 11889), False, 'from isstools.elements import EmittingStream\n'), ((11920, 11973), 'isstools.elements.EmittingStream.EmittingStream', 'EmittingStream.EmittingStream', (['self.textEdit_terminal'], {}), '(self.textEdit_terminal)\n', (11949, 11973), False, 'from isstools.elements import EmittingStream\n'), ((12302, 12330), 'numpy.round', 'np.round', (['self.progressValue'], {}), '(self.progressValue)\n', (12310, 12330), True, 'import numpy as np\n'), ((4688, 4703), 'PyQt5.QtCore.QTimer', 'QtCore.QTimer', ([], {}), '()\n', (4701, 4703), False, 'from PyQt5 import uic, QtGui, QtCore\n'), ((6878, 6924), 'isstools.widgets.widget_sdd_manager.UISDDManager', 'widget_sdd_manager.UISDDManager', (['self.xia_list'], {}), '(self.xia_list)\n', (6909, 6924), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((7467, 7538), 'isstools.widgets.widget_trajectory_manager.UITrajectoryManager', 'widget_trajectory_manager.UITrajectoryManager', (['mono', 'self.run_prep_traj'], {}), '(mono, self.run_prep_traj)\n', (7512, 7538), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((8039, 8162), 'isstools.widgets.widget_run.UIRun', 'widget_run.UIRun', (['self.plan_funcs', 'db', 'shutters_dict', 'self.adc_list', 'self.enc_list', 'self.xia', 'self.html_log_func', 'self'], {}), '(self.plan_funcs, db, shutters_dict, self.adc_list, self.\n enc_list, self.xia, self.html_log_func, self)\n', (8055, 8162), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((9604, 9975), 'isstools.widgets.widget_beamline_setup.UIBeamlineSetup', 'widget_beamline_setup.UIBeamlineSetup', (['RE', 'self.mono', 'db', 'self.adc_list', 'self.enc_list', 'self.det_dict', 'self.xia', 'self.ic_amplifiers', 'self.prepare_bl_plan', 'self.plan_funcs', 'self.prepare_bl_list', 'self.set_gains_offsets_scan', 'aux_plan_funcs', 'self.motors_dict', 'general_scan_func', 'self.widget_run.create_log_scan', 'self.auto_tune_dict', 'shutters_dict', 'self'], {}), '(RE, self.mono, db, self.adc_list,\n self.enc_list, self.det_dict, self.xia, self.ic_amplifiers, self.\n prepare_bl_plan, self.plan_funcs, self.prepare_bl_list, self.\n set_gains_offsets_scan, aux_plan_funcs, self.motors_dict,\n general_scan_func, self.widget_run.create_log_scan, self.auto_tune_dict,\n shutters_dict, self)\n', (9641, 9975), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((10858, 10925), 'isstools.widgets.widget_run_diff.UIRunDiff', 'widget_run_diff.UIRunDiff', (['RE', 'db', 'self.diff_plans'], {'parent_gui': 'self'}), '(RE, db, self.diff_plans, parent_gui=self)\n', (10883, 10925), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((11216, 11273), 'isstools.widgets.widget_sdd_manager.UISDDManager', 'widget_sdd_manager.UISDDManager', (['self.plan_funcs', 'sdd', 'RE'], {}), '(self.plan_funcs, sdd, RE)\n', (11247, 11273), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((11399, 11458), 'isstools.widgets.widget_beamline_status.UIBeamlineStatus', 'widget_beamline_status.UIBeamlineStatus', (['self.shutters_dict'], {}), '(self.shutters_dict)\n', (11438, 11458), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((12346, 12363), 'math.isnan', 'math.isnan', (['value'], {}), '(value)\n', (12356, 12363), False, 'import math\n'), ((6179, 6199), 're.match', 're.match', (['regex', 'det'], {}), '(regex, det)\n', (6187, 6199), False, 'import re\n'), ((6428, 6448), 're.match', 're.match', (['regex', 'det'], {}), '(regex, det)\n', (6436, 6448), False, 'import re\n'), ((6658, 6678), 're.match', 're.match', (['regex', 'det'], {}), '(regex, det)\n', (6666, 6678), False, 'import re\n'), ((8629, 8889), 'isstools.widgets.widget_batch_mode.UIBatchMode', 'widget_batch_mode.UIBatchMode', (['self.plan_funcs', 'self.motors_dict', 'mono', 'RE', 'db', 'self.adc_list', 'self.enc_list', 'self.xia', 'self.run_prep_traj', 'self.widget_run.create_log_scan'], {'sample_stages': 'sample_stages', 'parent_gui': 'self', 'job_submitter': 'job_submitter'}), '(self.plan_funcs, self.motors_dict, mono, RE,\n db, self.adc_list, self.enc_list, self.xia, self.run_prep_traj, self.\n widget_run.create_log_scan, sample_stages=sample_stages, parent_gui=\n self, job_submitter=job_submitter)\n', (8658, 8889), False, 'from isstools.widgets import widget_general_info, widget_trajectory_manager, widget_processing, widget_batch_mode, widget_run, widget_beamline_setup, widget_run_diff, widget_sdd_manager, widget_beamline_status\n'), ((12971, 12997), 'PyQt5.QtGui.QColor', 'QtGui.QColor', (['(193)', '(140)', '(15)'], {}), '(193, 140, 15)\n', (12983, 12997), False, 'from PyQt5 import uic, QtGui, QtCore\n'), ((13103, 13126), 'PyQt5.QtGui.QColor', 'QtGui.QColor', (['(0)', '(165)', '(0)'], {}), '(0, 165, 0)\n', (13115, 13126), False, 'from PyQt5 import uic, QtGui, QtCore\n'), ((13231, 13254), 'PyQt5.QtGui.QColor', 'QtGui.QColor', (['(255)', '(0)', '(0)'], {}), '(255, 0, 0)\n', (13243, 13254), False, 'from PyQt5 import uic, QtGui, QtCore\n'), ((13358, 13381), 'PyQt5.QtGui.QColor', 'QtGui.QColor', (['(255)', '(0)', '(0)'], {}), '(255, 0, 0)\n', (13370, 13381), False, 'from PyQt5 import uic, QtGui, QtCore\n')]
#!/usr/bin/env python # coding: utf-8 import pandas as pd from sklearn.base import BaseEstimator import torch from torch import nn from torch import optim import numpy as np torch.autograd.set_detect_anomaly(True) class TorchCox(BaseEstimator): """Fit a Cox model """ def __init__(self, lr=1, random_state=None): self.random_state = random_state self.lr = lr def _padToMatch2d(self, inputtens, targetshape): target = torch.full(targetshape, fill_value=-1e3)#torch.zeros(*targetshape) target[:inputtens.shape[0], :inputtens.shape[1]] = inputtens return target def get_loss(self, tensor, event_tens, num_tied, beta): loss_event = torch.einsum('ik,k->i', event_tens, beta) XB = torch.einsum('ijk,k->ij', tensor, beta) loss_atrisk = -num_tied*torch.logsumexp(XB, dim=1) loss = torch.sum(loss_event + loss_atrisk) return -loss # the arguments are ignored anyway, so we make them optional def fit(self, df, Xnames=None, tname=None, dname=None, basehaz=True): self.Xnames = Xnames self.tname = tname self.dname = dname #self.random_state_ = check_random_state(self.random_state) beta = nn.Parameter(torch.zeros(len(self.Xnames))).float() optimizer = optim.LBFGS([beta], lr=self.lr) inputdf = df[[self.tname,self.dname,*self.Xnames]].sort_values([self.dname,self.tname], ascending=[False,True]) tiecountdf = inputdf.loc[inputdf[self.dname]==1,:].groupby([self.tname]).size().reset_index(name='tiecount') num_tied = torch.from_numpy(tiecountdf.tiecount.values).int() tensin = torch.from_numpy(inputdf[[self.tname,self.dname,*self.Xnames]].values) #Get unique event times tensin_events = torch.unique(tensin[tensin[:,1]==1, 0]) #For each unique event stack another matrix with event at the top, and all at risk entries below tensor = torch.stack([self._padToMatch2d(tensin[tensin[:,0] >= eventtime, :], tensin.shape) for eventtime in tensin_events]) assert all(tensor[:,0,1] == 1) #One actually has to sum over the covariates which have a tied event time in the Breslow correction method! #See page 33 here: https://www.math.ucsd.edu/~rxu/math284/slect5.pdf event_tens = torch.stack([tensor[i, :num_tied[i], 2:].sum(dim=0) for i in range(tensor.shape[0])]) #Drop time and status columns as no longer required tensor = tensor[:,:,2:] def closure(): optimizer.zero_grad() loss = self.get_loss(tensor, event_tens, num_tied, beta) #print(loss) loss.backward() return loss optimizer.step(closure) self.beta = beta print(self.beta.detach().numpy()) #Compute baseline hazard during fit() to avoid having to save dataset to memory in TorchCox() objects, so it # can then later be calculated if basehaz() is called. if basehaz: t, _ = torch.sort(torch.from_numpy(inputdf[self.tname].values)) t_uniq = torch.unique(t) h0 = [] for time in t_uniq: value = 1/torch.sum(torch.exp(torch.einsum('ij,j->i', torch.from_numpy(inputdf.loc[inputdf[self.tname] >= time.numpy(), self.Xnames].values).float(), self.beta))) h0.append({'time':time.numpy(), 'h0':value.detach().numpy()}) h0df = pd.DataFrame(h0) h0df['H0'] = h0df.h0.cumsum() self.basehaz = h0df def predict_proba(self, testdf, Xnames=None, tname=None): betas = self.beta.detach().numpy() H0 = np.asarray([self.basehaz.loc[self.basehaz.time<=t, 'H0'].iloc[-1] for t in testdf[tname].values]) S = np.exp(np.multiply(-np.exp(np.dot(testdf[Xnames].values, betas)), H0)) assert all(S>=0) assert all(S<=1) #F = 1 - S #assert all(F>=0) #assert all(F<=1) return S
[ "torch.autograd.set_detect_anomaly", "torch.unique", "torch.full", "numpy.asarray", "torch.from_numpy", "numpy.dot", "torch.sum", "torch.einsum", "torch.optim.LBFGS", "pandas.DataFrame", "torch.logsumexp" ]
[((176, 215), 'torch.autograd.set_detect_anomaly', 'torch.autograd.set_detect_anomaly', (['(True)'], {}), '(True)\n', (209, 215), False, 'import torch\n'), ((471, 514), 'torch.full', 'torch.full', (['targetshape'], {'fill_value': '(-1000.0)'}), '(targetshape, fill_value=-1000.0)\n', (481, 514), False, 'import torch\n'), ((719, 760), 'torch.einsum', 'torch.einsum', (['"""ik,k->i"""', 'event_tens', 'beta'], {}), "('ik,k->i', event_tens, beta)\n", (731, 760), False, 'import torch\n'), ((799, 838), 'torch.einsum', 'torch.einsum', (['"""ijk,k->ij"""', 'tensor', 'beta'], {}), "('ijk,k->ij', tensor, beta)\n", (811, 838), False, 'import torch\n'), ((922, 957), 'torch.sum', 'torch.sum', (['(loss_event + loss_atrisk)'], {}), '(loss_event + loss_atrisk)\n', (931, 957), False, 'import torch\n'), ((1381, 1412), 'torch.optim.LBFGS', 'optim.LBFGS', (['[beta]'], {'lr': 'self.lr'}), '([beta], lr=self.lr)\n', (1392, 1412), False, 'from torch import optim\n'), ((1740, 1812), 'torch.from_numpy', 'torch.from_numpy', (['inputdf[[self.tname, self.dname, *self.Xnames]].values'], {}), '(inputdf[[self.tname, self.dname, *self.Xnames]].values)\n', (1756, 1812), False, 'import torch\n'), ((1868, 1910), 'torch.unique', 'torch.unique', (['tensin[tensin[:, 1] == 1, 0]'], {}), '(tensin[tensin[:, 1] == 1, 0])\n', (1880, 1910), False, 'import torch\n'), ((3785, 3888), 'numpy.asarray', 'np.asarray', (["[self.basehaz.loc[self.basehaz.time <= t, 'H0'].iloc[-1] for t in testdf[\n tname].values]"], {}), "([self.basehaz.loc[self.basehaz.time <= t, 'H0'].iloc[-1] for t in\n testdf[tname].values])\n", (3795, 3888), True, 'import numpy as np\n'), ((871, 897), 'torch.logsumexp', 'torch.logsumexp', (['XB'], {'dim': '(1)'}), '(XB, dim=1)\n', (886, 897), False, 'import torch\n'), ((3210, 3225), 'torch.unique', 'torch.unique', (['t'], {}), '(t)\n', (3222, 3225), False, 'import torch\n'), ((3556, 3572), 'pandas.DataFrame', 'pd.DataFrame', (['h0'], {}), '(h0)\n', (3568, 3572), True, 'import pandas as pd\n'), ((1671, 1715), 'torch.from_numpy', 'torch.from_numpy', (['tiecountdf.tiecount.values'], {}), '(tiecountdf.tiecount.values)\n', (1687, 1715), False, 'import torch\n'), ((3143, 3187), 'torch.from_numpy', 'torch.from_numpy', (['inputdf[self.tname].values'], {}), '(inputdf[self.tname].values)\n', (3159, 3187), False, 'import torch\n'), ((3923, 3959), 'numpy.dot', 'np.dot', (['testdf[Xnames].values', 'betas'], {}), '(testdf[Xnames].values, betas)\n', (3929, 3959), True, 'import numpy as np\n')]
from __future__ import absolute_import import os,sys import numpy as np from Bio.PDB.Polypeptide import is_aa from computeFeatures.structStep.myPDBParser import myPDBParser as PDBParser from ..StructFeatComputer import StructFeatComputer from utils import myMakeDir, tryToRemove #utils is at the root of the package class DistMapComputer(StructFeatComputer): ''' Extends StructFeatComputer class. Computes pairwise distance between all amino acids of receptor and ligand independently ''' def __init__(self, rFname, lFname, computedFeatsRootDir=None, statusManager=None): ''' @param rFname: str. path to receptor pdb file @param lFname: str. path to ligand pdb file @param computedFeatsRootDir: str. path where features will be stored @param statusManager: class that implements .setStatus(msg) to communicate ''' StructFeatComputer.__init__(self, rFname, lFname, computedFeatsRootDir, statusManager=statusManager) self.outPath= myMakeDir(self.computedFeatsRootDir, "distanceMatricesData") self.parser= PDBParser(QUIET=True) def computeOneFile(self, fileName): ''' Computes distance for each pair of aminoacids for a given pdb file @param fileName: str. fname to pdb file ''' prefixAndChainTypeId = (fileName.split("/")[-1]).split(".pdb")[0] outName= os.path.join(self.outPath,prefixAndChainTypeId+".distMat") if os.path.isfile(outName): print("Already computed Distance Maps") return 0 structure= self.parser.get_structure(prefixAndChainTypeId, fileName) structCenterMass= self.getStructCenterMass(structure) try: outFile= open(outName,"w") outFile.write("chainId1 structResId1 chainId2 structResId2 distance angle_to_protCM\n") for res1 in structure[0].get_residues(): if is_aa(res1,standard=True): ## print res, res.get_full_id() structId1,modelId1,chainId1, resId1= res1.get_full_id() resId1= list(resId1) resId1[1]=str(resId1[1]) resId1= "".join(resId1[1:]) if chainId1==" ": chainId1="*" for res2 in structure[0].get_residues(): if is_aa(res2,standard=True): ## print( res, res.get_full_id()) structId2,modelId2,chainId2, resId2= res2.get_full_id() resId2= list(resId2) resId2[1]=str(resId2[1]) resId2= "".join(resId2[1:]) if chainId2==" ": chainId2="*" magnitude= self.getMagnitude(res1, res2, structCenterMass) # print( chainId1, resId1, chainId2, resId2, magnitude) # a= raw_input() outFile.write(chainId1+" "+resId1+" "+chainId2+" "+resId2+" "+" ".join([str(val) for val in magnitude])+"\n") outFile.close() except (KeyboardInterrupt, Exception): print("Exception happend computing %s"%outName) tryToRemove(outName) raise return 0 def getStructCenterMass(self, struct): ''' Computes center of mass for a given structure @param pdbStruct: Bio.PDB.Structure. Structure of the pdb that is being analyzed @return np.array len=3 ''' resList= struct[0].get_residues() coords= np.zeros((len(list(resList)),3)) for i,res in enumerate(resList): try: coords[i,:]= res["CA"].get_coord() except KeyError: try: coords[i,:]= res["CB"].get_coord() except KeyError: try: coords[i,:]= res["N"].get_coord() except KeyError: try: coords[i,:]= res["O"].get_coord() except KeyError: coords[i,:]= res.get_list()[0].get_coord() return np.mean(coords,axis=0) def computeAngle(self, res1_atom, res2_atom, structCenterMass): ''' Computes angle between 2 atoms with respect one point @param res1_atom: Bio.PDB.Atom. Atom @param res2_atom: Bio.PDB.Atom. Atom @param structCenterMass: np.array len=3. Point where vector origin will be set @return float. The angle ''' vect1= res1_atom.get_coord() - structCenterMass vect2= res2_atom.get_coord() - structCenterMass vect1 = vect1 /np.linalg.norm(vect1) vect2 = vect2 /np.linalg.norm(vect2) return np.arccos(np.clip(np.dot(vect1, vect2), -1.0, 1.0)) def getMagnitude(self, res1, res2, structCenterMass): ''' Computes both distance and angle with respect protein center of mass of 2 residues @param res1: Bio.PDB.Residue. res1 @param res2: Bio.PDB.Residue. res2 @param structCenterMass: np.array len=3. Point where vector origin will be set @return Tuple (float, float). (Distance, angle) ''' try: res1_atom= res1["CA"] except KeyError: try: res1_atom= res1["CB"] except KeyError: try: res1_atom= res1["CA"] except KeyError: res1_atom= res1.get_list()[0] try: res2_atom= res2["CA"] except KeyError: try: res2_atom= res2["CB"] except KeyError: try: res2_atom= res2["CA"] except KeyError: res2_atom= res2.get_list()[0] resDist= round( res1_atom - res2_atom,4) resAngl= round( self.computeAngle( res1_atom, res2_atom, structCenterMass), 4) return resDist,resAngl def testModule(): # rFname="/home/rsanchez/Tesis/rriPredMethod/data/ppdockingBenchData/BenchmarkData/rawBenchmark3/1A2K_r_u.pdb" # lFname="/home/rsanchez/Tesis/rriPredMethod/data/ppdockingBenchData/BenchmarkData/rawBenchmark3/1A2K_l_u.pdb" rFname="/home/rsanchez/Tesis/managePDB/data/dimersAndTrimersRawPDBs/1A22.pdb" lFname="/home/rsanchez/Tesis/managePDB/data/dimersAndTrimersRawPDBs/1ABR.pdb" computedFeatsRootDir="/home/rsanchez/Tesis/rriPredMethod/data/ppdockingBenchData/tmpComputedFeatures" distComp= DistMapComputer(rFname, lFname, computedFeatsRootDir) distComp.computeFun() raise FeatureComputerException("Debug Mode. Comment out testModule() line 128") if __name__=="__main__": # testModule() pdbsIndir= "/home/rsanchez/Tesis/rriPredMethod/data/bench5Data/b5structures/" computedFeatsRootDir= "/home/rsanchez/Tesis/rriPredMethod/data/bench5Data/newCodeData/computedFeatures/structStep/DIST_MAT" StructFeatComputer.computeFeaturesAllComplexes(DistMapComputer,pdbsIndir= pdbsIndir ,computedFeatsRootDir= computedFeatsRootDir)
[ "numpy.mean", "utils.tryToRemove", "os.path.join", "Bio.PDB.Polypeptide.is_aa", "os.path.isfile", "numpy.dot", "computeFeatures.structStep.myPDBParser.myPDBParser", "utils.myMakeDir", "numpy.linalg.norm" ]
[((987, 1047), 'utils.myMakeDir', 'myMakeDir', (['self.computedFeatsRootDir', '"""distanceMatricesData"""'], {}), "(self.computedFeatsRootDir, 'distanceMatricesData')\n", (996, 1047), False, 'from utils import myMakeDir, tryToRemove\n'), ((1065, 1086), 'computeFeatures.structStep.myPDBParser.myPDBParser', 'PDBParser', ([], {'QUIET': '(True)'}), '(QUIET=True)\n', (1074, 1086), True, 'from computeFeatures.structStep.myPDBParser import myPDBParser as PDBParser\n'), ((1345, 1406), 'os.path.join', 'os.path.join', (['self.outPath', "(prefixAndChainTypeId + '.distMat')"], {}), "(self.outPath, prefixAndChainTypeId + '.distMat')\n", (1357, 1406), False, 'import os, sys\n'), ((1411, 1434), 'os.path.isfile', 'os.path.isfile', (['outName'], {}), '(outName)\n', (1425, 1434), False, 'import os, sys\n'), ((3734, 3757), 'numpy.mean', 'np.mean', (['coords'], {'axis': '(0)'}), '(coords, axis=0)\n', (3741, 3757), True, 'import numpy as np\n'), ((4236, 4257), 'numpy.linalg.norm', 'np.linalg.norm', (['vect1'], {}), '(vect1)\n', (4250, 4257), True, 'import numpy as np\n'), ((4277, 4298), 'numpy.linalg.norm', 'np.linalg.norm', (['vect2'], {}), '(vect2)\n', (4291, 4298), True, 'import numpy as np\n'), ((1825, 1851), 'Bio.PDB.Polypeptide.is_aa', 'is_aa', (['res1'], {'standard': '(True)'}), '(res1, standard=True)\n', (1830, 1851), False, 'from Bio.PDB.Polypeptide import is_aa\n'), ((2926, 2946), 'utils.tryToRemove', 'tryToRemove', (['outName'], {}), '(outName)\n', (2937, 2946), False, 'from utils import myMakeDir, tryToRemove\n'), ((4328, 4348), 'numpy.dot', 'np.dot', (['vect1', 'vect2'], {}), '(vect1, vect2)\n', (4334, 4348), True, 'import numpy as np\n'), ((2184, 2210), 'Bio.PDB.Polypeptide.is_aa', 'is_aa', (['res2'], {'standard': '(True)'}), '(res2, standard=True)\n', (2189, 2210), False, 'from Bio.PDB.Polypeptide import is_aa\n')]
from tkinter import * from tkinter import ttk from tkinter import simpledialog, messagebox from PIL import Image, ImageTk import AER_config as config from AER_utils import Plot_Types import os import numpy as np import time import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import matplotlib.image as mpimg from enum import Enum class Plot_Windows(Enum): THEORIST = 1 EXPERIMENTALIST = 2 class AER_GUI(Frame): AER_cycles = 5 # GUI settings _title = "AER" # general settings _msg_modeling_start = "# START" _msg_modeling_finish = "DONE" _default_label_status_text = "Status" _default_run_text = "RUN" _default_stop_text = "STOP" _label_bgcolor = "#DDDDDD" _up_down_bgcolor = config.up_down_bgcolor _run_bgcolor = "#d2ffbf" _stop_bgcolor = config.stop_bgcolor _listbox_bgcolor = "white" _font_family = config.font_family _font_size = config.font_size _title_font_size = config.title_font_size _font_size_button = config.font_size_button # grid parameters _model_plot_height = 220 _run_button_width = 150 _theorist_plot_width = 200 _theorist_button_width = 30 _experimentalist_plot_width = _theorist_plot_width _root = None _running = False _paused = False _last_meta_param_idx = 0 _last_epoch = 0 # plot parameters _reset_theorist_plot = False model_plot_img = None _plot_fontSize = 10 _scatter_area = 50 _scatter_color = "#FF0000" _plot_colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'r--', 'g--', 'b--', 'c--', 'm--', 'y--', 'k--', 'r:', 'g:', 'b:', 'c:', 'm:', 'y:', 'k:'] # Initialize GUI. def __init__(self, object_of_study, theorist, experimentalist, root=None): # set up window if root is not None: self._root = root self.object_of_study = object_of_study self.theorist = theorist self.experimentalist = experimentalist Frame.__init__(self, self._root) # define styles self.label_style = ttk.Style() self.label_style.configure("Default.TLabel", foreground="black", background=self._label_bgcolor, font=(self._font_family, self._title_font_size), anchor="center") self.active_label_style = ttk.Style() self.active_label_style.configure("Active.TLabel", foreground="red", background=self._label_bgcolor, font=(self._font_family, self._title_font_size), anchor="center") self.up_down_button_style = ttk.Style() self.up_down_button_style.configure("UpDown.TButton", foreground="black", background=self._up_down_bgcolor, font=(self._font_family, self._font_size_button)) self.run_button_style = ttk.Style() self.run_button_style.configure("Run.TButton", foreground="black", background=self._run_bgcolor, font=(self._font_family, self._font_size_button)) self.stop_button_style = ttk.Style() self.stop_button_style.configure("Stop.TButton", foreground="black", background=self._stop_bgcolor, font=(self._font_family, self._font_size_button)) # configure grid for row in range(4): Grid.rowconfigure(self._root, row, weight=1) for col in range(5): Grid.columnconfigure(self._root, col, weight=1) # set size Grid.rowconfigure(self._root, 1, minsize=self._model_plot_height) Grid.columnconfigure(self._root, 0, minsize=self._run_button_width) Grid.columnconfigure(self._root, 1, minsize=self._theorist_plot_width) Grid.columnconfigure(self._root, 3, minsize=self._experimentalist_plot_width) # set up window components # AER control panel self.label_aer = ttk.Label(self._root, text='AER Status', style='Default.TLabel') self.listbox_status = Listbox(self._root, selectmode=SINGLE, font=(self._font_family, self._font_size), bg=self._listbox_bgcolor) self.button_run = ttk.Button(self._root, text=self._default_run_text, command=self.run_study, style="Run.TButton") self.button_stop = ttk.Button(self._root, text=self._default_stop_text, command=self.stop_study, style="Stop.TButton") # theorist self.label_theorist = ttk.Label(self._root, text='Theorist', style='Default.TLabel') self.model_plot_canvas = Label(self._root) self._fig_theorist = Figure(figsize=(1, 1), dpi=100) self._axis_theorist = self._fig_theorist.add_subplot(111) self._fig_theorist.subplots_adjust(bottom=0.2) self._fig_theorist.subplots_adjust(left=0.35) self._axis_theorist.plot([0],[0]) self._axis_theorist.set_xlabel('Ordinate', fontsize=self._font_size) self._axis_theorist.set_ylabel('Epochs', fontsize=self._font_size) self._axis_theorist.set_title('No Data Available', fontsize=self._font_size) self._axis_theorist.grid() self._canvas_theorist = FigureCanvasTkAgg(self._fig_theorist, self._root) # self.model_plot_canvas = Label(self._root) self._theorist_canvas_width = self._theorist_plot_width + self._theorist_button_width self.listbox_theorist = Listbox(self._root, selectmode=SINGLE, font=(self._font_family, self._font_size), bg=self._listbox_bgcolor, exportselection=False) self.listbox_theorist.bind('<<ListboxSelect>>', self.update_theorist_plot) self.button_theorist_selection_up = ttk.Button(self._root, text=" /\\ ", command=self.theorist_selection_up, style="UpDown.TButton") self.button_theorist_selection_down = ttk.Button(self._root, text=" \\/ ", command=self.theorist_selection_down, style="UpDown.TButton") # experimentalist self.label_experimentalist = ttk.Label(self._root, text='Experimentalist', style='Default.TLabel') self.listbox_experimentalist = Listbox(self._root, selectmode=SINGLE, font=(self._font_family, self._font_size), bg=self._listbox_bgcolor, exportselection=False) self.listbox_experimentalist.bind('<<ListboxSelect>>', self.update_experimentalist_plot) self.button_experimentalist_up = ttk.Button(self._root, text=" /\\ ", command=self.experimentalist_selection_up, style="UpDown.TButton") self.button_experimentalist_down = ttk.Button(self._root, text=" \\/ ", command=self.experimentalist_selection_down, style="UpDown.TButton") self._fig_experimentalist = Figure(figsize=(1, 1), dpi=100) self._axis_experimentalist = self._fig_experimentalist.add_subplot(111) self._fig_experimentalist.subplots_adjust(bottom=0.2) self._fig_experimentalist.subplots_adjust(left=0.35) self._axis_experimentalist.plot([0], [0]) self._axis_experimentalist.set_xlabel('Independent Var', fontsize=self._font_size) self._axis_experimentalist.set_ylabel('Dependent Var', fontsize=self._font_size) self._axis_experimentalist.set_title('No Data Available', fontsize=self._font_size) self._axis_experimentalist.grid() self._canvas_experimentalist = FigureCanvasTkAgg(self._fig_experimentalist, self._root) self.init_window() def init_window(self): # set up GUI self._root.title(self._title) # AER status self.label_aer.grid(row=0, column=0, sticky=N + S + E + W) self.listbox_status.grid(row=1, column=0, sticky=N + S + E + W) self.button_stop.grid(row=2, column=0, sticky=N + S + E + W) self.button_run.grid(row=3, column=0, sticky=N + S + E + W) # theorist self.label_theorist.grid(row=0, column=1, columnspan=2, sticky=N + S + E + W) self.model_plot_canvas.grid(row=1, column=1, columnspan=2, sticky=N + S + E + W) self._canvas_theorist.get_tk_widget().grid(row=1, column=1, columnspan=2, sticky=N + S + E + W) self.listbox_theorist.grid(row=2, rowspan=2, column=1, sticky=N + S + E + W) self.button_theorist_selection_up.grid(row=2, column=2, sticky=N + S + E + W) self.button_theorist_selection_down.grid(row=3, column=2, sticky=N + S + E + W) # experimentalist self.label_experimentalist.grid(row=0, column=3, columnspan=2, sticky=N + S + E + W) self._canvas_experimentalist.get_tk_widget().grid(row=1, column=3, columnspan=2, sticky=N + S + E + W) self.listbox_experimentalist.grid(row=2, rowspan=2, column=3, columnspan=2, sticky=N + S + E + W) self.button_experimentalist_up.grid(row=2, column=4, sticky=N + S + E + W) self.button_experimentalist_down.grid(row=3, column=4, sticky=N + S + E + W) # resize hpad = 67 wpad = 3 self._geom = '800x400+0+0' self._root.geometry("{0}x{1}+0+0".format( self._root.winfo_screenwidth() - wpad, self._root.winfo_screenheight() - hpad)) self._root.bind('<Escape>', self.toggle_geom) def toggle_geom(self, event): geom = self._root.winfo_geometry() print(geom, self._geom) self._root.geometry(self._geom) self._geom = geom def theorist_selection_up(self): self.move_listbox_selection(self.listbox_theorist, -1) def theorist_selection_down(self): self.move_listbox_selection(self.listbox_theorist, +1) def experimentalist_selection_up(self): self.move_listbox_selection(self.listbox_experimentalist, -1) def experimentalist_selection_down(self): self.move_listbox_selection(self.listbox_experimentalist, +1) def move_listbox_selection(self, listbox, movement): selection = listbox.curselection() if len(selection) > 0: current_value = selection[0] max_value = listbox.size() new_value = max(min(current_value + movement, max_value-1), 0) listbox.selection_clear(0, END) listbox.select_set(new_value) listbox.activate(new_value) elif listbox.size() > 0: listbox.select_set(0) listbox.activate(0) def get_position_from_listbox_value(self, listbox, target_value): # find index corresponding to value of listbox item position = None for idx in range(listbox.size()): value = listbox.get(idx) if value == target_value: position = idx break return position def set_listbox_selection_to_value(self, listbox, target_value): position = self.get_position_from_listbox_value(listbox, target_value) # if the item exists, set selection of listbox to this item if position is not None: self.set_listbox_selection(listbox, position) return True else: return False def set_listbox_selection(self, listbox, position): listbox.selection_clear(0, END) listbox.select_set(position) listbox.activate(position) def update_status(self, msg): self.listbox_status.insert(END, msg) self.set_listbox_selection(self.listbox_status, self.listbox_status.size() - 1) self.listbox_status.yview_moveto(1) def update_status_theorist(self, msg): msg = "Theorist: " + msg self.update_status(msg) def update_status_experimentalist(self, msg): msg = "Experimentalist: " + msg self.update_status(msg) def activate_theorist(self): self.label_theorist.config(style = "Active.TLabel") self.label_experimentalist.config(style = "Default.TLabel") def activate_experimentalist(self): self.label_experimentalist.config(style = "Active.TLabel") self.label_theorist.config(style = "Default.TLabel") def update_run_button(self, epoch=0, num_epochs=1, meta_idx=0, num_meta_idx=0): if self._running is True: if self._paused is True: epoch = self._last_epoch num_epochs = self.theorist.model_search_epochs percent = np.round(epoch / num_epochs * 100) if percent < 10: str_percent = "0" + str(percent) else: str_percent = "" + str(percent) if self._paused is True: self.button_run.config(text="RESUME\n" + str(meta_idx) + " (" + str_percent + "%)" + " / " + str(num_meta_idx), command=self.resume_study) else: self.button_run.config(text="PAUSE\n" + str(meta_idx) + " (" + str_percent + "%)" + " / " + str(num_meta_idx), command=self.pause_study) else: self.button_run.config(text=self._default_run_text, command=self.run_study) def update_model_plot(self): # load image model_image_path = self.theorist.plot_model(self.object_of_study) image = mpimg.imread(model_image_path) self._axis_theorist.cla() self._axis_theorist.imshow(image) self._axis_theorist.get_xaxis().set_visible(False) self._axis_theorist.get_yaxis().set_visible(False) self._canvas_theorist.draw() self._reset_theorist_plot = True # needed here, otherwise canvas doesn't update # self._root.update() def get_theorist_plots(self): # collect performance plots performance_plots = self.theorist.get_performance_plots(self.object_of_study) # collect supplementary plots supplementary_plots = self.theorist.get_supplementary_plots(self.object_of_study) theorist_plots = {**performance_plots, **supplementary_plots} # add model plot plot_dict = dict() plot_dict[config.plot_key_type] = Plot_Types.MODEL theorist_plots["model architecture"] = plot_dict return theorist_plots def update_theorist_plot_list(self, theorist_plots): self.listbox_theorist.delete(0, 'end') keys = theorist_plots.keys() for key in keys: param_label = key self.listbox_theorist.insert(END, param_label) def get_experimentalist_plots(self): experimentalist_plots = self.experimentalist.get_plots(self.best_model, self.object_of_study) return experimentalist_plots def update_experimentalist_plot_list(self, experimentalist_plots): self.listbox_experimentalist.delete(0, 'end') keys = experimentalist_plots.keys() for key in keys: param_label = key self.listbox_experimentalist.insert(END, param_label) def update_theorist_plot(self, event): plots = self.get_theorist_plots() self.update_plot(plots=plots, plot_type=Plot_Windows.THEORIST) def update_experimentalist_plot(self, event): plots = self.get_experimentalist_plots() plot_name = self.update_plot(plots=plots, plot_type=Plot_Windows.EXPERIMENTALIST) success = self.set_listbox_selection_to_value(self.listbox_theorist, plot_name) if success: plots = self.get_theorist_plots() self.update_plot(plots=plots, plot_type=Plot_Windows.THEORIST) def update_plot(self, plots=None, plot_type=Plot_Windows.THEORIST, save=False, AER_step=1): if plot_type == Plot_Windows.THEORIST: relevant_listbox = self.listbox_theorist if isinstance(plots, dict) is False: plots = self.get_theorist_plots() if hasattr(self, '_axis_theorist'): plot_axis = self._axis_theorist if hasattr(self, '_canvas_theorist'): plot_canvas = self._canvas_theorist elif plot_type == Plot_Windows.EXPERIMENTALIST: relevant_listbox = self.listbox_experimentalist if isinstance(plots, dict) is False: if hasattr(self, 'best_model'): plots = self.get_experimentalist_plots() else: return if hasattr(self, '_axis_theorist'): plot_axis = self._axis_experimentalist if hasattr(self, '_canvas_theorist'): plot_canvas = self._canvas_experimentalist else: return listbox_selection = relevant_listbox.curselection() if len(listbox_selection) == 0: listbox_selection = [0] key = str(relevant_listbox.get(listbox_selection[0])) # during initial call, key is empty if key == '': return key if key in plots.keys(): plot_dict = plots[key] if self._reset_theorist_plot: self._fig_theorist = Figure(figsize=(1, 1), dpi=100) self._axis_theorist = self._fig_theorist.add_subplot(111) self._fig_theorist.subplots_adjust(bottom=0.2) self._fig_theorist.subplots_adjust(left=0.35) self._axis_theorist.plot([0], [0]) self._axis_theorist.set_xlabel('Ordinate', fontsize=self._font_size) self._axis_theorist.set_ylabel('Epochs', fontsize=self._font_size) self._axis_theorist.set_title('No Data Available', fontsize=self._font_size) self._axis_theorist.grid() self._canvas_theorist = FigureCanvasTkAgg(self._fig_theorist, self._root) self._canvas_theorist.get_tk_widget().grid(row=1, column=1, columnspan=2, sticky=N + S + E + W) self._reset_theorist_plot = False type = plot_dict[config.plot_key_type] if type == Plot_Types.LINE: # get relevant data x_data = plot_dict[config.plot_key_x_data] y_data = plot_dict[config.plot_key_y_data] x_limit = plot_dict[config.plot_key_x_limit] y_limit = plot_dict[config.plot_key_y_limit] x_label = plot_dict[config.plot_key_x_label] y_label = plot_dict[config.plot_key_y_label] legend = plot_dict[config.plot_key_legend] # generate plots plot_axis.cla() del plot_axis.lines[:] # remove previous lines plots = list() if isinstance(x_data, tuple) or isinstance(x_data, list): for idx, (x, y, leg) in enumerate(zip(x_data, y_data, legend)): plots.append(plot_axis.plot(x, y, self._plot_colors[idx], label=leg)) else: plots.append(plot_axis.plot(x_data, y_data, self._plot_colors[0], label=legend)) # adjust axes plot_axis.set_xlim(x_limit[0], x_limit[1]) plot_axis.set_ylim(y_limit[0], y_limit[1]) # set labels plot_axis.set_xlabel(x_label, fontsize=self._plot_fontSize) plot_axis.set_ylabel(y_label, fontsize=self._plot_fontSize) plot_axis.legend(loc=2, fontsize="small") plot_canvas.draw() elif type == Plot_Types.MODEL: self.update_model_plot() return elif type == Plot_Types.IMAGE: # get relevant data image = plot_dict[config.plot_key_image] x_data = plot_dict[config.plot_key_x_data] y_data = plot_dict[config.plot_key_y_data] x_label = plot_dict[config.plot_key_x_label] y_label = plot_dict[config.plot_key_y_label] # generate image plot_axis.cla() plot_axis.imshow(image, interpolation='nearest', aspect='auto') x = x_data y = y_data plot_axis.plot(x, y, color='red') # set labels plot_axis.set_xlabel(x_label, fontsize=self._plot_fontSize) plot_axis.set_ylabel(y_label, fontsize=self._plot_fontSize) elif type == Plot_Types.LINE_SCATTER: # get relevant data x_data = plot_dict[config.plot_key_x_data] y_data = plot_dict[config.plot_key_y_data] x_model = plot_dict[config.plot_key_x_model] y_model = plot_dict[config.plot_key_y_model] x_limit = plot_dict[config.plot_key_x_limit] y_limit = plot_dict[config.plot_key_y_limit] x_label = plot_dict[config.plot_key_x_label] y_label = plot_dict[config.plot_key_y_label] legend = plot_dict[config.plot_key_legend] if config.plot_key_x_conditions in plot_dict: x_conditions = plot_dict[config.plot_key_x_conditions] else: x_conditions = None # generate plots plot_axis.cla() del plot_axis.lines[:] # remove previous lines plots = list() # plot data plots.append(plot_axis.scatter(x_data, y_data, marker='.', c='k', label=legend[0])) # plot model prediction plots.append(plot_axis.plot(x_model, y_model, 'k', label=legend[1])) legend_idx = 1 # plot highlighted data if config.plot_key_x_highlighted_data in plot_dict.keys(): legend_idx += 1 x_highlighted = plot_dict[config.plot_key_x_highlighted_data] y_highlighted = plot_dict[config.plot_key_y_highlighted_data] plots.append(plot_axis.scatter(x_highlighted, y_highlighted, marker='.', c='r', label=legend[legend_idx])) # plot conditions if config.plot_key_x_conditions in plot_dict.keys(): for idx, condition in enumerate(x_conditions): if idx == 0: legend_idx += 1 x = [condition, condition] y = [y_limit[0], y_limit[1]] if idx == 0: plots.append(plot_axis.plot(x, y, 'b', label=legend[legend_idx])) else: plots.append(plot_axis.plot(x, y, 'b')) # adjust axes plot_axis.set_xlim(x_limit[0], x_limit[1]) plot_axis.set_ylim(y_limit[0], y_limit[1]) # set labels plot_axis.set_xlabel(x_label, fontsize=self._plot_fontSize) plot_axis.set_ylabel(y_label, fontsize=self._plot_fontSize) plot_axis.legend(loc=2, fontsize="small") elif type == Plot_Types.SURFACE_SCATTER: # get relevant data (x1_data, x2_data) = plot_dict[config.plot_key_x_data] y_data = plot_dict[config.plot_key_y_data] (x1_model, x2_model) = plot_dict[config.plot_key_x_model] y_model = plot_dict[config.plot_key_y_model] (x1_limit, x2_limit) = plot_dict[config.plot_key_x_limit] y_limit = plot_dict[config.plot_key_y_limit] (x1_label, x2_label) = plot_dict[config.plot_key_x_label] y_label = plot_dict[config.plot_key_y_label] legend = plot_dict[config.plot_key_legend] if config.plot_key_x_conditions in plot_dict: x_conditions = plot_dict[config.plot_key_x_conditions] else: x_conditions = None if config.plot_key_y_conditions in plot_dict: y_conditions = plot_dict[config.plot_key_y_conditions] else: y_conditions = None # generate plots plot_axis.cla() plots = list() # plot data plots.append(plot_axis.scatter(x1_data, x2_data, y_data, color = (0, 0, 0, 0), label=legend[0])) # plot model prediction plots.append(plot_axis.plot_surface(x1_model, x2_model, y_model, color=(0, 0, 0, 0.5), label=legend[1])) legend_idx = 1 # plot highlighted data if config.plot_key_x_highlighted_data in plot_dict.keys(): legend_idx += 1 (x1_highlighted, x2_highlighted) = plot_dict[config.plot_key_x_highlighted_data] y_highlighted = plot_dict[config.plot_key_y_highlighted_data] plots.append(plot_axis.scatter(x1_highlighted, x2_highlighted, y_highlighted, color=(1, 0, 0, 0.5), label=legend[2])) # plot conditions for idx, x1_x2_condition in enumerate(x_conditions): if idx == 0: legend_idx += 1 x1 = [x1_x2_condition[0], x1_x2_condition[0]] x2 = [x1_x2_condition[1], x1_x2_condition[1]] y = [y_limit[0], y_limit[1]] if idx == 0: plots.append(plot_axis.plot(x1, x2, y, 'r', label=legend[legend_idx])) else: plots.append(plot_axis.plot(x1, x2, y, 'r')) # adjust axes plot_axis.set_xlim(x1_limit[0], x1_limit[1]) plot_axis.set_ylim(x2_limit[0], x2_limit[1]) plot_axis.set_zlim(y_limit[0], y_limit[1]) # set labels self.mismatchPlot.set_xlabel(x1_label, fontsize=self._plot_fontSize) self.mismatchPlot.set_ylabel(x2_label, fontsize=self._plot_fontSize) self.mismatchPlot.set_zlabel(y_label, fontsize=self._plot_fontSize) pass # finalize performance plot plot_axis.set_title(key, fontsize=self._plot_fontSize) plot_canvas.draw() # save plot if save is True: self._root.update() if plot_type == Plot_Windows.THEORIST: plot_filepath = os.path.join(self.theorist.results_path, 'plot_AER_step_' + str(AER_step) + '_theorist_' + key + '.png') self._fig_theorist.savefig(plot_filepath) elif plot_type == Plot_Windows.EXPERIMENTALIST: plot_filepath = os.path.join(self.theorist.results_path, 'plot_AER_step_' + str(AER_step) + '_experimentalist_' + key + '.png') self._fig_experimentalist.savefig(plot_filepath) return key # plot_canvas.get_tk_widget().lift() else: raise Exception("Key '" + str(key) + "' not found in dictionary performance_plots.") def stop_study(self): self.update_status("Aborting study...") self._running = False if self._paused is True: self.reset_gui() def pause_study(self): # self.update_status("Pausing study...") # self._paused = True # todo: implement proper pausing pass def resume_study(self): self._paused = False self.update_status("Resuming study...") self.run_study(resume=True) def run_study(self, resume=False): if resume is False: self._running = True self._paused = False self.update_run_button() self._root.update() new_param_value = simpledialog.askstring("AER Cycles", "Please enter number of autonomous research cycles:", parent=self._root) if new_param_value is not None: self.AER_cycles = int(new_param_value) # (Main) AER Loop for AER_cycle in range(self.AER_cycles): status_msg = "------------------" self.update_status(status_msg) status_msg = "AER CYCLE " + str(AER_cycle+1) + "/" + str(self.AER_cycles) self.update_status(status_msg) status_msg = "------------------" self.update_status(status_msg) self._root.update() # Experimentalist: collect seed data self.activate_experimentalist() if AER_cycle == 0: status_msg = "Collecting seed data" self.update_status_experimentalist(status_msg) self._root.update() seed_data = self.experimentalist.seed(self.object_of_study) self.object_of_study.add_data(seed_data) else: # activate experimenter self.activate_experimentalist() # Experimenter: update experimentalist plot based on best-fitting model status_msg = "Looking at best-fitting model..." self.update_status_experimentalist(status_msg) experimentalist_plots = self.experimentalist.get_plots(self.best_model, self.object_of_study) self.update_experimentalist_plot_list(experimentalist_plots) self.update_plot(plots=experimentalist_plots, plot_type=Plot_Windows.EXPERIMENTALIST) self._root.update() # Experimenter: initiating experiment search status_msg = "Initiating experiment search..." self.update_status_experimentalist(status_msg) self._root.update() self.experimentalist.init_experiment_search(self.best_model, self.object_of_study) experimentalist_plots = self.experimentalist.get_plots(self.best_model, self.object_of_study) self.update_experimentalist_plot_list(experimentalist_plots) self.update_plot(plots=experimentalist_plots, plot_type=Plot_Windows.EXPERIMENTALIST) # Experimenter: identifying novel experiment conditions status_msg = "Identifying " + str(self.experimentalist.conditions_per_experiment) \ + " experiment conditions..." self.update_status_experimentalist(status_msg) self._root.update() for condition in range(self.experimentalist.conditions_per_experiment): self.experimentalist.sample_experiment_condition(self.best_model, self.object_of_study, condition) # plot new experiment conditions experimentalist_plots = self.experimentalist.get_plots(self.best_model, self.object_of_study) self.update_experimentalist_plot_list(experimentalist_plots) self.update_plot(plots=experimentalist_plots, plot_type=Plot_Windows.EXPERIMENTALIST) self._root.update() # write novel experiment status_msg = "Writing experiment..." self.update_status_experimentalist(status_msg) self._root.update() experiment_file_path = self.experimentalist._write_experiment(self.object_of_study, self.experimentalist._experiment_sequence) # collect data from experiment status_msg = "Commissioning experiment..." self.update_status_experimentalist(status_msg) self._root.update() data = self.experimentalist.commission_experiment(object_of_study=self.object_of_study, experiment_file_path=experiment_file_path) # add new data to object of study status_msg = "Adding collected data..." self.update_status_experimentalist(status_msg) self.object_of_study.add_data(data) experimentalist_plots = self.experimentalist.get_plots(self.best_model, self.object_of_study) self.update_experimentalist_plot_list(experimentalist_plots) self.update_plot(plots=experimentalist_plots, plot_type=Plot_Windows.EXPERIMENTALIST) self._root.update() # save all experimentalist plots experimentalist_plots = self.experimentalist.get_plots(self.best_model, self.object_of_study) for item in range(self.listbox_experimentalist.size()): self.set_listbox_selection(self.listbox_experimentalist, item) self.update_plot(plot_type=Plot_Windows.EXPERIMENTALIST, plots=experimentalist_plots, save=True, AER_step=(AER_cycle + 1)) # Theorist: initialize meta-parameter search self.activate_theorist() status_msg = "Initializing model search" self.update_status_theorist(status_msg) self.theorist.init_meta_search(self.object_of_study) # Theorist: perform architecture search for different hyper-parameters for idx, meta_params in enumerate(self.theorist._meta_parameters): if resume is True: if idx < self._last_meta_param_idx: continue else: status_msg = "Model search " + str(idx+1) + "/" + str(len(self.theorist._meta_parameters)) self.update_status_theorist(status_msg) [arch_weight_decay_df, num_graph_nodes, seed] = meta_params self.theorist.init_model_search(self.object_of_study) # update theorist plot list theorist_plots = self.get_theorist_plots() self.update_theorist_plot_list(theorist_plots) for epoch in range(self.theorist.model_search_epochs): if resume is True: if epoch < self._last_epoch: continue # check if still running if self._running is False: break # check if paused if self._paused is True: self._last_meta_param_idx = idx self._last_epoch = epoch self.update_run_button(meta_idx=idx+1, num_meta_idx=len(self.theorist._meta_parameters)) self._root.update() return # update run button self.update_run_button(epoch=epoch+1, num_epochs=self.theorist.model_search_epochs, meta_idx=idx+1, num_meta_idx=len(self.theorist._meta_parameters)) self.theorist.run_model_search_epoch(epoch) # update GUI self._root.update() # update performance plot self.theorist.log_plot_data(epoch, self.object_of_study) theorist_plots = self.get_theorist_plots() self.update_plot(plots=theorist_plots, plot_type=Plot_Windows.THEORIST) if self._running is True: # save all performance plots theorist_plots = self.get_theorist_plots() for item in range(self.listbox_theorist.size()): self.set_listbox_selection(self.listbox_theorist, item) self.update_plot(plot_type=Plot_Windows.THEORIST, plots=theorist_plots, save=True, AER_step=(AER_cycle + 1)) status_msg = "Evaluating architecture..." self.update_status_theorist(status_msg) self._root.update() self.theorist.log_model_search(self.object_of_study) # self.theorist.evaluate_model_search(self.object_of_study) # Theorist: evaluate model architecture # initialize meta evaluation self.theorist.init_meta_evaluation(self.object_of_study) # perform architecture search for different hyper-parameters for eval_meta_params in self.theorist._eval_meta_parameters: status_msg = "Evaluation " + str(idx + 1) + "/" + str(len(self.theorist._eval_meta_parameters)) self.update_status_theorist(status_msg) self.theorist.init_model_evaluation(self.object_of_study) # loop over epochs for epoch in range(self.theorist.eval_epochs): # run single epoch self.theorist.run_eval_epoch(epoch, self.object_of_study) # log performance (for plotting purposes) self.theorist.log_plot_data(epoch, self.object_of_study) theorist_plots = self.get_theorist_plots() self.update_plot(plots=theorist_plots, plot_type=Plot_Windows.THEORIST) self._root.update() # log model evaluation self.theorist.log_model_evaluation(self.object_of_study) # sum up meta evaluation self.theorist.log_meta_evaluation(self.object_of_study) self.theorist._meta_parameters_iteration += 1 # Theorist: determine best-fitting model if self._running is True: status_msg = "Determining best-fitting model..." self.update_status_theorist(status_msg) self._root.update() self.best_model = self.theorist.get_best_model(self.object_of_study) self.theorist.model = self.best_model if self._running is not True: # reset gui elements # self.reset_gui() pass self._running = False status_msg = "DONE" self.update_status(status_msg) def reset_gui(self): self.update_run_button() self.listbox_theorist.delete(0, 'end') self.listbox_experimentalist.delete(0, 'end') self._root.update()
[ "tkinter.ttk.Button", "tkinter.ttk.Style", "matplotlib.use", "matplotlib.figure.Figure", "tkinter.ttk.Label", "matplotlib.image.imread", "tkinter.simpledialog.askstring", "numpy.round", "matplotlib.backends.backend_tkagg.FigureCanvasTkAgg" ]
[((243, 266), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (257, 266), False, 'import matplotlib\n'), ((2176, 2187), 'tkinter.ttk.Style', 'ttk.Style', ([], {}), '()\n', (2185, 2187), False, 'from tkinter import ttk\n'), ((2429, 2440), 'tkinter.ttk.Style', 'ttk.Style', ([], {}), '()\n', (2438, 2440), False, 'from tkinter import ttk\n'), ((2688, 2699), 'tkinter.ttk.Style', 'ttk.Style', ([], {}), '()\n', (2697, 2699), False, 'from tkinter import ttk\n'), ((2934, 2945), 'tkinter.ttk.Style', 'ttk.Style', ([], {}), '()\n', (2943, 2945), False, 'from tkinter import ttk\n'), ((3223, 3234), 'tkinter.ttk.Style', 'ttk.Style', ([], {}), '()\n', (3232, 3234), False, 'from tkinter import ttk\n'), ((4110, 4174), 'tkinter.ttk.Label', 'ttk.Label', (['self._root'], {'text': '"""AER Status"""', 'style': '"""Default.TLabel"""'}), "(self._root, text='AER Status', style='Default.TLabel')\n", (4119, 4174), False, 'from tkinter import ttk\n'), ((4383, 4483), 'tkinter.ttk.Button', 'ttk.Button', (['self._root'], {'text': 'self._default_run_text', 'command': 'self.run_study', 'style': '"""Run.TButton"""'}), "(self._root, text=self._default_run_text, command=self.run_study,\n style='Run.TButton')\n", (4393, 4483), False, 'from tkinter import ttk\n'), ((4622, 4726), 'tkinter.ttk.Button', 'ttk.Button', (['self._root'], {'text': 'self._default_stop_text', 'command': 'self.stop_study', 'style': '"""Stop.TButton"""'}), "(self._root, text=self._default_stop_text, command=self.\n stop_study, style='Stop.TButton')\n", (4632, 4726), False, 'from tkinter import ttk\n'), ((4886, 4948), 'tkinter.ttk.Label', 'ttk.Label', (['self._root'], {'text': '"""Theorist"""', 'style': '"""Default.TLabel"""'}), "(self._root, text='Theorist', style='Default.TLabel')\n", (4895, 4948), False, 'from tkinter import ttk\n'), ((5031, 5062), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': '(1, 1)', 'dpi': '(100)'}), '(figsize=(1, 1), dpi=100)\n', (5037, 5062), False, 'from matplotlib.figure import Figure\n'), ((5584, 5633), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['self._fig_theorist', 'self._root'], {}), '(self._fig_theorist, self._root)\n', (5601, 5633), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n'), ((6116, 6218), 'tkinter.ttk.Button', 'ttk.Button', (['self._root'], {'text': '""" /\\\\ """', 'command': 'self.theorist_selection_up', 'style': '"""UpDown.TButton"""'}), "(self._root, text=' /\\\\ ', command=self.theorist_selection_up,\n style='UpDown.TButton')\n", (6126, 6218), False, 'from tkinter import ttk\n'), ((6433, 6537), 'tkinter.ttk.Button', 'ttk.Button', (['self._root'], {'text': '""" \\\\/ """', 'command': 'self.theorist_selection_down', 'style': '"""UpDown.TButton"""'}), "(self._root, text=' \\\\/ ', command=self.theorist_selection_down,\n style='UpDown.TButton')\n", (6443, 6537), False, 'from tkinter import ttk\n'), ((6776, 6845), 'tkinter.ttk.Label', 'ttk.Label', (['self._root'], {'text': '"""Experimentalist"""', 'style': '"""Default.TLabel"""'}), "(self._root, text='Experimentalist', style='Default.TLabel')\n", (6785, 6845), False, 'from tkinter import ttk\n'), ((7208, 7318), 'tkinter.ttk.Button', 'ttk.Button', (['self._root'], {'text': '""" /\\\\ """', 'command': 'self.experimentalist_selection_up', 'style': '"""UpDown.TButton"""'}), "(self._root, text=' /\\\\ ', command=self.\n experimentalist_selection_up, style='UpDown.TButton')\n", (7218, 7318), False, 'from tkinter import ttk\n'), ((7532, 7644), 'tkinter.ttk.Button', 'ttk.Button', (['self._root'], {'text': '""" \\\\/ """', 'command': 'self.experimentalist_selection_down', 'style': '"""UpDown.TButton"""'}), "(self._root, text=' \\\\/ ', command=self.\n experimentalist_selection_down, style='UpDown.TButton')\n", (7542, 7644), False, 'from tkinter import ttk\n'), ((7857, 7888), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': '(1, 1)', 'dpi': '(100)'}), '(figsize=(1, 1), dpi=100)\n', (7863, 7888), False, 'from matplotlib.figure import Figure\n'), ((8495, 8551), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['self._fig_experimentalist', 'self._root'], {}), '(self._fig_experimentalist, self._root)\n', (8512, 8551), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n'), ((14547, 14577), 'matplotlib.image.imread', 'mpimg.imread', (['model_image_path'], {}), '(model_image_path)\n', (14559, 14577), True, 'import matplotlib.image as mpimg\n'), ((13404, 13438), 'numpy.round', 'np.round', (['(epoch / num_epochs * 100)'], {}), '(epoch / num_epochs * 100)\n', (13412, 13438), True, 'import numpy as np\n'), ((29070, 29183), 'tkinter.simpledialog.askstring', 'simpledialog.askstring', (['"""AER Cycles"""', '"""Please enter number of autonomous research cycles:"""'], {'parent': 'self._root'}), "('AER Cycles',\n 'Please enter number of autonomous research cycles:', parent=self._root)\n", (29092, 29183), False, 'from tkinter import simpledialog, messagebox\n'), ((18306, 18337), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': '(1, 1)', 'dpi': '(100)'}), '(figsize=(1, 1), dpi=100)\n', (18312, 18337), False, 'from matplotlib.figure import Figure\n'), ((18932, 18981), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['self._fig_theorist', 'self._root'], {}), '(self._fig_theorist, self._root)\n', (18949, 18981), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n')]
import argparse import joblib import numpy as np import pandas as pd from sklearn.metrics import (balanced_accuracy_score, classification_report, f1_score, precision_score, recall_score, roc_auc_score, roc_curve) from tqdm import tqdm from utils import _get_subject_level_split, _map_age, get_patient_prediction stats_test_data = {} # This function is used to collect final metrics. def collect_metrics_heldout(y_probs_test, y_true_test, y_pred_test, sample_indices_test, _INDEX_DF, dataset): dataset_index = _INDEX_DF if dataset == "lemon": title = "subject_id" elif dataset == "tuh": title = "patient_id" else: raise ValueError("unknown dataset") # create patient-level train and test dataframes rows = [ ] for i in range(len(sample_indices_test)): idx = sample_indices_test[i] temp = { } temp[title] = str(dataset_index.loc[idx, title]) temp["raw_file_path"] = str(dataset_index.loc[idx, "raw_file_path"]) temp["sample_idx"] = idx temp["y_true"] = y_true_test[i] temp["y_probs_0"] = y_probs_test[i, 0] temp["y_probs_1"] = y_probs_test[i, 1] temp["y_pred"] = y_pred_test[i] rows.append(temp) test_patient_df = pd.DataFrame(rows) # get patient-level metrics from window-level dataframes y_probs_test_patient, y_true_test_patient, y_pred_test_patient = get_patient_prediction(test_patient_df, dataset) auc_patient_history, prec_history, recall_history, f1_history, bacc_history = [], [], [], [], [] # perform leave-1-out sampling for i in tqdm(range(len(y_probs_test_patient))): y_prob = np.copy(y_probs_test_patient) y_prob = np.delete(y_prob, i, axis=0) y_true_s = np.copy(y_true_test_patient) y_true_s = np.delete(y_true_s, i) stats_test_data[f"probs_0"] = y_prob[:, 0] stats_test_data[f"probs_1"] = y_prob[:, 1] patient_csv_dict = { } # PATIENT-LEVEL ROC PLOT - select optimal threshold for this, and get patient-level precision, recall, f1 fpr, tpr, thresholds = roc_curve(y_true_s, y_prob[:,1], pos_label=1) patient_csv_dict[f"fpr_fold"] = fpr patient_csv_dict[f"tpr_fold"] = tpr patient_csv_dict[f"thres_fold"] = thresholds # select an optimal threshold using the ROC curve # Youden's J statistic to obtain the optimal probability threshold and this method gives equal weights to both false positives and false negatives optimal_proba_cutoff = sorted(list(zip(np.abs(tpr - fpr), thresholds)), key=lambda i: i[0], reverse=True)[0][1] # calculate class predictions and confusion-based metrics using the optimal threshold roc_predictions = [1 if i >= optimal_proba_cutoff else 0 for i in y_prob[:,1]] precision_patient_test = precision_score(y_true_s, roc_predictions, pos_label=1) recall_patient_test = recall_score(y_true_s, roc_predictions, pos_label=1) f1_patient_test = f1_score(y_true_s, roc_predictions, pos_label=1) bal_acc_patient_test = balanced_accuracy_score(y_true_s, roc_predictions) # PATIENT-LEVEL AUROC auroc_patient_test = roc_auc_score(y_true_s, y_prob[:,1]) auc_patient_history.append(auroc_patient_test) prec_history.append(precision_patient_test) recall_history.append(recall_patient_test) f1_history.append(f1_patient_test) bacc_history.append(bal_acc_patient_test) return auc_patient_history, prec_history, recall_history, f1_history, bacc_history def _eval_downstream_task(index_df, dataset, task): X = np.load(f'../resources/psd_bandpower_relative_{dataset}.npy').astype(np.float32) X = X.reshape(X.shape[0], X.shape[1] * X.shape[2]) #load data index file if dataset == 'tuh': if task == "gender": y = index_df['parsed_gender'].to_numpy() index_df = index_df.loc[index_df["parsed_gender"].isin(["Male", "Female"])] elif task == "age": y = index_df['parsed_age_binary'].to_numpy() index_df = index_df.loc[index_df["parsed_age_binary"].isin(["young", "old"])] elif task == "condition": y = index_df["text_label"].to_numpy() index_df = index_df.loc[index_df["text_label"].isin(["normal", "abnormal"])] else: raise ValueError('unknown task!') keep_idx = index_df.index X = X[keep_idx, ...] y = y[keep_idx, ...] index_df.reset_index(drop=True, inplace=True) index_df.sort_index(inplace=True) index_df['new_window_idx'] = index_df.index elif dataset == "lemon": if task == "gender": y = index_df['gender'].to_numpy() print(y.shape) elif task == "age": y = index_df['age'].to_numpy() elif task == "condition": y = index_df["condition"].to_numpy() else: raise ValueError('unknown task!') else: raise ValueError('unknown dataset!') all_subjects, train_subjects, val_subjects, heldout_subjects, train_window_idx, val_window_idx, heldout_window_idx = \ _get_subject_level_split(index_df, _RANDOM_SEED, dataset, task) # map labels to 0/1 label_mapping, y = np.unique(y, return_inverse=True) print(f"Unique labels 0/1 mapping: {label_mapping}") print("heldout_subjects: ", len(heldout_subjects)) print(f"len heldout_window_idx:{len(heldout_window_idx)}") #load corresponding model final_model = joblib.load(f'../resources/finetuned_models/{dataset}_{task}_linear.pkl', mmap_mode='r') heldout_indices_all = [] X_list, y_list = [], [] # Leave 1 out sampling for lemon dataset and condition task. if (dataset == "lemon") and (task=="condition"): # bootstrap for i in tqdm(range(len(heldout_subjects))): heldout_subjects_resample = np.copy(heldout_subjects) heldout_subjects_resample = np.delete(heldout_subjects_resample, i) if i == 0: print("length of bootstrap subject: ", len(heldout_subjects_resample)) # create X and y corresponding to resampled subjects heldout_indices = _INDEX_DF.index[_INDEX_DF["subject_id"].astype("str").isin(heldout_subjects_resample)].tolist() heldout_indices_all.append(heldout_indices) X_heldout = X[heldout_indices, ...] y_heldout = y[heldout_indices, ...] X_list.append(X_heldout) y_list.append(y_heldout) print("length of bootstrap indices 0: ", len(heldout_indices_all[0])) #initialize metrics lists all_auc, all_prec, all_recall, all_f1, all_bacc = [],[],[],[],[] # report final metrics on heldout test set for j in tqdm(range(len(X_list))): X_heldout = X_list[j] y_heldout = y_list[j] y_pred_heldout = final_model.predict(X_heldout) y_probs_heldout = final_model.predict_proba(X_heldout) auroc_test = roc_auc_score(y_heldout, final_model.predict_proba(X_heldout)[:,1]) if _TASK == 'condition': bal_acc_test = balanced_accuracy_score(y_heldout, y_pred_heldout) report = classification_report(y_heldout, y_pred_heldout, output_dict=True) all_auc.append(auroc_test) all_bacc.append(bal_acc_test) all_prec.append(report['1']['precision']) all_recall.append(report['1']['recall']) all_f1.append(report['1']['f1-score']) alpha = 0.95 print("Report-------------------------------") print(f"heldout test AUROC: {np.mean(all_auc):.3f}({np.std(all_auc):.3f})") print(f"heldout test PRECISION: {np.mean(all_prec):.3f}({np.std(all_prec):.3f})") print(f"heldout test RECALL: {np.mean(all_recall):.3f}({np.std(all_recall):.3f})") print(f"heldout test F-1: {np.mean(all_f1):.3f}({np.std(all_f1):.3f})") print(f"heldout test BALANCED ACCURACY: {np.mean(all_bacc):.3f}({np.std(all_bacc):.3f})") # calculate interval percentile p = ((1.0-alpha)/2.0) * 100 lower = max(0.0, np.percentile(all_auc, p)) p = (alpha+((1.0-alpha)/2.0)) * 100 upper = min(1.0, np.percentile(all_auc, p)) # confidence interval print('%.1f%% AUC confidence interval %.1f%% and %.1f%%' % (alpha*100, lower*100, upper*100)) print("[MAIN] exiting...") return X_heldout = X[heldout_window_idx, ...] y_heldout = y[heldout_window_idx, ...] # make predictions on heldout subjects y_pred_heldout = final_model.predict(X_heldout) y_probs_heldout = final_model.predict_proba(X_heldout) # calculate metrics with leave-1-out sampling auc_patient_history, prec_history, recall_history, f1_history, bacc_history = collect_metrics_heldout(y_probs_test=y_probs_heldout, y_true_test=y_heldout, y_pred_test=y_pred_heldout, sample_indices_test = heldout_window_idx, _INDEX_DF=index_df, dataset=dataset) # confidence level alpha = 0.95 print("Report-------------------------------") print(f"heldout test patient AUROC: {np.mean(auc_patient_history):.3f}({np.std(auc_patient_history):.4f})") print(f"heldout test patient PRECISION: {np.mean(prec_history):.3f}({np.std(prec_history):.4f})") print(f"heldout test patient RECALL: {np.mean(recall_history):.3f}({np.std(recall_history):.4f})") print(f"heldout test patient F-1: {np.mean(f1_history):.3f}({np.std(f1_history):.4f})") print(f"heldout test patient BALANCED ACCURACY: {np.mean(bacc_history):.3f}({np.std(bacc_history):.4f})") # calculate interval percentile p = ((1.0-alpha)/2.0) * 100 lower = max(0.0, np.percentile(auc_patient_history, p)) p = (alpha+((1.0-alpha)/2.0)) * 100 upper = min(1.0, np.percentile(auc_patient_history, p)) # confidence interval print('%.1f%% AUC confidence interval %.2f%% and %.2f%%' % (alpha*100, lower*100, upper*100)) print("[MAIN] exiting...") return if __name__ == '__main__': parser = argparse.ArgumentParser(description="Execute evaluation pipeline using baseline PSD features.") parser.add_argument('--dataset', type=str, help="choose between tuh and lemon") parser.add_argument('--task', type=str, help="choose from ...") args = parser.parse_args() dataset = args.dataset _TASK = args.task # load dataset indices if dataset == "lemon": _INDEX_PATH = "../resources/lemon_window_index.csv" _INDEX_DF = pd.read_csv(_INDEX_PATH) elif dataset == "tuh": _INDEX_PATH = "../resources/abnormal_corpus_window_index.csv" _INDEX_DF = pd.read_csv(_INDEX_PATH) _INDEX_DF['parsed_age_binary'] = _INDEX_DF['parsed_age'].map(_map_age) else: raise ValueError("unknown dataset") # ensure reproducibility of results _RANDOM_SEED = 42 np.random.seed(_RANDOM_SEED) print(f"Numpy seed set to {_RANDOM_SEED} for reproducibility.") _eval_downstream_task(_INDEX_DF, dataset, _TASK)
[ "sklearn.metrics.balanced_accuracy_score", "pandas.read_csv", "sklearn.metrics.classification_report", "sklearn.metrics.precision_score", "sklearn.metrics.recall_score", "sklearn.metrics.roc_auc_score", "sklearn.metrics.roc_curve", "numpy.mean", "argparse.ArgumentParser", "numpy.delete", "numpy....
[((1211, 1229), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {}), '(rows)\n', (1223, 1229), True, 'import pandas as pd\n'), ((1355, 1403), 'utils.get_patient_prediction', 'get_patient_prediction', (['test_patient_df', 'dataset'], {}), '(test_patient_df, dataset)\n', (1377, 1403), False, 'from utils import _get_subject_level_split, _map_age, get_patient_prediction\n'), ((4732, 4795), 'utils._get_subject_level_split', '_get_subject_level_split', (['index_df', '_RANDOM_SEED', 'dataset', 'task'], {}), '(index_df, _RANDOM_SEED, dataset, task)\n', (4756, 4795), False, 'from utils import _get_subject_level_split, _map_age, get_patient_prediction\n'), ((4838, 4871), 'numpy.unique', 'np.unique', (['y'], {'return_inverse': '(True)'}), '(y, return_inverse=True)\n', (4847, 4871), True, 'import numpy as np\n'), ((5083, 5175), 'joblib.load', 'joblib.load', (['f"""../resources/finetuned_models/{dataset}_{task}_linear.pkl"""'], {'mmap_mode': '"""r"""'}), "(f'../resources/finetuned_models/{dataset}_{task}_linear.pkl',\n mmap_mode='r')\n", (5094, 5175), False, 'import joblib\n'), ((9246, 9346), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Execute evaluation pipeline using baseline PSD features."""'}), "(description=\n 'Execute evaluation pipeline using baseline PSD features.')\n", (9269, 9346), False, 'import argparse\n'), ((10005, 10033), 'numpy.random.seed', 'np.random.seed', (['_RANDOM_SEED'], {}), '(_RANDOM_SEED)\n', (10019, 10033), True, 'import numpy as np\n'), ((1597, 1626), 'numpy.copy', 'np.copy', (['y_probs_test_patient'], {}), '(y_probs_test_patient)\n', (1604, 1626), True, 'import numpy as np\n'), ((1638, 1666), 'numpy.delete', 'np.delete', (['y_prob', 'i'], {'axis': '(0)'}), '(y_prob, i, axis=0)\n', (1647, 1666), True, 'import numpy as np\n'), ((1681, 1709), 'numpy.copy', 'np.copy', (['y_true_test_patient'], {}), '(y_true_test_patient)\n', (1688, 1709), True, 'import numpy as np\n'), ((1723, 1745), 'numpy.delete', 'np.delete', (['y_true_s', 'i'], {}), '(y_true_s, i)\n', (1732, 1745), True, 'import numpy as np\n'), ((1999, 2045), 'sklearn.metrics.roc_curve', 'roc_curve', (['y_true_s', 'y_prob[:, 1]'], {'pos_label': '(1)'}), '(y_true_s, y_prob[:, 1], pos_label=1)\n', (2008, 2045), False, 'from sklearn.metrics import balanced_accuracy_score, classification_report, f1_score, precision_score, recall_score, roc_auc_score, roc_curve\n'), ((2683, 2738), 'sklearn.metrics.precision_score', 'precision_score', (['y_true_s', 'roc_predictions'], {'pos_label': '(1)'}), '(y_true_s, roc_predictions, pos_label=1)\n', (2698, 2738), False, 'from sklearn.metrics import balanced_accuracy_score, classification_report, f1_score, precision_score, recall_score, roc_auc_score, roc_curve\n'), ((2764, 2816), 'sklearn.metrics.recall_score', 'recall_score', (['y_true_s', 'roc_predictions'], {'pos_label': '(1)'}), '(y_true_s, roc_predictions, pos_label=1)\n', (2776, 2816), False, 'from sklearn.metrics import balanced_accuracy_score, classification_report, f1_score, precision_score, recall_score, roc_auc_score, roc_curve\n'), ((2837, 2885), 'sklearn.metrics.f1_score', 'f1_score', (['y_true_s', 'roc_predictions'], {'pos_label': '(1)'}), '(y_true_s, roc_predictions, pos_label=1)\n', (2845, 2885), False, 'from sklearn.metrics import balanced_accuracy_score, classification_report, f1_score, precision_score, recall_score, roc_auc_score, roc_curve\n'), ((2911, 2961), 'sklearn.metrics.balanced_accuracy_score', 'balanced_accuracy_score', (['y_true_s', 'roc_predictions'], {}), '(y_true_s, roc_predictions)\n', (2934, 2961), False, 'from sklearn.metrics import balanced_accuracy_score, classification_report, f1_score, precision_score, recall_score, roc_auc_score, roc_curve\n'), ((3010, 3047), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_true_s', 'y_prob[:, 1]'], {}), '(y_true_s, y_prob[:, 1])\n', (3023, 3047), False, 'from sklearn.metrics import balanced_accuracy_score, classification_report, f1_score, precision_score, recall_score, roc_auc_score, roc_curve\n'), ((8918, 8955), 'numpy.percentile', 'np.percentile', (['auc_patient_history', 'p'], {}), '(auc_patient_history, p)\n', (8931, 8955), True, 'import numpy as np\n'), ((9012, 9049), 'numpy.percentile', 'np.percentile', (['auc_patient_history', 'p'], {}), '(auc_patient_history, p)\n', (9025, 9049), True, 'import numpy as np\n'), ((9677, 9701), 'pandas.read_csv', 'pd.read_csv', (['_INDEX_PATH'], {}), '(_INDEX_PATH)\n', (9688, 9701), True, 'import pandas as pd\n'), ((3414, 3475), 'numpy.load', 'np.load', (['f"""../resources/psd_bandpower_relative_{dataset}.npy"""'], {}), "(f'../resources/psd_bandpower_relative_{dataset}.npy')\n", (3421, 3475), True, 'import numpy as np\n'), ((5432, 5457), 'numpy.copy', 'np.copy', (['heldout_subjects'], {}), '(heldout_subjects)\n', (5439, 5457), True, 'import numpy as np\n'), ((5489, 5528), 'numpy.delete', 'np.delete', (['heldout_subjects_resample', 'i'], {}), '(heldout_subjects_resample, i)\n', (5498, 5528), True, 'import numpy as np\n'), ((7416, 7441), 'numpy.percentile', 'np.percentile', (['all_auc', 'p'], {}), '(all_auc, p)\n', (7429, 7441), True, 'import numpy as np\n'), ((7500, 7525), 'numpy.percentile', 'np.percentile', (['all_auc', 'p'], {}), '(all_auc, p)\n', (7513, 7525), True, 'import numpy as np\n'), ((9804, 9828), 'pandas.read_csv', 'pd.read_csv', (['_INDEX_PATH'], {}), '(_INDEX_PATH)\n', (9815, 9828), True, 'import pandas as pd\n'), ((6524, 6574), 'sklearn.metrics.balanced_accuracy_score', 'balanced_accuracy_score', (['y_heldout', 'y_pred_heldout'], {}), '(y_heldout, y_pred_heldout)\n', (6547, 6574), False, 'from sklearn.metrics import balanced_accuracy_score, classification_report, f1_score, precision_score, recall_score, roc_auc_score, roc_curve\n'), ((6588, 6654), 'sklearn.metrics.classification_report', 'classification_report', (['y_heldout', 'y_pred_heldout'], {'output_dict': '(True)'}), '(y_heldout, y_pred_heldout, output_dict=True)\n', (6609, 6654), False, 'from sklearn.metrics import balanced_accuracy_score, classification_report, f1_score, precision_score, recall_score, roc_auc_score, roc_curve\n'), ((8371, 8399), 'numpy.mean', 'np.mean', (['auc_patient_history'], {}), '(auc_patient_history)\n', (8378, 8399), True, 'import numpy as np\n'), ((8406, 8433), 'numpy.std', 'np.std', (['auc_patient_history'], {}), '(auc_patient_history)\n', (8412, 8433), True, 'import numpy as np\n'), ((8484, 8505), 'numpy.mean', 'np.mean', (['prec_history'], {}), '(prec_history)\n', (8491, 8505), True, 'import numpy as np\n'), ((8512, 8532), 'numpy.std', 'np.std', (['prec_history'], {}), '(prec_history)\n', (8518, 8532), True, 'import numpy as np\n'), ((8580, 8603), 'numpy.mean', 'np.mean', (['recall_history'], {}), '(recall_history)\n', (8587, 8603), True, 'import numpy as np\n'), ((8610, 8632), 'numpy.std', 'np.std', (['recall_history'], {}), '(recall_history)\n', (8616, 8632), True, 'import numpy as np\n'), ((8677, 8696), 'numpy.mean', 'np.mean', (['f1_history'], {}), '(f1_history)\n', (8684, 8696), True, 'import numpy as np\n'), ((8703, 8721), 'numpy.std', 'np.std', (['f1_history'], {}), '(f1_history)\n', (8709, 8721), True, 'import numpy as np\n'), ((8780, 8801), 'numpy.mean', 'np.mean', (['bacc_history'], {}), '(bacc_history)\n', (8787, 8801), True, 'import numpy as np\n'), ((8808, 8828), 'numpy.std', 'np.std', (['bacc_history'], {}), '(bacc_history)\n', (8814, 8828), True, 'import numpy as np\n'), ((6950, 6966), 'numpy.mean', 'np.mean', (['all_auc'], {}), '(all_auc)\n', (6957, 6966), True, 'import numpy as np\n'), ((6973, 6988), 'numpy.std', 'np.std', (['all_auc'], {}), '(all_auc)\n', (6979, 6988), True, 'import numpy as np\n'), ((7032, 7049), 'numpy.mean', 'np.mean', (['all_prec'], {}), '(all_prec)\n', (7039, 7049), True, 'import numpy as np\n'), ((7056, 7072), 'numpy.std', 'np.std', (['all_prec'], {}), '(all_prec)\n', (7062, 7072), True, 'import numpy as np\n'), ((7113, 7132), 'numpy.mean', 'np.mean', (['all_recall'], {}), '(all_recall)\n', (7120, 7132), True, 'import numpy as np\n'), ((7139, 7157), 'numpy.std', 'np.std', (['all_recall'], {}), '(all_recall)\n', (7145, 7157), True, 'import numpy as np\n'), ((7195, 7210), 'numpy.mean', 'np.mean', (['all_f1'], {}), '(all_f1)\n', (7202, 7210), True, 'import numpy as np\n'), ((7217, 7231), 'numpy.std', 'np.std', (['all_f1'], {}), '(all_f1)\n', (7223, 7231), True, 'import numpy as np\n'), ((7283, 7300), 'numpy.mean', 'np.mean', (['all_bacc'], {}), '(all_bacc)\n', (7290, 7300), True, 'import numpy as np\n'), ((7307, 7323), 'numpy.std', 'np.std', (['all_bacc'], {}), '(all_bacc)\n', (7313, 7323), True, 'import numpy as np\n'), ((2411, 2428), 'numpy.abs', 'np.abs', (['(tpr - fpr)'], {}), '(tpr - fpr)\n', (2417, 2428), True, 'import numpy as np\n')]
import numpy as np from numba import njit, prange # consav from consav import linear_interp # for linear interpolation from consav import golden_section_search # for optimization in 1D # local modules import utility # a. define objective function @njit def obj_bellman(c,m,interp_w,par): """ evaluate bellman equation """ # a. end-of-period assets a = m-c # b. continuation value w = linear_interp.interp_1d(par.grid_a,interp_w,a) # c. total value value_of_choice = utility.func(c,par) + w return -value_of_choice # we are minimizing # b. solve bellman equation @njit(parallel=True) def solve_bellman(t,sol,par): """solve bellman equation using nvfi""" # unpack (this helps numba optimize) v = sol.v[t] c = sol.c[t] # loop over outer states for ip in prange(par.Np): # in parallel # loop over cash-on-hand for im in range(par.Nm): # a. cash-on-hand m = par.grid_m[im] # b. optimal choice c_low = np.fmin(m/2,1e-8) c_high = m c[ip,im] = golden_section_search.optimizer(obj_bellman,c_low,c_high,args=(m,sol.w[ip],par),tol=par.tol) # note: the above finds the minimum of obj_bellman in range [c_low,c_high] with a tolerance of par.tol # and arguments (except for c) as specified # c. optimal value v[ip,im] = -obj_bellman(c[ip,im],m,sol.w[ip],par)
[ "consav.golden_section_search.optimizer", "numba.njit", "numpy.fmin", "numba.prange", "consav.linear_interp.interp_1d", "utility.func" ]
[((616, 635), 'numba.njit', 'njit', ([], {'parallel': '(True)'}), '(parallel=True)\n', (620, 635), False, 'from numba import njit, prange\n'), ((414, 462), 'consav.linear_interp.interp_1d', 'linear_interp.interp_1d', (['par.grid_a', 'interp_w', 'a'], {}), '(par.grid_a, interp_w, a)\n', (437, 462), False, 'from consav import linear_interp\n'), ((830, 844), 'numba.prange', 'prange', (['par.Np'], {}), '(par.Np)\n', (836, 844), False, 'from numba import njit, prange\n'), ((505, 525), 'utility.func', 'utility.func', (['c', 'par'], {}), '(c, par)\n', (517, 525), False, 'import utility\n'), ((1054, 1075), 'numpy.fmin', 'np.fmin', (['(m / 2)', '(1e-08)'], {}), '(m / 2, 1e-08)\n', (1061, 1075), True, 'import numpy as np\n'), ((1118, 1221), 'consav.golden_section_search.optimizer', 'golden_section_search.optimizer', (['obj_bellman', 'c_low', 'c_high'], {'args': '(m, sol.w[ip], par)', 'tol': 'par.tol'}), '(obj_bellman, c_low, c_high, args=(m, sol.w[\n ip], par), tol=par.tol)\n', (1149, 1221), False, 'from consav import golden_section_search\n')]
import numpy as np import random def random_sys(size=1): if size > 1: rd = [] for i in range(size): rd.append(random.random()) rd = np.array(rd, dtype=np.float32) return rd else: return random.random() def rand(a=0., b=1.): """ 随机变化比例 :param a: 变化随机值下限 :param b: 变化范围的上限 :return: """ return random_sys() * (b - a) + a def select(position, keep_num=16): num = position[0].shape[0] if num <= keep_num: return position, num, [] slt = np.arange(num) random.shuffle(slt) slt = slt[:keep_num] return tuple(p[slt] for p in position), keep_num, slt
[ "numpy.array", "random.random", "random.shuffle", "numpy.arange" ]
[((578, 592), 'numpy.arange', 'np.arange', (['num'], {}), '(num)\n', (587, 592), True, 'import numpy as np\n'), ((598, 617), 'random.shuffle', 'random.shuffle', (['slt'], {}), '(slt)\n', (612, 617), False, 'import random\n'), ((187, 217), 'numpy.array', 'np.array', (['rd'], {'dtype': 'np.float32'}), '(rd, dtype=np.float32)\n', (195, 217), True, 'import numpy as np\n'), ((264, 279), 'random.random', 'random.random', ([], {}), '()\n', (277, 279), False, 'import random\n'), ((156, 171), 'random.random', 'random.random', ([], {}), '()\n', (169, 171), False, 'import random\n')]
import numpy as np import scipy.signal import torch import torch.nn as nn from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence def combined_shape(length, shape=None): if shape is None: return (length,) return (length, shape) if np.isscalar(shape) else (length, *shape) def mlp(sizes, activation, output_activation=nn.Identity): layers = [] for j in range(len(sizes)-1): act = activation if j < len(sizes)-2 else output_activation layers += [nn.Linear(sizes[j], sizes[j+1]), act()] return nn.Sequential(*layers) def count_vars(module): return sum([np.prod(p.shape) for p in module.parameters()]) class MLPActor(nn.Module): def __init__(self, obs_dim, act_dim, hidden_sizes, activation, act_limit): super().__init__() pi_sizes = [obs_dim] + list(hidden_sizes) + [act_dim] self.pi = mlp(pi_sizes, activation, nn.Tanh) self.act_limit = act_limit def forward(self, obs): # Return output from network scaled to action space limits. return self.act_limit * self.pi(obs) class MLPQFunction(nn.Module): def __init__(self, obs_dim, act_dim, hidden_sizes, activation): super().__init__() self.q = mlp([obs_dim + act_dim] + list(hidden_sizes) + [1], activation) def forward(self, obs, act): q = self.q(torch.cat([obs, act], dim=-1)) return torch.squeeze(q, -1) # Critical to ensure q has right shape. class MLPActorCritic(nn.Module): def __init__(self, observation_space, action_space, hidden_sizes=(256,256), activation=nn.ReLU): super().__init__() obs_dim = observation_space.shape[0] act_dim = action_space.shape[0] act_limit = action_space.high[0] # build policy and value functions self.pi = MLPActor(obs_dim, act_dim, hidden_sizes, activation, act_limit) self.q = MLPQFunction(obs_dim, act_dim, hidden_sizes, activation) def act(self, obs): with torch.no_grad(): return self.pi(obs).numpy() class LSTMActor(nn.Module): def __init__(self, obs_dim, act_dim, act_limit, lstm_hidden_dim=128, lstm_hidden_num_layers=2, fc_hidden_sizes=(256,)): super().__init__() self.obs_dim = obs_dim self.act_dim = act_dim self.act_limit = act_limit # LSTM layers self.lstm_hidden_dim = lstm_hidden_dim self.lstm_hidden_num_layers = lstm_hidden_num_layers self.lstm = nn.LSTM(obs_dim, self.lstm_hidden_dim, self.lstm_hidden_num_layers, batch_first=True) # Fully connected layers self.fc_layers = [] self.fc_hidden_sizes = [self.lstm_hidden_dim] + list(fc_hidden_sizes) for j in range(len(self.fc_hidden_sizes) - 1): self.fc_layers += [nn.Linear(self.fc_hidden_sizes[j], self.fc_hidden_sizes[j + 1]), nn.ReLU()] # Output layer self.out_layer = [nn.Linear(self.fc_hidden_sizes[-1], self.act_dim), nn.Tanh()] def forward(self, obs, seg_len=None): # LSTM layers if seg_len is not None: obs_packed = pack_padded_sequence(obs, lengths=seg_len, batch_first=True, enforce_sorted=False) else: obs_packed = pack_padded_sequence(obs, lengths=[obs.size(1) for _ in range(obs.size(0))], batch_first=True, enforce_sorted=False) lstm_output_packed, (lstm_hidden_state, lstm_cell_state) = self.lstm(obs_packed) lstm_output_padded, lstm_output_lengths = pad_packed_sequence(lstm_output_packed, batch_first=True) # Fully connected layers fc_output = lstm_output_padded for fc_l in self.fc_layers: fc_output = fc_l(fc_output) # Return output from network scaled to action space limits. output = fc_output for out_l in self.out_layer: output = out_l(output) return self.act_limit * output class LSTMQFunction(nn.Module): def __init__(self, obs_dim, act_dim, lstm_hidden_dim=128, lstm_hidden_num_layers=2, fc_hidden_sizes=(256,)): super().__init__() self.obs_dim = obs_dim self.act_dim = act_dim # LSTM layers self.lstm_hidden_dim = lstm_hidden_dim self.lstm_hidden_num_layers = lstm_hidden_num_layers self.lstm_layer = nn.LSTM(obs_dim+act_dim, self.lstm_hidden_dim, self.lstm_hidden_num_layers, batch_first=True) # Fully connected layers self.fc_layers = [] self.fc_hidden_sizes = [self.lstm_hidden_dim] + list(fc_hidden_sizes) for j in range(len(self.fc_hidden_sizes) - 1): self.fc_layers += [nn.Linear(self.fc_hidden_sizes[j], self.fc_hidden_sizes[j + 1]), nn.ReLU()] # Output layer self.out_layer = [nn.Linear(self.fc_hidden_sizes[-1], 1), nn.Identity()] # self.layers = nn.ModuleList() # self.layers += [self.lstm_layer] + self.fc_layers + self.out_layer def forward(self, obs, act, seg_len=None): # LSTM layers cat_input = torch.cat([obs, act], dim=-1) if seg_len is not None: input_packed = pack_padded_sequence(cat_input, lengths=seg_len, batch_first=True, enforce_sorted=False) else: input_packed = pack_padded_sequence(cat_input, lengths=[cat_input.size(1) for _ in range(cat_input.size(0))], batch_first=True, enforce_sorted=False) lstm_output_packed, (lstm_hidden_state, lstm_cell_state) = self.lstm_layer(input_packed) lstm_output_padded, lstm_output_lengths = pad_packed_sequence(lstm_output_packed, batch_first=True) # Fully connected layers fc_output = lstm_output_padded for fc_l in self.fc_layers: fc_output = fc_l(fc_output) output = fc_output for out_l in self.out_layer: output = out_l(output) return output class LSTMActorCritic(nn.Module): def __init__(self, obs_dim, act_dim, act_limit): super().__init__() # build policy and value functions self.pi = LSTMActor(obs_dim, act_dim, act_limit, lstm_hidden_dim=128, lstm_hidden_num_layers=2, fc_hidden_sizes=(256,)) self.q = LSTMQFunction(obs_dim, act_dim, lstm_hidden_dim=128, lstm_hidden_num_layers=2, fc_hidden_sizes=(256,)) def act(self, obs): with torch.no_grad(): return self.pi(obs).numpy()
[ "numpy.prod", "torch.nn.ReLU", "numpy.isscalar", "torch.nn.Tanh", "torch.nn.Sequential", "torch.nn.LSTM", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.Linear", "torch.squeeze", "torch.no_grad", "torch.nn.Identity", "torch.nn.utils.rnn.pad_packed_sequence", "torch.cat" ]
[((570, 592), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (583, 592), True, 'import torch.nn as nn\n'), ((281, 299), 'numpy.isscalar', 'np.isscalar', (['shape'], {}), '(shape)\n', (292, 299), True, 'import numpy as np\n'), ((1417, 1437), 'torch.squeeze', 'torch.squeeze', (['q', '(-1)'], {}), '(q, -1)\n', (1430, 1437), False, 'import torch\n'), ((2525, 2614), 'torch.nn.LSTM', 'nn.LSTM', (['obs_dim', 'self.lstm_hidden_dim', 'self.lstm_hidden_num_layers'], {'batch_first': '(True)'}), '(obs_dim, self.lstm_hidden_dim, self.lstm_hidden_num_layers,\n batch_first=True)\n', (2532, 2614), True, 'import torch.nn as nn\n'), ((3569, 3626), 'torch.nn.utils.rnn.pad_packed_sequence', 'pad_packed_sequence', (['lstm_output_packed'], {'batch_first': '(True)'}), '(lstm_output_packed, batch_first=True)\n', (3588, 3626), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((4373, 4473), 'torch.nn.LSTM', 'nn.LSTM', (['(obs_dim + act_dim)', 'self.lstm_hidden_dim', 'self.lstm_hidden_num_layers'], {'batch_first': '(True)'}), '(obs_dim + act_dim, self.lstm_hidden_dim, self.\n lstm_hidden_num_layers, batch_first=True)\n', (4380, 4473), True, 'import torch.nn as nn\n'), ((5079, 5108), 'torch.cat', 'torch.cat', (['[obs, act]'], {'dim': '(-1)'}), '([obs, act], dim=-1)\n', (5088, 5108), False, 'import torch\n'), ((5677, 5734), 'torch.nn.utils.rnn.pad_packed_sequence', 'pad_packed_sequence', (['lstm_output_packed'], {'batch_first': '(True)'}), '(lstm_output_packed, batch_first=True)\n', (5696, 5734), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((519, 552), 'torch.nn.Linear', 'nn.Linear', (['sizes[j]', 'sizes[j + 1]'], {}), '(sizes[j], sizes[j + 1])\n', (528, 552), True, 'import torch.nn as nn\n'), ((634, 650), 'numpy.prod', 'np.prod', (['p.shape'], {}), '(p.shape)\n', (641, 650), True, 'import numpy as np\n'), ((1371, 1400), 'torch.cat', 'torch.cat', (['[obs, act]'], {'dim': '(-1)'}), '([obs, act], dim=-1)\n', (1380, 1400), False, 'import torch\n'), ((2023, 2038), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2036, 2038), False, 'import torch\n'), ((2961, 3010), 'torch.nn.Linear', 'nn.Linear', (['self.fc_hidden_sizes[-1]', 'self.act_dim'], {}), '(self.fc_hidden_sizes[-1], self.act_dim)\n', (2970, 3010), True, 'import torch.nn as nn\n'), ((3012, 3021), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (3019, 3021), True, 'import torch.nn as nn\n'), ((3145, 3232), 'torch.nn.utils.rnn.pack_padded_sequence', 'pack_padded_sequence', (['obs'], {'lengths': 'seg_len', 'batch_first': '(True)', 'enforce_sorted': '(False)'}), '(obs, lengths=seg_len, batch_first=True, enforce_sorted\n =False)\n', (3165, 3232), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((4817, 4855), 'torch.nn.Linear', 'nn.Linear', (['self.fc_hidden_sizes[-1]', '(1)'], {}), '(self.fc_hidden_sizes[-1], 1)\n', (4826, 4855), True, 'import torch.nn as nn\n'), ((4857, 4870), 'torch.nn.Identity', 'nn.Identity', ([], {}), '()\n', (4868, 4870), True, 'import torch.nn as nn\n'), ((5168, 5260), 'torch.nn.utils.rnn.pack_padded_sequence', 'pack_padded_sequence', (['cat_input'], {'lengths': 'seg_len', 'batch_first': '(True)', 'enforce_sorted': '(False)'}), '(cat_input, lengths=seg_len, batch_first=True,\n enforce_sorted=False)\n', (5188, 5260), False, 'from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\n'), ((6508, 6523), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6521, 6523), False, 'import torch\n'), ((2836, 2899), 'torch.nn.Linear', 'nn.Linear', (['self.fc_hidden_sizes[j]', 'self.fc_hidden_sizes[j + 1]'], {}), '(self.fc_hidden_sizes[j], self.fc_hidden_sizes[j + 1])\n', (2845, 2899), True, 'import torch.nn as nn\n'), ((2901, 2910), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (2908, 2910), True, 'import torch.nn as nn\n'), ((4692, 4755), 'torch.nn.Linear', 'nn.Linear', (['self.fc_hidden_sizes[j]', 'self.fc_hidden_sizes[j + 1]'], {}), '(self.fc_hidden_sizes[j], self.fc_hidden_sizes[j + 1])\n', (4701, 4755), True, 'import torch.nn as nn\n'), ((4757, 4766), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4764, 4766), True, 'import torch.nn as nn\n')]
import torch.nn as nn import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader from torch.utils.tensorboard import SummaryWriter import os import numpy as np import torch import sys from tqdm import tqdm from tqdm._utils import _term_move_up import time torch.manual_seed(0) np.random.seed(0) M1=48 N1=2 C1=16 H1=22 K1=7 M2=96 N2=48 C2=8 H2=12 K2=5 M3=4*4*60 C3=1 H3=1 K3=1 N4=4*4*40 N5=64 N6=4*4*40 N7=4*4*60 N8=4*4*96 N9=96 M9=48 K9=5 C9=4 N10=48 M10=96 K10=7 C10=8 def custom_fc(weight,bias,input0): output0=np.zeros([1,weight.shape[0],1,1]) for out_ch in range(weight.shape[0]): for in_ch in range(weight.shape[1]): output0[0,out_ch,0,0]+=input0[0,in_ch,0,0]*weight[out_ch,in_ch,0,0] for out_ch in range(weight.shape[0]): output0[0,out_ch,0,0]=np.tanh(bias[out_ch]+output0[0,out_ch,0,0]) return output0 def custom_deconv(weight, input0): return None class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv2d1=self.conv2d(N1,M1,K1) self.conv2d2=self.conv2d(N2,M2,K2) self.f1=self.conv2d(M2*C2//2*C2//2,M3,1) self.f2=self.conv2d(M3,N4,1) self.f3=self.conv2d(N4,N5,1) self.f4=self.conv2d(N5,N6,1) self.f5=self.conv2d(N6,N7,1) self.f6=self.conv2d(N7,N8,1) self.deconv2d1=self.deconv2d(N9,M9,K9) self.deconv2d2=self.deconv2d(N10,M10,K10) self.max1=nn.MaxPool2d(2, stride=2) self.upsample= nn.Upsample(scale_factor=2) self.f7=self.conv2d(M10*C10*C10*4,M10*C10*C10*4,1) def deconv2d(self,input_channel,output_channel,k): deconv2d_layers=[] deconv2d_layers.append(nn.ConvTranspose2d(input_channel, output_channel, k, 1,k//2)) deconv2d_layers.append(nn.Tanh()) return nn.Sequential(*deconv2d_layers) def conv2d(self,input_channel, output_channel, k): conv2d_layers=[] conv2d_layers.append(nn.Conv2d(input_channel,output_channel,k, padding=k//2,bias=True)) conv2d_layers.append(nn.Tanh()) #conv2d_layers.append(nn.BatchNorm2d(output_channel)) return nn.Sequential(*conv2d_layers) def forward(self, x): x =self.conv2d1(x) x =self.max1(x) x =self.conv2d2(x) x =self.max1(x) #print('input before') #print(x.data) x =x.view(1,M2*C2//2*C2//2,1,1) #print('input afterwards') #print(x.data) x =self.f1(x) x =self.f2(x) x =self.f3(x) x =self.f4(x) x =self.f5(x) x =self.f6(x) x =x.view(1,N9,C9,C9) x =self.deconv2d1(x) x =self.upsample(x) x =self.deconv2d2(x) x =self.upsample(x) x =x.view(1,M10*C10*C10*4,1,1) x =self.f7(x) #x =self.f3(x) return x test_x=np.random.rand(1,N1,C1,C1) test_x=test_x.astype(np.float32) net1=Net() # for name, param in net1.named_parameters(): # if param.requires_grad: # print (name, param.data) tensor_test_x= torch.tensor(test_x) start=time.time() tensor_output= net1(tensor_test_x) print(time.time()-start) test_output=tensor_output.data #with open("test_output.inc","w") as f: # for i in range(N4): # for j in range(1): # for k in range(1): # f.write(str(float(test_output[0][i][j][k]))+"\n\r") #test_x=np.random.rand(1,M2*C2//2*C2//2,1,1).astype('float32') #output0_from_torch=net1.f1(torch.tensor(test_x)) #output0=custom_fc(test_weight3,test_bias3,test_x) #print(output0_from_torch.data[0,11,0,0]) #print(output0[0,11,0,0])
[ "torch.nn.ConvTranspose2d", "torch.manual_seed", "numpy.random.rand", "torch.nn.Tanh", "torch.nn.Sequential", "numpy.tanh", "torch.nn.Conv2d", "torch.tensor", "numpy.zeros", "torch.nn.MaxPool2d", "numpy.random.seed", "torch.nn.Upsample", "time.time" ]
[((285, 305), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (302, 305), False, 'import torch\n'), ((310, 327), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (324, 327), True, 'import numpy as np\n'), ((2881, 2910), 'numpy.random.rand', 'np.random.rand', (['(1)', 'N1', 'C1', 'C1'], {}), '(1, N1, C1, C1)\n', (2895, 2910), True, 'import numpy as np\n'), ((3088, 3108), 'torch.tensor', 'torch.tensor', (['test_x'], {}), '(test_x)\n', (3100, 3108), False, 'import torch\n'), ((3115, 3126), 'time.time', 'time.time', ([], {}), '()\n', (3124, 3126), False, 'import time\n'), ((561, 597), 'numpy.zeros', 'np.zeros', (['[1, weight.shape[0], 1, 1]'], {}), '([1, weight.shape[0], 1, 1])\n', (569, 597), True, 'import numpy as np\n'), ((838, 886), 'numpy.tanh', 'np.tanh', (['(bias[out_ch] + output0[0, out_ch, 0, 0])'], {}), '(bias[out_ch] + output0[0, out_ch, 0, 0])\n', (845, 886), True, 'import numpy as np\n'), ((1476, 1501), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['(2)'], {'stride': '(2)'}), '(2, stride=2)\n', (1488, 1501), True, 'import torch.nn as nn\n'), ((1525, 1552), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2)'}), '(scale_factor=2)\n', (1536, 1552), True, 'import torch.nn as nn\n'), ((1844, 1875), 'torch.nn.Sequential', 'nn.Sequential', (['*deconv2d_layers'], {}), '(*deconv2d_layers)\n', (1857, 1875), True, 'import torch.nn as nn\n'), ((2169, 2198), 'torch.nn.Sequential', 'nn.Sequential', (['*conv2d_layers'], {}), '(*conv2d_layers)\n', (2182, 2198), True, 'import torch.nn as nn\n'), ((3170, 3181), 'time.time', 'time.time', ([], {}), '()\n', (3179, 3181), False, 'import time\n'), ((1725, 1788), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['input_channel', 'output_channel', 'k', '(1)', '(k // 2)'], {}), '(input_channel, output_channel, k, 1, k // 2)\n', (1743, 1788), True, 'import torch.nn as nn\n'), ((1818, 1827), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (1825, 1827), True, 'import torch.nn as nn\n'), ((1985, 2055), 'torch.nn.Conv2d', 'nn.Conv2d', (['input_channel', 'output_channel', 'k'], {'padding': '(k // 2)', 'bias': '(True)'}), '(input_channel, output_channel, k, padding=k // 2, bias=True)\n', (1994, 2055), True, 'import torch.nn as nn\n'), ((2081, 2090), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (2088, 2090), True, 'import torch.nn as nn\n')]
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse from collections import deque from unityagents import UnityEnvironment import matplotlib.pyplot as plt import numpy as np import torch from agent import ActorCriticAgent from env import ContinuousUnityAgentEnvironment def ddpg_train(n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.995, seed=7, plot=True): """Train DDPG agent.""" # Step environment and agent. print('TRAINING DDPG') env = ContinuousUnityAgentEnvironment( './Reacher_Windows_x86_64/Reacher.exe', True) state_size, action_size, n_agents = env.info() agent = ActorCriticAgent(state_size, n_agents, action_size, 4) scores = [] scores_window = deque(maxlen=100) n_episodes = 1000 for i_episode in range(n_episodes): states = env.reset() agent.reset() # reset noise score = np.zeros(n_agents) while True: actions = agent.act(states) next_states, rewards, dones = env.step(actions) agent.step(states, actions, rewards, next_states, dones) score += rewards states = next_states if np.any(dones): break agent.checkpoint() scores.append(np.mean(score)) scores_window.append(np.mean(score)) print('\rEpisode: \t{} \tScore: \t{:.2f} \tAverage Score: \t{:.2f}'.format(i_episode, np.mean(score), np.mean(scores_window)), end="") if i_episode % 100 == 0: print('\rEpisode {}\tAverage Score: {:.2f}'.format( \ i_episode, np.mean(scores_window))) # Stopping condition if np.mean(scores_window) >= 30.0: print('\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window))) break plot_scores('Training Scores', scores) return agent def ddpg_test(): """Test a trained DDPG agent.""" print('TESTING DDPG') env = ContinuousUnityAgentEnvironment( './Reacher_Windows_x86_64/Reacher.exe', False) state_size, action_size, n_agents = env.info() agent = ActorCriticAgent(state_size, n_agents, action_size, 4) for episode in range(3): states = env.reset() score = np.zeros(n_agents) while True: actions = agent.act(states, add_noise=False) next_states, rewards, dones = env.step(actions) score += rewards states = next_states if np.any(dones): break print('Episode: \t{} \tScore: \t{:.2f}'.format(episode, np.mean(score))) def plot_scores(title, scores): plt.title(title) plt.title('DDPG', loc='left') plt.plot(np.arange(1, len(scores) + 1), scores) plt.ylabel('Score') plt.xlabel('Episode #') plt.show() def main(): """Entry point of program.""" # Argument parsing parser = argparse.ArgumentParser(description='Train and test a DQN agent.') parser.add_argument('--train', help='Train the agent.', \ action='store_true') parser.add_argument('--test', help='Test the agent.', \ action='store_true') args = parser.parse_args() if args.train: _ = ddpg_train() if args.test: ddpg_test() if __name__ == '__main__': main()
[ "numpy.mean", "collections.deque", "argparse.ArgumentParser", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.any", "numpy.zeros", "env.ContinuousUnityAgentEnvironment", "agent.ActorCriticAgent", "matplotlib.pyplot.title", "matplotlib.pyplot.show" ]
[((505, 582), 'env.ContinuousUnityAgentEnvironment', 'ContinuousUnityAgentEnvironment', (['"""./Reacher_Windows_x86_64/Reacher.exe"""', '(True)'], {}), "('./Reacher_Windows_x86_64/Reacher.exe', True)\n", (536, 582), False, 'from env import ContinuousUnityAgentEnvironment\n'), ((655, 709), 'agent.ActorCriticAgent', 'ActorCriticAgent', (['state_size', 'n_agents', 'action_size', '(4)'], {}), '(state_size, n_agents, action_size, 4)\n', (671, 709), False, 'from agent import ActorCriticAgent\n'), ((746, 763), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (751, 763), False, 'from collections import deque\n'), ((2027, 2105), 'env.ContinuousUnityAgentEnvironment', 'ContinuousUnityAgentEnvironment', (['"""./Reacher_Windows_x86_64/Reacher.exe"""', '(False)'], {}), "('./Reacher_Windows_x86_64/Reacher.exe', False)\n", (2058, 2105), False, 'from env import ContinuousUnityAgentEnvironment\n'), ((2178, 2232), 'agent.ActorCriticAgent', 'ActorCriticAgent', (['state_size', 'n_agents', 'action_size', '(4)'], {}), '(state_size, n_agents, action_size, 4)\n', (2194, 2232), False, 'from agent import ActorCriticAgent\n'), ((2695, 2711), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2704, 2711), True, 'import matplotlib.pyplot as plt\n'), ((2716, 2745), 'matplotlib.pyplot.title', 'plt.title', (['"""DDPG"""'], {'loc': '"""left"""'}), "('DDPG', loc='left')\n", (2725, 2745), True, 'import matplotlib.pyplot as plt\n'), ((2802, 2821), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Score"""'], {}), "('Score')\n", (2812, 2821), True, 'import matplotlib.pyplot as plt\n'), ((2826, 2849), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode #"""'], {}), "('Episode #')\n", (2836, 2849), True, 'import matplotlib.pyplot as plt\n'), ((2854, 2864), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2862, 2864), True, 'import matplotlib.pyplot as plt\n'), ((2948, 3014), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train and test a DQN agent."""'}), "(description='Train and test a DQN agent.')\n", (2971, 3014), False, 'import argparse\n'), ((907, 925), 'numpy.zeros', 'np.zeros', (['n_agents'], {}), '(n_agents)\n', (915, 925), True, 'import numpy as np\n'), ((2307, 2325), 'numpy.zeros', 'np.zeros', (['n_agents'], {}), '(n_agents)\n', (2315, 2325), True, 'import numpy as np\n'), ((1192, 1205), 'numpy.any', 'np.any', (['dones'], {}), '(dones)\n', (1198, 1205), True, 'import numpy as np\n'), ((1278, 1292), 'numpy.mean', 'np.mean', (['score'], {}), '(score)\n', (1285, 1292), True, 'import numpy as np\n'), ((1323, 1337), 'numpy.mean', 'np.mean', (['score'], {}), '(score)\n', (1330, 1337), True, 'import numpy as np\n'), ((1701, 1723), 'numpy.mean', 'np.mean', (['scores_window'], {}), '(scores_window)\n', (1708, 1723), True, 'import numpy as np\n'), ((2540, 2553), 'numpy.any', 'np.any', (['dones'], {}), '(dones)\n', (2546, 2553), True, 'import numpy as np\n'), ((1433, 1447), 'numpy.mean', 'np.mean', (['score'], {}), '(score)\n', (1440, 1447), True, 'import numpy as np\n'), ((1449, 1471), 'numpy.mean', 'np.mean', (['scores_window'], {}), '(scores_window)\n', (1456, 1471), True, 'import numpy as np\n'), ((2641, 2655), 'numpy.mean', 'np.mean', (['score'], {}), '(score)\n', (2648, 2655), True, 'import numpy as np\n'), ((1636, 1658), 'numpy.mean', 'np.mean', (['scores_window'], {}), '(scores_window)\n', (1643, 1658), True, 'import numpy as np\n'), ((1833, 1855), 'numpy.mean', 'np.mean', (['scores_window'], {}), '(scores_window)\n', (1840, 1855), True, 'import numpy as np\n')]
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from typing import Any from typing import Dict from typing import List from typing import Optional import numpy as np import paddle from paddle import nn from paddle.nn import functional as F class Stretch2D(nn.Layer): def __init__(self, w_scale: int, h_scale: int, mode: str="nearest"): """Strech an image (or image-like object) with some interpolation. Parameters ---------- w_scale : int Scalar of width. h_scale : int Scalar of the height. mode : str, optional Interpolation mode, modes suppored are "nearest", "bilinear", "trilinear", "bicubic", "linear" and "area",by default "nearest" For more details about interpolation, see `paddle.nn.functional.interpolate <https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/nn/functional/interpolate_en.html>`_. """ super().__init__() self.w_scale = w_scale self.h_scale = h_scale self.mode = mode def forward(self, x): """ Parameters ---------- x : Tensor Shape (N, C, H, W) Returns ------- Tensor Shape (N, C, H', W'), where ``H'=h_scale * H``, ``W'=w_scale * W``. The stretched image. """ out = F.interpolate( x, scale_factor=(self.h_scale, self.w_scale), mode=self.mode) return out class UpsampleNet(nn.Layer): """A Layer to upsample spectrogram by applying consecutive stretch and convolutions. Parameters ---------- upsample_scales : List[int] Upsampling factors for each strech. nonlinear_activation : Optional[str], optional Activation after each convolution, by default None nonlinear_activation_params : Dict[str, Any], optional Parameters passed to construct the activation, by default {} interpolate_mode : str, optional Interpolation mode of the strech, by default "nearest" freq_axis_kernel_size : int, optional Convolution kernel size along the frequency axis, by default 1 use_causal_conv : bool, optional Whether to use causal padding before convolution, by default False If True, Causal padding is used along the time axis, i.e. padding amount is ``receptive field - 1`` and 0 for before and after, respectively. If False, "same" padding is used along the time axis. """ def __init__(self, upsample_scales: List[int], nonlinear_activation: Optional[str]=None, nonlinear_activation_params: Dict[str, Any]={}, interpolate_mode: str="nearest", freq_axis_kernel_size: int=1, use_causal_conv: bool=False): super().__init__() self.use_causal_conv = use_causal_conv self.up_layers = nn.LayerList() for scale in upsample_scales: stretch = Stretch2D(scale, 1, interpolate_mode) assert freq_axis_kernel_size % 2 == 1 freq_axis_padding = (freq_axis_kernel_size - 1) // 2 kernel_size = (freq_axis_kernel_size, scale * 2 + 1) if use_causal_conv: padding = (freq_axis_padding, scale * 2) else: padding = (freq_axis_padding, scale) conv = nn.Conv2D( 1, 1, kernel_size, padding=padding, bias_attr=False) self.up_layers.extend([stretch, conv]) if nonlinear_activation is not None: nonlinear = getattr( nn, nonlinear_activation)(**nonlinear_activation_params) self.up_layers.append(nonlinear) def forward(self, c): """ Parameters ---------- c : Tensor Shape (N, F, T), spectrogram Returns ------- Tensor Shape (N, F, T'), where ``T' = upsample_factor * T``, upsampled spectrogram """ c = c.unsqueeze(1) for f in self.up_layers: if self.use_causal_conv and isinstance(f, nn.Conv2D): c = f(c)[:, :, :, c.shape[-1]] else: c = f(c) return c.squeeze(1) class ConvInUpsampleNet(nn.Layer): """A Layer to upsample spectrogram composed of a convolution and an UpsampleNet. Parameters ---------- upsample_scales : List[int] Upsampling factors for each strech. nonlinear_activation : Optional[str], optional Activation after each convolution, by default None nonlinear_activation_params : Dict[str, Any], optional Parameters passed to construct the activation, by default {} interpolate_mode : str, optional Interpolation mode of the strech, by default "nearest" freq_axis_kernel_size : int, optional Convolution kernel size along the frequency axis, by default 1 aux_channels : int, optional Feature size of the input, by default 80 aux_context_window : int, optional Context window of the first 1D convolution applied to the input. It related to the kernel size of the convolution, by default 0 If use causal convolution, the kernel size is ``window + 1``, else the kernel size is ``2 * window + 1``. use_causal_conv : bool, optional Whether to use causal padding before convolution, by default False If True, Causal padding is used along the time axis, i.e. padding amount is ``receptive field - 1`` and 0 for before and after, respectively. If False, "same" padding is used along the time axis. """ def __init__(self, upsample_scales: List[int], nonlinear_activation: Optional[str]=None, nonlinear_activation_params: Dict[str, Any]={}, interpolate_mode: str="nearest", freq_axis_kernel_size: int=1, aux_channels: int=80, aux_context_window: int=0, use_causal_conv: bool=False): super().__init__() self.aux_context_window = aux_context_window self.use_causal_conv = use_causal_conv and aux_context_window > 0 kernel_size = aux_context_window + 1 if use_causal_conv else 2 * aux_context_window + 1 self.conv_in = nn.Conv1D( aux_channels, aux_channels, kernel_size=kernel_size, bias_attr=False) self.upsample = UpsampleNet( upsample_scales=upsample_scales, nonlinear_activation=nonlinear_activation, nonlinear_activation_params=nonlinear_activation_params, interpolate_mode=interpolate_mode, freq_axis_kernel_size=freq_axis_kernel_size, use_causal_conv=use_causal_conv) def forward(self, c): """ Parameters ---------- c : Tensor Shape (N, F, T), spectrogram Returns ------- Tensors Shape (N, F, T'), where ``T' = upsample_factor * T``, upsampled spectrogram """ c_ = self.conv_in(c) c = c_[:, :, :-self.aux_context_window] if self.use_causal_conv else c_ return self.upsample(c) class ResidualBlock(nn.Layer): """A gated activation unit composed of an 1D convolution, a gated tanh unit and parametric redidual and skip connections. For more details, refer to `WaveNet: A Generative Model for Raw Audio <https://arxiv.org/abs/1609.03499>`_. Parameters ---------- kernel_size : int, optional Kernel size of the 1D convolution, by default 3 residual_channels : int, optional Feature size of the resiaudl output(and also the input), by default 64 gate_channels : int, optional Output feature size of the 1D convolution, by default 128 skip_channels : int, optional Feature size of the skip output, by default 64 aux_channels : int, optional Feature size of the auxiliary input (e.g. spectrogram), by default 80 dropout : float, optional Probability of the dropout before the 1D convolution, by default 0. dilation : int, optional Dilation of the 1D convolution, by default 1 bias : bool, optional Whether to use bias in the 1D convolution, by default True use_causal_conv : bool, optional Whether to use causal padding for the 1D convolution, by default False """ def __init__(self, kernel_size: int=3, residual_channels: int=64, gate_channels: int=128, skip_channels: int=64, aux_channels: int=80, dropout: float=0., dilation: int=1, bias: bool=True, use_causal_conv: bool=False): super().__init__() self.dropout = dropout if use_causal_conv: padding = (kernel_size - 1) * dilation else: assert kernel_size % 2 == 1 padding = (kernel_size - 1) // 2 * dilation self.use_causal_conv = use_causal_conv self.conv = nn.Conv1D( residual_channels, gate_channels, kernel_size, padding=padding, dilation=dilation, bias_attr=bias) if aux_channels is not None: self.conv1x1_aux = nn.Conv1D( aux_channels, gate_channels, kernel_size=1, bias_attr=False) else: self.conv1x1_aux = None gate_out_channels = gate_channels // 2 self.conv1x1_out = nn.Conv1D( gate_out_channels, residual_channels, kernel_size=1, bias_attr=bias) self.conv1x1_skip = nn.Conv1D( gate_out_channels, skip_channels, kernel_size=1, bias_attr=bias) def forward(self, x, c): """ Parameters ---------- x : Tensor Shape (N, C_res, T), the input features. c : Tensor Shape (N, C_aux, T), the auxiliary input. Returns ------- res : Tensor Shape (N, C_res, T), the residual output, which is used as the input of the next ResidualBlock in a stack of ResidualBlocks. skip : Tensor Shape (N, C_skip, T), the skip output, which is collected among each layer in a stack of ResidualBlocks. """ x_input = x x = F.dropout(x, self.dropout, training=self.training) x = self.conv(x) x = x[:, :, x_input.shape[-1]] if self.use_causal_conv else x if c is not None: c = self.conv1x1_aux(c) x += c a, b = paddle.chunk(x, 2, axis=1) x = paddle.tanh(a) * F.sigmoid(b) skip = self.conv1x1_skip(x) res = (self.conv1x1_out(x) + x_input) * math.sqrt(0.5) return res, skip class PWGGenerator(nn.Layer): """Wave Generator for Parallel WaveGAN Parameters ---------- in_channels : int, optional Number of channels of the input waveform, by default 1 out_channels : int, optional Number of channels of the output waveform, by default 1 kernel_size : int, optional Kernel size of the residual blocks inside, by default 3 layers : int, optional Number of residual blocks inside, by default 30 stacks : int, optional The number of groups to split the residual blocks into, by default 3 Within each group, the dilation of the residual block grows exponentially. residual_channels : int, optional Residual channel of the residual blocks, by default 64 gate_channels : int, optional Gate channel of the residual blocks, by default 128 skip_channels : int, optional Skip channel of the residual blocks, by default 64 aux_channels : int, optional Auxiliary channel of the residual blocks, by default 80 aux_context_window : int, optional The context window size of the first convolution applied to the auxiliary input, by default 2 dropout : float, optional Dropout of the residual blocks, by default 0. bias : bool, optional Whether to use bias in residual blocks, by default True use_weight_norm : bool, optional Whether to use weight norm in all convolutions, by default True use_causal_conv : bool, optional Whether to use causal padding in the upsample network and residual blocks, by default False upsample_scales : List[int], optional Upsample scales of the upsample network, by default [4, 4, 4, 4] nonlinear_activation : Optional[str], optional Non linear activation in upsample network, by default None nonlinear_activation_params : Dict[str, Any], optional Parameters passed to the linear activation in the upsample network, by default {} interpolate_mode : str, optional Interpolation mode of the upsample network, by default "nearest" freq_axis_kernel_size : int, optional Kernel size along the frequency axis of the upsample network, by default 1 """ def __init__(self, in_channels: int=1, out_channels: int=1, kernel_size: int=3, layers: int=30, stacks: int=3, residual_channels: int=64, gate_channels: int=128, skip_channels: int=64, aux_channels: int=80, aux_context_window: int=2, dropout: float=0., bias: bool=True, use_weight_norm: bool=True, use_causal_conv: bool=False, upsample_scales: List[int]=[4, 4, 4, 4], nonlinear_activation: Optional[str]=None, nonlinear_activation_params: Dict[str, Any]={}, interpolate_mode: str="nearest", freq_axis_kernel_size: int=1): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.aux_channels = aux_channels self.aux_context_window = aux_context_window self.layers = layers self.stacks = stacks self.kernel_size = kernel_size assert layers % stacks == 0 layers_per_stack = layers // stacks self.first_conv = nn.Conv1D( in_channels, residual_channels, 1, bias_attr=True) self.upsample_net = ConvInUpsampleNet( upsample_scales=upsample_scales, nonlinear_activation=nonlinear_activation, nonlinear_activation_params=nonlinear_activation_params, interpolate_mode=interpolate_mode, freq_axis_kernel_size=freq_axis_kernel_size, aux_channels=aux_channels, aux_context_window=aux_context_window, use_causal_conv=use_causal_conv) self.upsample_factor = np.prod(upsample_scales) self.conv_layers = nn.LayerList() for layer in range(layers): dilation = 2**(layer % layers_per_stack) conv = ResidualBlock( kernel_size=kernel_size, residual_channels=residual_channels, gate_channels=gate_channels, skip_channels=skip_channels, aux_channels=aux_channels, dilation=dilation, dropout=dropout, bias=bias, use_causal_conv=use_causal_conv) self.conv_layers.append(conv) self.last_conv_layers = nn.Sequential(nn.ReLU(), nn.Conv1D( skip_channels, skip_channels, 1, bias_attr=True), nn.ReLU(), nn.Conv1D( skip_channels, out_channels, 1, bias_attr=True)) if use_weight_norm: self.apply_weight_norm() def forward(self, x, c): """Generate waveform. Parameters ---------- x : Tensor Shape (N, C_in, T), The input waveform. c : Tensor Shape (N, C_aux, T'). The auxiliary input (e.g. spectrogram). It is upsampled to match the time resolution of the input. Returns ------- Tensor Shape (N, C_out, T), the generated waveform. """ c = self.upsample_net(c) assert c.shape[-1] == x.shape[-1] x = self.first_conv(x) skips = 0 for f in self.conv_layers: x, s = f(x, c) skips += s skips *= math.sqrt(1.0 / len(self.conv_layers)) x = self.last_conv_layers(skips) return x def apply_weight_norm(self): """Recursively apply weight normalization to all the Convolution layers in the sublayers. """ def _apply_weight_norm(layer): if isinstance(layer, (nn.Conv1D, nn.Conv2D)): nn.utils.weight_norm(layer) self.apply(_apply_weight_norm) def remove_weight_norm(self): """Recursively remove weight normalization from all the Convolution layers in the sublayers. """ def _remove_weight_norm(layer): try: nn.utils.remove_weight_norm(layer) except ValueError: pass self.apply(_remove_weight_norm) def inference(self, c=None): """Waveform generation. This function is used for single instance inference. Parameters ---------- c : Tensor, optional Shape (T', C_aux), the auxiliary input, by default None x : Tensor, optional Shape (T, C_in), the noise waveform, by default None If not provided, a sample is drawn from a gaussian distribution. Returns ------- Tensor Shape (T, C_out), the generated waveform """ x = paddle.randn( [1, self.in_channels, paddle.shape(c)[0] * self.upsample_factor]) c = paddle.transpose(c, [1, 0]).unsqueeze(0) # pseudo batch c = nn.Pad1D(self.aux_context_window, mode='replicate')(c) out = self(x, c).squeeze(0).transpose([1, 0]) return out class PWGDiscriminator(nn.Layer): """A convolutional discriminator for audio. Parameters ---------- in_channels : int, optional Number of channels of the input audio, by default 1 out_channels : int, optional Output feature size, by default 1 kernel_size : int, optional Kernel size of convolutional sublayers, by default 3 layers : int, optional Number of layers, by default 10 conv_channels : int, optional Feature size of the convolutional sublayers, by default 64 dilation_factor : int, optional The factor with which dilation of each convolutional sublayers grows exponentially if it is greater than 1, else the dilation of each convolutional sublayers grows linearly, by default 1 nonlinear_activation : str, optional The activation after each convolutional sublayer, by default "LeakyReLU" nonlinear_activation_params : Dict[str, Any], optional The parameters passed to the activation's initializer, by default {"negative_slope": 0.2} bias : bool, optional Whether to use bias in convolutional sublayers, by default True use_weight_norm : bool, optional Whether to use weight normalization at all convolutional sublayers, by default True """ def __init__( self, in_channels: int=1, out_channels: int=1, kernel_size: int=3, layers: int=10, conv_channels: int=64, dilation_factor: int=1, nonlinear_activation: str="LeakyReLU", nonlinear_activation_params: Dict[str, Any]={"negative_slope": 0.2}, bias: bool=True, use_weight_norm: bool=True): super().__init__() assert kernel_size % 2 == 1 assert dilation_factor > 0 conv_layers = [] conv_in_channels = in_channels for i in range(layers - 1): if i == 0: dilation = 1 else: dilation = i if dilation_factor == 1 else dilation_factor**i conv_in_channels = conv_channels padding = (kernel_size - 1) // 2 * dilation conv_layer = nn.Conv1D( conv_in_channels, conv_channels, kernel_size, padding=padding, dilation=dilation, bias_attr=bias) nonlinear = getattr( nn, nonlinear_activation)(**nonlinear_activation_params) conv_layers.append(conv_layer) conv_layers.append(nonlinear) padding = (kernel_size - 1) // 2 last_conv = nn.Conv1D( conv_in_channels, out_channels, kernel_size, padding=padding, bias_attr=bias) conv_layers.append(last_conv) self.conv_layers = nn.Sequential(*conv_layers) if use_weight_norm: self.apply_weight_norm() def forward(self, x): """ Parameters ---------- x : Tensor Shape (N, in_channels, num_samples), the input audio. Returns ------- Tensor Shape (N, out_channels, num_samples), the predicted logits. """ return self.conv_layers(x) def apply_weight_norm(self): def _apply_weight_norm(layer): if isinstance(layer, (nn.Conv1D, nn.Conv2D)): nn.utils.weight_norm(layer) self.apply(_apply_weight_norm) def remove_weight_norm(self): def _remove_weight_norm(layer): try: nn.utils.remove_weight_norm(layer) except ValueError: pass self.apply(_remove_weight_norm) class ResidualPWGDiscriminator(nn.Layer): """A wavenet-style discriminator for audio. Parameters ---------- in_channels : int, optional Number of channels of the input audio, by default 1 out_channels : int, optional Output feature size, by default 1 kernel_size : int, optional Kernel size of residual blocks, by default 3 layers : int, optional Number of residual blocks, by default 30 stacks : int, optional Number of groups of residual blocks, within which the dilation of each residual blocks grows exponentially, by default 3 residual_channels : int, optional Residual channels of residual blocks, by default 64 gate_channels : int, optional Gate channels of residual blocks, by default 128 skip_channels : int, optional Skip channels of residual blocks, by default 64 dropout : float, optional Dropout probability of residual blocks, by default 0. bias : bool, optional Whether to use bias in residual blocks, by default True use_weight_norm : bool, optional Whether to use weight normalization in all convolutional layers, by default True use_causal_conv : bool, optional Whether to use causal convolution in residual blocks, by default False nonlinear_activation : str, optional Activation after convolutions other than those in residual blocks, by default "LeakyReLU" nonlinear_activation_params : Dict[str, Any], optional Parameters to pass to the activation, by default {"negative_slope": 0.2} """ def __init__(self, in_channels: int=1, out_channels: int=1, kernel_size: int=3, layers: int=30, stacks: int=3, residual_channels: int=64, gate_channels: int=128, skip_channels: int=64, dropout: float=0., bias: bool=True, use_weight_norm: bool=True, use_causal_conv: bool=False, nonlinear_activation: str="LeakyReLU", nonlinear_activation_params: Dict[ str, Any]={"negative_slope": 0.2}): super().__init__() assert kernel_size % 2 == 1 self.in_channels = in_channels self.out_channels = out_channels self.layers = layers self.stacks = stacks self.kernel_size = kernel_size assert layers % stacks == 0 layers_per_stack = layers // stacks self.first_conv = nn.Sequential( nn.Conv1D(in_channels, residual_channels, 1, bias_attr=True), getattr(nn, nonlinear_activation)(**nonlinear_activation_params)) self.conv_layers = nn.LayerList() for layer in range(layers): dilation = 2**(layer % layers_per_stack) conv = ResidualBlock( kernel_size=kernel_size, residual_channels=residual_channels, gate_channels=gate_channels, skip_channels=skip_channels, aux_channels=None, # no auxiliary input dropout=dropout, dilation=dilation, bias=bias, use_causal_conv=use_causal_conv) self.conv_layers.append(conv) self.last_conv_layers = nn.Sequential( getattr(nn, nonlinear_activation)(**nonlinear_activation_params), nn.Conv1D(skip_channels, skip_channels, 1, bias_attr=True), getattr(nn, nonlinear_activation)(**nonlinear_activation_params), nn.Conv1D(skip_channels, out_channels, 1, bias_attr=True)) if use_weight_norm: self.apply_weight_norm() def forward(self, x): """ Parameters ---------- x : Tensor Shape (N, in_channels, num_samples), the input audio. Returns ------- Tensor Shape (N, out_channels, num_samples), the predicted logits. """ x = self.first_conv(x) skip = 0 for f in self.conv_layers: x, h = f(x, None) skip += h skip *= math.sqrt(1 / len(self.conv_layers)) x = skip x = self.last_conv_layers(x) return x def apply_weight_norm(self): def _apply_weight_norm(layer): if isinstance(layer, (nn.Conv1D, nn.Conv2D)): nn.utils.weight_norm(layer) self.apply(_apply_weight_norm) def remove_weight_norm(self): def _remove_weight_norm(layer): try: nn.utils.remove_weight_norm(layer) except ValueError: pass self.apply(_remove_weight_norm) class PWGInference(nn.Layer): def __init__(self, normalizer, pwg_generator): super().__init__() self.normalizer = normalizer self.pwg_generator = pwg_generator def forward(self, logmel): normalized_mel = self.normalizer(logmel) wav = self.pwg_generator.inference(normalized_mel) return wav
[ "numpy.prod", "paddle.nn.Pad1D", "paddle.tanh", "paddle.transpose", "paddle.nn.Sequential", "paddle.nn.functional.interpolate", "paddle.nn.Conv2D", "paddle.nn.functional.sigmoid", "paddle.nn.ReLU", "paddle.shape", "paddle.nn.LayerList", "math.sqrt", "paddle.nn.Conv1D", "paddle.chunk", "p...
[((1965, 2040), 'paddle.nn.functional.interpolate', 'F.interpolate', (['x'], {'scale_factor': '(self.h_scale, self.w_scale)', 'mode': 'self.mode'}), '(x, scale_factor=(self.h_scale, self.w_scale), mode=self.mode)\n', (1978, 2040), True, 'from paddle.nn import functional as F\n'), ((3541, 3555), 'paddle.nn.LayerList', 'nn.LayerList', ([], {}), '()\n', (3553, 3555), False, 'from paddle import nn\n'), ((7017, 7096), 'paddle.nn.Conv1D', 'nn.Conv1D', (['aux_channels', 'aux_channels'], {'kernel_size': 'kernel_size', 'bias_attr': '(False)'}), '(aux_channels, aux_channels, kernel_size=kernel_size, bias_attr=False)\n', (7026, 7096), False, 'from paddle import nn\n'), ((9849, 9961), 'paddle.nn.Conv1D', 'nn.Conv1D', (['residual_channels', 'gate_channels', 'kernel_size'], {'padding': 'padding', 'dilation': 'dilation', 'bias_attr': 'bias'}), '(residual_channels, gate_channels, kernel_size, padding=padding,\n dilation=dilation, bias_attr=bias)\n', (9858, 9961), False, 'from paddle import nn\n'), ((10312, 10390), 'paddle.nn.Conv1D', 'nn.Conv1D', (['gate_out_channels', 'residual_channels'], {'kernel_size': '(1)', 'bias_attr': 'bias'}), '(gate_out_channels, residual_channels, kernel_size=1, bias_attr=bias)\n', (10321, 10390), False, 'from paddle import nn\n'), ((10432, 10506), 'paddle.nn.Conv1D', 'nn.Conv1D', (['gate_out_channels', 'skip_channels'], {'kernel_size': '(1)', 'bias_attr': 'bias'}), '(gate_out_channels, skip_channels, kernel_size=1, bias_attr=bias)\n', (10441, 10506), False, 'from paddle import nn\n'), ((11144, 11194), 'paddle.nn.functional.dropout', 'F.dropout', (['x', 'self.dropout'], {'training': 'self.training'}), '(x, self.dropout, training=self.training)\n', (11153, 11194), True, 'from paddle.nn import functional as F\n'), ((11387, 11413), 'paddle.chunk', 'paddle.chunk', (['x', '(2)'], {'axis': '(1)'}), '(x, 2, axis=1)\n', (11399, 11413), False, 'import paddle\n'), ((15109, 15169), 'paddle.nn.Conv1D', 'nn.Conv1D', (['in_channels', 'residual_channels', '(1)'], {'bias_attr': '(True)'}), '(in_channels, residual_channels, 1, bias_attr=True)\n', (15118, 15169), False, 'from paddle import nn\n'), ((15669, 15693), 'numpy.prod', 'np.prod', (['upsample_scales'], {}), '(upsample_scales)\n', (15676, 15693), True, 'import numpy as np\n'), ((15722, 15736), 'paddle.nn.LayerList', 'nn.LayerList', ([], {}), '()\n', (15734, 15736), False, 'from paddle import nn\n'), ((22089, 22180), 'paddle.nn.Conv1D', 'nn.Conv1D', (['conv_in_channels', 'out_channels', 'kernel_size'], {'padding': 'padding', 'bias_attr': 'bias'}), '(conv_in_channels, out_channels, kernel_size, padding=padding,\n bias_attr=bias)\n', (22098, 22180), False, 'from paddle import nn\n'), ((22303, 22330), 'paddle.nn.Sequential', 'nn.Sequential', (['*conv_layers'], {}), '(*conv_layers)\n', (22316, 22330), False, 'from paddle import nn\n'), ((25996, 26010), 'paddle.nn.LayerList', 'nn.LayerList', ([], {}), '()\n', (26008, 26010), False, 'from paddle import nn\n'), ((4013, 4075), 'paddle.nn.Conv2D', 'nn.Conv2D', (['(1)', '(1)', 'kernel_size'], {'padding': 'padding', 'bias_attr': '(False)'}), '(1, 1, kernel_size, padding=padding, bias_attr=False)\n', (4022, 4075), False, 'from paddle import nn\n'), ((10099, 10169), 'paddle.nn.Conv1D', 'nn.Conv1D', (['aux_channels', 'gate_channels'], {'kernel_size': '(1)', 'bias_attr': '(False)'}), '(aux_channels, gate_channels, kernel_size=1, bias_attr=False)\n', (10108, 10169), False, 'from paddle import nn\n'), ((11426, 11440), 'paddle.tanh', 'paddle.tanh', (['a'], {}), '(a)\n', (11437, 11440), False, 'import paddle\n'), ((11443, 11455), 'paddle.nn.functional.sigmoid', 'F.sigmoid', (['b'], {}), '(b)\n', (11452, 11455), True, 'from paddle.nn import functional as F\n'), ((11541, 11555), 'math.sqrt', 'math.sqrt', (['(0.5)'], {}), '(0.5)\n', (11550, 11555), False, 'import math\n'), ((16320, 16329), 'paddle.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (16327, 16329), False, 'from paddle import nn\n'), ((16377, 16435), 'paddle.nn.Conv1D', 'nn.Conv1D', (['skip_channels', 'skip_channels', '(1)'], {'bias_attr': '(True)'}), '(skip_channels, skip_channels, 1, bias_attr=True)\n', (16386, 16435), False, 'from paddle import nn\n'), ((16684, 16693), 'paddle.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (16691, 16693), False, 'from paddle import nn\n'), ((16741, 16798), 'paddle.nn.Conv1D', 'nn.Conv1D', (['skip_channels', 'out_channels', '(1)'], {'bias_attr': '(True)'}), '(skip_channels, out_channels, 1, bias_attr=True)\n', (16750, 16798), False, 'from paddle import nn\n'), ((19270, 19321), 'paddle.nn.Pad1D', 'nn.Pad1D', (['self.aux_context_window'], {'mode': '"""replicate"""'}), "(self.aux_context_window, mode='replicate')\n", (19278, 19321), False, 'from paddle import nn\n'), ((21632, 21743), 'paddle.nn.Conv1D', 'nn.Conv1D', (['conv_in_channels', 'conv_channels', 'kernel_size'], {'padding': 'padding', 'dilation': 'dilation', 'bias_attr': 'bias'}), '(conv_in_channels, conv_channels, kernel_size, padding=padding,\n dilation=dilation, bias_attr=bias)\n', (21641, 21743), False, 'from paddle import nn\n'), ((25828, 25888), 'paddle.nn.Conv1D', 'nn.Conv1D', (['in_channels', 'residual_channels', '(1)'], {'bias_attr': '(True)'}), '(in_channels, residual_channels, 1, bias_attr=True)\n', (25837, 25888), False, 'from paddle import nn\n'), ((26699, 26757), 'paddle.nn.Conv1D', 'nn.Conv1D', (['skip_channels', 'skip_channels', '(1)'], {'bias_attr': '(True)'}), '(skip_channels, skip_channels, 1, bias_attr=True)\n', (26708, 26757), False, 'from paddle import nn\n'), ((26849, 26906), 'paddle.nn.Conv1D', 'nn.Conv1D', (['skip_channels', 'out_channels', '(1)'], {'bias_attr': '(True)'}), '(skip_channels, out_channels, 1, bias_attr=True)\n', (26858, 26906), False, 'from paddle import nn\n'), ((18110, 18137), 'paddle.nn.utils.weight_norm', 'nn.utils.weight_norm', (['layer'], {}), '(layer)\n', (18130, 18137), False, 'from paddle import nn\n'), ((18409, 18443), 'paddle.nn.utils.remove_weight_norm', 'nn.utils.remove_weight_norm', (['layer'], {}), '(layer)\n', (18436, 18443), False, 'from paddle import nn\n'), ((19201, 19228), 'paddle.transpose', 'paddle.transpose', (['c', '[1, 0]'], {}), '(c, [1, 0])\n', (19217, 19228), False, 'import paddle\n'), ((22873, 22900), 'paddle.nn.utils.weight_norm', 'nn.utils.weight_norm', (['layer'], {}), '(layer)\n', (22893, 22900), False, 'from paddle import nn\n'), ((23049, 23083), 'paddle.nn.utils.remove_weight_norm', 'nn.utils.remove_weight_norm', (['layer'], {}), '(layer)\n', (23076, 23083), False, 'from paddle import nn\n'), ((27675, 27702), 'paddle.nn.utils.weight_norm', 'nn.utils.weight_norm', (['layer'], {}), '(layer)\n', (27695, 27702), False, 'from paddle import nn\n'), ((27851, 27885), 'paddle.nn.utils.remove_weight_norm', 'nn.utils.remove_weight_norm', (['layer'], {}), '(layer)\n', (27878, 27885), False, 'from paddle import nn\n'), ((19145, 19160), 'paddle.shape', 'paddle.shape', (['c'], {}), '(c)\n', (19157, 19160), False, 'import paddle\n')]
import errno import itertools import os from collections import Counter from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast import numpy as np from loguru import logger from tqdm import tqdm import slp.util.system as system import slp.util.types as types from slp.config.nlp import SPECIAL_TOKENS from slp.data.transforms import HuggingFaceTokenizer, SpacyTokenizer, ToTokenIds def create_vocab( corpus: Union[List[str], List[List[str]]], vocab_size: int = -1, special_tokens: Optional[SPECIAL_TOKENS] = None, ) -> Dict[str, int]: """Create the vocabulary based on tokenized input corpus * Injects special tokens in the vocabulary * Calculates the occurence count for each token * Limits vocabulary to vocab_size most common tokens Args: corpus (Union[List[str], List[List[str]]]): The tokenized corpus as a list of sentences or a list of tokenized sentences vocab_size (int): [description]. Limit vocabulary to vocab_size most common tokens. Defaults to -1 which keeps all tokens. special_tokens Optional[SPECIAL_TOKENS]: Special tokens to include in the vocabulary. Defaults to None. Returns: Dict[str, int]: Dictionary of all accepted tokens and their corresponding occurence counts Examples: >>> create_vocab(["in", "a", "galaxy", "far", "far", "away"]) {'far': 2, 'away': 1, 'galaxy': 1, 'a': 1, 'in': 1} >>> create_vocab(["in", "a", "galaxy", "far", "far", "away"], vocab_size=3) {'far': 2, 'a': 1, 'in': 1} >>> create_vocab(["in", "a", "galaxy", "far", "far", "away"], vocab_size=3, special_tokens=slp.config.nlp.SPECIAL_TOKENS) {'[PAD]': 0, '[MASK]': 0, '[UNK]': 0, '[BOS]': 0, '[EOS]': 0, '[CLS]': 0, '[SEP]': 0, 'far': 2, 'a': 1, 'in': 1} """ if isinstance(corpus[0], list): corpus = list(itertools.chain.from_iterable(corpus)) freq = Counter(corpus) if special_tokens is None: extra_tokens = [] else: extra_tokens = special_tokens.to_list() if vocab_size < 0: vocab_size = len(freq) take = min(vocab_size, len(freq)) logger.info(f"Keeping {vocab_size} most common tokens out of {len(freq)}") def take0(x: Tuple[Any, Any]) -> Any: """Take first tuple element""" return x[0] common_words = list(map(take0, freq.most_common(take))) common_words = list(set(common_words) - set(extra_tokens)) words = extra_tokens + common_words if len(words) > vocab_size: words = words[: vocab_size + len(extra_tokens)] def token_freq(t): """Token frequeny""" return 0 if t in extra_tokens else freq[t] vocab = dict(zip(words, map(token_freq, words))) logger.info(f"Vocabulary created with {len(vocab)} tokens.") logger.info(f"The 10 most common tokens are:\n{freq.most_common(10)}") return vocab class EmbeddingsLoader(object): def __init__( self, embeddings_file: str, dim: int, vocab: Optional[Dict[str, int]] = None, extra_tokens: Optional[SPECIAL_TOKENS] = None, ) -> None: """Load word embeddings in text format Args: embeddings_file (str): File where embeddings are stored (e.g. glove.6B.50d.txt) dim (int): Dimensionality of embeddings vocab (Optional[Dict[str, int]]): Load only embeddings in vocab. Defaults to None. extra_tokens (Optional[slp.config.nlp.SPECIAL_TOKENS]): Create random embeddings for these special tokens. Defaults to None. """ self.embeddings_file = embeddings_file self.vocab = vocab self.cache_ = self._get_cache_name() self.dim_ = dim self.extra_tokens = extra_tokens def __repr__(self): """String representation of class""" return f"{self.__class__.__name__}({self.embeddings_file}, {self.dim_})" def in_accepted_vocab(self, word: str) -> bool: """Check if word exists in given vocabulary Args: word (str): word from embeddings file Returns: bool: Word exists """ return True if self.vocab is None else word in self.vocab def _get_cache_name(self) -> str: """Create a cache file name to avoid reloading the embeddings Cache name is something like glove.6B.50d.1000.p, where 1000 is the size of the vocab provided in __init__ Returns: str: Cache file name """ head, tail = os.path.split(self.embeddings_file) filename, _ = os.path.splitext(tail) if self.vocab is not None: cache_name = os.path.join(head, f"{filename}.{len(self.vocab)}.p") else: cache_name = os.path.join(head, f"{filename}.p") logger.info(f"Cache: {cache_name}") return cache_name def _dump_cache(self, data: types.Embeddings) -> None: """Save loaded embeddings to cache as a pickle Saves a tuple of (word2idx, idx2word, embeddings) Args: data (types.Embeddings): (word2idx, idx2word, embeddings) tuple """ system.pickle_dump(data, self.cache_) def _load_cache(self) -> types.Embeddings: """Load Embeddings from cache Returns: types.Embeddings: (word2idx, idx2word, embeddings) tuple """ return cast(types.Embeddings, system.pickle_load(self.cache_)) def augment_embeddings( self, word2idx: Dict[str, int], idx2word: Dict[int, str], embeddings: List[np.ndarray], token: str, emb: Optional[np.ndarray] = None, ) -> Tuple[Dict[str, int], Dict[int, str], List[np.ndarray]]: """Create a random embedding for a special token and append it to the embeddings array Args: word2idx (Dict[str, int]): Current word2idx map idx2word (Dict[int, str]): Current idx2word map embeddings (List[np.ndarray]): Embeddings array as list of embeddings token (str): The special token (e.g. [PAD]) emb (Optional[np.ndarray]): Optional value for the embedding to be appended. Defaults to None, where a random embedding is created. Returns: Tuple[Dict[str, int], Dict[int, str], List[np.ndarray]]: (word2idx, idx2word, embeddings) tuple """ word2idx[token] = len(embeddings) idx2word[len(embeddings)] = token if emb is None: emb = np.random.uniform(low=-0.05, high=0.05, size=self.dim_) embeddings.append(emb) return word2idx, idx2word, embeddings @system.timethis(method=True) def load(self) -> types.Embeddings: """Read the word vectors from a text file * Read embeddings * Filter with given vocabulary * Augment with special tokens Returns: types.Embeddings: (word2idx, idx2word, embeddings) tuple """ # in order to avoid this time consuming operation, cache the results try: cache = self._load_cache() logger.info("Loaded word embeddings from cache.") return cache except OSError: logger.warning(f"Didn't find embeddings cache file {self.embeddings_file}") logger.warning("Loading embeddings from file.") # create the necessary dictionaries and the word embeddings matrix if not os.path.exists(self.embeddings_file): logger.critical(f"{self.embeddings_file} not found!") raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), self.embeddings_file) logger.info(f"Indexing file {self.embeddings_file} ...") # create the 2D array, which will be used for initializing # the Embedding layer of a NN. # We reserve the first row (idx=0), as the word embedding, # which will be used for zero padding (word with id = 0). if self.extra_tokens is not None: word2idx, idx2word, embeddings = self.augment_embeddings( {}, {}, [], self.extra_tokens.PAD.value, # type: ignore emb=np.zeros(self.dim_), ) for token in self.extra_tokens: # type: ignore logger.debug(f"Adding token {token.value} to embeddings matrix") if token == self.extra_tokens.PAD: continue word2idx, idx2word, embeddings = self.augment_embeddings( word2idx, idx2word, embeddings, token.value ) else: word2idx, idx2word, embeddings = self.augment_embeddings( {}, {}, [], "[PAD]", emb=np.zeros(self.dim_) ) # read file, line by line with open(self.embeddings_file, "r") as f: num_lines = sum(1 for line in f) with open(self.embeddings_file, "r") as f: index = len(embeddings) for line in tqdm( f, total=num_lines, desc="Loading word embeddings...", leave=False ): # skip the first row if it is a header if len(line.split()) < self.dim_: continue values = line.rstrip().split(" ") word = values[0] if word in word2idx: continue if not self.in_accepted_vocab(word): continue vector = np.asarray(values[1:], dtype=np.float32) idx2word[index] = word word2idx[word] = index embeddings.append(vector) index += 1 logger.info(f"Loaded {len(embeddings)} word vectors.") embeddings_out = np.array(embeddings, dtype="float32") # write the data to a cache file self._dump_cache((word2idx, idx2word, embeddings_out)) return word2idx, idx2word, embeddings_out class WordCorpus(object): def __init__( self, corpus: List[str], limit_vocab_size: int = 30000, word2idx: Optional[Dict[str, int]] = None, idx2word: Optional[Dict[int, str]] = None, embeddings: Optional[np.ndarray] = None, embeddings_file: Optional[str] = None, embeddings_dim: int = 300, lower: bool = True, special_tokens: Optional[SPECIAL_TOKENS] = SPECIAL_TOKENS, # type: ignore prepend_bos: bool = False, append_eos: bool = False, lang: str = "en_core_web_md", max_length: int = -1, **kwargs, ): """Load corpus embeddings, tokenize in words using spacy and convert to ids This class handles the handling of a raw corpus. It handles: * Tokenization into words (spacy) * Loading of pretrained word embedding * Calculation of word frequencies / corpus statistics * Conversion to token ids You can pass either: * Pass an embeddings file to load pretrained embeddings and create the word2idx mapping * Pass already loaded embeddings array and word2idx. This is useful for the dev / test splits where we want to pass the train split embeddings / word2idx. Args: corpus (List[List[str]]): Corpus as a list of sentences limit_vocab_size (int): Upper bound for number of most frequent tokens to keep. Defaults to 30000. word2idx (Optional[Dict[str, int]]): Mapping of word to indices. Defaults to None. idx2word (Optional[Dict[int, str]]): Mapping of indices to words. Defaults to None. embeddings (Optional[np.ndarray]): Embeddings array. Defaults to None. embeddings_file (Optional[str]): Embeddings file to read. Defaults to None. embeddings_dim (int): Dimension of embeddings. Defaults to 300. lower (bool): Convert strings to lower case. Defaults to True. special_tokens (Optional[SPECIAL_TOKENS]): Special tokens to include in the vocabulary. Defaults to slp.config.nlp.SPECIAL_TOKENS. prepend_bos (bool): Prepend Beginning of Sequence token for seq2seq tasks. Defaults to False. append_eos (bool): Append End of Sequence token for seq2seq tasks. Defaults to False. lang (str): Spacy language, e.g. el_core_web_sm, en_core_web_sm etc. Defaults to "en_core_web_md". max_length (int): Crop sequences above this length. Defaults to -1 where sequences are left unaltered. """ # FIXME: Extract super class to avoid repetition self.corpus_ = corpus self.max_length = max_length self.tokenizer = SpacyTokenizer( lower=lower, prepend_bos=prepend_bos, append_eos=append_eos, specials=special_tokens, lang=lang, ) logger.info(f"Tokenizing corpus using spacy {lang}") self.tokenized_corpus_ = [ self.tokenizer(s) for s in tqdm(self.corpus_, desc="Tokenizing corpus...", leave=False) ] self.vocab_ = create_vocab( self.tokenized_corpus_, vocab_size=limit_vocab_size if word2idx is None else -1, special_tokens=special_tokens, ) self.word2idx_, self.idx2word_, self.embeddings_ = None, None, None # self.corpus_indices_ = self.tokenized_corpus_ if word2idx is not None: logger.info("Word2idx was already provided. Going to used it.") if embeddings_file is not None and word2idx is None: logger.info( f"Going to load {len(self.vocab_)} embeddings from {embeddings_file}" ) loader = EmbeddingsLoader( embeddings_file, embeddings_dim, vocab=self.vocab_, extra_tokens=special_tokens, ) word2idx, idx2word, embeddings = loader.load() if embeddings is not None: self.embeddings_ = embeddings if idx2word is not None: self.idx2word_ = idx2word if word2idx is not None: self.word2idx_ = word2idx logger.info("Converting tokens to ids using word2idx.") self.to_token_ids = ToTokenIds( self.word2idx_, specials=SPECIAL_TOKENS, # type: ignore ) self.corpus_indices_ = [ self.to_token_ids(s) for s in tqdm( self.tokenized_corpus_, desc="Converting tokens to token ids...", leave=False, ) ] logger.info("Filtering corpus vocabulary.") updated_vocab = {} for k, v in self.vocab_.items(): if k in self.word2idx_: updated_vocab[k] = v logger.info( f"Out of {len(self.vocab_)} tokens {len(self.vocab_) - len(updated_vocab)} were not found in the pretrained embeddings." ) self.vocab_ = updated_vocab @property def vocab_size(cls) -> int: """Retrieve vocabulary size for corpus Returns: int: vocabulary size """ sz: int = ( cls.embeddings.shape[0] if cls.embeddings is not None else len(cls.vocab_) ) return sz @property def frequencies(cls) -> Dict[str, int]: """Retrieve word occurence counts Returns: Dict[str, int]: word occurence counts """ return cls.vocab_ @property def vocab(cls) -> Set[str]: """Retrieve set of words in vocabulary Returns: Set[str]: set of words in vocabulary """ return set(cls.vocab_.keys()) @property def embeddings(cls) -> np.ndarray: """Retrieve embeddings array Returns: np.ndarray: Array of pretrained word embeddings """ return cast(np.ndarray, cls.embeddings_) @property def word2idx(cls) -> Dict[str, int]: """Retrieve word2idx mapping Returns: Dict[str, int]: word2idx mapping """ return cast(Dict[str, int], cls.word2idx_) @property def idx2word(cls) -> Dict[int, str]: """Retrieve idx2word mapping Returns: Dict[str, int]: idx2word mapping """ return cast(Dict[int, str], cls.idx2word_) @property def tokenized(cls) -> List[List[str]]: """Retrieve tokenized corpus Returns: List[List[str]]: Tokenized corpus """ return cls.tokenized_corpus_ @property def indices(cls) -> List[List[int]]: """Retrieve corpus as token indices Returns: List[List[int]]: Token indices for corpus """ return cls.corpus_indices_ @property def raw(cls) -> List[str]: """Retrieve raw corpus Returns: List[str]: Raw Corpus """ return cls.corpus_ def __len__(self) -> int: """Number of samples in corpus Returns: int: Corpus length """ return len(self.corpus_indices_) def __getitem__(self, idx) -> List[int]: """Get ith element in corpus as token indices Args: idx (List[int]): index in corpus Returns: List[int]: List of token indices for sentence """ out: List[int] = ( self.corpus_indices_[idx] if self.max_length <= 0 else self.corpus_indices_[idx][: self.max_length] ) return out class HfCorpus(object): def __init__( self, corpus: List[str], lower: bool = True, tokenizer_model: str = "bert-base-uncased", add_special_tokens: bool = True, special_tokens: Optional[SPECIAL_TOKENS] = SPECIAL_TOKENS, # type: ignore max_length: int = -1, **kwargs, ): """Process a corpus using hugging face tokenizers Select one of hugging face tokenizers and process corpus Args: corpus (List[str]): List of sentences lower (bool): Convert strings to lower case. Defaults to True. tokenizer_model (str): Hugging face model to use. Defaults to "bert-base-uncased". add_special_tokens (bool): Add special tokens in sentence during tokenization. Defaults to True. special_tokens (Optional[SPECIAL_TOKENS]): Special tokens to include in the vocabulary. Defaults to slp.config.nlp.SPECIAL_TOKENS. max_length (int): Crop sequences above this length. Defaults to -1 where sequences are left unaltered. """ self.corpus_ = corpus self.max_length = max_length logger.info( f"Tokenizing corpus using hugging face tokenizer from {tokenizer_model}" ) self.tokenizer = HuggingFaceTokenizer( lower=lower, model=tokenizer_model, add_special_tokens=add_special_tokens ) self.corpus_indices_ = [ self.tokenizer(s) for s in tqdm( self.corpus_, desc="Converting tokens to indices...", leave=False ) ] self.tokenized_corpus_ = [ self.tokenizer.detokenize(s) for s in tqdm( self.corpus_indices_, desc="Mapping indices to tokens...", leave=False, ) ] self.vocab_ = create_vocab( self.tokenized_corpus_, vocab_size=-1, special_tokens=special_tokens, ) @property def vocab_size(cls) -> int: """Retrieve vocabulary size Returns: int: Vocabulary size """ sz: int = cls.tokenizer.vocab_size return sz @property def frequencies(cls) -> Dict[str, int]: """Retrieve wordpieces occurence counts Returns: Dict[str, int]: wordpieces occurence counts """ return cls.vocab_ @property def vocab(cls) -> Set[str]: """Retrieve set of words in vocabulary Returns: Set[str]: set of words in vocabulary """ return set(cls.vocab_.keys()) @property def embeddings(cls) -> None: """Unused. Defined for compatibility""" return None @property def word2idx(cls) -> None: """Unused. Defined for compatibility""" return None @property def idx2word(cls) -> None: """Unused. Defined for compatibility""" return None @property def tokenized(cls) -> List[List[str]]: """Retrieve tokenized corpus Returns: List[List[str]]: tokenized corpus """ return cls.tokenized_corpus_ @property def indices(cls) -> List[List[int]]: """Retrieve corpus as token indices Returns: List[List[int]]: Token indices for corpus """ return cls.corpus_indices_ @property def raw(cls) -> List[str]: """Retrieve raw corpus Returns: List[str]: Raw Corpus """ return cls.corpus_ def __len__(self) -> int: """Number of samples in corpus Returns: int: Corpus length """ return len(self.corpus_indices_) def __getitem__(self, idx) -> List[int]: """Get ith element in corpus as token indices Args: idx (List[int]): index in corpus Returns: List[int]: List of token indices for sentence """ out: List[int] = ( self.corpus_indices_[idx] if self.max_length <= 0 else self.corpus_indices_[idx][: self.max_length] ) return out class TokenizedCorpus(object): def __init__( self, corpus: Union[List[str], List[List[str]]], word2idx: Dict[str, int] = None, special_tokens: Optional[SPECIAL_TOKENS] = SPECIAL_TOKENS, # type: ignore max_length: int = -1, **kwargs, ): """Wrap a corpus that's already tokenized Args: corpus (Union[List[str], List[List[str]]]): List of tokens or List of lists of tokens word2idx (Dict[str, int], optional): Token to index mapping. Defaults to None. special_tokens (Optional[SPECIAL_TOKENS], optional): Special Tokens. Defaults to SPECIAL_TOKENS. """ self.corpus_ = corpus self.tokenized_corpus_ = corpus self.max_length = max_length self.vocab_ = create_vocab( self.tokenized_corpus_, vocab_size=-1, special_tokens=special_tokens, ) if word2idx is not None: logger.info("Converting tokens to ids using word2idx.") self.word2idx_ = word2idx else: logger.info( "No word2idx provided. Will convert tokens to ids using an iterative counter." ) self.word2idx_ = dict(zip(self.vocab_.keys(), itertools.count())) self.idx2word_ = {v: k for k, v in self.word2idx_.items()} self.to_token_ids = ToTokenIds( self.word2idx_, specials=SPECIAL_TOKENS, # type: ignore ) if isinstance(self.tokenized_corpus_[0], list): self.corpus_indices_ = [ self.to_token_ids(s) for s in tqdm( self.tokenized_corpus_, desc="Converting tokens to token ids...", leave=False, ) ] else: self.corpus_indices_ = self.to_token_ids(self.tokenized_corpus_) # type: ignore @property def vocab_size(cls) -> int: """Retrieve vocabulary size Returns: int: Vocabulary size """ return len(cls.vocab_) @property def frequencies(cls) -> Dict[str, int]: """Retrieve wordpieces occurence counts Returns: Dict[str, int]: wordpieces occurence counts """ return cls.vocab_ @property def vocab(cls) -> Set[str]: """Retrieve set of words in vocabulary Returns: Set[str]: set of words in vocabulary """ return set(cls.vocab_.keys()) @property def embeddings(cls) -> None: """Unused. Kept for compatibility""" return None @property def word2idx(cls) -> Dict[str, int]: """Retrieve word2idx mapping Returns: Dict[str, int]: word2idx mapping """ return cls.word2idx_ @property def idx2word(cls) -> Dict[int, str]: """Retrieve idx2word mapping Returns: Dict[str, int]: idx2word mapping """ return cls.idx2word_ @property def tokenized(cls) -> Union[List[str], List[List[str]]]: """Retrieve tokenized corpus Returns: List[List[str]]: Tokenized corpus """ return cls.tokenized_corpus_ @property def indices(cls) -> Union[List[int], List[List[int]]]: """Retrieve corpus as token indices Returns: List[List[int]]: Token indices for corpus """ return cls.corpus_indices_ @property def raw(cls) -> Union[List[str], List[List[str]]]: """Retrieve raw corpus Returns: List[str]: Raw Corpus """ return cls.corpus_ def __len__(self) -> int: """Number of samples in corpus Returns: int: Corpus length """ return len(self.corpus_indices_) def __getitem__(self, idx) -> List[int]: """Get ith element in corpus as token indices Args: idx (List[int]): index in corpus Returns: List[int]: List of token indices for sentence """ out: List[int] = ( self.corpus_indices_[idx] if self.max_length <= 0 else self.corpus_indices_[idx][: self.max_length] ) return out if __name__ == "__main__": corpus = [ "the big", "brown fox", "jumps over", "the lazy dog", "supercalifragilisticexpialidocious", ] word_corpus = WordCorpus( corpus, embeddings_file="./cache/glove.6B.50d.txt", embeddings_dim=50, lower=True, prepend_bos=True, append_eos=True, ) hugging_face_corpus = HfCorpus(corpus)
[ "loguru.logger.warning", "slp.util.system.pickle_dump", "numpy.array", "os.strerror", "os.path.exists", "slp.data.transforms.HuggingFaceTokenizer", "slp.data.transforms.ToTokenIds", "numpy.asarray", "os.path.split", "itertools.chain.from_iterable", "slp.util.system.pickle_load", "slp.util.syst...
[((1924, 1939), 'collections.Counter', 'Counter', (['corpus'], {}), '(corpus)\n', (1931, 1939), False, 'from collections import Counter\n'), ((6681, 6709), 'slp.util.system.timethis', 'system.timethis', ([], {'method': '(True)'}), '(method=True)\n', (6696, 6709), True, 'import slp.util.system as system\n'), ((4549, 4584), 'os.path.split', 'os.path.split', (['self.embeddings_file'], {}), '(self.embeddings_file)\n', (4562, 4584), False, 'import os\n'), ((4607, 4629), 'os.path.splitext', 'os.path.splitext', (['tail'], {}), '(tail)\n', (4623, 4629), False, 'import os\n'), ((4828, 4863), 'loguru.logger.info', 'logger.info', (['f"""Cache: {cache_name}"""'], {}), "(f'Cache: {cache_name}')\n", (4839, 4863), False, 'from loguru import logger\n'), ((5176, 5213), 'slp.util.system.pickle_dump', 'system.pickle_dump', (['data', 'self.cache_'], {}), '(data, self.cache_)\n', (5194, 5213), True, 'import slp.util.system as system\n'), ((7686, 7742), 'loguru.logger.info', 'logger.info', (['f"""Indexing file {self.embeddings_file} ..."""'], {}), "(f'Indexing file {self.embeddings_file} ...')\n", (7697, 7742), False, 'from loguru import logger\n'), ((9829, 9866), 'numpy.array', 'np.array', (['embeddings'], {'dtype': '"""float32"""'}), "(embeddings, dtype='float32')\n", (9837, 9866), True, 'import numpy as np\n'), ((12753, 12868), 'slp.data.transforms.SpacyTokenizer', 'SpacyTokenizer', ([], {'lower': 'lower', 'prepend_bos': 'prepend_bos', 'append_eos': 'append_eos', 'specials': 'special_tokens', 'lang': 'lang'}), '(lower=lower, prepend_bos=prepend_bos, append_eos=append_eos,\n specials=special_tokens, lang=lang)\n', (12767, 12868), False, 'from slp.data.transforms import HuggingFaceTokenizer, SpacyTokenizer, ToTokenIds\n'), ((12945, 12997), 'loguru.logger.info', 'logger.info', (['f"""Tokenizing corpus using spacy {lang}"""'], {}), "(f'Tokenizing corpus using spacy {lang}')\n", (12956, 12997), False, 'from loguru import logger\n'), ((16097, 16130), 'typing.cast', 'cast', (['np.ndarray', 'cls.embeddings_'], {}), '(np.ndarray, cls.embeddings_)\n', (16101, 16130), False, 'from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast\n'), ((16315, 16350), 'typing.cast', 'cast', (['Dict[str, int]', 'cls.word2idx_'], {}), '(Dict[str, int], cls.word2idx_)\n', (16319, 16350), False, 'from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast\n'), ((16535, 16570), 'typing.cast', 'cast', (['Dict[int, str]', 'cls.idx2word_'], {}), '(Dict[int, str], cls.idx2word_)\n', (16539, 16570), False, 'from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast\n'), ((18958, 19048), 'loguru.logger.info', 'logger.info', (['f"""Tokenizing corpus using hugging face tokenizer from {tokenizer_model}"""'], {}), "(\n f'Tokenizing corpus using hugging face tokenizer from {tokenizer_model}')\n", (18969, 19048), False, 'from loguru import logger\n'), ((19092, 19192), 'slp.data.transforms.HuggingFaceTokenizer', 'HuggingFaceTokenizer', ([], {'lower': 'lower', 'model': 'tokenizer_model', 'add_special_tokens': 'add_special_tokens'}), '(lower=lower, model=tokenizer_model, add_special_tokens\n =add_special_tokens)\n', (19112, 19192), False, 'from slp.data.transforms import HuggingFaceTokenizer, SpacyTokenizer, ToTokenIds\n'), ((23400, 23451), 'slp.data.transforms.ToTokenIds', 'ToTokenIds', (['self.word2idx_'], {'specials': 'SPECIAL_TOKENS'}), '(self.word2idx_, specials=SPECIAL_TOKENS)\n', (23410, 23451), False, 'from slp.data.transforms import HuggingFaceTokenizer, SpacyTokenizer, ToTokenIds\n'), ((1874, 1911), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['corpus'], {}), '(corpus)\n', (1903, 1911), False, 'import itertools\n'), ((4784, 4819), 'os.path.join', 'os.path.join', (['head', 'f"""{filename}.p"""'], {}), "(head, f'{filename}.p')\n", (4796, 4819), False, 'import os\n'), ((5438, 5469), 'slp.util.system.pickle_load', 'system.pickle_load', (['self.cache_'], {}), '(self.cache_)\n', (5456, 5469), True, 'import slp.util.system as system\n'), ((6541, 6596), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-0.05)', 'high': '(0.05)', 'size': 'self.dim_'}), '(low=-0.05, high=0.05, size=self.dim_)\n', (6558, 6596), True, 'import numpy as np\n'), ((7144, 7193), 'loguru.logger.info', 'logger.info', (['"""Loaded word embeddings from cache."""'], {}), "('Loaded word embeddings from cache.')\n", (7155, 7193), False, 'from loguru import logger\n'), ((7484, 7520), 'os.path.exists', 'os.path.exists', (['self.embeddings_file'], {}), '(self.embeddings_file)\n', (7498, 7520), False, 'import os\n'), ((7534, 7587), 'loguru.logger.critical', 'logger.critical', (['f"""{self.embeddings_file} not found!"""'], {}), "(f'{self.embeddings_file} not found!')\n", (7549, 7587), False, 'from loguru import logger\n'), ((9053, 9125), 'tqdm.tqdm', 'tqdm', (['f'], {'total': 'num_lines', 'desc': '"""Loading word embeddings..."""', 'leave': '(False)'}), "(f, total=num_lines, desc='Loading word embeddings...', leave=False)\n", (9057, 9125), False, 'from tqdm import tqdm\n'), ((13530, 13593), 'loguru.logger.info', 'logger.info', (['"""Word2idx was already provided. Going to used it."""'], {}), "('Word2idx was already provided. Going to used it.')\n", (13541, 13593), False, 'from loguru import logger\n'), ((14273, 14328), 'loguru.logger.info', 'logger.info', (['"""Converting tokens to ids using word2idx."""'], {}), "('Converting tokens to ids using word2idx.')\n", (14284, 14328), False, 'from loguru import logger\n'), ((14361, 14412), 'slp.data.transforms.ToTokenIds', 'ToTokenIds', (['self.word2idx_'], {'specials': 'SPECIAL_TOKENS'}), '(self.word2idx_, specials=SPECIAL_TOKENS)\n', (14371, 14412), False, 'from slp.data.transforms import HuggingFaceTokenizer, SpacyTokenizer, ToTokenIds\n'), ((14766, 14809), 'loguru.logger.info', 'logger.info', (['"""Filtering corpus vocabulary."""'], {}), "('Filtering corpus vocabulary.')\n", (14777, 14809), False, 'from loguru import logger\n'), ((22983, 23038), 'loguru.logger.info', 'logger.info', (['"""Converting tokens to ids using word2idx."""'], {}), "('Converting tokens to ids using word2idx.')\n", (22994, 23038), False, 'from loguru import logger\n'), ((23103, 23204), 'loguru.logger.info', 'logger.info', (['"""No word2idx provided. Will convert tokens to ids using an iterative counter."""'], {}), "(\n 'No word2idx provided. Will convert tokens to ids using an iterative counter.'\n )\n", (23114, 23204), False, 'from loguru import logger\n'), ((7256, 7331), 'loguru.logger.warning', 'logger.warning', (['f"""Didn\'t find embeddings cache file {self.embeddings_file}"""'], {}), '(f"Didn\'t find embeddings cache file {self.embeddings_file}")\n', (7270, 7331), False, 'from loguru import logger\n'), ((7344, 7391), 'loguru.logger.warning', 'logger.warning', (['"""Loading embeddings from file."""'], {}), "('Loading embeddings from file.')\n", (7358, 7391), False, 'from loguru import logger\n'), ((7628, 7653), 'os.strerror', 'os.strerror', (['errno.ENOENT'], {}), '(errno.ENOENT)\n', (7639, 7653), False, 'import os\n'), ((8349, 8413), 'loguru.logger.debug', 'logger.debug', (['f"""Adding token {token.value} to embeddings matrix"""'], {}), "(f'Adding token {token.value} to embeddings matrix')\n", (8361, 8413), False, 'from loguru import logger\n'), ((9552, 9592), 'numpy.asarray', 'np.asarray', (['values[1:]'], {'dtype': 'np.float32'}), '(values[1:], dtype=np.float32)\n', (9562, 9592), True, 'import numpy as np\n'), ((13085, 13145), 'tqdm.tqdm', 'tqdm', (['self.corpus_'], {'desc': '"""Tokenizing corpus..."""', 'leave': '(False)'}), "(self.corpus_, desc='Tokenizing corpus...', leave=False)\n", (13089, 13145), False, 'from tqdm import tqdm\n'), ((19295, 19366), 'tqdm.tqdm', 'tqdm', (['self.corpus_'], {'desc': '"""Converting tokens to indices..."""', 'leave': '(False)'}), "(self.corpus_, desc='Converting tokens to indices...', leave=False)\n", (19299, 19366), False, 'from tqdm import tqdm\n'), ((19505, 19581), 'tqdm.tqdm', 'tqdm', (['self.corpus_indices_'], {'desc': '"""Mapping indices to tokens..."""', 'leave': '(False)'}), "(self.corpus_indices_, desc='Mapping indices to tokens...', leave=False)\n", (19509, 19581), False, 'from tqdm import tqdm\n'), ((8237, 8256), 'numpy.zeros', 'np.zeros', (['self.dim_'], {}), '(self.dim_)\n', (8245, 8256), True, 'import numpy as np\n'), ((8776, 8795), 'numpy.zeros', 'np.zeros', (['self.dim_'], {}), '(self.dim_)\n', (8784, 8795), True, 'import numpy as np\n'), ((14576, 14663), 'tqdm.tqdm', 'tqdm', (['self.tokenized_corpus_'], {'desc': '"""Converting tokens to token ids..."""', 'leave': '(False)'}), "(self.tokenized_corpus_, desc='Converting tokens to token ids...',\n leave=False)\n", (14580, 14663), False, 'from tqdm import tqdm\n'), ((23283, 23300), 'itertools.count', 'itertools.count', ([], {}), '()\n', (23298, 23300), False, 'import itertools\n'), ((23659, 23746), 'tqdm.tqdm', 'tqdm', (['self.tokenized_corpus_'], {'desc': '"""Converting tokens to token ids..."""', 'leave': '(False)'}), "(self.tokenized_corpus_, desc='Converting tokens to token ids...',\n leave=False)\n", (23663, 23746), False, 'from tqdm import tqdm\n')]
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import pickle import unittest from math import prod import numpy as np import torch from rlmeta.core.segment_tree import SumSegmentTree, MinSegmentTree from tests.test_utils import TestCaseBase class SumSegmentTreeTest(TestCaseBase): def setUp(self) -> None: self.size = 100 self.data = torch.randn(self.size) self.segment_tree = SumSegmentTree(self.size) self.segment_tree[torch.arange(self.size)] = self.data self.query_size = (2, 3, 4) def test_at(self) -> None: index = torch.randint(self.size, self.query_size) value = self.segment_tree[index] self.assert_tensor_equal(value, self.data[index]) value = self.segment_tree.at(index) self.assert_tensor_equal(value, self.data[index]) def test_update(self) -> None: weights = torch.ones(self.size) index = weights.multinomial(prod(self.query_size), replacement=False) index = index.view(self.query_size) origin_value = self.segment_tree[index] value = np.random.randn() self.segment_tree[index] = value self.assert_tensor_equal(self.segment_tree[index], torch.full(self.query_size, value)) self.segment_tree[index] = origin_value value = np.random.randn() self.segment_tree.update(index, value) self.assert_tensor_equal(self.segment_tree[index], torch.full(self.query_size, value)) self.segment_tree[index] = origin_value value = torch.randn(self.query_size) self.segment_tree[index] = value self.assert_tensor_equal(self.segment_tree[index], value) self.segment_tree[index] = origin_value value = torch.randn(self.query_size) self.segment_tree.update(index, value) self.assert_tensor_equal(self.segment_tree[index], value) self.segment_tree[index] = origin_value def test_query(self) -> None: a = torch.randint(self.size, self.query_size) b = torch.randint(self.size, self.query_size) l = torch.minimum(a, b) r = torch.maximum(a, b) value = self.segment_tree.query(l, r) l_list = l.view(-1).tolist() r_list = r.view(-1).tolist() ret = [] for (x, y) in zip(l_list, r_list): ret.append(self.data[x:y].sum()) ret = torch.tensor(ret).view(self.query_size) self.assert_tensor_close(value, ret, rtol=1e-6, atol=1e-6) def test_pickle(self) -> None: s = pickle.dumps(self.segment_tree) t = pickle.loads(s) self.assert_tensor_equal(t[torch.arange(self.size)], self.data) for _ in range(10): l = np.random.randint(self.size) r = np.random.randint(self.size) if l > r: l, r = r, l ret = t.query(l, r) ans = self.data[l:r].sum().item() self.assertAlmostEqual(ret, ans, places=5) if __name__ == "__main__": unittest.main()
[ "torch.maximum", "rlmeta.core.segment_tree.SumSegmentTree", "torch.full", "pickle.dumps", "pickle.loads", "math.prod", "torch.randint", "numpy.random.randint", "torch.tensor", "unittest.main", "torch.minimum", "numpy.random.randn", "torch.randn", "torch.arange", "torch.ones" ]
[((3193, 3208), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3206, 3208), False, 'import unittest\n'), ((493, 515), 'torch.randn', 'torch.randn', (['self.size'], {}), '(self.size)\n', (504, 515), False, 'import torch\n'), ((544, 569), 'rlmeta.core.segment_tree.SumSegmentTree', 'SumSegmentTree', (['self.size'], {}), '(self.size)\n', (558, 569), False, 'from rlmeta.core.segment_tree import SumSegmentTree, MinSegmentTree\n'), ((717, 758), 'torch.randint', 'torch.randint', (['self.size', 'self.query_size'], {}), '(self.size, self.query_size)\n', (730, 758), False, 'import torch\n'), ((1014, 1035), 'torch.ones', 'torch.ones', (['self.size'], {}), '(self.size)\n', (1024, 1035), False, 'import torch\n'), ((1223, 1240), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (1238, 1240), True, 'import numpy as np\n'), ((1475, 1492), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (1490, 1492), True, 'import numpy as np\n'), ((1733, 1761), 'torch.randn', 'torch.randn', (['self.query_size'], {}), '(self.query_size)\n', (1744, 1761), False, 'import torch\n'), ((1934, 1962), 'torch.randn', 'torch.randn', (['self.query_size'], {}), '(self.query_size)\n', (1945, 1962), False, 'import torch\n'), ((2171, 2212), 'torch.randint', 'torch.randint', (['self.size', 'self.query_size'], {}), '(self.size, self.query_size)\n', (2184, 2212), False, 'import torch\n'), ((2225, 2266), 'torch.randint', 'torch.randint', (['self.size', 'self.query_size'], {}), '(self.size, self.query_size)\n', (2238, 2266), False, 'import torch\n'), ((2279, 2298), 'torch.minimum', 'torch.minimum', (['a', 'b'], {}), '(a, b)\n', (2292, 2298), False, 'import torch\n'), ((2311, 2330), 'torch.maximum', 'torch.maximum', (['a', 'b'], {}), '(a, b)\n', (2324, 2330), False, 'import torch\n'), ((2727, 2758), 'pickle.dumps', 'pickle.dumps', (['self.segment_tree'], {}), '(self.segment_tree)\n', (2739, 2758), False, 'import pickle\n'), ((2771, 2786), 'pickle.loads', 'pickle.loads', (['s'], {}), '(s)\n', (2783, 2786), False, 'import pickle\n'), ((596, 619), 'torch.arange', 'torch.arange', (['self.size'], {}), '(self.size)\n', (608, 619), False, 'import torch\n'), ((1072, 1093), 'math.prod', 'prod', (['self.query_size'], {}), '(self.query_size)\n', (1076, 1093), False, 'from math import prod\n'), ((1374, 1408), 'torch.full', 'torch.full', (['self.query_size', 'value'], {}), '(self.query_size, value)\n', (1384, 1408), False, 'import torch\n'), ((1632, 1666), 'torch.full', 'torch.full', (['self.query_size', 'value'], {}), '(self.query_size, value)\n', (1642, 1666), False, 'import torch\n'), ((2903, 2931), 'numpy.random.randint', 'np.random.randint', (['self.size'], {}), '(self.size)\n', (2920, 2931), True, 'import numpy as np\n'), ((2948, 2976), 'numpy.random.randint', 'np.random.randint', (['self.size'], {}), '(self.size)\n', (2965, 2976), True, 'import numpy as np\n'), ((2571, 2588), 'torch.tensor', 'torch.tensor', (['ret'], {}), '(ret)\n', (2583, 2588), False, 'import torch\n'), ((2822, 2845), 'torch.arange', 'torch.arange', (['self.size'], {}), '(self.size)\n', (2834, 2845), False, 'import torch\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt def dist_comp(df, bins, filepath, cfg): # Define columns all_columns = list(df.index.names) columns_noname = [c for c in all_columns if c != "name"] columns_nobins = [c for c in all_columns if "bin" not in c] # Remove under and overflow bins (add overflow into final bin) def truncate(indf): indf.iloc[-2] += indf.iloc[-1] indf = indf.iloc[1:-1] indf = indf.reset_index(columns_nobins, drop=True) return indf df = df.groupby(columns_nobins).apply(truncate) bins = bins[0][1:-1] df_pivot_name = df.pivot_table( values = 'yield', index = columns_noname, columns = 'name', aggfunc = np.sum, ) name_uncorr = [c for c in df_pivot_name.columns if "corrected" not in c].pop() name_corr = [c for c in df_pivot_name.columns if "corrected" in c].pop() df_uncorr = df_pivot_name[name_uncorr] df_corr = df_pivot_name[name_corr] df_uncorr.columns = ['yield'] df_corr.columns = ['yield'] df_pivot_uncorr = df_uncorr.unstack(level='key') df_pivot_corr = df_corr.unstack(level='key') df_pivot_ratio = df_pivot_corr / df_pivot_uncorr # Get the global bins xlow = df_pivot_uncorr.index.get_level_values("bin0_low").values xupp = df_pivot_uncorr.index.get_level_values("bin0_upp").values xcenters = (xupp+xlow)/2 # Split axis into top and bottom with ratio 3:1 # Share the x axis, not the y axis # Figure size is 4.8 by 6.4 inches fig, (axtop, axbot) = plt.subplots( nrows=2, ncols=1, sharex='col', sharey=False, gridspec_kw={'height_ratios': [3, 1]}, figsize = (4.8, 6.4), ) if cfg.log: axtop.set_yscale('log') # Draw hists all_keys = list(df.index.get_level_values("key").unique()) axtop.hist( [xcenters]*len(all_keys), bins = bins, weights = [df_pivot_uncorr[k] for k in all_keys], histtype = 'step', color = [cfg.sample_colours.get(k, "blue") for k in all_keys], label = [cfg.sample_names.get(k, k) for k in all_keys], ls = '--', ) handles, labels = axtop.get_legend_handles_labels() axtop.hist( [xcenters]*len(all_keys), bins = bins, weights = [df_pivot_corr[k] for k in all_keys], histtype = 'step', color = [cfg.sample_colours.get(k, "blue") for k in all_keys], label = [cfg.sample_names.get(k, k) for k in all_keys], ) handles_corr, labels_corr = axtop.get_legend_handles_labels() handles_corr = handles_corr[len(handles):] labels_corr = labels_corr[len(labels):] labels_corr = [l+" corr." for l in labels_corr] labels = reduce(lambda x,y: x+y, list(zip(labels, labels_corr))) handles = reduce(lambda x,y: x+y, list(zip(handles, handles_corr))) axtop.set_xlim(bins[0], bins[-1]) # Add CMS text to top + energy + lumi axtop.text(0, 1, r'$\mathbf{CMS}\ \mathit{Preliminary}$', horizontalalignment='left', verticalalignment='bottom', transform=axtop.transAxes, fontsize='large') axtop.text(1, 1, r'$35.9\ \mathrm{fb}^{-1}(13\ \mathrm{TeV})$', horizontalalignment='right', verticalalignment='bottom', transform=axtop.transAxes, fontsize='large') # Legend - reverse the labels axtop.legend(handles, labels) # Ratio in bottom panel axbot.hist( [xcenters]*len(all_keys), bins = bins, weights = [df_pivot_ratio[k] for k in all_keys], histtype = 'step', color = [cfg.sample_colours.get(k, 'blue') for k in all_keys], ) axbot.axhline(1, ls='--', color='gray') name = cfg.name ymin = min(df_pivot_ratio[all_keys].min()) ymax = max(df_pivot_ratio[all_keys].max()) padding = (ymax - ymin)*0.05 if not (np.isinf(ymin) or np.isnan(ymin) or np.isinf(ymax) or np.isnan(ymax)): axbot.set_ylim((ymin-padding, ymax+padding)) axbot.set_xlabel(cfg.axis_label.get(name, name), fontsize='large') axbot.set_ylabel(r'$1 + \kappa_{EW}$', fontsize='large') # Report print("Creating {}.pdf".format(filepath)) # Actually save the figure plt.tight_layout() fig.savefig(filepath+".pdf", format="pdf", bbox_inches="tight") plt.close(fig) return df
[ "matplotlib.pyplot.close", "numpy.isnan", "matplotlib.pyplot.tight_layout", "numpy.isinf", "matplotlib.pyplot.subplots" ]
[((1584, 1706), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(1)', 'sharex': '"""col"""', 'sharey': '(False)', 'gridspec_kw': "{'height_ratios': [3, 1]}", 'figsize': '(4.8, 6.4)'}), "(nrows=2, ncols=1, sharex='col', sharey=False, gridspec_kw={\n 'height_ratios': [3, 1]}, figsize=(4.8, 6.4))\n", (1596, 1706), True, 'import matplotlib.pyplot as plt\n'), ((4315, 4333), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4331, 4333), True, 'import matplotlib.pyplot as plt\n'), ((4406, 4420), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (4415, 4420), True, 'import matplotlib.pyplot as plt\n'), ((3942, 3956), 'numpy.isinf', 'np.isinf', (['ymin'], {}), '(ymin)\n', (3950, 3956), True, 'import numpy as np\n'), ((3960, 3974), 'numpy.isnan', 'np.isnan', (['ymin'], {}), '(ymin)\n', (3968, 3974), True, 'import numpy as np\n'), ((3978, 3992), 'numpy.isinf', 'np.isinf', (['ymax'], {}), '(ymax)\n', (3986, 3992), True, 'import numpy as np\n'), ((3996, 4010), 'numpy.isnan', 'np.isnan', (['ymax'], {}), '(ymax)\n', (4004, 4010), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import cv2 import sys import numpy as np import imutils from skimage.filters import threshold_local def vid_to_frames(filename, write=False): vidcap = cv2.VideoCapture(filename) success, image = vidcap.read() count = 0 images = [] while success: if write: cv2.imwrite("frames/frame%d.jpg" % count, image) # save frame as JPEG file else: images.append(image) success, image = vidcap.read() count += 1 return images def order_points(pts): # order 4 points by top-left, top-right, bottom-right, bottom-left rect = np.zeros((4, 2), dtype="float32") s = pts.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] # return the ordered coordinates return rect def get_homography(points, dst): # Gets the homography transformation matrix from a set of 4 points to another 4 points rect = order_points(points) dst = np.array([[0, 0], [dst[0] - 1, 0], [dst[0] - 1, dst[1] - 1], [0, dst[1] - 1]], dtype="float32") return cv2.getPerspectiveTransform(rect, dst) def get_points(image): # Resize image for optimization purposes ratio = image.shape[0] / 500.0 orig = image.copy() image = imutils.resize(image, height=500) # convert the image to grayscale, blur it, and find edges in the image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(gray, 75, 200) # find the contours in the edged image, keeping only the largest ones cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5] for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) # if our approximated contour has four points, then we # can assume that we have found our screen if len(approx) == 4: return (approx * ratio).astype(int) if (len(sys.argv) < 3): print("Error: " + sys.argv[0] + " <video-path> <template-path> <optional-output-path>", file=sys.stderr) exit(1) args = {"video": sys.argv[1], "template": sys.argv[2], "output": sys.argv[3] if len(sys.argv) > 3 else 'nasty.mp4'} frames = vid_to_frames(args["video"]) template = cv2.imread(args["template"]) out_video = cv2.VideoWriter(args["output"], cv2.VideoWriter_fourcc( *'mp4v'), 30, (template.shape[1], template.shape[0])) points = get_points(frames[0]).reshape(4, 2) homography = get_homography(points, template.shape) for f in range(len(frames)): # cv2.drawContours(frames[f], [paper_pts], -1, (0, 255, 0), 2) # cv2.imwrite(f"output/frame{f}-drawn.jpg", frames[f]) warped = cv2.warpPerspective(frames[f], homography, template.shape[:2]) # cv2.imwrite(f"output/frame{f}.jpg", cv2.rotate(warped, cv2.ROTATE_90_CLOCKWISE), (1275, 1650)) out_video.write(cv2.rotate(warped, cv2.ROTATE_90_CLOCKWISE)) out_video.release()
[ "numpy.array", "cv2.warpPerspective", "cv2.approxPolyDP", "cv2.arcLength", "numpy.diff", "imutils.grab_contours", "cv2.VideoWriter_fourcc", "numpy.argmin", "cv2.getPerspectiveTransform", "numpy.argmax", "cv2.cvtColor", "cv2.Canny", "cv2.GaussianBlur", "cv2.imread", "cv2.imwrite", "cv2....
[((2619, 2647), 'cv2.imread', 'cv2.imread', (["args['template']"], {}), "(args['template'])\n", (2629, 2647), False, 'import cv2\n'), ((180, 206), 'cv2.VideoCapture', 'cv2.VideoCapture', (['filename'], {}), '(filename)\n', (196, 206), False, 'import cv2\n'), ((630, 663), 'numpy.zeros', 'np.zeros', (['(4, 2)'], {'dtype': '"""float32"""'}), "((4, 2), dtype='float32')\n", (638, 663), True, 'import numpy as np\n'), ((765, 785), 'numpy.diff', 'np.diff', (['pts'], {'axis': '(1)'}), '(pts, axis=1)\n', (772, 785), True, 'import numpy as np\n'), ((1079, 1179), 'numpy.array', 'np.array', (['[[0, 0], [dst[0] - 1, 0], [dst[0] - 1, dst[1] - 1], [0, dst[1] - 1]]'], {'dtype': '"""float32"""'}), "([[0, 0], [dst[0] - 1, 0], [dst[0] - 1, dst[1] - 1], [0, dst[1] - 1\n ]], dtype='float32')\n", (1087, 1179), True, 'import numpy as np\n'), ((1266, 1304), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['rect', 'dst'], {}), '(rect, dst)\n', (1293, 1304), False, 'import cv2\n'), ((1446, 1479), 'imutils.resize', 'imutils.resize', (['image'], {'height': '(500)'}), '(image, height=500)\n', (1460, 1479), False, 'import imutils\n'), ((1567, 1606), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (1579, 1606), False, 'import cv2\n'), ((1618, 1651), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['gray', '(5, 5)', '(0)'], {}), '(gray, (5, 5), 0)\n', (1634, 1651), False, 'import cv2\n'), ((1664, 1688), 'cv2.Canny', 'cv2.Canny', (['gray', '(75)', '(200)'], {}), '(gray, 75, 200)\n', (1673, 1688), False, 'import cv2\n'), ((1857, 1884), 'imutils.grab_contours', 'imutils.grab_contours', (['cnts'], {}), '(cnts)\n', (1878, 1884), False, 'import imutils\n'), ((2692, 2723), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mp4v'"], {}), "(*'mp4v')\n", (2714, 2723), False, 'import cv2\n'), ((3042, 3104), 'cv2.warpPerspective', 'cv2.warpPerspective', (['frames[f]', 'homography', 'template.shape[:2]'], {}), '(frames[f], homography, template.shape[:2])\n', (3061, 3104), False, 'import cv2\n'), ((707, 719), 'numpy.argmin', 'np.argmin', (['s'], {}), '(s)\n', (716, 719), True, 'import numpy as np\n'), ((739, 751), 'numpy.argmax', 'np.argmax', (['s'], {}), '(s)\n', (748, 751), True, 'import numpy as np\n'), ((804, 819), 'numpy.argmin', 'np.argmin', (['diff'], {}), '(diff)\n', (813, 819), True, 'import numpy as np\n'), ((839, 854), 'numpy.argmax', 'np.argmax', (['diff'], {}), '(diff)\n', (848, 854), True, 'import numpy as np\n'), ((2017, 2039), 'cv2.arcLength', 'cv2.arcLength', (['c', '(True)'], {}), '(c, True)\n', (2030, 2039), False, 'import cv2\n'), ((2057, 2095), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['c', '(0.02 * peri)', '(True)'], {}), '(c, 0.02 * peri, True)\n', (2073, 2095), False, 'import cv2\n'), ((3226, 3269), 'cv2.rotate', 'cv2.rotate', (['warped', 'cv2.ROTATE_90_CLOCKWISE'], {}), '(warped, cv2.ROTATE_90_CLOCKWISE)\n', (3236, 3269), False, 'import cv2\n'), ((321, 369), 'cv2.imwrite', 'cv2.imwrite', (["('frames/frame%d.jpg' % count)", 'image'], {}), "('frames/frame%d.jpg' % count, image)\n", (332, 369), False, 'import cv2\n')]
# Authors: # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD 3 clause """ Sphere element """ # pylint: disable=invalid-name import logging # from textwrap import dedent import numpy as np from .base import Element from .utils import distance_ellipsoid log = logging.getLogger(__name__) # pylint: disable=invalid-name class Sphere(Element): """ Class Sphere Parameters ---------- center : list the three coordinates of the center radius : real a positive real number for the radius label : list one integer (default [0]) isfluid : boolean - True if the sphere is added - False if the sphere is deleted Attributes ---------- number_of_bounds : int 1 dim: int 3 center : ndarray the coordinates of the center of the sphere radius : real a positive real number for the radius of the sphere label : list the list of the label of the edge isfluid : boolean True if the sphere is added and False if the sphere is deleted Examples -------- the sphere centered in (0, 0, 0) with radius 1 >>> center = [0., 0., 0.] >>> radius = 1. >>> Sphere(center, radius) +--------+ | Sphere | +--------+ - dimension: 3 - center: [0. 0. 0.] - radius: 1.0 - label: [0] - type: solid """ def __init__(self, center, radius, label=0, isfluid=False): self.number_of_bounds = 1 # number of edges self.dim = 3 self.center = np.asarray(center) if radius >= 0: self.radius = radius else: log.error('The radius of the sphere should be positive') super(Sphere, self).__init__(label, isfluid) log.info(self.__str__()) def get_bounds(self): """ Get the bounds of the sphere. """ return self.center - self.radius, self.center + self.radius def point_inside(self, grid): """ return a boolean array which defines if a point is inside or outside of the sphere. Notes ----- the edge of the sphere is considered as inside. Parameters ---------- grid : ndarray coordinates of the points Returns ------- ndarray Array of boolean (True inside the sphere, False otherwise) """ x, y, z = grid v2 = np.asarray([ x - self.center[0], y - self.center[1], z - self.center[2] ]) return (v2[0]**2 + v2[1]**2 + v2[2]**2) <= self.radius**2 def distance(self, grid, v, dmax=None): """ Compute the distance in the v direction between the sphere and the points defined by (x, y, z). .. image:: ../figures/Sphere.png :width: 100% Parameters ---------- grid : ndarray coordinates of the points v : ndarray direction of interest dmax : float distance max Returns ------- ndarray array of distances """ x, y, z = grid v1 = self.radius*np.array([1, 0, 0]) v2 = self.radius*np.array([0, 1, 0]) v3 = self.radius*np.array([0, 0, 1]) return distance_ellipsoid( x, y, z, v, self.center, v1, v2, v3, dmax, self.label ) def __str__(self): from ..utils import header_string from ..jinja_env import env template = env.get_template('circle.tpl') elem_type = 'fluid' if self.isfluid else 'solid' return template.render( header=header_string(self.__class__.__name__), elem=self, type=elem_type ) def visualize(self, viewer, color, viewlabel=False, scale=np.ones(3), alpha=1. ): v1 = self.radius*np.array([1, 0, 0])*scale v2 = self.radius*np.array([0, 1, 0])*scale v3 = self.radius*np.array([0, 0, 1])*scale viewer.ellipse_3d(self.center*scale, v1, v2, v3, color, alpha=alpha) if viewlabel: x, y, z = self.center[0], self.center[1], self.center[2] viewer.text(str(self.label[0]), [x, y, z])
[ "logging.getLogger", "numpy.array", "numpy.asarray", "numpy.ones" ]
[((276, 303), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (293, 303), False, 'import logging\n'), ((1591, 1609), 'numpy.asarray', 'np.asarray', (['center'], {}), '(center)\n', (1601, 1609), True, 'import numpy as np\n'), ((2497, 2569), 'numpy.asarray', 'np.asarray', (['[x - self.center[0], y - self.center[1], z - self.center[2]]'], {}), '([x - self.center[0], y - self.center[1], z - self.center[2]])\n', (2507, 2569), True, 'import numpy as np\n'), ((3941, 3951), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (3948, 3951), True, 'import numpy as np\n'), ((3261, 3280), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (3269, 3280), True, 'import numpy as np\n'), ((3306, 3325), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (3314, 3325), True, 'import numpy as np\n'), ((3351, 3370), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (3359, 3370), True, 'import numpy as np\n'), ((4008, 4027), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (4016, 4027), True, 'import numpy as np\n'), ((4059, 4078), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (4067, 4078), True, 'import numpy as np\n'), ((4110, 4129), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (4118, 4129), True, 'import numpy as np\n')]
import cv2 import os import re import numpy as np from multiprocessing import Pool import pickle root_folder = './NTURGBD' rgb_folder = os.path.join(root_folder, './nturgb+d_rgb') depth_folder = os.path.join(root_folder, './nturgb+d_depth_masked') skeleton_folder = os.path.join(root_folder, './nturgb+d_skeletons') tags = os.listdir(rgb_folder) tags = [f.split('_')[0] for f in tags] video_set = [] compiled_regex = re.compile('.*S(\d{3})C(\d{3})P(\d{3})R(\d{3})A(\d{3}).*') for t in tags: match = re.match(compiled_regex, t) setup, camera, performer, replication, action = [*map(int, match.groups())] video_set.append((setup, camera)) def process_video_set(target_video_set): print("Starting {}".format(target_video_set)) rgb = [] d = [] for i in range(len(tags)): if video_set[i] != target_video_set or np.random.rand() > 0.5: continue with open(os.path.join(skeleton_folder, tags[i] + '.skeleton'), 'r') as fd: data = fd.readlines() joint_data = [] for frame_idx in range(int(data.pop(0))): for body_idx in range(int(data.pop(0))): body = data.pop(0) for joint_idx in range(int(data.pop(0))): line = data.pop(0).split() if body_idx == 0: joint_data.append((frame_idx, body_idx, joint_idx, line[:7])) depth = [] color = [] for joint in joint_data: x = np.array(joint[3], dtype=np.float32) depth.append(x[3:5]) color.append(x[5:7]) if len(depth) == 0: assert len(color) == 0 continue d.append(np.stack(depth)) rgb.append(np.stack(color)) rgb = np.concatenate(rgb).astype(np.float32) d = np.concatenate(d).astype(np.float32) H, _ = cv2.findHomography(rgb, d, cv2.RANSAC) print("Finishing {}".format(target_video_set)) return (target_video_set, H) def process_tag(arg): tag = arg[0] H = arg[1] print("Starting {}".format(tag)) target_folder = os.path.join(root_folder, './nturgb+d_rgb_warped_correction', tag) if not os.path.exists(target_folder): os.makedirs(target_folder, exist_ok=True) vidcap = cv2.VideoCapture(os.path.join(rgb_folder, tag + '_rgb.avi')) counter = 1 success = 1 while success: success, image = vidcap.read() if not success: break warped_image = cv2.warpPerspective(image, H, (512, 424)) save_image_fname = os.path.join(target_folder, 'WRGB-{}.jpg'.format(str(counter).zfill(8))) cv2.imwrite(save_image_fname, warped_image) counter += 1 print("Finishing {} with {} frames".format(tag, counter)) if __name__ == '__main__': unique_video_set = set(video_set) processNum = 16 pool = Pool(processNum) print("Calculating the Homography...") return_value = pool.map(process_video_set, list(unique_video_set)) homography_dict = {d[0]: d[1] for d in return_value} pickle.dump(homography_dict, open('homography_dict_correction.pkl', 'wb')) print("Warping RGB...") print("Before tags num: {}".format(len(tags))) exclude_list = open('./NTU_RGBD_samples_with_missing_skeletons.txt', 'r').readlines() exclude_list = [l.strip() for l in exclude_list] new_tags = [t for t in tags if t not in exclude_list] print("After tags num: {}".format(len(new_tags))) homography_dict = pickle.load(open('homography_dict_correction.pkl', 'rb')) args = [] for k in homography_dict.keys(): ind = video_set.index(k) args.append((new_tags[ind], homography_dict[k])) pool.map(process_tag, args)
[ "os.path.exists", "cv2.imwrite", "os.listdir", "numpy.random.rand", "os.makedirs", "cv2.findHomography", "re.compile", "os.path.join", "re.match", "numpy.array", "cv2.warpPerspective", "numpy.stack", "multiprocessing.Pool", "numpy.concatenate" ]
[((137, 180), 'os.path.join', 'os.path.join', (['root_folder', '"""./nturgb+d_rgb"""'], {}), "(root_folder, './nturgb+d_rgb')\n", (149, 180), False, 'import os\n'), ((196, 248), 'os.path.join', 'os.path.join', (['root_folder', '"""./nturgb+d_depth_masked"""'], {}), "(root_folder, './nturgb+d_depth_masked')\n", (208, 248), False, 'import os\n'), ((267, 316), 'os.path.join', 'os.path.join', (['root_folder', '"""./nturgb+d_skeletons"""'], {}), "(root_folder, './nturgb+d_skeletons')\n", (279, 316), False, 'import os\n'), ((325, 347), 'os.listdir', 'os.listdir', (['rgb_folder'], {}), '(rgb_folder)\n', (335, 347), False, 'import os\n'), ((420, 483), 're.compile', 're.compile', (['""".*S(\\\\d{3})C(\\\\d{3})P(\\\\d{3})R(\\\\d{3})A(\\\\d{3}).*"""'], {}), "('.*S(\\\\d{3})C(\\\\d{3})P(\\\\d{3})R(\\\\d{3})A(\\\\d{3}).*')\n", (430, 483), False, 'import re\n'), ((506, 533), 're.match', 're.match', (['compiled_regex', 't'], {}), '(compiled_regex, t)\n', (514, 533), False, 'import re\n'), ((1849, 1887), 'cv2.findHomography', 'cv2.findHomography', (['rgb', 'd', 'cv2.RANSAC'], {}), '(rgb, d, cv2.RANSAC)\n', (1867, 1887), False, 'import cv2\n'), ((2084, 2150), 'os.path.join', 'os.path.join', (['root_folder', '"""./nturgb+d_rgb_warped_correction"""', 'tag'], {}), "(root_folder, './nturgb+d_rgb_warped_correction', tag)\n", (2096, 2150), False, 'import os\n'), ((2846, 2862), 'multiprocessing.Pool', 'Pool', (['processNum'], {}), '(processNum)\n', (2850, 2862), False, 'from multiprocessing import Pool\n'), ((2162, 2191), 'os.path.exists', 'os.path.exists', (['target_folder'], {}), '(target_folder)\n', (2176, 2191), False, 'import os\n'), ((2201, 2242), 'os.makedirs', 'os.makedirs', (['target_folder'], {'exist_ok': '(True)'}), '(target_folder, exist_ok=True)\n', (2212, 2242), False, 'import os\n'), ((2273, 2315), 'os.path.join', 'os.path.join', (['rgb_folder', "(tag + '_rgb.avi')"], {}), "(rgb_folder, tag + '_rgb.avi')\n", (2285, 2315), False, 'import os\n'), ((2472, 2513), 'cv2.warpPerspective', 'cv2.warpPerspective', (['image', 'H', '(512, 424)'], {}), '(image, H, (512, 424))\n', (2491, 2513), False, 'import cv2\n'), ((2622, 2665), 'cv2.imwrite', 'cv2.imwrite', (['save_image_fname', 'warped_image'], {}), '(save_image_fname, warped_image)\n', (2633, 2665), False, 'import cv2\n'), ((1487, 1523), 'numpy.array', 'np.array', (['joint[3]'], {'dtype': 'np.float32'}), '(joint[3], dtype=np.float32)\n', (1495, 1523), True, 'import numpy as np\n'), ((1691, 1706), 'numpy.stack', 'np.stack', (['depth'], {}), '(depth)\n', (1699, 1706), True, 'import numpy as np\n'), ((1727, 1742), 'numpy.stack', 'np.stack', (['color'], {}), '(color)\n', (1735, 1742), True, 'import numpy as np\n'), ((1754, 1773), 'numpy.concatenate', 'np.concatenate', (['rgb'], {}), '(rgb)\n', (1768, 1773), True, 'import numpy as np\n'), ((1801, 1818), 'numpy.concatenate', 'np.concatenate', (['d'], {}), '(d)\n', (1815, 1818), True, 'import numpy as np\n'), ((846, 862), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (860, 862), True, 'import numpy as np\n'), ((909, 961), 'os.path.join', 'os.path.join', (['skeleton_folder', "(tags[i] + '.skeleton')"], {}), "(skeleton_folder, tags[i] + '.skeleton')\n", (921, 961), False, 'import os\n')]
import numpy as np import hetu as ht from hetu import gpu_links as gpu_op def test_adamw(): ctx = ht.gpu(0) shape = (500,400) param = np.random.uniform(-10, 10, size=shape).astype(np.float32) grad = np.random.uniform(-10, 10, size=shape).astype(np.float32) m = np.random.uniform(-10, 10, size=shape).astype(np.float32) v = np.random.uniform(0, 10, size=shape).astype(np.float32) lr = 1e-2 beta1 = 0.9 beta2 = 0.99 beta1t = beta1**10 beta2t = beta2**10 eps = 1e-7 weight_decay = 0.1 print("Prev param:") print(param) print("Prev m:") print(m) print("Prev v:") print(v) arr_param = ht.array(param, ctx) arr_grad = ht.array(grad, ctx) arr_m = ht.array(m, ctx) arr_v = ht.array(v, ctx) gpu_op.adamw_update(arr_param, arr_grad, arr_m, arr_v, lr, beta1, beta2, beta1t, beta2t, eps, weight_decay) re_param = arr_param.asnumpy() re_m = arr_m.asnumpy() re_v = arr_v.asnumpy() m = beta1 * m + (1 - beta1) * grad v = beta2 * v + (1 - beta2) * grad * grad mc = m / (1 - beta1t) vc = v / (1 - beta2t) update = mc / (np.sqrt(vc) + eps) param = param - lr * (update + weight_decay * param) print("Cur param:") print(re_param) print(param) print("Cur m:") print(re_m) print(m) print("Cur v:") print(re_v) print(v) np.testing.assert_allclose(re_param, param, atol=1e-5) np.testing.assert_allclose(re_m, m, atol=1e-5) np.testing.assert_allclose(re_v, v, atol=1e-5) def test_lamb(): ctx = ht.gpu(0) shape = (4,5) param = np.random.uniform(-10, 10, size=shape).astype(np.float32) grad = np.random.uniform(-10, 10, size=shape).astype(np.float32) m = np.random.uniform(-10, 10, size=shape).astype(np.float32) v = np.random.uniform(0, 10, size=shape).astype(np.float32) lr = 1e-2 beta1 = 0.9 beta2 = 0.99 beta1t = beta1**10 beta2t = beta2**10 eps = 1e-7 weight_decay = 0.1 print("Prev param:") print(param) print("Prev m:") print(m) print("Prev v:") print(v) arr_param = ht.array(param, ctx) arr_grad = ht.array(grad, ctx) arr_m = ht.array(m, ctx) arr_v = ht.array(v, ctx) gpu_op.lamb_update(arr_param, arr_grad, arr_m, arr_v, lr, beta1, beta2, beta1t, beta2t, eps, weight_decay) re_param = arr_param.asnumpy() re_m = arr_m.asnumpy() re_v = arr_v.asnumpy() m = beta1 * m + (1 - beta1) * grad v = beta2 * v + (1 - beta2) * grad * grad mc = m / (1 - beta1t) vc = v / (1 - beta2t) update = mc / (np.sqrt(vc) + eps) norm2_param = np.sqrt(np.sum(np.power(param, 2))) norm2_update = np.sqrt(np.sum(np.power(update, 2))) param = param - lr * norm2_param / norm2_update * (update + weight_decay * param) print("Cur param:") print(re_param) print(param) print("Cur m:") print(re_m) print(m) print("Cur v:") print(re_v) print(v) np.testing.assert_allclose(re_param, param, atol=1e-5) np.testing.assert_allclose(re_m, m, atol=1e-5) np.testing.assert_allclose(re_v, v, atol=1e-5) def test_adamw_sparse(): ctx = ht.gpu(0) shape = (500, 400) l = np.random.randint(0,500,size=(100)) indices = np.array(l) param = np.random.uniform(-10, 10, size=shape).astype(np.float32) grad = np.random.uniform(-10, 10, size=(indices.shape[0], shape[1])).astype(np.float32) m = np.random.uniform(-10, 10, size=shape).astype(np.float32) v = np.random.uniform(0, 10, size=shape).astype(np.float32) lr = 1e-2 beta1 = 0.9 beta2 = 0.99 beta1t = beta1**10 beta2t = beta2**10 eps = 1e-7 weight_decay = 0.1 print("Prev param:") print(param) print("Prev m:") print(m) print("Prev v:") print(v) print("Indices:") print(indices) print("Grad:") print(grad) arr_param = ht.array(param, ctx) arr_indices = ht.array(indices, ctx) arr_value = ht.array(grad, ctx) arr_grad = ht.IndexedSlices(indices = arr_indices, values = arr_value, dense_shape = shape) arr_m = ht.array(m, ctx) arr_v = ht.array(v, ctx) gpu_op.adamw_update(arr_param, arr_grad, arr_m, arr_v, lr, beta1, beta2, beta1t, beta2t, eps, weight_decay) re_param = arr_param.asnumpy() re_m = arr_m.asnumpy() re_v = arr_v.asnumpy() # numpy deduplicate d = dict() for i in l: d[i]=[] for i, g in zip(l, grad): d[i].append(g) for key in d.keys(): g0 = d[key][0] for i in range(1, len(d[key])): g0 += d[key][i] d[key] = g0 grad_new = [] l_new = [] for key in d.keys(): l_new.append(key) grad_new.append(d[key]) grad_new = np.array(grad_new) for idx, g in zip(l_new, grad_new): m[idx] = beta1 * m[idx] + (1 - beta1) * g v[idx] = beta2 * v[idx] + (1 - beta2) * g * g mc_idx = m[idx] / (1 - beta1t) vc_idx = v[idx] / (1 - beta2t) update = mc_idx / (np.sqrt(vc_idx) + eps) param[idx] = param[idx] - lr * (update + weight_decay * param[idx]) print("Cur param:") print(re_param) print(param) print("Cur m:") print(re_m) print(m) print("Cur v:") print(re_v) print(v) np.testing.assert_allclose(re_param, param, atol=1e-5) np.testing.assert_allclose(re_m, m, atol=1e-5) np.testing.assert_allclose(re_v, v, atol=1e-5) def test_lamb_sparse(): ctx = ht.gpu(0) shape = (500, 400) l = np.random.randint(0,500,size=(100)) # shape = (5,4) # l = [0,2,3] indices = np.array(l) param = np.random.uniform(-10, 10, size=shape).astype(np.float32) grad = np.random.uniform(-10, 10, size=(indices.shape[0], shape[1])).astype(np.float32) m = np.random.uniform(-10, 10, size=shape).astype(np.float32) v = np.random.uniform(0, 10, size=shape).astype(np.float32) lr = 1e-2 beta1 = 0.9 beta2 = 0.99 beta1t = beta1**10 beta2t = beta2**10 eps = 1e-7 weight_decay = 0.1 print("Prev param:") print(param) print("Prev m:") print(m) print("Prev v:") print(v) print("Indices:") print(indices) print("Grad:") print(grad) arr_param = ht.array(param, ctx) arr_indices = ht.array(indices, ctx) arr_value = ht.array(grad, ctx) arr_grad = ht.IndexedSlices(indices = arr_indices, values = arr_value, dense_shape = shape) arr_m = ht.array(m, ctx) arr_v = ht.array(v, ctx) gpu_op.lamb_update(arr_param, arr_grad, arr_m, arr_v, lr, beta1, beta2, beta1t, beta2t, eps, weight_decay) re_param = arr_param.asnumpy() re_m = arr_m.asnumpy() re_v = arr_v.asnumpy() # numpy deduplicate d = dict() for i in l: d[i]=[] for i, g in zip(l, grad): d[i].append(g) for key in d.keys(): g0 = d[key][0] for i in range(1, len(d[key])): g0 += d[key][i] d[key] = g0 grad_new = [] l_new = [] for key in d.keys(): l_new.append(key) grad_new.append(d[key]) grad_new = np.array(grad_new) updates = [] for idx, g in zip(l_new, grad_new): m[idx] = beta1 * m[idx] + (1 - beta1) * g v[idx] = beta2 * v[idx] + (1 - beta2) * g * g mc_idx = m[idx] / (1 - beta1t) vc_idx = v[idx] / (1 - beta2t) update = mc_idx / (np.sqrt(vc_idx) + eps) updates.append(update) updates = np.array(updates) param_indexed = [] for idx in l_new: param_indexed.append(param[idx]) param_indexed = np.array(param_indexed) norm2_param = np.sqrt(np.sum(np.power(param_indexed, 2))) # only use indexed params to calculate norm2 norm2_update = np.sqrt(np.sum(np.power(updates, 2))) #print(norm2_param, norm2_update) for idx, u in zip(l_new, updates): param[idx] = param[idx] - lr * norm2_param / norm2_update * (u + weight_decay * param[idx]) print("Cur param:") print(re_param) print(param) print("Cur m:") print(re_m) print(m) print("Cur v:") print(re_v) print(v) np.testing.assert_allclose(re_param, param, atol=1e-5) np.testing.assert_allclose(re_m, m, atol=1e-5) np.testing.assert_allclose(re_v, v, atol=1e-5) test_adamw() test_lamb() test_adamw_sparse() test_lamb_sparse()
[ "hetu.IndexedSlices", "hetu.gpu", "numpy.sqrt", "numpy.power", "numpy.testing.assert_allclose", "hetu.array", "numpy.array", "numpy.random.randint", "hetu.gpu_links.adamw_update", "numpy.random.uniform", "hetu.gpu_links.lamb_update" ]
[((104, 113), 'hetu.gpu', 'ht.gpu', (['(0)'], {}), '(0)\n', (110, 113), True, 'import hetu as ht\n'), ((664, 684), 'hetu.array', 'ht.array', (['param', 'ctx'], {}), '(param, ctx)\n', (672, 684), True, 'import hetu as ht\n'), ((700, 719), 'hetu.array', 'ht.array', (['grad', 'ctx'], {}), '(grad, ctx)\n', (708, 719), True, 'import hetu as ht\n'), ((732, 748), 'hetu.array', 'ht.array', (['m', 'ctx'], {}), '(m, ctx)\n', (740, 748), True, 'import hetu as ht\n'), ((761, 777), 'hetu.array', 'ht.array', (['v', 'ctx'], {}), '(v, ctx)\n', (769, 777), True, 'import hetu as ht\n'), ((782, 893), 'hetu.gpu_links.adamw_update', 'gpu_op.adamw_update', (['arr_param', 'arr_grad', 'arr_m', 'arr_v', 'lr', 'beta1', 'beta2', 'beta1t', 'beta2t', 'eps', 'weight_decay'], {}), '(arr_param, arr_grad, arr_m, arr_v, lr, beta1, beta2,\n beta1t, beta2t, eps, weight_decay)\n', (801, 893), True, 'from hetu import gpu_links as gpu_op\n'), ((1379, 1434), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_param', 'param'], {'atol': '(1e-05)'}), '(re_param, param, atol=1e-05)\n', (1405, 1434), True, 'import numpy as np\n'), ((1438, 1485), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_m', 'm'], {'atol': '(1e-05)'}), '(re_m, m, atol=1e-05)\n', (1464, 1485), True, 'import numpy as np\n'), ((1489, 1536), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_v', 'v'], {'atol': '(1e-05)'}), '(re_v, v, atol=1e-05)\n', (1515, 1536), True, 'import numpy as np\n'), ((1564, 1573), 'hetu.gpu', 'ht.gpu', (['(0)'], {}), '(0)\n', (1570, 1573), True, 'import hetu as ht\n'), ((2120, 2140), 'hetu.array', 'ht.array', (['param', 'ctx'], {}), '(param, ctx)\n', (2128, 2140), True, 'import hetu as ht\n'), ((2156, 2175), 'hetu.array', 'ht.array', (['grad', 'ctx'], {}), '(grad, ctx)\n', (2164, 2175), True, 'import hetu as ht\n'), ((2188, 2204), 'hetu.array', 'ht.array', (['m', 'ctx'], {}), '(m, ctx)\n', (2196, 2204), True, 'import hetu as ht\n'), ((2217, 2233), 'hetu.array', 'ht.array', (['v', 'ctx'], {}), '(v, ctx)\n', (2225, 2233), True, 'import hetu as ht\n'), ((2238, 2348), 'hetu.gpu_links.lamb_update', 'gpu_op.lamb_update', (['arr_param', 'arr_grad', 'arr_m', 'arr_v', 'lr', 'beta1', 'beta2', 'beta1t', 'beta2t', 'eps', 'weight_decay'], {}), '(arr_param, arr_grad, arr_m, arr_v, lr, beta1, beta2,\n beta1t, beta2t, eps, weight_decay)\n', (2256, 2348), True, 'from hetu import gpu_links as gpu_op\n'), ((2973, 3028), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_param', 'param'], {'atol': '(1e-05)'}), '(re_param, param, atol=1e-05)\n', (2999, 3028), True, 'import numpy as np\n'), ((3032, 3079), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_m', 'm'], {'atol': '(1e-05)'}), '(re_m, m, atol=1e-05)\n', (3058, 3079), True, 'import numpy as np\n'), ((3083, 3130), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_v', 'v'], {'atol': '(1e-05)'}), '(re_v, v, atol=1e-05)\n', (3109, 3130), True, 'import numpy as np\n'), ((3167, 3176), 'hetu.gpu', 'ht.gpu', (['(0)'], {}), '(0)\n', (3173, 3176), True, 'import hetu as ht\n'), ((3208, 3243), 'numpy.random.randint', 'np.random.randint', (['(0)', '(500)'], {'size': '(100)'}), '(0, 500, size=100)\n', (3225, 3243), True, 'import numpy as np\n'), ((3258, 3269), 'numpy.array', 'np.array', (['l'], {}), '(l)\n', (3266, 3269), True, 'import numpy as np\n'), ((3897, 3917), 'hetu.array', 'ht.array', (['param', 'ctx'], {}), '(param, ctx)\n', (3905, 3917), True, 'import hetu as ht\n'), ((3936, 3958), 'hetu.array', 'ht.array', (['indices', 'ctx'], {}), '(indices, ctx)\n', (3944, 3958), True, 'import hetu as ht\n'), ((3975, 3994), 'hetu.array', 'ht.array', (['grad', 'ctx'], {}), '(grad, ctx)\n', (3983, 3994), True, 'import hetu as ht\n'), ((4010, 4084), 'hetu.IndexedSlices', 'ht.IndexedSlices', ([], {'indices': 'arr_indices', 'values': 'arr_value', 'dense_shape': 'shape'}), '(indices=arr_indices, values=arr_value, dense_shape=shape)\n', (4026, 4084), True, 'import hetu as ht\n'), ((4103, 4119), 'hetu.array', 'ht.array', (['m', 'ctx'], {}), '(m, ctx)\n', (4111, 4119), True, 'import hetu as ht\n'), ((4132, 4148), 'hetu.array', 'ht.array', (['v', 'ctx'], {}), '(v, ctx)\n', (4140, 4148), True, 'import hetu as ht\n'), ((4153, 4264), 'hetu.gpu_links.adamw_update', 'gpu_op.adamw_update', (['arr_param', 'arr_grad', 'arr_m', 'arr_v', 'lr', 'beta1', 'beta2', 'beta1t', 'beta2t', 'eps', 'weight_decay'], {}), '(arr_param, arr_grad, arr_m, arr_v, lr, beta1, beta2,\n beta1t, beta2t, eps, weight_decay)\n', (4172, 4264), True, 'from hetu import gpu_links as gpu_op\n'), ((4743, 4761), 'numpy.array', 'np.array', (['grad_new'], {}), '(grad_new)\n', (4751, 4761), True, 'import numpy as np\n'), ((5278, 5333), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_param', 'param'], {'atol': '(1e-05)'}), '(re_param, param, atol=1e-05)\n', (5304, 5333), True, 'import numpy as np\n'), ((5337, 5384), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_m', 'm'], {'atol': '(1e-05)'}), '(re_m, m, atol=1e-05)\n', (5363, 5384), True, 'import numpy as np\n'), ((5388, 5435), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_v', 'v'], {'atol': '(1e-05)'}), '(re_v, v, atol=1e-05)\n', (5414, 5435), True, 'import numpy as np\n'), ((5471, 5480), 'hetu.gpu', 'ht.gpu', (['(0)'], {}), '(0)\n', (5477, 5480), True, 'import hetu as ht\n'), ((5512, 5547), 'numpy.random.randint', 'np.random.randint', (['(0)', '(500)'], {'size': '(100)'}), '(0, 500, size=100)\n', (5529, 5547), True, 'import numpy as np\n'), ((5600, 5611), 'numpy.array', 'np.array', (['l'], {}), '(l)\n', (5608, 5611), True, 'import numpy as np\n'), ((6239, 6259), 'hetu.array', 'ht.array', (['param', 'ctx'], {}), '(param, ctx)\n', (6247, 6259), True, 'import hetu as ht\n'), ((6278, 6300), 'hetu.array', 'ht.array', (['indices', 'ctx'], {}), '(indices, ctx)\n', (6286, 6300), True, 'import hetu as ht\n'), ((6317, 6336), 'hetu.array', 'ht.array', (['grad', 'ctx'], {}), '(grad, ctx)\n', (6325, 6336), True, 'import hetu as ht\n'), ((6352, 6426), 'hetu.IndexedSlices', 'ht.IndexedSlices', ([], {'indices': 'arr_indices', 'values': 'arr_value', 'dense_shape': 'shape'}), '(indices=arr_indices, values=arr_value, dense_shape=shape)\n', (6368, 6426), True, 'import hetu as ht\n'), ((6445, 6461), 'hetu.array', 'ht.array', (['m', 'ctx'], {}), '(m, ctx)\n', (6453, 6461), True, 'import hetu as ht\n'), ((6474, 6490), 'hetu.array', 'ht.array', (['v', 'ctx'], {}), '(v, ctx)\n', (6482, 6490), True, 'import hetu as ht\n'), ((6495, 6605), 'hetu.gpu_links.lamb_update', 'gpu_op.lamb_update', (['arr_param', 'arr_grad', 'arr_m', 'arr_v', 'lr', 'beta1', 'beta2', 'beta1t', 'beta2t', 'eps', 'weight_decay'], {}), '(arr_param, arr_grad, arr_m, arr_v, lr, beta1, beta2,\n beta1t, beta2t, eps, weight_decay)\n', (6513, 6605), True, 'from hetu import gpu_links as gpu_op\n'), ((7084, 7102), 'numpy.array', 'np.array', (['grad_new'], {}), '(grad_new)\n', (7092, 7102), True, 'import numpy as np\n'), ((7439, 7456), 'numpy.array', 'np.array', (['updates'], {}), '(updates)\n', (7447, 7456), True, 'import numpy as np\n'), ((7564, 7587), 'numpy.array', 'np.array', (['param_indexed'], {}), '(param_indexed)\n', (7572, 7587), True, 'import numpy as np\n'), ((8099, 8154), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_param', 'param'], {'atol': '(1e-05)'}), '(re_param, param, atol=1e-05)\n', (8125, 8154), True, 'import numpy as np\n'), ((8158, 8205), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_m', 'm'], {'atol': '(1e-05)'}), '(re_m, m, atol=1e-05)\n', (8184, 8205), True, 'import numpy as np\n'), ((8209, 8256), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['re_v', 'v'], {'atol': '(1e-05)'}), '(re_v, v, atol=1e-05)\n', (8235, 8256), True, 'import numpy as np\n'), ((148, 186), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (165, 186), True, 'import numpy as np\n'), ((217, 255), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (234, 255), True, 'import numpy as np\n'), ((283, 321), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (300, 321), True, 'import numpy as np\n'), ((349, 385), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(10)'], {'size': 'shape'}), '(0, 10, size=shape)\n', (366, 385), True, 'import numpy as np\n'), ((1136, 1147), 'numpy.sqrt', 'np.sqrt', (['vc'], {}), '(vc)\n', (1143, 1147), True, 'import numpy as np\n'), ((1604, 1642), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (1621, 1642), True, 'import numpy as np\n'), ((1673, 1711), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (1690, 1711), True, 'import numpy as np\n'), ((1739, 1777), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (1756, 1777), True, 'import numpy as np\n'), ((1805, 1841), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(10)'], {'size': 'shape'}), '(0, 10, size=shape)\n', (1822, 1841), True, 'import numpy as np\n'), ((2591, 2602), 'numpy.sqrt', 'np.sqrt', (['vc'], {}), '(vc)\n', (2598, 2602), True, 'import numpy as np\n'), ((2643, 2661), 'numpy.power', 'np.power', (['param', '(2)'], {}), '(param, 2)\n', (2651, 2661), True, 'import numpy as np\n'), ((2698, 2717), 'numpy.power', 'np.power', (['update', '(2)'], {}), '(update, 2)\n', (2706, 2717), True, 'import numpy as np\n'), ((3282, 3320), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (3299, 3320), True, 'import numpy as np\n'), ((3351, 3412), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': '(indices.shape[0], shape[1])'}), '(-10, 10, size=(indices.shape[0], shape[1]))\n', (3368, 3412), True, 'import numpy as np\n'), ((3440, 3478), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (3457, 3478), True, 'import numpy as np\n'), ((3506, 3542), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(10)'], {'size': 'shape'}), '(0, 10, size=shape)\n', (3523, 3542), True, 'import numpy as np\n'), ((5624, 5662), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (5641, 5662), True, 'import numpy as np\n'), ((5693, 5754), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': '(indices.shape[0], shape[1])'}), '(-10, 10, size=(indices.shape[0], shape[1]))\n', (5710, 5754), True, 'import numpy as np\n'), ((5782, 5820), 'numpy.random.uniform', 'np.random.uniform', (['(-10)', '(10)'], {'size': 'shape'}), '(-10, 10, size=shape)\n', (5799, 5820), True, 'import numpy as np\n'), ((5848, 5884), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(10)'], {'size': 'shape'}), '(0, 10, size=shape)\n', (5865, 5884), True, 'import numpy as np\n'), ((7622, 7648), 'numpy.power', 'np.power', (['param_indexed', '(2)'], {}), '(param_indexed, 2)\n', (7630, 7648), True, 'import numpy as np\n'), ((7730, 7750), 'numpy.power', 'np.power', (['updates', '(2)'], {}), '(updates, 2)\n', (7738, 7750), True, 'import numpy as np\n'), ((5012, 5027), 'numpy.sqrt', 'np.sqrt', (['vc_idx'], {}), '(vc_idx)\n', (5019, 5027), True, 'import numpy as np\n'), ((7371, 7386), 'numpy.sqrt', 'np.sqrt', (['vc_idx'], {}), '(vc_idx)\n', (7378, 7386), True, 'import numpy as np\n')]
import datetime import glob import os import operator import pytest import numpy as np from functools import reduce from numpy import nan from osgeo import gdal from test import DATA_DIR, TEST_DIR, pushd from RAiDER.constants import Zenith, _ZMIN, _ZREF from RAiDER.processWM import prepareWeatherModel from RAiDER.models.weatherModel import ( WeatherModel, find_svp, make_raw_weather_data_filename, make_weather_model_filename, ) from RAiDER.models.erai import ERAI from RAiDER.models.era5 import ERA5 from RAiDER.models.era5t import ERA5T from RAiDER.models.hres import HRES from RAiDER.models.hrrr import HRRR from RAiDER.models.gmao import GMAO from RAiDER.models.merra2 import MERRA2 from RAiDER.models.ncmr import NCMR WEATHER_FILE = os.path.join( DATA_DIR, "weather_files", "ERA-5_2018_07_01_T00_00_00.nc" ) @pytest.fixture def erai(): wm = ERAI() return wm @pytest.fixture def era5(): wm = ERA5() return wm @pytest.fixture def era5t(): wm = ERA5T() return wm @pytest.fixture def hres(): wm = HRES() return wm @pytest.fixture def gmao(): wm = GMAO() return wm @pytest.fixture def merra2(): wm = MERRA2() return wm @pytest.fixture def hrrr(): wm = HRRR() return wm @pytest.fixture def ncmr(): wm = NCMR() return wm def product(iterable): return reduce(operator.mul, iterable, 1) class MockWeatherModel(WeatherModel): """Implement abstract methods for testing.""" def __init__(self): super().__init__() self._Name = "MOCK" self._valid_range = (datetime.datetime(1970, 1, 1), "Present") self._lag_time = datetime.timedelta(days=15) def _fetch(self, lats, lons, time, out): pass def load_weather(self, *args, **kwargs): pass @pytest.fixture def model(): return MockWeatherModel() def test_weatherModel_basic1(model): wm = model assert wm._zmin == _ZMIN assert wm._zmax == _ZREF assert wm.Model() == 'MOCK' # check some defaults assert wm._humidityType == 'q' wm.setTime(datetime.datetime(2020, 1, 1, 6, 0, 0)) assert wm._time == datetime.datetime(2020, 1, 1, 6, 0, 0) wm.setTime('2020-01-01T00:00:00') assert wm._time == datetime.datetime(2020, 1, 1, 0, 0, 0) wm.setTime('19720229', fmt='%Y%m%d') # test a leap year assert wm._time == datetime.datetime(1972, 2, 29, 0, 0, 0) with pytest.raises(RuntimeError): wm.checkTime(datetime.datetime(1950, 1, 1)) wm.checkTime(datetime.datetime(2000, 1, 1)) with pytest.raises(RuntimeError): wm.checkTime(datetime.datetime.now()) def test_uniform_in_z_small(model): # Uneven z spacing, but averages to [1, 2] model._zs = np.array([ [[1., 2.], [0.9, 1.1]], [[1., 2.6], [1.1, 2.3]] ]) model._xs = np.array([1, 2, 2]) model._ys = np.array([2, 3, 2]) model._p = np.arange(8).reshape(2, 2, 2) model._t = model._p * 2 model._e = model._p * 3 model._lats = model._zs # for now just passing in dummy arrays for lats, lons model._lons = model._zs model._uniform_in_z() # Note that when the lower bound is exactly equal we get a value, but # when the upper bound is exactly equal we get the fill interpolated = np.array([ [[0, nan], [2.5, nan]], [[4., 4.625], [nan, 6.75]] ]) assert np.allclose(model._p, interpolated, equal_nan=True, rtol=0) assert np.allclose(model._t, interpolated * 2, equal_nan=True, rtol=0) assert np.allclose(model._e, interpolated * 3, equal_nan=True, rtol=0) assert np.allclose(model._zs, np.array([1, 2]), rtol=0) assert np.allclose(model._xs, np.array([1, 2]), rtol=0) assert np.allclose(model._ys, np.array([2, 3]), rtol=0) def test_uniform_in_z_large(model): shape = (400, 500, 40) x, y, z = shape size = product(shape) # Uneven spacing that averages to approximately [1, 2, ..., 39, 40] zlevels = np.arange(1, shape[-1] + 1) model._zs = np.random.normal(1, 0.1, size).reshape(shape) * zlevels model._xs = np.empty(0) # Doesn't matter model._ys = np.empty(0) # Doesn't matter model._p = np.tile(np.arange(y).reshape(-1, 1) * np.ones(z), (x, 1, 1)) model._t = model._p * 2 model._e = model._p * 3 model._lats = model._zs # for now just passing in dummy arrays for lats, lons model._lons = model._zs assert model._p.shape == shape model._uniform_in_z() interpolated = np.tile(np.arange(y), (x, 1)) assert np.allclose(np.nanmean(model._p, axis=-1), interpolated, equal_nan=True, rtol=0) assert np.allclose(np.nanmean(model._t, axis=-1), interpolated * 2, equal_nan=True, rtol=0) assert np.allclose(np.nanmean(model._e, axis=-1), interpolated * 3, equal_nan=True, rtol=0) assert np.allclose(model._zs, zlevels, atol=0.05, rtol=0) def test_mwmf(): name = 'ERA-5' time = datetime.datetime(2020, 1, 1) ll_bounds = (-90, 90, -180, 180) assert make_weather_model_filename(name, time, ll_bounds) == \ 'ERA-5_2020_01_01_T00_00_00_90S_90N_180W_180E.nc' def test_mrwmf(): outLoc = './' name = 'ERA-5' time = datetime.datetime(2020, 1, 1) assert make_raw_weather_data_filename(outLoc, name, time) == \ './ERA-5_2020_01_01_T00_00_00.nc' def test_checkLL_era5(era5): lats_good = np.array([-89, -45, 0, 45, 89]) lons_good = np.array([-179, -90, 0, 90, 179]) lats = np.array([-90, -45, 0, 45, 90]) lons = np.array([-180, -90, 0, 90, 180]) lats2, lons2 = era5.checkLL(lats, lons) assert np.allclose(lats2, lats) assert np.allclose(lons2, lons) def test_checkLL_era5_2(era5): lats_good = np.array([-89, -45, 0, 45, 89]) lons_good = np.array([-179, -90, 0, 90, 179]) lats = np.array([-95, -45, 0, 45, 90]) lons = np.array([-180, -90, 0, 90, 200]) lats2, lons2 = era5.checkLL(lats, lons) assert np.allclose(lats2, lats_good) assert np.allclose(lons2, lons_good) def test_erai(erai): wm = erai assert wm._humidityType == 'q' assert wm._Name == 'ERA-I' assert wm._valid_range[0] == datetime.datetime(1979, 1, 1) assert wm._valid_range[1] == datetime.datetime(2019, 8, 31) assert wm._proj.to_epsg() == 4326 def test_era5(era5): wm = era5 assert wm._humidityType == 'q' assert wm._Name == 'ERA-5' assert wm._valid_range[0] == datetime.datetime(1950, 1, 1) assert wm._proj.to_epsg() == 4326 def test_era5t(era5t): wm = era5t assert wm._humidityType == 'q' assert wm._Name == 'ERA-5T' assert wm._valid_range[0] == datetime.datetime(1950, 1, 1) assert wm._proj.to_epsg() == 4326 def test_hres(hres): wm = hres assert wm._humidityType == 'q' assert wm._Name == 'HRES' assert wm._valid_range[0] == datetime.datetime(1983, 4, 20) assert wm._proj.to_epsg() == 4326 assert wm._levels == 137 wm.update_a_b() assert wm._levels == 91 def test_gmao(gmao): wm = gmao assert wm._humidityType == 'q' assert wm._Name == 'GMAO' assert wm._valid_range[0] == datetime.datetime(2014, 2, 20) assert wm._proj.to_epsg() == 4326 def test_merra2(merra2): wm = merra2 assert wm._humidityType == 'q' assert wm._Name == 'MERRA2' assert wm._valid_range[0] == datetime.datetime(1980, 1, 1) assert wm._proj.to_epsg() == 4326 def test_hrrr(hrrr): wm = hrrr assert wm._humidityType == 'q' assert wm._Name == 'HRRR' assert wm._valid_range[0] == datetime.datetime(2016, 7, 15) assert wm._proj.to_epsg() is None def test_ncmr(ncmr): wm = ncmr assert wm._humidityType == 'q' assert wm._Name == 'NCMR' assert wm._valid_range[0] == datetime.datetime(2015, 12, 1) def test_find_svp(): t = np.arange(0, 100, 10) + 273.15 svp_test = find_svp(t) svp_true = np.array([ 611.21, 1227.5981, 2337.2825, 4243.5093, 7384.1753, 12369.2295, 20021.443, 31419.297, 47940.574, 71305.16 ]) assert np.allclose(svp_test, svp_true)
[ "RAiDER.models.erai.ERAI", "RAiDER.models.hres.HRES", "numpy.array", "numpy.nanmean", "datetime.timedelta", "RAiDER.models.weatherModel.make_weather_model_filename", "numpy.arange", "datetime.datetime", "RAiDER.models.ncmr.NCMR", "RAiDER.models.gmao.GMAO", "numpy.empty", "numpy.random.normal",...
[((761, 833), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""weather_files"""', '"""ERA-5_2018_07_01_T00_00_00.nc"""'], {}), "(DATA_DIR, 'weather_files', 'ERA-5_2018_07_01_T00_00_00.nc')\n", (773, 833), False, 'import os\n'), ((887, 893), 'RAiDER.models.erai.ERAI', 'ERAI', ([], {}), '()\n', (891, 893), False, 'from RAiDER.models.erai import ERAI\n'), ((947, 953), 'RAiDER.models.era5.ERA5', 'ERA5', ([], {}), '()\n', (951, 953), False, 'from RAiDER.models.era5 import ERA5\n'), ((1008, 1015), 'RAiDER.models.era5t.ERA5T', 'ERA5T', ([], {}), '()\n', (1013, 1015), False, 'from RAiDER.models.era5t import ERA5T\n'), ((1069, 1075), 'RAiDER.models.hres.HRES', 'HRES', ([], {}), '()\n', (1073, 1075), False, 'from RAiDER.models.hres import HRES\n'), ((1129, 1135), 'RAiDER.models.gmao.GMAO', 'GMAO', ([], {}), '()\n', (1133, 1135), False, 'from RAiDER.models.gmao import GMAO\n'), ((1191, 1199), 'RAiDER.models.merra2.MERRA2', 'MERRA2', ([], {}), '()\n', (1197, 1199), False, 'from RAiDER.models.merra2 import MERRA2\n'), ((1253, 1259), 'RAiDER.models.hrrr.HRRR', 'HRRR', ([], {}), '()\n', (1257, 1259), False, 'from RAiDER.models.hrrr import HRRR\n'), ((1313, 1319), 'RAiDER.models.ncmr.NCMR', 'NCMR', ([], {}), '()\n', (1317, 1319), False, 'from RAiDER.models.ncmr import NCMR\n'), ((1370, 1403), 'functools.reduce', 'reduce', (['operator.mul', 'iterable', '(1)'], {}), '(operator.mul, iterable, 1)\n', (1376, 1403), False, 'from functools import reduce\n'), ((2754, 2816), 'numpy.array', 'np.array', (['[[[1.0, 2.0], [0.9, 1.1]], [[1.0, 2.6], [1.1, 2.3]]]'], {}), '([[[1.0, 2.0], [0.9, 1.1]], [[1.0, 2.6], [1.1, 2.3]]])\n', (2762, 2816), True, 'import numpy as np\n'), ((2871, 2890), 'numpy.array', 'np.array', (['[1, 2, 2]'], {}), '([1, 2, 2])\n', (2879, 2890), True, 'import numpy as np\n'), ((2907, 2926), 'numpy.array', 'np.array', (['[2, 3, 2]'], {}), '([2, 3, 2])\n', (2915, 2926), True, 'import numpy as np\n'), ((3320, 3383), 'numpy.array', 'np.array', (['[[[0, nan], [2.5, nan]], [[4.0, 4.625], [nan, 6.75]]]'], {}), '([[[0, nan], [2.5, nan]], [[4.0, 4.625], [nan, 6.75]]])\n', (3328, 3383), True, 'import numpy as np\n'), ((3436, 3495), 'numpy.allclose', 'np.allclose', (['model._p', 'interpolated'], {'equal_nan': '(True)', 'rtol': '(0)'}), '(model._p, interpolated, equal_nan=True, rtol=0)\n', (3447, 3495), True, 'import numpy as np\n'), ((3507, 3570), 'numpy.allclose', 'np.allclose', (['model._t', '(interpolated * 2)'], {'equal_nan': '(True)', 'rtol': '(0)'}), '(model._t, interpolated * 2, equal_nan=True, rtol=0)\n', (3518, 3570), True, 'import numpy as np\n'), ((3582, 3645), 'numpy.allclose', 'np.allclose', (['model._e', '(interpolated * 3)'], {'equal_nan': '(True)', 'rtol': '(0)'}), '(model._e, interpolated * 3, equal_nan=True, rtol=0)\n', (3593, 3645), True, 'import numpy as np\n'), ((4025, 4052), 'numpy.arange', 'np.arange', (['(1)', '(shape[-1] + 1)'], {}), '(1, shape[-1] + 1)\n', (4034, 4052), True, 'import numpy as np\n'), ((4141, 4152), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (4149, 4152), True, 'import numpy as np\n'), ((4187, 4198), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (4195, 4198), True, 'import numpy as np\n'), ((4938, 4988), 'numpy.allclose', 'np.allclose', (['model._zs', 'zlevels'], {'atol': '(0.05)', 'rtol': '(0)'}), '(model._zs, zlevels, atol=0.05, rtol=0)\n', (4949, 4988), True, 'import numpy as np\n'), ((5038, 5067), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(1)', '(1)'], {}), '(2020, 1, 1)\n', (5055, 5067), False, 'import datetime\n'), ((5298, 5327), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(1)', '(1)'], {}), '(2020, 1, 1)\n', (5315, 5327), False, 'import datetime\n'), ((5484, 5515), 'numpy.array', 'np.array', (['[-89, -45, 0, 45, 89]'], {}), '([-89, -45, 0, 45, 89])\n', (5492, 5515), True, 'import numpy as np\n'), ((5532, 5565), 'numpy.array', 'np.array', (['[-179, -90, 0, 90, 179]'], {}), '([-179, -90, 0, 90, 179])\n', (5540, 5565), True, 'import numpy as np\n'), ((5577, 5608), 'numpy.array', 'np.array', (['[-90, -45, 0, 45, 90]'], {}), '([-90, -45, 0, 45, 90])\n', (5585, 5608), True, 'import numpy as np\n'), ((5620, 5653), 'numpy.array', 'np.array', (['[-180, -90, 0, 90, 180]'], {}), '([-180, -90, 0, 90, 180])\n', (5628, 5653), True, 'import numpy as np\n'), ((5709, 5733), 'numpy.allclose', 'np.allclose', (['lats2', 'lats'], {}), '(lats2, lats)\n', (5720, 5733), True, 'import numpy as np\n'), ((5745, 5769), 'numpy.allclose', 'np.allclose', (['lons2', 'lons'], {}), '(lons2, lons)\n', (5756, 5769), True, 'import numpy as np\n'), ((5819, 5850), 'numpy.array', 'np.array', (['[-89, -45, 0, 45, 89]'], {}), '([-89, -45, 0, 45, 89])\n', (5827, 5850), True, 'import numpy as np\n'), ((5867, 5900), 'numpy.array', 'np.array', (['[-179, -90, 0, 90, 179]'], {}), '([-179, -90, 0, 90, 179])\n', (5875, 5900), True, 'import numpy as np\n'), ((5912, 5943), 'numpy.array', 'np.array', (['[-95, -45, 0, 45, 90]'], {}), '([-95, -45, 0, 45, 90])\n', (5920, 5943), True, 'import numpy as np\n'), ((5955, 5988), 'numpy.array', 'np.array', (['[-180, -90, 0, 90, 200]'], {}), '([-180, -90, 0, 90, 200])\n', (5963, 5988), True, 'import numpy as np\n'), ((6044, 6073), 'numpy.allclose', 'np.allclose', (['lats2', 'lats_good'], {}), '(lats2, lats_good)\n', (6055, 6073), True, 'import numpy as np\n'), ((6085, 6114), 'numpy.allclose', 'np.allclose', (['lons2', 'lons_good'], {}), '(lons2, lons_good)\n', (6096, 6114), True, 'import numpy as np\n'), ((7939, 7950), 'RAiDER.models.weatherModel.find_svp', 'find_svp', (['t'], {}), '(t)\n', (7947, 7950), False, 'from RAiDER.models.weatherModel import WeatherModel, find_svp, make_raw_weather_data_filename, make_weather_model_filename\n'), ((7966, 8088), 'numpy.array', 'np.array', (['[611.21, 1227.5981, 2337.2825, 4243.5093, 7384.1753, 12369.2295, 20021.443,\n 31419.297, 47940.574, 71305.16]'], {}), '([611.21, 1227.5981, 2337.2825, 4243.5093, 7384.1753, 12369.2295, \n 20021.443, 31419.297, 47940.574, 71305.16])\n', (7974, 8088), True, 'import numpy as np\n'), ((8125, 8156), 'numpy.allclose', 'np.allclose', (['svp_test', 'svp_true'], {}), '(svp_test, svp_true)\n', (8136, 8156), True, 'import numpy as np\n'), ((1671, 1698), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(15)'}), '(days=15)\n', (1689, 1698), False, 'import datetime\n'), ((2100, 2138), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(1)', '(1)', '(6)', '(0)', '(0)'], {}), '(2020, 1, 1, 6, 0, 0)\n', (2117, 2138), False, 'import datetime\n'), ((2163, 2201), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(1)', '(1)', '(6)', '(0)', '(0)'], {}), '(2020, 1, 1, 6, 0, 0)\n', (2180, 2201), False, 'import datetime\n'), ((2264, 2302), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(1)', '(1)', '(0)', '(0)', '(0)'], {}), '(2020, 1, 1, 0, 0, 0)\n', (2281, 2302), False, 'import datetime\n'), ((2388, 2427), 'datetime.datetime', 'datetime.datetime', (['(1972)', '(2)', '(29)', '(0)', '(0)', '(0)'], {}), '(1972, 2, 29, 0, 0, 0)\n', (2405, 2427), False, 'import datetime\n'), ((2438, 2465), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (2451, 2465), False, 'import pytest\n'), ((2537, 2566), 'datetime.datetime', 'datetime.datetime', (['(2000)', '(1)', '(1)'], {}), '(2000, 1, 1)\n', (2554, 2566), False, 'import datetime\n'), ((2578, 2605), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (2591, 2605), False, 'import pytest\n'), ((3681, 3697), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (3689, 3697), True, 'import numpy as np\n'), ((3741, 3757), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (3749, 3757), True, 'import numpy as np\n'), ((3801, 3817), 'numpy.array', 'np.array', (['[2, 3]'], {}), '([2, 3])\n', (3809, 3817), True, 'import numpy as np\n'), ((4550, 4562), 'numpy.arange', 'np.arange', (['y'], {}), '(y)\n', (4559, 4562), True, 'import numpy as np\n'), ((4596, 4625), 'numpy.nanmean', 'np.nanmean', (['model._p'], {'axis': '(-1)'}), '(model._p, axis=-1)\n', (4606, 4625), True, 'import numpy as np\n'), ((4711, 4740), 'numpy.nanmean', 'np.nanmean', (['model._t'], {'axis': '(-1)'}), '(model._t, axis=-1)\n', (4721, 4740), True, 'import numpy as np\n'), ((4830, 4859), 'numpy.nanmean', 'np.nanmean', (['model._e'], {'axis': '(-1)'}), '(model._e, axis=-1)\n', (4840, 4859), True, 'import numpy as np\n'), ((5116, 5166), 'RAiDER.models.weatherModel.make_weather_model_filename', 'make_weather_model_filename', (['name', 'time', 'll_bounds'], {}), '(name, time, ll_bounds)\n', (5143, 5166), False, 'from RAiDER.models.weatherModel import WeatherModel, find_svp, make_raw_weather_data_filename, make_weather_model_filename\n'), ((5339, 5389), 'RAiDER.models.weatherModel.make_raw_weather_data_filename', 'make_raw_weather_data_filename', (['outLoc', 'name', 'time'], {}), '(outLoc, name, time)\n', (5369, 5389), False, 'from RAiDER.models.weatherModel import WeatherModel, find_svp, make_raw_weather_data_filename, make_weather_model_filename\n'), ((6251, 6280), 'datetime.datetime', 'datetime.datetime', (['(1979)', '(1)', '(1)'], {}), '(1979, 1, 1)\n', (6268, 6280), False, 'import datetime\n'), ((6314, 6344), 'datetime.datetime', 'datetime.datetime', (['(2019)', '(8)', '(31)'], {}), '(2019, 8, 31)\n', (6331, 6344), False, 'import datetime\n'), ((6519, 6548), 'datetime.datetime', 'datetime.datetime', (['(1950)', '(1)', '(1)'], {}), '(1950, 1, 1)\n', (6536, 6548), False, 'import datetime\n'), ((6727, 6756), 'datetime.datetime', 'datetime.datetime', (['(1950)', '(1)', '(1)'], {}), '(1950, 1, 1)\n', (6744, 6756), False, 'import datetime\n'), ((6930, 6960), 'datetime.datetime', 'datetime.datetime', (['(1983)', '(4)', '(20)'], {}), '(1983, 4, 20)\n', (6947, 6960), False, 'import datetime\n'), ((7212, 7242), 'datetime.datetime', 'datetime.datetime', (['(2014)', '(2)', '(20)'], {}), '(2014, 2, 20)\n', (7229, 7242), False, 'import datetime\n'), ((7424, 7453), 'datetime.datetime', 'datetime.datetime', (['(1980)', '(1)', '(1)'], {}), '(1980, 1, 1)\n', (7441, 7453), False, 'import datetime\n'), ((7627, 7657), 'datetime.datetime', 'datetime.datetime', (['(2016)', '(7)', '(15)'], {}), '(2016, 7, 15)\n', (7644, 7657), False, 'import datetime\n'), ((7831, 7861), 'datetime.datetime', 'datetime.datetime', (['(2015)', '(12)', '(1)'], {}), '(2015, 12, 1)\n', (7848, 7861), False, 'import datetime\n'), ((7893, 7914), 'numpy.arange', 'np.arange', (['(0)', '(100)', '(10)'], {}), '(0, 100, 10)\n', (7902, 7914), True, 'import numpy as np\n'), ((1604, 1633), 'datetime.datetime', 'datetime.datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (1621, 1633), False, 'import datetime\n'), ((2488, 2517), 'datetime.datetime', 'datetime.datetime', (['(1950)', '(1)', '(1)'], {}), '(1950, 1, 1)\n', (2505, 2517), False, 'import datetime\n'), ((2628, 2651), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2649, 2651), False, 'import datetime\n'), ((2942, 2954), 'numpy.arange', 'np.arange', (['(8)'], {}), '(8)\n', (2951, 2954), True, 'import numpy as np\n'), ((4270, 4280), 'numpy.ones', 'np.ones', (['z'], {}), '(z)\n', (4277, 4280), True, 'import numpy as np\n'), ((4069, 4099), 'numpy.random.normal', 'np.random.normal', (['(1)', '(0.1)', 'size'], {}), '(1, 0.1, size)\n', (4085, 4099), True, 'import numpy as np\n'), ((4240, 4252), 'numpy.arange', 'np.arange', (['y'], {}), '(y)\n', (4249, 4252), True, 'import numpy as np\n')]
# !/usr/bin/python3.6 # -*- coding: utf-8 -*- # @author breeze import threading import argparse import multiprocessing import time from multiprocessing import Queue, Pool import face_recognition import pandas as pd import win32com.client import cv2 import encoding_images from app_utils import * # This is a demo of running face recognition on live video from your webcam. It's a little more complicated than the # other example, but it includes some basic performance tweaks to make things run a lot faster: # 1. Process each video frame at 1/4 resolution (though still display it at full resolution) # 2. Only detect faces in every other frame of video. # PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam. # OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this # specific demo. If you have trouble installing it, try any of the other demos that don't require it instead. # Load a sample picture and learn how to recognize it. # face_recognition.api.batch_face_locations(images, number_of_times_to_upsample=1, batch_size=128)[source] # face_recognition.api.compare_faces(known_face_encodings, face_encoding_to_check, tolerance=0.6) # face_recognition.api.face_distance(face_encodings, face_to_compare)[source] # face_recognition.api.face_encodings(face_image, known_face_locations=None, num_jitters=1)[source] # face_recognition.api.face_landmarks(face_image, face_locations=None)[source] # face_recognition.api.face_locations(img, number_of_times_to_upsample=1, model='hog')[source] # face_recognition.api.load_image_file(file, mode='RGB')[source] # 语音模块 voice model speaker = win32com.client.Dispatch("SAPI.SpVoice") name = "Unknown" current_names = [name] last_time = time.time() known_face_names = [] known_face_encodings = [] known_face_encodings, known_face_names = encoding_images.load_encodings() # Initialize some variables face_locations = [] face_encodings = [] face_names = [] process_this_frame = True # TIME_DIFF = 20 # 持久化的时间间隔,当设置为 0 时候,每次识别的结果直接进行保存. name_record = "./dataset/face_record.txt" # 持久化识别出的人脸结果 NAME_DF = pd.DataFrame(known_face_names, columns=["name"]) last_ts = time.time() lock = threading.Lock() def myprint(log, ts): global lock, last_ts if lock.acquire(): diff = ts - last_ts print(log, '--------', diff) last_ts = ts lock.release() def process_face_records(name): """ 处理每一条识别的记录 ,并在一定时间之后将数据持久化到文件中 此处会碰到全局并发,导致锁的问题 :param name: :return: """ return print('process_face_records start', time.time()) global current_names, last_time # myprint("global current_names {}, last_time {}".format(current_names, last_time)) # 判断是不是在识别的列表中,不在的话就进行问候 if name not in current_names: print("ts ====", last_time, time.time()) current_names.append(name) myprint("Hello {}, nice to meet you! ".format(name)) # speaker.Speak("Hello {}, nice to meet you! ".format(name)) # 在一定时间内,清空已经识别的人, 并进行 if last_time < time.time() - TIME_DIFF: # 每隔一段时间清空一下检测到的人 last_time = time.time() time_format = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) myprint(time_format + " update last_time and clear current_names.") with open(name_record, 'a') as f: if len(current_names) > 0: f.writelines("{}:{} \n".format(time_format, str(current_names))) print("======", current_names) current_names = [] # clear() current_names = [name] myprint('process_face_records end', time.time()) def vote_class(face_encoding, tolerance=0.3, topN=5): myprint('vote start ', time.time()) """ 当比较的结果小于tolerance的时候,有多个值,采用取topN 进行投票 ,决定最终的分类,此处没有对 distance 距离进行加权 :param face_encoding: face encoding :param tolerance: 距离的阈值,越小越相似 :param topN: 参与投票的最大数量 :return: detect name """ # 计算出距离 distance_ = face_recognition.face_distance(known_face_encodings, face_encoding) df = pd.DataFrame(distance_, columns=["dis"]) # 转换成 DataFrame topDF = df[df['dis'] <= tolerance].nsmallest(topN, columns=['dis']) # 过滤结果集 namedf = NAME_DF.loc[topDF.index] # 从姓名列表中获取face距离对应的人脸名称 con = pd.concat([topDF, namedf], axis=1) # concat name and distance # print('con', con) group = con.groupby(["name"])['dis'].sum() gp = group.reset_index() print('vote -- ', gp) if len(gp) == 0: print("------unknown -----") return "Unknown", 10 import numpy as np # TODO optimize arr = np.array(gp) name1 = arr[0, 0] dis1 = arr[0, 1] print("get top one:", name1, dis1) myprint('vote end', time.time()) return name1, dis1 def face_process(frame): # Resize frame of video to 1/4 size for faster face recognition processing myprint("face process resize start", time.time()) small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) myprint("face process small_frame start", time.time()) rgb_small_frame = small_frame[:, :, ::-1] # Find all the faces and face encodings in the current frame of video # face_locations = face_recognition.face_locations(rgb_small_frame, model="cnn") myprint('face_locations start', time.time()) face_locations = face_recognition.face_locations(rgb_small_frame, model="hog") myprint('face_locations end', time.time()) myprint('face_encodings start', time.time()) face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) myprint('face_encodings end', time.time()) face_names = [] for face_encoding in face_encodings: # optimize start 采用KNN 排名*权重, 在类别上进行叠加,然后排序取出top1 name, dis = vote_class(face_encoding) # optimize end 采用 排名*权重, 在类别上进行叠加,然后排序取出top1 face_names.append(name) # 将人脸数据 # Display the results for (top, right, bottom, left), name in zip(face_locations, face_names): # Scale back up face locations since the frame we detected in was scaled to 1/4 size top *= 4 right *= 4 bottom *= 4 left *= 4 myprint('putText start', time.time()) # Draw a box around the face cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) # Draw a label with a name below the face cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) myprint("putText end " + name, time.time()) # say hello and save record to file myprint('process_face_records start', time.time()) process_face_records(name) myprint('process_face_records end', time.time()) # Display the resulting image # cv2.imshow('Video', frame) myprint("face process end", time.time()) return frame def worker(input_q, output_q): # Load a (frozen) Tensorflow model into memory. fps = FPS().start() while True: myprint("updata start ", time.time()) fps.update() myprint("updata end ", time.time()) # global lock # if lock.acquire(): # lock.release() frame = input_q.get() myprint("out queue {} and input que size {} after input_q get".format(output_q.qsize(), input_q.qsize()), time.time()) myprint("out queue {} and input que size {} after lock release ".format(output_q.qsize(), input_q.qsize()), time.time()) myprint("face process start", time.time()) # frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) out_frame = face_process(frame) myprint("out queue {} and input que size {}".format(output_q.qsize(), input_q.qsize()), time.time()) output_q.put(out_frame) myprint("out queue {} and input que size {} ".format(output_q.qsize(), input_q.qsize()), time.time()) fps.stop() if __name__ == '__main__': width = 640 height = 480 num_workers = 3 queue_size = 5 parser = argparse.ArgumentParser() parser.add_argument('-src', '--source', dest='video_source', type=int, default=0, help='Device index of the camera.') parser.add_argument('-wd', '--width', dest='width', type=int, default=width, help='Width of the frames in the video stream.') parser.add_argument('-ht', '--height', dest='height', type=int, default=height, help='Height of the frames in the video stream.') parser.add_argument('-num-w', '--num-workers', dest='num_workers', type=int, default=num_workers, help='Number of workers.') parser.add_argument('-q-size', '--queue-size', dest='queue_size', type=int, default=queue_size, help='Size of the queue.') args = parser.parse_args() logger = multiprocessing.log_to_stderr() logger.setLevel(multiprocessing.SUBDEBUG) input_q = Queue(maxsize=args.queue_size) output_q = Queue(maxsize=args.queue_size) pool = Pool(args.num_workers, worker, (input_q, output_q)) # Get a reference to webcam #0 (the default one) # video_capture = cv2.VideoCapture(0) video_capture = WebcamVideoStream(src=args.video_source, width=args.width, height=args.height).start() fps = FPS().start() # while video_capture.isOpened(): while True: # Grab a single frame of video # ret, frame = video_capture.read() myprint("out queue {} and input que size {} video_capture start ".format(output_q.qsize(), input_q.qsize()), time.time()) frame = video_capture.read() myprint("out queue {} and input que size {} ".format(output_q.qsize(), input_q.qsize()), time.time()) input_q.put(frame) myprint("out queue {} and input que size {} ".format(output_q.qsize(), input_q.qsize()), time.time()) # Only process every other frame of video to save time if process_this_frame: # COLOR_RGB2BGR myprint("out queue {} and input que size {} ".format(output_q.qsize(), input_q.qsize()), time.time()) cv2.imshow("aa", output_q.get()) myprint("out queue {} and input que size {} after imshow ".format(output_q.qsize(), input_q.qsize()), time.time()) # cv2.imshow("aa", frame) fps.update() # face_process(rgb_small_frame) # output_rgb = cv2.cvtColor(output_q.get(), cv2.COLOR_RGB2BGR) # t = threading.Thread(target=face_process, name='face_process') # 线程对象. # t.start() # 启动. # process_this_frame = not process_this_frame # Hit 'q' on the keyboard to quit! if cv2.waitKey(1) & 0xFF == ord('q'): break fps.stop() pool.terminate() # Release handle to the webcam video_capture.release() cv2.destroyAllWindows()
[ "cv2.rectangle", "numpy.array", "cv2.destroyAllWindows", "multiprocessing.log_to_stderr", "argparse.ArgumentParser", "threading.Lock", "face_recognition.face_distance", "pandas.DataFrame", "time.localtime", "cv2.waitKey", "face_recognition.face_locations", "cv2.putText", "cv2.resize", "mul...
[((1795, 1806), 'time.time', 'time.time', ([], {}), '()\n', (1804, 1806), False, 'import time\n'), ((1896, 1928), 'encoding_images.load_encodings', 'encoding_images.load_encodings', ([], {}), '()\n', (1926, 1928), False, 'import encoding_images\n'), ((2162, 2210), 'pandas.DataFrame', 'pd.DataFrame', (['known_face_names'], {'columns': "['name']"}), "(known_face_names, columns=['name'])\n", (2174, 2210), True, 'import pandas as pd\n'), ((2221, 2232), 'time.time', 'time.time', ([], {}), '()\n', (2230, 2232), False, 'import time\n'), ((2240, 2256), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (2254, 2256), False, 'import threading\n'), ((3982, 4049), 'face_recognition.face_distance', 'face_recognition.face_distance', (['known_face_encodings', 'face_encoding'], {}), '(known_face_encodings, face_encoding)\n', (4012, 4049), False, 'import face_recognition\n'), ((4059, 4099), 'pandas.DataFrame', 'pd.DataFrame', (['distance_'], {'columns': "['dis']"}), "(distance_, columns=['dis'])\n", (4071, 4099), True, 'import pandas as pd\n'), ((4271, 4305), 'pandas.concat', 'pd.concat', (['[topDF, namedf]'], {'axis': '(1)'}), '([topDF, namedf], axis=1)\n', (4280, 4305), True, 'import pandas as pd\n'), ((4598, 4610), 'numpy.array', 'np.array', (['gp'], {}), '(gp)\n', (4606, 4610), True, 'import numpy as np\n'), ((4931, 4974), 'cv2.resize', 'cv2.resize', (['frame', '(0, 0)'], {'fx': '(0.25)', 'fy': '(0.25)'}), '(frame, (0, 0), fx=0.25, fy=0.25)\n', (4941, 4974), False, 'import cv2\n'), ((5412, 5473), 'face_recognition.face_locations', 'face_recognition.face_locations', (['rgb_small_frame'], {'model': '"""hog"""'}), "(rgb_small_frame, model='hog')\n", (5443, 5473), False, 'import face_recognition\n'), ((5591, 5655), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['rgb_small_frame', 'face_locations'], {}), '(rgb_small_frame, face_locations)\n', (5622, 5655), False, 'import face_recognition\n'), ((8172, 8197), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (8195, 8197), False, 'import argparse\n'), ((9005, 9036), 'multiprocessing.log_to_stderr', 'multiprocessing.log_to_stderr', ([], {}), '()\n', (9034, 9036), False, 'import multiprocessing\n'), ((9097, 9127), 'multiprocessing.Queue', 'Queue', ([], {'maxsize': 'args.queue_size'}), '(maxsize=args.queue_size)\n', (9102, 9127), False, 'from multiprocessing import Queue, Pool\n'), ((9143, 9173), 'multiprocessing.Queue', 'Queue', ([], {'maxsize': 'args.queue_size'}), '(maxsize=args.queue_size)\n', (9148, 9173), False, 'from multiprocessing import Queue, Pool\n'), ((9185, 9236), 'multiprocessing.Pool', 'Pool', (['args.num_workers', 'worker', '(input_q, output_q)'], {}), '(args.num_workers, worker, (input_q, output_q))\n', (9189, 9236), False, 'from multiprocessing import Queue, Pool\n'), ((11084, 11107), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (11105, 11107), False, 'import cv2\n'), ((2625, 2636), 'time.time', 'time.time', ([], {}), '()\n', (2634, 2636), False, 'import time\n'), ((3152, 3163), 'time.time', 'time.time', ([], {}), '()\n', (3161, 3163), False, 'import time\n'), ((3725, 3736), 'time.time', 'time.time', ([], {}), '()\n', (3734, 3736), False, 'import time\n'), ((4717, 4728), 'time.time', 'time.time', ([], {}), '()\n', (4726, 4728), False, 'import time\n'), ((4900, 4911), 'time.time', 'time.time', ([], {}), '()\n', (4909, 4911), False, 'import time\n'), ((5123, 5134), 'time.time', 'time.time', ([], {}), '()\n', (5132, 5134), False, 'import time\n'), ((5378, 5389), 'time.time', 'time.time', ([], {}), '()\n', (5387, 5389), False, 'import time\n'), ((5508, 5519), 'time.time', 'time.time', ([], {}), '()\n', (5517, 5519), False, 'import time\n'), ((5557, 5568), 'time.time', 'time.time', ([], {}), '()\n', (5566, 5568), False, 'import time\n'), ((5690, 5701), 'time.time', 'time.time', ([], {}), '()\n', (5699, 5701), False, 'import time\n'), ((6324, 6390), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(left, top)', '(right, bottom)', '(0, 0, 255)', '(2)'], {}), '(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n', (6337, 6390), False, 'import cv2\n'), ((6449, 6537), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(left, bottom - 35)', '(right, bottom)', '(0, 0, 255)', 'cv2.FILLED'], {}), '(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2\n .FILLED)\n', (6462, 6537), False, 'import cv2\n'), ((6580, 6659), 'cv2.putText', 'cv2.putText', (['frame', 'name', '(left + 6, bottom - 6)', 'font', '(1.0)', '(255, 255, 255)', '(1)'], {}), '(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n', (6591, 6659), False, 'import cv2\n'), ((7007, 7018), 'time.time', 'time.time', ([], {}), '()\n', (7016, 7018), False, 'import time\n'), ((2863, 2874), 'time.time', 'time.time', ([], {}), '()\n', (2872, 2874), False, 'import time\n'), ((3088, 3099), 'time.time', 'time.time', ([], {}), '()\n', (3097, 3099), False, 'import time\n'), ((3221, 3237), 'time.localtime', 'time.localtime', ([], {}), '()\n', (3235, 3237), False, 'import time\n'), ((3629, 3640), 'time.time', 'time.time', ([], {}), '()\n', (3638, 3640), False, 'import time\n'), ((6266, 6277), 'time.time', 'time.time', ([], {}), '()\n', (6275, 6277), False, 'import time\n'), ((6699, 6710), 'time.time', 'time.time', ([], {}), '()\n', (6708, 6710), False, 'import time\n'), ((6802, 6813), 'time.time', 'time.time', ([], {}), '()\n', (6811, 6813), False, 'import time\n'), ((6894, 6905), 'time.time', 'time.time', ([], {}), '()\n', (6903, 6905), False, 'import time\n'), ((7195, 7206), 'time.time', 'time.time', ([], {}), '()\n', (7204, 7206), False, 'import time\n'), ((7260, 7271), 'time.time', 'time.time', ([], {}), '()\n', (7269, 7271), False, 'import time\n'), ((7497, 7508), 'time.time', 'time.time', ([], {}), '()\n', (7506, 7508), False, 'import time\n'), ((7626, 7637), 'time.time', 'time.time', ([], {}), '()\n', (7635, 7637), False, 'import time\n'), ((7677, 7688), 'time.time', 'time.time', ([], {}), '()\n', (7686, 7688), False, 'import time\n'), ((7887, 7898), 'time.time', 'time.time', ([], {}), '()\n', (7896, 7898), False, 'import time\n'), ((8029, 8040), 'time.time', 'time.time', ([], {}), '()\n', (8038, 8040), False, 'import time\n'), ((9795, 9806), 'time.time', 'time.time', ([], {}), '()\n', (9804, 9806), False, 'import time\n'), ((9942, 9953), 'time.time', 'time.time', ([], {}), '()\n', (9951, 9953), False, 'import time\n'), ((10079, 10090), 'time.time', 'time.time', ([], {}), '()\n', (10088, 10090), False, 'import time\n'), ((10315, 10326), 'time.time', 'time.time', ([], {}), '()\n', (10324, 10326), False, 'import time\n'), ((10507, 10518), 'time.time', 'time.time', ([], {}), '()\n', (10516, 10518), False, 'import time\n'), ((10927, 10941), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (10938, 10941), False, 'import cv2\n')]
import numpy as np from scipy.io import loadmat from tqdm import tqdm from cmfsapy.dimension.fsa import ml_dims load_path = "../benchmark_data/manifold_data/" save_path = "./" datasets = [1, 2, 3, 4, 5, 6, 7, 9, 101, 102, 103, 104, 11, 12, 13] D = [11, 5, 6, 8, 3, 36, 3, 20, 11, 18, 25, 71, 3, 20, 13] intdims = [10, 3, 4, 4, 2, 6, 2, 20, 10, 17, 24, 70, 2, 20, 1] names = [1, 2, 3, 4, 5, 6, 7, 9, 101, 102, 103, 104, 11, 12, 13] N = 100 k1 = 1 k2 = 10 result_ml = np.zeros([15, N]) for j in tqdm(range(15)): m_ml = np.zeros(N) for i in range(1, N+1): fn = 'M_{}_{}.mat'.format(datasets[j], i) M = loadmat(load_path+fn)['x'] d_ml = ml_dims(M.T, k2=k2, k1=k1)[0] m_ml[i - 1] = np.mean(d_ml) # if j==1: # bins = np.arange(0, 25, 1) # plt.figure() # plt.hist(d_ml, bins=bins, label='ml') # plt.hist(d, bins=bins, alpha=0.1) # plt.axvline(np.nanmean(d_ml)) # plt.legend() # plt.show() # exit() result_ml[j, :] = m_ml.copy() np.save(save_path+'ml_benchmark_res', result_ml) # plt.figure() # plt.boxplot(result.T) # plt.plot(range(1, 16), intdims, 'r_') # # # plt.figure() # # plt.plot(intdims, result, 'bo') # # plt.show()
[ "numpy.mean", "cmfsapy.dimension.fsa.ml_dims", "scipy.io.loadmat", "numpy.zeros", "numpy.save" ]
[((473, 490), 'numpy.zeros', 'np.zeros', (['[15, N]'], {}), '([15, N])\n', (481, 490), True, 'import numpy as np\n'), ((1081, 1131), 'numpy.save', 'np.save', (["(save_path + 'ml_benchmark_res')", 'result_ml'], {}), "(save_path + 'ml_benchmark_res', result_ml)\n", (1088, 1131), True, 'import numpy as np\n'), ((529, 540), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (537, 540), True, 'import numpy as np\n'), ((726, 739), 'numpy.mean', 'np.mean', (['d_ml'], {}), '(d_ml)\n', (733, 739), True, 'import numpy as np\n'), ((631, 654), 'scipy.io.loadmat', 'loadmat', (['(load_path + fn)'], {}), '(load_path + fn)\n', (638, 654), False, 'from scipy.io import loadmat\n'), ((674, 700), 'cmfsapy.dimension.fsa.ml_dims', 'ml_dims', (['M.T'], {'k2': 'k2', 'k1': 'k1'}), '(M.T, k2=k2, k1=k1)\n', (681, 700), False, 'from cmfsapy.dimension.fsa import ml_dims\n')]